From cf8c06b327e5b92799ebe2cf700ba300749f2e3c Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Thu, 3 Dec 2026 17:02:23 -0800 Subject: [PATCH 1/9] feat(gateway): work mode for the env clock, chosen by the clock step's clock_mode (FD-7183) A task whose clock is frozen lived through none of the agent's work: a turn took no task time, and a trigger due mid-turn waited for the next one. In work mode the clock stays at rate 0 and the gateway moves it on by a fixed 60 virtual seconds (WORK_SECONDS_PER_CALL, not configurable) for each answered tool call the agent makes, so thinking and model latency cost nothing and every model sees the same world for the same work. - sync_env_clock and set_env_clock_rate take clock_mode: "work" (unset keeps today's behaviour). It arms or sets rate 0 and turns work mode on (clock/v1 work); a nonzero rate with it is an error, and a gateway whose card lacks work is refused before the clock is touched. - The gateway charges calls on the MCP path and the step API's /step paths (not a post-turn hook's), after their barriers, through Clock.advance_by, then holds the answer until the time triggers the charge made due have landed (TriggerEngine.settle_due). Each charge is a work_clock_charge event. - Only the agent is charged: roles whose calls provoke triggers, less executors (TriggerEngine.agent_roles). Setup, verifier, user sim, contacts, trigger tool actions and hooks never are. get_time and stay_quiet are free. - set_time, set_rate and clear leave work mode, so set_env_clock_rate 0 after the agent stops it. - always_on gets no setting: it reads the mode from /clock/state and reports each turn's work in agent_turn_end, the judge's per-wake line and counts["work_clock"], and refuses an agent whose role work mode doesn't charge. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- src/agent_env/env/gateway/clock.py | 24 +- src/agent_env/env/gateway/constants.py | 8 +- src/agent_env/env/gateway/gateway.py | 89 +++- src/agent_env/env/gateway/triggers.py | 43 ++ src/agent_env/env/gateway/work_clock.py | 82 ++++ .../task_step/task_steps/always_on.py | 101 ++++- .../task_step/task_steps/clock_mode.py | 52 +++ .../task_steps/set_env_clock_rate.py | 30 +- .../task_step/task_steps/sync_env_clock.py | 28 +- tst/unit/env/gateway/clock_watch_test.py | 2 +- tst/unit/env/gateway/work_clock_test.py | 429 ++++++++++++++++++ tst/unit/task_step/always_on_harness.py | 19 +- tst/unit/task_step/clock_mode_test.py | 258 +++++++++++ .../task_step/test_always_on_work_clock.py | 206 +++++++++ 15 files changed, 1342 insertions(+), 31 deletions(-) create mode 100644 src/agent_env/env/gateway/work_clock.py create mode 100644 src/agent_env/task_step/task_steps/clock_mode.py create mode 100644 tst/unit/env/gateway/work_clock_test.py create mode 100644 tst/unit/task_step/clock_mode_test.py create mode 100644 tst/unit/task_step/test_always_on_work_clock.py diff --git a/AGENTS.md b/AGENTS.md index 22a01ee87..7ca8af9b3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,7 +191,7 @@ and deserialized through a registry. | Package | Contents | |---|---| -| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | +| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its work mode (`/clock/work`, `env/gateway/work_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "work"` on a clock at rate 0 and any later set_time, set_rate or clear turns off, moves the frozen clock on by a fixed `WORK_SECONDS_PER_CALL` (60 s, not configurable) for each answered tool call by the agent, a role whose calls provoke triggers and no executor's (`TriggerEngine.agent_roles`), charged on the MCP path and the step API's `/step` paths (not a post-turn hook's) after the call's barriers (`Clock.advance_by`), then holds the answer until the time triggers that made due have ended or wait on a later task time (`TriggerEngine.settle_due`), each charge a `work_clock_charge` trajectory event; always_on reads it from `/clock/state` and reports each turn's work. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | | `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, the `attempt_epoch` it was written under, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), each naming exactly what it was sent (`input`: a direct call's messages, response format and settings, an agent call's message, every file its step staged in the judge's sandbox and, for a judge the task deployed, what the task's own `load_artifact` steps put there as the run recorded it, stored by sha256 under `judge-inputs/` in the background, `judge_utils/judge_inputs.py`; the step waits for those uploads, at most 120 s, before it writes its grade, `VerifierTaskStep.settle`, and one that failed or hadn't finished is the call's `input_error`, never a failed grade), and its `verifier_settings` hold the trajectory source of each turn it read (`trajectory_sources`); with `judge_samples` (a count, as a step field, a run override or `--judge-samples` on `run`, `task run` and `eval run`), a rubric_binary or rubric_partial judge grades each criterion that many times, each a call of its own under `judge_batch_concurrency` (an agent judge the verifier deploys gets a deployment of its own per sample, its trajectory staged in each; the task's own judge takes every sample), and keeps its median, the lower middle score on a tie, which fails it, the row the first sample that scored it gave with every sample's score, verdict and justification in its `samples` and its `agreement`, the share of samples giving its verdict; a row under `min_judge_agreement` (0.5 by default, which never fails, so the median decides; 1.0 fails any split; set where `judge_samples` is, `--min-judge-agreement`) fails the grade, its rows kept, and then the step (`JudgeDisagreementError`), and `agent-env run` names the criteria a grade that stood split on (`samples split:`), and one failed sample fails the grade (a run's count or agreement a judge of another format can't take is recorded in `not_sent`) and the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`), each computer its own, a multi env's included, never the gateway's: its boot environment holds only the token's sha256 (`AGENTENV_CONTROL_TOKEN_SHA256`) when its probed card's computer/v1 says `control_token = "sha256"`, else, for a driver an older protocol built, the token itself (`AGENTENV_CONTROL_TOKEN`); the gateway learns each computer's (`CHILD_CONTROL_TOKENS`), puts it in place of its own on that computer's `/svc` routes, and lets a computer's token through only to that computer and its clock watch; a multi env's record grants each computer's `/svc` route its own token (`DeployedGatewayEnv.control_grants`, the longest granted address winning), and `CONTROL_TOKEN_CHILDREN`, the computers an older agent-env booted with the gateway's token, is kept for them; framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index 5f575c86e..1b6bad9ea 100644 --- a/src/agent_env/env/gateway/clock.py +++ b/src/agent_env/env/gateway/clock.py @@ -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; work mode (work_clock.py) can also move it on by a fixed charge per agent tool call +(advance_by). Off by default: an unarmed clock 404s. """ from __future__ import annotations @@ -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: work 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: diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index a82888c79..31176df06 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -98,6 +98,11 @@ 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 +# Work mode (clock/v1 work, work_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 WORK_SECONDS_PER_CALL for each tool call the agent makes. Fixed in agent-env, the same for +# every task and every model. +CLOCK_WORK_MODE = "work" +WORK_SECONDS_PER_CALL = 60.0 # Env/gateway-level extensions the gateway itself owns (tool gating + triggers). EXT_DISABLE_TOOL_URI = "urn:agentenv:disable-tool/v1" @@ -304,7 +309,7 @@ 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; work turns work mode on or off (on needs an armed clock at rate 0; set_time, set_rate and clear turn it off): each answered tool call by the agent, a role whose calls provoke triggers and no executor's, moves the clock on by a fixed " f"{WORK_SECONDS_PER_CALL:g}" " s (get_time and stay_quiet are free), and its answer waits for the time triggers that made due to land; it changes no version, and state's work block shows it, the roles it counts 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"]}}, @@ -312,6 +317,7 @@ def random_mcp_server_name() -> str: "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": {}}}, + "work": {"method": "PUT", "endpoint": "/clock/work", "request": {"type": "object", "properties": {"on": {"type": "boolean"}}, "required": ["on"], "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"}}}}}}, diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 5605a5834..494a32c82 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -117,6 +117,7 @@ from .notifications import CHECK_TOOL_NAMES, NotificationError, Notifications, build_check_tools from .user_chat import MESSAGE_USER_TOOL_NAME, UserChat, UserChatError, build_user_chat_tool from .user_chat import STAY_QUIET_TOOL_NAME, build_stay_quiet_tool +from .work_clock import HOLD_SECONDS, WorkClock, parse_work_body logger = logging.getLogger(__name__) @@ -285,6 +286,7 @@ async def list_website_urls() -> list[str]: ) self._clock = Clock() self._clock_followers = ClockFollowers(lambda: self._clock, clock_followers or {}) + self._work_clock = WorkClock(lambda: self._trigger_engine.agent_roles()) self._notifications = Notifications(lambda: self._clock) self._user_chat = UserChat(lambda: self._clock) self._env_get_time_url_cache: str | None = None @@ -406,14 +408,16 @@ def arm(body: dict) -> dict: 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 + return self._out_of_work_mode(state) return await self._clock_write(request, arm) @self._mcp.custom_route("/clock/set-rate", methods=["PUT"]) async def clock_set_rate(request: Request) -> Response: - return await self._clock_write( - request, lambda body: self._clock.set_rate(body.get("virtual_seconds_per_real_second"))) + def rate(body: dict) -> dict: + return self._out_of_work_mode(self._clock.set_rate(body.get("virtual_seconds_per_real_second"))) + + return await self._clock_write(request, rate) @self._mcp.custom_route("/clock/advance", methods=["PUT"]) async def clock_advance(request: Request) -> Response: @@ -423,10 +427,29 @@ async def clock_advance(request: Request) -> Response: async def clock_clear(request: Request) -> Response: def disarm(body: dict) -> dict: self._unregister_get_time_tool() - return self._clock.clear() + return self._out_of_work_mode(self._clock.clear()) return await self._clock_write(request, disarm, body_optional=True) + @self._mcp.custom_route("/clock/work", methods=["PUT"]) + async def clock_work(request: Request) -> Response: + # A mode, not a clock change: the clock's version stays, and no follower is waited for. + try: + body = await request.json() + except Exception: + return self._json_response({"ok": False, "error": "Invalid JSON body"}, 400) + try: + on = parse_work_body(body) + if on and not self._clock.armed: + raise ClockError("work mode moves the clock, which is not armed: set_time first") + if on and self._clock.rate: + raise ClockError(f"work mode runs the clock at rate 0, and it runs at {self._clock.rate:g}: " + "set_rate 0 first") + except ClockError as e: + return self._json_response({"ok": False, "error": str(e)}, 400) + self._work_clock.on = on + return self._json_response({"ok": True, "work": self._work_clock.state()}, 200) + @self._mcp.custom_route(CLOCK_WATCH_PATH, methods=["GET"]) async def clock_watch(request: Request) -> Response: received = time.time() @@ -472,7 +495,8 @@ async def clock_state(request: Request) -> Response: st = self._clock.state() if st.get("armed"): st["env_get_time_url"] = await self._env_get_time_url() - return self._json_response({**st, "followers": self._clock_followers.state()}, 200) + return self._json_response({**st, "work": self._work_clock.state(), + "followers": self._clock_followers.state()}, 200) async def _notifications_write(request: Request, method) -> Response: try: @@ -812,11 +836,14 @@ async def filtered_call_tool(name, arguments, context=None, convert_result=False raise ToolError(f"Tool '{name}' is disabled for role '{role}'") native = name not in self._tool_server_urls event_id = await self._log_native_tool_call(name, arguments, role) if native else None + started = time.monotonic() result = await original_call_tool(name, arguments, context=context, convert_result=convert_result) + call_real_s = time.monotonic() - started if native: await self._log_native_tool_result(event_id, result) barrier_tasks, barrier_timeout_s = self._fire_triggers(role, name, arguments, result) await self._await_barriers(barrier_tasks, barrier_timeout_s) + await self._charge_work(role, name, call_real_s) return result tm.list_tools = filtered_list_tools @@ -850,6 +877,50 @@ async def _await_barriers(self, pending: list[asyncio.Task], timeout_s: float | except Exception: logger.exception("Awaiting trigger barriers failed (fail-open)") + def _out_of_work_mode(self, state: dict) -> dict: + """A set_time, set_rate or clear leaves work mode (work_clock.py): the clock runs as that write set it.""" + self._work_clock.on = False + return state + + async def _charge_work(self, role: str, name: str, call_real_s: float) -> None: + """Work mode's charge for an answered tool call (work_clock.py), made once its barriers have settled: the clock + moved on by the call's cost, then the answer held until the time triggers that made due have landed, up to + HOLD_SECONDS. Recorded in the trajectory (``work_clock_charge``: the virtual time before and after, what came + due, how long the answer was held, what was still running, and the call's own real seconds), or as + ``work_clock_skipped`` when the clock can't be moved. Fail-open: a charge that fails never fails the call.""" + try: + seconds = self._work_clock.cost(role, name) + if seconds is None: + return + charge = {"source": "work_clock", "tool": name, "role": role, "seconds": seconds} + before: dict = {} + + def advance() -> dict: + before["at"] = self._clock.now() + return self._clock.advance_by(seconds) + + try: + if not self._clock.armed: + raise ClockError("the clock is not armed") + state, _ = await self._change_clock(advance) + except ClockError as e: + await self._log_event({"event_type": "work_clock_skipped", **charge, "reason": str(e)}) + return + self._work_clock.record(role, seconds) + due = list(state.get("due") or []) + held_from = time.monotonic() + still_running = await self._trigger_engine.settle_due(due, HOLD_SECONDS) if due else [] + held_s = time.monotonic() - held_from + if still_running: + logger.warning(f"work mode: fire(s) {still_running} still running after {HOLD_SECONDS:g}s; " + "answering the call") + await self._log_event({"event_type": "work_clock_charge", **charge, + "virtual_time_before": _iso(before["at"]), "virtual_time_after": state["virtual_time"], + "due": due, "held_s": round(held_s, 3), "still_running": still_running, + "call_real_s": round(call_real_s, 3)}) + except Exception: + logger.exception(f"Work mode charge for '{name}' failed (fail-open)") + async def _clock_write(self, request: Request, change, *, body_optional: bool = False) -> Response: """A clock write route: its JSON object body (none at all when ``body_optional``) applied by ``change`` through ``_change_clock``; 400 for a body or value the clock refuses, else 200, or 504 naming the followers behind, with @@ -1455,12 +1526,14 @@ async def _step_call_tool(self, body: dict, role: str, source: dict = _STEP_API) try: async with self._tool_call_guard(): changelog_before = self._query_changelog_id() + started = time.monotonic() try: result = await self._call_child_tool(server_url, tool_name, arguments, caller=Caller(role=role), report=True) except Exception as e: await self._log_failed_call(tool_call_event_id, changelog_before, e, **source) raise + call_real_s = time.monotonic() - started changelog_id = self._query_changelog_id() await self._log_event({ @@ -1473,6 +1546,8 @@ async def _step_call_tool(self, body: dict, role: str, source: dict = _STEP_API) }) barrier_tasks, barrier_timeout_s = self._fire_triggers(role, tool_name, arguments, result) await self._await_barriers(barrier_tasks, barrier_timeout_s) + if source == _STEP_API: # a post-turn hook's call is the harness's, never the agent's work + await self._charge_work(role, tool_name, call_real_s) response_data = result.model_dump(mode="json", exclude_none=True) response_data["changelog_id"] = changelog_id return self._json_response(response_data, 200) @@ -1499,10 +1574,12 @@ async def _step_call_gateway_tool(self, tool_name: str, arguments: dict, role: s async with self._tool_call_guard(): # bound as the MCP path binds it, so a tool that acts for its caller (schedule_check) reads the role token = Caller(role=role, session=Caller.current().session).bind() + started = time.monotonic() try: result = await tool.run(arguments) finally: Caller.reset(token) + call_real_s = time.monotonic() - started changelog_id = self._query_changelog_id() if isinstance(result, CallToolResult): response_data = result.model_dump(mode="json", exclude_none=True) @@ -1519,6 +1596,8 @@ async def _step_call_gateway_tool(self, tool_name: str, arguments: dict, role: s }) barrier_tasks, barrier_timeout_s = self._fire_triggers(role, tool_name, arguments, result) await self._await_barriers(barrier_tasks, barrier_timeout_s) + if source == _STEP_API: + await self._charge_work(role, tool_name, call_real_s) response_data["changelog_id"] = changelog_id return self._json_response(response_data, 200) except Exception as e: diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index 47f70dc9d..b20578abb 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -63,6 +63,8 @@ _VIRTUAL_RECHECK_S = 5.0 # The clock's resolution: virtual times are microseconds. _VIRTUAL_RESOLUTION_S = 1e-6 +# Real seconds between looks at the fires settle_due waits for, to see one start waiting on a later task time. +_SETTLE_POLL_S = 0.02 # Seconds an executor call waits to connect, and for a task poll's answer. _EXECUTOR_HTTP_TIMEOUT_S = 30.0 # An allowlist, not a size bound: identifier/metadata keys only, since bodies and addresses are PII. @@ -1105,6 +1107,11 @@ def _provoked_by(self, trig: dict, role: str) -> bool: def _executor_roles(self) -> set[str]: return {e["role"] for e in self._executors.values()} + def agent_roles(self) -> set[str]: + """The agent's roles: those whose calls provoke triggers (watch_roles, ``default`` before any registration) less + every executor's, as ``_provoked_by`` reads them. Work mode charges calls by these alone (work_clock.py).""" + return (self._watch_roles if self._config_set else {DEFAULT_ROLE}) - self._executor_roles + def _mark_detected(self, tid: str, trig: dict, provoking: dict, ctx: dict | None = None) -> asyncio.Task | None: ctx = ctx if ctx is not None else {} since = self._gw._clock.elapsed() # a delay runs from the provoking call, not from when its turn comes @@ -1187,6 +1194,42 @@ def clock_changed(self) -> None: self._clock_moved.set() self._clock_moved = asyncio.Event() + async def settle_due(self, tids: list[str], timeout_s: float) -> list[str]: + """Wait, up to ``timeout_s`` real seconds, until no fire of the triggers ``tids`` (the ones a clock advance made + due) is at work: each has ended, or waits on a task time still ahead (a delay, its executor's hours), which only + more task time reaches. Work mode holds a call's answer on it, so the agent's next call sees what they + did. The ids still at work when it gave up.""" + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout_s + tids = list(dict.fromkeys(tids)) + while True: + busy = [tid for tid in tids if self._at_work(tid)] + left = deadline - loop.time() + if not busy or left <= 0: + return busy + # A fire ending wakes this; one starting to wait sets nothing to wake on, so it is polled. + tasks = {t for tid in busy for t in self._fire_tasks(self._triggers[tid]) if not t.done()} + pause = min(left, _SETTLE_POLL_S) + if tasks: + await asyncio.wait(tasks, timeout=pause, return_when=asyncio.FIRST_COMPLETED) + else: + await asyncio.sleep(pause) + + def _at_work(self, tid: str) -> bool: + """Whether a fire of trigger ``tid`` is at work: more fires running than waiting on a task time ahead.""" + trig = self._triggers.get(tid) + if trig is None or not trig["running"]: + return False + now = self._gw._clock.now() + ahead = sum(1 for w in trig["waits"].values() + if now is not None and (at := self._wait_resumes(w)) is not None + and (at - now).total_seconds() >= _VIRTUAL_RESOLUTION_S) + return trig["running"] > ahead + + @staticmethod + def _fire_tasks(trig: dict) -> list[asyncio.Task]: + return [t for t in [trig["task"], *trig["alongside"]] if t is not None] + def _resolve_first_mark(self, trig: dict, now: datetime) -> None: """Stamp the first mark for a non-anchored time-trigger; event-anchored ones wait for _resolve_dependents.""" when = trig["spec"]["when"] diff --git a/src/agent_env/env/gateway/work_clock.py b/src/agent_env/env/gateway/work_clock.py new file mode 100644 index 000000000..b114b4997 --- /dev/null +++ b/src/agent_env/env/gateway/work_clock.py @@ -0,0 +1,82 @@ +"""Work mode (urn:agentenv:clock/v1 ``work``, FD-7183): task time that passes as the agent works. + +A task whose clock is frozen (rate 0) lives through none of the agent's work otherwise: a turn takes no task time, and a +trigger due in the middle of one waits for the next. In work mode the clock stays frozen and the gateway moves it on by +``WORK_SECONDS_PER_CALL`` for each tool call the agent makes, once the call is answered, an error result included. +``get_time`` and ``stay_quiet`` cost nothing. A call refused as disabled, or one that raised, costs nothing, and neither +do model latency, thinking or retries, so every model sees the same world for the same work. + +The agent is the trigger engine's: the roles whose calls provoke triggers (``watch_roles``, ``default`` when none were +registered) less every trigger executor's (``TriggerEngine.agent_roles``). Every other caller, a setup or verifier +step, a user sim, a contact, a trigger's own tool action or a post-turn hook, is never charged. + +The task's clock step turns it on (``sync_env_clock`` or ``set_env_clock_rate`` with ``clock_mode: "work"``), on an +armed clock at rate 0; any later set_time, set_rate or clear turns it off, so a task without clock_mode runs as it always +has. The gateway charges a call with Clock.advance_by, through ``Gateway._change_clock``, then holds its answer until the +time triggers the charge made due have landed, each fire ended or waiting on a later task time, or ``HOLD_SECONDS`` have +passed (``TriggerEngine.settle_due``), so the agent's next call sees the world they changed. +""" +from __future__ import annotations + +from typing import Callable, Iterable + +from .clock import ClockError +from .constants import WORK_SECONDS_PER_CALL +from .get_time import GET_TIME_TOOL_NAME +from .user_chat import STAY_QUIET_TOOL_NAME + +# How long a charged call's answer may wait for the time triggers its charge made due. +HOLD_SECONDS = 30.0 +# Reading the time, or saying there is nothing to do, is not work. +FREE_TOOLS = frozenset({GET_TIME_TOOL_NAME, STAY_QUIET_TOOL_NAME}) + + +def parse_work_body(body) -> bool: + """Whether a ``work`` request turns work mode on: a JSON object holding ``on``, true or false, and nothing else. + Raises ClockError for anything else.""" + if not isinstance(body, dict): + raise ClockError("body must be a JSON object") + unknown = sorted(set(body) - {"on"}) + if unknown: + raise ClockError(f"unknown work setting(s) {unknown}: work takes only 'on' (the charge per call is fixed at " + f"{WORK_SECONDS_PER_CALL:g} s)") + if not isinstance(body.get("on"), bool): + raise ClockError("on must be true or false") + return body["on"] + + +class WorkClock: + """The gateway's work mode: whether it is on, who it counts (``agent_roles``, asked at each call, so triggers + registered after it was turned on count), and what it has charged, in all and by role, since the gateway started.""" + + def __init__(self, agent_roles: Callable[[], Iterable[str]]) -> None: + self._agent_roles = agent_roles + self.on = False + self.calls = 0 + self.virtual_seconds = 0.0 + self.by_role: dict[str, dict] = {} + + def roles(self) -> list[str]: + return sorted(self._agent_roles()) + + def cost(self, role: str, tool: str) -> float | None: + """What an answered call of ``tool`` by ``role`` costs, in task seconds; None when it costs nothing (work mode + off, a role that isn't the agent's, a free tool).""" + if not self.on or tool in FREE_TOOLS or role not in set(self._agent_roles()): + return None + return WORK_SECONDS_PER_CALL + + def record(self, role: str, seconds: float) -> None: + self.calls += 1 + self.virtual_seconds += seconds + mine = self.by_role.setdefault(role, {"calls": 0, "virtual_seconds": 0.0}) + mine["calls"] += 1 + mine["virtual_seconds"] += seconds + + def state(self) -> dict: + """Whether it is on, its charge per call, the roles it counts now, then what it has charged (``calls``, + ``virtual_seconds``), in all and by role.""" + return {"on": self.on, "seconds_per_call": WORK_SECONDS_PER_CALL, "roles": self.roles(), + "calls": self.calls, "virtual_seconds": round(self.virtual_seconds, 6), + "by_role": {role: {"calls": t["calls"], "virtual_seconds": round(t["virtual_seconds"], 6)} + for role, t in self.by_role.items()}} diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 6e035d0b5..570cc8807 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -34,6 +34,13 @@ time limit is the one it was registered with (register_env_triggers' ``executor_timeout_seconds``), and one trigger's replies run side by side (``contact_replies_in_parallel``). What comes due in the same minute wakes the agent once. +- When the task's clock is in work mode (sync_env_clock or set_env_clock_rate with ``clock_mode: "work"``, FD-7183), + task time passes as the agent works: the clock stays frozen and the gateway moves it on by a fixed charge for each + tool call the agent makes, so thinking and model latency cost nothing, and what that makes due lands before the call + is answered. The step only reports it, as the gateway's ``/clock/state`` says: each turn's ``agent_turn_end`` records + what its work took (``work``) beside the agent's ``output_tokens``, the record's ``counts["work_clock"]`` sums it, + ``settings["clock"]["work"]`` names the clocks in work mode, and the judge reads each wake's. The agent's role must be + one the gateway charges (``work.roles``: a role its triggers watch, and no executor's), else the run fails at setup. - The agent can schedule its own wake-ups (scheduled checks) when the run is multi-day, at least ``scheduled_check_min_interval`` apart; ``scheduled_checks`` turns them on or off whatever the run's length. A check's wake counts toward ``max_wakes``. @@ -553,6 +560,10 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): self.folded: Optional[dict] = None self.clock: dict = {} # the task's clock rate, and whether the step freezes it between turns self.clock_rates: list[tuple[Any, float]] = [] # (env, the task's rate) for each clock the step freezes + self.work_envs: list = [] # the clocks in work mode, each charging the agent's tool calls + self.work_seen: Optional[dict] = None # what they had charged the agent when last read: calls, task seconds + self.turn_work: Optional[dict] = None # what the last turn's work cost: calls charged, task seconds + self.work_total = {"calls": 0, "virtual_seconds": 0.0} self.undo: list[tuple[str, Any]] = [] # (what, coroutine function): the gateway settings to put back at the end self.rules_in_system_prompt = False # whether the agent took the rules in its system prompt self.turn_task_id: Optional[str] = None # the agent's A2A task for the turn in progress, once it accepted it @@ -811,10 +822,13 @@ async def _configure_clock(self) -> None: turns, so a slow contact reply or user sim read doesn't move the task's time. With clock/v1 ``set_rate``, which keeps the clock's marks (a re-arm with set_time, as sync_env_clock arms it, would re-anchor every relative or recurring time trigger); the task's rate is put back at the end. A clock already frozen (rate 0) - is left alone; a gateway without set_rate keeps running between turns, as the record says.""" - envs = [] + is left alone; a gateway without set_rate keeps running between turns, as the record says. A clock in work mode + (frozen, its gateway charging the agent's tool calls) is reported on (``_configure_work``).""" + envs, work = [], [] for env in await self._armed(): state = await _call(env, EXT_CLOCK_URI, "state") + if (state.get("work") or {}).get("on"): + work.append((env, state["work"])) rate = float(state.get("virtual_seconds_per_real_second") or 0) if rate <= 0: continue @@ -828,6 +842,9 @@ async def _configure_clock(self) -> None: self.undo.append(("the clock's rate", lambda: self._clock_runs(True))) await self._clock_runs(False) self.clock = {"envs": envs} + if work: + self._configure_work(work) + self.work_seen = await self._work_totals() async def _clock_runs(self, running: bool) -> None: """Run each clock the step freezes at the task's rate (``running``), or freeze it.""" @@ -835,12 +852,54 @@ async def _clock_runs(self, running: bool) -> None: await _call(env, EXT_CLOCK_URI, "set_rate", {"virtual_seconds_per_real_second": rate if running else 0}, attempts=3) + def _configure_work(self, work: list[tuple[Any, dict]]) -> None: + """Report on the clocks in work mode (each ``(env, its state's work block)``): the agent's tool calls move them on, + charged by the gateway (clock/v1 work, FD-7183), so each turn records what its work took. Refuses a run whose + agent's role a clock in work mode doesn't charge, which would take no task time for its work.""" + uncounted = [env.env_id for env, block in work if self.recipient not in (block.get("roles") or [])] + if uncounted: + raise ValueError(f"always_on: the clock of {', '.join(uncounted)} is in work mode, which charges the tool " + f"calls of the roles its triggers watch, and the agent's role {self.recipient!r} is not " + "one: register its triggers with watch_roles naming it") + self.work_envs = [env for env, _ in work] + self.clock["work"] = {"seconds_per_call": work[0][1].get("seconds_per_call"), + "envs": [env.env_id for env in self.work_envs]} + + async def _work_totals(self) -> dict: + """What the clocks in work mode have charged the agent's role so far, summed: calls, task seconds.""" + total = {"calls": 0, "virtual_seconds": 0.0} + for env in self.work_envs: + mine = (((await _call(env, EXT_CLOCK_URI, "state")).get("work") or {}).get("by_role") or {}).get( + self.recipient) or {} + total["calls"] += mine.get("calls", 0) + total["virtual_seconds"] += mine.get("virtual_seconds", 0.0) + return total + + async def _work_done(self) -> None: + """What the agent's work took since it was last read, the turn just ended's: in ``turn_work`` and the run's + ``work_total``. A late call of an earlier turn cut off counts here. A failed read is logged, not raised.""" + if self.work_seen is None: + return + try: + now = await self._work_totals() + except Exception as e: + logger.warning(f"always_on: reading what the agent's work took failed: {e}") + return + work = {"calls": now["calls"] - self.work_seen["calls"], + "virtual_seconds": round(now["virtual_seconds"] - self.work_seen["virtual_seconds"], 3)} + self.work_seen = now + self.turn_work = work + self.work_total = {"calls": self.work_total["calls"] + work["calls"], + "virtual_seconds": round(self.work_total["virtual_seconds"] + work["virtual_seconds"], 3)} + async def _agent_turn(self, parts: list[dict], msg_id: str, record) -> AgentTurn: """One turn of the agent on ``parts``: the task's clock runs at its rate while the agent works, and is frozen - again after. The turn's usage is recorded as its reply arrives, before the clock is frozen. The agent's task id - for the turn is ``turn_task_id`` once it accepts the message.""" + again after; a clock in work mode stays frozen, moved on by the agent's tool calls, and what they took is read + after. The turn's usage is recorded as its reply arrives, before the clock is frozen. The agent's task id for + the turn is ``turn_task_id`` once it accepts the message.""" step = self.step self.turn_task_id = None + self.turn_work = None def accepted(task_id: str) -> None: self.turn_task_id = task_id @@ -861,7 +920,10 @@ def accepted(task_id: str) -> None: self.usage.turn(ModelRole.SOLVER, turn.reply) return turn finally: - await self._clock_runs(False) + try: + await self._work_done() + finally: + await self._clock_runs(False) async def _stopped_at_time_limit(self, error: TimeoutError) -> Optional[dict]: """A turn that ran out of time, with continue_after_wake_limit on: its A2A task as the agent confirms it ended @@ -1554,7 +1616,7 @@ def record() -> None: if ended is None: state = self._no_answer(e, "wake") self.log("agent_turn_end", n=self.wakes, state=state, real_seconds=round(time.time() - t, 1), - **({"stop": "unconfirmed"} if step.continue_after_wake_limit else {})) + **self._work_fields(), **({"stop": "unconfirmed"} if step.continue_after_wake_limit else {})) return turn, stopped = self._stopped_turn(ended, f"agent turn timed out after {step.timeout_seconds}s: {e}") task_id, state, term = turn.task_id, turn.state, turn.reply @@ -1571,7 +1633,8 @@ def record() -> None: self.log("agent_turn_end", n=self.wakes, state=str(state), virtual_time=_iso(ended), virtual_seconds=round((ended - sent_at).total_seconds()), real_seconds=round(time.time() - t, 1), tool_calls=term.tool_call_count, plain_reply=plain, messages_to_user=len(messages), - trajectory_url=traj, **which, **extra, **({"cut_off": cut_off} if cut_off else {})) + trajectory_url=traj, **which, **extra, **self._work_fields(term), + **({"cut_off": cut_off} if cut_off else {})) self._sent(messages) if cut_off or _completed(state): self.failed_in_a_row = 0 @@ -1657,6 +1720,13 @@ def _kept_parts(self, parts: list[dict]) -> list[dict]: kept.append(part) return kept + def _work_fields(self, term: Optional[protocol.TerminalResponse] = None) -> dict: + """What a turn's end records of its cost: the output tokens its agent reported, and with a clock in work mode what + its work took (``work``: calls charged, task seconds).""" + tokens = term.usage.output_tokens if term is not None and term.usage is not None else None + return {**({"output_tokens": tokens} if tokens is not None else {}), + **({"work": self.turn_work} if self.turn_work is not None else {})} + async def _nudge(self, closing: str) -> None: """The wake ended with closing text and neither message_user nor stay_quiet, so give the agent one more short turn with ``nudge_text``; record what the closing text was and what it did after.""" @@ -1678,7 +1748,7 @@ def record() -> None: if ended is None: state = self._no_answer(e, "nudge") self.log("nudge", n=self.nudges, wake=self.wakes, virtual_time=_iso(sent_at), closing_text=closing, - state=state, outcome=state, real_seconds=round(time.time() - t, 1), + state=state, outcome=state, real_seconds=round(time.time() - t, 1), **self._work_fields(), **({"stop": "unconfirmed"} if step.continue_after_wake_limit else {})) return turn, stopped = self._stopped_turn(ended, f"agent nudge turn timed out after {step.timeout_seconds}s: {e}") @@ -1695,7 +1765,7 @@ def record() -> None: self.log("nudge", n=self.nudges, wake=self.wakes, virtual_time=_iso(sent_at), closing_text=closing, state=str(state), outcome=outcome, messages_to_user=len(messages), stay_quiet_calls=len(quiet), plain_reply_after=plain, tool_calls=term.tool_call_count, real_seconds=round(time.time() - t, 1), - trajectory_url=traj, **which, **({"cut_off": cut_off} if cut_off else {})) + trajectory_url=traj, **which, **self._work_fields(term), **({"cut_off": cut_off} if cut_off else {})) self._sent(messages, after_nudge=True) if cut_off or _completed(state): self.failed_in_a_row = 0 @@ -2141,6 +2211,8 @@ async def finish(self) -> None: and e.get("stay_quiet_calls")) if step.continue_after_wake_limit: counts["cut_off_wakes"] = len(self.cut_offs) + if self.work_envs: + counts["work_clock"] = dict(self.work_total) # the agent's tool calls charged, and the task time they took record = {"step_id": step.id, "end_reason": self.end_reason, "end_note": self.end_note, "reached_scheduled_end": self.end_reason in SCHEDULED_ENDS, "error": self.error, "error_type": self.error_type, "error_code": self.error_code, "counts": counts, @@ -2269,6 +2341,8 @@ def render_for_judge(record: dict) -> str: turn = turns.get(n) or {} sent = (turn.get("messages_to_user") or 0) + (nudges.get(n, {}).get("messages_to_user") or 0) calls = f" · {turn['tool_calls']} tool calls" if turn.get("tool_calls") is not None else "" + if (turn.get("work") or {}).get("virtual_seconds"): + calls += f" · its work took {_task_time_text(turn['work']['virtual_seconds'])} of task time" state = f" · its turn {turn['state']}" if turn.get("state") not in (None, "completed", "TaskState.completed") \ else "" cut = turn.get("cut_off") or nudges.get(n, {}).get("cut_off") @@ -2346,6 +2420,15 @@ async def _call(env, uri: str, method: str, params: Optional[dict] = None, *, at raise last +def _task_time_text(seconds: float) -> str: + """Task seconds in words for a judge: 45 s, 4.5 min, 1.2 h.""" + if seconds < 60: + return f"{round(seconds, 1):g} s" + if seconds < 3600: + return f"{round(seconds / 60, 1):g} min" + return f"{round(seconds / 3600, 1):g} h" + + def _task_zone(us: dict, clocks: list[dict]) -> str: return task_zone(us, clocks, "always_on") diff --git a/src/agent_env/task_step/task_steps/clock_mode.py b/src/agent_env/task_step/task_steps/clock_mode.py new file mode 100644 index 000000000..8264bbea9 --- /dev/null +++ b/src/agent_env/task_step/task_steps/clock_mode.py @@ -0,0 +1,52 @@ +"""The clock setup steps' ``clock_mode`` (sync_env_clock, set_env_clock_rate), FD-7183. + +Unset, the default, the clock runs at the step's rate, as it always has. ``"work"`` is work mode: the clock is frozen +(rate 0) and the gateway moves it on by a fixed charge for each tool call the agent makes (clock/v1 ``work``, +``agent_env.env.gateway.work_clock``), so the agent's work takes task time and thinking or model latency take none. A +rate other than 0 with it is an error. A later set_time or set_rate without it (sync_env_clock, or set_env_clock_rate to +0 after the agent's last prompt_agent) leaves work mode. +""" +from __future__ import annotations + +from typing import Any, Optional + +import httpx + +from agent_env.env.gateway.constants import CLOCK_WORK_MODE, EXT_CLOCK_URI, WORK_SECONDS_PER_CALL +from agent_env.task_step.context import StepContextError + +CLOCK_MODES = (CLOCK_WORK_MODE,) +_MAX_ERROR_CHARS = 300 + + +def clock_mode_rate(step_type: str, clock_mode: Any, rate: Any, default: Optional[float]) -> Any: + """The rate a clock step runs the clock at: ``rate``, or when it is None, 0 in work mode and else ``default``. + Raises ValueError for a clock_mode other than None or ``"work"``, and for work mode with a rate other than 0.""" + if clock_mode is not None and (not isinstance(clock_mode, str) or clock_mode not in CLOCK_MODES): + raise ValueError(f"{step_type}: clock_mode must be {' or '.join(repr(m) for m in CLOCK_MODES)}, or left out " + f"for a clock that runs at its rate; got {clock_mode!r}") + if rate is None: + return 0 if clock_mode == CLOCK_WORK_MODE else default + if clock_mode == CLOCK_WORK_MODE and (isinstance(rate, bool) or not isinstance(rate, (int, float)) or rate != 0): + raise ValueError(f"{step_type}: clock_mode 'work' runs the clock at rate 0, moving it on " + f"{WORK_SECONDS_PER_CALL:g} s for each of the agent's tool calls; got " + f"virtual_seconds_per_real_second={rate!r}: leave it out or set 0") + return rate + + +def require_work(deployed, env_id: str) -> None: + """Refuse, before the clock is touched, work mode on a gateway whose stored card offers no clock/v1 work. A + record that kept no card is left to the clock call, which says so.""" + if deployed.environment_card and not deployed.supports(EXT_CLOCK_URI, "work"): + raise StepContextError(f"env '{env_id}': clock_mode 'work' needs its gateway's {EXT_CLOCK_URI} work, which its " + "card does not offer; put the gateway env again (agent-env env gateway put) and redeploy") + + +async def start_work(deployed, env_id: str, timeout: int) -> dict: + """Turn work mode on at ``deployed``'s gateway, its clock armed at rate 0; the gateway's work block.""" + try: + answer = await deployed.invoke(EXT_CLOCK_URI, "work", {"on": True}, timeout=timeout) + except httpx.HTTPStatusError as e: + raise RuntimeError(f"env '{env_id}': turning work mode on failed (HTTP {e.response.status_code}): " + f"{e.response.text[:_MAX_ERROR_CHARS]}") from e + return (answer or {}).get("work") or {} diff --git a/src/agent_env/task_step/task_steps/set_env_clock_rate.py b/src/agent_env/task_step/task_steps/set_env_clock_rate.py index c969ebbfa..be41990e1 100644 --- a/src/agent_env/task_step/task_steps/set_env_clock_rate.py +++ b/src/agent_env/task_step/task_steps/set_env_clock_rate.py @@ -4,6 +4,11 @@ set the task's rate right before prompt_agent, so the agent starts at the armed time; set 0 after the agent's last prompt_agent, so verifiers read a world that no longer moves on its clock. ``env_step_id`` names the deploy_env step whose deployment's clock to change when the env is deployed more than once. + +With clock_mode "work" (``clock_mode.py``) as the step that starts the clock before prompt_agent, the rate is 0, its +default in that mode (any other is an error), and the gateway's work mode is turned on, so each tool call the agent +makes moves task time on by a fixed charge. Without it, the rate set leaves work mode, so a rate of 0 after the agent's +last prompt_agent stops the clock for verifiers in either mode. """ from __future__ import annotations @@ -17,6 +22,7 @@ from agent_env.env.gateway.constants import EXT_CLOCK_URI from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.task_step.task_step import TaskStep, TaskStepDependency +from agent_env.task_step.task_steps.clock_mode import clock_mode_rate, require_work, start_work from agent_env.task_step.task_steps.deploy_agent import bound_deployment logger = logging.getLogger(__name__) @@ -42,18 +48,20 @@ def __init__( id: str, version: Optional[int], env_id: str, - virtual_seconds_per_real_second: float, + virtual_seconds_per_real_second: Optional[float] = None, env_step_id: Optional[str] = None, depends_on: Optional[list[TaskStepDependency]] = None, fail_task_on_error: bool = True, timeout_seconds: int = 30, + clock_mode: Optional[str] = None, ): super().__init__(id, version, depends_on=depends_on, fail_task_on_error=fail_task_on_error) - rate = virtual_seconds_per_real_second + rate = clock_mode_rate(self.type, clock_mode, virtual_seconds_per_real_second, None) if isinstance(rate, bool) or not isinstance(rate, (int, float)) or rate < 0: raise ValueError(f"virtual_seconds_per_real_second must be a non-negative number, got {rate!r}") self.env_id = env_id self.virtual_seconds_per_real_second = rate + self.clock_mode = clock_mode self.env_step_id = env_step_id self.timeout_seconds = timeout_seconds @@ -63,6 +71,8 @@ def to_dict(self) -> dict: base["virtual_seconds_per_real_second"] = self.virtual_seconds_per_real_second base["env_step_id"] = self.env_step_id base["timeout_seconds"] = self.timeout_seconds + if self.clock_mode is not None: + base["clock_mode"] = self.clock_mode return base @classmethod @@ -70,26 +80,34 @@ def from_dict(cls, data: dict) -> SetEnvClockRateTaskStep: return cls( **cls._base_from_dict(data), env_id=data["env_id"], - virtual_seconds_per_real_second=data["virtual_seconds_per_real_second"], + virtual_seconds_per_real_second=data.get("virtual_seconds_per_real_second"), env_step_id=data.get("env_step_id"), timeout_seconds=data.get("timeout_seconds", 30), + clock_mode=data.get("clock_mode"), ) async def execute(self, context: TaskStepContext) -> TaskStepContext: deployed = bound_deployment(context, self.env_id, env_step_id=self.env_step_id, step_id=self.id) if deployed is None: raise StepContextError(f"Env '{self.env_id}' not found in context.deployed_envs") + if self.clock_mode is not None: + require_work(deployed, self.env_id) try: state = await deployed.invoke(EXT_CLOCK_URI, "set_rate", {"virtual_seconds_per_real_second": self.virtual_seconds_per_real_second}, timeout=self.timeout_seconds) except httpx.HTTPStatusError as e: raise RuntimeError(f"clock rate change failed (HTTP {e.response.status_code}): {_gateway_error(e.response)}") from e - context.metadata.setdefault("clock_configurations", []).append({ + configuration = { "step_id": self.id, "env_id": self.env_id, "virtual_seconds_per_real_second": self.virtual_seconds_per_real_second, "virtual_time": state.get("virtual_time"), - }) - logger.info(f"set_env_clock_rate env={self.env_id}: rate={self.virtual_seconds_per_real_second} " + } + if self.clock_mode is not None: + configuration.update(clock_mode=self.clock_mode, + work=await start_work(deployed, self.env_id, self.timeout_seconds)) + context.metadata.setdefault("clock_configurations", []).append(configuration) + mode = f" in {self.clock_mode} mode" if self.clock_mode else "" + logger.info(f"set_env_clock_rate env={self.env_id}: rate={self.virtual_seconds_per_real_second}{mode} " f"at {state.get('virtual_time')}") return context diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index f14876926..be05b8f70 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -13,6 +13,8 @@ Non-advertisers are skipped when tolerate_missing_sync_time (default True), and websites always. Place right before prompt_agent so the virtual timeline starts at agent-start; when setup needs the clock armed, arm it at rate 0 and start it with set_env_clock_rate right before prompt_agent. +With clock_mode "work" (``clock_mode.py``), the clock is armed frozen and the gateway's work mode turned on, so each +tool call the agent makes moves task time on by a fixed charge; a nonzero rate with it is an error. """ from __future__ import annotations @@ -32,6 +34,7 @@ from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.entity.refs import EntityRef from agent_env.task_step.task_step import TaskStep, TaskStepDependency +from agent_env.task_step.task_steps.clock_mode import clock_mode_rate, require_work, start_work from agent_env.task_step.task_steps.deploy_agent import bound_deployment if TYPE_CHECKING: @@ -76,7 +79,7 @@ def __init__( version: Optional[int], env_id: str, virtual_time: str, - virtual_seconds_per_real_second: float = 1.0, + virtual_seconds_per_real_second: Optional[float] = None, tolerate_missing_sync_time: bool = True, env_step_id: Optional[str] = None, depends_on: Optional[list[TaskStepDependency]] = None, @@ -85,10 +88,15 @@ def __init__( timezone: Optional[str] = None, require_agent_clock: bool = False, agent_clock: bool = False, + clock_mode: Optional[str] = None, ): - """virtual_seconds_per_real_second = clock speed (1.0 real time, 0 frozen, 86400 cap = + """virtual_seconds_per_real_second = clock speed (1.0 real time, the default, 0 frozen, 86400 cap = 1 real s -> 1 virtual day). For ~V virtual seconds over an ~R-real-second task, pass V/R. + clock_mode = unset, the default, for a clock that runs at its rate, as it always has; "work" for work mode: the + clock frozen (rate 0, the rate's default in it; any other rate is an error) and moved on by a fixed charge for + each tool call the agent makes (``clock_mode.py``). + timezone = optional IANA name. Unset keeps today's behaviour. Set, a wall-clock virtual_time is local time in 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). @@ -105,7 +113,8 @@ def __init__( self.env_id = env_id self.env_step_id = env_step_id self.virtual_time = virtual_time - self.virtual_seconds_per_real_second = virtual_seconds_per_real_second + self.virtual_seconds_per_real_second = clock_mode_rate(self.type, clock_mode, virtual_seconds_per_real_second, 1.0) + self.clock_mode = clock_mode self.tolerate_missing_sync_time = tolerate_missing_sync_time self.require_agent_clock = require_agent_clock self.agent_clock = agent_clock or require_agent_clock @@ -127,6 +136,8 @@ def to_dict(self) -> dict: base["require_agent_clock"] = True if self.agent_clock: base["agent_clock"] = True + if self.clock_mode is not None: + base["clock_mode"] = self.clock_mode return base @classmethod @@ -136,12 +147,13 @@ def from_dict(cls, data: dict) -> SyncEnvClockTaskStep: env_id=data["env_id"], env_step_id=data.get("env_step_id"), virtual_time=data["virtual_time"], - virtual_seconds_per_real_second=data.get("virtual_seconds_per_real_second", 1.0), + virtual_seconds_per_real_second=data.get("virtual_seconds_per_real_second"), tolerate_missing_sync_time=data.get("tolerate_missing_sync_time", True), timeout_seconds=data.get("timeout_seconds", 30), timezone=data.get("timezone"), require_agent_clock=data.get("require_agent_clock", False), agent_clock=data.get("agent_clock", False), + clock_mode=data.get("clock_mode"), ) async def _backing_servers(self, deployed) -> list[BackingServer]: @@ -156,6 +168,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: deployed = bound_deployment(context, self.env_id, env_step_id=self.env_step_id, step_id=self.id) if deployed is None: raise StepContextError(f"Env '{self.env_id}' not found in context.deployed_envs") + if self.clock_mode is not None: + require_work(deployed, self.env_id) 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, @@ -172,6 +186,7 @@ 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") + work = await start_work(deployed, self.env_id, self.timeout_seconds) if self.clock_mode is not None else None 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 " @@ -202,8 +217,11 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: if self.timezone is not None: configuration.update(timezone=self.timezone, armed_at=self.armed_virtual_time, get_time_zone=state.get("time_zone")) + if self.clock_mode is not None: + configuration.update(clock_mode=self.clock_mode, work=work) 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}; " + mode = f" in {self.clock_mode} mode" if self.clock_mode else "" + logger.info(f"sync_env_clock env={self.env_id}: armed rate={self.virtual_seconds_per_real_second}{mode}; " f"synced={[s['service'] for s in synced]} skipped={[s['service'] for s in skipped]} " f"agents={[(a['agent'], a['synced']) for a in agents]}") if not synced: diff --git a/tst/unit/env/gateway/clock_watch_test.py b/tst/unit/env/gateway/clock_watch_test.py index 7b7afc1ac..3e9fd0ddc 100644 --- a/tst/unit/env/gateway/clock_watch_test.py +++ b/tst/unit/env/gateway/clock_watch_test.py @@ -80,7 +80,7 @@ def test_the_card_offers_every_clock_method_with_the_waits_bound_and_the_watchs_ assert {name: (m["method"], m["endpoint"]) for name, m in methods.items()} == { "get_time": ("GET", "/clock/time"), "set_time": ("PUT", "/clock/set-time"), "set_rate": ("PUT", "/clock/set-rate"), "advance": ("PUT", "/clock/advance"), "clear": ("POST", "/clock/clear"), "state": ("GET", "/clock/state"), - "declare_follower": ("PUT", "/clock/followers"), "retire_follower": ("DELETE", "/clock/followers"), + "work": ("PUT", "/clock/work"), "declare_follower": ("PUT", "/clock/followers"), "retire_follower": ("DELETE", "/clock/followers"), "watch": ("GET", "/clock/watch")} assert all(methods[name]["request"]["properties"]["wait_followers_s"] == wait for name in ("set_time", "set_rate", "advance", "clear")) diff --git a/tst/unit/env/gateway/work_clock_test.py b/tst/unit/env/gateway/work_clock_test.py new file mode 100644 index 000000000..23c9773ea --- /dev/null +++ b/tst/unit/env/gateway/work_clock_test.py @@ -0,0 +1,429 @@ +"""Work mode (FD-7183): a frozen clock moved on by a fixed charge for each answered tool call the agent makes, counted by +the gateway, so the world lives through the agent's work. Clock.advance_by, the /clock/work switch, the charge on every +agent call path and on no one else's, and the hold until the time triggers a charge made due have landed.""" +from __future__ import annotations + +import asyncio +import json +import threading + +import httpx +import pytest +from mcp.types import CallToolResult, TextContent + +from agent_env.env.gateway import gateway as gw_mod +from agent_env.env.gateway.caller import Caller +from agent_env.env.gateway.clock import Clock, ClockError +from agent_env.env.gateway.constants import AGENT_ENV_ROLE_HEADER, EXT_CLOCK_URI, GATEWAY_EXTENSIONS +from agent_env.env.gateway.gateway import Gateway +from agent_env.env.gateway.triggers import TriggerEngine +from tst.unit.env.gateway.triggers_time_test import FakeNow + +T0 = "2026-11-08T17:00:00Z" +GW = "http://gateway.test" + + +# ---- Clock.advance_by ----------------------------------------------------------------------------------------------- + +def _armed(rate: float = 0) -> tuple[Clock, FakeNow]: + now = FakeNow() + clock = Clock(now_fn=now) + clock.set_time(T0, rate=rate) + return clock, now + + +def test_advance_by_moves_time_on_and_keeps_t0_rate_and_generation(): + clock, _ = _armed() + version, generation, lived = clock.version, clock.generation, clock.elapsed() + state = clock.advance_by(90) + assert state["virtual_time"] == "2026-11-08T17:01:30Z" + assert (state["t0"], state["virtual_seconds_per_real_second"]) == (T0, 0) + assert clock.generation == generation and state["version"] != version + assert clock.elapsed() == pytest.approx(lived + 90) + clock.advance_by(0.5) + assert clock.read()["virtual_time"] == "2026-11-08T17:01:30.500000Z" + + +def test_advance_by_adds_to_a_running_clock(): + clock, now = _armed(rate=60) + now.tick(60) # an hour at 60x + clock.advance_by(600) + assert clock.read()["virtual_time"] == "2026-11-08T18:10:00Z" + now.tick(1) + assert clock.read()["virtual_time"] == "2026-11-08T18:11:00Z" + + +def test_advance_by_is_atomic_so_parallel_charges_sum(): + clock, _ = _armed() + threads = [threading.Thread(target=lambda: [clock.advance_by(1) for _ in range(50)]) for _ in range(8)] + for t in threads: + t.start() + for t in threads: + t.join() + assert clock.read()["virtual_time"] == "2026-11-08T17:06:40Z" # 400 s + + +@pytest.mark.parametrize("bad", [-1, -0.001, float("nan"), float("inf"), True, False, "60", None, [60]]) +def test_advance_by_refuses_anything_but_a_finite_non_negative_number(bad): + clock, _ = _armed() + version = clock.version + with pytest.raises(ClockError): + clock.advance_by(bad) + assert clock.version == version and clock.read()["virtual_time"] == T0 + + +def test_advance_by_refuses_an_unarmed_clock_and_an_overflow(): + with pytest.raises(ClockError, match="not armed"): + Clock(now_fn=FakeNow()).advance_by(1) + clock, _ = _armed() + with pytest.raises(ClockError): + clock.advance_by(1e300) + assert clock.read()["virtual_time"] == T0 + + +# ---- the gateway ---------------------------------------------------------------------------------------------------- + +@pytest.fixture +def gw(tmp_path, monkeypatch): + monkeypatch.setattr(gw_mod, "GATEWAY_TRAJECTORY_FILE", str(tmp_path / "trajectory.jsonl")) + gateway = Gateway(host="127.0.0.1", port=0, server_name="AgentEnvGateway", internal_mcp_servers=[]) + gateway._tools_discovered = True + + def app_lookup() -> str: + """Look something up.""" + return "found" + + def app_refuses() -> CallToolResult: + """Answer with an error result.""" + return CallToolResult(content=[TextContent(type="text", text="no such order")], isError=True) + + def app_crashes() -> str: + """Raise.""" + raise RuntimeError("backend down") + + for fn in (app_lookup, app_refuses, app_crashes): + gateway._mcp.add_tool(fn, name=fn.__name__) + yield gateway + gateway._close_trajectory_file() + + +def _client(gateway: Gateway) -> httpx.AsyncClient: + return httpx.AsyncClient(transport=httpx.ASGITransport(app=gateway._mcp.streamable_http_app()), base_url=GW) + + +async def _arm(client: httpx.AsyncClient) -> None: + r = await client.put("/clock/set-time", json={"virtual_time": T0, "virtual_seconds_per_real_second": 0}) + assert r.status_code == 200, r.text + + +async def _work(client: httpx.AsyncClient, on: bool = True) -> httpx.Response: + return await client.put("/clock/work", json={"on": on}) + + +async def _call(client: httpx.AsyncClient, tool: str, role: str = "default", **body) -> httpx.Response: + return await client.post("/step", json={"action": "call_tool", "tool_name": tool, "arguments": {}, **body}, + headers={AGENT_ENV_ROLE_HEADER: role}) + + +async def _now(client: httpx.AsyncClient) -> str: + return (await client.get("/clock/time")).json()["virtual_time"] + + +async def _work_state(client: httpx.AsyncClient) -> dict: + return (await client.get("/clock/state")).json()["work"] + + +def _logged(gateway: Gateway, event_type: str) -> list[dict]: + gateway._trajectory_file.flush() + with open(gateway._trajectory_file.name) as f: + return [e for e in map(json.loads, filter(str.strip, f)) if e["event_type"] == event_type] + + +@pytest.mark.asyncio +async def test_state_shows_work_mode_off_until_turned_on(gw): + async with _client(gw) as client: + await _arm(client) + assert await _work_state(client) == {"on": False, "seconds_per_call": 60.0, "roles": ["default"], + "calls": 0, "virtual_seconds": 0.0, "by_role": {}} + r = await _work(client) + assert r.status_code == 200, r.text + assert r.json()["work"]["on"] is True + assert (await _work_state(client))["on"] is True + assert (await _work(client, on=False)).json()["work"]["on"] is False + + +@pytest.mark.asyncio +@pytest.mark.parametrize("body", [ + [], {}, {"on": "yes"}, {"on": 1}, {"on": None}, {"on": True, "seconds_per_call": 30}, + {"on": True, "roles": ["default"]}, {"on": True, "hold_seconds": 5}, {"on": True, "tool_seconds": {"x": 1}}, +]) +async def test_a_bad_body_is_refused_and_changes_nothing(gw, body): + async with _client(gw) as client: + await _arm(client) + assert (await _work(client)).status_code == 200 + r = await client.put("/clock/work", content=json.dumps(body)) + assert r.status_code == 400, r.text + assert (await _work_state(client))["on"] is True + assert (await client.put("/clock/work", content=b"not json")).status_code == 400 + + +@pytest.mark.asyncio +async def test_turning_it_on_needs_an_armed_frozen_clock_and_keeps_the_clocks_version(gw): + async with _client(gw) as client: + r = await _work(client) + assert r.status_code == 400 and "armed" in r.json()["error"] + assert (await _work(client, on=False)).status_code == 200 # off needs no clock + r = await client.put("/clock/set-time", json={"virtual_time": T0, "virtual_seconds_per_real_second": 1}) + assert r.status_code == 200 + r = await _work(client) + assert r.status_code == 400 and "rate 0" in r.json()["error"] + await _arm(client) + version = (await client.get("/clock/state")).json()["version"] + assert (await _work(client)).status_code == 200 + assert (await client.get("/clock/state")).json()["version"] == version + + +@pytest.mark.asyncio +async def test_set_time_set_rate_and_clear_leave_work_mode_and_advance_doesnt(gw): + async with _client(gw) as client: + for leave in (lambda: client.put("/clock/set-rate", json={"virtual_seconds_per_real_second": 0}), + lambda: client.put("/clock/set-time", json={"virtual_time": T0, + "virtual_seconds_per_real_second": 0}), + lambda: client.post("/clock/clear")): + await _arm(client) + assert (await _work(client)).status_code == 200 + assert (await client.put("/clock/advance", json={"virtual_time": "2026-11-08T18:00:00Z"})).status_code == 200 + assert (await _work_state(client))["on"] is True + assert (await leave()).status_code == 200 + assert (await _work_state(client))["on"] is False + # A write the clock refuses changes nothing, work mode included. + await _arm(client) + await _work(client) + assert (await client.put("/clock/set-rate", json={"virtual_seconds_per_real_second": -1})).status_code == 400 + assert (await _work_state(client))["on"] is True + + +def test_the_card_offers_work(): + clock_ext = next(e for e in GATEWAY_EXTENSIONS if e["uri"] == EXT_CLOCK_URI) + work = clock_ext["params"]["methods"]["work"] + assert (work["method"], work["endpoint"]) == ("PUT", "/clock/work") + assert set(work["request"]["properties"]) == {"on"} and work["request"]["required"] == ["on"] + assert "work" in clock_ext["description"] and "60 s" in clock_ext["description"] + + +@pytest.mark.asyncio +async def test_each_answered_call_by_the_agent_moves_the_clock_a_minute(gw): + async with _client(gw) as client: + await _arm(client) + await _work(client) + assert (await _call(client, "app_lookup")).status_code == 200 + assert await _now(client) == "2026-11-08T17:01:00Z" + r = await _call(client, "app_refuses") # an error result is an answered call + assert r.status_code == 200 and r.json()["isError"] is True + assert await _now(client) == "2026-11-08T17:02:00Z" + work = await _work_state(client) + assert (work["calls"], work["virtual_seconds"], work["by_role"]) == ( + 2, 120.0, {"default": {"calls": 2, "virtual_seconds": 120.0}}) + first, second = _logged(gw, "work_clock_charge") + assert {k: first[k] for k in ("tool", "role", "seconds", "virtual_time_before", "virtual_time_after", "due", + "still_running")} == { + "tool": "app_lookup", "role": "default", "seconds": 60.0, "virtual_time_before": T0, + "virtual_time_after": "2026-11-08T17:01:00Z", "due": [], "still_running": []} + assert first["held_s"] >= 0 and first["call_real_s"] >= 0 + assert (second["tool"], second["seconds"]) == ("app_refuses", 60.0) + + +@pytest.mark.asyncio +async def test_a_call_to_a_backing_server_is_charged(gw, monkeypatch): + gw._tool_server_urls["svc_send"] = "http://svc:8000/mcp" + + async def child(url, tool, arguments, **kw): + return CallToolResult(content=[TextContent(type="text", text="sent")]) + monkeypatch.setattr(gw, "_call_child_tool", child) + async with _client(gw) as client: + await _arm(client) + await _work(client) + assert (await _call(client, "svc_send")).status_code == 200 + assert await _now(client) == "2026-11-08T17:01:00Z" + assert [e["tool"] for e in _logged(gw, "work_clock_charge")] == ["svc_send"] + + +@pytest.mark.asyncio +async def test_a_call_over_mcp_is_charged(gw): + async with _client(gw) as client: + await _arm(client) + await _work(client) + token = Caller(role="default").bind() + try: + await gw._mcp._tool_manager.call_tool("app_lookup", {}) + finally: + Caller.reset(token) + assert await _now(client) == "2026-11-08T17:01:00Z" + + +@pytest.mark.asyncio +async def test_what_the_agent_does_that_is_not_charged(gw): + """A call that raised, a disabled tool, and get_time, the agent's own calls all.""" + async with _client(gw) as client: + await _arm(client) + await _work(client) + assert (await _call(client, "app_crashes")).status_code == 500 + gw._apply_rule("default", "app_lookup", True) + assert (await _call(client, "app_lookup")).status_code == 403 + assert (await _call(client, "get_time")).status_code == 200 + assert await _now(client) == T0 + assert _logged(gw, "work_clock_charge") == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("path", ["mcp", "step"]) +async def test_no_one_but_the_agent_is_charged(gw, monkeypatch, path): + """The agent is whose calls provoke triggers (watch_roles) and no executor's. A setup step's, a verifier's, a user + sim's or a contact's calls, a trigger's own tool action and a post-turn hook's call, even one made as the agent, + move nothing: only the agent's own call does.""" + gw._trigger_engine.register({ + "watch_roles": ["assistant"], "executors": {"bob": {"a2a_url": "http://bob", "role": "contact-bob"}}, + "triggers": [{"id": "mirror", "when": {"type": "action", "tool": "app_lookup", "repeat": True}, + "barrier": {"at": "provoking_call"}, + "actions": [{"type": "tool", "tool": "app_lookup", "args": {}}]}]}) + + async def call(tool: str, role: str) -> None: + if path == "step": + assert (await _call(client, tool, role)).status_code == 200 + return + token = Caller(role=role).bind() + try: + await gw._mcp._tool_manager.call_tool(tool, {}) + finally: + Caller.reset(token) + + async with _client(gw) as client: + await _arm(client) + await _work(client) + assert (await _work_state(client))["roles"] == ["assistant"] + for role in ("default", "setup", "verifier", "user-sim", "contact-bob"): + await call("app_lookup", role) # watched only for the agent: a non-agent's call fires nothing either + r = await _call(client, "app_lookup", "assistant", source="post_turn_hook", hook_artifact_id="next-event") + assert r.status_code == 200 + assert await _now(client) == T0 and _logged(gw, "work_clock_charge") == [] + + await call("app_lookup", "assistant") # the agent's call, whose trigger's own tool action is free + assert await _now(client) == "2026-11-08T17:01:00Z" + mirror = next(t for t in gw._trigger_engine.state()["triggers"] if t["id"] == "mirror") + # Fired by the hook's call, made as the agent, and the agent's own, never by another role's; its action ran. + assert mirror["fire_count"] == 2 + assert [(e["tool"], e["role"]) for e in _logged(gw, "work_clock_charge")] == [("app_lookup", "assistant")] + + +@pytest.mark.asyncio +async def test_the_agents_roles_are_read_at_each_call(gw): + """Triggers registered after work mode was turned on decide who the agent is from then on.""" + async with _client(gw) as client: + await _arm(client) + await _work(client) + await _call(client, "app_lookup", "assistant") + assert await _now(client) == T0 + gw._trigger_engine.register({"watch_roles": ["assistant"], "triggers": []}) + await _call(client, "app_lookup", "assistant") + await _call(client, "app_lookup", "default") + assert await _now(client) == "2026-11-08T17:01:00Z" + + +@pytest.mark.asyncio +async def test_parallel_calls_each_pay(gw): + async with _client(gw) as client: + await _arm(client) + await _work(client) + rs = await asyncio.gather(*(_call(client, "app_lookup") for _ in range(5))) + assert {r.status_code for r in rs} == {200} + assert await _now(client) == "2026-11-08T17:05:00Z" + + +@pytest.mark.asyncio +async def test_a_charge_on_a_clock_disarmed_under_it_is_skipped_and_says_so(gw): + async with _client(gw) as client: + await _arm(client) + await _work(client) + gw._clock.clear() # disarmed without the route, which would also have left work mode + assert (await _call(client, "app_lookup")).status_code == 200 + (skipped,) = _logged(gw, "work_clock_skipped") + assert (skipped["tool"], skipped["role"], skipped["seconds"]) == ("app_lookup", "default", 60.0) + assert "armed" in skipped["reason"] + assert _logged(gw, "work_clock_charge") == [] + + +# ---- what the charge made due --------------------------------------------------------------------------------------- + +def _reply_at(gw: Gateway, at: str = "PT1M", **action) -> None: + gw._trigger_engine.register({ + "watch_roles": ["default"], "executors": {"bob": {"a2a_url": "http://bob", "role": "bob"}}, + "triggers": [{"id": "sellout", "when": {"type": "time", "at": at}, + "actions": [{"type": "nl", "executor": "bob", "instruction": "reply", **action}]}]}) + + +def _executor(monkeypatch, seconds: float) -> list: + calls = [] + + async def call(engine, ex, instruction, context_id): + await asyncio.sleep(seconds) + calls.append(engine._gw._clock.read()["virtual_time"]) + return "replied" + monkeypatch.setattr(TriggerEngine, "_call_executor", call) + return calls + + +def _trigger(gw: Gateway) -> dict: + return next(t for t in gw._trigger_engine.state()["triggers"] if t["id"] == "sellout") + + +@pytest.mark.asyncio +async def test_a_trigger_the_charge_made_due_lands_before_the_call_is_answered(gw, monkeypatch): + replies = _executor(monkeypatch, 0.3) + async with _client(gw) as client: + await _arm(client) + _reply_at(gw) + await _work(client) + assert (await _call(client, "app_lookup")).status_code == 200 + assert replies == ["2026-11-08T17:01:00Z"] + assert (_trigger(gw)["status"], _trigger(gw)["fire_count"]) == ("fired", 1) + (charge,) = _logged(gw, "work_clock_charge") + assert (charge["due"], charge["still_running"]) == (["sellout"], []) + assert charge["held_s"] >= 0.25 + + +@pytest.mark.asyncio +async def test_a_fire_waiting_on_later_task_time_doesnt_hold_the_call(gw, monkeypatch): + replies = _executor(monkeypatch, 0) + async with _client(gw) as client: + await _arm(client) + _reply_at(gw, delay="PT1H") + await _work(client) + assert (await _call(client, "app_lookup")).status_code == 200 + assert replies == [] and _trigger(gw)["waiting"] is True + (charge,) = _logged(gw, "work_clock_charge") + assert (charge["due"], charge["still_running"]) == (["sellout"], []) + assert charge["held_s"] < 2 + await gw._trigger_engine.cancel_scheduled() + + +@pytest.mark.asyncio +async def test_the_hold_gives_up_after_hold_seconds(gw, monkeypatch): + _executor(monkeypatch, 30) + monkeypatch.setattr(gw_mod, "HOLD_SECONDS", 0.2) + async with _client(gw) as client: + await _arm(client) + _reply_at(gw) + await _work(client) + assert (await _call(client, "app_lookup")).status_code == 200 + (charge,) = _logged(gw, "work_clock_charge") + assert (charge["due"], charge["still_running"]) == (["sellout"], ["sellout"]) + assert 0.15 <= charge["held_s"] < 5 + await gw._trigger_engine.cancel_scheduled() + + +# ---- TriggerEngine.settle_due --------------------------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_settle_due_with_nothing_due_returns_at_once(gw): + assert await gw._trigger_engine.settle_due([], 5) == [] + assert await gw._trigger_engine.settle_due(["no-such-trigger"], 5) == [] diff --git a/tst/unit/task_step/always_on_harness.py b/tst/unit/task_step/always_on_harness.py index 384fd619c..71a95e42d 100644 --- a/tst/unit/task_step/always_on_harness.py +++ b/tst/unit/task_step/always_on_harness.py @@ -79,7 +79,8 @@ class Rig: """The world, the agent and the user sim for one always_on run. ``agent(n, texts, rig)`` plays the agent's nth turn (nudges included) given the texts it was sent, acting through - ``message``, ``quiet`` and ``schedule``, and returns its closing text; by default it stays quiet. ``answers`` are the + ``message``, ``quiet`` and ``schedule``, and returns its closing text; by default it stays quiet. An async one may + also call the gateway's tools (``call``, on a ``tool`` the gateway serves). ``answers`` are the user sim's answers to its reads, in order; once they run out it answers no_reply. Every message the agent got is in ``sent``, every read the user sim got in ``reads``. A ``plugin`` replaces the scripted one; what it sends the user sim agent with ``ask`` is @@ -236,6 +237,20 @@ def quiet(self) -> dict: def schedule(self, note: str, at: str) -> dict: return self.gw._notifications.schedule(note, at=at, to=ROLE) + def tool(self, name: str, answer: str = "done") -> None: + """A tool the gateway serves itself, answering ``answer``, for ``call``.""" + def fn() -> str: + return answer + self.gw._mcp.add_tool(fn, name=name, description=f"{name}, for the test") + + async def call(self, tool: str, arguments: Optional[dict] = None, role: str = ROLE) -> dict: + """The agent's tool call through the gateway (``/step``), as an agent makes one, for an async turn.""" + async with self.http() as client: + r = await client.post("/step", json={"action": "call_tool", "tool_name": tool, "arguments": arguments or {}}, + headers={AGENT_ENV_ROLE_HEADER: role}) + r.raise_for_status() + return r.json() + async def tools(self, role: str = ROLE) -> set[str]: async with self.http() as client: r = await client.post("/step", json={"action": "list_tools"}, headers={AGENT_ENV_ROLE_HEADER: role}) @@ -312,6 +327,8 @@ async def _send_and_wait(self, url, parts, *, before_send=None, **kw): if kw.get("on_sent"): kw["on_sent"](task_id) closing = self.agent(len(self.sent), texts, self) # a TimeoutError it raises is the turn timing out + if asyncio.iscoroutine(closing): # a turn that calls the gateway's tools (``call``) is async + closing = await closing if isinstance(closing, Slow): work = asyncio.ensure_future(self._work(closing)) self.agent_tasks[task_id] = (work, closing) diff --git a/tst/unit/task_step/clock_mode_test.py b/tst/unit/task_step/clock_mode_test.py new file mode 100644 index 000000000..7e24d6ec1 --- /dev/null +++ b/tst/unit/task_step/clock_mode_test.py @@ -0,0 +1,258 @@ +"""The clock setup steps' ``clock_mode`` (FD-7183): ``"work"`` arms the clock frozen (rate 0) and turns on the +gateway's work mode, where each tool call the agent makes moves task time on by a fixed charge, so a frozen world +still lives through the agent's work. sync_env_clock and set_env_clock_rate both take it, each driving a real +in-process gateway here. Without clock_mode, either step does exactly what it did before.""" +from __future__ import annotations + +import json +from types import SimpleNamespace + +import httpx +import pytest + +from agent_env.env.env import DeployedGatewayEnv +from agent_env.env.gateway import gateway as gw_mod +from agent_env.env.gateway.constants import AGENT_ENV_ROLE_HEADER, WELL_KNOWN_PATH +from agent_env.env.gateway.gateway import Gateway +from agent_env.task_step.context import StepContextError, TaskStepContext +from agent_env.task_step.task_steps.set_env_clock_rate import SetEnvClockRateTaskStep +from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep + +T0 = "2026-11-09T14:00:00Z" +GATEWAY = "http://gateway.test" + + +class _Recording(httpx.AsyncBaseTransport): + """The gateway's own ASGI app behind a transport that records each request: (method, path, JSON body or None).""" + + def __init__(self, app) -> None: + self.inner = httpx.ASGITransport(app=app) + self.sent: list[tuple[str, str, object]] = [] + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + body = request.content + self.sent.append((request.method, request.url.path, json.loads(body) if body else None)) + return await self.inner.handle_async_request(request) + + +class World: + """A real gateway, the deploy record a task holds for it, and a native tool for the agent to call.""" + + def __init__(self, monkeypatch, tmp_path) -> None: + monkeypatch.setattr(gw_mod, "GATEWAY_TRAJECTORY_FILE", str(tmp_path / "trajectory.jsonl")) + self.gw = Gateway(host="127.0.0.1", port=0, server_name="AgentEnvGateway", internal_mcp_servers=[]) + self.gw._tools_discovered = True + + def lookup() -> str: + return "found" + self.gw._mcp.add_tool(lookup, name="lookup", description="lookup, for the test") + self.transport = _Recording(self.gw._mcp.streamable_http_app()) + real = httpx.AsyncClient + monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **kw: real(*a, **{**kw, "transport": self.transport})) + self.http = lambda: real(transport=self.transport, base_url=GATEWAY) + # The env's definition names no servers, so the step syncs none. + monkeypatch.setattr("agent_env.env.env.Env.get", + lambda *a, **k: SimpleNamespace(mcp_server_envs=[], website_envs=[])) + + async def deployed(self, card: dict | None = None) -> DeployedGatewayEnv: + if card is None: + card = json.loads((await self.gw._serve_env_card()).body) + return DeployedGatewayEnv(env_id="e1", env_version=1, gateway_url=GATEWAY, mcp_url=f"{GATEWAY}/mcp", + sandbox_id="sb-1", environment_card_url=f"{GATEWAY}{WELL_KNOWN_PATH}", + environment_card=card) + + async def context(self, card: dict | None = None) -> TaskStepContext: + return TaskStepContext(deployed_envs=[await self.deployed(card)]) + + async def state(self) -> dict: + async with self.http() as client: + return (await client.get("/clock/state")).json() + + async def call(self, tool: str = "lookup", role: str | None = None) -> None: + """A tool call through the gateway's /step, as the agent (no role header: the default role) or ``role``.""" + async with self.http() as client: + r = await client.post("/step", json={"action": "call_tool", "tool_name": tool, "arguments": {}}, + headers={AGENT_ENV_ROLE_HEADER: role} if role else {}) + r.raise_for_status() + + def clock_calls(self) -> list[tuple[str, str, object]]: + return [(m, p, b) for m, p, b in self.transport.sent if p.startswith("/clock/")] + + def forget(self) -> None: + self.transport.sent.clear() + + +@pytest.fixture +def world(monkeypatch, tmp_path) -> World: + return World(monkeypatch, tmp_path) + + +def _sync(**kw) -> SyncEnvClockTaskStep: + return SyncEnvClockTaskStep(id="clock", version=1, env_id="e1", virtual_time=T0, depends_on=[], **kw) + + +def _rate(rate=None, **kw) -> SetEnvClockRateTaskStep: + if rate is not None: + kw["virtual_seconds_per_real_second"] = rate + return SetEnvClockRateTaskStep(id="clock-rate", version=1, env_id="e1", depends_on=[], **kw) + + +# ---- sync_env_clock ------------------------------------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_sync_env_clock_in_work_mode_arms_frozen_then_turns_work_on(world): + context = await world.context() + + await _sync(clock_mode="work").execute(context) + + assert world.clock_calls() == [ + ("PUT", "/clock/set-time", {"virtual_time": T0, "virtual_seconds_per_real_second": 0}), + ("GET", "/clock/state", None), + ("PUT", "/clock/work", {"on": True}), + ] + state = await world.state() + assert state["virtual_seconds_per_real_second"] == 0 + assert state["work"]["on"] is True and state["work"]["seconds_per_call"] == 60 + record = context.metadata["clock_configurations"][0] + assert record["clock_mode"] == "work" and record["virtual_seconds_per_real_second"] == 0 + + await world.call() + assert (await world.state())["virtual_time"] == "2026-11-09T14:01:00Z" + + +@pytest.mark.asyncio +async def test_sync_env_clock_work_mode_takes_an_explicit_rate_of_zero(world): + step = _sync(clock_mode="work", virtual_seconds_per_real_second=0) + await step.execute(await world.context()) + assert (await world.state())["work"]["on"] is True + + +@pytest.mark.parametrize("rate", [1, 1.0, 0.5, 3600]) +def test_sync_env_clock_refuses_work_mode_with_a_running_rate(rate): + with pytest.raises(ValueError, match="clock_mode 'work'.*rate 0"): + _sync(clock_mode="work", virtual_seconds_per_real_second=rate) + + +@pytest.mark.parametrize("mode", ["Work", "real", "frozen", "", 1, True]) +def test_sync_env_clock_refuses_an_unknown_clock_mode(mode): + with pytest.raises(ValueError, match="clock_mode"): + _sync(clock_mode=mode) + + +def test_sync_env_clock_work_mode_round_trips_and_a_plain_step_has_no_clock_mode(): + d = _sync(clock_mode="work").to_dict() + assert d["clock_mode"] == "work" and d["virtual_seconds_per_real_second"] == 0 + again = SyncEnvClockTaskStep.from_dict(d) + assert (again.clock_mode, again.virtual_seconds_per_real_second) == ("work", 0) + # A task JSON that names the mode and leaves the rate out is armed frozen. + bare = {k: v for k, v in d.items() if k != "virtual_seconds_per_real_second"} + assert SyncEnvClockTaskStep.from_dict(bare).virtual_seconds_per_real_second == 0 + + +@pytest.mark.asyncio +async def test_sync_env_clock_work_mode_on_a_gateway_without_work_fails_before_arming(world): + card = json.loads((await world.gw._serve_env_card()).body) + for ext in card["capabilities"]["extensions"]: + (ext.get("params") or {}).get("methods", {}).pop("work", None) # a gateway image from before work mode + + with pytest.raises(StepContextError, match="work"): + await _sync(clock_mode="work").execute(await world.context(card)) + assert world.clock_calls() == [] + assert (await world.state())["armed"] is False + + +# ---- set_env_clock_rate --------------------------------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_set_env_clock_rate_in_work_mode_freezes_the_clock_then_turns_work_on(world): + await _sync(virtual_seconds_per_real_second=0).execute(await world.context()) # armed frozen during setup + world.forget() + context = await world.context() + + await _rate(clock_mode="work").execute(context) + + assert world.clock_calls() == [ + ("PUT", "/clock/set-rate", {"virtual_seconds_per_real_second": 0}), + ("PUT", "/clock/work", {"on": True}), + ] + assert (await world.state())["work"]["on"] is True + assert context.metadata["clock_configurations"][0]["clock_mode"] == "work" + await world.call() + assert (await world.state())["virtual_time"] == "2026-11-09T14:01:00Z" + + +@pytest.mark.parametrize("rate", [1, 0.25, 86400]) +def test_set_env_clock_rate_refuses_work_mode_with_a_running_rate(rate): + with pytest.raises(ValueError, match="clock_mode 'work'.*rate 0"): + _rate(rate, clock_mode="work") + + +def test_set_env_clock_rate_needs_a_rate_or_work_mode(): + with pytest.raises(ValueError, match="virtual_seconds_per_real_second"): + _rate() + assert _rate(clock_mode="work").virtual_seconds_per_real_second == 0 + d = _rate(clock_mode="work").to_dict() + assert d["clock_mode"] == "work" + assert SetEnvClockRateTaskStep.from_dict({k: v for k, v in d.items() + if k != "virtual_seconds_per_real_second"}).clock_mode == "work" + + +@pytest.mark.asyncio +async def test_set_env_clock_rate_to_zero_after_the_agent_ends_work_mode(world): + """The usual stop after the agent's last prompt_agent: a plain rate of 0 leaves work mode, so the harness's own + calls after it (verifiers, collecting artifacts) move nothing.""" + await _sync(clock_mode="work").execute(await world.context()) + await world.call() + + await _rate(0).execute(await world.context()) + + state = await world.state() + assert state["work"]["on"] is False + await world.call() + assert (await world.state())["virtual_time"] == state["virtual_time"] + + +# ---- no clock_mode: exactly as before ------------------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_without_clock_mode_the_steps_send_what_they_always_sent(world): + sync, rate = _sync(), _rate(0) + assert "clock_mode" not in sync.to_dict() and "clock_mode" not in rate.to_dict() + assert sync.to_dict()["virtual_seconds_per_real_second"] == 1.0 + assert SyncEnvClockTaskStep.from_dict(sync.to_dict()).to_dict() == sync.to_dict() + assert SetEnvClockRateTaskStep.from_dict(rate.to_dict()).to_dict() == rate.to_dict() + + context = await world.context() + await _sync(virtual_seconds_per_real_second=0).execute(context) + await rate.execute(context) + + assert world.clock_calls() == [ + ("PUT", "/clock/set-time", {"virtual_time": T0, "virtual_seconds_per_real_second": 0}), + ("GET", "/clock/state", None), + ("PUT", "/clock/set-rate", {"virtual_seconds_per_real_second": 0}), + ] + assert [set(c) for c in context.metadata["clock_configurations"]] == [ + {"step_id", "env_id", "deploy_step_id", "virtual_time", "virtual_seconds_per_real_second", "env_get_time_url", + "synced", "skipped", "agents", "require_agent_clock", "agent_clock"}, + {"step_id", "env_id", "virtual_seconds_per_real_second", "virtual_time"}, + ] + + +@pytest.mark.asyncio +async def test_without_clock_mode_agent_calls_move_no_time(world): + await _sync(virtual_seconds_per_real_second=0).execute(await world.context()) + for _ in range(3): + await world.call() + state = await world.state() + assert state["virtual_time"] == T0 + assert state["work"]["on"] is False and state["work"]["calls"] == 0 + + +@pytest.mark.asyncio +async def test_a_plain_re_arm_leaves_work_mode(world): + """A later sync_env_clock without clock_mode arms the clock as it always has: work mode doesn't outlive it.""" + await _sync(clock_mode="work").execute(await world.context()) + await _sync(virtual_seconds_per_real_second=0).execute(await world.context()) + assert (await world.state())["work"]["on"] is False + await world.call() + assert (await world.state())["virtual_time"] == T0 diff --git a/tst/unit/task_step/test_always_on_work_clock.py b/tst/unit/task_step/test_always_on_work_clock.py new file mode 100644 index 000000000..2a1968b7c --- /dev/null +++ b/tst/unit/task_step/test_always_on_work_clock.py @@ -0,0 +1,206 @@ +"""Work mode (FD-7183) in an always_on run. The task's clock step puts the clock in work mode (sync_env_clock with +``clock_mode: "work"``): frozen, and moved on a minute by the gateway for each tool call the agent makes, so the world +lives through the agent's work and what comes due mid-wake lands then. always_on only reports it, as the gateway's +/clock/state says: each wake records what its work took, the run's record sums it, and the judge reads it. No one but +the agent is charged, inside its turns or out.""" + +from __future__ import annotations + +import asyncio +from types import SimpleNamespace + +import pytest + +from agent_env.env.gateway.triggers import TriggerEngine +from agent_env.task_step.task_steps import always_on as ao +from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep +from tst.unit.task_step.always_on_harness import ROLE, Rig + +pytestmark = pytest.mark.usefixtures("local_stores") + + +async def _work_mode(monkeypatch, rig: Rig, ctx) -> None: + """Arm the clock in work mode as the task's clock step does: sync_env_clock with clock_mode "work".""" + monkeypatch.setattr("agent_env.env.env.Env.get", + lambda *a, **k: SimpleNamespace(mcp_server_envs=[], website_envs=[])) + await SyncEnvClockTaskStep(id="clock", version=1, env_id="world", virtual_time=rig.t0, + clock_mode="work").execute(ctx) + + +async def _work_state(rig: Rig) -> dict: + async with rig.http() as client: + return (await client.get("/clock/state")).json()["work"] + + +@pytest.mark.asyncio +async def test_in_work_mode_each_wake_records_what_the_agents_work_took(monkeypatch, tmp_path): + async def agent(n, texts, rig): + if n == 1: + for _ in range(3): + await rig.call("market_search") + rig.message("Chicago is still open; holding two seats") + else: + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "great"},)) + rig.tool("market_search", "Chicago: 2 left") + ctx = rig.context() + await _work_mode(monkeypatch, rig, ctx) + await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=2), ctx) + + first, second = rig.events(ctx, "agent_turn_end") + assert first["work"] == {"calls": 3, "virtual_seconds": 180.0} + assert first["virtual_seconds"] == 180 + assert second["work"] == {"calls": 0, "virtual_seconds": 0.0} + record = rig.record(ctx) + assert record["counts"]["work_clock"] == {"calls": 3, "virtual_seconds": 180.0} + assert record["settings"]["clock"] == {"envs": [], "work": {"seconds_per_call": 60.0, "envs": ["world"]}} + # always_on reports work mode and changes nothing of it: the clock is still in it after the run. + work = await _work_state(rig) + assert work["on"] is True and work["by_role"] == {ROLE: {"calls": 3, "virtual_seconds": 180.0}} + + +@pytest.mark.asyncio +async def test_what_comes_due_mid_wake_lands_before_the_agents_next_call(monkeypatch, tmp_path): + status: list[str] = [] + + async def agent(n, texts, rig): + if n == 1: + await rig.call("market_search") + await rig.call("market_search") # 9:02, when Chicago sells out + status.append(next(t["status"] for t in rig.gw._trigger_engine.state()["triggers"] + if t["id"] == "sellout")) + await rig.call("market_search") + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + rig.tool("market_search") + ctx = rig.context() + await _work_mode(monkeypatch, rig, ctx) + rig.triggers(rig.notify_at("sellout", "PT2M", "Chicago is sold out", channel="Market")) + await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=2), ctx) + + assert status == ["fired"] + _, alerted = rig.events(ctx, "wake") + assert "[Mon Nov 9, 9:02 AM EST · Market]" in alerted["parts_text"] + assert alerted["virtual_time"].startswith("2026-11-09T14:03:00") # after the turn's three calls + + +@pytest.mark.asyncio +async def test_no_one_but_the_agent_is_charged_inside_or_outside_its_turns(monkeypatch, tmp_path): + """A setup step's, a verifier's and a user sim's calls, a contact's (a trigger's executor), and a trigger's own + tool action, made before the run, during the agent's turn, between its turns and after the run, take no task time; + the agent's one call takes a minute.""" + others = ("setup", "verifier", "user-sim", "contact-bob") + turn = {"on": False} + contact_in_turn: list[bool] = [] + + async def agent(n, texts, rig): + turn["on"] = True + try: + if n == 1: + await rig.call("market_search") # the agent's own: it fires "echo" + for role in others: + await rig.call("market_search", role=role) + rig.message("on it") + else: + rig.quiet() + return "" + finally: + turn["on"] = False + + async def contact(engine, executor, instruction, context_id): + await asyncio.sleep(0.05) # past the end of the agent's turn + contact_in_turn.append(turn["on"]) + await rig.call("market_search", role=executor["role"]) + return "replied" + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "thanks"},)) + rig.tool("market_search") + ctx = rig.context() + await _work_mode(monkeypatch, rig, ctx) + monkeypatch.setattr(TriggerEngine, "_call_executor", contact) + rig.triggers({"id": "echo", "when": {"type": "action", "tool": "market_search"}, + "actions": [{"type": "tool", "tool": "market_search", "args": {}}, + {"type": "nl", "executor": "bob", "instruction": "reply to the agent"}]}, + executors={"bob": {"a2a_url": "http://bob.test", "role": "contact-bob"}}) + for role in others: + await rig.call("market_search", role=role) + assert rig.now() == rig.t0 + + await rig.run(rig.step(settle_timeout_seconds=0.5, max_wakes=2), ctx) + for _ in range(100): + if contact_in_turn: + break + await asyncio.sleep(0.01) + for role in others: + await rig.call("market_search", role=role) + + assert contact_in_turn == [False] + assert rig.now() == "2026-11-09T14:01:00Z" + assert (await _work_state(rig))["by_role"] == {ROLE: {"calls": 1, "virtual_seconds": 60.0}} + first, _ = rig.events(ctx, "agent_turn_end") + assert first["work"] == {"calls": 1, "virtual_seconds": 60.0} + + +@pytest.mark.asyncio +async def test_an_agent_whose_role_work_mode_doesnt_charge_is_refused(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path) + ctx = rig.context() + await _work_mode(monkeypatch, rig, ctx) + rig.gw._trigger_engine.register({"watch_roles": ["assistant"], "triggers": []}) + with pytest.raises(ValueError, match="work mode.*'default'"): + await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1), ctx) + + +@pytest.mark.asyncio +async def test_the_judge_reads_what_each_wakes_work_took(monkeypatch, tmp_path): + async def agent(n, texts, rig): + for _ in range(3): + await rig.call("market_search") + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + rig.tool("market_search") + ctx = rig.context() + await _work_mode(monkeypatch, rig, ctx) + await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1), ctx) + assert "· its work took 3 min of task time" in ao.render_for_judge(rig.record(ctx)) + + +@pytest.mark.asyncio +async def test_each_wake_records_the_agents_output_tokens(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path) + rig.solver_usage = {"tool_call_count": 1, "input_tokens": 900, "output_tokens": 345} + await rig.arm() + ctx = await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1)) + (turn,) = rig.events(ctx, "agent_turn_end") + assert turn["output_tokens"] == 345 + + +@pytest.mark.asyncio +async def test_a_run_without_work_mode_is_as_before(monkeypatch, tmp_path): + async def agent(n, texts, rig): + await rig.call("market_search") + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + rig.tool("market_search") + await rig.arm() + ctx = await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1)) + (turn,) = rig.events(ctx, "agent_turn_end") + assert "work" not in turn and turn["virtual_seconds"] == 0 + record = rig.record(ctx) + assert "work_clock" not in record["counts"] and record["settings"]["clock"] == {"envs": []} + assert "its work took" not in ao.render_for_judge(record) + assert rig.now() == rig.t0 + + +def test_always_on_takes_no_work_setting_of_its_own(monkeypatch, tmp_path): + """Work mode is the clock step's to choose; always_on has no field for it.""" + with pytest.raises(TypeError): + Rig(monkeypatch, tmp_path).step(work_clock={"seconds_per_call": 60}) From 5d61fab239594521fa765a8cbc1cecc6a51abfe2 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Thu, 3 Dec 2026 17:59:46 -0800 Subject: [PATCH 2/9] fix(gateway): work mode charges only the agent's work window and holds for all runnable world work (FD-7183) Review fixes for cf8c06b3. Who is charged: the role guess is gone (TriggerEngine.agent_roles). A call with no AgentEnv-Role header resolved to "default", which the guess charged, so collect_artifacts, a verifier and run_code scripts moved the clock; an agent on its own role with no matching watch_roles was never charged. Now prompt_agent opens a work window (PUT /clock/work/window) naming its agent's role around its conversation, and always_on one around each turn, nudges included; a call is charged only while a window naming its role is open. Late calls of the agent's role outside a window are logged as work_clock_outside_window. Both steps refuse more than one env in work mode. always_on's roles check is removed. The hold: a charged call's answer now waits for all world work runnable now (every trigger fire at work, due deferred calls, and what they set going), not only the triggers that one charge made due; a fire waiting on later task time is excluded. Barrier wait and hold share one budget. Virtual stamps no longer depend on executor latency. Lifecycle: set_time leaves work mode before registering get_time; /clock/work and /clock/work/window are control routes; a post-turn hook's /step call is free only with the control token; get_time/stay_quiet are free only as the gateway's own tools; _change_clock wakes watchers and followers, and a charge is recorded, even when what follows the advance raises. Reporting: work_clock_charge is logged before the hold with tool_call_event_id, and work_clock_hold in a finally (shielded), so a cancelled call leaves a trace. always_on reads each turn's work from its window's close, after freezing, within attempts=2/timeout=10; logs work_mode_off once; the judge line adds the nudge turn's work. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- src/agent_env/env/gateway/constants.py | 14 +- src/agent_env/env/gateway/deferred_calls.py | 14 +- src/agent_env/env/gateway/gateway.py | 231 +++++-- src/agent_env/env/gateway/triggers.py | 32 +- src/agent_env/env/gateway/work_clock.py | 155 ++++- .../task_step/task_steps/always_on.py | 142 ++-- .../task_step/task_steps/clock_mode.py | 117 +++- .../task_step/task_steps/prompt_agent.py | 8 +- .../task_steps/set_env_clock_rate.py | 9 +- .../task_step/task_steps/sync_env_clock.py | 5 +- tst/unit/env/gateway/clock_watch_test.py | 3 +- tst/unit/env/gateway/control_token_test.py | 2 +- .../env/gateway/work_clock_socket_test.py | 49 ++ tst/unit/env/gateway/work_clock_test.py | 624 +++++++++++++++--- tst/unit/task_step/clock_mode_test.py | 226 ++++++- .../task_step/test_always_on_work_clock.py | 182 ++++- 17 files changed, 1454 insertions(+), 361 deletions(-) create mode 100644 tst/unit/env/gateway/work_clock_socket_test.py diff --git a/AGENTS.md b/AGENTS.md index 7ca8af9b3..f64064068 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,7 +191,7 @@ and deserialized through a registry. | Package | Contents | |---|---| -| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its work mode (`/clock/work`, `env/gateway/work_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "work"` on a clock at rate 0 and any later set_time, set_rate or clear turns off, moves the frozen clock on by a fixed `WORK_SECONDS_PER_CALL` (60 s, not configurable) for each answered tool call by the agent, a role whose calls provoke triggers and no executor's (`TriggerEngine.agent_roles`), charged on the MCP path and the step API's `/step` paths (not a post-turn hook's) after the call's barriers (`Clock.advance_by`), then holds the answer until the time triggers that made due have ended or wait on a later task time (`TriggerEngine.settle_due`), each charge a `work_clock_charge` trajectory event; always_on reads it from `/clock/state` and reports each turn's work. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | +| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its work mode (`/clock/work`, `env/gateway/work_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "work"` on a clock at rate 0 and any later set_time, set_rate or clear turns off, ending every open window, moves the frozen clock on by a fixed `WORK_SECONDS_PER_CALL` (60 s, not configurable) for each answered tool call made while a work window naming its role is open (`/clock/work/window`, PUT to open with `roles`, DELETE to close, answering its totals; both control routes): prompt_agent opens one for its agent's role around its conversation and always_on one around each turn, nudges included (`task_steps/clock_mode.py` `agent_work_window`), and both refuse more than one env in work mode, so a setup script, a verifier, collect_artifacts, a user sim, a contact or the agent between its turns is never charged, the agent's role outside its window logged as `work_clock_outside_window`. A charge, on the MCP path and the step API's `/step` paths (not a post-turn hook's that shows the control token; never the gateway's own `get_time` or `stay_quiet`), comes after the call's barriers (`Clock.advance_by`), then the answer is held until all world work runnable now has landed, every trigger fire at work and each deferred call the clock reached (`Gateway._settle_world`), but not a fire waiting on a later task time, the barriers and the hold sharing one budget; each charge is a `work_clock_charge` trajectory event and its hold a `work_clock_hold`, written even when the call is cancelled. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | | `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, the `attempt_epoch` it was written under, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), each naming exactly what it was sent (`input`: a direct call's messages, response format and settings, an agent call's message, every file its step staged in the judge's sandbox and, for a judge the task deployed, what the task's own `load_artifact` steps put there as the run recorded it, stored by sha256 under `judge-inputs/` in the background, `judge_utils/judge_inputs.py`; the step waits for those uploads, at most 120 s, before it writes its grade, `VerifierTaskStep.settle`, and one that failed or hadn't finished is the call's `input_error`, never a failed grade), and its `verifier_settings` hold the trajectory source of each turn it read (`trajectory_sources`); with `judge_samples` (a count, as a step field, a run override or `--judge-samples` on `run`, `task run` and `eval run`), a rubric_binary or rubric_partial judge grades each criterion that many times, each a call of its own under `judge_batch_concurrency` (an agent judge the verifier deploys gets a deployment of its own per sample, its trajectory staged in each; the task's own judge takes every sample), and keeps its median, the lower middle score on a tie, which fails it, the row the first sample that scored it gave with every sample's score, verdict and justification in its `samples` and its `agreement`, the share of samples giving its verdict; a row under `min_judge_agreement` (0.5 by default, which never fails, so the median decides; 1.0 fails any split; set where `judge_samples` is, `--min-judge-agreement`) fails the grade, its rows kept, and then the step (`JudgeDisagreementError`), and `agent-env run` names the criteria a grade that stood split on (`samples split:`), and one failed sample fails the grade (a run's count or agreement a judge of another format can't take is recorded in `not_sent`) and the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`), each computer its own, a multi env's included, never the gateway's: its boot environment holds only the token's sha256 (`AGENTENV_CONTROL_TOKEN_SHA256`) when its probed card's computer/v1 says `control_token = "sha256"`, else, for a driver an older protocol built, the token itself (`AGENTENV_CONTROL_TOKEN`); the gateway learns each computer's (`CHILD_CONTROL_TOKENS`), puts it in place of its own on that computer's `/svc` routes, and lets a computer's token through only to that computer and its clock watch; a multi env's record grants each computer's `/svc` route its own token (`DeployedGatewayEnv.control_grants`, the longest granted address winning), and `CONTROL_TOKEN_CHILDREN`, the computers an older agent-env booted with the gateway's token, is kept for them; framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index 31176df06..bc20e2c37 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -99,10 +99,12 @@ def data_plane_load_timeout_s(size_bytes: int | None) -> int: # The longest a clock write's wait_followers_s may ask it to wait for the followers. CLOCK_MAX_WAIT_FOLLOWERS_S = 30.0 # Work mode (clock/v1 work, work_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 WORK_SECONDS_PER_CALL for each tool call the agent makes. Fixed in agent-env, the same for -# every task and every model. +# moves the frozen clock on by WORK_SECONDS_PER_CALL for each tool call the agent makes inside a work window, which the +# step running the agent opens for the agent's roles. Fixed in agent-env, the same for every task and every model. CLOCK_WORK_MODE = "work" WORK_SECONDS_PER_CALL = 60.0 +CLOCK_WORK_PATH = "/clock/work" +CLOCK_WORK_WINDOW_PATH = "/clock/work/window" # Env/gateway-level extensions the gateway itself owns (tool gating + triggers). EXT_DISABLE_TOOL_URI = "urn:agentenv:disable-tool/v1" @@ -235,7 +237,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_WORK_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// takes the control token for each, and anything under it, on a gateway that has one. @@ -309,7 +311,7 @@ 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; work turns work mode on or off (on needs an armed clock at rate 0; set_time, set_rate and clear turn it off): each answered tool call by the agent, a role whose calls provoke triggers and no executor's, moves the clock on by a fixed " f"{WORK_SECONDS_PER_CALL:g}" " s (get_time and stay_quiet are free), and its answer waits for the time triggers that made due to land; it changes no version, and state's work block shows it, the roles it counts and its totals; 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; work turns work 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 a fixed " f"{WORK_SECONDS_PER_CALL:g}" " s (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 work block shows the mode, 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"]}}, @@ -317,7 +319,9 @@ def random_mcp_server_name() -> str: "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": {}}}, - "work": {"method": "PUT", "endpoint": "/clock/work", "request": {"type": "object", "properties": {"on": {"type": "boolean"}}, "required": ["on"], "additionalProperties": False}}, + "work": {"method": "PUT", "endpoint": CLOCK_WORK_PATH, "request": {"type": "object", "properties": {"on": {"type": "boolean"}}, "required": ["on"], "additionalProperties": False}}, + "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"}}}}}}, diff --git a/src/agent_env/env/gateway/deferred_calls.py b/src/agent_env/env/gateway/deferred_calls.py index 7ad7b4e68..ce42daa94 100644 --- a/src/agent_env/env/gateway/deferred_calls.py +++ b/src/agent_env/env/gateway/deferred_calls.py @@ -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 @@ -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 + work-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.""" @@ -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) @@ -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) diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 494a32c82..928d343e9 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -49,6 +49,8 @@ CHANGES_PAGE_DEFAULT, CLOCK_FOLLOWERS_PATH, CLOCK_WATCH_PATH, + CLOCK_WORK_PATH, + CLOCK_WORK_WINDOW_PATH, CHANGES_PAGE_MAX, CHILD_DISCOVERY_TIMEOUT_S, CONTROL_ROUTES, @@ -113,11 +115,13 @@ upstream_url, website_routes, ) -from .triggers import TriggerEngine, TriggerError +from .triggers import _SETTLE_POLL_S, TriggerEngine, TriggerError from .notifications import CHECK_TOOL_NAMES, NotificationError, Notifications, build_check_tools from .user_chat import MESSAGE_USER_TOOL_NAME, UserChat, UserChatError, build_user_chat_tool from .user_chat import STAY_QUIET_TOOL_NAME, build_stay_quiet_tool -from .work_clock import HOLD_SECONDS, WorkClock, parse_work_body +from .work_clock import ( + HOLD_SECONDS, NoSuchWindow, WindowConflict, WorkClock, WorkModeOff, parse_window_body, parse_work_body, +) logger = logging.getLogger(__name__) @@ -129,6 +133,8 @@ # and httpx's, for each request the gateway forwards. _TOKEN_LOGGERS = ("uvicorn.access", "uvicorn.error", "httpx") _STEP_API = {"source": "step_api"} +# The ASGI scope key the served app sets, on a gateway with a control token, to whether the request showed it. +_CONTROL_SCOPE_KEY = "agentenv.control_token" class SiteCard(NamedTuple): @@ -286,7 +292,7 @@ async def list_website_urls() -> list[str]: ) self._clock = Clock() self._clock_followers = ClockFollowers(lambda: self._clock, clock_followers or {}) - self._work_clock = WorkClock(lambda: self._trigger_engine.agent_roles()) + self._work_clock = WorkClock() self._notifications = Notifications(lambda: self._clock) self._user_chat = UserChat(lambda: self._clock) self._env_get_time_url_cache: str | None = None @@ -405,10 +411,10 @@ 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"), - body.get("time_zone")) - self._register_get_time_tool() - return self._out_of_work_mode(state) + state = self._out_of_work_mode(self._clock.set_time( + body.get("virtual_time"), body.get("virtual_seconds_per_real_second"), body.get("time_zone"))) + self._register_get_time_tool() # after: work mode is off even if this fails + return state return await self._clock_write(request, arm) @@ -431,7 +437,7 @@ def disarm(body: dict) -> dict: return await self._clock_write(request, disarm, body_optional=True) - @self._mcp.custom_route("/clock/work", methods=["PUT"]) + @self._mcp.custom_route(CLOCK_WORK_PATH, methods=["PUT"]) async def clock_work(request: Request) -> Response: # A mode, not a clock change: the clock's version stays, and no follower is waited for. try: @@ -447,9 +453,17 @@ async def clock_work(request: Request) -> Response: "set_rate 0 first") except ClockError as e: return self._json_response({"ok": False, "error": str(e)}, 400) - self._work_clock.on = on + self._work_clock.turn(on) return self._json_response({"ok": True, "work": self._work_clock.state()}, 200) + @self._mcp.custom_route(CLOCK_WORK_WINDOW_PATH, methods=["PUT"]) + async def clock_open_work_window(request: Request) -> Response: + return await self._work_window(request, opening=True) + + @self._mcp.custom_route(CLOCK_WORK_WINDOW_PATH, methods=["DELETE"]) + async def clock_close_work_window(request: Request) -> Response: + return await self._work_window(request, opening=False) + @self._mcp.custom_route(CLOCK_WATCH_PATH, methods=["GET"]) async def clock_watch(request: Request) -> Response: received = time.time() @@ -691,7 +705,7 @@ async def app(scope, receive, send): passed = [(name, self._passed_authorization(scope["path"], value) if name == b"authorization" else value) for name, value in headers] scope = {**scope, "headers": without_session_cookie( - [(name, value) for name, value in passed if value is not None])} + [(name, value) for name, value in passed if value is not None]), _CONTROL_SCOPE_KEY: bearer} if scope["type"] != "http": await inner(scope, receive, send) return @@ -841,9 +855,7 @@ async def filtered_call_tool(name, arguments, context=None, convert_result=False call_real_s = time.monotonic() - started if native: await self._log_native_tool_result(event_id, result) - barrier_tasks, barrier_timeout_s = self._fire_triggers(role, name, arguments, result) - await self._await_barriers(barrier_tasks, barrier_timeout_s) - await self._charge_work(role, name, call_real_s) + await self._after_call(role, name, arguments, result, call_real_s, native=native, event_id=event_id) return result tm.list_tools = filtered_list_tools @@ -878,48 +890,144 @@ async def _await_barriers(self, pending: list[asyncio.Task], timeout_s: float | logger.exception("Awaiting trigger barriers failed (fail-open)") def _out_of_work_mode(self, state: dict) -> dict: - """A set_time, set_rate or clear leaves work mode (work_clock.py): the clock runs as that write set it.""" - self._work_clock.on = False + """A set_time, set_rate or clear leaves work mode (work_clock.py), ending every window: the clock runs as that + write set it.""" + self._work_clock.turn(False) return state - async def _charge_work(self, role: str, name: str, call_real_s: float) -> None: + async def _work_window(self, request: Request, *, opening: bool) -> Response: + """Open (PUT) or close (DELETE) a work window (work_clock.py): 400 for a body it refuses, 409 for an open with + work mode off or an open window's id with other roles, 404 for a close naming no window; else 200 with the + window, what it charged so far, and the work block. Neither changes the clock or its version.""" + try: + body = await request.json() + except Exception: + return self._json_response({"ok": False, "error": "Invalid JSON body"}, 400) + try: + window, roles = parse_window_body(body, opening=opening) + mine = self._work_clock.open(window, roles) if opening else self._work_clock.close(window) + except (WorkModeOff, WindowConflict) as e: + return self._json_response({"ok": False, "error": str(e)}, 409) + except NoSuchWindow as e: + return self._json_response({"ok": False, "error": str(e)}, 404) + except ClockError as e: + return self._json_response({"ok": False, "error": str(e)}, 400) + await self._log_event({"event_type": "work_window", "source": "work_clock", + "action": "open" if opening else "close", **mine}) + return self._json_response({"ok": True, "window": mine, "work": self._work_clock.state()}, 200) + + async def _after_call(self, role: str, name: str, arguments: dict | None, result: Any, call_real_s: float, *, + native: bool, free: bool = False, event_id: str | None = None) -> None: + """What every answered external tool call goes through before its answer goes out (the MCP filter and both + /step handlers): its triggers fed, then its barriers waited for, and in work mode, for a call an open window + charges (work_clock.py), its charge and the hold, the barrier wait and the hold sharing one budget + (HOLD_SECONDS, or a barrier's own longer timeout). ``free`` is a call never charged, a post-turn hook's that + showed the control token. An agent's call outside its windows is logged as ``work_clock_outside_window``.""" + barrier_tasks, barrier_timeout_s = self._fire_triggers(role, name, arguments, result) + seconds = None + try: + if not free: + seconds = self._work_clock.cost(role, name, native) + if seconds is None and self._work_clock.outside(role, name, native): + await self._log_event({"event_type": "work_clock_outside_window", "source": "work_clock", + "tool": name, "role": role, + **({"tool_call_event_id": event_id} if event_id else {})}) + except Exception: + logger.exception(f"Work mode check for '{name}' failed (fail-open)") + seconds = None + if seconds is None: + await self._await_barriers(barrier_tasks, barrier_timeout_s) + return + windows = self._work_clock.windows_of(role) + budget = max(HOLD_SECONDS, barrier_timeout_s or self.TRIGGER_BARRIER_TIMEOUT_S) if barrier_tasks \ + else HOLD_SECONDS + deadline = asyncio.get_running_loop().time() + budget + await self._await_barriers(barrier_tasks, barrier_timeout_s) + await self._charge_work(role, name, seconds, windows, call_real_s, deadline, event_id) + + async def _charge_work(self, role: str, name: str, seconds: float, windows: list[str], call_real_s: float, + deadline: float, event_id: str | None) -> None: """Work mode's charge for an answered tool call (work_clock.py), made once its barriers have settled: the clock - moved on by the call's cost, then the answer held until the time triggers that made due have landed, up to - HOLD_SECONDS. Recorded in the trajectory (``work_clock_charge``: the virtual time before and after, what came - due, how long the answer was held, what was still running, and the call's own real seconds), or as - ``work_clock_skipped`` when the clock can't be moved. Fail-open: a charge that fails never fails the call.""" + moved on by ``seconds``, counted for ``role`` and its ``windows``, then the answer held until the world's work + runnable now has landed, or the loop time ``deadline``. The trajectory records the charge before the hold + (``work_clock_charge``: the virtual time before and after, what came due, the windows, the call's own real + seconds), then the hold however it ends (``work_clock_hold``: how long, what was still at work, whether the + call was cancelled), or ``work_clock_skipped`` when the clock can't be moved. Fail-open: a charge that fails + never fails the call.""" + charge = {"source": "work_clock", "tool": name, "role": role, "seconds": seconds, + **({"tool_call_event_id": event_id} if event_id else {})} try: - seconds = self._work_clock.cost(role, name) - if seconds is None: - return - charge = {"source": "work_clock", "tool": name, "role": role, "seconds": seconds} - before: dict = {} + moved: dict = {} def advance() -> dict: - before["at"] = self._clock.now() - return self._clock.advance_by(seconds) + at = self._clock.now() + state = self._clock.advance_by(seconds) # ClockError, unarmed: nothing moved + moved["at"] = at + return state try: - if not self._clock.armed: - raise ClockError("the clock is not armed") - state, _ = await self._change_clock(advance) + try: + state, _ = await self._change_clock(advance) + finally: + if moved: # the clock moved, so it is counted even if what follows the advance raised + self._work_clock.record(role, seconds, windows) except ClockError as e: await self._log_event({"event_type": "work_clock_skipped", **charge, "reason": str(e)}) return - self._work_clock.record(role, seconds) - due = list(state.get("due") or []) - held_from = time.monotonic() - still_running = await self._trigger_engine.settle_due(due, HOLD_SECONDS) if due else [] - held_s = time.monotonic() - held_from - if still_running: - logger.warning(f"work mode: fire(s) {still_running} still running after {HOLD_SECONDS:g}s; " - "answering the call") - await self._log_event({"event_type": "work_clock_charge", **charge, - "virtual_time_before": _iso(before["at"]), "virtual_time_after": state["virtual_time"], - "due": due, "held_s": round(held_s, 3), "still_running": still_running, - "call_real_s": round(call_real_s, 3)}) + await self._log_event({"event_type": "work_clock_charge", **charge, "windows": windows, + "virtual_time_before": _iso(moved["at"]), "virtual_time_after": state["virtual_time"], + "due": list(state.get("due") or []), "call_real_s": round(call_real_s, 3)}) except Exception: logger.exception(f"Work mode charge for '{name}' failed (fail-open)") + return + await self._hold(charge, deadline) + + async def _hold(self, charge: dict, deadline: float) -> None: + """Hold a charged call's answer on ``_settle_world`` until ``deadline``, and record how it ended, a cancelled + call's included, as ``work_clock_hold``.""" + loop = asyncio.get_running_loop() + started = loop.time() + still: list[str] = [] + cancelled = False + try: + still = await self._settle_world(deadline) + if still: + logger.warning(f"work mode: {still} still at work after the hold's budget; answering the call") + except asyncio.CancelledError: + cancelled = True + raise + except Exception: + logger.exception(f"Work mode hold for '{charge['tool']}' failed (fail-open)") + finally: + event = {"event_type": "work_clock_hold", **charge, "held_s": round(loop.time() - started, 3), + "still_running": still, "cancelled": cancelled} + try: # shielded, so a call cancelled again while it is written still leaves its trace + await asyncio.shield(self._log_event(event)) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Logging a work mode hold failed") + + async def _settle_world(self, deadline: float) -> list[str]: + """Wait, until the loop time ``deadline``, for the world's work runnable now to end, as a settle reads it + (prompt_agent's ``_is_settling``, DeferredCalls.state's ``due``): every trigger fire at work, bar one waiting on + a task time still ahead, and every deferred call the clock has reached; whatever one of them sets going is + waited for in turn. The work clock keeps the clock frozen meanwhile, so no recurrence comes due again. What + was still at work when it gave up: trigger ids, then ``deferred:`` for deferred calls.""" + loop = asyncio.get_running_loop() + while True: + fires = self._trigger_engine.at_work() + calls = self._deferred.due() + left = deadline - loop.time() + if (not fires and not calls) or left <= 0: + return sorted(fires) + [f"deferred:{key}" for key in sorted(calls)] + # One ending wakes this; a fire starting to wait on later time sets nothing to wake on, so it is polled. + tasks = {t for ts in fires.values() for t in ts if not t.done()} | {t for t in calls.values() if not t.done()} + pause = min(left, _SETTLE_POLL_S) + if tasks: + await asyncio.wait(tasks, timeout=pause, return_when=asyncio.FIRST_COMPLETED) + else: + await asyncio.sleep(pause) async def _clock_write(self, request: Request, change, *, body_optional: bool = False) -> Response: """A clock write route: its JSON object body (none at all when ``body_optional``) applied by ``change`` through @@ -951,12 +1059,17 @@ async def _change_clock(self, change, wait_s: float = 0.0) -> tuple[dict, list[s again (clock_advanced does it too). The state ``change`` left, with the triggers it made ``due``, and the followers still behind.""" generation = self._clock.generation - state = change() - if self._clock.generation == generation: - state = {**state, "due": self._trigger_engine.clock_advanced()} - else: - self._trigger_engine.clock_changed() - self._clock_followers.changed() + state = change() # a ClockError here changed nothing + try: + if self._clock.generation == generation: + state = {**state, "due": self._trigger_engine.clock_advanced()} + else: + self._trigger_engine.clock_changed() + except Exception: + self._trigger_engine.clock_changed() # the clock moved: whatever waits on it reads it again regardless + raise + finally: + self._clock_followers.changed() return state, await self._clock_followers.stale_after(state["version"], wait_s) if wait_s else [] async def _env_get_time_url(self) -> str: @@ -1482,7 +1595,9 @@ async def _handle_step(self, request: Request) -> Response: if action == "list_tools": return self._step_list_tools(role) elif action == "call_tool": - return await self._step_call_tool(body, role, source) + # A post-turn hook's call is the harness's, never the agent's work, when it shows the control token. + free = source != _STEP_API and (not self._control_bearer or request.scope.get(_CONTROL_SCOPE_KEY) is True) + return await self._step_call_tool(body, role, source, free=free) else: return self._json_response({"error": f"Unknown action: {action}. Expected 'list_tools' or 'call_tool'."}, 400) @@ -1500,7 +1615,7 @@ def _step_list_tools(self, role: str) -> Response: ] return self._json_response({"tools": tools}, 200) - async def _step_call_tool(self, body: dict, role: str, source: dict = _STEP_API) -> Response: + async def _step_call_tool(self, body: dict, role: str, source: dict = _STEP_API, *, free: bool = False) -> Response: tool_name = body.get("tool_name") if not tool_name or not isinstance(tool_name, str): return self._json_response({"error": "Missing or invalid 'tool_name' field"}, 400) @@ -1516,7 +1631,7 @@ async def _step_call_tool(self, body: dict, role: str, source: dict = _STEP_API) server_url = self._tool_server_urls.get(tool_name) if server_url is None: - return await self._step_call_gateway_tool(tool_name, arguments, role, source) + return await self._step_call_gateway_tool(tool_name, arguments, role, source, free=free) tool_call_event_id = await self._log_event({ "event_type": "tool_call", **source, @@ -1544,10 +1659,8 @@ async def _step_call_tool(self, body: dict, role: str, source: dict = _STEP_API) "changelog_id_before": changelog_before, "changelog_id": changelog_id, }) - barrier_tasks, barrier_timeout_s = self._fire_triggers(role, tool_name, arguments, result) - await self._await_barriers(barrier_tasks, barrier_timeout_s) - if source == _STEP_API: # a post-turn hook's call is the harness's, never the agent's work - await self._charge_work(role, tool_name, call_real_s) + await self._after_call(role, tool_name, arguments, result, call_real_s, native=False, free=free, + event_id=tool_call_event_id) response_data = result.model_dump(mode="json", exclude_none=True) response_data["changelog_id"] = changelog_id return self._json_response(response_data, 200) @@ -1559,7 +1672,7 @@ async def _step_call_tool(self, body: dict, role: str, source: dict = _STEP_API) return self._json_response({"error": f"Tool execution failed ({type(e).__name__}): {error_detail}"}, 500) async def _step_call_gateway_tool(self, tool_name: str, arguments: dict, role: str = DEFAULT_ROLE, - source: dict = _STEP_API) -> Response: + source: dict = _STEP_API, *, free: bool = False) -> Response: """Call a FastMCP-registered tool (e.g. list_website_urls) for /step.""" tool = self._mcp._tool_manager._tools.get(tool_name) if tool is None: @@ -1594,10 +1707,8 @@ async def _step_call_gateway_tool(self, tool_name: str, arguments: dict, role: s "tool_call_result": response_data, "changelog_id": changelog_id, }) - barrier_tasks, barrier_timeout_s = self._fire_triggers(role, tool_name, arguments, result) - await self._await_barriers(barrier_tasks, barrier_timeout_s) - if source == _STEP_API: - await self._charge_work(role, tool_name, call_real_s) + await self._after_call(role, tool_name, arguments, result, call_real_s, native=True, free=free, + event_id=tool_call_event_id) response_data["changelog_id"] = changelog_id return self._json_response(response_data, 200) except Exception as e: diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index b20578abb..348e84d1e 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -63,7 +63,8 @@ _VIRTUAL_RECHECK_S = 5.0 # The clock's resolution: virtual times are microseconds. _VIRTUAL_RESOLUTION_S = 1e-6 -# Real seconds between looks at the fires settle_due waits for, to see one start waiting on a later task time. +# Real seconds between looks at the work a work-mode hold waits for (Gateway._settle_world), to see a fire start +# waiting on a later task time. _SETTLE_POLL_S = 0.02 # Seconds an executor call waits to connect, and for a task poll's answer. _EXECUTOR_HTTP_TIMEOUT_S = 30.0 @@ -1107,11 +1108,6 @@ def _provoked_by(self, trig: dict, role: str) -> bool: def _executor_roles(self) -> set[str]: return {e["role"] for e in self._executors.values()} - def agent_roles(self) -> set[str]: - """The agent's roles: those whose calls provoke triggers (watch_roles, ``default`` before any registration) less - every executor's, as ``_provoked_by`` reads them. Work mode charges calls by these alone (work_clock.py).""" - return (self._watch_roles if self._config_set else {DEFAULT_ROLE}) - self._executor_roles - def _mark_detected(self, tid: str, trig: dict, provoking: dict, ctx: dict | None = None) -> asyncio.Task | None: ctx = ctx if ctx is not None else {} since = self._gw._clock.elapsed() # a delay runs from the provoking call, not from when its turn comes @@ -1194,26 +1190,10 @@ def clock_changed(self) -> None: self._clock_moved.set() self._clock_moved = asyncio.Event() - async def settle_due(self, tids: list[str], timeout_s: float) -> list[str]: - """Wait, up to ``timeout_s`` real seconds, until no fire of the triggers ``tids`` (the ones a clock advance made - due) is at work: each has ended, or waits on a task time still ahead (a delay, its executor's hours), which only - more task time reaches. Work mode holds a call's answer on it, so the agent's next call sees what they - did. The ids still at work when it gave up.""" - loop = asyncio.get_running_loop() - deadline = loop.time() + timeout_s - tids = list(dict.fromkeys(tids)) - while True: - busy = [tid for tid in tids if self._at_work(tid)] - left = deadline - loop.time() - if not busy or left <= 0: - return busy - # A fire ending wakes this; one starting to wait sets nothing to wake on, so it is polled. - tasks = {t for tid in busy for t in self._fire_tasks(self._triggers[tid]) if not t.done()} - pause = min(left, _SETTLE_POLL_S) - if tasks: - await asyncio.wait(tasks, timeout=pause, return_when=asyncio.FIRST_COMPLETED) - else: - await asyncio.sleep(pause) + def at_work(self) -> dict[str, list[asyncio.Task]]: + """Each trigger with a fire at work now (``_at_work``: running, and not only waiting on a task time still + ahead), with its fire tasks: what work mode holds a charged call's answer on (Gateway._settle_world).""" + return {tid: self._fire_tasks(trig) for tid, trig in self._triggers.items() if self._at_work(tid)} def _at_work(self, tid: str) -> bool: """Whether a fire of trigger ``tid`` is at work: more fires running than waiting on a task time ahead.""" diff --git a/src/agent_env/env/gateway/work_clock.py b/src/agent_env/env/gateway/work_clock.py index b114b4997..2eacadf7a 100644 --- a/src/agent_env/env/gateway/work_clock.py +++ b/src/agent_env/env/gateway/work_clock.py @@ -3,32 +3,52 @@ A task whose clock is frozen (rate 0) lives through none of the agent's work otherwise: a turn takes no task time, and a trigger due in the middle of one waits for the next. In work mode the clock stays frozen and the gateway moves it on by ``WORK_SECONDS_PER_CALL`` for each tool call the agent makes, once the call is answered, an error result included. -``get_time`` and ``stay_quiet`` cost nothing. A call refused as disabled, or one that raised, costs nothing, and neither -do model latency, thinking or retries, so every model sees the same world for the same work. - -The agent is the trigger engine's: the roles whose calls provoke triggers (``watch_roles``, ``default`` when none were -registered) less every trigger executor's (``TriggerEngine.agent_roles``). Every other caller, a setup or verifier -step, a user sim, a contact, a trigger's own tool action or a post-turn hook, is never charged. - -The task's clock step turns it on (``sync_env_clock`` or ``set_env_clock_rate`` with ``clock_mode: "work"``), on an -armed clock at rate 0; any later set_time, set_rate or clear turns it off, so a task without clock_mode runs as it always -has. The gateway charges a call with Clock.advance_by, through ``Gateway._change_clock``, then holds its answer until the -time triggers the charge made due have landed, each fire ended or waiting on a later task time, or ``HOLD_SECONDS`` have -passed (``TriggerEngine.settle_due``), so the agent's next call sees the world they changed. +The gateway's own ``get_time`` and ``stay_quiet`` cost nothing. A call refused as disabled, or one that raised, costs +nothing, and neither do model latency, thinking or retries, so every model sees the same world for the same work. + +Who the agent is, the step that runs it says: it opens a work window naming the agent's roles before the agent's turn +and closes it after (prompt_agent around its conversation, always_on around each turn, nudges included), and a call is +charged only while a window naming its role is open. Every other caller, a setup script, a verifier, collect_artifacts, +a user sim, a contact, a trigger's own tool action or a post-turn hook that shows the control token, is never charged, +and neither is the agent's own call outside its window (a late call of a turn cut off), which the trajectory records as +``work_clock_outside_window``. + +The task's clock step turns the mode on (``sync_env_clock`` or ``set_env_clock_rate`` with ``clock_mode: "work"``), on +an armed clock at rate 0; any later set_time, set_rate or clear turns it off, ending every open window, so a task +without clock_mode runs as it always has. The gateway charges a call with Clock.advance_by, through +``Gateway._change_clock``, then holds its answer until the world's work runnable now has landed (``Gateway._settle_world``: +every trigger fire at work, and every deferred call the clock has reached, with what each sets going), so the agent's +next call sees the world they changed. The barrier wait and the hold share one budget per call, ``HOLD_SECONDS`` or a +barrier's own longer timeout. """ from __future__ import annotations -from typing import Callable, Iterable +from collections import OrderedDict +from typing import Any from .clock import ClockError from .constants import WORK_SECONDS_PER_CALL from .get_time import GET_TIME_TOOL_NAME from .user_chat import STAY_QUIET_TOOL_NAME -# How long a charged call's answer may wait for the time triggers its charge made due. +# How long a charged call's answer may wait, its barriers and the hold together. HOLD_SECONDS = 30.0 -# Reading the time, or saying there is nothing to do, is not work. +# Reading the time, or saying there is nothing to do, is not work: the gateway's own tools of these names. FREE_TOOLS = frozenset({GET_TIME_TOOL_NAME, STAY_QUIET_TOOL_NAME}) +# The windows closed lately whose totals a retried close answers again. +CLOSED_KEPT = 64 + + +class WorkModeOff(ClockError): + """A window asked for while work mode is off (409).""" + + +class WindowConflict(ClockError): + """A window opened again with other roles (409).""" + + +class NoSuchWindow(ClockError): + """A close naming a window the gateway never opened, or no longer remembers (404).""" def parse_work_body(body) -> bool: @@ -45,38 +65,117 @@ def parse_work_body(body) -> bool: return body["on"] +def parse_window_body(body, *, opening: bool) -> tuple[str, list[str]]: + """A window request's id, and for an open its roles (each named once, in order): a JSON object holding a non-empty + ``window`` and, to open, a non-empty ``roles`` list of role names, and nothing else. Raises ClockError otherwise.""" + if not isinstance(body, dict): + raise ClockError("body must be a JSON object") + allowed = {"window", "roles"} if opening else {"window"} + unknown = sorted(set(body) - allowed) + if unknown: + raise ClockError(f"unknown window setting(s) {unknown}: takes {sorted(allowed)}") + window = body.get("window") + if not isinstance(window, str) or not window.strip(): + raise ClockError("window must be a non-empty string naming the window") + if not opening: + return window, [] + roles = body.get("roles") + if not isinstance(roles, list) or not roles or not all(isinstance(r, str) and r.strip() for r in roles): + raise ClockError("roles must be a non-empty list of the role names whose calls the window charges") + return window, list(dict.fromkeys(r.strip() for r in roles)) + + class WorkClock: - """The gateway's work mode: whether it is on, who it counts (``agent_roles``, asked at each call, so triggers - registered after it was turned on count), and what it has charged, in all and by role, since the gateway started.""" + """The gateway's work mode: whether it is on, the windows open (each the roles it charges and what it charged), + and what it has charged, in all and by role, since the gateway started.""" - def __init__(self, agent_roles: Callable[[], Iterable[str]]) -> None: - self._agent_roles = agent_roles + def __init__(self) -> None: self.on = False self.calls = 0 self.virtual_seconds = 0.0 self.by_role: dict[str, dict] = {} + self._windows: dict[str, dict] = {} + self._closed: OrderedDict[str, dict] = OrderedDict() + self._seen: set[str] = set() # every role a window named since the mode came on + + def turn(self, on: bool) -> None: + """Turn the mode on or off. Either way every open window ends, its totals kept for its close.""" + for window in list(self._windows): + self._end(window) + self._seen.clear() + self.on = on + + def open(self, window: str, roles: list[str]) -> dict: + """Open ``window`` charging ``roles``; opening it again with the same roles answers it as it stands. Raises + WorkModeOff with the mode off, WindowConflict for an open one with other roles.""" + if not self.on: + raise WorkModeOff("work mode is off: the clock step turns it on (clock_mode 'work'), and set_time, " + "set_rate or clear turn it off") + mine = self._windows.get(window) + if mine is not None: + if mine["roles"] != roles: + raise WindowConflict(f"window {window!r} is open for {mine['roles']}, not {roles}") + return self._view(window, mine) + self._closed.pop(window, None) + self._windows[window] = {"roles": roles, "calls": 0, "virtual_seconds": 0.0} + self._seen.update(roles) + return self._view(window, self._windows[window]) - def roles(self) -> list[str]: - return sorted(self._agent_roles()) + def close(self, window: str) -> dict: + """Close ``window``: what it charged. A window already closed, by a close or by the mode turning off, answers the + same again. Raises NoSuchWindow for one never opened, or closed too long ago to remember.""" + if window in self._windows: + self._end(window) + if window not in self._closed: + raise NoSuchWindow(f"no work window {window!r}") + return dict(self._closed[window]) - def cost(self, role: str, tool: str) -> float | None: - """What an answered call of ``tool`` by ``role`` costs, in task seconds; None when it costs nothing (work mode - off, a role that isn't the agent's, a free tool).""" - if not self.on or tool in FREE_TOOLS or role not in set(self._agent_roles()): + def cost(self, role: str, tool: str, native: bool) -> float | None: + """What an answered call of ``tool`` by ``role`` costs, in task seconds; None when it costs nothing: the mode + off, the gateway's own free tool (``native``), or no open window naming the role.""" + if not self.on or (native and tool in FREE_TOOLS) or not self.windows_of(role): return None return WORK_SECONDS_PER_CALL - def record(self, role: str, seconds: float) -> None: + def windows_of(self, role: str) -> list[str]: + """The open windows that charge ``role``.""" + return [w for w, mine in self._windows.items() if role in mine["roles"]] + + def outside(self, role: str, tool: str, native: bool) -> bool: + """Whether a call costs nothing only for being outside its windows: a role a window named since the mode came + on, its tool not free, and no window naming it open now (a late call of a turn cut off).""" + return self.on and role in self._seen and not (native and tool in FREE_TOOLS) and not self.windows_of(role) + + def record(self, role: str, seconds: float, windows: list[str]) -> None: + """Count a charge, in all, for ``role`` and in each of ``windows``, the ones open when the call was answered: a + window closed since counts it in the totals its close answers.""" self.calls += 1 self.virtual_seconds += seconds mine = self.by_role.setdefault(role, {"calls": 0, "virtual_seconds": 0.0}) mine["calls"] += 1 mine["virtual_seconds"] += seconds + for window in windows: + target = self._windows.get(window, self._closed.get(window)) + if target is not None: + target["calls"] += 1 + target["virtual_seconds"] = round(target["virtual_seconds"] + seconds, 6) def state(self) -> dict: - """Whether it is on, its charge per call, the roles it counts now, then what it has charged (``calls``, + """Whether it is on, its charge per call, the windows open, then what it has charged (``calls``, ``virtual_seconds``), in all and by role.""" - return {"on": self.on, "seconds_per_call": WORK_SECONDS_PER_CALL, "roles": self.roles(), + return {"on": self.on, "seconds_per_call": WORK_SECONDS_PER_CALL, + "windows": [self._view(w, mine) for w, mine in self._windows.items()], "calls": self.calls, "virtual_seconds": round(self.virtual_seconds, 6), "by_role": {role: {"calls": t["calls"], "virtual_seconds": round(t["virtual_seconds"], 6)} for role, t in self.by_role.items()}} + + def _end(self, window: str) -> None: + self._closed[window] = self._view(window, self._windows.pop(window)) + self._closed.move_to_end(window) + while len(self._closed) > CLOSED_KEPT: + self._closed.popitem(last=False) + + @staticmethod + def _view(window: str, mine: dict[str, Any]) -> dict: + return {"window": window, "roles": list(mine["roles"]), "calls": mine["calls"], + "virtual_seconds": round(mine["virtual_seconds"], 6)} diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 570cc8807..2bf9b8a9f 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -36,11 +36,14 @@ agent once. - When the task's clock is in work mode (sync_env_clock or set_env_clock_rate with ``clock_mode: "work"``, FD-7183), task time passes as the agent works: the clock stays frozen and the gateway moves it on by a fixed charge for each - tool call the agent makes, so thinking and model latency cost nothing, and what that makes due lands before the call - is answered. The step only reports it, as the gateway's ``/clock/state`` says: each turn's ``agent_turn_end`` records - what its work took (``work``) beside the agent's ``output_tokens``, the record's ``counts["work_clock"]`` sums it, - ``settings["clock"]["work"]`` names the clocks in work mode, and the judge reads each wake's. The agent's role must be - one the gateway charges (``work.roles``: a role its triggers watch, and no executor's), else the run fails at setup. + tool call the agent makes inside its work window, so thinking and model latency cost nothing, and what that makes due + lands before the call is answered. The step opens the window, naming the agent's role, around each of the agent's + turns, nudges included, and closes it when the turn ends, so a user sim, a contact, a setup script or a verifier is + never charged, nor the agent between its turns. Each turn's ``agent_turn_end`` (and ``nudge``) records what its work + took (``work``, the window's totals) beside the agent's ``output_tokens``, the record's ``counts["work_clock"]`` sums + it, ``settings["clock"]["work"]`` names the clock in work mode, and the judge reads each wake's, its nudge's included. + Work mode ended mid-run (a hook's set_rate, say) is logged once (``work_mode_off``) and no window is opened after. + More than one clock in work mode is refused at setup: their task times would drift apart. - The agent can schedule its own wake-ups (scheduled checks) when the run is multi-day, at least ``scheduled_check_min_interval`` apart; ``scheduled_checks`` turns them on or off whatever the run's length. A check's wake counts toward ``max_wakes``. @@ -143,6 +146,7 @@ from typing import Any, ClassVar, Optional from zoneinfo import ZoneInfo +import httpx from a2a.types import TaskState from agentenv_protocol.atif import FORMAT as ATIF_FORMAT @@ -560,8 +564,9 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): self.folded: Optional[dict] = None self.clock: dict = {} # the task's clock rate, and whether the step freezes it between turns self.clock_rates: list[tuple[Any, float]] = [] # (env, the task's rate) for each clock the step freezes - self.work_envs: list = [] # the clocks in work mode, each charging the agent's tool calls - self.work_seen: Optional[dict] = None # what they had charged the agent when last read: calls, task seconds + self.work_env: Any = None # the clock in work mode, charging the agent's calls in its turns' windows + self.work_off = False # work mode ended there mid-run (logged once): no window is opened after + self.turn_window: Optional[str] = None # the work window of the turn in progress, while it is open self.turn_work: Optional[dict] = None # what the last turn's work cost: calls charged, task seconds self.work_total = {"calls": 0, "virtual_seconds": 0.0} self.undo: list[tuple[str, Any]] = [] # (what, coroutine function): the gateway settings to put back at the end @@ -823,7 +828,8 @@ async def _configure_clock(self) -> None: which keeps the clock's marks (a re-arm with set_time, as sync_env_clock arms it, would re-anchor every relative or recurring time trigger); the task's rate is put back at the end. A clock already frozen (rate 0) is left alone; a gateway without set_rate keeps running between turns, as the record says. A clock in work mode - (frozen, its gateway charging the agent's tool calls) is reported on (``_configure_work``).""" + (frozen, its gateway charging the agent's tool calls in its window) is the one each turn's window opens on + (``_configure_work``); more than one is refused, before any clock is touched.""" envs, work = [], [] for env in await self._armed(): state = await _call(env, EXT_CLOCK_URI, "state") @@ -838,13 +844,17 @@ async def _configure_clock(self) -> None: continue self.clock_rates.append((env, rate)) envs.append({"env_id": env.env_id, "rate": rate, "frozen_between_turns": True}) + if len(work) > 1: + self.clock_rates = [] + raise ValueError(f"always_on: work mode is on at more than one env's clock " + f"({', '.join(env.env_id for env, _ in work)}), each charged the agent's tool calls: their " + "task times would drift apart and no total would match either; put one clock in work mode") if self.clock_rates: self.undo.append(("the clock's rate", lambda: self._clock_runs(True))) await self._clock_runs(False) self.clock = {"envs": envs} if work: - self._configure_work(work) - self.work_seen = await self._work_totals() + self._configure_work(*work[0]) async def _clock_runs(self, running: bool) -> None: """Run each clock the step freezes at the task's rate (``running``), or freeze it.""" @@ -852,51 +862,65 @@ async def _clock_runs(self, running: bool) -> None: await _call(env, EXT_CLOCK_URI, "set_rate", {"virtual_seconds_per_real_second": rate if running else 0}, attempts=3) - def _configure_work(self, work: list[tuple[Any, dict]]) -> None: - """Report on the clocks in work mode (each ``(env, its state's work block)``): the agent's tool calls move them on, - charged by the gateway (clock/v1 work, FD-7183), so each turn records what its work took. Refuses a run whose - agent's role a clock in work mode doesn't charge, which would take no task time for its work.""" - uncounted = [env.env_id for env, block in work if self.recipient not in (block.get("roles") or [])] - if uncounted: - raise ValueError(f"always_on: the clock of {', '.join(uncounted)} is in work mode, which charges the tool " - f"calls of the roles its triggers watch, and the agent's role {self.recipient!r} is not " - "one: register its triggers with watch_roles naming it") - self.work_envs = [env for env, _ in work] - self.clock["work"] = {"seconds_per_call": work[0][1].get("seconds_per_call"), - "envs": [env.env_id for env in self.work_envs]} - - async def _work_totals(self) -> dict: - """What the clocks in work mode have charged the agent's role so far, summed: calls, task seconds.""" - total = {"calls": 0, "virtual_seconds": 0.0} - for env in self.work_envs: - mine = (((await _call(env, EXT_CLOCK_URI, "state")).get("work") or {}).get("by_role") or {}).get( - self.recipient) or {} - total["calls"] += mine.get("calls", 0) - total["virtual_seconds"] += mine.get("virtual_seconds", 0.0) - return total - - async def _work_done(self) -> None: - """What the agent's work took since it was last read, the turn just ended's: in ``turn_work`` and the run's - ``work_total``. A late call of an earlier turn cut off counts here. A failed read is logged, not raised.""" - if self.work_seen is None: + def _configure_work(self, env, block: dict) -> None: + """The clock in work mode (``env``, its state's work block): the gateway charges the agent's tool calls while a + window naming its role is open (clock/v1 work, FD-7183), so each turn opens one and records what it charged.""" + self.work_env = env + self.clock["work"] = {"seconds_per_call": block.get("seconds_per_call"), "envs": [env.env_id]} + + async def _open_window(self) -> None: + """Open the turn's work window, naming the agent's role, on the clock in work mode: ``turn_window``. Work mode + ended there since (409) is logged once, and the turn's work takes no task time; another failure is raised.""" + if self.work_env is None or self.work_off: + return + window = f"{self.step.id}:wake-{self.wakes}:{uuid.uuid4().hex[:8]}" + try: + await _call(self.work_env, EXT_CLOCK_URI, "open_work_window", {"window": window, "roles": [self.recipient]}, + answers=(409,)) + except httpx.HTTPStatusError as e: + if e.response.status_code != 409: + raise + self._work_mode_off() + return + self.turn_window = window + + async def _close_window(self) -> None: + """Close the turn's work window: what it charged, in ``turn_work`` and the run's ``work_total``. Within a short + budget, so a struggling gateway can't stall the turn's cleanup; a failed close is logged, not raised. Work mode + found ended is logged once (``_work_mode_off``).""" + window, self.turn_window = self.turn_window, None + if window is None: return try: - now = await self._work_totals() + answer = await _call(self.work_env, EXT_CLOCK_URI, "close_work_window", {"window": window}, attempts=2, + timeout=10) or {} except Exception as e: - logger.warning(f"always_on: reading what the agent's work took failed: {e}") + logger.warning(f"always_on: wake {self.wakes}: closing the agent's work window failed, so what its work " + f"took is not known: {type(e).__name__}: {e}") return - work = {"calls": now["calls"] - self.work_seen["calls"], - "virtual_seconds": round(now["virtual_seconds"] - self.work_seen["virtual_seconds"], 3)} - self.work_seen = now + mine = answer.get("window") or {} + work = {"calls": mine.get("calls", 0), "virtual_seconds": round(mine.get("virtual_seconds", 0.0), 3)} self.turn_work = work self.work_total = {"calls": self.work_total["calls"] + work["calls"], "virtual_seconds": round(self.work_total["virtual_seconds"] + work["virtual_seconds"], 3)} + if not (answer.get("work") or {}).get("on", True): + self._work_mode_off() + + def _work_mode_off(self) -> None: + """Work mode ended on the clock mid-run (a hook's set_rate, say): logged once, so the turns after report no + work rather than none done.""" + if not self.work_off: + self.work_off = True + self.log("work_mode_off", env_id=self.work_env.env_id, wake=self.wakes) + logger.warning(f"always_on: wake {self.wakes}: the clock of {self.work_env.env_id} left work mode; the " + "agent's work takes no task time from here") async def _agent_turn(self, parts: list[dict], msg_id: str, record) -> AgentTurn: """One turn of the agent on ``parts``: the task's clock runs at its rate while the agent works, and is frozen - again after; a clock in work mode stays frozen, moved on by the agent's tool calls, and what they took is read - after. The turn's usage is recorded as its reply arrives, before the clock is frozen. The agent's task id for - the turn is ``turn_task_id`` once it accepts the message.""" + again after; a clock in work mode stays frozen, moved on by the agent's tool calls inside the turn's work + window, closed once the clock is frozen, and what they took is read from it. The turn's usage is recorded as its + reply arrives, before the clock is frozen. The agent's task id for the turn is ``turn_task_id`` once it accepts + the message.""" step = self.step self.turn_task_id = None self.turn_work = None @@ -906,6 +930,7 @@ def accepted(task_id: str) -> None: await self._clock_runs(True) try: + await self._open_window() # Cut off past its limit and grace, whatever send_and_wait's own retries do: a TimeoutError, as its own. turn = await asyncio.wait_for( send_and_wait(self.target_url, parts, agent=self.agent, message_id=msg_id, @@ -921,9 +946,9 @@ def accepted(task_id: str) -> None: return turn finally: try: - await self._work_done() - finally: await self._clock_runs(False) + finally: + await self._close_window() async def _stopped_at_time_limit(self, error: TimeoutError) -> Optional[dict]: """A turn that ran out of time, with continue_after_wake_limit on: its A2A task as the agent confirms it ended @@ -2211,7 +2236,7 @@ async def finish(self) -> None: and e.get("stay_quiet_calls")) if step.continue_after_wake_limit: counts["cut_off_wakes"] = len(self.cut_offs) - if self.work_envs: + if self.work_env is not None: counts["work_clock"] = dict(self.work_total) # the agent's tool calls charged, and the task time they took record = {"step_id": step.id, "end_reason": self.end_reason, "end_note": self.end_note, "reached_scheduled_end": self.end_reason in SCHEDULED_ENDS, "error": self.error, @@ -2341,8 +2366,9 @@ def render_for_judge(record: dict) -> str: turn = turns.get(n) or {} sent = (turn.get("messages_to_user") or 0) + (nudges.get(n, {}).get("messages_to_user") or 0) calls = f" · {turn['tool_calls']} tool calls" if turn.get("tool_calls") is not None else "" - if (turn.get("work") or {}).get("virtual_seconds"): - calls += f" · its work took {_task_time_text(turn['work']['virtual_seconds'])} of task time" + work = sum(((e.get("work") or {}).get("virtual_seconds") or 0) for e in (turn, nudges.get(n) or {})) + if work: # the nudge turn's work too, as with the messages sent + calls += f" · its work took {_task_time_text(work)} of task time" state = f" · its turn {turn['state']}" if turn.get("state") not in (None, "completed", "TaskState.completed") \ else "" cut = turn.get("cut_off") or nudges.get(n, {}).get("cut_off") @@ -2401,16 +2427,24 @@ def _actor(change: dict) -> str: async def _call(env, uri: str, method: str, params: Optional[dict] = None, *, attempts: int = 6, - timeout: int = 60) -> Any: - """A gateway control call, retried on a transient failure (a busy gateway can take seconds to answer). - Every call the step retries is safe to repeat: reads, config, advance (checked against the clock after) and takes - with a take_id.""" + timeout: int = 60, answers: tuple[int, ...] = ()) -> Any: + """A gateway control call, retried on a transient failure (a busy gateway can take seconds to answer); an HTTP + status in ``answers`` is the gateway's answer, raised at once. Every call the step retries is safe to repeat: + reads, config, advance (checked against the clock after), takes with a take_id, and work windows.""" last: Optional[Exception] = None for attempt in range(attempts): try: return await env.invoke(uri, method, params, timeout=timeout) except EnvCapabilityUnsupported: raise + except httpx.HTTPStatusError as e: + if e.response.status_code in answers: + raise + last = e + if attempt + 1 < attempts: + logger.warning(f"always_on: {method} on {getattr(env, 'env_id', env)} failed (HTTP " + f"{e.response.status_code}); retry {attempt + 1}/{attempts - 1}") + await asyncio.sleep(min(2 ** attempt, CALL_RETRY_MAX_SLEEP_SECONDS)) except Exception as e: last = e if attempt + 1 < attempts: diff --git a/src/agent_env/task_step/task_steps/clock_mode.py b/src/agent_env/task_step/task_steps/clock_mode.py index 8264bbea9..18527cdd1 100644 --- a/src/agent_env/task_step/task_steps/clock_mode.py +++ b/src/agent_env/task_step/task_steps/clock_mode.py @@ -1,21 +1,37 @@ -"""The clock setup steps' ``clock_mode`` (sync_env_clock, set_env_clock_rate), FD-7183. +"""The clock setup steps' ``clock_mode`` (sync_env_clock, set_env_clock_rate), and the work window the steps that run +the agent open in it, FD-7183. Unset, the default, the clock runs at the step's rate, as it always has. ``"work"`` is work mode: the clock is frozen -(rate 0) and the gateway moves it on by a fixed charge for each tool call the agent makes (clock/v1 ``work``, -``agent_env.env.gateway.work_clock``), so the agent's work takes task time and thinking or model latency take none. A -rate other than 0 with it is an error. A later set_time or set_rate without it (sync_env_clock, or set_env_clock_rate to -0 after the agent's last prompt_agent) leaves work mode. +(rate 0) and the gateway moves it on by a fixed charge for each tool call the agent makes inside a work window (clock/v1 +``work``, ``agent_env.env.gateway.work_clock``), so the agent's work takes task time and thinking or model latency take +none. A rate other than 0 with it is an error. A later set_time or set_rate without it (sync_env_clock, or +set_env_clock_rate to 0 after the agent's last prompt_agent) leaves work mode. + +The clock step only turns the mode on; who the agent is, the step that runs it says. prompt_agent opens a window for +its agent's role around its conversation (``agent_work_window``) and always_on one around each of the agent's turns, so +a setup script, a verifier, collect_artifacts or a user sim calling the same gateway before, between or after is never +charged. Which env is in work mode the run's ``clock_configurations`` say (``work_mode_envs``), so a task that never +names the mode makes no window call at all. One env in work mode at most: two clocks charged for the same calls would +drift apart, and their totals would match neither. """ from __future__ import annotations -from typing import Any, Optional +import logging +import uuid +from contextlib import asynccontextmanager +from typing import Any, AsyncIterator, Optional import httpx from agent_env.env.gateway.constants import CLOCK_WORK_MODE, EXT_CLOCK_URI, WORK_SECONDS_PER_CALL from agent_env.task_step.context import StepContextError +logger = logging.getLogger(__name__) + CLOCK_MODES = (CLOCK_WORK_MODE,) +WORK_METHODS = ("work", "open_work_window", "close_work_window") +WORK_WINDOWS_KEY = "work_windows" # context.metadata: each window a step opened, with what it charged +_WINDOW_TIMEOUT_S = 30 _MAX_ERROR_CHARS = 300 @@ -35,11 +51,13 @@ def clock_mode_rate(step_type: str, clock_mode: Any, rate: Any, default: Optiona def require_work(deployed, env_id: str) -> None: - """Refuse, before the clock is touched, work mode on a gateway whose stored card offers no clock/v1 work. A - record that kept no card is left to the clock call, which says so.""" - if deployed.environment_card and not deployed.supports(EXT_CLOCK_URI, "work"): - raise StepContextError(f"env '{env_id}': clock_mode 'work' needs its gateway's {EXT_CLOCK_URI} work, which its " - "card does not offer; put the gateway env again (agent-env env gateway put) and redeploy") + """Refuse, before the clock is touched, work mode on a gateway whose stored card offers no clock/v1 work or work + windows. A record that kept no card is left to the clock call, which says so.""" + missing = [m for m in WORK_METHODS if not deployed.supports(EXT_CLOCK_URI, m)] if deployed.environment_card else [] + if missing: + raise StepContextError(f"env '{env_id}': clock_mode 'work' needs its gateway's {EXT_CLOCK_URI} " + f"{', '.join(missing)}, which its card does not offer; put the gateway env again " + "(agent-env env gateway put) and redeploy") async def start_work(deployed, env_id: str, timeout: int) -> dict: @@ -50,3 +68,80 @@ async def start_work(deployed, env_id: str, timeout: int) -> dict: raise RuntimeError(f"env '{env_id}': turning work mode on failed (HTTP {e.response.status_code}): " f"{e.response.text[:_MAX_ERROR_CHARS]}") from e return (answer or {}).get("work") or {} + + +def work_mode_envs(context) -> list: + """The deployed envs whose clock the run left in work mode: those whose latest clock step, by env and deployment, + put it there (``clock_mode: "work"``). A clock step's record that names no deployment counts for every deployment + of its env.""" + configurations = context.metadata.get("clock_configurations") or [] + envs = [] + for deployed in context.deployed_envs: + step = (deployed.metadata or {}).get("deploy_step_id") + latest = None + for c in configurations: + if c.get("env_id") == deployed.env_id and c.get("deploy_step_id") in (None, step): + latest = c + if latest is not None and latest.get("clock_mode") == CLOCK_WORK_MODE: + envs.append(deployed) + return envs + + +def one_work_mode_env(context, step: str) -> Optional[Any]: + """The deployed env in work mode, or None; StepContextError for more than one.""" + envs = work_mode_envs(context) + if len(envs) > 1: + raise StepContextError(f"{step}: work mode is on at more than one env's clock " + f"({', '.join(e.env_id for e in envs)}), each charged the agent's tool calls: their task " + "times would drift apart and no total would match either; put one clock in work mode") + return envs[0] if envs else None + + +@asynccontextmanager +async def agent_work_window(context, step_id: str, roles: list[str]) -> AsyncIterator[Optional[str]]: + """A work window naming ``roles`` held open on the env in work mode, if there is one, around the agent's work: + yields the window's id, or None with no env in work mode, or with work mode already ended there (logged). Closed + however the work ends; what it charged is recorded under ``context.metadata["work_windows"]``. A close that fails + is logged, not raised, so it never replaces the agent's own error. Refuses more than one env in work mode.""" + env = one_work_mode_env(context, step_id) + if env is None: + yield None + return + window = f"{step_id}:{uuid.uuid4().hex[:12]}" + try: + await _window_call(env, "open_work_window", {"window": window, "roles": list(roles)}) + except httpx.HTTPStatusError as e: + if e.response.status_code != 409: + raise RuntimeError(f"env '{env.env_id}': opening the agent's work window failed (HTTP " + f"{e.response.status_code}): {e.response.text[:_MAX_ERROR_CHARS]}") from e + logger.warning(f"{step_id}: env '{env.env_id}' refused the agent's work window " + f"({e.response.text[:_MAX_ERROR_CHARS]}); the agent's work takes no task time") + yield None + return + try: + yield window + finally: + try: + answer = await _window_call(env, "close_work_window", {"window": window}) + except Exception as e: + logger.warning(f"{step_id}: closing the agent's work window {window!r} on env '{env.env_id}' failed: " + f"{type(e).__name__}: {str(e)[:_MAX_ERROR_CHARS]}") + else: + mine = (answer or {}).get("window") or {} + context.metadata.setdefault(WORK_WINDOWS_KEY, []).append({ + "step_id": step_id, "env_id": env.env_id, "window": window, "roles": list(roles), + "calls": mine.get("calls", 0), "virtual_seconds": mine.get("virtual_seconds", 0.0)}) + if not ((answer or {}).get("work") or {}).get("on", True): + logger.warning(f"{step_id}: env '{env.env_id}' left work mode during the agent's work; the window " + "counts what it charged until then") + + +async def _window_call(env, method: str, params: dict) -> Any: + """A window call, made once more after a failure that isn't the gateway's answer: both are safe to repeat.""" + try: + return await env.invoke(EXT_CLOCK_URI, method, params, timeout=_WINDOW_TIMEOUT_S) + except httpx.HTTPStatusError: + raise + except Exception as e: + logger.warning(f"{method} on env '{env.env_id}' failed ({type(e).__name__}: {e}); trying once more") + return await env.invoke(EXT_CLOCK_URI, method, params, timeout=_WINDOW_TIMEOUT_S) diff --git a/src/agent_env/task_step/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py index 677d4985f..dbebd728c 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -51,6 +51,7 @@ from agent_env.entity.refs import EntityRef from agent_env.entity.scopes import FieldScope from agent_env.task_step.task_step import RetryConfig, StepRole, TaskStep, TaskStepDependency +from agent_env.task_step.task_steps.clock_mode import agent_work_window, one_work_mode_env from agent_env.task_step.task_steps.notification_delivery import delivered_parts, labels_zone, next_message, take_due from agent_env.task_step.task_steps.post_turn_hooks import PostTurnHooks, run_post_turn_hooks, validate_hook_specs from agent_env.task_step.task_steps.server_fault_logs import capture_server_fault_logs @@ -514,6 +515,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: async def _execute(self, context: TaskStepContext) -> TaskStepContext: # Refused here (always_on has its own), so a bad setting leaves no conversation, capture or model call. self._built_in_user_sim(context) + one_work_mode_env(context, f"prompt_agent '{self.id}'") # Minted here, not in `_execute_conversation`, so the series can address the # same session before the first turn. a2a_context_id = self.context_id or uuid.uuid4().hex @@ -549,8 +551,12 @@ async def _execute_conversation( series: Optional[SnapshotSeries] = None, ) -> TaskStepContext: hooks = await PostTurnHooks.load(self.post_turn_hooks, self.id) if self.post_turn_hooks else None + agent = next((a for a in context.deployed_agents if a.agent_name == self.agent_name), None) + # In work mode, the agent's calls are charged only while its window is open: none before or after (clock_mode). + window = agent_work_window(context, self.id, [agent.role or DEFAULT_ROLE]) if agent else nullcontext() try: - return await self._converse(context, a2a_context_id=a2a_context_id, series=series, hooks=hooks) + async with window: + return await self._converse(context, a2a_context_id=a2a_context_id, series=series, hooks=hooks) finally: if hooks is not None: hooks.close() diff --git a/src/agent_env/task_step/task_steps/set_env_clock_rate.py b/src/agent_env/task_step/task_steps/set_env_clock_rate.py index be41990e1..f58093e9b 100644 --- a/src/agent_env/task_step/task_steps/set_env_clock_rate.py +++ b/src/agent_env/task_step/task_steps/set_env_clock_rate.py @@ -7,8 +7,9 @@ With clock_mode "work" (``clock_mode.py``) as the step that starts the clock before prompt_agent, the rate is 0, its default in that mode (any other is an error), and the gateway's work mode is turned on, so each tool call the agent -makes moves task time on by a fixed charge. Without it, the rate set leaves work mode, so a rate of 0 after the agent's -last prompt_agent stops the clock for verifiers in either mode. +makes inside its work window (prompt_agent's, always_on's) moves task time on by a fixed charge. Without it, the rate +set leaves work mode, ending any window open, so a rate of 0 after the agent's last prompt_agent stops the clock for +verifiers in either mode. """ from __future__ import annotations @@ -23,7 +24,7 @@ from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.task_step.task_step import TaskStep, TaskStepDependency from agent_env.task_step.task_steps.clock_mode import clock_mode_rate, require_work, start_work -from agent_env.task_step.task_steps.deploy_agent import bound_deployment +from agent_env.task_step.task_steps.deploy_agent import _deploy_step_of, bound_deployment logger = logging.getLogger(__name__) @@ -103,6 +104,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: "virtual_seconds_per_real_second": self.virtual_seconds_per_real_second, "virtual_time": state.get("virtual_time"), } + if self.clock_mode is not None or self.env_step_id: # the deployment it names, for work_mode_envs + configuration["deploy_step_id"] = _deploy_step_of(deployed) if self.clock_mode is not None: configuration.update(clock_mode=self.clock_mode, work=await start_work(deployed, self.env_id, self.timeout_seconds)) diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index be05b8f70..1be15b3ac 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -14,7 +14,8 @@ before prompt_agent so the virtual timeline starts at agent-start; when setup needs the clock armed, arm it at rate 0 and start it with set_env_clock_rate right before prompt_agent. With clock_mode "work" (``clock_mode.py``), the clock is armed frozen and the gateway's work mode turned on, so each -tool call the agent makes moves task time on by a fixed charge; a nonzero rate with it is an error. +tool call the agent makes inside its work window (prompt_agent's, always_on's) moves task time on by a fixed charge; a +nonzero rate with it is an error. """ from __future__ import annotations @@ -95,7 +96,7 @@ def __init__( clock_mode = unset, the default, for a clock that runs at its rate, as it always has; "work" for work mode: the clock frozen (rate 0, the rate's default in it; any other rate is an error) and moved on by a fixed charge for - each tool call the agent makes (``clock_mode.py``). + each tool call the agent makes inside the work window the step running it opens (``clock_mode.py``). timezone = optional IANA name. Unset keeps today's behaviour. Set, a wall-clock virtual_time is local time in that zone, the gateway's clock is armed in it, so its get_time answers in it too, and every synced server is diff --git a/tst/unit/env/gateway/clock_watch_test.py b/tst/unit/env/gateway/clock_watch_test.py index 3e9fd0ddc..1602aaa2c 100644 --- a/tst/unit/env/gateway/clock_watch_test.py +++ b/tst/unit/env/gateway/clock_watch_test.py @@ -80,7 +80,8 @@ def test_the_card_offers_every_clock_method_with_the_waits_bound_and_the_watchs_ assert {name: (m["method"], m["endpoint"]) for name, m in methods.items()} == { "get_time": ("GET", "/clock/time"), "set_time": ("PUT", "/clock/set-time"), "set_rate": ("PUT", "/clock/set-rate"), "advance": ("PUT", "/clock/advance"), "clear": ("POST", "/clock/clear"), "state": ("GET", "/clock/state"), - "work": ("PUT", "/clock/work"), "declare_follower": ("PUT", "/clock/followers"), "retire_follower": ("DELETE", "/clock/followers"), + "work": ("PUT", "/clock/work"), "open_work_window": ("PUT", "/clock/work/window"), + "close_work_window": ("DELETE", "/clock/work/window"), "declare_follower": ("PUT", "/clock/followers"), "retire_follower": ("DELETE", "/clock/followers"), "watch": ("GET", "/clock/watch")} assert all(methods[name]["request"]["properties"]["wait_followers_s"] == wait for name in ("set_time", "set_rate", "advance", "clear")) diff --git a/tst/unit/env/gateway/control_token_test.py b/tst/unit/env/gateway/control_token_test.py index fea8efb38..fcfe69e5d 100644 --- a/tst/unit/env/gateway/control_token_test.py +++ b/tst/unit/env/gateway/control_token_test.py @@ -24,7 +24,7 @@ "/tools/disable": "POST", "/tools/enable": "POST", "/triggers/register": "POST", "/triggers/remove": "POST", "/triggers/clear": "POST", "/notifications/config": "POST", "/notifications/take": "POST", "/notifications/clear": "POST", - "/clock/followers": "PUT", + "/clock/followers": "PUT", "/clock/work": "PUT", "/clock/work/window": "PUT", } OPEN = {"/state": "GET", "/step": "POST", "/clock/time": "GET", "/clock/state": "GET", "/triggers/state": "GET", "/notifications/state": "GET", "/trajectory": "GET", "/changes": "GET", "/.well-known/agent-env.json": "GET", diff --git a/tst/unit/env/gateway/work_clock_socket_test.py b/tst/unit/env/gateway/work_clock_socket_test.py new file mode 100644 index 000000000..62c915c3f --- /dev/null +++ b/tst/unit/env/gateway/work_clock_socket_test.py @@ -0,0 +1,49 @@ +"""Work mode (FD-7183) over real loopback sockets: an agent's MCP client that sends its AgentEnv-Role header over +streamable HTTP is the role its work window names, so its calls are charged, and another role's are not.""" +from __future__ import annotations + +import httpx +import pytest +from pytest_socket import enable_socket + +from agent_env.env.gateway import gateway as gw_mod +from agent_env.env.gateway.gateway import Gateway +from tst.unit.env.gateway.deferred_calls_socket_test import _client, _serve + +T0 = "2026-11-08T17:00:00Z" + + +@pytest.fixture(autouse=True) +def _disable_network(): + """Override the suite-wide socket block (tst/unit/conftest.py) for this module: loopback is the point here.""" + enable_socket() + yield + + +@pytest.mark.asyncio +@pytest.mark.timeout(60) +async def test_the_role_an_mcp_client_sends_is_the_one_charged(tmp_path, monkeypatch): + monkeypatch.setattr(gw_mod, "GATEWAY_TRAJECTORY_FILE", str(tmp_path / "trajectory.jsonl")) + gw = Gateway(host="127.0.0.1", port=0, server_name="t", internal_mcp_servers=[]) + + def app_lookup() -> str: + """Look something up.""" + return "found" + gw._mcp.add_tool(app_lookup, name="app_lookup") + server, url = await _serve(gw._asgi_app()) + try: + async with httpx.AsyncClient(base_url=url) as http: + r = await http.put("/clock/set-time", json={"virtual_time": T0, "virtual_seconds_per_real_second": 0}) + assert r.status_code == 200, r.text + assert (await http.put("/clock/work", json={"on": True})).status_code == 200 + r = await http.put("/clock/work/window", json={"window": "turn-1", "roles": ["solver"]}) + assert r.status_code == 200, r.text + + async with _client(url, "solver") as solver, _client(url, "verifier") as verifier: + assert not (await solver.call_tool("app_lookup", {})).isError + assert not (await verifier.call_tool("app_lookup", {})).isError + state = (await http.get("/clock/state")).json() + assert state["virtual_time"] == "2026-11-08T17:01:00Z" + assert state["work"]["by_role"] == {"solver": {"calls": 1, "virtual_seconds": 60.0}} + finally: + await server.shutdown() diff --git a/tst/unit/env/gateway/work_clock_test.py b/tst/unit/env/gateway/work_clock_test.py index 23c9773ea..e1fe7c82a 100644 --- a/tst/unit/env/gateway/work_clock_test.py +++ b/tst/unit/env/gateway/work_clock_test.py @@ -1,11 +1,12 @@ -"""Work mode (FD-7183): a frozen clock moved on by a fixed charge for each answered tool call the agent makes, counted by -the gateway, so the world lives through the agent's work. Clock.advance_by, the /clock/work switch, the charge on every -agent call path and on no one else's, and the hold until the time triggers a charge made due have landed.""" +"""Work mode (FD-7183): a frozen clock moved on by a fixed charge for each answered tool call the agent makes, so the +world lives through the agent's work. Clock.advance_by, the /clock/work switch, the work windows the agent-running +steps open for the agent's roles, the charge on every call path inside a window and on no one else's, and the hold +until the world's work runnable now has landed.""" from __future__ import annotations import asyncio import json -import threading +import time import httpx import pytest @@ -14,13 +15,16 @@ from agent_env.env.gateway import gateway as gw_mod from agent_env.env.gateway.caller import Caller from agent_env.env.gateway.clock import Clock, ClockError -from agent_env.env.gateway.constants import AGENT_ENV_ROLE_HEADER, EXT_CLOCK_URI, GATEWAY_EXTENSIONS +from agent_env.env.gateway.constants import ( + AGENT_ENV_DEFERRED_CALLS_META_KEY, AGENT_ENV_ROLE_HEADER, CONTROL_ROUTES, EXT_CLOCK_URI, GATEWAY_EXTENSIONS, +) from agent_env.env.gateway.gateway import Gateway from agent_env.env.gateway.triggers import TriggerEngine from tst.unit.env.gateway.triggers_time_test import FakeNow T0 = "2026-11-08T17:00:00Z" GW = "http://gateway.test" +CONTROL_TOKEN = "work-clock-test-token" # ---- Clock.advance_by ----------------------------------------------------------------------------------------------- @@ -53,16 +57,6 @@ def test_advance_by_adds_to_a_running_clock(): assert clock.read()["virtual_time"] == "2026-11-08T18:11:00Z" -def test_advance_by_is_atomic_so_parallel_charges_sum(): - clock, _ = _armed() - threads = [threading.Thread(target=lambda: [clock.advance_by(1) for _ in range(50)]) for _ in range(8)] - for t in threads: - t.start() - for t in threads: - t.join() - assert clock.read()["virtual_time"] == "2026-11-08T17:06:40Z" # 400 s - - @pytest.mark.parametrize("bad", [-1, -0.001, float("nan"), float("inf"), True, False, "60", None, [60]]) def test_advance_by_refuses_anything_but_a_finite_non_negative_number(bad): clock, _ = _armed() @@ -83,10 +77,9 @@ def test_advance_by_refuses_an_unarmed_clock_and_an_overflow(): # ---- the gateway ---------------------------------------------------------------------------------------------------- -@pytest.fixture -def gw(tmp_path, monkeypatch): +def _gateway(tmp_path, monkeypatch, **kw) -> Gateway: monkeypatch.setattr(gw_mod, "GATEWAY_TRAJECTORY_FILE", str(tmp_path / "trajectory.jsonl")) - gateway = Gateway(host="127.0.0.1", port=0, server_name="AgentEnvGateway", internal_mcp_servers=[]) + gateway = Gateway(host="127.0.0.1", port=0, server_name="AgentEnvGateway", internal_mcp_servers=[], **kw) gateway._tools_discovered = True def app_lookup() -> str: @@ -103,12 +96,28 @@ def app_crashes() -> str: for fn in (app_lookup, app_refuses, app_crashes): gateway._mcp.add_tool(fn, name=fn.__name__) + return gateway + + +@pytest.fixture +def gw(tmp_path, monkeypatch): + gateway = _gateway(tmp_path, monkeypatch) + yield gateway + gateway._close_trajectory_file() + + +@pytest.fixture +def guarded(tmp_path, monkeypatch): + """A gateway deployed with a control token, served through its own ASGI app (the token check included).""" + gateway = _gateway(tmp_path, monkeypatch, control_token=CONTROL_TOKEN) yield gateway gateway._close_trajectory_file() -def _client(gateway: Gateway) -> httpx.AsyncClient: - return httpx.AsyncClient(transport=httpx.ASGITransport(app=gateway._mcp.streamable_http_app()), base_url=GW) +def _client(gateway: Gateway, *, guarded: bool = False, token: bool = False) -> httpx.AsyncClient: + app = gateway._asgi_app() if guarded else gateway._mcp.streamable_http_app() + headers = {"authorization": f"Bearer {CONTROL_TOKEN}"} if token else {} + return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url=GW, headers=headers) async def _arm(client: httpx.AsyncClient) -> None: @@ -120,9 +129,35 @@ async def _work(client: httpx.AsyncClient, on: bool = True) -> httpx.Response: return await client.put("/clock/work", json={"on": on}) -async def _call(client: httpx.AsyncClient, tool: str, role: str = "default", **body) -> httpx.Response: +async def _open(client: httpx.AsyncClient, roles=("default",), window: str = "turn-1") -> httpx.Response: + return await client.put("/clock/work/window", json={"window": window, "roles": list(roles)}) + + +async def _close(client: httpx.AsyncClient, window: str = "turn-1") -> httpx.Response: + return await client.request("DELETE", "/clock/work/window", json={"window": window}) + + +async def _working(client: httpx.AsyncClient, roles=("default",)) -> None: + """Armed frozen, work mode on and a window open for ``roles``: the agent's turn, as the steps set it up.""" + await _arm(client) + assert (await _work(client)).status_code == 200 + r = await _open(client, roles) + assert r.status_code == 200, r.text + + +async def _call(client: httpx.AsyncClient, tool: str, role: str | None = "default", **body) -> httpx.Response: + """A /step call_tool as ``role``, or with no AgentEnv-Role header at all for None.""" return await client.post("/step", json={"action": "call_tool", "tool_name": tool, "arguments": {}, **body}, - headers={AGENT_ENV_ROLE_HEADER: role}) + headers={AGENT_ENV_ROLE_HEADER: role} if role is not None else {}) + + +async def _mcp(gateway: Gateway, tool: str, role: str = "default", arguments: dict | None = None): + """A tools/call through the gateway's MCP filter as ``role``.""" + token = Caller(role=role).bind() + try: + return await gateway._mcp._tool_manager.call_tool(tool, arguments or {}) + finally: + Caller.reset(token) async def _now(client: httpx.AsyncClient) -> str: @@ -143,7 +178,7 @@ def _logged(gateway: Gateway, event_type: str) -> list[dict]: async def test_state_shows_work_mode_off_until_turned_on(gw): async with _client(gw) as client: await _arm(client) - assert await _work_state(client) == {"on": False, "seconds_per_call": 60.0, "roles": ["default"], + assert await _work_state(client) == {"on": False, "seconds_per_call": 60.0, "windows": [], "calls": 0, "virtual_seconds": 0.0, "by_role": {}} r = await _work(client) assert r.status_code == 200, r.text @@ -180,6 +215,8 @@ async def test_turning_it_on_needs_an_armed_frozen_clock_and_keeps_the_clocks_ve await _arm(client) version = (await client.get("/clock/state")).json()["version"] assert (await _work(client)).status_code == 200 + assert (await _open(client)).status_code == 200 + assert (await _close(client)).status_code == 200 assert (await client.get("/clock/state")).json()["version"] == version @@ -192,10 +229,13 @@ async def test_set_time_set_rate_and_clear_leave_work_mode_and_advance_doesnt(gw lambda: client.post("/clock/clear")): await _arm(client) assert (await _work(client)).status_code == 200 + assert (await _open(client)).status_code == 200 assert (await client.put("/clock/advance", json={"virtual_time": "2026-11-08T18:00:00Z"})).status_code == 200 assert (await _work_state(client))["on"] is True assert (await leave()).status_code == 200 - assert (await _work_state(client))["on"] is False + work = await _work_state(client) + assert work["on"] is False and work["windows"] == [] + assert (await _close(client)).status_code == 200 # the turn's own close still gets its totals # A write the clock refuses changes nothing, work mode included. await _arm(client) await _work(client) @@ -203,19 +243,139 @@ async def test_set_time_set_rate_and_clear_leave_work_mode_and_advance_doesnt(gw assert (await _work_state(client))["on"] is True -def test_the_card_offers_work(): +@pytest.mark.asyncio +async def test_a_set_time_that_fails_after_arming_still_leaves_work_mode(gw, monkeypatch): + """set_time arms the clock, then registers get_time: work mode is off before the second step can fail.""" + async with _client(gw) as client: + await _working(client) + + def fails(): + raise ValueError("registering get_time failed") + monkeypatch.setattr(gw, "_register_get_time_tool", fails) + with pytest.raises(ValueError): + await client.put("/clock/set-time", json={"virtual_time": T0, "virtual_seconds_per_real_second": 1}) + assert gw._clock.rate == 1 + assert (await _work_state(client))["on"] is False + + +def test_the_card_offers_work_and_its_windows(): clock_ext = next(e for e in GATEWAY_EXTENSIONS if e["uri"] == EXT_CLOCK_URI) - work = clock_ext["params"]["methods"]["work"] + methods = clock_ext["params"]["methods"] + work = methods["work"] assert (work["method"], work["endpoint"]) == ("PUT", "/clock/work") assert set(work["request"]["properties"]) == {"on"} and work["request"]["required"] == ["on"] - assert "work" in clock_ext["description"] and "60 s" in clock_ext["description"] + opened, closed = methods["open_work_window"], methods["close_work_window"] + assert (opened["method"], opened["endpoint"]) == ("PUT", "/clock/work/window") + assert set(opened["request"]["required"]) == {"window", "roles"} + assert (closed["method"], closed["endpoint"]) == ("DELETE", "/clock/work/window") + assert closed["request"]["required"] == ["window"] + assert "work" in clock_ext["description"] and "window" in clock_ext["description"] + + +def test_the_work_routes_are_control_routes(): + assert {"/clock/work", "/clock/work/window"} <= CONTROL_ROUTES + + +@pytest.mark.asyncio +async def test_the_work_routes_take_the_control_token(guarded): + async with _client(guarded, guarded=True) as anyone, _client(guarded, guarded=True, token=True) as harness: + await _arm(harness) + assert (await _work(anyone)).status_code == 401 + assert (await _work(harness)).status_code == 200 + assert (await _open(anyone)).status_code == 401 + assert (await _open(harness)).status_code == 200 + assert (await _close(anyone)).status_code == 401 + assert (await _close(harness)).status_code == 200 + + +# ---- work windows --------------------------------------------------------------------------------------------------- + +@pytest.mark.asyncio +@pytest.mark.parametrize("body", [ + [], {}, {"window": "w"}, {"roles": ["a"]}, {"window": "", "roles": ["a"]}, {"window": 3, "roles": ["a"]}, + {"window": "w", "roles": []}, {"window": "w", "roles": "a"}, {"window": "w", "roles": [""]}, + {"window": "w", "roles": [" "]}, {"window": "w", "roles": [1]}, {"window": "w", "roles": ["a"], "extra": 1}, +]) +async def test_opening_a_window_needs_an_id_and_some_roles(gw, body): + async with _client(gw) as client: + await _arm(client) + await _work(client) + r = await client.put("/clock/work/window", content=json.dumps(body)) + assert r.status_code == 400, r.text + assert (await _work_state(client))["windows"] == [] + assert _logged(gw, "work_window") == [] @pytest.mark.asyncio -async def test_each_answered_call_by_the_agent_moves_the_clock_a_minute(gw): +async def test_a_window_opens_only_in_work_mode_and_again_only_with_the_same_roles(gw): async with _client(gw) as client: await _arm(client) + r = await _open(client, ["solver"]) + assert r.status_code == 409 and "work mode" in r.json()["error"] await _work(client) + r = await _open(client, ["solver", "solver"]) + assert r.status_code == 200, r.text + assert r.json()["window"] == {"window": "turn-1", "roles": ["solver"], "calls": 0, "virtual_seconds": 0.0} + assert (await _open(client, ["solver"])).status_code == 200 # a retried open + assert (await _open(client, ["planner"])).status_code == 409 + assert (await _work_state(client))["windows"] == [ + {"window": "turn-1", "roles": ["solver"], "calls": 0, "virtual_seconds": 0.0}] + + +@pytest.mark.asyncio +async def test_closing_a_window_answers_what_it_charged_and_a_retry_answers_the_same(gw): + async with _client(gw) as client: + await _working(client, ["solver"]) + await _call(client, "app_lookup", "solver") + await _call(client, "app_lookup", "solver") + r = await _close(client) + assert r.status_code == 200, r.text + assert r.json()["window"] == {"window": "turn-1", "roles": ["solver"], "calls": 2, "virtual_seconds": 120.0} + assert r.json()["work"]["windows"] == [] + again = await _close(client) + assert again.status_code == 200 and again.json()["window"] == r.json()["window"] + assert (await _close(client, "no-such-window")).status_code == 404 + assert (await client.request("DELETE", "/clock/work/window", json={})).status_code == 400 + # Closed, the agent's calls are charged no more. + await _call(client, "app_lookup", "solver") + assert await _now(client) == "2026-11-08T17:02:00Z" + opened, closed, retried = _logged(gw, "work_window") + assert (opened["action"], opened["window"], opened["roles"]) == ("open", "turn-1", ["solver"]) + assert (closed["action"], closed["calls"], closed["virtual_seconds"]) == ("close", 2, 120.0) + assert (retried["action"], retried["calls"]) == ("close", 2) + + +@pytest.mark.asyncio +async def test_a_window_work_mode_ended_still_answers_its_close(gw): + async with _client(gw) as client: + await _working(client) + await _call(client, "app_lookup") + await client.put("/clock/set-rate", json={"virtual_seconds_per_real_second": 0}) # a hook, say + r = await _close(client) + assert r.status_code == 200 + assert (r.json()["window"]["calls"], r.json()["work"]["on"]) == (1, False) + + +@pytest.mark.asyncio +async def test_two_windows_each_count_their_own_roles(gw): + async with _client(gw) as client: + await _working(client, ["solver"]) + assert (await _open(client, ["solver", "planner"], window="turn-2")).status_code == 200 + await _call(client, "app_lookup", "solver") + await _call(client, "app_lookup", "planner") + assert await _now(client) == "2026-11-08T17:02:00Z" # each call charged once, whatever windows name it + work = await _work_state(client) + assert [(w["window"], w["calls"]) for w in work["windows"]] == [("turn-1", 1), ("turn-2", 2)] + assert work["by_role"] == {"solver": {"calls": 1, "virtual_seconds": 60.0}, + "planner": {"calls": 1, "virtual_seconds": 60.0}} + + +# ---- who is charged ------------------------------------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_each_answered_call_in_a_window_moves_the_clock_a_minute(gw): + async with _client(gw) as client: + await _working(client) assert (await _call(client, "app_lookup")).status_code == 200 assert await _now(client) == "2026-11-08T17:01:00Z" r = await _call(client, "app_refuses") # an error result is an answered call @@ -225,62 +385,57 @@ async def test_each_answered_call_by_the_agent_moves_the_clock_a_minute(gw): assert (work["calls"], work["virtual_seconds"], work["by_role"]) == ( 2, 120.0, {"default": {"calls": 2, "virtual_seconds": 120.0}}) first, second = _logged(gw, "work_clock_charge") + calls = {e["event_id"]: e for e in _logged(gw, "tool_call")} assert {k: first[k] for k in ("tool", "role", "seconds", "virtual_time_before", "virtual_time_after", "due", - "still_running")} == { + "windows")} == { "tool": "app_lookup", "role": "default", "seconds": 60.0, "virtual_time_before": T0, - "virtual_time_after": "2026-11-08T17:01:00Z", "due": [], "still_running": []} - assert first["held_s"] >= 0 and first["call_real_s"] >= 0 + "virtual_time_after": "2026-11-08T17:01:00Z", "due": [], "windows": ["turn-1"]} + assert first["call_real_s"] >= 0 + assert calls[first["tool_call_event_id"]]["tool_call"]["function_name"] == "app_lookup" assert (second["tool"], second["seconds"]) == ("app_refuses", 60.0) + holds = _logged(gw, "work_clock_hold") + assert [(h["tool_call_event_id"], h["still_running"], h["cancelled"]) for h in holds] == [ + (first["tool_call_event_id"], [], False), (second["tool_call_event_id"], [], False)] + assert all(h["held_s"] >= 0 for h in holds) @pytest.mark.asyncio -async def test_a_call_to_a_backing_server_is_charged(gw, monkeypatch): - gw._tool_server_urls["svc_send"] = "http://svc:8000/mcp" - - async def child(url, tool, arguments, **kw): - return CallToolResult(content=[TextContent(type="text", text="sent")]) - monkeypatch.setattr(gw, "_call_child_tool", child) +async def test_an_agent_on_its_own_role_with_no_triggers_is_charged(gw): + """The agent deployed with its own AgentEnv-Role (deploy_agent's ``role``, the CLI's ``cli``), no triggers.""" async with _client(gw) as client: - await _arm(client) - await _work(client) - assert (await _call(client, "svc_send")).status_code == 200 - assert await _now(client) == "2026-11-08T17:01:00Z" - assert [e["tool"] for e in _logged(gw, "work_clock_charge")] == ["svc_send"] - - -@pytest.mark.asyncio -async def test_a_call_over_mcp_is_charged(gw): - async with _client(gw) as client: - await _arm(client) - await _work(client) - token = Caller(role="default").bind() - try: - await gw._mcp._tool_manager.call_tool("app_lookup", {}) - finally: - Caller.reset(token) - assert await _now(client) == "2026-11-08T17:01:00Z" + await _working(client, ["solver"]) + assert (await _call(client, "app_lookup", "solver")).status_code == 200 + await _mcp(gw, "app_lookup", "solver") + assert await _now(client) == "2026-11-08T17:02:00Z" @pytest.mark.asyncio -async def test_what_the_agent_does_that_is_not_charged(gw): - """A call that raised, a disabled tool, and get_time, the agent's own calls all.""" +@pytest.mark.parametrize("when", ["before the agent starts", "after the agent finished"]) +async def test_a_header_less_call_outside_the_agents_window_is_free_and_fires_nothing_due(gw, monkeypatch, when): + """A /step call_tool with no AgentEnv-Role header, as collect_artifacts and a run_code setup script make it, and an + env_outcome_verifier's read: the default role, but no window is open.""" + replies = _executor(monkeypatch, 0) async with _client(gw) as client: await _arm(client) + _reply_at(gw) # due a minute in: a charge would set it going await _work(client) - assert (await _call(client, "app_crashes")).status_code == 500 - gw._apply_rule("default", "app_lookup", True) - assert (await _call(client, "app_lookup")).status_code == 403 - assert (await _call(client, "get_time")).status_code == 200 + if when == "after the agent finished": + await _open(client) + await _close(client) + for _ in range(3): + assert (await _call(client, "app_lookup", role=None)).status_code == 200 + await _mcp(gw, "app_lookup") assert await _now(client) == T0 - assert _logged(gw, "work_clock_charge") == [] + assert replies == [] and _trigger(gw)["status"] == "armed" + assert (await _work_state(client))["calls"] == 0 + assert _logged(gw, "work_clock_charge") == [] @pytest.mark.asyncio @pytest.mark.parametrize("path", ["mcp", "step"]) -async def test_no_one_but_the_agent_is_charged(gw, monkeypatch, path): - """The agent is whose calls provoke triggers (watch_roles) and no executor's. A setup step's, a verifier's, a user - sim's or a contact's calls, a trigger's own tool action and a post-turn hook's call, even one made as the agent, - move nothing: only the agent's own call does.""" +async def test_no_one_but_the_windows_roles_is_charged(gw, path): + """A setup step's, a verifier's, a user sim's or a contact's calls, a trigger's own tool action and a post-turn + hook's call, even one made as the agent, move nothing: only the agent's own call does.""" gw._trigger_engine.register({ "watch_roles": ["assistant"], "executors": {"bob": {"a2a_url": "http://bob", "role": "contact-bob"}}, "triggers": [{"id": "mirror", "when": {"type": "action", "tool": "app_lookup", "repeat": True}, @@ -290,19 +445,13 @@ async def test_no_one_but_the_agent_is_charged(gw, monkeypatch, path): async def call(tool: str, role: str) -> None: if path == "step": assert (await _call(client, tool, role)).status_code == 200 - return - token = Caller(role=role).bind() - try: - await gw._mcp._tool_manager.call_tool(tool, {}) - finally: - Caller.reset(token) + else: + await _mcp(gw, tool, role) async with _client(gw) as client: - await _arm(client) - await _work(client) - assert (await _work_state(client))["roles"] == ["assistant"] + await _working(client, ["assistant"]) for role in ("default", "setup", "verifier", "user-sim", "contact-bob"): - await call("app_lookup", role) # watched only for the agent: a non-agent's call fires nothing either + await call("app_lookup", role) r = await _call(client, "app_lookup", "assistant", source="post_turn_hook", hook_artifact_id="next-event") assert r.status_code == 200 assert await _now(client) == T0 and _logged(gw, "work_clock_charge") == [] @@ -310,58 +459,175 @@ async def call(tool: str, role: str) -> None: await call("app_lookup", "assistant") # the agent's call, whose trigger's own tool action is free assert await _now(client) == "2026-11-08T17:01:00Z" mirror = next(t for t in gw._trigger_engine.state()["triggers"] if t["id"] == "mirror") - # Fired by the hook's call, made as the agent, and the agent's own, never by another role's; its action ran. - assert mirror["fire_count"] == 2 + assert mirror["fire_count"] == 2 # the hook's call made as the agent provokes it too; its action ran assert [(e["tool"], e["role"]) for e in _logged(gw, "work_clock_charge")] == [("app_lookup", "assistant")] @pytest.mark.asyncio -async def test_the_agents_roles_are_read_at_each_call(gw): - """Triggers registered after work mode was turned on decide who the agent is from then on.""" +async def test_an_agents_call_outside_its_window_is_free_and_logged(gw): + """A late call of a turn cut off: its window closed, so it moves nothing, and the trajectory says so.""" async with _client(gw) as client: - await _arm(client) - await _work(client) - await _call(client, "app_lookup", "assistant") + await _working(client, ["solver"]) + await _close(client) + await _call(client, "app_lookup", "solver") + await _call(client, "get_time", "solver") # free anyway: not logged + await _call(client, "app_lookup", "verifier") # never a window's role: not logged assert await _now(client) == T0 - gw._trigger_engine.register({"watch_roles": ["assistant"], "triggers": []}) - await _call(client, "app_lookup", "assistant") - await _call(client, "app_lookup", "default") + (outside,) = _logged(gw, "work_clock_outside_window") + assert (outside["tool"], outside["role"]) == ("app_lookup", "solver") and outside["tool_call_event_id"] + + +@pytest.mark.asyncio +async def test_a_call_to_a_backing_server_is_charged(gw, monkeypatch): + gw._tool_server_urls["svc_send"] = "http://svc:8000/mcp" + + async def child(url, tool, arguments, **kw): + return CallToolResult(content=[TextContent(type="text", text="sent")]) + monkeypatch.setattr(gw, "_call_child_tool", child) + async with _client(gw) as client: + await _working(client) + assert (await _call(client, "svc_send")).status_code == 200 + assert await _now(client) == "2026-11-08T17:01:00Z" + assert [e["tool"] for e in _logged(gw, "work_clock_charge")] == ["svc_send"] + + +@pytest.mark.asyncio +async def test_a_call_over_mcp_is_charged(gw): + async with _client(gw) as client: + await _working(client) + await _mcp(gw, "app_lookup") assert await _now(client) == "2026-11-08T17:01:00Z" +@pytest.mark.asyncio +async def test_what_the_agent_does_that_is_not_charged(gw, monkeypatch): + """A call that raised (on /step and over MCP, native and backing), a disabled tool, and get_time.""" + gw._tool_server_urls["svc_send"] = "http://svc:8000/mcp" + + async def child(url, tool, arguments, **kw): + raise RuntimeError("backing server down") + monkeypatch.setattr(gw, "_call_child_tool", child) + async with _client(gw) as client: + await _working(client) + assert (await _call(client, "app_crashes")).status_code == 500 + assert (await _call(client, "svc_send")).status_code == 500 + with pytest.raises(Exception): + await _mcp(gw, "app_crashes") + gw._apply_rule("default", "app_lookup", True) + assert (await _call(client, "app_lookup")).status_code == 403 + assert (await _call(client, "get_time")).status_code == 200 + assert await _now(client) == T0 + assert (await _work_state(client))["calls"] == 0 + assert _logged(gw, "work_clock_charge") == [] + + +@pytest.mark.asyncio +async def test_stay_quiet_is_free_and_message_user_is_charged(gw): + async with _client(gw) as client: + r = await client.post("/user_chat/config", json={"roles": ["solver"], "stay_quiet": True}) + assert r.status_code == 200, r.text + await _working(client, ["solver"]) + assert (await _call(client, "stay_quiet", "solver")).status_code == 200 + assert await _now(client) == T0 + r = await _call(client, "message_user", "solver", arguments={"text": "booked"}) + assert r.status_code == 200 and not r.json().get("isError"), r.text + assert await _now(client) == "2026-11-08T17:01:00Z" + + +@pytest.mark.asyncio +async def test_a_backing_servers_tool_named_like_a_free_one_is_charged(gw, monkeypatch): + """Free means the gateway's own get_time and stay_quiet; a backing server's tool of that name is work.""" + gw._tool_server_urls["stay_quiet"] = "http://svc:8000/mcp" + + async def child(url, tool, arguments, **kw): + return CallToolResult(content=[TextContent(type="text", text="ok")]) + monkeypatch.setattr(gw, "_call_child_tool", child) + async with _client(gw) as client: + await _working(client) + assert (await _call(client, "stay_quiet")).status_code == 200 + assert await _now(client) == "2026-11-08T17:01:00Z" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("backing", [False, True]) +async def test_a_post_turn_hooks_call_is_free_only_with_the_control_token(guarded, monkeypatch, backing): + tool = "app_lookup" + if backing: + tool = "svc_lookup" + guarded._tool_server_urls[tool] = "http://svc:8000/mcp" + + async def child(url, name, arguments, **kw): + return CallToolResult(content=[TextContent(type="text", text="found")]) + monkeypatch.setattr(guarded, "_call_child_tool", child) + hook = {"source": "post_turn_hook", "hook_artifact_id": "next-event"} + async with _client(guarded, guarded=True) as anyone, _client(guarded, guarded=True, token=True) as harness: + await _working(harness, ["solver"]) + assert (await _call(harness, tool, "solver", **hook)).status_code == 200 + assert await _now(harness) == T0 + assert (await _call(anyone, tool, "solver", **hook)).status_code == 200 # a claim without the token + assert await _now(harness) == "2026-11-08T17:01:00Z" + (charge,) = _logged(guarded, "work_clock_charge") + assert (charge["tool"], charge["role"]) == (tool, "solver") + + @pytest.mark.asyncio async def test_parallel_calls_each_pay(gw): async with _client(gw) as client: - await _arm(client) - await _work(client) + await _working(client) rs = await asyncio.gather(*(_call(client, "app_lookup") for _ in range(5))) assert {r.status_code for r in rs} == {200} assert await _now(client) == "2026-11-08T17:05:00Z" @pytest.mark.asyncio -async def test_a_charge_on_a_clock_disarmed_under_it_is_skipped_and_says_so(gw): +async def test_a_charge_on_a_clock_disarmed_under_it_is_skipped_and_records_nothing(gw): async with _client(gw) as client: - await _arm(client) - await _work(client) + await _working(client) gw._clock.clear() # disarmed without the route, which would also have left work mode assert (await _call(client, "app_lookup")).status_code == 200 + work = gw._work_clock.state() + assert (work["calls"], work["virtual_seconds"], work["by_role"]) == (0, 0.0, {}) + assert work["windows"][0]["calls"] == 0 (skipped,) = _logged(gw, "work_clock_skipped") assert (skipped["tool"], skipped["role"], skipped["seconds"]) == ("app_lookup", "default", 60.0) assert "armed" in skipped["reason"] assert _logged(gw, "work_clock_charge") == [] -# ---- what the charge made due --------------------------------------------------------------------------------------- +@pytest.mark.asyncio +async def test_a_charge_whose_trigger_check_fails_is_still_recorded_and_wakes_the_clocks_watchers(gw, monkeypatch): + """The clock moved, so what follows from that happens even if re-evaluating the triggers raises.""" + woken, followers = [], [] + + def fails(): + raise RuntimeError("trigger evaluation failed") + monkeypatch.setattr(gw._trigger_engine, "clock_advanced", fails) + real_changed = gw._trigger_engine.clock_changed + monkeypatch.setattr(gw._trigger_engine, "clock_changed", lambda: (woken.append(1), real_changed())[1]) + real_followers = gw._clock_followers.changed + monkeypatch.setattr(gw._clock_followers, "changed", lambda: (followers.append(1), real_followers())[1]) + async with _client(gw) as client: + await _working(client) + woken.clear() + followers.clear() + assert (await _call(client, "app_lookup")).status_code == 200 # fail-open + assert await _now(client) == "2026-11-08T17:01:00Z" + work = await _work_state(client) + assert (work["calls"], work["windows"][0]["calls"]) == (1, 1) + assert woken and followers + + +# ---- the hold: what the charge, or anything else, set going --------------------------------------------------------- -def _reply_at(gw: Gateway, at: str = "PT1M", **action) -> None: +def _reply_at(gw: Gateway, at: str = "PT1M", watch: str = "default", **action) -> None: gw._trigger_engine.register({ - "watch_roles": ["default"], "executors": {"bob": {"a2a_url": "http://bob", "role": "bob"}}, + "watch_roles": [watch], "executors": {"bob": {"a2a_url": "http://bob", "role": "bob"}}, "triggers": [{"id": "sellout", "when": {"type": "time", "at": at}, "actions": [{"type": "nl", "executor": "bob", "instruction": "reply", **action}]}]}) def _executor(monkeypatch, seconds: float) -> list: + """bob's replies, each stamped with the task time it was written at, after ``seconds`` real seconds.""" calls = [] async def call(engine, ex, instruction, context_id): @@ -372,8 +638,8 @@ async def call(engine, ex, instruction, context_id): return calls -def _trigger(gw: Gateway) -> dict: - return next(t for t in gw._trigger_engine.state()["triggers"] if t["id"] == "sellout") +def _trigger(gw: Gateway, tid: str = "sellout") -> dict: + return next(t for t in gw._trigger_engine.state()["triggers"] if t["id"] == tid) @pytest.mark.asyncio @@ -383,12 +649,112 @@ async def test_a_trigger_the_charge_made_due_lands_before_the_call_is_answered(g await _arm(client) _reply_at(gw) await _work(client) + await _open(client) assert (await _call(client, "app_lookup")).status_code == 200 assert replies == ["2026-11-08T17:01:00Z"] assert (_trigger(gw)["status"], _trigger(gw)["fire_count"]) == ("fired", 1) (charge,) = _logged(gw, "work_clock_charge") - assert (charge["due"], charge["still_running"]) == (["sellout"], []) - assert charge["held_s"] >= 0.25 + (hold,) = _logged(gw, "work_clock_hold") + assert charge["due"] == ["sellout"] and hold["still_running"] == [] + assert hold["held_s"] >= 0.25 + + +@pytest.mark.asyncio +async def test_the_charge_comes_after_the_calls_barriers_settle(gw, monkeypatch): + """A barrier fire the call provoked lands at the call's own task time; the charge moves the clock after it.""" + replies = _executor(monkeypatch, 0.2) + gw._trigger_engine.register({ + "watch_roles": ["default"], "executors": {"bob": {"a2a_url": "http://bob", "role": "bob"}}, + "triggers": [{"id": "ack", "when": {"type": "action", "tool": "app_lookup"}, + "barrier": {"at": "provoking_call"}, + "actions": [{"type": "nl", "executor": "bob", "instruction": "ack"}]}]}) + async with _client(gw) as client: + await _working(client) + assert (await _call(client, "app_lookup")).status_code == 200 + assert replies == [T0] + assert await _now(client) == "2026-11-08T17:01:00Z" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("latency_s", [0.05, 0.6]) +async def test_what_the_agents_call_sets_going_lands_at_a_task_time_its_latency_doesnt_change(gw, monkeypatch, + latency_s): + """bob's reply to the agent's call (no barrier) is written before the call is answered, so the agent's later + calls can't move the clock under it, however long bob takes.""" + replies = _executor(monkeypatch, latency_s) + gw._trigger_engine.register({ + "watch_roles": ["default"], "executors": {"bob": {"a2a_url": "http://bob", "role": "bob"}}, + "triggers": [{"id": "bob-replies", "when": {"type": "action", "tool": "app_lookup"}, + "actions": [{"type": "nl", "executor": "bob", "instruction": "reply"}]}]}) + async with _client(gw) as client: + await _working(client) + await _call(client, "app_lookup") + for _ in range(5): + await asyncio.sleep(0.1) + await _call(client, "app_refuses") + assert replies == ["2026-11-08T17:01:00Z"] + assert await _now(client) == "2026-11-08T17:06:00Z" + + +@pytest.mark.asyncio +async def test_parallel_calls_are_both_held_for_a_fire_either_set_going(gw, monkeypatch): + landed: list[float] = [] + + async def executor(engine, ex, instruction, context_id): + await asyncio.sleep(0.4) + landed.append(time.monotonic()) + return "replied" + monkeypatch.setattr(TriggerEngine, "_call_executor", executor) + answered: list[float] = [] + + async def call(): + assert (await _call(client, "app_lookup")).status_code == 200 + answered.append(time.monotonic()) + + async with _client(gw) as client: + await _arm(client) + _reply_at(gw) + await _work(client) + await _open(client) + await asyncio.gather(call(), call()) + assert await _now(client) == "2026-11-08T17:02:00Z" + assert len(landed) == 1 and len(answered) == 2 + assert min(answered) >= landed[0] + + +@pytest.mark.asyncio +async def test_a_deferred_call_the_charge_made_due_is_held_for_with_what_it_sets_going(gw, monkeypatch): + gw._tool_server_urls["svc_schedule"] = "http://svc:8000/mcp" + gw._tool_server_urls["svc_post"] = "http://svc:8000/mcp" + posted: list[str] = [] + + class Sessions: + async def call(self, url, tool, arguments, meta, *, timeout): + if tool == "svc_schedule": + return CallToolResult(content=[TextContent(type="text", text="scheduled")], _meta={ + AGENT_ENV_DEFERRED_CALLS_META_KEY: [{ + "key": "post-1", "at": "2026-11-08T17:01:00Z", + "call": {"tool": "svc_post", "arguments": {}}, + "report_as": {"tool": "svc_post", "arguments": {}}}]}) + posted.append("posted") + return CallToolResult(content=[TextContent(type="text", text="posted")]) + gw._sessions = Sessions() + monkeypatch.setattr(gw._trigger_engine, "_known_tools", lambda: None) + replies = _executor(monkeypatch, 0.3) + + async with _client(gw) as client: + await _arm(client) + gw._trigger_engine.register({ + "watch_roles": ["default"], "executors": {"bob": {"a2a_url": "http://bob", "role": "bob"}}, + "triggers": [{"id": "reply", "when": {"type": "action", "tool": "svc_post"}, + "actions": [{"type": "nl", "executor": "bob", "instruction": "reply"}]}]}) + await _work(client) + await _open(client) + assert (await _call(client, "svc_schedule")).status_code == 200 + # Delivered at 17:01, the charge's end, and bob's reply to it written, before the agent heard back. + assert posted == ["posted"] and replies == ["2026-11-08T17:01:00Z"] + (hold,) = _logged(gw, "work_clock_hold") + assert hold["still_running"] == [] @pytest.mark.asyncio @@ -398,11 +764,13 @@ async def test_a_fire_waiting_on_later_task_time_doesnt_hold_the_call(gw, monkey await _arm(client) _reply_at(gw, delay="PT1H") await _work(client) + await _open(client) assert (await _call(client, "app_lookup")).status_code == 200 assert replies == [] and _trigger(gw)["waiting"] is True (charge,) = _logged(gw, "work_clock_charge") - assert (charge["due"], charge["still_running"]) == (["sellout"], []) - assert charge["held_s"] < 2 + (hold,) = _logged(gw, "work_clock_hold") + assert (charge["due"], hold["still_running"]) == (["sellout"], []) + assert hold["held_s"] < 2 await gw._trigger_engine.cancel_scheduled() @@ -414,16 +782,58 @@ async def test_the_hold_gives_up_after_hold_seconds(gw, monkeypatch): await _arm(client) _reply_at(gw) await _work(client) + await _open(client) assert (await _call(client, "app_lookup")).status_code == 200 - (charge,) = _logged(gw, "work_clock_charge") - assert (charge["due"], charge["still_running"]) == (["sellout"], ["sellout"]) - assert 0.15 <= charge["held_s"] < 5 + (hold,) = _logged(gw, "work_clock_hold") + assert hold["still_running"] == ["sellout"] + assert 0.15 <= hold["held_s"] < 5 await gw._trigger_engine.cancel_scheduled() -# ---- TriggerEngine.settle_due --------------------------------------------------------------------------------------- +@pytest.mark.asyncio +async def test_the_barrier_wait_and_the_hold_share_one_budget(gw, monkeypatch): + async def executor(engine, ex, instruction, context_id): + await asyncio.sleep(0.4 if instruction == "ack" else 30) + return "replied" + monkeypatch.setattr(TriggerEngine, "_call_executor", executor) + monkeypatch.setattr(gw_mod, "HOLD_SECONDS", 0.6) + gw.TRIGGER_BARRIER_TIMEOUT_S = 0.6 + gw._trigger_engine.register({ + "watch_roles": ["default"], "executors": {"bob": {"a2a_url": "http://bob", "role": "bob"}}, + "triggers": [{"id": "ack", "when": {"type": "action", "tool": "app_lookup"}, + "barrier": {"at": "provoking_call"}, + "actions": [{"type": "nl", "executor": "bob", "instruction": "ack"}]}, + {"id": "sellout", "when": {"type": "time", "at": "PT1M"}, + "actions": [{"type": "nl", "executor": "bob", "instruction": "late"}]}]}) + async with _client(gw) as client: + await _working(client) + started = time.monotonic() + assert (await _call(client, "app_lookup")).status_code == 200 + took = time.monotonic() - started + (hold,) = _logged(gw, "work_clock_hold") + assert hold["still_running"] == ["sellout"] + assert 0.5 <= took < 0.95 # 0.6 s in all, not 0.4 s of barrier plus a fresh 0.6 s of hold + await gw._trigger_engine.cancel_scheduled() + @pytest.mark.asyncio -async def test_settle_due_with_nothing_due_returns_at_once(gw): - assert await gw._trigger_engine.settle_due([], 5) == [] - assert await gw._trigger_engine.settle_due(["no-such-trigger"], 5) == [] +async def test_a_call_cancelled_during_its_hold_still_leaves_its_charge_in_the_trajectory(gw, monkeypatch): + _executor(monkeypatch, 5) + async with _client(gw) as client: + await _arm(client) + _reply_at(gw) + await _work(client) + await _open(client) + task = asyncio.create_task(_mcp(gw, "app_lookup")) + await asyncio.sleep(0.3) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await asyncio.sleep(0.05) + assert await _now(client) == "2026-11-08T17:01:00Z" + assert (await _work_state(client))["calls"] == 1 + await gw._trigger_engine.cancel_scheduled() + (charge,) = _logged(gw, "work_clock_charge") + (hold,) = _logged(gw, "work_clock_hold") + assert (charge["tool"], charge["due"]) == ("app_lookup", ["sellout"]) + assert hold["cancelled"] is True and hold["held_s"] >= 0.25 diff --git a/tst/unit/task_step/clock_mode_test.py b/tst/unit/task_step/clock_mode_test.py index 7e24d6ec1..6063ba558 100644 --- a/tst/unit/task_step/clock_mode_test.py +++ b/tst/unit/task_step/clock_mode_test.py @@ -1,7 +1,8 @@ """The clock setup steps' ``clock_mode`` (FD-7183): ``"work"`` arms the clock frozen (rate 0) and turns on the -gateway's work mode, where each tool call the agent makes moves task time on by a fixed charge, so a frozen world -still lives through the agent's work. sync_env_clock and set_env_clock_rate both take it, each driving a real -in-process gateway here. Without clock_mode, either step does exactly what it did before.""" +gateway's work mode, where each tool call the agent makes inside a work window moves task time on by a fixed charge, +so a frozen world still lives through the agent's work. sync_env_clock and set_env_clock_rate both take it, and +prompt_agent opens the window around the agent's turns, each driving a real in-process gateway here. Without +clock_mode, every step does exactly what it did before.""" from __future__ import annotations import json @@ -9,12 +10,15 @@ import httpx import pytest +from a2a.types import TaskState from agent_env.env.env import DeployedGatewayEnv from agent_env.env.gateway import gateway as gw_mod -from agent_env.env.gateway.constants import AGENT_ENV_ROLE_HEADER, WELL_KNOWN_PATH +from agent_env.env.gateway.constants import AGENT_ENV_ROLE_HEADER, EXT_STEP_URI, WELL_KNOWN_PATH from agent_env.env.gateway.gateway import Gateway -from agent_env.task_step.context import StepContextError, TaskStepContext +from agent_env.task_step.context import DeployedAgent, StepContextError, TaskStepContext +from agent_env.task_step.task_steps import prompt_agent as pa_mod +from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep from agent_env.task_step.task_steps.set_env_clock_rate import SetEnvClockRateTaskStep from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep @@ -54,12 +58,12 @@ def lookup() -> str: monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace(mcp_server_envs=[], website_envs=[])) - async def deployed(self, card: dict | None = None) -> DeployedGatewayEnv: + async def deployed(self, card: dict | None = None, env_id: str = "e1") -> DeployedGatewayEnv: if card is None: card = json.loads((await self.gw._serve_env_card()).body) - return DeployedGatewayEnv(env_id="e1", env_version=1, gateway_url=GATEWAY, mcp_url=f"{GATEWAY}/mcp", + return DeployedGatewayEnv(env_id=env_id, env_version=1, gateway_url=GATEWAY, mcp_url=f"{GATEWAY}/mcp", sandbox_id="sb-1", environment_card_url=f"{GATEWAY}{WELL_KNOWN_PATH}", - environment_card=card) + environment_card=card, metadata={"deploy_step_id": "deploy"}) async def context(self, card: dict | None = None) -> TaskStepContext: return TaskStepContext(deployed_envs=[await self.deployed(card)]) @@ -69,7 +73,7 @@ async def state(self) -> dict: return (await client.get("/clock/state")).json() async def call(self, tool: str = "lookup", role: str | None = None) -> None: - """A tool call through the gateway's /step, as the agent (no role header: the default role) or ``role``.""" + """A tool call through the gateway's /step as ``role``, or with no role header (the default role).""" async with self.http() as client: r = await client.post("/step", json={"action": "call_tool", "tool_name": tool, "arguments": {}}, headers={AGENT_ENV_ROLE_HEADER: role} if role else {}) @@ -115,9 +119,10 @@ async def test_sync_env_clock_in_work_mode_arms_frozen_then_turns_work_on(world) assert state["work"]["on"] is True and state["work"]["seconds_per_call"] == 60 record = context.metadata["clock_configurations"][0] assert record["clock_mode"] == "work" and record["virtual_seconds_per_real_second"] == 0 + assert record["work"]["on"] is True and record["deploy_step_id"] == "deploy" - await world.call() - assert (await world.state())["virtual_time"] == "2026-11-09T14:01:00Z" + await world.call() # no agent's turn has opened a work window yet: setup's calls take no time + assert (await world.state())["virtual_time"] == T0 @pytest.mark.asyncio @@ -150,10 +155,10 @@ def test_sync_env_clock_work_mode_round_trips_and_a_plain_step_has_no_clock_mode @pytest.mark.asyncio -async def test_sync_env_clock_work_mode_on_a_gateway_without_work_fails_before_arming(world): - card = json.loads((await world.gw._serve_env_card()).body) - for ext in card["capabilities"]["extensions"]: - (ext.get("params") or {}).get("methods", {}).pop("work", None) # a gateway image from before work mode +@pytest.mark.parametrize("missing", [("work", "open_work_window", "close_work_window"), + ("open_work_window", "close_work_window")]) +async def test_sync_env_clock_work_mode_on_a_gateway_without_work_fails_before_arming(world, missing): + card = _card_without(json.loads((await world.gw._serve_env_card()).body), *missing) with pytest.raises(StepContextError, match="work"): await _sync(clock_mode="work").execute(await world.context(card)) @@ -161,6 +166,14 @@ async def test_sync_env_clock_work_mode_on_a_gateway_without_work_fails_before_a assert (await world.state())["armed"] is False +def _card_without(card: dict, *methods: str) -> dict: + """``card`` with its clock/v1 offering none of ``methods``: a gateway image from before them.""" + for ext in card["capabilities"]["extensions"]: + for method in methods: + (ext.get("params") or {}).get("methods", {}).pop(method, None) + return card + + # ---- set_env_clock_rate --------------------------------------------------------------------------------------------- @pytest.mark.asyncio @@ -176,9 +189,10 @@ async def test_set_env_clock_rate_in_work_mode_freezes_the_clock_then_turns_work ("PUT", "/clock/work", {"on": True}), ] assert (await world.state())["work"]["on"] is True - assert context.metadata["clock_configurations"][0]["clock_mode"] == "work" + record = context.metadata["clock_configurations"][0] + assert (record["clock_mode"], record["deploy_step_id"]) == ("work", "deploy") await world.call() - assert (await world.state())["virtual_time"] == "2026-11-09T14:01:00Z" + assert (await world.state())["virtual_time"] == T0 @pytest.mark.parametrize("rate", [1, 0.25, 86400]) @@ -198,17 +212,20 @@ def test_set_env_clock_rate_needs_a_rate_or_work_mode(): @pytest.mark.asyncio -async def test_set_env_clock_rate_to_zero_after_the_agent_ends_work_mode(world): - """The usual stop after the agent's last prompt_agent: a plain rate of 0 leaves work mode, so the harness's own - calls after it (verifiers, collecting artifacts) move nothing.""" - await _sync(clock_mode="work").execute(await world.context()) - await world.call() +async def test_set_env_clock_rate_to_zero_ends_work_mode_and_the_agents_window(world, monkeypatch): + """A plain rate of 0 leaves work mode, the agent's open window with it.""" + context = await world.context() + await _sync(clock_mode="work").execute(context) + async with world.http() as client: + await client.put("/clock/work/window", json={"window": "turn", "roles": ["solver"]}) + await world.call(role="solver") + assert (await world.state())["virtual_time"] == "2026-11-09T14:01:00Z" - await _rate(0).execute(await world.context()) + await _rate(0).execute(context) state = await world.state() - assert state["work"]["on"] is False - await world.call() + assert state["work"]["on"] is False and state["work"]["windows"] == [] + await world.call(role="solver") assert (await world.state())["virtual_time"] == state["virtual_time"] @@ -238,6 +255,18 @@ async def test_without_clock_mode_the_steps_send_what_they_always_sent(world): ] +@pytest.mark.asyncio +async def test_without_clock_mode_the_steps_work_against_a_gateway_without_work(world): + """A gateway image from before work mode: the plain steps never ask for it.""" + card = _card_without(json.loads((await world.gw._serve_env_card()).body), "work", "open_work_window", + "close_work_window") + context = await world.context(card) + await _sync(virtual_seconds_per_real_second=0).execute(context) + await _rate(0).execute(context) + assert [p for _, p, _ in world.clock_calls()] == ["/clock/set-time", "/clock/state", "/clock/set-rate"] + assert "clock_mode" not in context.metadata["clock_configurations"][1] + + @pytest.mark.asyncio async def test_without_clock_mode_agent_calls_move_no_time(world): await _sync(virtual_seconds_per_real_second=0).execute(await world.context()) @@ -256,3 +285,150 @@ async def test_a_plain_re_arm_leaves_work_mode(world): assert (await world.state())["work"]["on"] is False await world.call() assert (await world.state())["virtual_time"] == T0 + + +# ---- prompt_agent: the agent's work window --------------------------------------------------------------------------- + +SOLVER = "http://solver.test" + + +def _agent(monkeypatch, world: World, turn) -> list[str]: + """The agent prompt_agent prompts: each turn runs ``turn()`` (its tool calls on the gateway) and ends completed. + The texts it was sent are returned.""" + sent: list[str] = [] + + async def post_agent_config(url, fields, headers=None): + return None + + async def send(url, parts, message_id, context_id, timeout): + sent.append(" ".join(p.get("text", "") for p in parts)) + return f"task-{message_id}", None + + async def poll(url, task_id, timeout, interval, **_): + await turn() + return {"status": {"state": TaskState.completed, "message": {"parts": [{"kind": "text", "text": "done"}]}}} + + monkeypatch.setattr(pa_mod.protocol, "post_agent_config", post_agent_config) + monkeypatch.setattr(pa_mod.protocol, "send_a2a_message", send) + monkeypatch.setattr(pa_mod.protocol, "poll_a2a_task", poll) + return sent + + +def _prompt(**kw) -> PromptAgentTaskStep: + return PromptAgentTaskStep(id="solve", version=None, prompt="sort the order out", agent_name="solver", + max_conversation_turns=1, poll_interval_seconds=0, **kw) + + +def _with_agent(context: TaskStepContext, role: str | None = "solver") -> TaskStepContext: + context.deployed_agents.append(DeployedAgent(agent_name="solver", api_url=SOLVER, a2a_url=SOLVER, a2a_card={}, + role=role)) + return context + + +async def _collect(deployed) -> None: + """A read through step/v1 exactly as collect_artifacts makes it: DeployedEnv.invoke, no role header.""" + data = await deployed.invoke(EXT_STEP_URI, "step", {"action": "call_tool", "tool_name": "lookup", "arguments": {}}, + timeout=600) + assert not data.get("isError"), data + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_charges_the_agent_in_its_window_and_not_the_harness_before_or_after(world, monkeypatch): + async def turn(): + await world.call(role="solver") + await world.call(role="solver") + await world.call() # a user sim or a setup script with no role, mid-turn: not the agent + + _agent(monkeypatch, world, turn) + context = _with_agent(await world.context()) + await _sync(clock_mode="work").execute(context) + deployed = context.deployed_envs[0] + await _collect(deployed) # a run_code setup script's read, before the agent starts + world.forget() + + await _prompt().execute(context) + + windows = [(m, b) for m, p, b in world.clock_calls() if p == "/clock/work/window"] + assert [m for m, _ in windows] == ["PUT", "DELETE"] + opened = windows[0][1] + assert opened["roles"] == ["solver"] and windows[1][1] == {"window": opened["window"]} + state = await world.state() + assert state["virtual_time"] == "2026-11-09T14:02:00Z" + assert state["work"]["windows"] == [] and state["work"]["by_role"] == { + "solver": {"calls": 2, "virtual_seconds": 120.0}} + (record,) = context.metadata["work_windows"] + assert record == {"step_id": "solve", "env_id": "e1", "window": opened["window"], "roles": ["solver"], + "calls": 2, "virtual_seconds": 120.0} + + for _ in range(3): # the verifier's and collect_artifacts' reads, after the agent + await _collect(deployed) + assert (await world.state())["virtual_time"] == "2026-11-09T14:02:00Z" + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_closes_its_window_when_the_agent_fails(world, monkeypatch): + async def turn(): + await world.call() # an agent with no role sends no role header + raise RuntimeError("the agent's sandbox died") + + _agent(monkeypatch, world, turn) + context = _with_agent(await world.context(), role=None) # an agent with no role of its own: the default one + await _sync(clock_mode="work").execute(context) + + with pytest.raises(RuntimeError, match="sandbox died"): + await _prompt().execute(context) + state = await world.state() + assert state["work"]["windows"] == [] + assert state["work"]["by_role"] == {"default": {"calls": 1, "virtual_seconds": 60.0}} + await world.call() + assert (await world.state())["virtual_time"] == "2026-11-09T14:01:00Z" + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_without_work_mode_opens_no_window(world, monkeypatch): + async def turn(): + await world.call(role="solver") + + _agent(monkeypatch, world, turn) + context = _with_agent(await world.context()) + await _sync(virtual_seconds_per_real_second=0).execute(context) + world.forget() + await _prompt().execute(context) + assert not [p for _, p, _ in world.clock_calls() if p.startswith("/clock/work")] + assert "work_windows" not in context.metadata + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_after_work_mode_was_ended_opens_no_window(world, monkeypatch): + """A later plain clock step ended work mode: the latest step on each env decides.""" + async def turn(): + await world.call(role="solver") + + _agent(monkeypatch, world, turn) + context = _with_agent(await world.context()) + await _sync(clock_mode="work").execute(context) + await _rate(0).execute(context) + world.forget() + await _prompt().execute(context) + assert not [p for _, p, _ in world.clock_calls() if p.startswith("/clock/work")] + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_refuses_more_than_one_env_in_work_mode(world, monkeypatch): + """Two clocks charged for the same calls would drift apart, and their summed totals would match neither.""" + sent = _agent(monkeypatch, world, lambda: None) + context = _with_agent(await world.context()) + context.deployed_envs.append(await world.deployed(env_id="e2")) + await _sync(clock_mode="work").execute(context) + await SyncEnvClockTaskStep(id="clock-2", version=1, env_id="e2", virtual_time=T0, depends_on=[], + clock_mode="work").execute(context) + world.forget() + + with pytest.raises(StepContextError, match="work mode.*e1.*e2"): + await _prompt().execute(context) + assert sent == [] and not [p for _, p, _ in world.clock_calls() if p.startswith("/clock/work")] diff --git a/tst/unit/task_step/test_always_on_work_clock.py b/tst/unit/task_step/test_always_on_work_clock.py index 2a1968b7c..3d9b41193 100644 --- a/tst/unit/task_step/test_always_on_work_clock.py +++ b/tst/unit/task_step/test_always_on_work_clock.py @@ -1,8 +1,8 @@ """Work mode (FD-7183) in an always_on run. The task's clock step puts the clock in work mode (sync_env_clock with -``clock_mode: "work"``): frozen, and moved on a minute by the gateway for each tool call the agent makes, so the world -lives through the agent's work and what comes due mid-wake lands then. always_on only reports it, as the gateway's -/clock/state says: each wake records what its work took, the run's record sums it, and the judge reads it. No one but -the agent is charged, inside its turns or out.""" +``clock_mode: "work"``): frozen, and moved on a minute by the gateway for each tool call the agent makes inside a work +window, so the world lives through the agent's work and what comes due mid-wake lands then. always_on opens the window +for the agent's role around each turn, nudges included, and closes it at the turn's end: each wake records what its +work took, the run's record sums it, and the judge reads it. No one but the agent is charged, inside its turns or out.""" from __future__ import annotations @@ -11,10 +11,12 @@ import pytest +from agent_env.env.env import DeployedGatewayEnv +from agent_env.env.gateway.constants import EXT_CLOCK_URI, GATEWAY_EXTENSIONS, WELL_KNOWN_PATH from agent_env.env.gateway.triggers import TriggerEngine from agent_env.task_step.task_steps import always_on as ao from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep -from tst.unit.task_step.always_on_harness import ROLE, Rig +from tst.unit.task_step.always_on_harness import GATEWAY, ROLE, Rig pytestmark = pytest.mark.usefixtures("local_stores") @@ -32,6 +34,13 @@ async def _work_state(rig: Rig) -> dict: return (await client.get("/clock/state")).json()["work"] +async def _header_less(rig: Rig, tool: str) -> None: + """A /step call_tool with no AgentEnv-Role header, as collect_artifacts, a run_code script and a verifier make it.""" + async with rig.http() as client: + r = await client.post("/step", json={"action": "call_tool", "tool_name": tool, "arguments": {}}) + r.raise_for_status() + + @pytest.mark.asyncio async def test_in_work_mode_each_wake_records_what_the_agents_work_took(monkeypatch, tmp_path): async def agent(n, texts, rig): @@ -56,9 +65,10 @@ async def agent(n, texts, rig): record = rig.record(ctx) assert record["counts"]["work_clock"] == {"calls": 3, "virtual_seconds": 180.0} assert record["settings"]["clock"] == {"envs": [], "work": {"seconds_per_call": 60.0, "envs": ["world"]}} - # always_on reports work mode and changes nothing of it: the clock is still in it after the run. + # always_on changes nothing of work mode: the clock is still in it after the run, every window closed. work = await _work_state(rig) - assert work["on"] is True and work["by_role"] == {ROLE: {"calls": 3, "virtual_seconds": 180.0}} + assert work["on"] is True and work["windows"] == [] + assert work["by_role"] == {ROLE: {"calls": 3, "virtual_seconds": 180.0}} @pytest.mark.asyncio @@ -90,11 +100,12 @@ async def agent(n, texts, rig): @pytest.mark.asyncio async def test_no_one_but_the_agent_is_charged_inside_or_outside_its_turns(monkeypatch, tmp_path): - """A setup step's, a verifier's and a user sim's calls, a contact's (a trigger's executor), and a trigger's own - tool action, made before the run, during the agent's turn, between its turns and after the run, take no task time; - the agent's one call takes a minute.""" - others = ("setup", "verifier", "user-sim", "contact-bob") + """A setup script's and a verifier's reads (no role header) before and after the run, a user sim's and a contact's + calls during the agent's turn and after it, and a trigger's own tool action take no task time; the agent's one call + takes a minute. (This agent is on the default role, which a call with no role header resolves to, so a header-less + call inside its turn would be its own: prompt_agent's test has an agent on a role of its own for that case.)""" turn = {"on": False} + turn_over = asyncio.Event() contact_in_turn: list[bool] = [] async def agent(n, texts, rig): @@ -102,18 +113,21 @@ async def agent(n, texts, rig): try: if n == 1: await rig.call("market_search") # the agent's own: it fires "echo" - for role in others: + for role in ("user-sim", "contact-bob"): await rig.call("market_search", role=role) + await rig.call("get_time") # free, so not held: bob's reply to it comes after the turn rig.message("on it") else: rig.quiet() return "" finally: turn["on"] = False + turn_over.set() async def contact(engine, executor, instruction, context_id): - await asyncio.sleep(0.05) # past the end of the agent's turn - contact_in_turn.append(turn["on"]) + if instruction == "reply after the turn": + await turn_over.wait() + contact_in_turn.append(turn["on"]) await rig.call("market_search", role=executor["role"]) return "replied" @@ -125,18 +139,14 @@ async def contact(engine, executor, instruction, context_id): rig.triggers({"id": "echo", "when": {"type": "action", "tool": "market_search"}, "actions": [{"type": "tool", "tool": "market_search", "args": {}}, {"type": "nl", "executor": "bob", "instruction": "reply to the agent"}]}, + {"id": "later", "when": {"type": "action", "tool": "get_time"}, + "actions": [{"type": "nl", "executor": "bob", "instruction": "reply after the turn"}]}, executors={"bob": {"a2a_url": "http://bob.test", "role": "contact-bob"}}) - for role in others: - await rig.call("market_search", role=role) + await _header_less(rig, "market_search") assert rig.now() == rig.t0 await rig.run(rig.step(settle_timeout_seconds=0.5, max_wakes=2), ctx) - for _ in range(100): - if contact_in_turn: - break - await asyncio.sleep(0.01) - for role in others: - await rig.call("market_search", role=role) + await _header_less(rig, "market_search") assert contact_in_turn == [False] assert rig.now() == "2026-11-09T14:01:00Z" @@ -146,29 +156,106 @@ async def contact(engine, executor, instruction, context_id): @pytest.mark.asyncio -async def test_an_agent_whose_role_work_mode_doesnt_charge_is_refused(monkeypatch, tmp_path): - rig = Rig(monkeypatch, tmp_path) +async def test_an_agent_on_a_role_no_trigger_watches_is_charged_in_its_turns(monkeypatch, tmp_path): + async def agent(n, texts, rig): + await rig.call("market_search") + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + rig.tool("market_search") ctx = rig.context() await _work_mode(monkeypatch, rig, ctx) rig.gw._trigger_engine.register({"watch_roles": ["assistant"], "triggers": []}) - with pytest.raises(ValueError, match="work mode.*'default'"): + await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1), ctx) + assert rig.now() == "2026-11-09T14:01:00Z" + (turn,) = rig.events(ctx, "agent_turn_end") + assert turn["work"] == {"calls": 1, "virtual_seconds": 60.0} + + +@pytest.mark.asyncio +async def test_stay_quiet_is_free_and_message_user_is_charged_through_the_agents_tools(monkeypatch, tmp_path): + async def agent(n, texts, rig): + if n == 1: + await rig.call("message_user", {"text": "Chicago has 2 seats"}) + else: + await rig.call("stay_quiet") + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "great"},)) + ctx = rig.context() + await _work_mode(monkeypatch, rig, ctx) + await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=2), ctx) + first, second = rig.events(ctx, "agent_turn_end") + assert (first["work"], second["work"]) == ({"calls": 1, "virtual_seconds": 60.0}, + {"calls": 0, "virtual_seconds": 0.0}) + + +@pytest.mark.asyncio +async def test_always_on_refuses_more_than_one_env_in_work_mode(monkeypatch, tmp_path): + """Two clocks charged for the same calls would drift apart, and the summed totals would match neither.""" + rig = Rig(monkeypatch, tmp_path) + ctx = rig.context() + await _work_mode(monkeypatch, rig, ctx) + ctx.deployed_envs.append(DeployedGatewayEnv( + env_id="world-2", env_version=1, gateway_url=GATEWAY, mcp_url="", sandbox_id="sb-2", + environment_card_url=f"{GATEWAY}{WELL_KNOWN_PATH}", + environment_card={"capabilities": {"extensions": list(GATEWAY_EXTENSIONS)}}, + metadata={"deploy_step_id": "deploy-2"})) + with pytest.raises(ValueError, match="work mode.*world.*world-2"): await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1), ctx) + assert (await _work_state(rig))["windows"] == [] @pytest.mark.asyncio -async def test_the_judge_reads_what_each_wakes_work_took(monkeypatch, tmp_path): +async def test_work_mode_ended_mid_run_is_logged_not_read_as_no_work(monkeypatch, tmp_path): async def agent(n, texts, rig): - for _ in range(3): + await rig.call("market_search") + if n == 1: # a hook, say, sets the rate during the turn + async with rig.http() as client: + await client.put("/clock/set-rate", json={"virtual_seconds_per_real_second": 0}) + rig.message("checked") + else: + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "ok"},)) + rig.tool("market_search") + ctx = rig.context() + await _work_mode(monkeypatch, rig, ctx) + await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=2), ctx) + (off,) = rig.events(ctx, "work_mode_off") + assert off["env_id"] == "world" and off["wake"] == 1 + first, second = rig.events(ctx, "agent_turn_end") + assert first["work"] == {"calls": 1, "virtual_seconds": 60.0} + assert "work" not in second # nothing to read once work mode is off + assert rig.now() == "2026-11-09T14:01:00Z" + + +@pytest.mark.asyncio +async def test_the_judge_reads_what_each_wakes_work_took_its_nudge_included(monkeypatch, tmp_path): + async def agent(n, texts, rig): + if n == 1: await rig.call("market_search") + return "I looked it up." # neither message_user nor stay_quiet: a nudge follows + if n == 2: # the nudge + for _ in range(4): + await rig.call("market_search") + rig.message("Chicago has 2 seats") + return "" rig.quiet() return "" - rig = Rig(monkeypatch, tmp_path, agent=agent) + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "no_reply", "message": ""},)) rig.tool("market_search") ctx = rig.context() await _work_mode(monkeypatch, rig, ctx) await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1), ctx) - assert "· its work took 3 min of task time" in ao.render_for_judge(rig.record(ctx)) + record = rig.record(ctx) + assert record["counts"]["work_clock"] == {"calls": 5, "virtual_seconds": 300.0} + (nudge,) = rig.events(ctx, "nudge") + assert nudge["work"] == {"calls": 4, "virtual_seconds": 240.0} + assert "· its work took 5 min of task time" in ao.render_for_judge(record) @pytest.mark.asyncio @@ -191,16 +278,43 @@ async def agent(n, texts, rig): rig = Rig(monkeypatch, tmp_path, agent=agent) rig.tool("market_search") await rig.arm() + opened: list = [] + real_call = ao._call + + async def call(env, uri, method, params=None, **kw): + if method in ("open_work_window", "close_work_window"): + opened.append(method) + return await real_call(env, uri, method, params, **kw) + monkeypatch.setattr(ao, "_call", call) ctx = await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1)) (turn,) = rig.events(ctx, "agent_turn_end") assert "work" not in turn and turn["virtual_seconds"] == 0 record = rig.record(ctx) assert "work_clock" not in record["counts"] and record["settings"]["clock"] == {"envs": []} assert "its work took" not in ao.render_for_judge(record) - assert rig.now() == rig.t0 + assert rig.now() == rig.t0 and opened == [] + +@pytest.mark.asyncio +async def test_a_gateway_whose_clock_state_has_no_work_block_runs_as_before(monkeypatch, tmp_path): + """A gateway image from before work mode: /clock/state says nothing of it.""" + async def agent(n, texts, rig): + await rig.call("market_search") + rig.quiet() + return "" -def test_always_on_takes_no_work_setting_of_its_own(monkeypatch, tmp_path): - """Work mode is the clock step's to choose; always_on has no field for it.""" - with pytest.raises(TypeError): - Rig(monkeypatch, tmp_path).step(work_clock={"seconds_per_call": 60}) + rig = Rig(monkeypatch, tmp_path, agent=agent) + rig.tool("market_search") + await rig.arm() + real_call = ao._call + + async def call(env, uri, method, params=None, **kw): + answer = await real_call(env, uri, method, params, **kw) + if uri == EXT_CLOCK_URI and method == "state": + answer = {k: v for k, v in answer.items() if k != "work"} + return answer + monkeypatch.setattr(ao, "_call", call) + ctx = await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1)) + (turn,) = rig.events(ctx, "agent_turn_end") + assert "work" not in turn + assert "work_clock" not in rig.record(ctx)["counts"] From b6ebd4076fb05cec03aca180aa5f355daf8dd8c5 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Thu, 3 Dec 2026 18:18:21 -0800 Subject: [PATCH 3/9] fix(task_step): a work window that can't be closed fails the step as an infra error (FD-7183) A window left open would charge calls made after the agent (a verifier's or collect_artifacts' header-less reads, for an agent on the default role) and move the world on under the grading. So a close that still fails after its retry now fails closed with WorkWindowError, an AgentTurnInfraError, which a retry_config can redo: - prompt_agent raises it once the agent's work is done; when the agent itself raised, its error stays the one raised, the close failure logged and added as a note on it. - always_on ends the run with it at the turn's end (two tries, 10 s each); a run being cancelled stays cancelled, the failure logged. - A window that can't be opened (other than work mode found off, a 409) fails the same way before the agent starts. Also adds the tests the mutation run asked for: a deferred call due later doesn't hold a call; a barrier's own longer timeout is the call's budget; a call answered after its window closed counts in a retried close; a second cancel doesn't drop the hold's record; the window goes on the deployment in work mode only; a 409 on open runs the agent with no window; work mode ended between always_on turns is found at once. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- .../task_step/task_steps/always_on.py | 41 ++++-- .../task_step/task_steps/clock_mode.py | 79 ++++++++---- tst/unit/env/gateway/work_clock_test.py | 97 +++++++++++++++ tst/unit/task_step/clock_mode_test.py | 117 +++++++++++++++++- .../task_step/test_always_on_work_clock.py | 71 +++++++++++ 6 files changed, 369 insertions(+), 38 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f64064068..6540534b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,7 +191,7 @@ and deserialized through a registry. | Package | Contents | |---|---| -| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its work mode (`/clock/work`, `env/gateway/work_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "work"` on a clock at rate 0 and any later set_time, set_rate or clear turns off, ending every open window, moves the frozen clock on by a fixed `WORK_SECONDS_PER_CALL` (60 s, not configurable) for each answered tool call made while a work window naming its role is open (`/clock/work/window`, PUT to open with `roles`, DELETE to close, answering its totals; both control routes): prompt_agent opens one for its agent's role around its conversation and always_on one around each turn, nudges included (`task_steps/clock_mode.py` `agent_work_window`), and both refuse more than one env in work mode, so a setup script, a verifier, collect_artifacts, a user sim, a contact or the agent between its turns is never charged, the agent's role outside its window logged as `work_clock_outside_window`. A charge, on the MCP path and the step API's `/step` paths (not a post-turn hook's that shows the control token; never the gateway's own `get_time` or `stay_quiet`), comes after the call's barriers (`Clock.advance_by`), then the answer is held until all world work runnable now has landed, every trigger fire at work and each deferred call the clock reached (`Gateway._settle_world`), but not a fire waiting on a later task time, the barriers and the hold sharing one budget; each charge is a `work_clock_charge` trajectory event and its hold a `work_clock_hold`, written even when the call is cancelled. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | +| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its work mode (`/clock/work`, `env/gateway/work_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "work"` on a clock at rate 0 and any later set_time, set_rate or clear turns off, ending every open window, moves the frozen clock on by a fixed `WORK_SECONDS_PER_CALL` (60 s, not configurable) for each answered tool call made while a work window naming its role is open (`/clock/work/window`, PUT to open with `roles`, DELETE to close, answering its totals; both control routes): prompt_agent opens one for its agent's role around its conversation and always_on one around each turn, nudges included (`task_steps/clock_mode.py` `agent_work_window`), each failing closed, as an infra error (`WorkWindowError`), when a window can't be closed, and both refuse more than one env in work mode, so a setup script, a verifier, collect_artifacts, a user sim, a contact or the agent between its turns is never charged, the agent's role outside its window logged as `work_clock_outside_window`. A charge, on the MCP path and the step API's `/step` paths (not a post-turn hook's that shows the control token; never the gateway's own `get_time` or `stay_quiet`), comes after the call's barriers (`Clock.advance_by`), then the answer is held until all world work runnable now has landed, every trigger fire at work and each deferred call the clock reached (`Gateway._settle_world`), but not a fire waiting on a later task time, the barriers and the hold sharing one budget; each charge is a `work_clock_charge` trajectory event and its hold a `work_clock_hold`, written even when the call is cancelled. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | | `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, the `attempt_epoch` it was written under, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), each naming exactly what it was sent (`input`: a direct call's messages, response format and settings, an agent call's message, every file its step staged in the judge's sandbox and, for a judge the task deployed, what the task's own `load_artifact` steps put there as the run recorded it, stored by sha256 under `judge-inputs/` in the background, `judge_utils/judge_inputs.py`; the step waits for those uploads, at most 120 s, before it writes its grade, `VerifierTaskStep.settle`, and one that failed or hadn't finished is the call's `input_error`, never a failed grade), and its `verifier_settings` hold the trajectory source of each turn it read (`trajectory_sources`); with `judge_samples` (a count, as a step field, a run override or `--judge-samples` on `run`, `task run` and `eval run`), a rubric_binary or rubric_partial judge grades each criterion that many times, each a call of its own under `judge_batch_concurrency` (an agent judge the verifier deploys gets a deployment of its own per sample, its trajectory staged in each; the task's own judge takes every sample), and keeps its median, the lower middle score on a tie, which fails it, the row the first sample that scored it gave with every sample's score, verdict and justification in its `samples` and its `agreement`, the share of samples giving its verdict; a row under `min_judge_agreement` (0.5 by default, which never fails, so the median decides; 1.0 fails any split; set where `judge_samples` is, `--min-judge-agreement`) fails the grade, its rows kept, and then the step (`JudgeDisagreementError`), and `agent-env run` names the criteria a grade that stood split on (`samples split:`), and one failed sample fails the grade (a run's count or agreement a judge of another format can't take is recorded in `not_sent`) and the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`), each computer its own, a multi env's included, never the gateway's: its boot environment holds only the token's sha256 (`AGENTENV_CONTROL_TOKEN_SHA256`) when its probed card's computer/v1 says `control_token = "sha256"`, else, for a driver an older protocol built, the token itself (`AGENTENV_CONTROL_TOKEN`); the gateway learns each computer's (`CHILD_CONTROL_TOKENS`), puts it in place of its own on that computer's `/svc` routes, and lets a computer's token through only to that computer and its clock watch; a multi env's record grants each computer's `/svc` route its own token (`DeployedGatewayEnv.control_grants`, the longest granted address winning), and `CONTROL_TOKEN_CHILDREN`, the computers an older agent-env booted with the gateway's token, is kept for them; framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 2bf9b8a9f..2557359fc 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -43,7 +43,9 @@ took (``work``, the window's totals) beside the agent's ``output_tokens``, the record's ``counts["work_clock"]`` sums it, ``settings["clock"]["work"]`` names the clock in work mode, and the judge reads each wake's, its nudge's included. Work mode ended mid-run (a hook's set_rate, say) is logged once (``work_mode_off``) and no window is opened after. - More than one clock in work mode is refused at setup: their task times would drift apart. + A window that can't be opened or closed ends the run as an infrastructure error (``WorkWindowError``): one left open + would charge calls made after the turn. More than one clock in work mode is refused at setup: their task times would + drift apart. - The agent can schedule its own wake-ups (scheduled checks) when the run is multi-day, at least ``scheduled_check_min_interval`` apart; ``scheduled_checks`` turns them on or off whatever the run's length. A check's wake counts toward ``max_wakes``. @@ -181,6 +183,7 @@ from agent_env.task_step.task_step import RetryConfig, TaskStep from agent_env.task_step.task_steps.agent import user_sim_versions from agent_env.task_step.task_steps.agent.deploy_user_sim_agent import USER_SIMS_KEY, recorded_instructions, user_sim_model +from agent_env.task_step.task_steps.clock_mode import WorkWindowError from agent_env.task_step.task_steps.notification_delivery import delivered_parts, label_time, take_due from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import ended_turn_error from agent_env.task_step.task_steps.server_fault_logs import capture_server_fault_logs @@ -870,7 +873,8 @@ def _configure_work(self, env, block: dict) -> None: async def _open_window(self) -> None: """Open the turn's work window, naming the agent's role, on the clock in work mode: ``turn_window``. Work mode - ended there since (409) is logged once, and the turn's work takes no task time; another failure is raised.""" + ended there since (409) is logged once, and the turn's work takes no task time; another failure ends the run + (WorkWindowError).""" if self.work_env is None or self.work_off: return window = f"{self.step.id}:wake-{self.wakes}:{uuid.uuid4().hex[:8]}" @@ -879,14 +883,20 @@ async def _open_window(self) -> None: answers=(409,)) except httpx.HTTPStatusError as e: if e.response.status_code != 409: - raise + raise WorkWindowError(f"always_on: wake {self.wakes}: opening the agent's work window on " + f"{self.work_env.env_id} failed (HTTP {e.response.status_code})") from e self._work_mode_off() return + except Exception as e: + raise WorkWindowError(f"always_on: wake {self.wakes}: opening the agent's work window on " + f"{self.work_env.env_id} failed: {type(e).__name__}: {e}") from e self.turn_window = window - async def _close_window(self) -> None: + async def _close_window(self, failed: Optional[BaseException] = None) -> None: """Close the turn's work window: what it charged, in ``turn_work`` and the run's ``work_total``. Within a short - budget, so a struggling gateway can't stall the turn's cleanup; a failed close is logged, not raised. Work mode + budget, so a struggling gateway can't stall the turn's cleanup. Fails closed: a window that can't be closed + would charge whoever calls with the agent's role after the turn, so the run ends with WorkWindowError, the + turn's own error (``failed``) named in it; a run being cancelled stays cancelled, the failure logged. Work mode found ended is logged once (``_work_mode_off``).""" window, self.turn_window = self.turn_window, None if window is None: @@ -895,9 +905,15 @@ async def _close_window(self) -> None: answer = await _call(self.work_env, EXT_CLOCK_URI, "close_work_window", {"window": window}, attempts=2, timeout=10) or {} except Exception as e: - logger.warning(f"always_on: wake {self.wakes}: closing the agent's work window failed, so what its work " - f"took is not known: {type(e).__name__}: {e}") - return + error = WorkWindowError( + f"always_on: wake {self.wakes}: closing the agent's work window on {self.work_env.env_id} failed " + f"({type(e).__name__}: {e}): it may still charge calls made after the turn, so the run is not graded" + + (f"; the turn itself had failed ({type(failed).__name__}: {failed})" if failed is not None else "")) + if isinstance(failed, asyncio.CancelledError): + logger.error(str(error)) + failed.add_note(str(error)) + return + raise error from e mine = answer.get("window") or {} work = {"calls": mine.get("calls", 0), "virtual_seconds": round(mine.get("virtual_seconds", 0.0), 3)} self.turn_work = work @@ -929,6 +945,7 @@ def accepted(task_id: str) -> None: self.turn_task_id = task_id await self._clock_runs(True) + failed: Optional[BaseException] = None try: await self._open_window() # Cut off past its limit and grace, whatever send_and_wait's own retries do: a TimeoutError, as its own. @@ -938,8 +955,10 @@ def accepted(task_id: str) -> None: poll_interval_seconds=step.poll_interval_seconds, before_send=record, on_sent=accepted), step.timeout_seconds + TURN_GRACE_SECONDS) - except (TimeoutError, asyncio.CancelledError): - self.usage.cut_off(ModelRole.SOLVER) + except BaseException as e: + failed = e + if isinstance(e, (TimeoutError, asyncio.CancelledError)): + self.usage.cut_off(ModelRole.SOLVER) raise else: self.usage.turn(ModelRole.SOLVER, turn.reply) @@ -948,7 +967,7 @@ def accepted(task_id: str) -> None: try: await self._clock_runs(False) finally: - await self._close_window() + await self._close_window(failed) async def _stopped_at_time_limit(self, error: TimeoutError) -> Optional[dict]: """A turn that ran out of time, with continue_after_wake_limit on: its A2A task as the agent confirms it ended diff --git a/src/agent_env/task_step/task_steps/clock_mode.py b/src/agent_env/task_step/task_steps/clock_mode.py index 18527cdd1..161155c4f 100644 --- a/src/agent_env/task_step/task_steps/clock_mode.py +++ b/src/agent_env/task_step/task_steps/clock_mode.py @@ -10,8 +10,9 @@ The clock step only turns the mode on; who the agent is, the step that runs it says. prompt_agent opens a window for its agent's role around its conversation (``agent_work_window``) and always_on one around each of the agent's turns, so a setup script, a verifier, collect_artifacts or a user sim calling the same gateway before, between or after is never -charged. Which env is in work mode the run's ``clock_configurations`` say (``work_mode_envs``), so a task that never -names the mode makes no window call at all. One env in work mode at most: two clocks charged for the same calls would +charged. A window that can't be closed fails the step as an infrastructure error (``WorkWindowError``), since it +would charge whoever calls after. Which env is in work mode the run's ``clock_configurations`` say +(``work_mode_envs``), so a task that never names the mode makes no window call at all. One env in work mode at most: two clocks charged for the same calls would drift apart, and their totals would match neither. """ from __future__ import annotations @@ -24,7 +25,7 @@ import httpx from agent_env.env.gateway.constants import CLOCK_WORK_MODE, EXT_CLOCK_URI, WORK_SECONDS_PER_CALL -from agent_env.task_step.context import StepContextError +from agent_env.task_step.context import AgentTurnInfraError, StepContextError logger = logging.getLogger(__name__) @@ -97,12 +98,21 @@ def one_work_mode_env(context, step: str) -> Optional[Any]: return envs[0] if envs else None +class WorkWindowError(AgentTurnInfraError): + """The agent's work window could not be opened, or, worse, closed: one left open would charge whoever calls with + its roles after the agent (a verifier's or collect_artifacts' header-less reads, for the default role) and move the + world on under the grading, so the run says nothing about the agent. An infrastructure failure, which a + retry_config can redo.""" + + @asynccontextmanager async def agent_work_window(context, step_id: str, roles: list[str]) -> AsyncIterator[Optional[str]]: """A work window naming ``roles`` held open on the env in work mode, if there is one, around the agent's work: - yields the window's id, or None with no env in work mode, or with work mode already ended there (logged). Closed - however the work ends; what it charged is recorded under ``context.metadata["work_windows"]``. A close that fails - is logged, not raised, so it never replaces the agent's own error. Refuses more than one env in work mode.""" + yields the window's id, or None with no env in work mode, or with work mode already ended there (409, logged). + Closed however the work ends, and what it charged recorded under ``context.metadata["work_windows"]``. Fails + closed: a close that still fails after a retry raises WorkWindowError once the agent's work is done; when the work + itself raised, that error stays the one raised, the close's failure logged and noted on it. Refuses more than one + env in work mode.""" env = one_work_mode_env(context, step_id) if env is None: yield None @@ -112,36 +122,55 @@ async def agent_work_window(context, step_id: str, roles: list[str]) -> AsyncIte await _window_call(env, "open_work_window", {"window": window, "roles": list(roles)}) except httpx.HTTPStatusError as e: if e.response.status_code != 409: - raise RuntimeError(f"env '{env.env_id}': opening the agent's work window failed (HTTP " - f"{e.response.status_code}): {e.response.text[:_MAX_ERROR_CHARS]}") from e + raise WorkWindowError(f"{step_id}: opening the agent's work window on env '{env.env_id}' failed (HTTP " + f"{e.response.status_code}): {e.response.text[:_MAX_ERROR_CHARS]}") from e logger.warning(f"{step_id}: env '{env.env_id}' refused the agent's work window " f"({e.response.text[:_MAX_ERROR_CHARS]}); the agent's work takes no task time") yield None return + except Exception as e: + raise WorkWindowError(f"{step_id}: opening the agent's work window on env '{env.env_id}' failed: " + f"{type(e).__name__}: {str(e)[:_MAX_ERROR_CHARS]}") from e try: yield window - finally: + except BaseException as error: try: - answer = await _window_call(env, "close_work_window", {"window": window}) - except Exception as e: - logger.warning(f"{step_id}: closing the agent's work window {window!r} on env '{env.env_id}' failed: " - f"{type(e).__name__}: {str(e)[:_MAX_ERROR_CHARS]}") - else: - mine = (answer or {}).get("window") or {} - context.metadata.setdefault(WORK_WINDOWS_KEY, []).append({ - "step_id": step_id, "env_id": env.env_id, "window": window, "roles": list(roles), - "calls": mine.get("calls", 0), "virtual_seconds": mine.get("virtual_seconds", 0.0)}) - if not ((answer or {}).get("work") or {}).get("on", True): - logger.warning(f"{step_id}: env '{env.env_id}' left work mode during the agent's work; the window " - "counts what it charged until then") + await _close_window(context, env, step_id, window, roles) + except WorkWindowError as close_error: + logger.error(str(close_error)) + error.add_note(str(close_error)) + raise + await _close_window(context, env, step_id, window, roles) + + +async def _close_window(context, env, step_id: str, window: str, roles: list[str]) -> None: + """Close ``window`` and record what it charged; WorkWindowError when it can't be closed, a retry included.""" + try: + answer = await _window_call(env, "close_work_window", {"window": window}) + except Exception as e: + detail = (f"HTTP {e.response.status_code}: {e.response.text[:_MAX_ERROR_CHARS]}" + if isinstance(e, httpx.HTTPStatusError) else f"{type(e).__name__}: {str(e)[:_MAX_ERROR_CHARS]}") + raise WorkWindowError(f"{step_id}: closing the agent's work window {window!r} on env '{env.env_id}' failed " + f"({detail}): it may still charge calls made after the agent, so the run is not " + "graded") from e + mine = (answer or {}).get("window") or {} + context.metadata.setdefault(WORK_WINDOWS_KEY, []).append({ + "step_id": step_id, "env_id": env.env_id, "window": window, "roles": list(roles), + "calls": mine.get("calls", 0), "virtual_seconds": mine.get("virtual_seconds", 0.0)}) + if not ((answer or {}).get("work") or {}).get("on", True): + logger.warning(f"{step_id}: env '{env.env_id}' left work mode during the agent's work; the window counts what " + "it charged until then") async def _window_call(env, method: str, params: dict) -> Any: - """A window call, made once more after a failure that isn't the gateway's answer: both are safe to repeat.""" + """A window call, made once more after a failure that isn't the gateway's own answer to it (a 4xx): both are safe + to repeat.""" try: return await env.invoke(EXT_CLOCK_URI, method, params, timeout=_WINDOW_TIMEOUT_S) - except httpx.HTTPStatusError: - raise + except httpx.HTTPStatusError as e: + if e.response.status_code < 500: + raise + logger.warning(f"{method} on env '{env.env_id}' failed (HTTP {e.response.status_code}); trying once more") except Exception as e: logger.warning(f"{method} on env '{env.env_id}' failed ({type(e).__name__}: {e}); trying once more") - return await env.invoke(EXT_CLOCK_URI, method, params, timeout=_WINDOW_TIMEOUT_S) + return await env.invoke(EXT_CLOCK_URI, method, params, timeout=_WINDOW_TIMEOUT_S) diff --git a/tst/unit/env/gateway/work_clock_test.py b/tst/unit/env/gateway/work_clock_test.py index e1fe7c82a..78c706df2 100644 --- a/tst/unit/env/gateway/work_clock_test.py +++ b/tst/unit/env/gateway/work_clock_test.py @@ -757,6 +757,33 @@ async def call(self, url, tool, arguments, meta, *, timeout): assert hold["still_running"] == [] +@pytest.mark.asyncio +async def test_a_deferred_call_due_at_a_later_task_time_doesnt_hold_the_call(gw): + gw._tool_server_urls["svc_schedule"] = "http://svc:8000/mcp" + posted: list[str] = [] + + class Sessions: + async def call(self, url, tool, arguments, meta, *, timeout): + if tool == "svc_schedule": + return CallToolResult(content=[TextContent(type="text", text="scheduled")], _meta={ + AGENT_ENV_DEFERRED_CALLS_META_KEY: [{ + "key": "post-1", "at": "2026-11-08T17:30:00Z", + "call": {"tool": "svc_post", "arguments": {}}, + "report_as": {"tool": "svc_post", "arguments": {}}}]}) + posted.append("posted") + return CallToolResult(content=[TextContent(type="text", text="posted")]) + gw._sessions = Sessions() + + async with _client(gw) as client: + await _working(client) + started = time.monotonic() + assert (await _call(client, "svc_schedule")).status_code == 200 + assert time.monotonic() - started < 2 and posted == [] + (hold,) = _logged(gw, "work_clock_hold") + assert hold["still_running"] == [] + await gw._deferred.cancel() + + @pytest.mark.asyncio async def test_a_fire_waiting_on_later_task_time_doesnt_hold_the_call(gw, monkeypatch): replies = _executor(monkeypatch, 0) @@ -816,6 +843,53 @@ async def executor(engine, ex, instruction, context_id): await gw._trigger_engine.cancel_scheduled() +@pytest.mark.asyncio +async def test_a_barriers_own_longer_timeout_is_the_calls_budget(gw, monkeypatch): + """A barrier given more time than HOLD_SECONDS gives the hold after it that long too: bob's reply, set going by + the same call, lands before the answer, though the barrier alone outlasted HOLD_SECONDS.""" + replies: list[str] = [] + + async def executor(engine, ex, instruction, context_id): + await asyncio.sleep(0.4 if instruction == "ack" else 0.6) + replies.append(instruction) + return "replied" + monkeypatch.setattr(TriggerEngine, "_call_executor", executor) + monkeypatch.setattr(gw_mod, "HOLD_SECONDS", 0.2) + gw._trigger_engine.register({ + "watch_roles": ["default"], "executors": {"bob": {"a2a_url": "http://bob", "role": "bob"}}, + "triggers": [{"id": "ack", "when": {"type": "action", "tool": "app_lookup"}, + "barrier": {"at": "provoking_call", "timeout_seconds": 2}, + "actions": [{"type": "nl", "executor": "bob", "instruction": "ack"}]}, + {"id": "reply", "when": {"type": "action", "tool": "app_lookup"}, + "actions": [{"type": "nl", "executor": "bob", "instruction": "reply"}]}]}) + async with _client(gw) as client: + await _working(client) + assert (await _call(client, "app_lookup")).status_code == 200 + assert sorted(replies) == ["ack", "reply"] + (hold,) = _logged(gw, "work_clock_hold") + assert hold["still_running"] == [] + + +@pytest.mark.asyncio +async def test_a_call_answered_after_its_window_closed_counts_in_a_retried_close(gw, monkeypatch): + """The window open when the call was answered counts its charge, even once closed: a close retried after answers + it (the turn's own close, made while the call waited on its barrier, came first).""" + _executor(monkeypatch, 0.4) + gw._trigger_engine.register({ + "watch_roles": ["default"], "executors": {"bob": {"a2a_url": "http://bob", "role": "bob"}}, + "triggers": [{"id": "ack", "when": {"type": "action", "tool": "app_lookup"}, + "barrier": {"at": "provoking_call"}, + "actions": [{"type": "nl", "executor": "bob", "instruction": "ack"}]}]}) + async with _client(gw) as client: + await _working(client) + call = asyncio.create_task(_call(client, "app_lookup")) + await asyncio.sleep(0.2) + first = (await _close(client)).json()["window"] + assert (await call).status_code == 200 + retried = (await _close(client)).json()["window"] + assert (first["calls"], retried["calls"], retried["virtual_seconds"]) == (0, 1, 60.0) + + @pytest.mark.asyncio async def test_a_call_cancelled_during_its_hold_still_leaves_its_charge_in_the_trajectory(gw, monkeypatch): _executor(monkeypatch, 5) @@ -837,3 +911,26 @@ async def test_a_call_cancelled_during_its_hold_still_leaves_its_charge_in_the_t (hold,) = _logged(gw, "work_clock_hold") assert (charge["tool"], charge["due"]) == ("app_lookup", ["sellout"]) assert hold["cancelled"] is True and hold["held_s"] >= 0.25 + + +@pytest.mark.asyncio +async def test_a_call_cancelled_again_while_its_hold_is_written_still_leaves_it(gw, monkeypatch): + """The hold's record waits on another event being written; a second cancel then doesn't drop it.""" + _executor(monkeypatch, 5) + async with _client(gw) as client: + await _arm(client) + _reply_at(gw) + await _work(client) + await _open(client) + task = asyncio.create_task(_mcp(gw, "app_lookup")) + await asyncio.sleep(0.3) + async with gw._event_lock: # another event being written + task.cancel() + await asyncio.sleep(0.05) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await asyncio.sleep(0.05) + await gw._trigger_engine.cancel_scheduled() + (hold,) = _logged(gw, "work_clock_hold") + assert hold["cancelled"] is True diff --git a/tst/unit/task_step/clock_mode_test.py b/tst/unit/task_step/clock_mode_test.py index 6063ba558..85f5ce759 100644 --- a/tst/unit/task_step/clock_mode_test.py +++ b/tst/unit/task_step/clock_mode_test.py @@ -16,8 +16,9 @@ from agent_env.env.gateway import gateway as gw_mod from agent_env.env.gateway.constants import AGENT_ENV_ROLE_HEADER, EXT_STEP_URI, WELL_KNOWN_PATH from agent_env.env.gateway.gateway import Gateway -from agent_env.task_step.context import DeployedAgent, StepContextError, TaskStepContext +from agent_env.task_step.context import AgentTurnInfraError, DeployedAgent, StepContextError, TaskStepContext from agent_env.task_step.task_steps import prompt_agent as pa_mod +from agent_env.task_step.task_steps.clock_mode import WorkWindowError from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep from agent_env.task_step.task_steps.set_env_clock_rate import SetEnvClockRateTaskStep from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep @@ -432,3 +433,117 @@ async def test_prompt_agent_refuses_more_than_one_env_in_work_mode(world, monkey with pytest.raises(StepContextError, match="work mode.*e1.*e2"): await _prompt().execute(context) assert sent == [] and not [p for _, p, _ in world.clock_calls() if p.startswith("/clock/work")] + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_opens_the_window_on_the_deployment_in_work_mode_only(world, monkeypatch): + """An env deployed twice: the clock step's deployment is in work mode, the other one isn't.""" + async def turn(): + await world.call(role="solver") + + _agent(monkeypatch, world, turn) + context = _with_agent(await world.context()) + other = await world.deployed() + other.metadata = {"deploy_step_id": "deploy-b"} + context.deployed_envs.append(other) + await _sync(clock_mode="work", env_step_id="deploy").execute(context) + world.forget() + + await _prompt().execute(context) + + assert [m for m, p, _ in world.clock_calls() if p == "/clock/work/window"] == ["PUT", "DELETE"] + (record,) = context.metadata["work_windows"] + assert (record["env_id"], record["calls"]) == ("e1", 1) + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_runs_without_a_window_when_work_mode_ended_outside_the_steps(world, monkeypatch): + """Work mode turned off at the gateway behind the clock steps' backs (a restarted gateway, say): the window is + refused (409), which is logged, and the agent still runs.""" + async def turn(): + await world.call(role="solver") + + sent = _agent(monkeypatch, world, turn) + context = _with_agent(await world.context()) + await _sync(clock_mode="work").execute(context) + async with world.http() as client: + await client.put("/clock/work", json={"on": False}) + + await _prompt().execute(context) + + assert sent and "work_windows" not in context.metadata + assert (await world.state())["virtual_time"] == T0 + + +def _close_fails(monkeypatch) -> list[str]: + """The gateway unreachable for the window's close: each try is returned.""" + tries: list[str] = [] + real = DeployedGatewayEnv.invoke + + async def invoke(self, uri, method, params=None, **kw): + if method == "close_work_window": + tries.append(method) + raise httpx.ConnectError("the gateway is gone") + return await real(self, uri, method, params, **kw) + monkeypatch.setattr(DeployedGatewayEnv, "invoke", invoke) + return tries + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_fails_as_infra_when_its_window_cant_be_closed(world, monkeypatch): + """A window left open would charge the verifier's and collect_artifacts' reads: the step fails closed.""" + async def turn(): + await world.call(role="solver") + + _agent(monkeypatch, world, turn) + context = _with_agent(await world.context()) + await _sync(clock_mode="work").execute(context) + tries = _close_fails(monkeypatch) + + with pytest.raises(WorkWindowError, match="closing the agent's work window") as failed: + await _prompt().execute(context) + assert isinstance(failed.value, AgentTurnInfraError) and tries == ["close_work_window"] * 2 + assert "work_windows" not in context.metadata + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_keeps_the_agents_own_error_when_its_window_cant_be_closed_either(world, monkeypatch): + async def turn(): + await world.call(role="solver") + raise RuntimeError("the agent's sandbox died") + + _agent(monkeypatch, world, turn) + context = _with_agent(await world.context()) + await _sync(clock_mode="work").execute(context) + _close_fails(monkeypatch) + + with pytest.raises(RuntimeError, match="sandbox died") as failed: + await _prompt().execute(context) + assert not isinstance(failed.value, WorkWindowError) + assert any("closing the agent's work window" in note for note in failed.value.__notes__) + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_fails_as_infra_before_the_agent_starts_when_its_window_cant_be_opened(world, monkeypatch): + async def turn(): + await world.call(role="solver") + + sent = _agent(monkeypatch, world, turn) + context = _with_agent(await world.context()) + await _sync(clock_mode="work").execute(context) + real = DeployedGatewayEnv.invoke + + async def invoke(self, uri, method, params=None, **kw): + if method == "open_work_window": + raise httpx.ConnectError("the gateway is gone") + return await real(self, uri, method, params, **kw) + monkeypatch.setattr(DeployedGatewayEnv, "invoke", invoke) + + with pytest.raises(WorkWindowError, match="opening the agent's work window"): + await _prompt().execute(context) + assert sent == [] diff --git a/tst/unit/task_step/test_always_on_work_clock.py b/tst/unit/task_step/test_always_on_work_clock.py index 3d9b41193..e7cf3fe2d 100644 --- a/tst/unit/task_step/test_always_on_work_clock.py +++ b/tst/unit/task_step/test_always_on_work_clock.py @@ -9,12 +9,15 @@ import asyncio from types import SimpleNamespace +import httpx import pytest from agent_env.env.env import DeployedGatewayEnv from agent_env.env.gateway.constants import EXT_CLOCK_URI, GATEWAY_EXTENSIONS, WELL_KNOWN_PATH from agent_env.env.gateway.triggers import TriggerEngine +from agent_env.task_step.context import AgentTurnInfraError from agent_env.task_step.task_steps import always_on as ao +from agent_env.task_step.task_steps.clock_mode import WorkWindowError from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep from tst.unit.task_step.always_on_harness import GATEWAY, ROLE, Rig @@ -232,6 +235,74 @@ async def agent(n, texts, rig): assert rig.now() == "2026-11-09T14:01:00Z" +@pytest.mark.asyncio +async def test_a_window_that_cant_be_closed_ends_the_run_as_an_infra_error(monkeypatch, tmp_path): + """Closing the turn's window is tried twice, 10 s each at most, so a struggling gateway can't stall the turn's + cleanup; a window still open would charge calls made after the turn, so the run fails rather than go on.""" + async def agent(n, texts, rig): + await rig.call("market_search") + rig.message("Chicago has 2 seats") + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "great"},)) + rig.tool("market_search") + ctx = rig.context() + await _work_mode(monkeypatch, rig, ctx) + tries: list[int] = [] + + class Struggling: + env_id = "world" + + async def invoke(self, uri, method, params=None, *, timeout): + tries.append(timeout) + raise httpx.ConnectError("the gateway is struggling") + real_call = ao._call + + async def call(env, uri, method, params=None, **kw): + return await real_call(Struggling() if method == "close_work_window" else env, uri, method, params, **kw) + monkeypatch.setattr(ao, "_call", call) + with pytest.raises(WorkWindowError, match="closing the agent's work window") as failed: + await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=2), ctx) + assert isinstance(failed.value, AgentTurnInfraError) + assert tries == [10, 10] + assert len(rig.events(ctx, "wake")) == 1 # no second wake on a window left open + (error,) = rig.events(ctx, "error") + assert "WorkWindowError" in error["error"] + + +@pytest.mark.asyncio +async def test_work_mode_ended_between_turns_is_found_at_the_next_window_at_once(monkeypatch, tmp_path): + """The gateway's refusal of the next turn's window (409) is its answer, not a failure to retry.""" + async def agent(n, texts, rig): + await rig.call("market_search") + if n == 1: + rig.message("checked") + else: + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "ok"},)) + rig.tool("market_search") + ctx = rig.context() + await _work_mode(monkeypatch, rig, ctx) + real_call = ao._call + + async def call(env, uri, method, params=None, **kw): + answer = await real_call(env, uri, method, params, **kw) + if method == "close_work_window": # behind the step's back, after the turn + async with rig.http() as client: + await client.put("/clock/work", json={"on": False}) + return answer + monkeypatch.setattr(ao, "_call", call) + started = asyncio.get_running_loop().time() + await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=2), ctx) + assert asyncio.get_running_loop().time() - started < 5 + (off,) = rig.events(ctx, "work_mode_off") + assert off["wake"] == 2 + first, second = rig.events(ctx, "agent_turn_end") + assert first["work"] == {"calls": 1, "virtual_seconds": 60.0} and "work" not in second + + @pytest.mark.asyncio async def test_the_judge_reads_what_each_wakes_work_took_its_nudge_included(monkeypatch, tmp_path): async def agent(n, texts, rig): From 970152f42833e3c8ea827f5596013bb82ce58b26 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Thu, 3 Dec 2026 19:03:20 -0800 Subject: [PATCH 4/9] refactor(gateway): name the clock mode "fixed", not "work" (FD-7183) The mode charges a fixed 60 s per answered tool call, so its public surface now says so, with no "work" alias (nothing is released yet): - clock_mode: "fixed"; the clock/v1 card method "fixed"; the route /clock/fixed (windows at /clock/fixed/window); the "fixed" block in /clock/state and in the mode's and windows' answers - trace events fixed_clock_charge, fixed_clock_hold, fixed_clock_skipped, fixed_clock_outside_window and fixed_mode_off; the run record's counts["fixed_clock"] and settings["clock"]["fixed"] - work_clock.py -> fixed_clock.py (FixedClock, FixedModeOff, parse_fixed_body), CLOCK_FIXED_MODE, CLOCK_FIXED_PATH, FIXED_SECONDS_PER_CALL, start_fixed, require_fixed, fixed_mode_envs; error messages, docstrings and AGENTS.md The agent's work window keeps its name (open_work_window, close_work_window, the work_window event, WorkWindowError), as does each turn's "work" field, since they describe the agent working, not the mode. No behaviour change; a test now shows "work" is refused as a clock_mode. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- src/agent_env/env/gateway/clock.py | 4 +- src/agent_env/env/gateway/constants.py | 18 +- src/agent_env/env/gateway/deferred_calls.py | 2 +- .../gateway/{work_clock.py => fixed_clock.py} | 36 +-- src/agent_env/env/gateway/gateway.py | 102 ++++----- src/agent_env/env/gateway/triggers.py | 4 +- .../task_step/task_steps/always_on.py | 90 ++++---- .../task_step/task_steps/clock_mode.py | 76 +++---- .../task_step/task_steps/prompt_agent.py | 6 +- .../task_steps/set_env_clock_rate.py | 14 +- .../task_step/task_steps/sync_env_clock.py | 12 +- tst/unit/env/gateway/clock_watch_test.py | 4 +- tst/unit/env/gateway/control_token_test.py | 2 +- ...ket_test.py => fixed_clock_socket_test.py} | 8 +- ...work_clock_test.py => fixed_clock_test.py} | 210 +++++++++--------- tst/unit/task_step/clock_mode_test.py | 154 ++++++------- ...clock.py => test_always_on_fixed_clock.py} | 82 +++---- 18 files changed, 413 insertions(+), 413 deletions(-) rename src/agent_env/env/gateway/{work_clock.py => fixed_clock.py} (86%) rename tst/unit/env/gateway/{work_clock_socket_test.py => fixed_clock_socket_test.py} (81%) rename tst/unit/env/gateway/{work_clock_test.py => fixed_clock_test.py} (86%) rename tst/unit/task_step/{test_always_on_work_clock.py => test_always_on_fixed_clock.py} (83%) diff --git a/AGENTS.md b/AGENTS.md index 6540534b6..9bb5d6d6b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,7 +191,7 @@ and deserialized through a registry. | Package | Contents | |---|---| -| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its work mode (`/clock/work`, `env/gateway/work_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "work"` on a clock at rate 0 and any later set_time, set_rate or clear turns off, ending every open window, moves the frozen clock on by a fixed `WORK_SECONDS_PER_CALL` (60 s, not configurable) for each answered tool call made while a work window naming its role is open (`/clock/work/window`, PUT to open with `roles`, DELETE to close, answering its totals; both control routes): prompt_agent opens one for its agent's role around its conversation and always_on one around each turn, nudges included (`task_steps/clock_mode.py` `agent_work_window`), each failing closed, as an infra error (`WorkWindowError`), when a window can't be closed, and both refuse more than one env in work mode, so a setup script, a verifier, collect_artifacts, a user sim, a contact or the agent between its turns is never charged, the agent's role outside its window logged as `work_clock_outside_window`. A charge, on the MCP path and the step API's `/step` paths (not a post-turn hook's that shows the control token; never the gateway's own `get_time` or `stay_quiet`), comes after the call's barriers (`Clock.advance_by`), then the answer is held until all world work runnable now has landed, every trigger fire at work and each deferred call the clock reached (`Gateway._settle_world`), but not a fire waiting on a later task time, the barriers and the hold sharing one budget; each charge is a `work_clock_charge` trajectory event and its hold a `work_clock_hold`, written even when the call is cancelled. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | +| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its fixed mode (`/clock/fixed`, `env/gateway/fixed_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "fixed"` on a clock at rate 0 and any later set_time, set_rate or clear turns off, ending every open window, moves the frozen clock on by a fixed `FIXED_SECONDS_PER_CALL` (60 s, not configurable) for each answered tool call made while a work window naming its role is open (`/clock/fixed/window`, PUT to open with `roles`, DELETE to close, answering its totals; both control routes): prompt_agent opens one for its agent's role around its conversation and always_on one around each turn, nudges included (`task_steps/clock_mode.py` `agent_work_window`), each failing closed, as an infra error (`WorkWindowError`), when a window can't be closed, and both refuse more than one env in fixed mode, so a setup script, a verifier, collect_artifacts, a user sim, a contact or the agent between its turns is never charged, the agent's role outside its window logged as `fixed_clock_outside_window`. A charge, on the MCP path and the step API's `/step` paths (not a post-turn hook's that shows the control token; never the gateway's own `get_time` or `stay_quiet`), comes after the call's barriers (`Clock.advance_by`), then the answer is held until all world work runnable now has landed, every trigger fire at work and each deferred call the clock reached (`Gateway._settle_world`), but not a fire waiting on a later task time, the barriers and the hold sharing one budget; each charge is a `fixed_clock_charge` trajectory event and its hold a `fixed_clock_hold`, written even when the call is cancelled. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | | `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, the `attempt_epoch` it was written under, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), each naming exactly what it was sent (`input`: a direct call's messages, response format and settings, an agent call's message, every file its step staged in the judge's sandbox and, for a judge the task deployed, what the task's own `load_artifact` steps put there as the run recorded it, stored by sha256 under `judge-inputs/` in the background, `judge_utils/judge_inputs.py`; the step waits for those uploads, at most 120 s, before it writes its grade, `VerifierTaskStep.settle`, and one that failed or hadn't finished is the call's `input_error`, never a failed grade), and its `verifier_settings` hold the trajectory source of each turn it read (`trajectory_sources`); with `judge_samples` (a count, as a step field, a run override or `--judge-samples` on `run`, `task run` and `eval run`), a rubric_binary or rubric_partial judge grades each criterion that many times, each a call of its own under `judge_batch_concurrency` (an agent judge the verifier deploys gets a deployment of its own per sample, its trajectory staged in each; the task's own judge takes every sample), and keeps its median, the lower middle score on a tie, which fails it, the row the first sample that scored it gave with every sample's score, verdict and justification in its `samples` and its `agreement`, the share of samples giving its verdict; a row under `min_judge_agreement` (0.5 by default, which never fails, so the median decides; 1.0 fails any split; set where `judge_samples` is, `--min-judge-agreement`) fails the grade, its rows kept, and then the step (`JudgeDisagreementError`), and `agent-env run` names the criteria a grade that stood split on (`samples split:`), and one failed sample fails the grade (a run's count or agreement a judge of another format can't take is recorded in `not_sent`) and the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`), each computer its own, a multi env's included, never the gateway's: its boot environment holds only the token's sha256 (`AGENTENV_CONTROL_TOKEN_SHA256`) when its probed card's computer/v1 says `control_token = "sha256"`, else, for a driver an older protocol built, the token itself (`AGENTENV_CONTROL_TOKEN`); the gateway learns each computer's (`CHILD_CONTROL_TOKENS`), puts it in place of its own on that computer's `/svc` routes, and lets a computer's token through only to that computer and its clock watch; a multi env's record grants each computer's `/svc` route its own token (`DeployedGatewayEnv.control_grants`, the longest granted address winning), and `CONTROL_TOKEN_CHILDREN`, the computers an older agent-env booted with the gateway's token, is kept for them; framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index 1b6bad9ea..cfee5c767 100644 --- a/src/agent_env/env/gateway/clock.py +++ b/src/agent_env/env/gateway/clock.py @@ -1,7 +1,7 @@ """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 and reads never -mutate it; work mode (work_clock.py) can also move it on by a fixed charge per agent tool call +mutate it; fixed mode (fixed_clock.py) can also move it on by a fixed charge per agent tool call (advance_by). Off by default: an unarmed clock 404s. """ from __future__ import annotations @@ -241,7 +241,7 @@ def advance(self, virtual_time: str) -> dict: 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: work mode's charge for one tool call, so calls charged at once each add theirs.""" + 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. diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index bc20e2c37..10aa149a1 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -98,13 +98,13 @@ 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 -# Work mode (clock/v1 work, work_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 WORK_SECONDS_PER_CALL for each tool call the agent makes inside a work window, which the +# 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 FIXED_SECONDS_PER_CALL for each tool call the agent makes inside a work window, which the # step running the agent opens for the agent's roles. Fixed in agent-env, the same for every task and every model. -CLOCK_WORK_MODE = "work" -WORK_SECONDS_PER_CALL = 60.0 -CLOCK_WORK_PATH = "/clock/work" -CLOCK_WORK_WINDOW_PATH = "/clock/work/window" +CLOCK_FIXED_MODE = "fixed" +FIXED_SECONDS_PER_CALL = 60.0 +CLOCK_FIXED_PATH = "/clock/fixed" +CLOCK_WORK_WINDOW_PATH = "/clock/fixed/window" # Env/gateway-level extensions the gateway itself owns (tool gating + triggers). EXT_DISABLE_TOOL_URI = "urn:agentenv:disable-tool/v1" @@ -237,7 +237,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_WORK_PATH, CLOCK_WORK_WINDOW_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// takes the control token for each, and anything under it, on a gateway that has one. @@ -311,7 +311,7 @@ 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; work turns work 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 a fixed " f"{WORK_SECONDS_PER_CALL:g}" " s (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 work block shows the mode, the windows open and its totals; 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 a fixed " f"{FIXED_SECONDS_PER_CALL:g}" " s (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, 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"]}}, @@ -319,7 +319,7 @@ def random_mcp_server_name() -> str: "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": {}}}, - "work": {"method": "PUT", "endpoint": CLOCK_WORK_PATH, "request": {"type": "object", "properties": {"on": {"type": "boolean"}}, "required": ["on"], "additionalProperties": False}}, + "fixed": {"method": "PUT", "endpoint": CLOCK_FIXED_PATH, "request": {"type": "object", "properties": {"on": {"type": "boolean"}}, "required": ["on"], "additionalProperties": False}}, "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"]}}, diff --git a/src/agent_env/env/gateway/deferred_calls.py b/src/agent_env/env/gateway/deferred_calls.py index ce42daa94..19d449a6d 100644 --- a/src/agent_env/env/gateway/deferred_calls.py +++ b/src/agent_env/env/gateway/deferred_calls.py @@ -69,7 +69,7 @@ def state(self) -> list[dict]: 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 - work-mode hold waits for, as ``state``'s ``due`` marks it (Gateway._settle_world).""" + 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 diff --git a/src/agent_env/env/gateway/work_clock.py b/src/agent_env/env/gateway/fixed_clock.py similarity index 86% rename from src/agent_env/env/gateway/work_clock.py rename to src/agent_env/env/gateway/fixed_clock.py index 2eacadf7a..e491bda26 100644 --- a/src/agent_env/env/gateway/work_clock.py +++ b/src/agent_env/env/gateway/fixed_clock.py @@ -1,8 +1,8 @@ -"""Work mode (urn:agentenv:clock/v1 ``work``, FD-7183): task time that passes as the agent works. +"""Fixed mode (urn:agentenv:clock/v1 ``fixed``, FD-7183): task time that passes as the agent works. A task whose clock is frozen (rate 0) lives through none of the agent's work otherwise: a turn takes no task time, and a -trigger due in the middle of one waits for the next. In work mode the clock stays frozen and the gateway moves it on by -``WORK_SECONDS_PER_CALL`` for each tool call the agent makes, once the call is answered, an error result included. +trigger due in the middle of one waits for the next. In fixed mode the clock stays frozen and the gateway moves it on by +``FIXED_SECONDS_PER_CALL`` for each tool call the agent makes, once the call is answered, an error result included. The gateway's own ``get_time`` and ``stay_quiet`` cost nothing. A call refused as disabled, or one that raised, costs nothing, and neither do model latency, thinking or retries, so every model sees the same world for the same work. @@ -11,9 +11,9 @@ charged only while a window naming its role is open. Every other caller, a setup script, a verifier, collect_artifacts, a user sim, a contact, a trigger's own tool action or a post-turn hook that shows the control token, is never charged, and neither is the agent's own call outside its window (a late call of a turn cut off), which the trajectory records as -``work_clock_outside_window``. +``fixed_clock_outside_window``. -The task's clock step turns the mode on (``sync_env_clock`` or ``set_env_clock_rate`` with ``clock_mode: "work"``), on +The task's clock step turns the mode on (``sync_env_clock`` or ``set_env_clock_rate`` with ``clock_mode: "fixed"``), on an armed clock at rate 0; any later set_time, set_rate or clear turns it off, ending every open window, so a task without clock_mode runs as it always has. The gateway charges a call with Clock.advance_by, through ``Gateway._change_clock``, then holds its answer until the world's work runnable now has landed (``Gateway._settle_world``: @@ -27,7 +27,7 @@ from typing import Any from .clock import ClockError -from .constants import WORK_SECONDS_PER_CALL +from .constants import FIXED_SECONDS_PER_CALL from .get_time import GET_TIME_TOOL_NAME from .user_chat import STAY_QUIET_TOOL_NAME @@ -39,8 +39,8 @@ CLOSED_KEPT = 64 -class WorkModeOff(ClockError): - """A window asked for while work mode is off (409).""" +class FixedModeOff(ClockError): + """A window asked for while fixed mode is off (409).""" class WindowConflict(ClockError): @@ -51,15 +51,15 @@ class NoSuchWindow(ClockError): """A close naming a window the gateway never opened, or no longer remembers (404).""" -def parse_work_body(body) -> bool: - """Whether a ``work`` request turns work mode on: a JSON object holding ``on``, true or false, and nothing else. +def parse_fixed_body(body) -> bool: + """Whether a ``fixed`` request turns fixed mode on: a JSON object holding ``on``, true or false, and nothing else. Raises ClockError for anything else.""" if not isinstance(body, dict): raise ClockError("body must be a JSON object") unknown = sorted(set(body) - {"on"}) if unknown: - raise ClockError(f"unknown work setting(s) {unknown}: work takes only 'on' (the charge per call is fixed at " - f"{WORK_SECONDS_PER_CALL:g} s)") + raise ClockError(f"unknown fixed mode setting(s) {unknown}: fixed takes only 'on' (the charge per call is fixed at " + f"{FIXED_SECONDS_PER_CALL:g} s)") if not isinstance(body.get("on"), bool): raise ClockError("on must be true or false") return body["on"] @@ -85,8 +85,8 @@ def parse_window_body(body, *, opening: bool) -> tuple[str, list[str]]: return window, list(dict.fromkeys(r.strip() for r in roles)) -class WorkClock: - """The gateway's work mode: whether it is on, the windows open (each the roles it charges and what it charged), +class FixedClock: + """The gateway's fixed mode: whether it is on, the windows open (each the roles it charges and what it charged), and what it has charged, in all and by role, since the gateway started.""" def __init__(self) -> None: @@ -107,9 +107,9 @@ def turn(self, on: bool) -> None: def open(self, window: str, roles: list[str]) -> dict: """Open ``window`` charging ``roles``; opening it again with the same roles answers it as it stands. Raises - WorkModeOff with the mode off, WindowConflict for an open one with other roles.""" + FixedModeOff with the mode off, WindowConflict for an open one with other roles.""" if not self.on: - raise WorkModeOff("work mode is off: the clock step turns it on (clock_mode 'work'), and set_time, " + raise FixedModeOff("fixed mode is off: the clock step turns it on (clock_mode 'fixed'), and set_time, " "set_rate or clear turn it off") mine = self._windows.get(window) if mine is not None: @@ -135,7 +135,7 @@ def cost(self, role: str, tool: str, native: bool) -> float | None: off, the gateway's own free tool (``native``), or no open window naming the role.""" if not self.on or (native and tool in FREE_TOOLS) or not self.windows_of(role): return None - return WORK_SECONDS_PER_CALL + return FIXED_SECONDS_PER_CALL def windows_of(self, role: str) -> list[str]: """The open windows that charge ``role``.""" @@ -163,7 +163,7 @@ def record(self, role: str, seconds: float, windows: list[str]) -> None: def state(self) -> dict: """Whether it is on, its charge per call, the windows open, then what it has charged (``calls``, ``virtual_seconds``), in all and by role.""" - return {"on": self.on, "seconds_per_call": WORK_SECONDS_PER_CALL, + return {"on": self.on, "seconds_per_call": FIXED_SECONDS_PER_CALL, "windows": [self._view(w, mine) for w, mine in self._windows.items()], "calls": self.calls, "virtual_seconds": round(self.virtual_seconds, 6), "by_role": {role: {"calls": t["calls"], "virtual_seconds": round(t["virtual_seconds"], 6)} diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 928d343e9..e8758b7e4 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -49,7 +49,7 @@ CHANGES_PAGE_DEFAULT, CLOCK_FOLLOWERS_PATH, CLOCK_WATCH_PATH, - CLOCK_WORK_PATH, + CLOCK_FIXED_PATH, CLOCK_WORK_WINDOW_PATH, CHANGES_PAGE_MAX, CHILD_DISCOVERY_TIMEOUT_S, @@ -119,8 +119,8 @@ from .notifications import CHECK_TOOL_NAMES, NotificationError, Notifications, build_check_tools from .user_chat import MESSAGE_USER_TOOL_NAME, UserChat, UserChatError, build_user_chat_tool from .user_chat import STAY_QUIET_TOOL_NAME, build_stay_quiet_tool -from .work_clock import ( - HOLD_SECONDS, NoSuchWindow, WindowConflict, WorkClock, WorkModeOff, parse_window_body, parse_work_body, +from .fixed_clock import ( + HOLD_SECONDS, NoSuchWindow, WindowConflict, FixedClock, FixedModeOff, parse_window_body, parse_fixed_body, ) logger = logging.getLogger(__name__) @@ -292,7 +292,7 @@ async def list_website_urls() -> list[str]: ) self._clock = Clock() self._clock_followers = ClockFollowers(lambda: self._clock, clock_followers or {}) - self._work_clock = WorkClock() + self._fixed_clock = FixedClock() self._notifications = Notifications(lambda: self._clock) self._user_chat = UserChat(lambda: self._clock) self._env_get_time_url_cache: str | None = None @@ -411,9 +411,9 @@ 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._out_of_work_mode(self._clock.set_time( + state = self._out_of_fixed_mode(self._clock.set_time( body.get("virtual_time"), body.get("virtual_seconds_per_real_second"), body.get("time_zone"))) - self._register_get_time_tool() # after: work mode is off even if this fails + self._register_get_time_tool() # after: fixed mode is off even if this fails return state return await self._clock_write(request, arm) @@ -421,7 +421,7 @@ def arm(body: dict) -> dict: @self._mcp.custom_route("/clock/set-rate", methods=["PUT"]) async def clock_set_rate(request: Request) -> Response: def rate(body: dict) -> dict: - return self._out_of_work_mode(self._clock.set_rate(body.get("virtual_seconds_per_real_second"))) + return self._out_of_fixed_mode(self._clock.set_rate(body.get("virtual_seconds_per_real_second"))) return await self._clock_write(request, rate) @@ -433,28 +433,28 @@ async def clock_advance(request: Request) -> Response: async def clock_clear(request: Request) -> Response: def disarm(body: dict) -> dict: self._unregister_get_time_tool() - return self._out_of_work_mode(self._clock.clear()) + return self._out_of_fixed_mode(self._clock.clear()) return await self._clock_write(request, disarm, body_optional=True) - @self._mcp.custom_route(CLOCK_WORK_PATH, methods=["PUT"]) - async def clock_work(request: Request) -> Response: + @self._mcp.custom_route(CLOCK_FIXED_PATH, methods=["PUT"]) + async def clock_fixed(request: Request) -> Response: # A mode, not a clock change: the clock's version stays, and no follower is waited for. try: body = await request.json() except Exception: return self._json_response({"ok": False, "error": "Invalid JSON body"}, 400) try: - on = parse_work_body(body) + on = parse_fixed_body(body) if on and not self._clock.armed: - raise ClockError("work mode moves the clock, which is not armed: set_time first") + raise ClockError("fixed mode moves the clock, which is not armed: set_time first") if on and self._clock.rate: - raise ClockError(f"work mode runs the clock at rate 0, and it runs at {self._clock.rate:g}: " + raise ClockError(f"fixed mode runs the clock at rate 0, and it runs at {self._clock.rate:g}: " "set_rate 0 first") except ClockError as e: return self._json_response({"ok": False, "error": str(e)}, 400) - self._work_clock.turn(on) - return self._json_response({"ok": True, "work": self._work_clock.state()}, 200) + self._fixed_clock.turn(on) + return self._json_response({"ok": True, "fixed": self._fixed_clock.state()}, 200) @self._mcp.custom_route(CLOCK_WORK_WINDOW_PATH, methods=["PUT"]) async def clock_open_work_window(request: Request) -> Response: @@ -509,7 +509,7 @@ async def clock_state(request: Request) -> Response: st = self._clock.state() if st.get("armed"): st["env_get_time_url"] = await self._env_get_time_url() - return self._json_response({**st, "work": self._work_clock.state(), + return self._json_response({**st, "fixed": self._fixed_clock.state(), "followers": self._clock_followers.state()}, 200) async def _notifications_write(request: Request, method) -> Response: @@ -889,72 +889,72 @@ async def _await_barriers(self, pending: list[asyncio.Task], timeout_s: float | except Exception: logger.exception("Awaiting trigger barriers failed (fail-open)") - def _out_of_work_mode(self, state: dict) -> dict: - """A set_time, set_rate or clear leaves work mode (work_clock.py), ending every window: the clock runs as that + def _out_of_fixed_mode(self, state: dict) -> dict: + """A set_time, set_rate or clear leaves fixed mode (fixed_clock.py), ending every window: the clock runs as that write set it.""" - self._work_clock.turn(False) + self._fixed_clock.turn(False) return state async def _work_window(self, request: Request, *, opening: bool) -> Response: - """Open (PUT) or close (DELETE) a work window (work_clock.py): 400 for a body it refuses, 409 for an open with - work mode off or an open window's id with other roles, 404 for a close naming no window; else 200 with the - window, what it charged so far, and the work block. Neither changes the clock or its version.""" + """Open (PUT) or close (DELETE) a work window (fixed_clock.py): 400 for a body it refuses, 409 for an open with + fixed mode off or an open window's id with other roles, 404 for a close naming no window; else 200 with the + window, what it charged so far, and the fixed block. Neither changes the clock or its version.""" try: body = await request.json() except Exception: return self._json_response({"ok": False, "error": "Invalid JSON body"}, 400) try: window, roles = parse_window_body(body, opening=opening) - mine = self._work_clock.open(window, roles) if opening else self._work_clock.close(window) - except (WorkModeOff, WindowConflict) as e: + mine = self._fixed_clock.open(window, roles) if opening else self._fixed_clock.close(window) + except (FixedModeOff, WindowConflict) as e: return self._json_response({"ok": False, "error": str(e)}, 409) except NoSuchWindow as e: return self._json_response({"ok": False, "error": str(e)}, 404) except ClockError as e: return self._json_response({"ok": False, "error": str(e)}, 400) - await self._log_event({"event_type": "work_window", "source": "work_clock", + await self._log_event({"event_type": "work_window", "source": "fixed_clock", "action": "open" if opening else "close", **mine}) - return self._json_response({"ok": True, "window": mine, "work": self._work_clock.state()}, 200) + return self._json_response({"ok": True, "window": mine, "fixed": self._fixed_clock.state()}, 200) async def _after_call(self, role: str, name: str, arguments: dict | None, result: Any, call_real_s: float, *, native: bool, free: bool = False, event_id: str | None = None) -> None: """What every answered external tool call goes through before its answer goes out (the MCP filter and both - /step handlers): its triggers fed, then its barriers waited for, and in work mode, for a call an open window - charges (work_clock.py), its charge and the hold, the barrier wait and the hold sharing one budget + /step handlers): its triggers fed, then its barriers waited for, and in fixed mode, for a call an open window + charges (fixed_clock.py), its charge and the hold, the barrier wait and the hold sharing one budget (HOLD_SECONDS, or a barrier's own longer timeout). ``free`` is a call never charged, a post-turn hook's that - showed the control token. An agent's call outside its windows is logged as ``work_clock_outside_window``.""" + showed the control token. An agent's call outside its windows is logged as ``fixed_clock_outside_window``.""" barrier_tasks, barrier_timeout_s = self._fire_triggers(role, name, arguments, result) seconds = None try: if not free: - seconds = self._work_clock.cost(role, name, native) - if seconds is None and self._work_clock.outside(role, name, native): - await self._log_event({"event_type": "work_clock_outside_window", "source": "work_clock", + seconds = self._fixed_clock.cost(role, name, native) + if seconds is None and self._fixed_clock.outside(role, name, native): + await self._log_event({"event_type": "fixed_clock_outside_window", "source": "fixed_clock", "tool": name, "role": role, **({"tool_call_event_id": event_id} if event_id else {})}) except Exception: - logger.exception(f"Work mode check for '{name}' failed (fail-open)") + logger.exception(f"Fixed mode check for '{name}' failed (fail-open)") seconds = None if seconds is None: await self._await_barriers(barrier_tasks, barrier_timeout_s) return - windows = self._work_clock.windows_of(role) + windows = self._fixed_clock.windows_of(role) budget = max(HOLD_SECONDS, barrier_timeout_s or self.TRIGGER_BARRIER_TIMEOUT_S) if barrier_tasks \ else HOLD_SECONDS deadline = asyncio.get_running_loop().time() + budget await self._await_barriers(barrier_tasks, barrier_timeout_s) - await self._charge_work(role, name, seconds, windows, call_real_s, deadline, event_id) + await self._charge_call(role, name, seconds, windows, call_real_s, deadline, event_id) - async def _charge_work(self, role: str, name: str, seconds: float, windows: list[str], call_real_s: float, + async def _charge_call(self, role: str, name: str, seconds: float, windows: list[str], call_real_s: float, deadline: float, event_id: str | None) -> None: - """Work mode's charge for an answered tool call (work_clock.py), made once its barriers have settled: the clock + """Fixed mode's charge for an answered tool call (fixed_clock.py), made once its barriers have settled: the clock moved on by ``seconds``, counted for ``role`` and its ``windows``, then the answer held until the world's work runnable now has landed, or the loop time ``deadline``. The trajectory records the charge before the hold - (``work_clock_charge``: the virtual time before and after, what came due, the windows, the call's own real - seconds), then the hold however it ends (``work_clock_hold``: how long, what was still at work, whether the - call was cancelled), or ``work_clock_skipped`` when the clock can't be moved. Fail-open: a charge that fails + (``fixed_clock_charge``: the virtual time before and after, what came due, the windows, the call's own real + seconds), then the hold however it ends (``fixed_clock_hold``: how long, what was still at work, whether the + call was cancelled), or ``fixed_clock_skipped`` when the clock can't be moved. Fail-open: a charge that fails never fails the call.""" - charge = {"source": "work_clock", "tool": name, "role": role, "seconds": seconds, + charge = {"source": "fixed_clock", "tool": name, "role": role, "seconds": seconds, **({"tool_call_event_id": event_id} if event_id else {})} try: moved: dict = {} @@ -970,21 +970,21 @@ def advance() -> dict: state, _ = await self._change_clock(advance) finally: if moved: # the clock moved, so it is counted even if what follows the advance raised - self._work_clock.record(role, seconds, windows) + self._fixed_clock.record(role, seconds, windows) except ClockError as e: - await self._log_event({"event_type": "work_clock_skipped", **charge, "reason": str(e)}) + await self._log_event({"event_type": "fixed_clock_skipped", **charge, "reason": str(e)}) return - await self._log_event({"event_type": "work_clock_charge", **charge, "windows": windows, + await self._log_event({"event_type": "fixed_clock_charge", **charge, "windows": windows, "virtual_time_before": _iso(moved["at"]), "virtual_time_after": state["virtual_time"], "due": list(state.get("due") or []), "call_real_s": round(call_real_s, 3)}) except Exception: - logger.exception(f"Work mode charge for '{name}' failed (fail-open)") + logger.exception(f"Fixed mode charge for '{name}' failed (fail-open)") return await self._hold(charge, deadline) async def _hold(self, charge: dict, deadline: float) -> None: """Hold a charged call's answer on ``_settle_world`` until ``deadline``, and record how it ended, a cancelled - call's included, as ``work_clock_hold``.""" + call's included, as ``fixed_clock_hold``.""" loop = asyncio.get_running_loop() started = loop.time() still: list[str] = [] @@ -992,27 +992,27 @@ async def _hold(self, charge: dict, deadline: float) -> None: try: still = await self._settle_world(deadline) if still: - logger.warning(f"work mode: {still} still at work after the hold's budget; answering the call") + logger.warning(f"fixed mode: {still} still at work after the hold's budget; answering the call") except asyncio.CancelledError: cancelled = True raise except Exception: - logger.exception(f"Work mode hold for '{charge['tool']}' failed (fail-open)") + logger.exception(f"Fixed mode hold for '{charge['tool']}' failed (fail-open)") finally: - event = {"event_type": "work_clock_hold", **charge, "held_s": round(loop.time() - started, 3), + event = {"event_type": "fixed_clock_hold", **charge, "held_s": round(loop.time() - started, 3), "still_running": still, "cancelled": cancelled} try: # shielded, so a call cancelled again while it is written still leaves its trace await asyncio.shield(self._log_event(event)) except asyncio.CancelledError: pass except Exception: - logger.exception("Logging a work mode hold failed") + logger.exception("Logging a fixed mode hold failed") async def _settle_world(self, deadline: float) -> list[str]: """Wait, until the loop time ``deadline``, for the world's work runnable now to end, as a settle reads it (prompt_agent's ``_is_settling``, DeferredCalls.state's ``due``): every trigger fire at work, bar one waiting on a task time still ahead, and every deferred call the clock has reached; whatever one of them sets going is - waited for in turn. The work clock keeps the clock frozen meanwhile, so no recurrence comes due again. What + waited for in turn. Fixed mode keeps the clock frozen meanwhile, so no recurrence comes due again. What was still at work when it gave up: trigger ids, then ``deferred:`` for deferred calls.""" loop = asyncio.get_running_loop() while True: diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index 348e84d1e..4c22f085a 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -63,7 +63,7 @@ _VIRTUAL_RECHECK_S = 5.0 # The clock's resolution: virtual times are microseconds. _VIRTUAL_RESOLUTION_S = 1e-6 -# Real seconds between looks at the work a work-mode hold waits for (Gateway._settle_world), to see a fire start +# Real seconds between looks at the work a fixed-mode hold waits for (Gateway._settle_world), to see a fire start # waiting on a later task time. _SETTLE_POLL_S = 0.02 # Seconds an executor call waits to connect, and for a task poll's answer. @@ -1192,7 +1192,7 @@ def clock_changed(self) -> None: def at_work(self) -> dict[str, list[asyncio.Task]]: """Each trigger with a fire at work now (``_at_work``: running, and not only waiting on a task time still - ahead), with its fire tasks: what work mode holds a charged call's answer on (Gateway._settle_world).""" + ahead), with its fire tasks: what fixed mode holds a charged call's answer on (Gateway._settle_world).""" return {tid: self._fire_tasks(trig) for tid, trig in self._triggers.items() if self._at_work(tid)} def _at_work(self, tid: str) -> bool: diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 2557359fc..be377df5f 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -34,17 +34,17 @@ time limit is the one it was registered with (register_env_triggers' ``executor_timeout_seconds``), and one trigger's replies run side by side (``contact_replies_in_parallel``). What comes due in the same minute wakes the agent once. -- When the task's clock is in work mode (sync_env_clock or set_env_clock_rate with ``clock_mode: "work"``, FD-7183), +- When the task's clock is in fixed mode (sync_env_clock or set_env_clock_rate with ``clock_mode: "fixed"``, FD-7183), task time passes as the agent works: the clock stays frozen and the gateway moves it on by a fixed charge for each tool call the agent makes inside its work window, so thinking and model latency cost nothing, and what that makes due lands before the call is answered. The step opens the window, naming the agent's role, around each of the agent's turns, nudges included, and closes it when the turn ends, so a user sim, a contact, a setup script or a verifier is never charged, nor the agent between its turns. Each turn's ``agent_turn_end`` (and ``nudge``) records what its work - took (``work``, the window's totals) beside the agent's ``output_tokens``, the record's ``counts["work_clock"]`` sums - it, ``settings["clock"]["work"]`` names the clock in work mode, and the judge reads each wake's, its nudge's included. - Work mode ended mid-run (a hook's set_rate, say) is logged once (``work_mode_off``) and no window is opened after. + took (``work``, the window's totals) beside the agent's ``output_tokens``, the record's ``counts["fixed_clock"]`` sums + it, ``settings["clock"]["fixed"]`` names the clock in fixed mode, and the judge reads each wake's, its nudge's included. + Fixed mode ended mid-run (a hook's set_rate, say) is logged once (``fixed_mode_off``) and no window is opened after. A window that can't be opened or closed ends the run as an infrastructure error (``WorkWindowError``): one left open - would charge calls made after the turn. More than one clock in work mode is refused at setup: their task times would + would charge calls made after the turn. More than one clock in fixed mode is refused at setup: their task times would drift apart. - The agent can schedule its own wake-ups (scheduled checks) when the run is multi-day, at least ``scheduled_check_min_interval`` apart; ``scheduled_checks`` turns them on or off whatever the run's length. A @@ -567,8 +567,8 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): self.folded: Optional[dict] = None self.clock: dict = {} # the task's clock rate, and whether the step freezes it between turns self.clock_rates: list[tuple[Any, float]] = [] # (env, the task's rate) for each clock the step freezes - self.work_env: Any = None # the clock in work mode, charging the agent's calls in its turns' windows - self.work_off = False # work mode ended there mid-run (logged once): no window is opened after + self.fixed_env: Any = None # the clock in fixed mode, charging the agent's calls in its turns' windows + self.fixed_off = False # fixed mode ended there mid-run (logged once): no window is opened after self.turn_window: Optional[str] = None # the work window of the turn in progress, while it is open self.turn_work: Optional[dict] = None # what the last turn's work cost: calls charged, task seconds self.work_total = {"calls": 0, "virtual_seconds": 0.0} @@ -830,14 +830,14 @@ async def _configure_clock(self) -> None: turns, so a slow contact reply or user sim read doesn't move the task's time. With clock/v1 ``set_rate``, which keeps the clock's marks (a re-arm with set_time, as sync_env_clock arms it, would re-anchor every relative or recurring time trigger); the task's rate is put back at the end. A clock already frozen (rate 0) - is left alone; a gateway without set_rate keeps running between turns, as the record says. A clock in work mode + is left alone; a gateway without set_rate keeps running between turns, as the record says. A clock in fixed mode (frozen, its gateway charging the agent's tool calls in its window) is the one each turn's window opens on - (``_configure_work``); more than one is refused, before any clock is touched.""" - envs, work = [], [] + (``_configure_fixed``); more than one is refused, before any clock is touched.""" + envs, fixed = [], [] for env in await self._armed(): state = await _call(env, EXT_CLOCK_URI, "state") - if (state.get("work") or {}).get("on"): - work.append((env, state["work"])) + if (state.get("fixed") or {}).get("on"): + fixed.append((env, state["fixed"])) rate = float(state.get("virtual_seconds_per_real_second") or 0) if rate <= 0: continue @@ -847,17 +847,17 @@ async def _configure_clock(self) -> None: continue self.clock_rates.append((env, rate)) envs.append({"env_id": env.env_id, "rate": rate, "frozen_between_turns": True}) - if len(work) > 1: + if len(fixed) > 1: self.clock_rates = [] - raise ValueError(f"always_on: work mode is on at more than one env's clock " - f"({', '.join(env.env_id for env, _ in work)}), each charged the agent's tool calls: their " - "task times would drift apart and no total would match either; put one clock in work mode") + raise ValueError(f"always_on: fixed mode is on at more than one env's clock " + f"({', '.join(env.env_id for env, _ in fixed)}), each charged the agent's tool calls: their " + "task times would drift apart and no total would match either; put one clock in fixed mode") if self.clock_rates: self.undo.append(("the clock's rate", lambda: self._clock_runs(True))) await self._clock_runs(False) self.clock = {"envs": envs} - if work: - self._configure_work(*work[0]) + if fixed: + self._configure_fixed(*fixed[0]) async def _clock_runs(self, running: bool) -> None: """Run each clock the step freezes at the task's rate (``running``), or freeze it.""" @@ -865,48 +865,48 @@ async def _clock_runs(self, running: bool) -> None: await _call(env, EXT_CLOCK_URI, "set_rate", {"virtual_seconds_per_real_second": rate if running else 0}, attempts=3) - def _configure_work(self, env, block: dict) -> None: - """The clock in work mode (``env``, its state's work block): the gateway charges the agent's tool calls while a - window naming its role is open (clock/v1 work, FD-7183), so each turn opens one and records what it charged.""" - self.work_env = env - self.clock["work"] = {"seconds_per_call": block.get("seconds_per_call"), "envs": [env.env_id]} + def _configure_fixed(self, env, block: dict) -> None: + """The clock in fixed mode (``env``, its state's fixed block): the gateway charges the agent's tool calls while a + window naming its role is open (clock/v1 fixed, FD-7183), so each turn opens one and records what it charged.""" + self.fixed_env = env + self.clock["fixed"] = {"seconds_per_call": block.get("seconds_per_call"), "envs": [env.env_id]} async def _open_window(self) -> None: - """Open the turn's work window, naming the agent's role, on the clock in work mode: ``turn_window``. Work mode + """Open the turn's work window, naming the agent's role, on the clock in fixed mode: ``turn_window``. Fixed mode ended there since (409) is logged once, and the turn's work takes no task time; another failure ends the run (WorkWindowError).""" - if self.work_env is None or self.work_off: + if self.fixed_env is None or self.fixed_off: return window = f"{self.step.id}:wake-{self.wakes}:{uuid.uuid4().hex[:8]}" try: - await _call(self.work_env, EXT_CLOCK_URI, "open_work_window", {"window": window, "roles": [self.recipient]}, + await _call(self.fixed_env, EXT_CLOCK_URI, "open_work_window", {"window": window, "roles": [self.recipient]}, answers=(409,)) except httpx.HTTPStatusError as e: if e.response.status_code != 409: raise WorkWindowError(f"always_on: wake {self.wakes}: opening the agent's work window on " - f"{self.work_env.env_id} failed (HTTP {e.response.status_code})") from e - self._work_mode_off() + f"{self.fixed_env.env_id} failed (HTTP {e.response.status_code})") from e + self._fixed_mode_off() return except Exception as e: raise WorkWindowError(f"always_on: wake {self.wakes}: opening the agent's work window on " - f"{self.work_env.env_id} failed: {type(e).__name__}: {e}") from e + f"{self.fixed_env.env_id} failed: {type(e).__name__}: {e}") from e self.turn_window = window async def _close_window(self, failed: Optional[BaseException] = None) -> None: """Close the turn's work window: what it charged, in ``turn_work`` and the run's ``work_total``. Within a short budget, so a struggling gateway can't stall the turn's cleanup. Fails closed: a window that can't be closed would charge whoever calls with the agent's role after the turn, so the run ends with WorkWindowError, the - turn's own error (``failed``) named in it; a run being cancelled stays cancelled, the failure logged. Work mode - found ended is logged once (``_work_mode_off``).""" + turn's own error (``failed``) named in it; a run being cancelled stays cancelled, the failure logged. Fixed mode + found ended is logged once (``_fixed_mode_off``).""" window, self.turn_window = self.turn_window, None if window is None: return try: - answer = await _call(self.work_env, EXT_CLOCK_URI, "close_work_window", {"window": window}, attempts=2, + answer = await _call(self.fixed_env, EXT_CLOCK_URI, "close_work_window", {"window": window}, attempts=2, timeout=10) or {} except Exception as e: error = WorkWindowError( - f"always_on: wake {self.wakes}: closing the agent's work window on {self.work_env.env_id} failed " + f"always_on: wake {self.wakes}: closing the agent's work window on {self.fixed_env.env_id} failed " f"({type(e).__name__}: {e}): it may still charge calls made after the turn, so the run is not graded" + (f"; the turn itself had failed ({type(failed).__name__}: {failed})" if failed is not None else "")) if isinstance(failed, asyncio.CancelledError): @@ -919,21 +919,21 @@ async def _close_window(self, failed: Optional[BaseException] = None) -> None: self.turn_work = work self.work_total = {"calls": self.work_total["calls"] + work["calls"], "virtual_seconds": round(self.work_total["virtual_seconds"] + work["virtual_seconds"], 3)} - if not (answer.get("work") or {}).get("on", True): - self._work_mode_off() + if not (answer.get("fixed") or {}).get("on", True): + self._fixed_mode_off() - def _work_mode_off(self) -> None: - """Work mode ended on the clock mid-run (a hook's set_rate, say): logged once, so the turns after report no + def _fixed_mode_off(self) -> None: + """Fixed mode ended on the clock mid-run (a hook's set_rate, say): logged once, so the turns after report no work rather than none done.""" - if not self.work_off: - self.work_off = True - self.log("work_mode_off", env_id=self.work_env.env_id, wake=self.wakes) - logger.warning(f"always_on: wake {self.wakes}: the clock of {self.work_env.env_id} left work mode; the " + if not self.fixed_off: + self.fixed_off = True + self.log("fixed_mode_off", env_id=self.fixed_env.env_id, wake=self.wakes) + logger.warning(f"always_on: wake {self.wakes}: the clock of {self.fixed_env.env_id} left fixed mode; the " "agent's work takes no task time from here") async def _agent_turn(self, parts: list[dict], msg_id: str, record) -> AgentTurn: """One turn of the agent on ``parts``: the task's clock runs at its rate while the agent works, and is frozen - again after; a clock in work mode stays frozen, moved on by the agent's tool calls inside the turn's work + again after; a clock in fixed mode stays frozen, moved on by the agent's tool calls inside the turn's work window, closed once the clock is frozen, and what they took is read from it. The turn's usage is recorded as its reply arrives, before the clock is frozen. The agent's task id for the turn is ``turn_task_id`` once it accepts the message.""" @@ -1765,7 +1765,7 @@ def _kept_parts(self, parts: list[dict]) -> list[dict]: return kept def _work_fields(self, term: Optional[protocol.TerminalResponse] = None) -> dict: - """What a turn's end records of its cost: the output tokens its agent reported, and with a clock in work mode what + """What a turn's end records of its cost: the output tokens its agent reported, and with a clock in fixed mode what its work took (``work``: calls charged, task seconds).""" tokens = term.usage.output_tokens if term is not None and term.usage is not None else None return {**({"output_tokens": tokens} if tokens is not None else {}), @@ -2255,8 +2255,8 @@ async def finish(self) -> None: and e.get("stay_quiet_calls")) if step.continue_after_wake_limit: counts["cut_off_wakes"] = len(self.cut_offs) - if self.work_env is not None: - counts["work_clock"] = dict(self.work_total) # the agent's tool calls charged, and the task time they took + if self.fixed_env is not None: + counts["fixed_clock"] = dict(self.work_total) # the agent's tool calls charged, and the task time they took record = {"step_id": step.id, "end_reason": self.end_reason, "end_note": self.end_note, "reached_scheduled_end": self.end_reason in SCHEDULED_ENDS, "error": self.error, "error_type": self.error_type, "error_code": self.error_code, "counts": counts, diff --git a/src/agent_env/task_step/task_steps/clock_mode.py b/src/agent_env/task_step/task_steps/clock_mode.py index 161155c4f..6accb6d4f 100644 --- a/src/agent_env/task_step/task_steps/clock_mode.py +++ b/src/agent_env/task_step/task_steps/clock_mode.py @@ -1,18 +1,18 @@ """The clock setup steps' ``clock_mode`` (sync_env_clock, set_env_clock_rate), and the work window the steps that run the agent open in it, FD-7183. -Unset, the default, the clock runs at the step's rate, as it always has. ``"work"`` is work mode: the clock is frozen +Unset, the default, the clock runs at the step's rate, as it always has. ``"fixed"`` is fixed mode: the clock is frozen (rate 0) and the gateway moves it on by a fixed charge for each tool call the agent makes inside a work window (clock/v1 -``work``, ``agent_env.env.gateway.work_clock``), so the agent's work takes task time and thinking or model latency take +``fixed``, ``agent_env.env.gateway.fixed_clock``), so the agent's work takes task time and thinking or model latency take none. A rate other than 0 with it is an error. A later set_time or set_rate without it (sync_env_clock, or -set_env_clock_rate to 0 after the agent's last prompt_agent) leaves work mode. +set_env_clock_rate to 0 after the agent's last prompt_agent) leaves fixed mode. The clock step only turns the mode on; who the agent is, the step that runs it says. prompt_agent opens a window for its agent's role around its conversation (``agent_work_window``) and always_on one around each of the agent's turns, so a setup script, a verifier, collect_artifacts or a user sim calling the same gateway before, between or after is never charged. A window that can't be closed fails the step as an infrastructure error (``WorkWindowError``), since it -would charge whoever calls after. Which env is in work mode the run's ``clock_configurations`` say -(``work_mode_envs``), so a task that never names the mode makes no window call at all. One env in work mode at most: two clocks charged for the same calls would +would charge whoever calls after. Which env is in fixed mode the run's ``clock_configurations`` say +(``fixed_mode_envs``), so a task that never names the mode makes no window call at all. One env in fixed mode at most: two clocks charged for the same calls would drift apart, and their totals would match neither. """ from __future__ import annotations @@ -24,56 +24,56 @@ import httpx -from agent_env.env.gateway.constants import CLOCK_WORK_MODE, EXT_CLOCK_URI, WORK_SECONDS_PER_CALL +from agent_env.env.gateway.constants import CLOCK_FIXED_MODE, EXT_CLOCK_URI, FIXED_SECONDS_PER_CALL from agent_env.task_step.context import AgentTurnInfraError, StepContextError logger = logging.getLogger(__name__) -CLOCK_MODES = (CLOCK_WORK_MODE,) -WORK_METHODS = ("work", "open_work_window", "close_work_window") +CLOCK_MODES = (CLOCK_FIXED_MODE,) +FIXED_METHODS = ("fixed", "open_work_window", "close_work_window") WORK_WINDOWS_KEY = "work_windows" # context.metadata: each window a step opened, with what it charged _WINDOW_TIMEOUT_S = 30 _MAX_ERROR_CHARS = 300 def clock_mode_rate(step_type: str, clock_mode: Any, rate: Any, default: Optional[float]) -> Any: - """The rate a clock step runs the clock at: ``rate``, or when it is None, 0 in work mode and else ``default``. - Raises ValueError for a clock_mode other than None or ``"work"``, and for work mode with a rate other than 0.""" + """The rate a clock step runs the clock at: ``rate``, or when it is None, 0 in fixed mode and else ``default``. + Raises ValueError for a clock_mode other than None or ``"fixed"``, and for fixed mode with a rate other than 0.""" if clock_mode is not None and (not isinstance(clock_mode, str) or clock_mode not in CLOCK_MODES): raise ValueError(f"{step_type}: clock_mode must be {' or '.join(repr(m) for m in CLOCK_MODES)}, or left out " f"for a clock that runs at its rate; got {clock_mode!r}") if rate is None: - return 0 if clock_mode == CLOCK_WORK_MODE else default - if clock_mode == CLOCK_WORK_MODE and (isinstance(rate, bool) or not isinstance(rate, (int, float)) or rate != 0): - raise ValueError(f"{step_type}: clock_mode 'work' runs the clock at rate 0, moving it on " - f"{WORK_SECONDS_PER_CALL:g} s for each of the agent's tool calls; got " + return 0 if clock_mode == CLOCK_FIXED_MODE else default + if clock_mode == CLOCK_FIXED_MODE and (isinstance(rate, bool) or not isinstance(rate, (int, float)) or rate != 0): + raise ValueError(f"{step_type}: clock_mode 'fixed' runs the clock at rate 0, moving it on " + f"{FIXED_SECONDS_PER_CALL:g} s for each of the agent's tool calls; got " f"virtual_seconds_per_real_second={rate!r}: leave it out or set 0") return rate -def require_work(deployed, env_id: str) -> None: - """Refuse, before the clock is touched, work mode on a gateway whose stored card offers no clock/v1 work or work +def require_fixed(deployed, env_id: str) -> None: + """Refuse, before the clock is touched, fixed mode on a gateway whose stored card offers no clock/v1 fixed or work windows. A record that kept no card is left to the clock call, which says so.""" - missing = [m for m in WORK_METHODS if not deployed.supports(EXT_CLOCK_URI, m)] if deployed.environment_card else [] + missing = [m for m in FIXED_METHODS if not deployed.supports(EXT_CLOCK_URI, m)] if deployed.environment_card else [] if missing: - raise StepContextError(f"env '{env_id}': clock_mode 'work' needs its gateway's {EXT_CLOCK_URI} " + raise StepContextError(f"env '{env_id}': clock_mode 'fixed' needs its gateway's {EXT_CLOCK_URI} " f"{', '.join(missing)}, which its card does not offer; put the gateway env again " "(agent-env env gateway put) and redeploy") -async def start_work(deployed, env_id: str, timeout: int) -> dict: - """Turn work mode on at ``deployed``'s gateway, its clock armed at rate 0; the gateway's work block.""" +async def start_fixed(deployed, env_id: str, timeout: int) -> dict: + """Turn fixed mode on at ``deployed``'s gateway, its clock armed at rate 0; the gateway's fixed block.""" try: - answer = await deployed.invoke(EXT_CLOCK_URI, "work", {"on": True}, timeout=timeout) + answer = await deployed.invoke(EXT_CLOCK_URI, "fixed", {"on": True}, timeout=timeout) except httpx.HTTPStatusError as e: - raise RuntimeError(f"env '{env_id}': turning work mode on failed (HTTP {e.response.status_code}): " + raise RuntimeError(f"env '{env_id}': turning fixed mode on failed (HTTP {e.response.status_code}): " f"{e.response.text[:_MAX_ERROR_CHARS]}") from e - return (answer or {}).get("work") or {} + return (answer or {}).get("fixed") or {} -def work_mode_envs(context) -> list: - """The deployed envs whose clock the run left in work mode: those whose latest clock step, by env and deployment, - put it there (``clock_mode: "work"``). A clock step's record that names no deployment counts for every deployment +def fixed_mode_envs(context) -> list: + """The deployed envs whose clock the run left in fixed mode: those whose latest clock step, by env and deployment, + put it there (``clock_mode: "fixed"``). A clock step's record that names no deployment counts for every deployment of its env.""" configurations = context.metadata.get("clock_configurations") or [] envs = [] @@ -83,18 +83,18 @@ def work_mode_envs(context) -> list: for c in configurations: if c.get("env_id") == deployed.env_id and c.get("deploy_step_id") in (None, step): latest = c - if latest is not None and latest.get("clock_mode") == CLOCK_WORK_MODE: + if latest is not None and latest.get("clock_mode") == CLOCK_FIXED_MODE: envs.append(deployed) return envs -def one_work_mode_env(context, step: str) -> Optional[Any]: - """The deployed env in work mode, or None; StepContextError for more than one.""" - envs = work_mode_envs(context) +def one_fixed_mode_env(context, step: str) -> Optional[Any]: + """The deployed env in fixed mode, or None; StepContextError for more than one.""" + envs = fixed_mode_envs(context) if len(envs) > 1: - raise StepContextError(f"{step}: work mode is on at more than one env's clock " + raise StepContextError(f"{step}: fixed mode is on at more than one env's clock " f"({', '.join(e.env_id for e in envs)}), each charged the agent's tool calls: their task " - "times would drift apart and no total would match either; put one clock in work mode") + "times would drift apart and no total would match either; put one clock in fixed mode") return envs[0] if envs else None @@ -107,13 +107,13 @@ class WorkWindowError(AgentTurnInfraError): @asynccontextmanager async def agent_work_window(context, step_id: str, roles: list[str]) -> AsyncIterator[Optional[str]]: - """A work window naming ``roles`` held open on the env in work mode, if there is one, around the agent's work: - yields the window's id, or None with no env in work mode, or with work mode already ended there (409, logged). + """A work window naming ``roles`` held open on the env in fixed mode, if there is one, around the agent's work: + yields the window's id, or None with no env in fixed mode, or with fixed mode already ended there (409, logged). Closed however the work ends, and what it charged recorded under ``context.metadata["work_windows"]``. Fails closed: a close that still fails after a retry raises WorkWindowError once the agent's work is done; when the work itself raised, that error stays the one raised, the close's failure logged and noted on it. Refuses more than one - env in work mode.""" - env = one_work_mode_env(context, step_id) + env in fixed mode.""" + env = one_fixed_mode_env(context, step_id) if env is None: yield None return @@ -157,8 +157,8 @@ async def _close_window(context, env, step_id: str, window: str, roles: list[str context.metadata.setdefault(WORK_WINDOWS_KEY, []).append({ "step_id": step_id, "env_id": env.env_id, "window": window, "roles": list(roles), "calls": mine.get("calls", 0), "virtual_seconds": mine.get("virtual_seconds", 0.0)}) - if not ((answer or {}).get("work") or {}).get("on", True): - logger.warning(f"{step_id}: env '{env.env_id}' left work mode during the agent's work; the window counts what " + if not ((answer or {}).get("fixed") or {}).get("on", True): + logger.warning(f"{step_id}: env '{env.env_id}' left fixed mode during the agent's work; the window counts what " "it charged until then") diff --git a/src/agent_env/task_step/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py index dbebd728c..69a0e8dba 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -51,7 +51,7 @@ from agent_env.entity.refs import EntityRef from agent_env.entity.scopes import FieldScope from agent_env.task_step.task_step import RetryConfig, StepRole, TaskStep, TaskStepDependency -from agent_env.task_step.task_steps.clock_mode import agent_work_window, one_work_mode_env +from agent_env.task_step.task_steps.clock_mode import agent_work_window, one_fixed_mode_env from agent_env.task_step.task_steps.notification_delivery import delivered_parts, labels_zone, next_message, take_due from agent_env.task_step.task_steps.post_turn_hooks import PostTurnHooks, run_post_turn_hooks, validate_hook_specs from agent_env.task_step.task_steps.server_fault_logs import capture_server_fault_logs @@ -515,7 +515,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: async def _execute(self, context: TaskStepContext) -> TaskStepContext: # Refused here (always_on has its own), so a bad setting leaves no conversation, capture or model call. self._built_in_user_sim(context) - one_work_mode_env(context, f"prompt_agent '{self.id}'") + one_fixed_mode_env(context, f"prompt_agent '{self.id}'") # Minted here, not in `_execute_conversation`, so the series can address the # same session before the first turn. a2a_context_id = self.context_id or uuid.uuid4().hex @@ -552,7 +552,7 @@ async def _execute_conversation( ) -> TaskStepContext: hooks = await PostTurnHooks.load(self.post_turn_hooks, self.id) if self.post_turn_hooks else None agent = next((a for a in context.deployed_agents if a.agent_name == self.agent_name), None) - # In work mode, the agent's calls are charged only while its window is open: none before or after (clock_mode). + # In fixed mode, the agent's calls are charged only while its window is open: none before or after (clock_mode). window = agent_work_window(context, self.id, [agent.role or DEFAULT_ROLE]) if agent else nullcontext() try: async with window: diff --git a/src/agent_env/task_step/task_steps/set_env_clock_rate.py b/src/agent_env/task_step/task_steps/set_env_clock_rate.py index f58093e9b..cdb8112c8 100644 --- a/src/agent_env/task_step/task_steps/set_env_clock_rate.py +++ b/src/agent_env/task_step/task_steps/set_env_clock_rate.py @@ -5,10 +5,10 @@ prompt_agent, so verifiers read a world that no longer moves on its clock. ``env_step_id`` names the deploy_env step whose deployment's clock to change when the env is deployed more than once. -With clock_mode "work" (``clock_mode.py``) as the step that starts the clock before prompt_agent, the rate is 0, its -default in that mode (any other is an error), and the gateway's work mode is turned on, so each tool call the agent +With clock_mode "fixed" (``clock_mode.py``) as the step that starts the clock before prompt_agent, the rate is 0, its +default in that mode (any other is an error), and the gateway's fixed mode is turned on, so each tool call the agent makes inside its work window (prompt_agent's, always_on's) moves task time on by a fixed charge. Without it, the rate -set leaves work mode, ending any window open, so a rate of 0 after the agent's last prompt_agent stops the clock for +set leaves fixed mode, ending any window open, so a rate of 0 after the agent's last prompt_agent stops the clock for verifiers in either mode. """ @@ -23,7 +23,7 @@ from agent_env.env.gateway.constants import EXT_CLOCK_URI from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.task_step.task_step import TaskStep, TaskStepDependency -from agent_env.task_step.task_steps.clock_mode import clock_mode_rate, require_work, start_work +from agent_env.task_step.task_steps.clock_mode import clock_mode_rate, require_fixed, start_fixed from agent_env.task_step.task_steps.deploy_agent import _deploy_step_of, bound_deployment logger = logging.getLogger(__name__) @@ -92,7 +92,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: if deployed is None: raise StepContextError(f"Env '{self.env_id}' not found in context.deployed_envs") if self.clock_mode is not None: - require_work(deployed, self.env_id) + require_fixed(deployed, self.env_id) try: state = await deployed.invoke(EXT_CLOCK_URI, "set_rate", {"virtual_seconds_per_real_second": self.virtual_seconds_per_real_second}, @@ -104,11 +104,11 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: "virtual_seconds_per_real_second": self.virtual_seconds_per_real_second, "virtual_time": state.get("virtual_time"), } - if self.clock_mode is not None or self.env_step_id: # the deployment it names, for work_mode_envs + if self.clock_mode is not None or self.env_step_id: # the deployment it names, for fixed_mode_envs configuration["deploy_step_id"] = _deploy_step_of(deployed) if self.clock_mode is not None: configuration.update(clock_mode=self.clock_mode, - work=await start_work(deployed, self.env_id, self.timeout_seconds)) + fixed=await start_fixed(deployed, self.env_id, self.timeout_seconds)) context.metadata.setdefault("clock_configurations", []).append(configuration) mode = f" in {self.clock_mode} mode" if self.clock_mode else "" logger.info(f"set_env_clock_rate env={self.env_id}: rate={self.virtual_seconds_per_real_second}{mode} " diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index 1be15b3ac..29ff489d1 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -13,7 +13,7 @@ Non-advertisers are skipped when tolerate_missing_sync_time (default True), and websites always. Place right before prompt_agent so the virtual timeline starts at agent-start; when setup needs the clock armed, arm it at rate 0 and start it with set_env_clock_rate right before prompt_agent. -With clock_mode "work" (``clock_mode.py``), the clock is armed frozen and the gateway's work mode turned on, so each +With clock_mode "fixed" (``clock_mode.py``), the clock is armed frozen and the gateway's fixed mode turned on, so each tool call the agent makes inside its work window (prompt_agent's, always_on's) moves task time on by a fixed charge; a nonzero rate with it is an error. """ @@ -35,7 +35,7 @@ from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.entity.refs import EntityRef from agent_env.task_step.task_step import TaskStep, TaskStepDependency -from agent_env.task_step.task_steps.clock_mode import clock_mode_rate, require_work, start_work +from agent_env.task_step.task_steps.clock_mode import clock_mode_rate, require_fixed, start_fixed from agent_env.task_step.task_steps.deploy_agent import bound_deployment if TYPE_CHECKING: @@ -94,7 +94,7 @@ def __init__( """virtual_seconds_per_real_second = clock speed (1.0 real time, the default, 0 frozen, 86400 cap = 1 real s -> 1 virtual day). For ~V virtual seconds over an ~R-real-second task, pass V/R. - clock_mode = unset, the default, for a clock that runs at its rate, as it always has; "work" for work mode: the + clock_mode = unset, the default, for a clock that runs at its rate, as it always has; "fixed" for fixed mode: the clock frozen (rate 0, the rate's default in it; any other rate is an error) and moved on by a fixed charge for each tool call the agent makes inside the work window the step running it opens (``clock_mode.py``). @@ -170,7 +170,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: if deployed is None: raise StepContextError(f"Env '{self.env_id}' not found in context.deployed_envs") if self.clock_mode is not None: - require_work(deployed, self.env_id) + require_fixed(deployed, self.env_id) 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, @@ -187,7 +187,7 @@ 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") - work = await start_work(deployed, self.env_id, self.timeout_seconds) if self.clock_mode is not None else None + fixed = await start_fixed(deployed, self.env_id, self.timeout_seconds) if self.clock_mode is not None else None 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 " @@ -219,7 +219,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: configuration.update(timezone=self.timezone, armed_at=self.armed_virtual_time, get_time_zone=state.get("time_zone")) if self.clock_mode is not None: - configuration.update(clock_mode=self.clock_mode, work=work) + configuration.update(clock_mode=self.clock_mode, fixed=fixed) context.metadata.setdefault("clock_configurations", []).append(configuration) mode = f" in {self.clock_mode} mode" if self.clock_mode else "" logger.info(f"sync_env_clock env={self.env_id}: armed rate={self.virtual_seconds_per_real_second}{mode}; " diff --git a/tst/unit/env/gateway/clock_watch_test.py b/tst/unit/env/gateway/clock_watch_test.py index 1602aaa2c..8a88da2ba 100644 --- a/tst/unit/env/gateway/clock_watch_test.py +++ b/tst/unit/env/gateway/clock_watch_test.py @@ -80,8 +80,8 @@ def test_the_card_offers_every_clock_method_with_the_waits_bound_and_the_watchs_ assert {name: (m["method"], m["endpoint"]) for name, m in methods.items()} == { "get_time": ("GET", "/clock/time"), "set_time": ("PUT", "/clock/set-time"), "set_rate": ("PUT", "/clock/set-rate"), "advance": ("PUT", "/clock/advance"), "clear": ("POST", "/clock/clear"), "state": ("GET", "/clock/state"), - "work": ("PUT", "/clock/work"), "open_work_window": ("PUT", "/clock/work/window"), - "close_work_window": ("DELETE", "/clock/work/window"), "declare_follower": ("PUT", "/clock/followers"), "retire_follower": ("DELETE", "/clock/followers"), + "fixed": ("PUT", "/clock/fixed"), "open_work_window": ("PUT", "/clock/fixed/window"), + "close_work_window": ("DELETE", "/clock/fixed/window"), "declare_follower": ("PUT", "/clock/followers"), "retire_follower": ("DELETE", "/clock/followers"), "watch": ("GET", "/clock/watch")} assert all(methods[name]["request"]["properties"]["wait_followers_s"] == wait for name in ("set_time", "set_rate", "advance", "clear")) diff --git a/tst/unit/env/gateway/control_token_test.py b/tst/unit/env/gateway/control_token_test.py index fcfe69e5d..17357a9c0 100644 --- a/tst/unit/env/gateway/control_token_test.py +++ b/tst/unit/env/gateway/control_token_test.py @@ -24,7 +24,7 @@ "/tools/disable": "POST", "/tools/enable": "POST", "/triggers/register": "POST", "/triggers/remove": "POST", "/triggers/clear": "POST", "/notifications/config": "POST", "/notifications/take": "POST", "/notifications/clear": "POST", - "/clock/followers": "PUT", "/clock/work": "PUT", "/clock/work/window": "PUT", + "/clock/followers": "PUT", "/clock/fixed": "PUT", "/clock/fixed/window": "PUT", } OPEN = {"/state": "GET", "/step": "POST", "/clock/time": "GET", "/clock/state": "GET", "/triggers/state": "GET", "/notifications/state": "GET", "/trajectory": "GET", "/changes": "GET", "/.well-known/agent-env.json": "GET", diff --git a/tst/unit/env/gateway/work_clock_socket_test.py b/tst/unit/env/gateway/fixed_clock_socket_test.py similarity index 81% rename from tst/unit/env/gateway/work_clock_socket_test.py rename to tst/unit/env/gateway/fixed_clock_socket_test.py index 62c915c3f..d17a4d06f 100644 --- a/tst/unit/env/gateway/work_clock_socket_test.py +++ b/tst/unit/env/gateway/fixed_clock_socket_test.py @@ -1,4 +1,4 @@ -"""Work mode (FD-7183) over real loopback sockets: an agent's MCP client that sends its AgentEnv-Role header over +"""Fixed mode (FD-7183) over real loopback sockets: an agent's MCP client that sends its AgentEnv-Role header over streamable HTTP is the role its work window names, so its calls are charged, and another role's are not.""" from __future__ import annotations @@ -35,8 +35,8 @@ def app_lookup() -> str: async with httpx.AsyncClient(base_url=url) as http: r = await http.put("/clock/set-time", json={"virtual_time": T0, "virtual_seconds_per_real_second": 0}) assert r.status_code == 200, r.text - assert (await http.put("/clock/work", json={"on": True})).status_code == 200 - r = await http.put("/clock/work/window", json={"window": "turn-1", "roles": ["solver"]}) + assert (await http.put("/clock/fixed", json={"on": True})).status_code == 200 + r = await http.put("/clock/fixed/window", json={"window": "turn-1", "roles": ["solver"]}) assert r.status_code == 200, r.text async with _client(url, "solver") as solver, _client(url, "verifier") as verifier: @@ -44,6 +44,6 @@ def app_lookup() -> str: assert not (await verifier.call_tool("app_lookup", {})).isError state = (await http.get("/clock/state")).json() assert state["virtual_time"] == "2026-11-08T17:01:00Z" - assert state["work"]["by_role"] == {"solver": {"calls": 1, "virtual_seconds": 60.0}} + assert state["fixed"]["by_role"] == {"solver": {"calls": 1, "virtual_seconds": 60.0}} finally: await server.shutdown() diff --git a/tst/unit/env/gateway/work_clock_test.py b/tst/unit/env/gateway/fixed_clock_test.py similarity index 86% rename from tst/unit/env/gateway/work_clock_test.py rename to tst/unit/env/gateway/fixed_clock_test.py index 78c706df2..6c35f9aa2 100644 --- a/tst/unit/env/gateway/work_clock_test.py +++ b/tst/unit/env/gateway/fixed_clock_test.py @@ -1,5 +1,5 @@ -"""Work mode (FD-7183): a frozen clock moved on by a fixed charge for each answered tool call the agent makes, so the -world lives through the agent's work. Clock.advance_by, the /clock/work switch, the work windows the agent-running +"""Fixed mode (FD-7183): a frozen clock moved on by a fixed charge for each answered tool call the agent makes, so the +world lives through the agent's work. Clock.advance_by, the /clock/fixed switch, the work windows the agent-running steps open for the agent's roles, the charge on every call path inside a window and on no one else's, and the hold until the world's work runnable now has landed.""" from __future__ import annotations @@ -24,7 +24,7 @@ T0 = "2026-11-08T17:00:00Z" GW = "http://gateway.test" -CONTROL_TOKEN = "work-clock-test-token" +CONTROL_TOKEN = "fixed-clock-test-token" # ---- Clock.advance_by ----------------------------------------------------------------------------------------------- @@ -125,22 +125,22 @@ async def _arm(client: httpx.AsyncClient) -> None: assert r.status_code == 200, r.text -async def _work(client: httpx.AsyncClient, on: bool = True) -> httpx.Response: - return await client.put("/clock/work", json={"on": on}) +async def _fixed(client: httpx.AsyncClient, on: bool = True) -> httpx.Response: + return await client.put("/clock/fixed", json={"on": on}) async def _open(client: httpx.AsyncClient, roles=("default",), window: str = "turn-1") -> httpx.Response: - return await client.put("/clock/work/window", json={"window": window, "roles": list(roles)}) + return await client.put("/clock/fixed/window", json={"window": window, "roles": list(roles)}) async def _close(client: httpx.AsyncClient, window: str = "turn-1") -> httpx.Response: - return await client.request("DELETE", "/clock/work/window", json={"window": window}) + return await client.request("DELETE", "/clock/fixed/window", json={"window": window}) async def _working(client: httpx.AsyncClient, roles=("default",)) -> None: - """Armed frozen, work mode on and a window open for ``roles``: the agent's turn, as the steps set it up.""" + """Armed frozen, fixed mode on and a window open for ``roles``: the agent's turn, as the steps set it up.""" await _arm(client) - assert (await _work(client)).status_code == 200 + assert (await _fixed(client)).status_code == 200 r = await _open(client, roles) assert r.status_code == 200, r.text @@ -164,8 +164,8 @@ async def _now(client: httpx.AsyncClient) -> str: return (await client.get("/clock/time")).json()["virtual_time"] -async def _work_state(client: httpx.AsyncClient) -> dict: - return (await client.get("/clock/state")).json()["work"] +async def _fixed_state(client: httpx.AsyncClient) -> dict: + return (await client.get("/clock/state")).json()["fixed"] def _logged(gateway: Gateway, event_type: str) -> list[dict]: @@ -175,16 +175,16 @@ def _logged(gateway: Gateway, event_type: str) -> list[dict]: @pytest.mark.asyncio -async def test_state_shows_work_mode_off_until_turned_on(gw): +async def test_state_shows_fixed_mode_off_until_turned_on(gw): async with _client(gw) as client: await _arm(client) - assert await _work_state(client) == {"on": False, "seconds_per_call": 60.0, "windows": [], + assert await _fixed_state(client) == {"on": False, "seconds_per_call": 60.0, "windows": [], "calls": 0, "virtual_seconds": 0.0, "by_role": {}} - r = await _work(client) + r = await _fixed(client) assert r.status_code == 200, r.text - assert r.json()["work"]["on"] is True - assert (await _work_state(client))["on"] is True - assert (await _work(client, on=False)).json()["work"]["on"] is False + assert r.json()["fixed"]["on"] is True + assert (await _fixed_state(client))["on"] is True + assert (await _fixed(client, on=False)).json()["fixed"]["on"] is False @pytest.mark.asyncio @@ -195,57 +195,57 @@ async def test_state_shows_work_mode_off_until_turned_on(gw): async def test_a_bad_body_is_refused_and_changes_nothing(gw, body): async with _client(gw) as client: await _arm(client) - assert (await _work(client)).status_code == 200 - r = await client.put("/clock/work", content=json.dumps(body)) + assert (await _fixed(client)).status_code == 200 + r = await client.put("/clock/fixed", content=json.dumps(body)) assert r.status_code == 400, r.text - assert (await _work_state(client))["on"] is True - assert (await client.put("/clock/work", content=b"not json")).status_code == 400 + assert (await _fixed_state(client))["on"] is True + assert (await client.put("/clock/fixed", content=b"not json")).status_code == 400 @pytest.mark.asyncio async def test_turning_it_on_needs_an_armed_frozen_clock_and_keeps_the_clocks_version(gw): async with _client(gw) as client: - r = await _work(client) + r = await _fixed(client) assert r.status_code == 400 and "armed" in r.json()["error"] - assert (await _work(client, on=False)).status_code == 200 # off needs no clock + assert (await _fixed(client, on=False)).status_code == 200 # off needs no clock r = await client.put("/clock/set-time", json={"virtual_time": T0, "virtual_seconds_per_real_second": 1}) assert r.status_code == 200 - r = await _work(client) + r = await _fixed(client) assert r.status_code == 400 and "rate 0" in r.json()["error"] await _arm(client) version = (await client.get("/clock/state")).json()["version"] - assert (await _work(client)).status_code == 200 + assert (await _fixed(client)).status_code == 200 assert (await _open(client)).status_code == 200 assert (await _close(client)).status_code == 200 assert (await client.get("/clock/state")).json()["version"] == version @pytest.mark.asyncio -async def test_set_time_set_rate_and_clear_leave_work_mode_and_advance_doesnt(gw): +async def test_set_time_set_rate_and_clear_leave_fixed_mode_and_advance_doesnt(gw): async with _client(gw) as client: for leave in (lambda: client.put("/clock/set-rate", json={"virtual_seconds_per_real_second": 0}), lambda: client.put("/clock/set-time", json={"virtual_time": T0, "virtual_seconds_per_real_second": 0}), lambda: client.post("/clock/clear")): await _arm(client) - assert (await _work(client)).status_code == 200 + assert (await _fixed(client)).status_code == 200 assert (await _open(client)).status_code == 200 assert (await client.put("/clock/advance", json={"virtual_time": "2026-11-08T18:00:00Z"})).status_code == 200 - assert (await _work_state(client))["on"] is True + assert (await _fixed_state(client))["on"] is True assert (await leave()).status_code == 200 - work = await _work_state(client) - assert work["on"] is False and work["windows"] == [] + fixed = await _fixed_state(client) + assert fixed["on"] is False and fixed["windows"] == [] assert (await _close(client)).status_code == 200 # the turn's own close still gets its totals - # A write the clock refuses changes nothing, work mode included. + # A write the clock refuses changes nothing, fixed mode included. await _arm(client) - await _work(client) + await _fixed(client) assert (await client.put("/clock/set-rate", json={"virtual_seconds_per_real_second": -1})).status_code == 400 - assert (await _work_state(client))["on"] is True + assert (await _fixed_state(client))["on"] is True @pytest.mark.asyncio -async def test_a_set_time_that_fails_after_arming_still_leaves_work_mode(gw, monkeypatch): - """set_time arms the clock, then registers get_time: work mode is off before the second step can fail.""" +async def test_a_set_time_that_fails_after_arming_still_leaves_fixed_mode(gw, monkeypatch): + """set_time arms the clock, then registers get_time: fixed mode is off before the second step can fail.""" async with _client(gw) as client: await _working(client) @@ -255,33 +255,33 @@ def fails(): with pytest.raises(ValueError): await client.put("/clock/set-time", json={"virtual_time": T0, "virtual_seconds_per_real_second": 1}) assert gw._clock.rate == 1 - assert (await _work_state(client))["on"] is False + assert (await _fixed_state(client))["on"] is False -def test_the_card_offers_work_and_its_windows(): +def test_the_card_offers_fixed_and_its_windows(): clock_ext = next(e for e in GATEWAY_EXTENSIONS if e["uri"] == EXT_CLOCK_URI) methods = clock_ext["params"]["methods"] - work = methods["work"] - assert (work["method"], work["endpoint"]) == ("PUT", "/clock/work") - assert set(work["request"]["properties"]) == {"on"} and work["request"]["required"] == ["on"] + fixed = methods["fixed"] + assert (fixed["method"], fixed["endpoint"]) == ("PUT", "/clock/fixed") + assert set(fixed["request"]["properties"]) == {"on"} and fixed["request"]["required"] == ["on"] opened, closed = methods["open_work_window"], methods["close_work_window"] - assert (opened["method"], opened["endpoint"]) == ("PUT", "/clock/work/window") + assert (opened["method"], opened["endpoint"]) == ("PUT", "/clock/fixed/window") assert set(opened["request"]["required"]) == {"window", "roles"} - assert (closed["method"], closed["endpoint"]) == ("DELETE", "/clock/work/window") + assert (closed["method"], closed["endpoint"]) == ("DELETE", "/clock/fixed/window") assert closed["request"]["required"] == ["window"] - assert "work" in clock_ext["description"] and "window" in clock_ext["description"] + assert "fixed" in clock_ext["description"] and "window" in clock_ext["description"] -def test_the_work_routes_are_control_routes(): - assert {"/clock/work", "/clock/work/window"} <= CONTROL_ROUTES +def test_the_fixed_routes_are_control_routes(): + assert {"/clock/fixed", "/clock/fixed/window"} <= CONTROL_ROUTES @pytest.mark.asyncio -async def test_the_work_routes_take_the_control_token(guarded): +async def test_the_fixed_routes_take_the_control_token(guarded): async with _client(guarded, guarded=True) as anyone, _client(guarded, guarded=True, token=True) as harness: await _arm(harness) - assert (await _work(anyone)).status_code == 401 - assert (await _work(harness)).status_code == 200 + assert (await _fixed(anyone)).status_code == 401 + assert (await _fixed(harness)).status_code == 200 assert (await _open(anyone)).status_code == 401 assert (await _open(harness)).status_code == 200 assert (await _close(anyone)).status_code == 401 @@ -299,26 +299,26 @@ async def test_the_work_routes_take_the_control_token(guarded): async def test_opening_a_window_needs_an_id_and_some_roles(gw, body): async with _client(gw) as client: await _arm(client) - await _work(client) - r = await client.put("/clock/work/window", content=json.dumps(body)) + await _fixed(client) + r = await client.put("/clock/fixed/window", content=json.dumps(body)) assert r.status_code == 400, r.text - assert (await _work_state(client))["windows"] == [] + assert (await _fixed_state(client))["windows"] == [] assert _logged(gw, "work_window") == [] @pytest.mark.asyncio -async def test_a_window_opens_only_in_work_mode_and_again_only_with_the_same_roles(gw): +async def test_a_window_opens_only_in_fixed_mode_and_again_only_with_the_same_roles(gw): async with _client(gw) as client: await _arm(client) r = await _open(client, ["solver"]) - assert r.status_code == 409 and "work mode" in r.json()["error"] - await _work(client) + assert r.status_code == 409 and "fixed mode" in r.json()["error"] + await _fixed(client) r = await _open(client, ["solver", "solver"]) assert r.status_code == 200, r.text assert r.json()["window"] == {"window": "turn-1", "roles": ["solver"], "calls": 0, "virtual_seconds": 0.0} assert (await _open(client, ["solver"])).status_code == 200 # a retried open assert (await _open(client, ["planner"])).status_code == 409 - assert (await _work_state(client))["windows"] == [ + assert (await _fixed_state(client))["windows"] == [ {"window": "turn-1", "roles": ["solver"], "calls": 0, "virtual_seconds": 0.0}] @@ -331,11 +331,11 @@ async def test_closing_a_window_answers_what_it_charged_and_a_retry_answers_the_ r = await _close(client) assert r.status_code == 200, r.text assert r.json()["window"] == {"window": "turn-1", "roles": ["solver"], "calls": 2, "virtual_seconds": 120.0} - assert r.json()["work"]["windows"] == [] + assert r.json()["fixed"]["windows"] == [] again = await _close(client) assert again.status_code == 200 and again.json()["window"] == r.json()["window"] assert (await _close(client, "no-such-window")).status_code == 404 - assert (await client.request("DELETE", "/clock/work/window", json={})).status_code == 400 + assert (await client.request("DELETE", "/clock/fixed/window", json={})).status_code == 400 # Closed, the agent's calls are charged no more. await _call(client, "app_lookup", "solver") assert await _now(client) == "2026-11-08T17:02:00Z" @@ -346,14 +346,14 @@ async def test_closing_a_window_answers_what_it_charged_and_a_retry_answers_the_ @pytest.mark.asyncio -async def test_a_window_work_mode_ended_still_answers_its_close(gw): +async def test_a_window_fixed_mode_ended_still_answers_its_close(gw): async with _client(gw) as client: await _working(client) await _call(client, "app_lookup") await client.put("/clock/set-rate", json={"virtual_seconds_per_real_second": 0}) # a hook, say r = await _close(client) assert r.status_code == 200 - assert (r.json()["window"]["calls"], r.json()["work"]["on"]) == (1, False) + assert (r.json()["window"]["calls"], r.json()["fixed"]["on"]) == (1, False) @pytest.mark.asyncio @@ -364,9 +364,9 @@ async def test_two_windows_each_count_their_own_roles(gw): await _call(client, "app_lookup", "solver") await _call(client, "app_lookup", "planner") assert await _now(client) == "2026-11-08T17:02:00Z" # each call charged once, whatever windows name it - work = await _work_state(client) - assert [(w["window"], w["calls"]) for w in work["windows"]] == [("turn-1", 1), ("turn-2", 2)] - assert work["by_role"] == {"solver": {"calls": 1, "virtual_seconds": 60.0}, + fixed = await _fixed_state(client) + assert [(w["window"], w["calls"]) for w in fixed["windows"]] == [("turn-1", 1), ("turn-2", 2)] + assert fixed["by_role"] == {"solver": {"calls": 1, "virtual_seconds": 60.0}, "planner": {"calls": 1, "virtual_seconds": 60.0}} @@ -381,10 +381,10 @@ async def test_each_answered_call_in_a_window_moves_the_clock_a_minute(gw): r = await _call(client, "app_refuses") # an error result is an answered call assert r.status_code == 200 and r.json()["isError"] is True assert await _now(client) == "2026-11-08T17:02:00Z" - work = await _work_state(client) - assert (work["calls"], work["virtual_seconds"], work["by_role"]) == ( + fixed = await _fixed_state(client) + assert (fixed["calls"], fixed["virtual_seconds"], fixed["by_role"]) == ( 2, 120.0, {"default": {"calls": 2, "virtual_seconds": 120.0}}) - first, second = _logged(gw, "work_clock_charge") + first, second = _logged(gw, "fixed_clock_charge") calls = {e["event_id"]: e for e in _logged(gw, "tool_call")} assert {k: first[k] for k in ("tool", "role", "seconds", "virtual_time_before", "virtual_time_after", "due", "windows")} == { @@ -393,7 +393,7 @@ async def test_each_answered_call_in_a_window_moves_the_clock_a_minute(gw): assert first["call_real_s"] >= 0 assert calls[first["tool_call_event_id"]]["tool_call"]["function_name"] == "app_lookup" assert (second["tool"], second["seconds"]) == ("app_refuses", 60.0) - holds = _logged(gw, "work_clock_hold") + holds = _logged(gw, "fixed_clock_hold") assert [(h["tool_call_event_id"], h["still_running"], h["cancelled"]) for h in holds] == [ (first["tool_call_event_id"], [], False), (second["tool_call_event_id"], [], False)] assert all(h["held_s"] >= 0 for h in holds) @@ -418,7 +418,7 @@ async def test_a_header_less_call_outside_the_agents_window_is_free_and_fires_no async with _client(gw) as client: await _arm(client) _reply_at(gw) # due a minute in: a charge would set it going - await _work(client) + await _fixed(client) if when == "after the agent finished": await _open(client) await _close(client) @@ -427,8 +427,8 @@ async def test_a_header_less_call_outside_the_agents_window_is_free_and_fires_no await _mcp(gw, "app_lookup") assert await _now(client) == T0 assert replies == [] and _trigger(gw)["status"] == "armed" - assert (await _work_state(client))["calls"] == 0 - assert _logged(gw, "work_clock_charge") == [] + assert (await _fixed_state(client))["calls"] == 0 + assert _logged(gw, "fixed_clock_charge") == [] @pytest.mark.asyncio @@ -454,13 +454,13 @@ async def call(tool: str, role: str) -> None: await call("app_lookup", role) r = await _call(client, "app_lookup", "assistant", source="post_turn_hook", hook_artifact_id="next-event") assert r.status_code == 200 - assert await _now(client) == T0 and _logged(gw, "work_clock_charge") == [] + assert await _now(client) == T0 and _logged(gw, "fixed_clock_charge") == [] await call("app_lookup", "assistant") # the agent's call, whose trigger's own tool action is free assert await _now(client) == "2026-11-08T17:01:00Z" mirror = next(t for t in gw._trigger_engine.state()["triggers"] if t["id"] == "mirror") assert mirror["fire_count"] == 2 # the hook's call made as the agent provokes it too; its action ran - assert [(e["tool"], e["role"]) for e in _logged(gw, "work_clock_charge")] == [("app_lookup", "assistant")] + assert [(e["tool"], e["role"]) for e in _logged(gw, "fixed_clock_charge")] == [("app_lookup", "assistant")] @pytest.mark.asyncio @@ -473,7 +473,7 @@ async def test_an_agents_call_outside_its_window_is_free_and_logged(gw): await _call(client, "get_time", "solver") # free anyway: not logged await _call(client, "app_lookup", "verifier") # never a window's role: not logged assert await _now(client) == T0 - (outside,) = _logged(gw, "work_clock_outside_window") + (outside,) = _logged(gw, "fixed_clock_outside_window") assert (outside["tool"], outside["role"]) == ("app_lookup", "solver") and outside["tool_call_event_id"] @@ -488,7 +488,7 @@ async def child(url, tool, arguments, **kw): await _working(client) assert (await _call(client, "svc_send")).status_code == 200 assert await _now(client) == "2026-11-08T17:01:00Z" - assert [e["tool"] for e in _logged(gw, "work_clock_charge")] == ["svc_send"] + assert [e["tool"] for e in _logged(gw, "fixed_clock_charge")] == ["svc_send"] @pytest.mark.asyncio @@ -517,8 +517,8 @@ async def child(url, tool, arguments, **kw): assert (await _call(client, "app_lookup")).status_code == 403 assert (await _call(client, "get_time")).status_code == 200 assert await _now(client) == T0 - assert (await _work_state(client))["calls"] == 0 - assert _logged(gw, "work_clock_charge") == [] + assert (await _fixed_state(client))["calls"] == 0 + assert _logged(gw, "fixed_clock_charge") == [] @pytest.mark.asyncio @@ -536,7 +536,7 @@ async def test_stay_quiet_is_free_and_message_user_is_charged(gw): @pytest.mark.asyncio async def test_a_backing_servers_tool_named_like_a_free_one_is_charged(gw, monkeypatch): - """Free means the gateway's own get_time and stay_quiet; a backing server's tool of that name is work.""" + """Free means the gateway's own get_time and stay_quiet; a backing server's tool of that name is charged.""" gw._tool_server_urls["stay_quiet"] = "http://svc:8000/mcp" async def child(url, tool, arguments, **kw): @@ -566,7 +566,7 @@ async def child(url, name, arguments, **kw): assert await _now(harness) == T0 assert (await _call(anyone, tool, "solver", **hook)).status_code == 200 # a claim without the token assert await _now(harness) == "2026-11-08T17:01:00Z" - (charge,) = _logged(guarded, "work_clock_charge") + (charge,) = _logged(guarded, "fixed_clock_charge") assert (charge["tool"], charge["role"]) == (tool, "solver") @@ -583,15 +583,15 @@ async def test_parallel_calls_each_pay(gw): async def test_a_charge_on_a_clock_disarmed_under_it_is_skipped_and_records_nothing(gw): async with _client(gw) as client: await _working(client) - gw._clock.clear() # disarmed without the route, which would also have left work mode + gw._clock.clear() # disarmed without the route, which would also have left fixed mode assert (await _call(client, "app_lookup")).status_code == 200 - work = gw._work_clock.state() - assert (work["calls"], work["virtual_seconds"], work["by_role"]) == (0, 0.0, {}) - assert work["windows"][0]["calls"] == 0 - (skipped,) = _logged(gw, "work_clock_skipped") + fixed = gw._fixed_clock.state() + assert (fixed["calls"], fixed["virtual_seconds"], fixed["by_role"]) == (0, 0.0, {}) + assert fixed["windows"][0]["calls"] == 0 + (skipped,) = _logged(gw, "fixed_clock_skipped") assert (skipped["tool"], skipped["role"], skipped["seconds"]) == ("app_lookup", "default", 60.0) assert "armed" in skipped["reason"] - assert _logged(gw, "work_clock_charge") == [] + assert _logged(gw, "fixed_clock_charge") == [] @pytest.mark.asyncio @@ -612,8 +612,8 @@ def fails(): followers.clear() assert (await _call(client, "app_lookup")).status_code == 200 # fail-open assert await _now(client) == "2026-11-08T17:01:00Z" - work = await _work_state(client) - assert (work["calls"], work["windows"][0]["calls"]) == (1, 1) + fixed = await _fixed_state(client) + assert (fixed["calls"], fixed["windows"][0]["calls"]) == (1, 1) assert woken and followers @@ -648,13 +648,13 @@ async def test_a_trigger_the_charge_made_due_lands_before_the_call_is_answered(g async with _client(gw) as client: await _arm(client) _reply_at(gw) - await _work(client) + await _fixed(client) await _open(client) assert (await _call(client, "app_lookup")).status_code == 200 assert replies == ["2026-11-08T17:01:00Z"] assert (_trigger(gw)["status"], _trigger(gw)["fire_count"]) == ("fired", 1) - (charge,) = _logged(gw, "work_clock_charge") - (hold,) = _logged(gw, "work_clock_hold") + (charge,) = _logged(gw, "fixed_clock_charge") + (hold,) = _logged(gw, "fixed_clock_hold") assert charge["due"] == ["sellout"] and hold["still_running"] == [] assert hold["held_s"] >= 0.25 @@ -714,7 +714,7 @@ async def call(): async with _client(gw) as client: await _arm(client) _reply_at(gw) - await _work(client) + await _fixed(client) await _open(client) await asyncio.gather(call(), call()) assert await _now(client) == "2026-11-08T17:02:00Z" @@ -748,12 +748,12 @@ async def call(self, url, tool, arguments, meta, *, timeout): "watch_roles": ["default"], "executors": {"bob": {"a2a_url": "http://bob", "role": "bob"}}, "triggers": [{"id": "reply", "when": {"type": "action", "tool": "svc_post"}, "actions": [{"type": "nl", "executor": "bob", "instruction": "reply"}]}]}) - await _work(client) + await _fixed(client) await _open(client) assert (await _call(client, "svc_schedule")).status_code == 200 # Delivered at 17:01, the charge's end, and bob's reply to it written, before the agent heard back. assert posted == ["posted"] and replies == ["2026-11-08T17:01:00Z"] - (hold,) = _logged(gw, "work_clock_hold") + (hold,) = _logged(gw, "fixed_clock_hold") assert hold["still_running"] == [] @@ -779,7 +779,7 @@ async def call(self, url, tool, arguments, meta, *, timeout): started = time.monotonic() assert (await _call(client, "svc_schedule")).status_code == 200 assert time.monotonic() - started < 2 and posted == [] - (hold,) = _logged(gw, "work_clock_hold") + (hold,) = _logged(gw, "fixed_clock_hold") assert hold["still_running"] == [] await gw._deferred.cancel() @@ -790,12 +790,12 @@ async def test_a_fire_waiting_on_later_task_time_doesnt_hold_the_call(gw, monkey async with _client(gw) as client: await _arm(client) _reply_at(gw, delay="PT1H") - await _work(client) + await _fixed(client) await _open(client) assert (await _call(client, "app_lookup")).status_code == 200 assert replies == [] and _trigger(gw)["waiting"] is True - (charge,) = _logged(gw, "work_clock_charge") - (hold,) = _logged(gw, "work_clock_hold") + (charge,) = _logged(gw, "fixed_clock_charge") + (hold,) = _logged(gw, "fixed_clock_hold") assert (charge["due"], hold["still_running"]) == (["sellout"], []) assert hold["held_s"] < 2 await gw._trigger_engine.cancel_scheduled() @@ -808,10 +808,10 @@ async def test_the_hold_gives_up_after_hold_seconds(gw, monkeypatch): async with _client(gw) as client: await _arm(client) _reply_at(gw) - await _work(client) + await _fixed(client) await _open(client) assert (await _call(client, "app_lookup")).status_code == 200 - (hold,) = _logged(gw, "work_clock_hold") + (hold,) = _logged(gw, "fixed_clock_hold") assert hold["still_running"] == ["sellout"] assert 0.15 <= hold["held_s"] < 5 await gw._trigger_engine.cancel_scheduled() @@ -837,7 +837,7 @@ async def executor(engine, ex, instruction, context_id): started = time.monotonic() assert (await _call(client, "app_lookup")).status_code == 200 took = time.monotonic() - started - (hold,) = _logged(gw, "work_clock_hold") + (hold,) = _logged(gw, "fixed_clock_hold") assert hold["still_running"] == ["sellout"] assert 0.5 <= took < 0.95 # 0.6 s in all, not 0.4 s of barrier plus a fresh 0.6 s of hold await gw._trigger_engine.cancel_scheduled() @@ -866,7 +866,7 @@ async def executor(engine, ex, instruction, context_id): await _working(client) assert (await _call(client, "app_lookup")).status_code == 200 assert sorted(replies) == ["ack", "reply"] - (hold,) = _logged(gw, "work_clock_hold") + (hold,) = _logged(gw, "fixed_clock_hold") assert hold["still_running"] == [] @@ -896,7 +896,7 @@ async def test_a_call_cancelled_during_its_hold_still_leaves_its_charge_in_the_t async with _client(gw) as client: await _arm(client) _reply_at(gw) - await _work(client) + await _fixed(client) await _open(client) task = asyncio.create_task(_mcp(gw, "app_lookup")) await asyncio.sleep(0.3) @@ -905,10 +905,10 @@ async def test_a_call_cancelled_during_its_hold_still_leaves_its_charge_in_the_t await task await asyncio.sleep(0.05) assert await _now(client) == "2026-11-08T17:01:00Z" - assert (await _work_state(client))["calls"] == 1 + assert (await _fixed_state(client))["calls"] == 1 await gw._trigger_engine.cancel_scheduled() - (charge,) = _logged(gw, "work_clock_charge") - (hold,) = _logged(gw, "work_clock_hold") + (charge,) = _logged(gw, "fixed_clock_charge") + (hold,) = _logged(gw, "fixed_clock_hold") assert (charge["tool"], charge["due"]) == ("app_lookup", ["sellout"]) assert hold["cancelled"] is True and hold["held_s"] >= 0.25 @@ -920,7 +920,7 @@ async def test_a_call_cancelled_again_while_its_hold_is_written_still_leaves_it( async with _client(gw) as client: await _arm(client) _reply_at(gw) - await _work(client) + await _fixed(client) await _open(client) task = asyncio.create_task(_mcp(gw, "app_lookup")) await asyncio.sleep(0.3) @@ -932,5 +932,5 @@ async def test_a_call_cancelled_again_while_its_hold_is_written_still_leaves_it( await task await asyncio.sleep(0.05) await gw._trigger_engine.cancel_scheduled() - (hold,) = _logged(gw, "work_clock_hold") + (hold,) = _logged(gw, "fixed_clock_hold") assert hold["cancelled"] is True diff --git a/tst/unit/task_step/clock_mode_test.py b/tst/unit/task_step/clock_mode_test.py index 85f5ce759..1250e4ea5 100644 --- a/tst/unit/task_step/clock_mode_test.py +++ b/tst/unit/task_step/clock_mode_test.py @@ -1,5 +1,5 @@ -"""The clock setup steps' ``clock_mode`` (FD-7183): ``"work"`` arms the clock frozen (rate 0) and turns on the -gateway's work mode, where each tool call the agent makes inside a work window moves task time on by a fixed charge, +"""The clock setup steps' ``clock_mode`` (FD-7183): ``"fixed"`` arms the clock frozen (rate 0) and turns on the +gateway's fixed mode, where each tool call the agent makes inside a work window moves task time on by a fixed charge, so a frozen world still lives through the agent's work. sync_env_clock and set_env_clock_rate both take it, and prompt_agent opens the window around the agent's turns, each driving a real in-process gateway here. Without clock_mode, every step does exactly what it did before.""" @@ -105,64 +105,64 @@ def _rate(rate=None, **kw) -> SetEnvClockRateTaskStep: # ---- sync_env_clock ------------------------------------------------------------------------------------------------- @pytest.mark.asyncio -async def test_sync_env_clock_in_work_mode_arms_frozen_then_turns_work_on(world): +async def test_sync_env_clock_in_fixed_mode_arms_frozen_then_turns_fixed_on(world): context = await world.context() - await _sync(clock_mode="work").execute(context) + await _sync(clock_mode="fixed").execute(context) assert world.clock_calls() == [ ("PUT", "/clock/set-time", {"virtual_time": T0, "virtual_seconds_per_real_second": 0}), ("GET", "/clock/state", None), - ("PUT", "/clock/work", {"on": True}), + ("PUT", "/clock/fixed", {"on": True}), ] state = await world.state() assert state["virtual_seconds_per_real_second"] == 0 - assert state["work"]["on"] is True and state["work"]["seconds_per_call"] == 60 + assert state["fixed"]["on"] is True and state["fixed"]["seconds_per_call"] == 60 record = context.metadata["clock_configurations"][0] - assert record["clock_mode"] == "work" and record["virtual_seconds_per_real_second"] == 0 - assert record["work"]["on"] is True and record["deploy_step_id"] == "deploy" + assert record["clock_mode"] == "fixed" and record["virtual_seconds_per_real_second"] == 0 + assert record["fixed"]["on"] is True and record["deploy_step_id"] == "deploy" await world.call() # no agent's turn has opened a work window yet: setup's calls take no time assert (await world.state())["virtual_time"] == T0 @pytest.mark.asyncio -async def test_sync_env_clock_work_mode_takes_an_explicit_rate_of_zero(world): - step = _sync(clock_mode="work", virtual_seconds_per_real_second=0) +async def test_sync_env_clock_fixed_mode_takes_an_explicit_rate_of_zero(world): + step = _sync(clock_mode="fixed", virtual_seconds_per_real_second=0) await step.execute(await world.context()) - assert (await world.state())["work"]["on"] is True + assert (await world.state())["fixed"]["on"] is True @pytest.mark.parametrize("rate", [1, 1.0, 0.5, 3600]) -def test_sync_env_clock_refuses_work_mode_with_a_running_rate(rate): - with pytest.raises(ValueError, match="clock_mode 'work'.*rate 0"): - _sync(clock_mode="work", virtual_seconds_per_real_second=rate) +def test_sync_env_clock_refuses_fixed_mode_with_a_running_rate(rate): + with pytest.raises(ValueError, match="clock_mode 'fixed'.*rate 0"): + _sync(clock_mode="fixed", virtual_seconds_per_real_second=rate) -@pytest.mark.parametrize("mode", ["Work", "real", "frozen", "", 1, True]) +@pytest.mark.parametrize("mode", ["work", "Fixed", "real", "frozen", "", 1, True]) def test_sync_env_clock_refuses_an_unknown_clock_mode(mode): with pytest.raises(ValueError, match="clock_mode"): _sync(clock_mode=mode) -def test_sync_env_clock_work_mode_round_trips_and_a_plain_step_has_no_clock_mode(): - d = _sync(clock_mode="work").to_dict() - assert d["clock_mode"] == "work" and d["virtual_seconds_per_real_second"] == 0 +def test_sync_env_clock_fixed_mode_round_trips_and_a_plain_step_has_no_clock_mode(): + d = _sync(clock_mode="fixed").to_dict() + assert d["clock_mode"] == "fixed" and d["virtual_seconds_per_real_second"] == 0 again = SyncEnvClockTaskStep.from_dict(d) - assert (again.clock_mode, again.virtual_seconds_per_real_second) == ("work", 0) + assert (again.clock_mode, again.virtual_seconds_per_real_second) == ("fixed", 0) # A task JSON that names the mode and leaves the rate out is armed frozen. bare = {k: v for k, v in d.items() if k != "virtual_seconds_per_real_second"} assert SyncEnvClockTaskStep.from_dict(bare).virtual_seconds_per_real_second == 0 @pytest.mark.asyncio -@pytest.mark.parametrize("missing", [("work", "open_work_window", "close_work_window"), +@pytest.mark.parametrize("missing", [("fixed", "open_work_window", "close_work_window"), ("open_work_window", "close_work_window")]) -async def test_sync_env_clock_work_mode_on_a_gateway_without_work_fails_before_arming(world, missing): +async def test_sync_env_clock_fixed_mode_on_a_gateway_without_fixed_fails_before_arming(world, missing): card = _card_without(json.loads((await world.gw._serve_env_card()).body), *missing) - with pytest.raises(StepContextError, match="work"): - await _sync(clock_mode="work").execute(await world.context(card)) + with pytest.raises(StepContextError, match="clock_mode 'fixed'"): + await _sync(clock_mode="fixed").execute(await world.context(card)) assert world.clock_calls() == [] assert (await world.state())["armed"] is False @@ -178,54 +178,54 @@ def _card_without(card: dict, *methods: str) -> dict: # ---- set_env_clock_rate --------------------------------------------------------------------------------------------- @pytest.mark.asyncio -async def test_set_env_clock_rate_in_work_mode_freezes_the_clock_then_turns_work_on(world): +async def test_set_env_clock_rate_in_fixed_mode_freezes_the_clock_then_turns_fixed_on(world): await _sync(virtual_seconds_per_real_second=0).execute(await world.context()) # armed frozen during setup world.forget() context = await world.context() - await _rate(clock_mode="work").execute(context) + await _rate(clock_mode="fixed").execute(context) assert world.clock_calls() == [ ("PUT", "/clock/set-rate", {"virtual_seconds_per_real_second": 0}), - ("PUT", "/clock/work", {"on": True}), + ("PUT", "/clock/fixed", {"on": True}), ] - assert (await world.state())["work"]["on"] is True + assert (await world.state())["fixed"]["on"] is True record = context.metadata["clock_configurations"][0] - assert (record["clock_mode"], record["deploy_step_id"]) == ("work", "deploy") + assert (record["clock_mode"], record["deploy_step_id"]) == ("fixed", "deploy") await world.call() assert (await world.state())["virtual_time"] == T0 @pytest.mark.parametrize("rate", [1, 0.25, 86400]) -def test_set_env_clock_rate_refuses_work_mode_with_a_running_rate(rate): - with pytest.raises(ValueError, match="clock_mode 'work'.*rate 0"): - _rate(rate, clock_mode="work") +def test_set_env_clock_rate_refuses_fixed_mode_with_a_running_rate(rate): + with pytest.raises(ValueError, match="clock_mode 'fixed'.*rate 0"): + _rate(rate, clock_mode="fixed") -def test_set_env_clock_rate_needs_a_rate_or_work_mode(): +def test_set_env_clock_rate_needs_a_rate_or_fixed_mode(): with pytest.raises(ValueError, match="virtual_seconds_per_real_second"): _rate() - assert _rate(clock_mode="work").virtual_seconds_per_real_second == 0 - d = _rate(clock_mode="work").to_dict() - assert d["clock_mode"] == "work" + assert _rate(clock_mode="fixed").virtual_seconds_per_real_second == 0 + d = _rate(clock_mode="fixed").to_dict() + assert d["clock_mode"] == "fixed" assert SetEnvClockRateTaskStep.from_dict({k: v for k, v in d.items() - if k != "virtual_seconds_per_real_second"}).clock_mode == "work" + if k != "virtual_seconds_per_real_second"}).clock_mode == "fixed" @pytest.mark.asyncio -async def test_set_env_clock_rate_to_zero_ends_work_mode_and_the_agents_window(world, monkeypatch): - """A plain rate of 0 leaves work mode, the agent's open window with it.""" +async def test_set_env_clock_rate_to_zero_ends_fixed_mode_and_the_agents_window(world, monkeypatch): + """A plain rate of 0 leaves fixed mode, the agent's open window with it.""" context = await world.context() - await _sync(clock_mode="work").execute(context) + await _sync(clock_mode="fixed").execute(context) async with world.http() as client: - await client.put("/clock/work/window", json={"window": "turn", "roles": ["solver"]}) + await client.put("/clock/fixed/window", json={"window": "turn", "roles": ["solver"]}) await world.call(role="solver") assert (await world.state())["virtual_time"] == "2026-11-09T14:01:00Z" await _rate(0).execute(context) state = await world.state() - assert state["work"]["on"] is False and state["work"]["windows"] == [] + assert state["fixed"]["on"] is False and state["fixed"]["windows"] == [] await world.call(role="solver") assert (await world.state())["virtual_time"] == state["virtual_time"] @@ -257,9 +257,9 @@ async def test_without_clock_mode_the_steps_send_what_they_always_sent(world): @pytest.mark.asyncio -async def test_without_clock_mode_the_steps_work_against_a_gateway_without_work(world): - """A gateway image from before work mode: the plain steps never ask for it.""" - card = _card_without(json.loads((await world.gw._serve_env_card()).body), "work", "open_work_window", +async def test_without_clock_mode_the_steps_work_against_a_gateway_without_fixed(world): + """A gateway image from before fixed mode: the plain steps never ask for it.""" + card = _card_without(json.loads((await world.gw._serve_env_card()).body), "fixed", "open_work_window", "close_work_window") context = await world.context(card) await _sync(virtual_seconds_per_real_second=0).execute(context) @@ -275,15 +275,15 @@ async def test_without_clock_mode_agent_calls_move_no_time(world): await world.call() state = await world.state() assert state["virtual_time"] == T0 - assert state["work"]["on"] is False and state["work"]["calls"] == 0 + assert state["fixed"]["on"] is False and state["fixed"]["calls"] == 0 @pytest.mark.asyncio -async def test_a_plain_re_arm_leaves_work_mode(world): - """A later sync_env_clock without clock_mode arms the clock as it always has: work mode doesn't outlive it.""" - await _sync(clock_mode="work").execute(await world.context()) +async def test_a_plain_re_arm_leaves_fixed_mode(world): + """A later sync_env_clock without clock_mode arms the clock as it always has: fixed mode doesn't outlive it.""" + await _sync(clock_mode="fixed").execute(await world.context()) await _sync(virtual_seconds_per_real_second=0).execute(await world.context()) - assert (await world.state())["work"]["on"] is False + assert (await world.state())["fixed"]["on"] is False await world.call() assert (await world.state())["virtual_time"] == T0 @@ -343,20 +343,20 @@ async def turn(): _agent(monkeypatch, world, turn) context = _with_agent(await world.context()) - await _sync(clock_mode="work").execute(context) + await _sync(clock_mode="fixed").execute(context) deployed = context.deployed_envs[0] await _collect(deployed) # a run_code setup script's read, before the agent starts world.forget() await _prompt().execute(context) - windows = [(m, b) for m, p, b in world.clock_calls() if p == "/clock/work/window"] + windows = [(m, b) for m, p, b in world.clock_calls() if p == "/clock/fixed/window"] assert [m for m, _ in windows] == ["PUT", "DELETE"] opened = windows[0][1] assert opened["roles"] == ["solver"] and windows[1][1] == {"window": opened["window"]} state = await world.state() assert state["virtual_time"] == "2026-11-09T14:02:00Z" - assert state["work"]["windows"] == [] and state["work"]["by_role"] == { + assert state["fixed"]["windows"] == [] and state["fixed"]["by_role"] == { "solver": {"calls": 2, "virtual_seconds": 120.0}} (record,) = context.metadata["work_windows"] assert record == {"step_id": "solve", "env_id": "e1", "window": opened["window"], "roles": ["solver"], @@ -376,20 +376,20 @@ async def turn(): _agent(monkeypatch, world, turn) context = _with_agent(await world.context(), role=None) # an agent with no role of its own: the default one - await _sync(clock_mode="work").execute(context) + await _sync(clock_mode="fixed").execute(context) with pytest.raises(RuntimeError, match="sandbox died"): await _prompt().execute(context) state = await world.state() - assert state["work"]["windows"] == [] - assert state["work"]["by_role"] == {"default": {"calls": 1, "virtual_seconds": 60.0}} + assert state["fixed"]["windows"] == [] + assert state["fixed"]["by_role"] == {"default": {"calls": 1, "virtual_seconds": 60.0}} await world.call() assert (await world.state())["virtual_time"] == "2026-11-09T14:01:00Z" @pytest.mark.asyncio @pytest.mark.usefixtures("local_stores") -async def test_prompt_agent_without_work_mode_opens_no_window(world, monkeypatch): +async def test_prompt_agent_without_fixed_mode_opens_no_window(world, monkeypatch): async def turn(): await world.call(role="solver") @@ -398,47 +398,47 @@ async def turn(): await _sync(virtual_seconds_per_real_second=0).execute(context) world.forget() await _prompt().execute(context) - assert not [p for _, p, _ in world.clock_calls() if p.startswith("/clock/work")] + assert not [p for _, p, _ in world.clock_calls() if p.startswith("/clock/fixed")] assert "work_windows" not in context.metadata @pytest.mark.asyncio @pytest.mark.usefixtures("local_stores") -async def test_prompt_agent_after_work_mode_was_ended_opens_no_window(world, monkeypatch): - """A later plain clock step ended work mode: the latest step on each env decides.""" +async def test_prompt_agent_after_fixed_mode_was_ended_opens_no_window(world, monkeypatch): + """A later plain clock step ended fixed mode: the latest step on each env decides.""" async def turn(): await world.call(role="solver") _agent(monkeypatch, world, turn) context = _with_agent(await world.context()) - await _sync(clock_mode="work").execute(context) + await _sync(clock_mode="fixed").execute(context) await _rate(0).execute(context) world.forget() await _prompt().execute(context) - assert not [p for _, p, _ in world.clock_calls() if p.startswith("/clock/work")] + assert not [p for _, p, _ in world.clock_calls() if p.startswith("/clock/fixed")] @pytest.mark.asyncio @pytest.mark.usefixtures("local_stores") -async def test_prompt_agent_refuses_more_than_one_env_in_work_mode(world, monkeypatch): +async def test_prompt_agent_refuses_more_than_one_env_in_fixed_mode(world, monkeypatch): """Two clocks charged for the same calls would drift apart, and their summed totals would match neither.""" sent = _agent(monkeypatch, world, lambda: None) context = _with_agent(await world.context()) context.deployed_envs.append(await world.deployed(env_id="e2")) - await _sync(clock_mode="work").execute(context) + await _sync(clock_mode="fixed").execute(context) await SyncEnvClockTaskStep(id="clock-2", version=1, env_id="e2", virtual_time=T0, depends_on=[], - clock_mode="work").execute(context) + clock_mode="fixed").execute(context) world.forget() - with pytest.raises(StepContextError, match="work mode.*e1.*e2"): + with pytest.raises(StepContextError, match="fixed mode.*e1.*e2"): await _prompt().execute(context) - assert sent == [] and not [p for _, p, _ in world.clock_calls() if p.startswith("/clock/work")] + assert sent == [] and not [p for _, p, _ in world.clock_calls() if p.startswith("/clock/fixed")] @pytest.mark.asyncio @pytest.mark.usefixtures("local_stores") -async def test_prompt_agent_opens_the_window_on_the_deployment_in_work_mode_only(world, monkeypatch): - """An env deployed twice: the clock step's deployment is in work mode, the other one isn't.""" +async def test_prompt_agent_opens_the_window_on_the_deployment_in_fixed_mode_only(world, monkeypatch): + """An env deployed twice: the clock step's deployment is in fixed mode, the other one isn't.""" async def turn(): await world.call(role="solver") @@ -447,29 +447,29 @@ async def turn(): other = await world.deployed() other.metadata = {"deploy_step_id": "deploy-b"} context.deployed_envs.append(other) - await _sync(clock_mode="work", env_step_id="deploy").execute(context) + await _sync(clock_mode="fixed", env_step_id="deploy").execute(context) world.forget() await _prompt().execute(context) - assert [m for m, p, _ in world.clock_calls() if p == "/clock/work/window"] == ["PUT", "DELETE"] + assert [m for m, p, _ in world.clock_calls() if p == "/clock/fixed/window"] == ["PUT", "DELETE"] (record,) = context.metadata["work_windows"] assert (record["env_id"], record["calls"]) == ("e1", 1) @pytest.mark.asyncio @pytest.mark.usefixtures("local_stores") -async def test_prompt_agent_runs_without_a_window_when_work_mode_ended_outside_the_steps(world, monkeypatch): - """Work mode turned off at the gateway behind the clock steps' backs (a restarted gateway, say): the window is +async def test_prompt_agent_runs_without_a_window_when_fixed_mode_ended_outside_the_steps(world, monkeypatch): + """Fixed mode turned off at the gateway behind the clock steps' backs (a restarted gateway, say): the window is refused (409), which is logged, and the agent still runs.""" async def turn(): await world.call(role="solver") sent = _agent(monkeypatch, world, turn) context = _with_agent(await world.context()) - await _sync(clock_mode="work").execute(context) + await _sync(clock_mode="fixed").execute(context) async with world.http() as client: - await client.put("/clock/work", json={"on": False}) + await client.put("/clock/fixed", json={"on": False}) await _prompt().execute(context) @@ -500,7 +500,7 @@ async def turn(): _agent(monkeypatch, world, turn) context = _with_agent(await world.context()) - await _sync(clock_mode="work").execute(context) + await _sync(clock_mode="fixed").execute(context) tries = _close_fails(monkeypatch) with pytest.raises(WorkWindowError, match="closing the agent's work window") as failed: @@ -518,7 +518,7 @@ async def turn(): _agent(monkeypatch, world, turn) context = _with_agent(await world.context()) - await _sync(clock_mode="work").execute(context) + await _sync(clock_mode="fixed").execute(context) _close_fails(monkeypatch) with pytest.raises(RuntimeError, match="sandbox died") as failed: @@ -535,7 +535,7 @@ async def turn(): sent = _agent(monkeypatch, world, turn) context = _with_agent(await world.context()) - await _sync(clock_mode="work").execute(context) + await _sync(clock_mode="fixed").execute(context) real = DeployedGatewayEnv.invoke async def invoke(self, uri, method, params=None, **kw): diff --git a/tst/unit/task_step/test_always_on_work_clock.py b/tst/unit/task_step/test_always_on_fixed_clock.py similarity index 83% rename from tst/unit/task_step/test_always_on_work_clock.py rename to tst/unit/task_step/test_always_on_fixed_clock.py index e7cf3fe2d..212c9fdf5 100644 --- a/tst/unit/task_step/test_always_on_work_clock.py +++ b/tst/unit/task_step/test_always_on_fixed_clock.py @@ -1,5 +1,5 @@ -"""Work mode (FD-7183) in an always_on run. The task's clock step puts the clock in work mode (sync_env_clock with -``clock_mode: "work"``): frozen, and moved on a minute by the gateway for each tool call the agent makes inside a work +"""Fixed mode (FD-7183) in an always_on run. The task's clock step puts the clock in fixed mode (sync_env_clock with +``clock_mode: "fixed"``): frozen, and moved on a minute by the gateway for each tool call the agent makes inside a work window, so the world lives through the agent's work and what comes due mid-wake lands then. always_on opens the window for the agent's role around each turn, nudges included, and closes it at the turn's end: each wake records what its work took, the run's record sums it, and the judge reads it. No one but the agent is charged, inside its turns or out.""" @@ -24,17 +24,17 @@ pytestmark = pytest.mark.usefixtures("local_stores") -async def _work_mode(monkeypatch, rig: Rig, ctx) -> None: - """Arm the clock in work mode as the task's clock step does: sync_env_clock with clock_mode "work".""" +async def _fixed_mode(monkeypatch, rig: Rig, ctx) -> None: + """Arm the clock in fixed mode as the task's clock step does: sync_env_clock with clock_mode "fixed".""" monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace(mcp_server_envs=[], website_envs=[])) await SyncEnvClockTaskStep(id="clock", version=1, env_id="world", virtual_time=rig.t0, - clock_mode="work").execute(ctx) + clock_mode="fixed").execute(ctx) -async def _work_state(rig: Rig) -> dict: +async def _fixed_state(rig: Rig) -> dict: async with rig.http() as client: - return (await client.get("/clock/state")).json()["work"] + return (await client.get("/clock/state")).json()["fixed"] async def _header_less(rig: Rig, tool: str) -> None: @@ -45,7 +45,7 @@ async def _header_less(rig: Rig, tool: str) -> None: @pytest.mark.asyncio -async def test_in_work_mode_each_wake_records_what_the_agents_work_took(monkeypatch, tmp_path): +async def test_in_fixed_mode_each_wake_records_what_the_agents_work_took(monkeypatch, tmp_path): async def agent(n, texts, rig): if n == 1: for _ in range(3): @@ -58,7 +58,7 @@ async def agent(n, texts, rig): rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "great"},)) rig.tool("market_search", "Chicago: 2 left") ctx = rig.context() - await _work_mode(monkeypatch, rig, ctx) + await _fixed_mode(monkeypatch, rig, ctx) await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=2), ctx) first, second = rig.events(ctx, "agent_turn_end") @@ -66,12 +66,12 @@ async def agent(n, texts, rig): assert first["virtual_seconds"] == 180 assert second["work"] == {"calls": 0, "virtual_seconds": 0.0} record = rig.record(ctx) - assert record["counts"]["work_clock"] == {"calls": 3, "virtual_seconds": 180.0} - assert record["settings"]["clock"] == {"envs": [], "work": {"seconds_per_call": 60.0, "envs": ["world"]}} - # always_on changes nothing of work mode: the clock is still in it after the run, every window closed. - work = await _work_state(rig) - assert work["on"] is True and work["windows"] == [] - assert work["by_role"] == {ROLE: {"calls": 3, "virtual_seconds": 180.0}} + assert record["counts"]["fixed_clock"] == {"calls": 3, "virtual_seconds": 180.0} + assert record["settings"]["clock"] == {"envs": [], "fixed": {"seconds_per_call": 60.0, "envs": ["world"]}} + # always_on changes nothing of fixed mode: the clock is still in it after the run, every window closed. + fixed = await _fixed_state(rig) + assert fixed["on"] is True and fixed["windows"] == [] + assert fixed["by_role"] == {ROLE: {"calls": 3, "virtual_seconds": 180.0}} @pytest.mark.asyncio @@ -91,7 +91,7 @@ async def agent(n, texts, rig): rig = Rig(monkeypatch, tmp_path, agent=agent) rig.tool("market_search") ctx = rig.context() - await _work_mode(monkeypatch, rig, ctx) + await _fixed_mode(monkeypatch, rig, ctx) rig.triggers(rig.notify_at("sellout", "PT2M", "Chicago is sold out", channel="Market")) await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=2), ctx) @@ -137,7 +137,7 @@ async def contact(engine, executor, instruction, context_id): rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "thanks"},)) rig.tool("market_search") ctx = rig.context() - await _work_mode(monkeypatch, rig, ctx) + await _fixed_mode(monkeypatch, rig, ctx) monkeypatch.setattr(TriggerEngine, "_call_executor", contact) rig.triggers({"id": "echo", "when": {"type": "action", "tool": "market_search"}, "actions": [{"type": "tool", "tool": "market_search", "args": {}}, @@ -153,7 +153,7 @@ async def contact(engine, executor, instruction, context_id): assert contact_in_turn == [False] assert rig.now() == "2026-11-09T14:01:00Z" - assert (await _work_state(rig))["by_role"] == {ROLE: {"calls": 1, "virtual_seconds": 60.0}} + assert (await _fixed_state(rig))["by_role"] == {ROLE: {"calls": 1, "virtual_seconds": 60.0}} first, _ = rig.events(ctx, "agent_turn_end") assert first["work"] == {"calls": 1, "virtual_seconds": 60.0} @@ -168,7 +168,7 @@ async def agent(n, texts, rig): rig = Rig(monkeypatch, tmp_path, agent=agent) rig.tool("market_search") ctx = rig.context() - await _work_mode(monkeypatch, rig, ctx) + await _fixed_mode(monkeypatch, rig, ctx) rig.gw._trigger_engine.register({"watch_roles": ["assistant"], "triggers": []}) await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1), ctx) assert rig.now() == "2026-11-09T14:01:00Z" @@ -187,7 +187,7 @@ async def agent(n, texts, rig): rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "great"},)) ctx = rig.context() - await _work_mode(monkeypatch, rig, ctx) + await _fixed_mode(monkeypatch, rig, ctx) await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=2), ctx) first, second = rig.events(ctx, "agent_turn_end") assert (first["work"], second["work"]) == ({"calls": 1, "virtual_seconds": 60.0}, @@ -195,23 +195,23 @@ async def agent(n, texts, rig): @pytest.mark.asyncio -async def test_always_on_refuses_more_than_one_env_in_work_mode(monkeypatch, tmp_path): +async def test_always_on_refuses_more_than_one_env_in_fixed_mode(monkeypatch, tmp_path): """Two clocks charged for the same calls would drift apart, and the summed totals would match neither.""" rig = Rig(monkeypatch, tmp_path) ctx = rig.context() - await _work_mode(monkeypatch, rig, ctx) + await _fixed_mode(monkeypatch, rig, ctx) ctx.deployed_envs.append(DeployedGatewayEnv( env_id="world-2", env_version=1, gateway_url=GATEWAY, mcp_url="", sandbox_id="sb-2", environment_card_url=f"{GATEWAY}{WELL_KNOWN_PATH}", environment_card={"capabilities": {"extensions": list(GATEWAY_EXTENSIONS)}}, metadata={"deploy_step_id": "deploy-2"})) - with pytest.raises(ValueError, match="work mode.*world.*world-2"): + with pytest.raises(ValueError, match="fixed mode.*world.*world-2"): await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1), ctx) - assert (await _work_state(rig))["windows"] == [] + assert (await _fixed_state(rig))["windows"] == [] @pytest.mark.asyncio -async def test_work_mode_ended_mid_run_is_logged_not_read_as_no_work(monkeypatch, tmp_path): +async def test_fixed_mode_ended_mid_run_is_logged_not_read_as_no_work(monkeypatch, tmp_path): async def agent(n, texts, rig): await rig.call("market_search") if n == 1: # a hook, say, sets the rate during the turn @@ -225,13 +225,13 @@ async def agent(n, texts, rig): rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "ok"},)) rig.tool("market_search") ctx = rig.context() - await _work_mode(monkeypatch, rig, ctx) + await _fixed_mode(monkeypatch, rig, ctx) await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=2), ctx) - (off,) = rig.events(ctx, "work_mode_off") + (off,) = rig.events(ctx, "fixed_mode_off") assert off["env_id"] == "world" and off["wake"] == 1 first, second = rig.events(ctx, "agent_turn_end") assert first["work"] == {"calls": 1, "virtual_seconds": 60.0} - assert "work" not in second # nothing to read once work mode is off + assert "work" not in second # nothing to read once fixed mode is off assert rig.now() == "2026-11-09T14:01:00Z" @@ -247,7 +247,7 @@ async def agent(n, texts, rig): rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "great"},)) rig.tool("market_search") ctx = rig.context() - await _work_mode(monkeypatch, rig, ctx) + await _fixed_mode(monkeypatch, rig, ctx) tries: list[int] = [] class Struggling: @@ -271,7 +271,7 @@ async def call(env, uri, method, params=None, **kw): @pytest.mark.asyncio -async def test_work_mode_ended_between_turns_is_found_at_the_next_window_at_once(monkeypatch, tmp_path): +async def test_fixed_mode_ended_between_turns_is_found_at_the_next_window_at_once(monkeypatch, tmp_path): """The gateway's refusal of the next turn's window (409) is its answer, not a failure to retry.""" async def agent(n, texts, rig): await rig.call("market_search") @@ -284,20 +284,20 @@ async def agent(n, texts, rig): rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "ok"},)) rig.tool("market_search") ctx = rig.context() - await _work_mode(monkeypatch, rig, ctx) + await _fixed_mode(monkeypatch, rig, ctx) real_call = ao._call async def call(env, uri, method, params=None, **kw): answer = await real_call(env, uri, method, params, **kw) if method == "close_work_window": # behind the step's back, after the turn async with rig.http() as client: - await client.put("/clock/work", json={"on": False}) + await client.put("/clock/fixed", json={"on": False}) return answer monkeypatch.setattr(ao, "_call", call) started = asyncio.get_running_loop().time() await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=2), ctx) assert asyncio.get_running_loop().time() - started < 5 - (off,) = rig.events(ctx, "work_mode_off") + (off,) = rig.events(ctx, "fixed_mode_off") assert off["wake"] == 2 first, second = rig.events(ctx, "agent_turn_end") assert first["work"] == {"calls": 1, "virtual_seconds": 60.0} and "work" not in second @@ -320,10 +320,10 @@ async def agent(n, texts, rig): rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "no_reply", "message": ""},)) rig.tool("market_search") ctx = rig.context() - await _work_mode(monkeypatch, rig, ctx) + await _fixed_mode(monkeypatch, rig, ctx) await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1), ctx) record = rig.record(ctx) - assert record["counts"]["work_clock"] == {"calls": 5, "virtual_seconds": 300.0} + assert record["counts"]["fixed_clock"] == {"calls": 5, "virtual_seconds": 300.0} (nudge,) = rig.events(ctx, "nudge") assert nudge["work"] == {"calls": 4, "virtual_seconds": 240.0} assert "· its work took 5 min of task time" in ao.render_for_judge(record) @@ -340,7 +340,7 @@ async def test_each_wake_records_the_agents_output_tokens(monkeypatch, tmp_path) @pytest.mark.asyncio -async def test_a_run_without_work_mode_is_as_before(monkeypatch, tmp_path): +async def test_a_run_without_fixed_mode_is_as_before(monkeypatch, tmp_path): async def agent(n, texts, rig): await rig.call("market_search") rig.quiet() @@ -361,14 +361,14 @@ async def call(env, uri, method, params=None, **kw): (turn,) = rig.events(ctx, "agent_turn_end") assert "work" not in turn and turn["virtual_seconds"] == 0 record = rig.record(ctx) - assert "work_clock" not in record["counts"] and record["settings"]["clock"] == {"envs": []} + assert "fixed_clock" not in record["counts"] and record["settings"]["clock"] == {"envs": []} assert "its work took" not in ao.render_for_judge(record) assert rig.now() == rig.t0 and opened == [] @pytest.mark.asyncio -async def test_a_gateway_whose_clock_state_has_no_work_block_runs_as_before(monkeypatch, tmp_path): - """A gateway image from before work mode: /clock/state says nothing of it.""" +async def test_a_gateway_whose_clock_state_has_no_fixed_block_runs_as_before(monkeypatch, tmp_path): + """A gateway image from before fixed mode: /clock/state says nothing of it.""" async def agent(n, texts, rig): await rig.call("market_search") rig.quiet() @@ -382,10 +382,10 @@ async def agent(n, texts, rig): async def call(env, uri, method, params=None, **kw): answer = await real_call(env, uri, method, params, **kw) if uri == EXT_CLOCK_URI and method == "state": - answer = {k: v for k, v in answer.items() if k != "work"} + answer = {k: v for k, v in answer.items() if k != "fixed"} return answer monkeypatch.setattr(ao, "_call", call) ctx = await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1)) (turn,) = rig.events(ctx, "agent_turn_end") assert "work" not in turn - assert "work_clock" not in rig.record(ctx)["counts"] + assert "fixed_clock" not in rig.record(ctx)["counts"] From d1fbdf00b4e5405bb2e16ea89aa56b3bbec380e4 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Thu, 3 Dec 2026 21:09:32 -0800 Subject: [PATCH 5/9] fix(gateway): fixed mode holds for state checks, charges only a live window, and window failures go ungraded (FD-7183) Three P1s from review on PR 1003: - State checks escaped the hold: at_work() now counts a state trigger whose check is under way (evaluating, its task kept as eval_task), so _settle_world waits for the check and then for the fire it starts, within the same budget, however slow the check. - A charge decided before the call's barrier wait was applied after it even if fixed mode had ended meanwhile. The call now carries a ticket (the clock's generation, fixed mode's session, the role's windows by the serial they were opened with), re-checked in the same step as the advance: set_rate, set_time, clear, turning it off, or the window closing (even reopened by the same id) skips the charge as fixed_clock_skipped. - A WorkWindowError (a window that couldn't be opened or closed) is now recorded as agent_turn_infra_error with error_code agent_env.work_window_failed before always_on's finish() saves the record, so ended_on_infra_failure is true and verifiers leave the run ungraded. prompt_agent's saved response gets error_type infra_error and the same code. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- src/agent_env/env/gateway/fixed_clock.py | 46 +++++++-- src/agent_env/env/gateway/gateway.py | 34 ++++--- src/agent_env/env/gateway/triggers.py | 21 +++-- .../task_step/task_steps/always_on.py | 9 +- .../task_step/task_steps/clock_mode.py | 36 +++++-- tst/unit/env/gateway/fixed_clock_test.py | 94 +++++++++++++++++-- tst/unit/task_step/clock_mode_test.py | 38 +++++++- .../task_step/test_always_on_fixed_clock.py | 51 +++++++++- 9 files changed, 284 insertions(+), 47 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9bb5d6d6b..9a8873454 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,7 +191,7 @@ and deserialized through a registry. | Package | Contents | |---|---| -| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its fixed mode (`/clock/fixed`, `env/gateway/fixed_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "fixed"` on a clock at rate 0 and any later set_time, set_rate or clear turns off, ending every open window, moves the frozen clock on by a fixed `FIXED_SECONDS_PER_CALL` (60 s, not configurable) for each answered tool call made while a work window naming its role is open (`/clock/fixed/window`, PUT to open with `roles`, DELETE to close, answering its totals; both control routes): prompt_agent opens one for its agent's role around its conversation and always_on one around each turn, nudges included (`task_steps/clock_mode.py` `agent_work_window`), each failing closed, as an infra error (`WorkWindowError`), when a window can't be closed, and both refuse more than one env in fixed mode, so a setup script, a verifier, collect_artifacts, a user sim, a contact or the agent between its turns is never charged, the agent's role outside its window logged as `fixed_clock_outside_window`. A charge, on the MCP path and the step API's `/step` paths (not a post-turn hook's that shows the control token; never the gateway's own `get_time` or `stay_quiet`), comes after the call's barriers (`Clock.advance_by`), then the answer is held until all world work runnable now has landed, every trigger fire at work and each deferred call the clock reached (`Gateway._settle_world`), but not a fire waiting on a later task time, the barriers and the hold sharing one budget; each charge is a `fixed_clock_charge` trajectory event and its hold a `fixed_clock_hold`, written even when the call is cancelled. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | +| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its fixed mode (`/clock/fixed`, `env/gateway/fixed_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "fixed"` on a clock at rate 0 and any later set_time, set_rate or clear turns off, ending every open window, moves the frozen clock on by a fixed `FIXED_SECONDS_PER_CALL` (60 s, not configurable) for each answered tool call made while a work window naming its role is open (`/clock/fixed/window`, PUT to open with `roles`, DELETE to close, answering its totals; both control routes): prompt_agent opens one for its agent's role around its conversation and always_on one around each turn, nudges included (`task_steps/clock_mode.py` `agent_work_window`), each failing closed, as an infra error (`WorkWindowError`), when a window can't be closed (or always_on's opened), the run recorded as one (error_type `infra_error`, error_code `agent_env.work_window_failed`) so a verifier the task runs all the same grades none of it, and both refuse more than one env in fixed mode, so a setup script, a verifier, collect_artifacts, a user sim, a contact or the agent between its turns is never charged, the agent's role outside its window logged as `fixed_clock_outside_window`. A charge, on the MCP path and the step API's `/step` paths (not a post-turn hook's that shows the control token; never the gateway's own `get_time` or `stay_quiet`), comes after the call's barriers (`Clock.advance_by`), and only if the window it was decided in is still open as it was (fixed mode ended, the clock re-armed or the window closed meanwhile skip it as `fixed_clock_skipped`), then the answer is held until all world work runnable now has landed, every trigger fire at work, every state check a write set going and each deferred call the clock reached (`Gateway._settle_world`), but not a fire waiting on a later task time, the barriers and the hold sharing one budget; each charge is a `fixed_clock_charge` trajectory event and its hold a `fixed_clock_hold`, written even when the call is cancelled. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | | `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, the `attempt_epoch` it was written under, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), each naming exactly what it was sent (`input`: a direct call's messages, response format and settings, an agent call's message, every file its step staged in the judge's sandbox and, for a judge the task deployed, what the task's own `load_artifact` steps put there as the run recorded it, stored by sha256 under `judge-inputs/` in the background, `judge_utils/judge_inputs.py`; the step waits for those uploads, at most 120 s, before it writes its grade, `VerifierTaskStep.settle`, and one that failed or hadn't finished is the call's `input_error`, never a failed grade), and its `verifier_settings` hold the trajectory source of each turn it read (`trajectory_sources`); with `judge_samples` (a count, as a step field, a run override or `--judge-samples` on `run`, `task run` and `eval run`), a rubric_binary or rubric_partial judge grades each criterion that many times, each a call of its own under `judge_batch_concurrency` (an agent judge the verifier deploys gets a deployment of its own per sample, its trajectory staged in each; the task's own judge takes every sample), and keeps its median, the lower middle score on a tie, which fails it, the row the first sample that scored it gave with every sample's score, verdict and justification in its `samples` and its `agreement`, the share of samples giving its verdict; a row under `min_judge_agreement` (0.5 by default, which never fails, so the median decides; 1.0 fails any split; set where `judge_samples` is, `--min-judge-agreement`) fails the grade, its rows kept, and then the step (`JudgeDisagreementError`), and `agent-env run` names the criteria a grade that stood split on (`samples split:`), and one failed sample fails the grade (a run's count or agreement a judge of another format can't take is recorded in `not_sent`) and the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`), each computer its own, a multi env's included, never the gateway's: its boot environment holds only the token's sha256 (`AGENTENV_CONTROL_TOKEN_SHA256`) when its probed card's computer/v1 says `control_token = "sha256"`, else, for a driver an older protocol built, the token itself (`AGENTENV_CONTROL_TOKEN`); the gateway learns each computer's (`CHILD_CONTROL_TOKENS`), puts it in place of its own on that computer's `/svc` routes, and lets a computer's token through only to that computer and its clock watch; a multi env's record grants each computer's `/svc` route its own token (`DeployedGatewayEnv.control_grants`, the longest granted address winning), and `CONTROL_TOKEN_CHILDREN`, the computers an older agent-env booted with the gateway's token, is kept for them; framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | diff --git a/src/agent_env/env/gateway/fixed_clock.py b/src/agent_env/env/gateway/fixed_clock.py index e491bda26..bbbfa8154 100644 --- a/src/agent_env/env/gateway/fixed_clock.py +++ b/src/agent_env/env/gateway/fixed_clock.py @@ -17,13 +17,17 @@ an armed clock at rate 0; any later set_time, set_rate or clear turns it off, ending every open window, so a task without clock_mode runs as it always has. The gateway charges a call with Clock.advance_by, through ``Gateway._change_clock``, then holds its answer until the world's work runnable now has landed (``Gateway._settle_world``: -every trigger fire at work, and every deferred call the clock has reached, with what each sets going), so the agent's -next call sees the world they changed. The barrier wait and the hold share one budget per call, ``HOLD_SECONDS`` or a -barrier's own longer timeout. +every trigger fire at work, every state check a write set going, and every deferred call the clock has reached, with +what each sets going), so the agent's next call sees the world they changed. The barrier wait and the hold share one +budget per call, ``HOLD_SECONDS`` or a barrier's own longer timeout. A charge is decided as the call is answered and +made once its barriers settle, only if the window it was decided in is still open as it was: fixed mode ended meanwhile +(even if turned on again), the clock re-armed or the window closed (even if opened again by the same id) skips it +(``fixed_clock_skipped``), so a call can't charge a clock its run has stopped, or a timeline it wasn't made on. """ from __future__ import annotations from collections import OrderedDict +from dataclasses import dataclass from typing import Any from .clock import ClockError @@ -51,6 +55,20 @@ class NoSuchWindow(ClockError): """A close naming a window the gateway never opened, or no longer remembers (404).""" +class ChargeLapsed(ClockError): + """A charge decided as a call was answered whose window is gone by the time its barriers settled: fixed mode ended + (set_time, set_rate, clear or turned off, even if turned on again since) or the window closed (even if opened again + by the same id). The clock is not moved.""" + + +@dataclass(frozen=True) +class Ticket: + """What a charge decided as a call is answered must still find once the call's barriers settle: the mode's + session, and each window that charged the call's role, by the serial it was opened with.""" + session: int + windows: dict[str, int] + + def parse_fixed_body(body) -> bool: """Whether a ``fixed`` request turns fixed mode on: a JSON object holding ``on``, true or false, and nothing else. Raises ClockError for anything else.""" @@ -97,6 +115,8 @@ def __init__(self) -> None: self._windows: dict[str, dict] = {} self._closed: OrderedDict[str, dict] = OrderedDict() self._seen: set[str] = set() # every role a window named since the mode came on + self._session = 0 # one more each time the mode is turned on or off + self._opened = 0 # the serial of the last window opened def turn(self, on: bool) -> None: """Turn the mode on or off. Either way every open window ends, its totals kept for its close.""" @@ -104,6 +124,7 @@ def turn(self, on: bool) -> None: self._end(window) self._seen.clear() self.on = on + self._session += 1 def open(self, window: str, roles: list[str]) -> dict: """Open ``window`` charging ``roles``; opening it again with the same roles answers it as it stands. Raises @@ -117,7 +138,8 @@ def open(self, window: str, roles: list[str]) -> dict: raise WindowConflict(f"window {window!r} is open for {mine['roles']}, not {roles}") return self._view(window, mine) self._closed.pop(window, None) - self._windows[window] = {"roles": roles, "calls": 0, "virtual_seconds": 0.0} + self._opened += 1 + self._windows[window] = {"roles": roles, "calls": 0, "virtual_seconds": 0.0, "serial": self._opened} self._seen.update(roles) return self._view(window, self._windows[window]) @@ -141,14 +163,26 @@ def windows_of(self, role: str) -> list[str]: """The open windows that charge ``role``.""" return [w for w, mine in self._windows.items() if role in mine["roles"]] + def ticket(self, role: str) -> Ticket: + """The session and the windows charging ``role`` now, for ``lapsed`` to check the charge against later.""" + return Ticket(self._session, {w: mine["serial"] for w, mine in self._windows.items() if role in mine["roles"]}) + + def lapsed(self, ticket: Ticket) -> tuple[list[str], str | None]: + """The windows of ``ticket`` still open as they were opened, and why the charge has lapsed when none is: the + mode ended since (turned off, or off and on again), or each of them closed (or closed and opened again).""" + if not self.on or ticket.session != self._session: + return [], "fixed mode ended" + windows = [w for w, serial in ticket.windows.items() + if (mine := self._windows.get(w)) is not None and mine["serial"] == serial] + return windows, None if windows else "the call's window closed" + def outside(self, role: str, tool: str, native: bool) -> bool: """Whether a call costs nothing only for being outside its windows: a role a window named since the mode came on, its tool not free, and no window naming it open now (a late call of a turn cut off).""" return self.on and role in self._seen and not (native and tool in FREE_TOOLS) and not self.windows_of(role) def record(self, role: str, seconds: float, windows: list[str]) -> None: - """Count a charge, in all, for ``role`` and in each of ``windows``, the ones open when the call was answered: a - window closed since counts it in the totals its close answers.""" + """Count a charge, in all, for ``role`` and in each of ``windows``, the ones it was made in (``lapsed``).""" self.calls += 1 self.virtual_seconds += seconds mine = self.by_role.setdefault(role, {"calls": 0, "virtual_seconds": 0.0}) diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index e8758b7e4..54cca09fe 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -120,7 +120,8 @@ from .user_chat import MESSAGE_USER_TOOL_NAME, UserChat, UserChatError, build_user_chat_tool from .user_chat import STAY_QUIET_TOOL_NAME, build_stay_quiet_tool from .fixed_clock import ( - HOLD_SECONDS, NoSuchWindow, WindowConflict, FixedClock, FixedModeOff, parse_window_body, parse_fixed_body, + HOLD_SECONDS, ChargeLapsed, NoSuchWindow, Ticket, WindowConflict, FixedClock, FixedModeOff, parse_window_body, + parse_fixed_body, ) logger = logging.getLogger(__name__) @@ -938,28 +939,39 @@ async def _after_call(self, role: str, name: str, arguments: dict | None, result if seconds is None: await self._await_barriers(barrier_tasks, barrier_timeout_s) return - windows = self._fixed_clock.windows_of(role) + ticket = (self._clock.generation, self._fixed_clock.ticket(role)) budget = max(HOLD_SECONDS, barrier_timeout_s or self.TRIGGER_BARRIER_TIMEOUT_S) if barrier_tasks \ else HOLD_SECONDS deadline = asyncio.get_running_loop().time() + budget await self._await_barriers(barrier_tasks, barrier_timeout_s) - await self._charge_call(role, name, seconds, windows, call_real_s, deadline, event_id) + await self._charge_call(role, name, seconds, ticket, call_real_s, deadline, event_id) - async def _charge_call(self, role: str, name: str, seconds: float, windows: list[str], call_real_s: float, + async def _charge_call(self, role: str, name: str, seconds: float, ticket: tuple[int, Ticket], call_real_s: float, deadline: float, event_id: str | None) -> None: - """Fixed mode's charge for an answered tool call (fixed_clock.py), made once its barriers have settled: the clock - moved on by ``seconds``, counted for ``role`` and its ``windows``, then the answer held until the world's work - runnable now has landed, or the loop time ``deadline``. The trajectory records the charge before the hold - (``fixed_clock_charge``: the virtual time before and after, what came due, the windows, the call's own real - seconds), then the hold however it ends (``fixed_clock_hold``: how long, what was still at work, whether the - call was cancelled), or ``fixed_clock_skipped`` when the clock can't be moved. Fail-open: a charge that fails - never fails the call.""" + """Fixed mode's charge for an answered tool call (fixed_clock.py), made once its barriers have settled, and only + in what it was decided in (``ticket``: the clock's generation, then fixed mode's session and the role's windows, + checked in the same step as the advance): the clock moved on by ``seconds``, counted for ``role`` and its + windows still open, then the answer held until the world's work runnable now has landed, or the loop time + ``deadline``. The trajectory records the charge before the hold (``fixed_clock_charge``: the virtual time before + and after, what came due, the windows, the call's own real seconds), then the hold however it ends + (``fixed_clock_hold``: how long, what was still at work, whether the call was cancelled), or + ``fixed_clock_skipped`` when the clock can't be moved, or the charge lapsed while the call waited on its barriers + (the clock re-armed, fixed mode ended, the window closed). Fail-open: a charge that fails never fails the + call.""" charge = {"source": "fixed_clock", "tool": name, "role": role, "seconds": seconds, **({"tool_call_event_id": event_id} if event_id else {})} + generation, tickets = ticket + windows: list[str] = [] try: moved: dict = {} def advance() -> dict: + open_now, lapsed = self._fixed_clock.lapsed(tickets) + if self._clock.generation != generation: + lapsed = "the clock was re-armed" + if lapsed: + raise ChargeLapsed(f"{lapsed} while the call waited on its barriers") + windows[:] = open_now at = self._clock.now() state = self._clock.advance_by(seconds) # ClockError, unarmed: nothing moved moved["at"] = at diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index 4c22f085a..6dfad6c78 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -510,9 +510,9 @@ def register(self, body: Any) -> dict: for tid, spec in to_add: # `running` counts its fires in flight, `alongside` holds those run beside the first (concurrent_fires), # `waits` each fire waiting out a delay or its executor's hours, `calls` each executor call in progress, - # `recheck` the write that asked a state check under way to run again. + # `eval_task` the state check under way (`evaluating`), `recheck` the write that asked it to run again. self._triggers[tid] = {"spec": spec, "status": "armed", "detected_at": None, - "fired_at": None, "evaluating": False, "recheck": None, + "fired_at": None, "evaluating": False, "eval_task": None, "recheck": None, "next_mark": None, "resolved": False, "fire_count": 0, "failure_count": 0, "last_failure_at": None, "rng": _make_rng(spec), "mark_gen": None, @@ -1078,7 +1078,7 @@ def _reevaluate_states(self, provokable: list[tuple[str, dict]], provoking: dict trig["recheck"] = provoking continue trig["evaluating"] = True - self._schedule(self._eval_state(tid, trig, provoking)) + trig["eval_task"] = self._schedule(self._eval_state(tid, trig, provoking)) def may_hold_website_request(self, role: str, app: str, method: str, path: str, status: int, op: str | None = None) -> bool: @@ -1191,9 +1191,12 @@ def clock_changed(self) -> None: self._clock_moved = asyncio.Event() def at_work(self) -> dict[str, list[asyncio.Task]]: - """Each trigger with a fire at work now (``_at_work``: running, and not only waiting on a task time still - ahead), with its fire tasks: what fixed mode holds a charged call's answer on (Gateway._settle_world).""" - return {tid: self._fire_tasks(trig) for tid, trig in self._triggers.items() if self._at_work(tid)} + """Each trigger at work now, with the tasks doing it: one checking its state after a write (``evaluating``), or + with a fire at work (``_at_work``: running, and not only waiting on a task time still ahead). What fixed mode + holds a charged call's answer on (Gateway._settle_world): a check that matches starts its fire before its task + ends, so the hold waits for that fire in turn, however long the check took.""" + return {tid: self._work_tasks(trig) for tid, trig in self._triggers.items() + if trig["evaluating"] or self._at_work(tid)} def _at_work(self, tid: str) -> bool: """Whether a fire of trigger ``tid`` is at work: more fires running than waiting on a task time ahead.""" @@ -1207,8 +1210,10 @@ def _at_work(self, tid: str) -> bool: return trig["running"] > ahead @staticmethod - def _fire_tasks(trig: dict) -> list[asyncio.Task]: - return [t for t in [trig["task"], *trig["alongside"]] if t is not None] + def _work_tasks(trig: dict) -> list[asyncio.Task]: + """``trig``'s fire tasks, and its state check's while one is under way.""" + check = trig["eval_task"] if trig["evaluating"] else None + return [t for t in [trig["task"], *trig["alongside"], check] if t is not None] def _resolve_first_mark(self, trig: dict, now: datetime) -> None: """Stamp the first mark for a non-anchored time-trigger; event-anchored ones wait for _resolve_dependents.""" diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index be377df5f..aca15145a 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -44,8 +44,9 @@ it, ``settings["clock"]["fixed"]`` names the clock in fixed mode, and the judge reads each wake's, its nudge's included. Fixed mode ended mid-run (a hook's set_rate, say) is logged once (``fixed_mode_off``) and no window is opened after. A window that can't be opened or closed ends the run as an infrastructure error (``WorkWindowError``): one left open - would charge calls made after the turn. More than one clock in fixed mode is refused at setup: their task times would - drift apart. + would charge calls made after the turn. The run is recorded as agent_turn_infra_error (error_code + ``agent_env.work_window_failed``), so a verifier the task runs all the same leaves it ungraded. More than one clock + in fixed mode is refused at setup: their task times would drift apart. - The agent can schedule its own wake-ups (scheduled checks) when the run is multi-day, at least ``scheduled_check_min_interval`` apart; ``scheduled_checks`` turns them on or off whatever the run's length. A check's wake counts toward ``max_wakes``. @@ -183,7 +184,7 @@ from agent_env.task_step.task_step import RetryConfig, TaskStep from agent_env.task_step.task_steps.agent import user_sim_versions from agent_env.task_step.task_steps.agent.deploy_user_sim_agent import USER_SIMS_KEY, recorded_instructions, user_sim_model -from agent_env.task_step.task_steps.clock_mode import WorkWindowError +from agent_env.task_step.task_steps.clock_mode import WORK_WINDOW_ERROR_CODE, WorkWindowError from agent_env.task_step.task_steps.notification_delivery import delivered_parts, label_time, take_due from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import ended_turn_error from agent_env.task_step.task_steps.server_fault_logs import capture_server_fault_logs @@ -725,6 +726,8 @@ async def go(self) -> None: await self.loop(now) except Exception as e: self.error = f"{type(e).__name__}: {e}" + if isinstance(e, WorkWindowError): # the gateway's failure, not the agent's: recorded so, so none grades it + self._failed(INFRA_ERROR, self.error, WORK_WINDOW_ERROR_CODE) self.end_reason = self.end_reason or "step_error" self.log("error", error=self.error) raise diff --git a/src/agent_env/task_step/task_steps/clock_mode.py b/src/agent_env/task_step/task_steps/clock_mode.py index 6accb6d4f..d4ab74a15 100644 --- a/src/agent_env/task_step/task_steps/clock_mode.py +++ b/src/agent_env/task_step/task_steps/clock_mode.py @@ -25,7 +25,7 @@ import httpx from agent_env.env.gateway.constants import CLOCK_FIXED_MODE, EXT_CLOCK_URI, FIXED_SECONDS_PER_CALL -from agent_env.task_step.context import AgentTurnInfraError, StepContextError +from agent_env.task_step.context import INFRA_ERROR, AgentTurnInfraError, StepContextError logger = logging.getLogger(__name__) @@ -98,11 +98,16 @@ def one_fixed_mode_env(context, step: str) -> Optional[Any]: return envs[0] if envs else None +# The error_code of a run whose agent's work window couldn't be opened or closed, beside error_type infra_error. +WORK_WINDOW_ERROR_CODE = "agent_env.work_window_failed" + + class WorkWindowError(AgentTurnInfraError): """The agent's work window could not be opened, or, worse, closed: one left open would charge whoever calls with its roles after the agent (a verifier's or collect_artifacts' header-less reads, for the default role) and move the world on under the grading, so the run says nothing about the agent. An infrastructure failure, which a - retry_config can redo.""" + retry_config can redo; the run is recorded as one (error_type infra_error, ``WORK_WINDOW_ERROR_CODE``), so a + verifier the task runs all the same (``fail_task_on_error`` off) doesn't grade what the agent did.""" @asynccontextmanager @@ -110,9 +115,9 @@ async def agent_work_window(context, step_id: str, roles: list[str]) -> AsyncIte """A work window naming ``roles`` held open on the env in fixed mode, if there is one, around the agent's work: yields the window's id, or None with no env in fixed mode, or with fixed mode already ended there (409, logged). Closed however the work ends, and what it charged recorded under ``context.metadata["work_windows"]``. Fails - closed: a close that still fails after a retry raises WorkWindowError once the agent's work is done; when the work - itself raised, that error stays the one raised, the close's failure logged and noted on it. Refuses more than one - env in fixed mode.""" + closed: a close that still fails after a retry saves the step's responses as an infrastructure failure + (``_saved_as_infra``) and raises WorkWindowError once the agent's work is done; when the work itself raised, that + error stays the one raised, the close's failure logged and noted on it. Refuses more than one env in fixed mode.""" env = one_fixed_mode_env(context, step_id) if env is None: yield None @@ -150,9 +155,11 @@ async def _close_window(context, env, step_id: str, window: str, roles: list[str except Exception as e: detail = (f"HTTP {e.response.status_code}: {e.response.text[:_MAX_ERROR_CHARS]}" if isinstance(e, httpx.HTTPStatusError) else f"{type(e).__name__}: {str(e)[:_MAX_ERROR_CHARS]}") - raise WorkWindowError(f"{step_id}: closing the agent's work window {window!r} on env '{env.env_id}' failed " - f"({detail}): it may still charge calls made after the agent, so the run is not " - "graded") from e + error = WorkWindowError(f"{step_id}: closing the agent's work window {window!r} on env '{env.env_id}' failed " + f"({detail}): it may still charge calls made after the agent, so the run is not " + "graded") + _saved_as_infra(context, step_id, str(error)) + raise error from e mine = (answer or {}).get("window") or {} context.metadata.setdefault(WORK_WINDOWS_KEY, []).append({ "step_id": step_id, "env_id": env.env_id, "window": window, "roles": list(roles), @@ -162,6 +169,19 @@ async def _close_window(context, env, step_id: str, window: str, roles: list[str "it charged until then") +def _saved_as_infra(context, step_id: str, message: str) -> None: + """The responses ``step_id`` saved, marked an infrastructure failure (error_type infra_error, + ``WORK_WINDOW_ERROR_CODE``) as prompt_agent marks its agent's own: what the agent said stands, but no verifier + checks it against a world its window may have moved on. An agent error the response had is kept in the message.""" + for response in context.prompt_responses: + if response.step_id != step_id: + continue + before = (f" (before it: {response.error_type}" + + (f": {response.error_message}" if response.error_message else "") + ")") if response.error_type else "" + response.error_type, response.error_code = INFRA_ERROR, WORK_WINDOW_ERROR_CODE + response.error_message = message + before + + async def _window_call(env, method: str, params: dict) -> Any: """A window call, made once more after a failure that isn't the gateway's own answer to it (a 4xx): both are safe to repeat.""" diff --git a/tst/unit/env/gateway/fixed_clock_test.py b/tst/unit/env/gateway/fixed_clock_test.py index 6c35f9aa2..7ed4d12a3 100644 --- a/tst/unit/env/gateway/fixed_clock_test.py +++ b/tst/unit/env/gateway/fixed_clock_test.py @@ -870,24 +870,102 @@ async def executor(engine, ex, instruction, context_id): assert hold["still_running"] == [] -@pytest.mark.asyncio -async def test_a_call_answered_after_its_window_closed_counts_in_a_retried_close(gw, monkeypatch): - """The window open when the call was answered counts its charge, even once closed: a close retried after answers - it (the turn's own close, made while the call waited on its barrier, came first).""" - _executor(monkeypatch, 0.4) +def _ack_barrier(gw: Gateway) -> None: + """bob acknowledges each app_lookup, the call held at its barrier until he has.""" gw._trigger_engine.register({ "watch_roles": ["default"], "executors": {"bob": {"a2a_url": "http://bob", "role": "bob"}}, "triggers": [{"id": "ack", "when": {"type": "action", "tool": "app_lookup"}, "barrier": {"at": "provoking_call"}, "actions": [{"type": "nl", "executor": "bob", "instruction": "ack"}]}]}) + + +async def _set_time_and_on_again(client: httpx.AsyncClient) -> None: + """A new timeline, fixed mode on again on it and the window opened again, the same id: a later run's setup.""" + r = await client.put("/clock/set-time", json={"virtual_time": "2026-11-09T09:00:00Z", + "virtual_seconds_per_real_second": 0}) + assert r.status_code == 200, r.text + assert (await _fixed(client)).status_code == 200 + assert (await _open(client)).status_code == 200 + + +async def _reopened(client: httpx.AsyncClient) -> None: + assert (await _close(client)).status_code == 200 + assert (await _open(client)).status_code == 200 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("change,now", [ + (lambda client: client.put("/clock/set-rate", json={"virtual_seconds_per_real_second": 0}), T0), + (_set_time_and_on_again, "2026-11-09T09:00:00Z"), + (lambda client: _fixed(client, on=False), T0), + (_close, T0), + (_reopened, T0), +], ids=["set_rate", "set_time then on again", "fixed off", "window closed", "window closed and opened again"]) +async def test_a_call_whose_window_ended_while_it_waited_on_its_barrier_is_not_charged(gw, monkeypatch, change, now): + """The charge is decided as the call is answered and made once its barriers settle: if, meanwhile, fixed mode + ended (a set_rate, a set_time, turned off) or the call's window closed, even to open again by the same id, the + window it was answered in is gone and the clock is not moved; the skip is logged.""" + _executor(monkeypatch, 0.4) + _ack_barrier(gw) async with _client(gw) as client: await _working(client) call = asyncio.create_task(_call(client, "app_lookup")) await asyncio.sleep(0.2) - first = (await _close(client)).json()["window"] + await change(client) assert (await call).status_code == 200 - retried = (await _close(client)).json()["window"] - assert (first["calls"], retried["calls"], retried["virtual_seconds"]) == (0, 1, 60.0) + assert await _now(client) == now + fixed = await _fixed_state(client) + assert (fixed["calls"], fixed["virtual_seconds"], fixed["by_role"]) == (0, 0.0, {}) + assert all(w["calls"] == 0 for w in fixed["windows"]) + assert (await _close(client)).json()["window"]["calls"] == 0 + (skipped,) = _logged(gw, "fixed_clock_skipped") + assert (skipped["tool"], skipped["role"]) == ("app_lookup", "default") + assert "while the call waited" in skipped["reason"] + assert _logged(gw, "fixed_clock_charge") == [] and _logged(gw, "fixed_clock_hold") == [] + + +@pytest.mark.asyncio +async def test_a_call_whose_window_stayed_open_through_its_barrier_is_charged_in_it(gw, monkeypatch): + """Another window opened and closed meanwhile changes nothing for the call's own.""" + _executor(monkeypatch, 0.4) + _ack_barrier(gw) + async with _client(gw) as client: + await _working(client) + call = asyncio.create_task(_call(client, "app_lookup")) + await asyncio.sleep(0.2) + await _open(client, ("solver",), window="other") + await _close(client, "other") + assert (await call).status_code == 200 + assert await _now(client) == "2026-11-08T17:01:00Z" + assert (await _close(client)).json()["window"]["calls"] == 1 + assert _logged(gw, "fixed_clock_skipped") == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("check_s", [0.05, 0.6]) +async def test_a_state_trigger_the_call_sets_off_lands_before_the_answer_however_slow_its_check(gw, monkeypatch, + check_s): + """A state trigger checks the world after the agent's write; the hold waits for the check, then for the fire it + starts, so bob's reply is written at the same task time, before the call is answered, for a fast check and a slow + one, and the agent's later calls can't move the clock under it.""" + replies = _executor(monkeypatch, 0.05) + + async def check(engine, check, ctx=None, role=None): + await asyncio.sleep(check_s) + return True + monkeypatch.setattr(TriggerEngine, "_run_check", check) + gw._trigger_engine.register({ + "watch_roles": ["default"], "executors": {"bob": {"a2a_url": "http://bob", "role": "bob"}}, + "triggers": [{"id": "restocked", "when": {"type": "state", "check": {"tool": "app_lookup", + "predicate": {"exists": True}}}, + "actions": [{"type": "nl", "executor": "bob", "instruction": "reply"}]}]}) + async with _client(gw) as client: + await _working(client) + assert (await _call(client, "app_lookup")).status_code == 200 + assert replies == ["2026-11-08T17:01:00Z"] + assert _trigger(gw, "restocked")["fire_count"] == 1 + (hold,) = _logged(gw, "fixed_clock_hold") + assert hold["still_running"] == [] and hold["held_s"] >= check_s @pytest.mark.asyncio diff --git a/tst/unit/task_step/clock_mode_test.py b/tst/unit/task_step/clock_mode_test.py index 1250e4ea5..86f0dddcd 100644 --- a/tst/unit/task_step/clock_mode_test.py +++ b/tst/unit/task_step/clock_mode_test.py @@ -16,12 +16,21 @@ from agent_env.env.gateway import gateway as gw_mod from agent_env.env.gateway.constants import AGENT_ENV_ROLE_HEADER, EXT_STEP_URI, WELL_KNOWN_PATH from agent_env.env.gateway.gateway import Gateway -from agent_env.task_step.context import AgentTurnInfraError, DeployedAgent, StepContextError, TaskStepContext +from agent_env.task_step.context import ( + INFRA_ERROR, + AgentTurnInfraError, + DeployedAgent, + StepContextError, + TaskStepContext, +) from agent_env.task_step.task_steps import prompt_agent as pa_mod from agent_env.task_step.task_steps.clock_mode import WorkWindowError from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep from agent_env.task_step.task_steps.set_env_clock_rate import SetEnvClockRateTaskStep from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep +from agent_env.task_step.task_steps.verifiers.agent_prompt_response_verifier import ( + AgentPromptResponseVerifierTaskStep, +) T0 = "2026-11-09T14:00:00Z" GATEWAY = "http://gateway.test" @@ -509,6 +518,33 @@ async def turn(): assert "work_windows" not in context.metadata +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_whose_window_cant_be_closed_saves_its_response_as_an_infra_failure(world, monkeypatch): + """A task that goes on past the failed step (fail_task_on_error off) reaches its verifiers: the response the agent + gave is saved as an infrastructure failure (error_type infra_error), as an agent's own infra_error is, so no + verifier checks what it says.""" + async def turn(): + await world.call(role="solver") + + _agent(monkeypatch, world, turn) + context = _with_agent(await world.context()) + await _sync(clock_mode="fixed").execute(context) + _close_fails(monkeypatch) + + with pytest.raises(WorkWindowError): + await _prompt().execute(context) + [response] = context.prompt_responses + assert (response.response, response.error_type, response.error_code) == ( + "done", INFRA_ERROR, "agent_env.work_window_failed") + assert "closing the agent's work window" in response.error_message + verifier = AgentPromptResponseVerifierTaskStep("check", None, prompt_id=response.prompt_id, verifier_id="words", + criteria=[{"type": "response_contains", "needles": ["done"]}]) + await verifier.execute(context) + checked = context.metadata["verifications"]["words"] + assert checked["score"] == 0 and [r["id"] for r in checked["results"]] == ["prompt_error"] + + @pytest.mark.asyncio @pytest.mark.usefixtures("local_stores") async def test_prompt_agent_keeps_the_agents_own_error_when_its_window_cant_be_closed_either(world, monkeypatch): diff --git a/tst/unit/task_step/test_always_on_fixed_clock.py b/tst/unit/task_step/test_always_on_fixed_clock.py index 212c9fdf5..fd18c9bff 100644 --- a/tst/unit/task_step/test_always_on_fixed_clock.py +++ b/tst/unit/task_step/test_always_on_fixed_clock.py @@ -15,10 +15,13 @@ from agent_env.env.env import DeployedGatewayEnv from agent_env.env.gateway.constants import EXT_CLOCK_URI, GATEWAY_EXTENSIONS, WELL_KNOWN_PATH from agent_env.env.gateway.triggers import TriggerEngine -from agent_env.task_step.context import AgentTurnInfraError +from agent_env.task_step.context import INFRA_ERROR, AgentTurnInfraError from agent_env.task_step.task_steps import always_on as ao from agent_env.task_step.task_steps.clock_mode import WorkWindowError from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep +from agent_env.task_step.task_steps.verifiers.agent_prompt_response_verifier import ( + AgentPromptResponseVerifierTaskStep, +) from tst.unit.task_step.always_on_harness import GATEWAY, ROLE, Rig pytestmark = pytest.mark.usefixtures("local_stores") @@ -270,6 +273,52 @@ async def call(env, uri, method, params=None, **kw): assert "WorkWindowError" in error["error"] +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["open_work_window", "close_work_window"]) +async def test_a_window_that_fails_leaves_the_run_an_infra_failure_its_verifiers_leave_ungraded(monkeypatch, tmp_path, + method): + """A task that goes on past the failed step (fail_task_on_error off) reaches its verifiers: a window that couldn't + be opened or closed is the gateway's failure, not the agent's, so the run is recorded as an infrastructure failure + (agent_turn_infra_error, its response's error_type infra_error) and each verifier leaves it ungraded.""" + async def agent(n, texts, rig): + await rig.call("market_search") + rig.message("Chicago has 2 seats") + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=({"outcome": "reply", "message": "great"},)) + rig.tool("market_search") + ctx = rig.context() + await _fixed_mode(monkeypatch, rig, ctx) + + class Struggling: + env_id = "world" + + async def invoke(self, uri, method, params=None, *, timeout): + raise httpx.ConnectError("the gateway is struggling") + real_call = ao._call + + async def call(env, uri, called, params=None, **kw): + return await real_call(Struggling() if called == method else env, uri, called, params, **kw) + monkeypatch.setattr(ao, "_call", call) + monkeypatch.setattr(ao, "CALL_RETRY_MAX_SLEEP_SECONDS", 0) # an open is retried as any call is: no need to wait + step = rig.step(settle_timeout_seconds=0.2, max_wakes=2) + with pytest.raises(WorkWindowError): + await rig.run(step, ctx) + + record = rig.record(ctx) + assert (record["end_reason"], record["error_type"], record["error_code"]) == ( + ao.AGENT_TURN_INFRA_ERROR, INFRA_ERROR, "agent_env.work_window_failed") + assert "work window" in record["error"] + assert ao.ended_on_infra_failure(ctx.metadata, step.id) + [response] = ctx.prompt_responses + assert (response.error_type, response.error_code) == (INFRA_ERROR, "agent_env.work_window_failed") + verifier = AgentPromptResponseVerifierTaskStep("check", None, prompt_id="ask", verifier_id="words", criteria=[ + {"type": "response_contains", "needles": ["Chicago"]}]) + await verifier.execute(ctx) + checked = ctx.metadata["verifications"]["words"] + assert (checked["score"], checked["results"]) == (None, []) and "work_window" in checked["skipped"] + + @pytest.mark.asyncio async def test_fixed_mode_ended_between_turns_is_found_at_the_next_window_at_once(monkeypatch, tmp_path): """The gateway's refusal of the next turn's window (409) is its answer, not a failure to retry.""" From 9d8fa088ae40e9abfc51cf1866161caa695f285d Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Thu, 3 Dec 2026 23:40:07 -0800 Subject: [PATCH 6/9] fix(verifiers): a prompt_agent run whose work window failed is left ungraded, not scored 0 (FD-7183) Review on PR 1003: prompt_agent saves its response as infra_error when its work window can't be closed, but the verifiers' skip check only knew always_on records, so the gateway's failure scored 0 against the agent. ended_on_infra_failure now also takes the prompt response and recognizes one saved with error_code agent_env.work_window_failed (clock_mode.work_window_failed). The response check and the judge (rubrics_verifier's _not_graded_reason, and always_on_agent_verifier's) leave such a run ungraded. Any other infra_error a prompt_agent turn ended on still scores 0 with a prompt_error row, as before. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/always_on.py | 17 +++++--- .../task_step/task_steps/clock_mode.py | 12 +++++- .../agent_prompt_response_verifier.py | 13 ++++--- .../verifiers/always_on_agent_verifier.py | 2 +- .../task_steps/verifiers/rubrics_verifier.py | 14 +++++-- tst/unit/task_step/clock_mode_test.py | 39 +++++++++++++++++-- 6 files changed, 74 insertions(+), 23 deletions(-) diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index aca15145a..99ff6b7e7 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -86,7 +86,8 @@ failure: the run is recorded the same way, with end reason agent_turn_infra_error and the turn's ``error_code``, and then the step fails with ``AgentTurnInfraError``, so a ``retry_config`` can redo it. A verifier reaches such a run only when the task goes on past the failed step (its ``fail_task_on_error`` off), and then leaves it ungraded, never - scored against the agent (``ended_on_infra_failure``). + scored against the agent (``ended_on_infra_failure``, which also covers a prompt_agent response saved as its work + window failing). - With ``continue_after_wake_limit`` on, a turn (a wake's, or its nudge's) that reaches its time limit (``timeout_seconds``) or its tool-call limit (``max_turns``) ends only that wake: what it did stands, its messages to the user are taken as any wake's are, and the run goes on to its next event, still bounded by ``max_wakes`` and the @@ -184,7 +185,7 @@ from agent_env.task_step.task_step import RetryConfig, TaskStep from agent_env.task_step.task_steps.agent import user_sim_versions from agent_env.task_step.task_steps.agent.deploy_user_sim_agent import USER_SIMS_KEY, recorded_instructions, user_sim_model -from agent_env.task_step.task_steps.clock_mode import WORK_WINDOW_ERROR_CODE, WorkWindowError +from agent_env.task_step.task_steps.clock_mode import WORK_WINDOW_ERROR_CODE, WorkWindowError, work_window_failed from agent_env.task_step.task_steps.notification_delivery import delivered_parts, label_time, take_due from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import ended_turn_error from agent_env.task_step.task_steps.server_fault_logs import capture_server_fault_logs @@ -2332,10 +2333,14 @@ def _append_prompt_response(self, final_text: str) -> None: "final": "the user's final line", "step:final": "the end of the job"} -def ended_on_infra_failure(metadata: dict, step_id: Optional[str]) -> bool: - """Whether ``step_id`` is an always_on step whose run ended on an infrastructure failure (agent_turn_infra_error), - which failed the step: a verifier the task runs all the same (``fail_task_on_error`` off) leaves it ungraded, never - scored against the agent. False for any other step's prompt and any other end.""" +def ended_on_infra_failure(metadata: dict, step_id: Optional[str], response: Optional[PromptResponse] = None) -> bool: + """Whether ``step_id``'s run ended on an infrastructure failure that failed the step, so a verifier the task runs + all the same (``fail_task_on_error`` off) leaves it ungraded, never scored against the agent: an always_on step's + that ended agent_turn_infra_error, or ``response``, any step's, saved as its agent's work window failing + (``clock_mode.work_window_failed``, a prompt_agent step's). False for any other prompt and any other end: another + infra_error a prompt_agent turn ended on still scores 0 unchecked.""" + if work_window_failed(response): + return True record = (metadata.get(ALWAYS_ON_KEY) or {}).get(step_id) if step_id else None return isinstance(record, dict) and record.get("end_reason") == AGENT_TURN_INFRA_ERROR diff --git a/src/agent_env/task_step/task_steps/clock_mode.py b/src/agent_env/task_step/task_steps/clock_mode.py index d4ab74a15..5dd7b06af 100644 --- a/src/agent_env/task_step/task_steps/clock_mode.py +++ b/src/agent_env/task_step/task_steps/clock_mode.py @@ -169,10 +169,18 @@ async def _close_window(context, env, step_id: str, window: str, roles: list[str "it charged until then") +def work_window_failed(response) -> bool: + """Whether ``response`` was saved as its agent's work window failing (error_type infra_error, + ``WORK_WINDOW_ERROR_CODE``): the gateway's failure, not the agent's, so a verifier leaves the run ungraded + (``always_on.ended_on_infra_failure``) rather than scoring it 0 as any other failed prompt_agent turn.""" + return response is not None and (response.error_type, response.error_code) == (INFRA_ERROR, WORK_WINDOW_ERROR_CODE) + + def _saved_as_infra(context, step_id: str, message: str) -> None: """The responses ``step_id`` saved, marked an infrastructure failure (error_type infra_error, - ``WORK_WINDOW_ERROR_CODE``) as prompt_agent marks its agent's own: what the agent said stands, but no verifier - checks it against a world its window may have moved on. An agent error the response had is kept in the message.""" + ``WORK_WINDOW_ERROR_CODE``): what the agent said stands, but a verifier leaves it ungraded + (``work_window_failed``) rather than check it against a world its window may have moved on. An agent error the + response had is kept in the message.""" for response in context.prompt_responses: if response.step_id != step_id: continue diff --git a/src/agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py b/src/agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py index c2daad6ef..4a974e52b 100644 --- a/src/agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py @@ -22,7 +22,7 @@ import uuid from typing import Any, ClassVar, Optional -from agent_env.task_step.context import StepContextError, TaskStepContext +from agent_env.task_step.context import PromptResponse, StepContextError, TaskStepContext from agent_env.task_step.task_step import TaskStepDependency from agent_env.task_step.task_steps.always_on_ends import ended_on_agent_failure from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator @@ -89,7 +89,7 @@ async def verify(self, context: TaskStepContext) -> Verification: if prompt_response is None: raise StepContextError(f"PromptResponse with prompt_id='{self.prompt_id}' not found in context") - if _ended_on_infra_failure(context, prompt_response.step_id): + if _ended_on_infra_failure(context, prompt_response): reason = (f"the run's turn failed for an infrastructure reason (error_code={prompt_response.error_code}), " "not the assistant's") logger.warning(f"Not checking '{self.verifier_id}': {reason}") @@ -193,9 +193,10 @@ def _criterion_problems(criterion: Any) -> list[str]: return [] -def _ended_on_infra_failure(context: TaskStepContext, step_id: Optional[str]) -> bool: - """An always_on run that ended on an infrastructure failure is left unchecked, never scored against the agent - (``ended_on_infra_failure``); any other failed prompt scores 0 unchecked.""" +def _ended_on_infra_failure(context: TaskStepContext, prompt_response: PromptResponse) -> bool: + """An always_on run that ended on an infrastructure failure, or a prompt response saved as its agent's work window + failing, is left unchecked, never scored against the agent (``ended_on_infra_failure``); any other failed prompt + scores 0 unchecked.""" from agent_env.task_step.task_steps.always_on import ended_on_infra_failure # here: always_on imports our peers - return ended_on_infra_failure(context.metadata, step_id) + return ended_on_infra_failure(context.metadata, prompt_response.step_id, prompt_response) diff --git a/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py b/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py index 642fef40f..5619161a8 100644 --- a/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py @@ -391,7 +391,7 @@ def _not_graded_reason(self, context: TaskStepContext, prompt_response: PromptRe """A run that ended on an infrastructure failure (``ended_on_infra_failure``) is left ungraded, never scored against the agent: its step failed so a retry could redo it, and this verifier reaches it only when the task goes on past that failure.""" - if not ended_on_infra_failure(context.metadata, prompt_response.step_id): + if not ended_on_infra_failure(context.metadata, prompt_response.step_id, prompt_response): return None return (f"the run's turn failed for an infrastructure reason (error_code={prompt_response.error_code}), not " "the assistant's") diff --git a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py index aac9e51b9..2e5396dfe 100644 --- a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py @@ -56,6 +56,7 @@ from agent_env.store.ids import is_local_id from agent_env.task_step.task_step import TaskStep, TaskStepDependency from agent_env.task_step.usage import StepUsage +from agent_env.task_step.task_steps.clock_mode import work_window_failed from agent_env.task_step.task_steps.verifiers.run_context import Run, load_run_context, render_run_context from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator, aggregate_score from agent_env.task_step.task_steps.verifiers.verifier import VERIFICATIONS_KEY, Verification, VerifierTaskStep @@ -821,10 +822,15 @@ def _not_graded(self, reason: str) -> RubricsVerdict: return RubricsVerdict(skipped=reason, output=self._entry_format_fields(), mistakes_entry=mistakes) def _not_graded_reason(self, context: TaskStepContext, prompt_response: PromptResponse) -> Optional[str]: - """Why a run is left ungraded (``_not_graded``: no score, no rows), else None: never here, so a prompt_agent - turn that failed for an infrastructure reason scores 0 unjudged (a ``prompt_error`` row) as any failed prompt - does. always_on_agent_verifier leaves ungraded an always_on run that ended on an infrastructure failure.""" - return None + """Why a run is left ungraded (``_not_graded``: no score, no rows), else None: a prompt response saved as its + agent's work window failing (``clock_mode.work_window_failed``), the gateway's failure, not the agent's. Any + other prompt_agent turn that failed for an infrastructure reason scores 0 unjudged (a ``prompt_error`` row) as + any failed prompt does. always_on_agent_verifier also leaves ungraded an always_on run that ended on an + infrastructure failure.""" + if not work_window_failed(prompt_response): + return None + return (f"the run's turn failed for an infrastructure reason (error_code={prompt_response.error_code}), not " + "the assistant's") def _judges_failed_run(self, context: TaskStepContext, prompt_response: PromptResponse) -> bool: """Whether a prompt response whose agent failed (an ``error_type`` that isn't ``infra_error``) is judged as it diff --git a/tst/unit/task_step/clock_mode_test.py b/tst/unit/task_step/clock_mode_test.py index 86f0dddcd..e459b4c87 100644 --- a/tst/unit/task_step/clock_mode_test.py +++ b/tst/unit/task_step/clock_mode_test.py @@ -20,6 +20,7 @@ INFRA_ERROR, AgentTurnInfraError, DeployedAgent, + PromptResponse, StepContextError, TaskStepContext, ) @@ -31,6 +32,7 @@ from agent_env.task_step.task_steps.verifiers.agent_prompt_response_verifier import ( AgentPromptResponseVerifierTaskStep, ) +from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerifierTaskStep T0 = "2026-11-09T14:00:00Z" GATEWAY = "http://gateway.test" @@ -520,10 +522,10 @@ async def turn(): @pytest.mark.asyncio @pytest.mark.usefixtures("local_stores") -async def test_prompt_agent_whose_window_cant_be_closed_saves_its_response_as_an_infra_failure(world, monkeypatch): +async def test_prompt_agent_whose_window_cant_be_closed_is_left_ungraded_by_its_verifiers(world, monkeypatch): """A task that goes on past the failed step (fail_task_on_error off) reaches its verifiers: the response the agent - gave is saved as an infrastructure failure (error_type infra_error), as an agent's own infra_error is, so no - verifier checks what it says.""" + gave is saved as an infrastructure failure (error_type infra_error, error_code agent_env.work_window_failed), the + gateway's failure, not the agent's, so a verifier leaves the run ungraded rather than scoring it 0.""" async def turn(): await world.call(role="solver") @@ -542,7 +544,36 @@ async def turn(): criteria=[{"type": "response_contains", "needles": ["done"]}]) await verifier.execute(context) checked = context.metadata["verifications"]["words"] - assert checked["score"] == 0 and [r["id"] for r in checked["results"]] == ["prompt_error"] + assert (checked["score"], checked["results"]) == (None, []) and "work_window" in checked["skipped"] + assert context.metadata["grades"]["check"]["verifier_status"] == "skipped" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("error_code,ungraded", [("agent_env.work_window_failed", True), ("psi.gateway", False)], + ids=["its window failed", "another infra error"]) +async def test_a_prompt_agent_response_whose_window_failed_is_left_ungraded_and_another_infra_error_scores_0( + error_code, ungraded): + """Only a prompt_agent response saved as its agent's work window failing is left ungraded, by the response check + and the judge alike; any other infra_error a prompt_agent turn ended on still scores 0 unchecked (a prompt_error + row), as it always has.""" + def context() -> TaskStepContext: + return TaskStepContext(prompt_responses=[PromptResponse( + prompt_id="p1", response="done", prompt_text="do it", step_id="solve", error_type=INFRA_ERROR, + error_code=error_code, error_message="the gateway failed")]) + + checked_ctx = context() + await AgentPromptResponseVerifierTaskStep("check", None, prompt_id="p1", verifier_id="words", criteria=[ + {"type": "response_contains", "needles": ["done"]}]).execute(checked_ctx) + judged_ctx = context() + judge = RubricsVerifierTaskStep(id="judge", version=1, prompt_id="p1", verifier_id="vt", use_agent_judge=False, + use_trajectory=False, criteria=[{"id": "done", "title": "Did it", "check": "done"}]) + await judge.execute(judged_ctx) + + for entry in (checked_ctx.metadata["verifications"]["words"], judged_ctx.metadata["verifications"]["vt"]): + if ungraded: + assert (entry["score"], entry["results"]) == (None, []) and error_code in entry["skipped"] + else: + assert entry["score"] == 0 and [r["id"] for r in entry["results"]] == ["prompt_error"] @pytest.mark.asyncio From 586df8bcfc6685b33b7c6ea3663595d808196173 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Fri, 4 Dec 2026 13:32:59 -0800 Subject: [PATCH 7/9] fix(task_step): charge a role-less agent's CLI calls, and close work windows left open (FD-7183) Two bugs an independent review found in fixed mode. A role-less agent's CLI calls were never charged. prompt_agent and always_on opened the window for `agent.role or "default"`, but deploy_agent sets AGENT_ENV_ROLE only for an agent with a role, so the generated MCP CLI sends its own default, `cli`, which no window named: nothing was charged and nothing logged. The window now names both `default` and `cli` for such an agent (clock_mode.agent_window_roles, used by both steps). The CLI's default role is unchanged, so no task outside fixed mode changes. No harness-side caller (verifier, collect_artifacts, user sim, contacts, triggers, post-turn hooks) sends role `cli`; only the generated CLI does. A window whose open or close failed was never cleaned up, and could go on charging later callers, a retry's or a later step's verifiers included: - After a failed open, the step now sends a close for that window id before raising (a 404 is fine), since the gateway may have opened it and only its answer was lost. - A window that may still be open (its close failed twice, or the close after a failed open failed too) is recorded in context.metadata["work_windows_left_open"], and the next step to open a window on that env closes it first, failing closed with WorkWindowError (before the agent starts) if that close fails. - Before opening, the step also closes any window the gateway shows open under its own step id. A step never runs beside itself, so such a window is an earlier attempt's: this covers a retry whose rollback undid the failed attempt's record (undo_steps drops everything the span wrote), and a worker that died with its context. - always_on's cancelled-turn path now records the run as an infrastructure failure (error_code agent_env.work_window_failed), as its other close-failure path does; the run stays cancelled. Why not have the gateway close an overlapping window on open: two windows naming the same role can be open at once on purpose. Task steps with no dependency between them run concurrently, so two prompt_agent steps whose agents share a role (two role-less agents, say) each hold a window naming it, and the gateway is built for that (per-window serials in Ticket, test_two_windows_each_count_their_own_roles). Replacing on open would close the first step's window when the second opens, and once the second closed, the first agent's later calls would go uncharged. always_on nudges don't overlap (each turn's window closes before the next opens), and WindowConflict only concerns re-opening the same id. Left open: a retry whose span starts after the clock step but before the failed step, with header-less tool calls in between, still runs those under the earlier attempt's window until the step itself re-runs and closes it (a span that re-runs the clock step ends every window anyway). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- .../task_step/task_steps/always_on.py | 77 +++++--- .../task_step/task_steps/clock_mode.py | 168 +++++++++++++++--- .../task_step/task_steps/prompt_agent.py | 4 +- tst/unit/task_step/clock_mode_test.py | 154 +++++++++++++++- .../task_step/test_always_on_fixed_clock.py | 113 ++++++++++++ 6 files changed, 463 insertions(+), 55 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9a8873454..033663230 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,7 +191,7 @@ and deserialized through a registry. | Package | Contents | |---|---| -| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its fixed mode (`/clock/fixed`, `env/gateway/fixed_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "fixed"` on a clock at rate 0 and any later set_time, set_rate or clear turns off, ending every open window, moves the frozen clock on by a fixed `FIXED_SECONDS_PER_CALL` (60 s, not configurable) for each answered tool call made while a work window naming its role is open (`/clock/fixed/window`, PUT to open with `roles`, DELETE to close, answering its totals; both control routes): prompt_agent opens one for its agent's role around its conversation and always_on one around each turn, nudges included (`task_steps/clock_mode.py` `agent_work_window`), each failing closed, as an infra error (`WorkWindowError`), when a window can't be closed (or always_on's opened), the run recorded as one (error_type `infra_error`, error_code `agent_env.work_window_failed`) so a verifier the task runs all the same grades none of it, and both refuse more than one env in fixed mode, so a setup script, a verifier, collect_artifacts, a user sim, a contact or the agent between its turns is never charged, the agent's role outside its window logged as `fixed_clock_outside_window`. A charge, on the MCP path and the step API's `/step` paths (not a post-turn hook's that shows the control token; never the gateway's own `get_time` or `stay_quiet`), comes after the call's barriers (`Clock.advance_by`), and only if the window it was decided in is still open as it was (fixed mode ended, the clock re-armed or the window closed meanwhile skip it as `fixed_clock_skipped`), then the answer is held until all world work runnable now has landed, every trigger fire at work, every state check a write set going and each deferred call the clock reached (`Gateway._settle_world`), but not a fire waiting on a later task time, the barriers and the hold sharing one budget; each charge is a `fixed_clock_charge` trajectory event and its hold a `fixed_clock_hold`, written even when the call is cancelled. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | +| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its fixed mode (`/clock/fixed`, `env/gateway/fixed_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "fixed"` on a clock at rate 0 and any later set_time, set_rate or clear turns off, ending every open window, moves the frozen clock on by a fixed `FIXED_SECONDS_PER_CALL` (60 s, not configurable) for each answered tool call made while a work window naming its role is open (`/clock/fixed/window`, PUT to open with `roles`, DELETE to close, answering its totals; both control routes): prompt_agent opens one for its agent's role around its conversation and always_on one around each turn, nudges included (`task_steps/clock_mode.py` `agent_work_window`; an agent with no role is charged as `default` and as its generated MCP CLI's `cli`, `agent_window_roles`), each failing closed, as an infra error (`WorkWindowError`), when a window can't be opened or closed, a cancelled always_on run's close included, a window that may still be open recorded under `context.metadata["work_windows_left_open"]` and closed by the next step's open first, as is one the gateway shows under the opening step's own id (an earlier attempt's; the gateway never closes one for another, since two windows may name a role at once), the run recorded as one (error_type `infra_error`, error_code `agent_env.work_window_failed`) so a verifier the task runs all the same grades none of it, and both refuse more than one env in fixed mode, so a setup script, a verifier, collect_artifacts, a user sim, a contact or the agent between its turns is never charged, the agent's role outside its window logged as `fixed_clock_outside_window`. A charge, on the MCP path and the step API's `/step` paths (not a post-turn hook's that shows the control token; never the gateway's own `get_time` or `stay_quiet`), comes after the call's barriers (`Clock.advance_by`), and only if the window it was decided in is still open as it was (fixed mode ended, the clock re-armed or the window closed meanwhile skip it as `fixed_clock_skipped`), then the answer is held until all world work runnable now has landed, every trigger fire at work, every state check a write set going and each deferred call the clock reached (`Gateway._settle_world`), but not a fire waiting on a later task time, the barriers and the hold sharing one budget; each charge is a `fixed_clock_charge` trajectory event and its hold a `fixed_clock_hold`, written even when the call is cancelled. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | | `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, the `attempt_epoch` it was written under, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), each naming exactly what it was sent (`input`: a direct call's messages, response format and settings, an agent call's message, every file its step staged in the judge's sandbox and, for a judge the task deployed, what the task's own `load_artifact` steps put there as the run recorded it, stored by sha256 under `judge-inputs/` in the background, `judge_utils/judge_inputs.py`; the step waits for those uploads, at most 120 s, before it writes its grade, `VerifierTaskStep.settle`, and one that failed or hadn't finished is the call's `input_error`, never a failed grade), and its `verifier_settings` hold the trajectory source of each turn it read (`trajectory_sources`); with `judge_samples` (a count, as a step field, a run override or `--judge-samples` on `run`, `task run` and `eval run`), a rubric_binary or rubric_partial judge grades each criterion that many times, each a call of its own under `judge_batch_concurrency` (an agent judge the verifier deploys gets a deployment of its own per sample, its trajectory staged in each; the task's own judge takes every sample), and keeps its median, the lower middle score on a tie, which fails it, the row the first sample that scored it gave with every sample's score, verdict and justification in its `samples` and its `agreement`, the share of samples giving its verdict; a row under `min_judge_agreement` (0.5 by default, which never fails, so the median decides; 1.0 fails any split; set where `judge_samples` is, `--min-judge-agreement`) fails the grade, its rows kept, and then the step (`JudgeDisagreementError`), and `agent-env run` names the criteria a grade that stood split on (`samples split:`), and one failed sample fails the grade (a run's count or agreement a judge of another format can't take is recorded in `not_sent`) and the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`), each computer its own, a multi env's included, never the gateway's: its boot environment holds only the token's sha256 (`AGENTENV_CONTROL_TOKEN_SHA256`) when its probed card's computer/v1 says `control_token = "sha256"`, else, for a driver an older protocol built, the token itself (`AGENTENV_CONTROL_TOKEN`); the gateway learns each computer's (`CHILD_CONTROL_TOKENS`), puts it in place of its own on that computer's `/svc` routes, and lets a computer's token through only to that computer and its clock watch; a multi env's record grants each computer's `/svc` route its own token (`DeployedGatewayEnv.control_grants`, the longest granted address winning), and `CONTROL_TOKEN_CHILDREN`, the computers an older agent-env booted with the gateway's token, is kept for them; framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 99ff6b7e7..405b1d3da 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -37,16 +37,19 @@ - When the task's clock is in fixed mode (sync_env_clock or set_env_clock_rate with ``clock_mode: "fixed"``, FD-7183), task time passes as the agent works: the clock stays frozen and the gateway moves it on by a fixed charge for each tool call the agent makes inside its work window, so thinking and model latency cost nothing, and what that makes due - lands before the call is answered. The step opens the window, naming the agent's role, around each of the agent's - turns, nudges included, and closes it when the turn ends, so a user sim, a contact, a setup script or a verifier is - never charged, nor the agent between its turns. Each turn's ``agent_turn_end`` (and ``nudge``) records what its work + lands before the call is answered. The step opens the window, naming the agent's role (an agent with none: the + default role and its MCP CLI's, ``clock_mode.agent_window_roles``), around each of the agent's turns, nudges + included, and closes it when the turn ends, so a user sim, a contact, a setup script or a verifier is never charged, + nor the agent between its turns. Each turn's ``agent_turn_end`` (and ``nudge``) records what its work took (``work``, the window's totals) beside the agent's ``output_tokens``, the record's ``counts["fixed_clock"]`` sums it, ``settings["clock"]["fixed"]`` names the clock in fixed mode, and the judge reads each wake's, its nudge's included. Fixed mode ended mid-run (a hook's set_rate, say) is logged once (``fixed_mode_off``) and no window is opened after. - A window that can't be opened or closed ends the run as an infrastructure error (``WorkWindowError``): one left open - would charge calls made after the turn. The run is recorded as agent_turn_infra_error (error_code - ``agent_env.work_window_failed``), so a verifier the task runs all the same leaves it ungraded. More than one clock - in fixed mode is refused at setup: their task times would drift apart. + A window that can't be opened or closed ends the run as an infrastructure error (``WorkWindowError``), a cancelled + run's included: one left open would charge calls made after the turn, so it is recorded for the next step's window + to close first, as each turn's window first closes one an earlier step or attempt left open (``clock_mode``). The run + is recorded as agent_turn_infra_error (error_code ``agent_env.work_window_failed``), so a verifier the task runs all + the same leaves it ungraded. More than one clock in fixed mode is refused at setup: their task times would drift + apart. - The agent can schedule its own wake-ups (scheduled checks) when the run is multi-day, at least ``scheduled_check_min_interval`` apart; ``scheduled_checks`` turns them on or off whatever the run's length. A check's wake counts toward ``max_wakes``. @@ -185,7 +188,16 @@ from agent_env.task_step.task_step import RetryConfig, TaskStep from agent_env.task_step.task_steps.agent import user_sim_versions from agent_env.task_step.task_steps.agent.deploy_user_sim_agent import USER_SIMS_KEY, recorded_instructions, user_sim_model -from agent_env.task_step.task_steps.clock_mode import WORK_WINDOW_ERROR_CODE, WorkWindowError, work_window_failed +from agent_env.task_step.task_steps.clock_mode import ( + WORK_WINDOW_ERROR_CODE, + WorkWindowError, + agent_window_roles, + close_left_open, + close_unsure_open, + record_left_open, + windows_in, + work_window_failed, +) from agent_env.task_step.task_steps.notification_delivery import delivered_parts, label_time, take_due from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import ended_turn_error from agent_env.task_step.task_steps.server_fault_logs import capture_server_fault_logs @@ -572,6 +584,7 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): self.fixed_env: Any = None # the clock in fixed mode, charging the agent's calls in its turns' windows self.fixed_off = False # fixed mode ended there mid-run (logged once): no window is opened after self.turn_window: Optional[str] = None # the work window of the turn in progress, while it is open + self.windows_at_start: list[str] = [] # the windows open on that clock as the run began, until the first turn self.turn_work: Optional[dict] = None # what the last turn's work cost: calls charged, task seconds self.work_total = {"calls": 0, "virtual_seconds": 0.0} self.undo: list[tuple[str, Any]] = [] # (what, coroutine function): the gateway settings to put back at the end @@ -874,34 +887,48 @@ def _configure_fixed(self, env, block: dict) -> None: window naming its role is open (clock/v1 fixed, FD-7183), so each turn opens one and records what it charged.""" self.fixed_env = env self.clock["fixed"] = {"seconds_per_call": block.get("seconds_per_call"), "envs": [env.env_id]} + self.windows_at_start = windows_in(block) + + async def _close_call(self, window: str) -> Any: + """Close ``window`` on the clock in fixed mode, within a short budget; a 404 (no such window) is the gateway's + answer, raised at once.""" + return await _call(self.fixed_env, EXT_CLOCK_URI, "close_work_window", {"window": window}, attempts=2, + timeout=10, answers=(404,)) async def _open_window(self) -> None: - """Open the turn's work window, naming the agent's role, on the clock in fixed mode: ``turn_window``. Fixed mode - ended there since (409) is logged once, and the turn's work takes no task time; another failure ends the run - (WorkWindowError).""" + """Open the turn's work window, naming the agent's roles (``agent_window_roles``), on the clock in fixed mode: + ``turn_window``. Each window left open on that clock is closed first (``close_left_open``): those the run + recorded, and, at the first turn, those an earlier attempt of this step left. Fixed mode ended there since + (409) is logged once, and the turn's work takes no task time; another failure ends the run (WorkWindowError), + once the window is closed in case the gateway opened it all the same (``close_unsure_open``).""" if self.fixed_env is None or self.fixed_off: return + found, self.windows_at_start = self.windows_at_start, [] + await close_left_open(self.ctx, self.fixed_env, self.step.id, found, self._close_call) window = f"{self.step.id}:wake-{self.wakes}:{uuid.uuid4().hex[:8]}" try: - await _call(self.fixed_env, EXT_CLOCK_URI, "open_work_window", {"window": window, "roles": [self.recipient]}, - answers=(409,)) - except httpx.HTTPStatusError as e: - if e.response.status_code != 409: - raise WorkWindowError(f"always_on: wake {self.wakes}: opening the agent's work window on " - f"{self.fixed_env.env_id} failed (HTTP {e.response.status_code})") from e - self._fixed_mode_off() - return + await _call(self.fixed_env, EXT_CLOCK_URI, "open_work_window", + {"window": window, "roles": agent_window_roles(self.agent)}, answers=(409,)) except Exception as e: - raise WorkWindowError(f"always_on: wake {self.wakes}: opening the agent's work window on " - f"{self.fixed_env.env_id} failed: {type(e).__name__}: {e}") from e + if isinstance(e, httpx.HTTPStatusError) and e.response.status_code == 409: + self._fixed_mode_off() + return + detail = (f"HTTP {e.response.status_code}" if isinstance(e, httpx.HTTPStatusError) + else f"{type(e).__name__}: {e}") + error = WorkWindowError(f"always_on: wake {self.wakes}: opening the agent's work window on " + f"{self.fixed_env.env_id} failed ({detail})") + await close_unsure_open(self.ctx, self.fixed_env, self.step.id, window, error, self._close_call) + raise error from e self.turn_window = window async def _close_window(self, failed: Optional[BaseException] = None) -> None: """Close the turn's work window: what it charged, in ``turn_work`` and the run's ``work_total``. Within a short budget, so a struggling gateway can't stall the turn's cleanup. Fails closed: a window that can't be closed - would charge whoever calls with the agent's role after the turn, so the run ends with WorkWindowError, the - turn's own error (``failed``) named in it; a run being cancelled stays cancelled, the failure logged. Fixed mode - found ended is logged once (``_fixed_mode_off``).""" + would charge whoever calls with the agent's role after the turn, so it is recorded as left open + (``record_left_open``), for the next step's window to close first, and the run ends with WorkWindowError, the + turn's own error (``failed``) named in it; a run being cancelled stays cancelled, the failure logged and the + run recorded as an infrastructure failure all the same. Fixed mode found ended is logged once + (``_fixed_mode_off``).""" window, self.turn_window = self.turn_window, None if window is None: return @@ -913,9 +940,11 @@ async def _close_window(self, failed: Optional[BaseException] = None) -> None: f"always_on: wake {self.wakes}: closing the agent's work window on {self.fixed_env.env_id} failed " f"({type(e).__name__}: {e}): it may still charge calls made after the turn, so the run is not graded" + (f"; the turn itself had failed ({type(failed).__name__}: {failed})" if failed is not None else "")) + record_left_open(self.ctx, self.step.id, self.fixed_env, window, str(error)) if isinstance(failed, asyncio.CancelledError): logger.error(str(error)) failed.add_note(str(error)) + self._failed(INFRA_ERROR, f"{type(error).__name__}: {error}", WORK_WINDOW_ERROR_CODE) return raise error from e mine = answer.get("window") or {} diff --git a/src/agent_env/task_step/task_steps/clock_mode.py b/src/agent_env/task_step/task_steps/clock_mode.py index 5dd7b06af..e90c9a512 100644 --- a/src/agent_env/task_step/task_steps/clock_mode.py +++ b/src/agent_env/task_step/task_steps/clock_mode.py @@ -8,30 +8,44 @@ set_env_clock_rate to 0 after the agent's last prompt_agent) leaves fixed mode. The clock step only turns the mode on; who the agent is, the step that runs it says. prompt_agent opens a window for -its agent's role around its conversation (``agent_work_window``) and always_on one around each of the agent's turns, so -a setup script, a verifier, collect_artifacts or a user sim calling the same gateway before, between or after is never -charged. A window that can't be closed fails the step as an infrastructure error (``WorkWindowError``), since it -would charge whoever calls after. Which env is in fixed mode the run's ``clock_configurations`` say -(``fixed_mode_envs``), so a task that never names the mode makes no window call at all. One env in fixed mode at most: two clocks charged for the same calls would -drift apart, and their totals would match neither. +its agent's roles around its conversation (``agent_work_window``) and always_on one around each of the agent's turns, +so a setup script, a verifier, collect_artifacts or a user sim calling the same gateway before, between or after is +never charged. An agent with no role of its own is charged as two roles (``agent_window_roles``): the default role its +MCP calls take, and the one its generated MCP CLI sends (``DEFAULT_CLI_ROLE``), since deploy_agent sets the CLI's +role only for an agent that has one. A window that can't be closed fails the step as an infrastructure error +(``WorkWindowError``), since it would charge whoever calls after. Which env is in fixed mode the run's +``clock_configurations`` say (``fixed_mode_envs``), so a task that never names the mode makes no window call at all. +One env in fixed mode at most: two clocks charged for the same calls would drift apart, and their totals would match +neither. + +A window that may still be open after its step (its close failed, or its open lost its answer and the close sent after +it failed too) is recorded in ``context.metadata["work_windows_left_open"]`` (``record_left_open``), and the next step to +open a window on that env closes it first (``close_left_open``), as it does any window the gateway shows open under its +own step id: one an earlier attempt of the same step left, whose record a retry's rollback or a dead worker took with +it. One that can't be closed fails that step too, before its agent starts. The gateway doesn't close them itself on the +next open: two windows naming the same role may be open at once on purpose (two prompt_agent steps the task runs side +by side, their agents on the same role), and each must go on charging until its own step closes it. """ from __future__ import annotations import logging +import re import uuid from contextlib import asynccontextmanager -from typing import Any, AsyncIterator, Optional +from typing import Any, AsyncIterator, Awaitable, Callable, Optional import httpx -from agent_env.env.gateway.constants import CLOCK_FIXED_MODE, EXT_CLOCK_URI, FIXED_SECONDS_PER_CALL +from agent_env.env.gateway.constants import CLOCK_FIXED_MODE, DEFAULT_ROLE, EXT_CLOCK_URI, FIXED_SECONDS_PER_CALL from agent_env.task_step.context import INFRA_ERROR, AgentTurnInfraError, StepContextError +from agent_env.task_step.task_steps.mcp_cli_builder.codegen import DEFAULT_CLI_ROLE logger = logging.getLogger(__name__) CLOCK_MODES = (CLOCK_FIXED_MODE,) FIXED_METHODS = ("fixed", "open_work_window", "close_work_window") WORK_WINDOWS_KEY = "work_windows" # context.metadata: each window a step opened, with what it charged +LEFT_OPEN_KEY = "work_windows_left_open" # context.metadata: each window a step couldn't be sure it closed _WINDOW_TIMEOUT_S = 30 _MAX_ERROR_CHARS = 300 @@ -110,32 +124,134 @@ class WorkWindowError(AgentTurnInfraError): verifier the task runs all the same (``fail_task_on_error`` off) doesn't grade what the agent did.""" +def agent_window_roles(agent) -> list[str]: + """The roles a work window names for ``agent``: its own role; for an agent with none, the gateway's default role, + which its MCP calls take (they carry no role header), and the generated MCP CLI's ``DEFAULT_CLI_ROLE``, which the + CLI sends when deploy_agent set it no AGENT_ENV_ROLE, as it does for an agent with no role.""" + return [agent.role] if agent.role else [DEFAULT_ROLE, DEFAULT_CLI_ROLE] + + +def opened_by(window: str, step_id: str) -> bool: + """Whether ``window`` is an id a work window of step ``step_id`` is opened with: prompt_agent's + ``:``, or always_on's ``:wake-:``.""" + return re.fullmatch(rf"{re.escape(step_id)}:(?:wake-\d+:)?[0-9a-f]+", window) is not None + + +def record_left_open(context, step_id: str, env, window: str, error: str) -> None: + """Record ``window``, which ``step_id`` opened on ``env``, as maybe still open there: its close failed, or its open + failed and so did the close sent after it. The next step to open a window on ``env`` closes it first + (``close_left_open``).""" + left = context.metadata.setdefault(LEFT_OPEN_KEY, []) + if not any(entry.get("window") == window for entry in left): + left.append({"step_id": step_id, "env_id": env.env_id, + "deploy_step_id": (env.metadata or {}).get("deploy_step_id"), "window": window, + "error": error[:_MAX_ERROR_CHARS * 2]}) + + +def _recorded_on(context, env) -> list[str]: + """The windows recorded as left open on ``env``: this env id, this deployment.""" + step = (env.metadata or {}).get("deploy_step_id") + return [e["window"] for e in context.metadata.get(LEFT_OPEN_KEY) or [] + if e.get("env_id") == env.env_id and e.get("deploy_step_id") == step] + + +def _forget_left_open(context, window: str) -> None: + left = context.metadata.get(LEFT_OPEN_KEY) + if left: + left[:] = [e for e in left if e.get("window") != window] + + +def windows_in(fixed: Optional[dict]) -> list[str]: + """The ids of the windows a clock state's fixed block shows open.""" + return [w["window"] for w in (fixed or {}).get("windows") or [] if isinstance(w, dict) and w.get("window")] + + +async def close_left_open(context, env, step_id: str, open_windows: list[str], + close: Callable[[str], Awaitable[Any]]) -> None: + """Before ``step_id`` opens a work window on ``env``, close (``close``) each window left open there: those the run + recorded (``record_left_open``), and those of ``open_windows`` (the gateway's) that an earlier attempt of this same + step opened, whose record a retry's rollback or a dead worker took with it. A step never runs beside itself, so + such a window is no live one. A 404 is a window already gone. Raises WorkWindowError when one can't be closed: it + would go on charging its roles beside the step's own window, and after it.""" + for window in dict.fromkeys(_recorded_on(context, env) + [w for w in open_windows if opened_by(w, step_id)]): + try: + await close(window) + except Exception as e: + if not (isinstance(e, httpx.HTTPStatusError) and e.response.status_code == 404): + raise WorkWindowError(f"{step_id}: closing the work window {window!r} left open on env '{env.env_id}' " + f"failed ({_detail(e)}): it would go on charging beside the agent's own, so the " + "agent isn't started") from e + else: + logger.warning(f"{step_id}: closed the work window {window!r} left open on env '{env.env_id}' before " + "opening the agent's own") + _forget_left_open(context, window) + + +async def close_unsure_open(context, env, step_id: str, window: str, error: WorkWindowError, + close: Callable[[str], Awaitable[Any]]) -> None: + """After the open of ``window`` failed (``error``): the gateway may have opened it all the same, only its answer + lost, so close it (``close``); a 404 means it never opened. A close that fails too leaves it recorded as left open + (``record_left_open``), for the next open on ``env`` to close first, and noted on ``error``.""" + try: + await close(window) + except Exception as e: + if isinstance(e, httpx.HTTPStatusError) and e.response.status_code == 404: + return + note = (f"the close of window {window!r} sent after the failed open failed as well ({_detail(e)}): it may be " + "open, so the next window opened on the env closes it first") + logger.error(f"{step_id}: {note}") + error.add_note(note) + record_left_open(context, step_id, env, window, str(error)) + + +async def _open_windows(env, step_id: str) -> list[str]: + """The windows ``env``'s gateway shows open (its clock state's fixed block); WorkWindowError when it can't be read, + since a window left open there would go unseen.""" + try: + state = await _window_call(env, "state", None) + except Exception as e: + raise WorkWindowError(f"{step_id}: reading the work windows open on env '{env.env_id}' failed " + f"({_detail(e)}), so a window left open there can't be closed first") from e + return windows_in((state or {}).get("fixed")) + + +def _detail(e: BaseException) -> str: + return (f"HTTP {e.response.status_code}: {e.response.text[:_MAX_ERROR_CHARS]}" + if isinstance(e, httpx.HTTPStatusError) else f"{type(e).__name__}: {str(e)[:_MAX_ERROR_CHARS]}") + + @asynccontextmanager async def agent_work_window(context, step_id: str, roles: list[str]) -> AsyncIterator[Optional[str]]: """A work window naming ``roles`` held open on the env in fixed mode, if there is one, around the agent's work: yields the window's id, or None with no env in fixed mode, or with fixed mode already ended there (409, logged). - Closed however the work ends, and what it charged recorded under ``context.metadata["work_windows"]``. Fails - closed: a close that still fails after a retry saves the step's responses as an infrastructure failure - (``_saved_as_infra``) and raises WorkWindowError once the agent's work is done; when the work itself raised, that - error stays the one raised, the close's failure logged and noted on it. Refuses more than one env in fixed mode.""" + Each window left open on the env is closed first (``close_left_open``). Closed however the work ends, and what it + charged recorded under ``context.metadata["work_windows"]``. Fails closed: an open that fails is closed again in + case the gateway opened it, then raises WorkWindowError; a close that still fails after a retry saves the step's + responses as an infrastructure failure (``_saved_as_infra``), records the window left open, and raises + WorkWindowError once the agent's work is done; when the work itself raised, that error stays the one raised, the + close's failure logged and noted on it. Refuses more than one env in fixed mode.""" env = one_fixed_mode_env(context, step_id) if env is None: yield None return + + async def close(window: str) -> Any: + return await _window_call(env, "close_work_window", {"window": window}) + + await close_left_open(context, env, step_id, await _open_windows(env, step_id), close) window = f"{step_id}:{uuid.uuid4().hex[:12]}" try: await _window_call(env, "open_work_window", {"window": window, "roles": list(roles)}) - except httpx.HTTPStatusError as e: - if e.response.status_code != 409: - raise WorkWindowError(f"{step_id}: opening the agent's work window on env '{env.env_id}' failed (HTTP " - f"{e.response.status_code}): {e.response.text[:_MAX_ERROR_CHARS]}") from e + except Exception as e: + if not (isinstance(e, httpx.HTTPStatusError) and e.response.status_code == 409): + error = WorkWindowError(f"{step_id}: opening the agent's work window on env '{env.env_id}' failed " + f"({_detail(e)})") + await close_unsure_open(context, env, step_id, window, error, close) + raise error from e logger.warning(f"{step_id}: env '{env.env_id}' refused the agent's work window " f"({e.response.text[:_MAX_ERROR_CHARS]}); the agent's work takes no task time") yield None return - except Exception as e: - raise WorkWindowError(f"{step_id}: opening the agent's work window on env '{env.env_id}' failed: " - f"{type(e).__name__}: {str(e)[:_MAX_ERROR_CHARS]}") from e try: yield window except BaseException as error: @@ -149,16 +265,16 @@ async def agent_work_window(context, step_id: str, roles: list[str]) -> AsyncIte async def _close_window(context, env, step_id: str, window: str, roles: list[str]) -> None: - """Close ``window`` and record what it charged; WorkWindowError when it can't be closed, a retry included.""" + """Close ``window`` and record what it charged; WorkWindowError when it can't be closed, a retry included, the + window then recorded as left open.""" try: answer = await _window_call(env, "close_work_window", {"window": window}) except Exception as e: - detail = (f"HTTP {e.response.status_code}: {e.response.text[:_MAX_ERROR_CHARS]}" - if isinstance(e, httpx.HTTPStatusError) else f"{type(e).__name__}: {str(e)[:_MAX_ERROR_CHARS]}") error = WorkWindowError(f"{step_id}: closing the agent's work window {window!r} on env '{env.env_id}' failed " - f"({detail}): it may still charge calls made after the agent, so the run is not " + f"({_detail(e)}): it may still charge calls made after the agent, so the run is not " "graded") _saved_as_infra(context, step_id, str(error)) + record_left_open(context, step_id, env, window, str(error)) raise error from e mine = (answer or {}).get("window") or {} context.metadata.setdefault(WORK_WINDOWS_KEY, []).append({ @@ -190,9 +306,9 @@ def _saved_as_infra(context, step_id: str, message: str) -> None: response.error_message = message + before -async def _window_call(env, method: str, params: dict) -> Any: - """A window call, made once more after a failure that isn't the gateway's own answer to it (a 4xx): both are safe - to repeat.""" +async def _window_call(env, method: str, params: Optional[dict]) -> Any: + """A window call, or the clock's state read, made once more after a failure that isn't the gateway's own answer to + it (a 4xx): each is safe to repeat.""" try: return await env.invoke(EXT_CLOCK_URI, method, params, timeout=_WINDOW_TIMEOUT_S) except httpx.HTTPStatusError as e: diff --git a/src/agent_env/task_step/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py index 69a0e8dba..8ef09d1e2 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -51,7 +51,7 @@ from agent_env.entity.refs import EntityRef from agent_env.entity.scopes import FieldScope from agent_env.task_step.task_step import RetryConfig, StepRole, TaskStep, TaskStepDependency -from agent_env.task_step.task_steps.clock_mode import agent_work_window, one_fixed_mode_env +from agent_env.task_step.task_steps.clock_mode import agent_window_roles, agent_work_window, one_fixed_mode_env from agent_env.task_step.task_steps.notification_delivery import delivered_parts, labels_zone, next_message, take_due from agent_env.task_step.task_steps.post_turn_hooks import PostTurnHooks, run_post_turn_hooks, validate_hook_specs from agent_env.task_step.task_steps.server_fault_logs import capture_server_fault_logs @@ -553,7 +553,7 @@ async def _execute_conversation( hooks = await PostTurnHooks.load(self.post_turn_hooks, self.id) if self.post_turn_hooks else None agent = next((a for a in context.deployed_agents if a.agent_name == self.agent_name), None) # In fixed mode, the agent's calls are charged only while its window is open: none before or after (clock_mode). - window = agent_work_window(context, self.id, [agent.role or DEFAULT_ROLE]) if agent else nullcontext() + window = agent_work_window(context, self.id, agent_window_roles(agent)) if agent else nullcontext() try: async with window: return await self._converse(context, a2a_context_id=a2a_context_id, series=series, hooks=hooks) diff --git a/tst/unit/task_step/clock_mode_test.py b/tst/unit/task_step/clock_mode_test.py index e459b4c87..838c787cd 100644 --- a/tst/unit/task_step/clock_mode_test.py +++ b/tst/unit/task_step/clock_mode_test.py @@ -26,6 +26,7 @@ ) from agent_env.task_step.task_steps import prompt_agent as pa_mod from agent_env.task_step.task_steps.clock_mode import WorkWindowError +from agent_env.task_step.task_steps.mcp_cli_builder.codegen import DEFAULT_CLI_ROLE from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep from agent_env.task_step.task_steps.set_env_clock_rate import SetEnvClockRateTaskStep from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep @@ -326,8 +327,8 @@ async def poll(url, task_id, timeout, interval, **_): return sent -def _prompt(**kw) -> PromptAgentTaskStep: - return PromptAgentTaskStep(id="solve", version=None, prompt="sort the order out", agent_name="solver", +def _prompt(step_id: str = "solve", **kw) -> PromptAgentTaskStep: + return PromptAgentTaskStep(id=step_id, version=None, prompt="sort the order out", agent_name="solver", max_conversation_turns=1, poll_interval_seconds=0, **kw) @@ -614,3 +615,152 @@ async def invoke(self, uri, method, params=None, **kw): with pytest.raises(WorkWindowError, match="opening the agent's work window"): await _prompt().execute(context) assert sent == [] + + +# ---- a role-less agent's CLI ---------------------------------------------------------------------------------------- + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_charges_a_role_less_agents_cli_calls_in_its_window(world, monkeypatch): + """An agent deployed with no role sends its MCP calls with no role header (the default role), and the generated MCP + CLI, which deploy_agent gives no AGENT_ENV_ROLE then, sends its own default role, ``cli``: the window names both.""" + async def turn(): + await world.call(role=DEFAULT_CLI_ROLE) + await world.call() + + _agent(monkeypatch, world, turn) + context = _with_agent(await world.context(), role=None) + await _sync(clock_mode="fixed").execute(context) + world.forget() + + await _prompt().execute(context) + + opened = next(b for m, p, b in world.clock_calls() if (m, p) == ("PUT", "/clock/fixed/window")) + assert opened["roles"] == ["default", DEFAULT_CLI_ROLE] + state = await world.state() + assert state["virtual_time"] == "2026-11-09T14:02:00Z" + assert state["fixed"]["by_role"] == {DEFAULT_CLI_ROLE: {"calls": 1, "virtual_seconds": 60.0}, + "default": {"calls": 1, "virtual_seconds": 60.0}} + await world.call(role=DEFAULT_CLI_ROLE) # after the agent's window: free + assert (await world.state())["virtual_time"] == "2026-11-09T14:02:00Z" + + +# ---- windows left open ---------------------------------------------------------------------------------------------- + +def _flaky(monkeypatch, method: str, *, reaches: bool) -> dict: + """``method`` fails while ``flaky["on"]``: its answer lost on the way back (``reaches``: the gateway did it), or the + gateway gone (it never got it). Each try is counted in ``flaky["tries"]``.""" + flaky = {"on": True, "tries": 0} + real = DeployedGatewayEnv.invoke + + async def invoke(self, uri, called, params=None, **kw): + if called == method and flaky["on"]: + flaky["tries"] += 1 + if reaches: + await real(self, uri, called, params, **kw) + raise httpx.ReadError("the answer was lost" if reaches else "the gateway is gone") + return await real(self, uri, called, params, **kw) + monkeypatch.setattr(DeployedGatewayEnv, "invoke", invoke) + return flaky + + +def _window_calls(world: World) -> list[tuple[str, str]]: + return [(m, b["window"]) for m, p, b in world.clock_calls() if p == "/clock/fixed/window"] + + +async def _role_less_run(world: World, monkeypatch) -> tuple[TaskStepContext, list[str]]: + """A role-less agent, whose window names the default role a verifier's header-less reads have too, in fixed mode; + each of its turns makes one call. The context and the texts the agent was sent.""" + async def turn(): + await world.call() + + sent = _agent(monkeypatch, world, turn) + context = _with_agent(await world.context(), role=None) + await _sync(clock_mode="fixed").execute(context) + return context, sent + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_prompt_agent_closes_a_window_whose_open_lost_its_answer(world, monkeypatch): + """The gateway opened the window, but its answer never came back: the step fails as infra before the agent starts, + and closes the window first, so it charges no one after it (a verifier's header-less reads).""" + context, sent = await _role_less_run(world, monkeypatch) + _flaky(monkeypatch, "open_work_window", reaches=True) + + with pytest.raises(WorkWindowError, match="opening the agent's work window"): + await _prompt().execute(context) + + assert sent == [] + assert (await world.state())["fixed"]["windows"] == [] + await _collect(context.deployed_envs[0]) + assert (await world.state())["virtual_time"] == T0 + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_a_window_a_failed_step_left_open_is_closed_before_the_next_step_opens_its_own(world, monkeypatch): + """The step's close failed twice, the gateway unreachable then, so its window may still be open; the task goes on + (fail_task_on_error off) to another prompt_agent step once the gateway is back, which closes it before opening its + own, so it charges nothing after, the verifier's header-less reads included.""" + context, _ = await _role_less_run(world, monkeypatch) + gone = _flaky(monkeypatch, "close_work_window", reaches=False) + with pytest.raises(WorkWindowError, match="closing the agent's work window"): + await _prompt().execute(context) + (left,) = (await world.state())["fixed"]["windows"] + gone["on"] = False + world.forget() + + await _prompt("solve-2").execute(context) + + (_, closed_first), (_, opened), (_, closed) = _window_calls(world) + assert closed_first == left["window"] and opened == closed != left["window"] + assert [m for m, _ in _window_calls(world)] == ["DELETE", "PUT", "DELETE"] + assert (await world.state())["fixed"]["windows"] == [] + await _collect(context.deployed_envs[0]) + assert (await world.state())["virtual_time"] == "2026-11-09T14:02:00Z" # the two agent calls, nothing else + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_a_retry_closes_the_window_its_failed_attempt_left_open_with_the_attempts_record_gone(world, monkeypatch): + """A retry of the step (retry_config) runs on a context rolled back to before it, and a worker that died took the + failed attempt's context with it: what the attempt recorded is gone, but the gateway still shows the window it + opened, under the step's id, and the retry closes it before opening its own.""" + context, _ = await _role_less_run(world, monkeypatch) + gone = _flaky(monkeypatch, "close_work_window", reaches=False) + with pytest.raises(WorkWindowError): + await _prompt().execute(context) + (left,) = (await world.state())["fixed"]["windows"] + gone["on"] = False + retry = _with_agent(await world.context(), role=None) # rolled back: what the clock step wrote, nothing after + retry.metadata["clock_configurations"] = context.metadata["clock_configurations"] + world.forget() + + await _prompt().execute(retry) + + assert [m for m, _ in _window_calls(world)] == ["DELETE", "PUT", "DELETE"] + assert _window_calls(world)[0][1] == left["window"] + assert (await world.state())["fixed"]["windows"] == [] + await _collect(retry.deployed_envs[0]) + assert (await world.state())["virtual_time"] == "2026-11-09T14:02:00Z" + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_a_window_left_open_that_still_cant_be_closed_keeps_the_next_agent_from_starting(world, monkeypatch): + """Fails closed: a window left open that can't be closed now either would go on charging beside the next one.""" + context, sent = await _role_less_run(world, monkeypatch) + _flaky(monkeypatch, "close_work_window", reaches=False) + with pytest.raises(WorkWindowError): + await _prompt().execute(context) + (left,) = (await world.state())["fixed"]["windows"] + before = list(sent) + world.forget() + + with pytest.raises(WorkWindowError, match="left open"): + await _prompt("solve-2").execute(context) + + assert sent == before + assert not [m for m, _ in _window_calls(world) if m == "PUT"] + assert (await world.state())["fixed"]["windows"] == [left] diff --git a/tst/unit/task_step/test_always_on_fixed_clock.py b/tst/unit/task_step/test_always_on_fixed_clock.py index fd18c9bff..86f0462f4 100644 --- a/tst/unit/task_step/test_always_on_fixed_clock.py +++ b/tst/unit/task_step/test_always_on_fixed_clock.py @@ -17,7 +17,9 @@ from agent_env.env.gateway.triggers import TriggerEngine from agent_env.task_step.context import INFRA_ERROR, AgentTurnInfraError from agent_env.task_step.task_steps import always_on as ao +from agent_env.task_step.task_steps import clock_mode from agent_env.task_step.task_steps.clock_mode import WorkWindowError +from agent_env.task_step.task_steps.mcp_cli_builder.codegen import DEFAULT_CLI_ROLE from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep from agent_env.task_step.task_steps.verifiers.agent_prompt_response_verifier import ( AgentPromptResponseVerifierTaskStep, @@ -438,3 +440,114 @@ async def call(env, uri, method, params=None, **kw): (turn,) = rig.events(ctx, "agent_turn_end") assert "work" not in turn assert "fixed_clock" not in rig.record(ctx)["counts"] + + +@pytest.mark.asyncio +async def test_a_role_less_agents_cli_calls_are_charged_in_its_turns(monkeypatch, tmp_path): + """The rig's agent has no role: its MCP calls are the default role's, and the generated MCP CLI, which deploy_agent + gives no AGENT_ENV_ROLE then, sends its own default role, ``cli``. Each turn's window names both.""" + async def agent(n, texts, rig): + await rig.call("market_search", role=DEFAULT_CLI_ROLE) + await rig.call("market_search") + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + rig.tool("market_search") + ctx = rig.context() + await _fixed_mode(monkeypatch, rig, ctx) + await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1), ctx) + (turn,) = rig.events(ctx, "agent_turn_end") + assert turn["work"] == {"calls": 2, "virtual_seconds": 120.0} + assert (await _fixed_state(rig))["by_role"] == {DEFAULT_CLI_ROLE: {"calls": 1, "virtual_seconds": 60.0}, + ROLE: {"calls": 1, "virtual_seconds": 60.0}} + + +@pytest.mark.asyncio +async def test_a_window_whose_open_lost_its_answer_is_closed_and_the_run_is_an_infra_failure(monkeypatch, tmp_path): + """The gateway opened the turn's window, but its answer never came back: the run ends as an infrastructure failure, + and the window is closed first, so it charges no one after the run (a verifier's header-less reads).""" + rig = Rig(monkeypatch, tmp_path) + rig.tool("market_search") + ctx = rig.context() + await _fixed_mode(monkeypatch, rig, ctx) + real_call = ao._call + + async def call(env, uri, method, params=None, **kw): + if method == "open_work_window": + await env.invoke(uri, method, params, timeout=60) + raise httpx.ReadError("the answer was lost") + return await real_call(env, uri, method, params, **kw) + monkeypatch.setattr(ao, "_call", call) + step = rig.step(settle_timeout_seconds=0.2, max_wakes=1) + + with pytest.raises(WorkWindowError, match="opening the agent's work window"): + await rig.run(step, ctx) + + assert rig.sent == [] + assert rig.record(ctx)["end_reason"] == ao.AGENT_TURN_INFRA_ERROR + assert (await _fixed_state(rig))["windows"] == [] + await _header_less(rig, "market_search") + assert (await _fixed_state(rig))["by_role"] == {} + + +@pytest.mark.asyncio +async def test_a_cancelled_turn_whose_window_cant_be_closed_leaves_the_run_an_infra_failure(monkeypatch, tmp_path): + """The run is cancelled mid-turn and the turn's window can't be closed: the run stays cancelled, but it is recorded + as an infrastructure failure, as a window that can't be closed is otherwise, so its verifiers leave it ungraded.""" + async def agent(n, texts, rig): + await rig.call("market_search") + raise asyncio.CancelledError() + + rig = Rig(monkeypatch, tmp_path, agent=agent) + rig.tool("market_search") + ctx = rig.context() + await _fixed_mode(monkeypatch, rig, ctx) + + class Struggling: + env_id = "world" + + async def invoke(self, uri, method, params=None, *, timeout): + raise httpx.ConnectError("the gateway is struggling") + real_call = ao._call + + async def call(env, uri, method, params=None, **kw): + return await real_call(Struggling() if method == "close_work_window" else env, uri, method, params, **kw) + monkeypatch.setattr(ao, "_call", call) + step = rig.step(settle_timeout_seconds=0.2, max_wakes=2) + + with pytest.raises(asyncio.CancelledError) as cancelled: + await rig.run(step, ctx) + + assert any("closing the agent's work window" in note for note in cancelled.value.__notes__) + record = rig.record(ctx) + assert (record["end_reason"], record["error_type"], record["error_code"]) == ( + ao.AGENT_TURN_INFRA_ERROR, INFRA_ERROR, "agent_env.work_window_failed") + assert ao.ended_on_infra_failure(ctx.metadata, step.id) + [response] = ctx.prompt_responses + assert (response.error_type, response.error_code) == (INFRA_ERROR, "agent_env.work_window_failed") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("left_by", ["an earlier step", "an earlier attempt of this step"]) +async def test_a_window_left_open_before_the_run_is_closed_before_its_first_turn(monkeypatch, tmp_path, left_by): + """A window an earlier step couldn't close (its record in the run's metadata), or one an earlier attempt of this + step left open (its record gone with a retry's rollback or a dead worker, but the gateway shows it under the + step's id), is closed before the run's first window opens, so it charges no one during the run or after it.""" + rig = Rig(monkeypatch, tmp_path) + rig.tool("market_search") + ctx = rig.context() + await _fixed_mode(monkeypatch, rig, ctx) + window = "solve:0123456789ab" if left_by == "an earlier step" else "week:wake-1:0123abcd" + async with rig.http() as client: + r = await client.put("/clock/fixed/window", json={"window": window, "roles": [ROLE]}) + r.raise_for_status() + if left_by == "an earlier step": + clock_mode.record_left_open(ctx, "solve", ctx.deployed_envs[0], window, "the gateway was gone") + + await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1), ctx) + + assert (await _fixed_state(rig))["windows"] == [] + assert not ctx.metadata.get(clock_mode.LEFT_OPEN_KEY) + await _header_less(rig, "market_search") + assert (await _fixed_state(rig))["by_role"] == {} From 31bab12af7b460acbffc731d2fd9648632201473 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Fri, 4 Dec 2026 19:01:13 -0800 Subject: [PATCH 8/9] refactor(always_on): name the work window close limits (FD-7183) Greptile P2: the two close calls repeated attempts=2, timeout=10 inline. They now share WINDOW_CLOSE_ATTEMPTS and WINDOW_CLOSE_TIMEOUT_SECONDS. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task_step/task_steps/always_on.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 405b1d3da..22eff2aa3 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -219,6 +219,9 @@ USER_PHONE = "user_phone" IN_FLIGHT = ("firing", "queued") POLL_SECONDS = 0.5 +# Closing a turn's work window in fixed mode, or one left open: tries, and real seconds per try (FD-7183). +WINDOW_CLOSE_ATTEMPTS = 2 +WINDOW_CLOSE_TIMEOUT_SECONDS = 10 DAYS = ("mon", "tue", "wed", "thu", "fri", "sat", "sun") FINAL_REMINDER = "(Only what you send with message_user reaches {first}; your normal reply is not shown to them.)" NUDGE_TEXT = ("Your closing text was not delivered. If the user should see it, send it with message_user; otherwise " @@ -892,8 +895,8 @@ def _configure_fixed(self, env, block: dict) -> None: async def _close_call(self, window: str) -> Any: """Close ``window`` on the clock in fixed mode, within a short budget; a 404 (no such window) is the gateway's answer, raised at once.""" - return await _call(self.fixed_env, EXT_CLOCK_URI, "close_work_window", {"window": window}, attempts=2, - timeout=10, answers=(404,)) + return await _call(self.fixed_env, EXT_CLOCK_URI, "close_work_window", {"window": window}, + attempts=WINDOW_CLOSE_ATTEMPTS, timeout=WINDOW_CLOSE_TIMEOUT_SECONDS, answers=(404,)) async def _open_window(self) -> None: """Open the turn's work window, naming the agent's roles (``agent_window_roles``), on the clock in fixed mode: @@ -933,8 +936,8 @@ async def _close_window(self, failed: Optional[BaseException] = None) -> None: if window is None: return try: - answer = await _call(self.fixed_env, EXT_CLOCK_URI, "close_work_window", {"window": window}, attempts=2, - timeout=10) or {} + answer = await _call(self.fixed_env, EXT_CLOCK_URI, "close_work_window", {"window": window}, + attempts=WINDOW_CLOSE_ATTEMPTS, timeout=WINDOW_CLOSE_TIMEOUT_SECONDS) or {} except Exception as e: error = WorkWindowError( f"always_on: wake {self.wakes}: closing the agent's work window on {self.fixed_env.env_id} failed " From 4749a0283dc374ce726a8b5e3d7c26ae3d82ca52 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Fri, 4 Dec 2026 20:02:51 -0800 Subject: [PATCH 9/9] feat(clock): a task sets fixed mode's charge per tool call; 60 s stays the default (FD-7183) Fixed mode moved the frozen clock on by a constant FIXED_SECONDS_PER_CALL (60 s) for each charged tool call. The charge is now a parameter, as the review asked. Gateway: - PUT /clock/fixed requires seconds_per_tool_call to turn the mode on, and answers 400 without it. The value must be a finite number above 0 and at most FIXED_MAX_SECONDS_PER_CALL (86400, a day). Booleans, NaN, infinity, 0, negatives and non-numbers are refused. Turning the mode off takes no charge, and a request that sends one is refused too. - FixedClock stores the charge and cost() charges it. The state's fixed block reports it as seconds_per_call, which is null while the mode is off. - The clock/v1 card's fixed request schema marks seconds_per_tool_call as required when on is true (if/then), and forbids it when on is false. - One validator, constants.fixed_seconds_per_call_error, is used by the gateway and by the steps. Steps: - sync_env_clock and set_env_clock_rate take fixed_time_increment_on_tool_call_seconds. Left unset it means FIXED_SECONDS_PER_CALL (60). It is checked at load the way the gateway checks it, and accepted only with clock_mode "fixed". - to_dict writes it only when set, so existing step JSON is unchanged. - The step sends it to the gateway (start_fixed) and records it in clock_configurations beside clock_mode. Docs and docstrings no longer say the charge is a fixed 60 s. They now say it defaults to 60 s and a task may set it. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- src/agent_env/env/gateway/clock.py | 2 +- src/agent_env/env/gateway/constants.py | 33 ++++- src/agent_env/env/gateway/fixed_clock.py | 60 ++++++--- src/agent_env/env/gateway/gateway.py | 7 +- .../task_step/task_steps/always_on.py | 9 +- .../task_step/task_steps/clock_mode.py | 52 ++++++-- .../task_steps/set_env_clock_rate.py | 26 +++- .../task_step/task_steps/sync_env_clock.py | 32 +++-- .../env/gateway/fixed_clock_socket_test.py | 2 +- tst/unit/env/gateway/fixed_clock_test.py | 116 ++++++++++++++++-- tst/unit/task_step/clock_mode_test.py | 80 +++++++++++- .../task_step/test_always_on_fixed_clock.py | 35 +++++- 13 files changed, 380 insertions(+), 76 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 033663230..64de9e149 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,7 +191,7 @@ and deserialized through a registry. | Package | Contents | |---|---| -| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its fixed mode (`/clock/fixed`, `env/gateway/fixed_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "fixed"` on a clock at rate 0 and any later set_time, set_rate or clear turns off, ending every open window, moves the frozen clock on by a fixed `FIXED_SECONDS_PER_CALL` (60 s, not configurable) for each answered tool call made while a work window naming its role is open (`/clock/fixed/window`, PUT to open with `roles`, DELETE to close, answering its totals; both control routes): prompt_agent opens one for its agent's role around its conversation and always_on one around each turn, nudges included (`task_steps/clock_mode.py` `agent_work_window`; an agent with no role is charged as `default` and as its generated MCP CLI's `cli`, `agent_window_roles`), each failing closed, as an infra error (`WorkWindowError`), when a window can't be opened or closed, a cancelled always_on run's close included, a window that may still be open recorded under `context.metadata["work_windows_left_open"]` and closed by the next step's open first, as is one the gateway shows under the opening step's own id (an earlier attempt's; the gateway never closes one for another, since two windows may name a role at once), the run recorded as one (error_type `infra_error`, error_code `agent_env.work_window_failed`) so a verifier the task runs all the same grades none of it, and both refuse more than one env in fixed mode, so a setup script, a verifier, collect_artifacts, a user sim, a contact or the agent between its turns is never charged, the agent's role outside its window logged as `fixed_clock_outside_window`. A charge, on the MCP path and the step API's `/step` paths (not a post-turn hook's that shows the control token; never the gateway's own `get_time` or `stay_quiet`), comes after the call's barriers (`Clock.advance_by`), and only if the window it was decided in is still open as it was (fixed mode ended, the clock re-armed or the window closed meanwhile skip it as `fixed_clock_skipped`), then the answer is held until all world work runnable now has landed, every trigger fire at work, every state check a write set going and each deferred call the clock reached (`Gateway._settle_world`), but not a fire waiting on a later task time, the barriers and the hold sharing one budget; each charge is a `fixed_clock_charge` trajectory event and its hold a `fixed_clock_hold`, written even when the call is cancelled. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | +| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its fixed mode (`/clock/fixed`, `env/gateway/fixed_clock.py`, FD-7183), which `sync_env_clock` or `set_env_clock_rate` turns on with `clock_mode: "fixed"` on a clock at rate 0, sending its charge per call (`seconds_per_tool_call`, which turning it on requires: 60 s, `FIXED_SECONDS_PER_CALL`, by default, or the step's `fixed_time_increment_on_tool_call_seconds`, above 0 and at most a day, checked at load and only with `clock_mode`; the state's `fixed` block shows it as `seconds_per_call`, null while off), and any later set_time, set_rate or clear turns off, ending every open window, moves the frozen clock on by a charge for each answered tool call made while a work window naming its role is open (`/clock/fixed/window`, PUT to open with `roles`, DELETE to close, answering its totals; both control routes): prompt_agent opens one for its agent's role around its conversation and always_on one around each turn, nudges included (`task_steps/clock_mode.py` `agent_work_window`; an agent with no role is charged as `default` and as its generated MCP CLI's `cli`, `agent_window_roles`), each failing closed, as an infra error (`WorkWindowError`), when a window can't be opened or closed, a cancelled always_on run's close included, a window that may still be open recorded under `context.metadata["work_windows_left_open"]` and closed by the next step's open first, as is one the gateway shows under the opening step's own id (an earlier attempt's; the gateway never closes one for another, since two windows may name a role at once), the run recorded as one (error_type `infra_error`, error_code `agent_env.work_window_failed`) so a verifier the task runs all the same grades none of it, and both refuse more than one env in fixed mode, so a setup script, a verifier, collect_artifacts, a user sim, a contact or the agent between its turns is never charged, the agent's role outside its window logged as `fixed_clock_outside_window`. A charge, on the MCP path and the step API's `/step` paths (not a post-turn hook's that shows the control token; never the gateway's own `get_time` or `stay_quiet`), comes after the call's barriers (`Clock.advance_by`), and only if the window it was decided in is still open as it was (fixed mode ended, the clock re-armed or the window closed meanwhile skip it as `fixed_clock_skipped`), then the answer is held until all world work runnable now has landed, every trigger fire at work, every state check a write set going and each deferred call the clock reached (`Gateway._settle_world`), but not a fire waiting on a later task time, the barriers and the hold sharing one budget; each charge is a `fixed_clock_charge` trajectory event and its hold a `fixed_clock_hold`, written even when the call is cancelled. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | | `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, the `attempt_epoch` it was written under, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), each naming exactly what it was sent (`input`: a direct call's messages, response format and settings, an agent call's message, every file its step staged in the judge's sandbox and, for a judge the task deployed, what the task's own `load_artifact` steps put there as the run recorded it, stored by sha256 under `judge-inputs/` in the background, `judge_utils/judge_inputs.py`; the step waits for those uploads, at most 120 s, before it writes its grade, `VerifierTaskStep.settle`, and one that failed or hadn't finished is the call's `input_error`, never a failed grade), and its `verifier_settings` hold the trajectory source of each turn it read (`trajectory_sources`); with `judge_samples` (a count, as a step field, a run override or `--judge-samples` on `run`, `task run` and `eval run`), a rubric_binary or rubric_partial judge grades each criterion that many times, each a call of its own under `judge_batch_concurrency` (an agent judge the verifier deploys gets a deployment of its own per sample, its trajectory staged in each; the task's own judge takes every sample), and keeps its median, the lower middle score on a tie, which fails it, the row the first sample that scored it gave with every sample's score, verdict and justification in its `samples` and its `agreement`, the share of samples giving its verdict; a row under `min_judge_agreement` (0.5 by default, which never fails, so the median decides; 1.0 fails any split; set where `judge_samples` is, `--min-judge-agreement`) fails the grade, its rows kept, and then the step (`JudgeDisagreementError`), and `agent-env run` names the criteria a grade that stood split on (`samples split:`), and one failed sample fails the grade (a run's count or agreement a judge of another format can't take is recorded in `not_sent`) and the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`), each computer its own, a multi env's included, never the gateway's: its boot environment holds only the token's sha256 (`AGENTENV_CONTROL_TOKEN_SHA256`) when its probed card's computer/v1 says `control_token = "sha256"`, else, for a driver an older protocol built, the token itself (`AGENTENV_CONTROL_TOKEN`); the gateway learns each computer's (`CHILD_CONTROL_TOKENS`), puts it in place of its own on that computer's `/svc` routes, and lets a computer's token through only to that computer and its clock watch; a multi env's record grants each computer's `/svc` route its own token (`DeployedGatewayEnv.control_grants`, the longest granted address winning), and `CONTROL_TOKEN_CHILDREN`, the computers an older agent-env booted with the gateway's token, is kept for them; framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index cfee5c767..b5471b6b2 100644 --- a/src/agent_env/env/gateway/clock.py +++ b/src/agent_env/env/gateway/clock.py @@ -1,7 +1,7 @@ """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 and reads never -mutate it; fixed mode (fixed_clock.py) can also move it on by a fixed charge per agent tool call +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 diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index 10aa149a1..4adc220e2 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -7,6 +7,7 @@ proxy >= actual load time. """ +import math import os from enum import Enum from uuid import uuid4 @@ -99,13 +100,28 @@ def data_plane_load_timeout_s(size_bytes: int | None) -> int: # 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 FIXED_SECONDS_PER_CALL for each tool call the agent makes inside a work window, which the -# step running the agent opens for the agent's roles. Fixed in agent-env, the same for every task and every model. +# 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: + 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" EXT_ENABLE_TOOL_URI = "urn:agentenv:enable-tool/v1" @@ -311,7 +327,7 @@ 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; 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 a fixed " f"{FIXED_SECONDS_PER_CALL:g}" " s (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, the windows open and its totals; 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"]}}, @@ -319,7 +335,16 @@ def random_mcp_server_name() -> str: "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"}}, "required": ["on"], "additionalProperties": False}}, + "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"]}}, diff --git a/src/agent_env/env/gateway/fixed_clock.py b/src/agent_env/env/gateway/fixed_clock.py index bbbfa8154..20c59b75d 100644 --- a/src/agent_env/env/gateway/fixed_clock.py +++ b/src/agent_env/env/gateway/fixed_clock.py @@ -2,7 +2,11 @@ A task whose clock is frozen (rate 0) lives through none of the agent's work otherwise: a turn takes no task time, and a trigger due in the middle of one waits for the next. In fixed mode the clock stays frozen and the gateway moves it on by -``FIXED_SECONDS_PER_CALL`` for each tool call the agent makes, once the call is answered, an error result included. +a charge for each tool call the agent makes, once the call is answered, an error result included. The charge is the +``seconds_per_tool_call`` the mode was turned on with, which turning it on requires: above 0 and at most +``FIXED_MAX_SECONDS_PER_CALL`` (a day). The clock steps send ``FIXED_SECONDS_PER_CALL`` (60 s) unless the task sets its +own (``fixed_time_increment_on_tool_call_seconds``). The state's ``fixed`` block shows it as ``seconds_per_call``, null +while the mode is off. The gateway's own ``get_time`` and ``stay_quiet`` cost nothing. A call refused as disabled, or one that raised, costs nothing, and neither do model latency, thinking or retries, so every model sees the same world for the same work. @@ -31,7 +35,7 @@ from typing import Any from .clock import ClockError -from .constants import FIXED_SECONDS_PER_CALL +from .constants import fixed_seconds_per_call_error from .get_time import GET_TIME_TOOL_NAME from .user_chat import STAY_QUIET_TOOL_NAME @@ -69,18 +73,30 @@ class Ticket: windows: dict[str, int] -def parse_fixed_body(body) -> bool: - """Whether a ``fixed`` request turns fixed mode on: a JSON object holding ``on``, true or false, and nothing else. - Raises ClockError for anything else.""" +def parse_fixed_body(body) -> tuple[bool, float | None]: + """Whether a ``fixed`` request turns fixed mode on, and the task seconds each charged call then costs (None to turn + it off): a JSON object holding ``on``, true or false, and, exactly when it is true, ``seconds_per_tool_call`` + (``fixed_seconds_per_call_error``), and nothing else. Raises ClockError for anything else.""" if not isinstance(body, dict): raise ClockError("body must be a JSON object") - unknown = sorted(set(body) - {"on"}) + unknown = sorted(set(body) - {"on", "seconds_per_tool_call"}) if unknown: - raise ClockError(f"unknown fixed mode setting(s) {unknown}: fixed takes only 'on' (the charge per call is fixed at " - f"{FIXED_SECONDS_PER_CALL:g} s)") + raise ClockError(f"unknown fixed mode setting(s) {unknown}: fixed takes 'on' and, to turn it on, " + "'seconds_per_tool_call'") if not isinstance(body.get("on"), bool): raise ClockError("on must be true or false") - return body["on"] + if not body["on"]: + if "seconds_per_tool_call" in body: + raise ClockError("seconds_per_tool_call is what each call costs while fixed mode is on: turning it off " + "takes none") + return False, None + if "seconds_per_tool_call" not in body: + raise ClockError("turning fixed mode on needs seconds_per_tool_call, the task seconds each charged tool call " + "moves the clock on") + error = fixed_seconds_per_call_error(body["seconds_per_tool_call"]) + if error: + raise ClockError(f"seconds_per_tool_call {error}") + return True, float(body["seconds_per_tool_call"]) def parse_window_body(body, *, opening: bool) -> tuple[str, list[str]]: @@ -104,11 +120,12 @@ def parse_window_body(body, *, opening: bool) -> tuple[str, list[str]]: class FixedClock: - """The gateway's fixed mode: whether it is on, the windows open (each the roles it charges and what it charged), - and what it has charged, in all and by role, since the gateway started.""" + """The gateway's fixed mode: whether it is on and at what charge per call, the windows open (each the roles it + charges and what it charged), and what it has charged, in all and by role, since the gateway started.""" def __init__(self) -> None: self.on = False + self.seconds_per_call: float | None = None # what each charged call costs while on; None while off self.calls = 0 self.virtual_seconds = 0.0 self.by_role: dict[str, dict] = {} @@ -118,12 +135,16 @@ def __init__(self) -> None: self._session = 0 # one more each time the mode is turned on or off self._opened = 0 # the serial of the last window opened - def turn(self, on: bool) -> None: - """Turn the mode on or off. Either way every open window ends, its totals kept for its close.""" + def turn(self, on: bool, seconds_per_call: float | None = None) -> None: + """Turn the mode on, each charged call then costing ``seconds_per_call`` (parse_fixed_body checked it), or off, + which forgets the charge. Either way every open window ends, its totals kept for its close.""" + if on and seconds_per_call is None: + raise ValueError("fixed mode is turned on with its charge per call") for window in list(self._windows): self._end(window) self._seen.clear() self.on = on + self.seconds_per_call = float(seconds_per_call) if on else None self._session += 1 def open(self, window: str, roles: list[str]) -> dict: @@ -153,11 +174,12 @@ def close(self, window: str) -> dict: return dict(self._closed[window]) def cost(self, role: str, tool: str, native: bool) -> float | None: - """What an answered call of ``tool`` by ``role`` costs, in task seconds; None when it costs nothing: the mode - off, the gateway's own free tool (``native``), or no open window naming the role.""" + """What an answered call of ``tool`` by ``role`` costs, in task seconds: the charge per call the mode was turned + on with; None when it costs nothing: the mode off, the gateway's own free tool (``native``), or no open window + naming the role.""" if not self.on or (native and tool in FREE_TOOLS) or not self.windows_of(role): return None - return FIXED_SECONDS_PER_CALL + return self.seconds_per_call def windows_of(self, role: str) -> list[str]: """The open windows that charge ``role``.""" @@ -195,9 +217,9 @@ def record(self, role: str, seconds: float, windows: list[str]) -> None: target["virtual_seconds"] = round(target["virtual_seconds"] + seconds, 6) def state(self) -> dict: - """Whether it is on, its charge per call, the windows open, then what it has charged (``calls``, - ``virtual_seconds``), in all and by role.""" - return {"on": self.on, "seconds_per_call": FIXED_SECONDS_PER_CALL, + """Whether it is on, its charge per call (``seconds_per_call``, None while off), the windows open, then what it + has charged (``calls``, ``virtual_seconds``), in all and by role.""" + return {"on": self.on, "seconds_per_call": self.seconds_per_call, "windows": [self._view(w, mine) for w, mine in self._windows.items()], "calls": self.calls, "virtual_seconds": round(self.virtual_seconds, 6), "by_role": {role: {"calls": t["calls"], "virtual_seconds": round(t["virtual_seconds"], 6)} diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 54cca09fe..a0b85b17c 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -440,13 +440,14 @@ def disarm(body: dict) -> dict: @self._mcp.custom_route(CLOCK_FIXED_PATH, methods=["PUT"]) async def clock_fixed(request: Request) -> Response: - # A mode, not a clock change: the clock's version stays, and no follower is waited for. + # A mode, not a clock change: the clock's version stays, and no follower is waited for. Turning it on names + # the charge per call (seconds_per_tool_call), which a refused request leaves as it was. try: body = await request.json() except Exception: return self._json_response({"ok": False, "error": "Invalid JSON body"}, 400) try: - on = parse_fixed_body(body) + on, seconds_per_call = parse_fixed_body(body) if on and not self._clock.armed: raise ClockError("fixed mode moves the clock, which is not armed: set_time first") if on and self._clock.rate: @@ -454,7 +455,7 @@ async def clock_fixed(request: Request) -> Response: "set_rate 0 first") except ClockError as e: return self._json_response({"ok": False, "error": str(e)}, 400) - self._fixed_clock.turn(on) + self._fixed_clock.turn(on, seconds_per_call) return self._json_response({"ok": True, "fixed": self._fixed_clock.state()}, 200) @self._mcp.custom_route(CLOCK_WORK_WINDOW_PATH, methods=["PUT"]) diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 22eff2aa3..8587e1b4b 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -35,10 +35,11 @@ trigger's replies run side by side (``contact_replies_in_parallel``). What comes due in the same minute wakes the agent once. - When the task's clock is in fixed mode (sync_env_clock or set_env_clock_rate with ``clock_mode: "fixed"``, FD-7183), - task time passes as the agent works: the clock stays frozen and the gateway moves it on by a fixed charge for each - tool call the agent makes inside its work window, so thinking and model latency cost nothing, and what that makes due - lands before the call is answered. The step opens the window, naming the agent's role (an agent with none: the - default role and its MCP CLI's, ``clock_mode.agent_window_roles``), around each of the agent's turns, nudges + task time passes as the agent works: the clock stays frozen and the gateway moves it on by a charge for each tool call + the agent makes inside its work window (60 s by default; the clock step may set it, and + ``settings["clock"]["fixed"]["seconds_per_call"]`` records it), so thinking and model latency cost nothing, and what + that makes due lands before the call is answered. The step opens the window, naming the agent's role (an agent with + none: the default role and its MCP CLI's, ``clock_mode.agent_window_roles``), around each of the agent's turns, nudges included, and closes it when the turn ends, so a user sim, a contact, a setup script or a verifier is never charged, nor the agent between its turns. Each turn's ``agent_turn_end`` (and ``nudge``) records what its work took (``work``, the window's totals) beside the agent's ``output_tokens``, the record's ``counts["fixed_clock"]`` sums diff --git a/src/agent_env/task_step/task_steps/clock_mode.py b/src/agent_env/task_step/task_steps/clock_mode.py index e90c9a512..3265acbe3 100644 --- a/src/agent_env/task_step/task_steps/clock_mode.py +++ b/src/agent_env/task_step/task_steps/clock_mode.py @@ -2,10 +2,14 @@ the agent open in it, FD-7183. Unset, the default, the clock runs at the step's rate, as it always has. ``"fixed"`` is fixed mode: the clock is frozen -(rate 0) and the gateway moves it on by a fixed charge for each tool call the agent makes inside a work window (clock/v1 +(rate 0) and the gateway moves it on by a charge for each tool call the agent makes inside a work window (clock/v1 ``fixed``, ``agent_env.env.gateway.fixed_clock``), so the agent's work takes task time and thinking or model latency take -none. A rate other than 0 with it is an error. A later set_time or set_rate without it (sync_env_clock, or -set_env_clock_rate to 0 after the agent's last prompt_agent) leaves fixed mode. +none. A rate other than 0 with it is an error. The charge defaults to 60 s (``FIXED_SECONDS_PER_CALL``), and a task may +set it with the step's ``fixed_time_increment_on_tool_call_seconds`` (``fixed_increment``): a number of seconds above 0 +and at most a day, checked at load as the gateway checks it, and accepted only with ``clock_mode: "fixed"``. The step +sends it to the gateway as it turns the mode on (``start_fixed``) and records it in ``clock_configurations`` beside +``clock_mode``. A later set_time or set_rate without it (sync_env_clock, or set_env_clock_rate to 0 after the agent's +last prompt_agent) leaves fixed mode. The clock step only turns the mode on; who the agent is, the step that runs it says. prompt_agent opens a window for its agent's roles around its conversation (``agent_work_window``) and always_on one around each of the agent's turns, @@ -36,13 +40,20 @@ import httpx -from agent_env.env.gateway.constants import CLOCK_FIXED_MODE, DEFAULT_ROLE, EXT_CLOCK_URI, FIXED_SECONDS_PER_CALL +from agent_env.env.gateway.constants import ( + CLOCK_FIXED_MODE, + DEFAULT_ROLE, + EXT_CLOCK_URI, + FIXED_SECONDS_PER_CALL, + fixed_seconds_per_call_error, +) from agent_env.task_step.context import INFRA_ERROR, AgentTurnInfraError, StepContextError from agent_env.task_step.task_steps.mcp_cli_builder.codegen import DEFAULT_CLI_ROLE logger = logging.getLogger(__name__) CLOCK_MODES = (CLOCK_FIXED_MODE,) +INCREMENT_FIELD = "fixed_time_increment_on_tool_call_seconds" # a clock step's charge per call in fixed mode FIXED_METHODS = ("fixed", "open_work_window", "close_work_window") WORK_WINDOWS_KEY = "work_windows" # context.metadata: each window a step opened, with what it charged LEFT_OPEN_KEY = "work_windows_left_open" # context.metadata: each window a step couldn't be sure it closed @@ -59,12 +70,33 @@ def clock_mode_rate(step_type: str, clock_mode: Any, rate: Any, default: Optiona if rate is None: return 0 if clock_mode == CLOCK_FIXED_MODE else default if clock_mode == CLOCK_FIXED_MODE and (isinstance(rate, bool) or not isinstance(rate, (int, float)) or rate != 0): - raise ValueError(f"{step_type}: clock_mode 'fixed' runs the clock at rate 0, moving it on " - f"{FIXED_SECONDS_PER_CALL:g} s for each of the agent's tool calls; got " + raise ValueError(f"{step_type}: clock_mode 'fixed' runs the clock at rate 0, moving it on by a charge for each " + f"of the agent's tool calls ({INCREMENT_FIELD}, {FIXED_SECONDS_PER_CALL:g} s by default); got " f"virtual_seconds_per_real_second={rate!r}: leave it out or set 0") return rate +def fixed_increment(step_type: str, clock_mode: Any, seconds: Any) -> Any: + """A clock step's ``fixed_time_increment_on_tool_call_seconds``, as given: None, unset, for the default charge; + else the task seconds each of the agent's charged tool calls takes in fixed mode. Raises ValueError for one set + without ``clock_mode: "fixed"``, and for one the gateway would refuse (``fixed_seconds_per_call_error``).""" + if seconds is None: + return None + if clock_mode != CLOCK_FIXED_MODE: + raise ValueError(f"{step_type}: {INCREMENT_FIELD} is the task time each of the agent's tool calls takes in " + f"fixed mode, so it needs clock_mode 'fixed'; got clock_mode={clock_mode!r}") + error = fixed_seconds_per_call_error(seconds) + if error: + raise ValueError(f"{step_type}: {INCREMENT_FIELD} {error}") + return seconds + + +def seconds_per_call(increment: Optional[float]) -> float: + """What each charged call costs for a step's ``fixed_time_increment_on_tool_call_seconds``: it, or + ``FIXED_SECONDS_PER_CALL`` unset.""" + return FIXED_SECONDS_PER_CALL if increment is None else float(increment) + + def require_fixed(deployed, env_id: str) -> None: """Refuse, before the clock is touched, fixed mode on a gateway whose stored card offers no clock/v1 fixed or work windows. A record that kept no card is left to the clock call, which says so.""" @@ -75,10 +107,12 @@ def require_fixed(deployed, env_id: str) -> None: "(agent-env env gateway put) and redeploy") -async def start_fixed(deployed, env_id: str, timeout: int) -> dict: - """Turn fixed mode on at ``deployed``'s gateway, its clock armed at rate 0; the gateway's fixed block.""" +async def start_fixed(deployed, env_id: str, timeout: int, seconds: float) -> dict: + """Turn fixed mode on at ``deployed``'s gateway, its clock armed at rate 0, each of the agent's charged tool calls + then moving the clock on ``seconds`` (``seconds_per_call``); the gateway's fixed block.""" try: - answer = await deployed.invoke(EXT_CLOCK_URI, "fixed", {"on": True}, timeout=timeout) + answer = await deployed.invoke(EXT_CLOCK_URI, "fixed", {"on": True, "seconds_per_tool_call": seconds}, + timeout=timeout) except httpx.HTTPStatusError as e: raise RuntimeError(f"env '{env_id}': turning fixed mode on failed (HTTP {e.response.status_code}): " f"{e.response.text[:_MAX_ERROR_CHARS]}") from e diff --git a/src/agent_env/task_step/task_steps/set_env_clock_rate.py b/src/agent_env/task_step/task_steps/set_env_clock_rate.py index cdb8112c8..70c633e2a 100644 --- a/src/agent_env/task_step/task_steps/set_env_clock_rate.py +++ b/src/agent_env/task_step/task_steps/set_env_clock_rate.py @@ -7,9 +7,10 @@ With clock_mode "fixed" (``clock_mode.py``) as the step that starts the clock before prompt_agent, the rate is 0, its default in that mode (any other is an error), and the gateway's fixed mode is turned on, so each tool call the agent -makes inside its work window (prompt_agent's, always_on's) moves task time on by a fixed charge. Without it, the rate -set leaves fixed mode, ending any window open, so a rate of 0 after the agent's last prompt_agent stops the clock for -verifiers in either mode. +makes inside its work window (prompt_agent's, always_on's) moves task time on by a charge: 60 s by default, or the +step's ``fixed_time_increment_on_tool_call_seconds`` (above 0, at most a day; only with clock_mode). Without it, the +rate set leaves fixed mode, ending any window open, so a rate of 0 after the agent's last prompt_agent stops the clock +for verifiers in either mode. """ from __future__ import annotations @@ -23,7 +24,13 @@ from agent_env.env.gateway.constants import EXT_CLOCK_URI from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.task_step.task_step import TaskStep, TaskStepDependency -from agent_env.task_step.task_steps.clock_mode import clock_mode_rate, require_fixed, start_fixed +from agent_env.task_step.task_steps.clock_mode import ( + clock_mode_rate, + fixed_increment, + require_fixed, + seconds_per_call, + start_fixed, +) from agent_env.task_step.task_steps.deploy_agent import _deploy_step_of, bound_deployment logger = logging.getLogger(__name__) @@ -55,6 +62,7 @@ def __init__( fail_task_on_error: bool = True, timeout_seconds: int = 30, clock_mode: Optional[str] = None, + fixed_time_increment_on_tool_call_seconds: Optional[float] = None, ): super().__init__(id, version, depends_on=depends_on, fail_task_on_error=fail_task_on_error) rate = clock_mode_rate(self.type, clock_mode, virtual_seconds_per_real_second, None) @@ -63,6 +71,8 @@ def __init__( self.env_id = env_id self.virtual_seconds_per_real_second = rate self.clock_mode = clock_mode + self.fixed_time_increment_on_tool_call_seconds = fixed_increment( + self.type, clock_mode, fixed_time_increment_on_tool_call_seconds) self.env_step_id = env_step_id self.timeout_seconds = timeout_seconds @@ -74,6 +84,8 @@ def to_dict(self) -> dict: base["timeout_seconds"] = self.timeout_seconds if self.clock_mode is not None: base["clock_mode"] = self.clock_mode + if self.fixed_time_increment_on_tool_call_seconds is not None: + base["fixed_time_increment_on_tool_call_seconds"] = self.fixed_time_increment_on_tool_call_seconds return base @classmethod @@ -85,6 +97,7 @@ def from_dict(cls, data: dict) -> SetEnvClockRateTaskStep: env_step_id=data.get("env_step_id"), timeout_seconds=data.get("timeout_seconds", 30), clock_mode=data.get("clock_mode"), + fixed_time_increment_on_tool_call_seconds=data.get("fixed_time_increment_on_tool_call_seconds"), ) async def execute(self, context: TaskStepContext) -> TaskStepContext: @@ -107,8 +120,9 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: if self.clock_mode is not None or self.env_step_id: # the deployment it names, for fixed_mode_envs configuration["deploy_step_id"] = _deploy_step_of(deployed) if self.clock_mode is not None: - configuration.update(clock_mode=self.clock_mode, - fixed=await start_fixed(deployed, self.env_id, self.timeout_seconds)) + increment = seconds_per_call(self.fixed_time_increment_on_tool_call_seconds) + configuration.update(clock_mode=self.clock_mode, fixed_time_increment_on_tool_call_seconds=increment, + fixed=await start_fixed(deployed, self.env_id, self.timeout_seconds, increment)) context.metadata.setdefault("clock_configurations", []).append(configuration) mode = f" in {self.clock_mode} mode" if self.clock_mode else "" logger.info(f"set_env_clock_rate env={self.env_id}: rate={self.virtual_seconds_per_real_second}{mode} " diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index 29ff489d1..37831cc32 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -14,8 +14,8 @@ before prompt_agent so the virtual timeline starts at agent-start; when setup needs the clock armed, arm it at rate 0 and start it with set_env_clock_rate right before prompt_agent. With clock_mode "fixed" (``clock_mode.py``), the clock is armed frozen and the gateway's fixed mode turned on, so each -tool call the agent makes inside its work window (prompt_agent's, always_on's) moves task time on by a fixed charge; a -nonzero rate with it is an error. +tool call the agent makes inside its work window (prompt_agent's, always_on's) moves task time on by a charge: 60 s by +default, or the step's fixed_time_increment_on_tool_call_seconds; a nonzero rate with it is an error. """ from __future__ import annotations @@ -35,7 +35,13 @@ from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.entity.refs import EntityRef from agent_env.task_step.task_step import TaskStep, TaskStepDependency -from agent_env.task_step.task_steps.clock_mode import clock_mode_rate, require_fixed, start_fixed +from agent_env.task_step.task_steps.clock_mode import ( + clock_mode_rate, + fixed_increment, + require_fixed, + seconds_per_call, + start_fixed, +) from agent_env.task_step.task_steps.deploy_agent import bound_deployment if TYPE_CHECKING: @@ -90,13 +96,17 @@ def __init__( require_agent_clock: bool = False, agent_clock: bool = False, clock_mode: Optional[str] = None, + fixed_time_increment_on_tool_call_seconds: Optional[float] = None, ): """virtual_seconds_per_real_second = clock speed (1.0 real time, the default, 0 frozen, 86400 cap = 1 real s -> 1 virtual day). For ~V virtual seconds over an ~R-real-second task, pass V/R. clock_mode = unset, the default, for a clock that runs at its rate, as it always has; "fixed" for fixed mode: the - clock frozen (rate 0, the rate's default in it; any other rate is an error) and moved on by a fixed charge for - each tool call the agent makes inside the work window the step running it opens (``clock_mode.py``). + clock frozen (rate 0, the rate's default in it; any other rate is an error) and moved on by a charge for each + tool call the agent makes inside the work window the step running it opens (``clock_mode.py``). + + fixed_time_increment_on_tool_call_seconds = that charge, in task seconds: unset, the default, for 60; else a + number above 0 and at most 86400 (a day). Only with clock_mode "fixed". timezone = optional IANA name. Unset keeps today's behaviour. Set, a wall-clock virtual_time is local time in that zone, the gateway's clock is armed in it, so its get_time answers in it too, and every synced server is @@ -116,6 +126,8 @@ def __init__( self.virtual_time = virtual_time self.virtual_seconds_per_real_second = clock_mode_rate(self.type, clock_mode, virtual_seconds_per_real_second, 1.0) self.clock_mode = clock_mode + self.fixed_time_increment_on_tool_call_seconds = fixed_increment( + self.type, clock_mode, fixed_time_increment_on_tool_call_seconds) self.tolerate_missing_sync_time = tolerate_missing_sync_time self.require_agent_clock = require_agent_clock self.agent_clock = agent_clock or require_agent_clock @@ -139,6 +151,8 @@ def to_dict(self) -> dict: base["agent_clock"] = True if self.clock_mode is not None: base["clock_mode"] = self.clock_mode + if self.fixed_time_increment_on_tool_call_seconds is not None: + base["fixed_time_increment_on_tool_call_seconds"] = self.fixed_time_increment_on_tool_call_seconds return base @classmethod @@ -155,6 +169,7 @@ def from_dict(cls, data: dict) -> SyncEnvClockTaskStep: require_agent_clock=data.get("require_agent_clock", False), agent_clock=data.get("agent_clock", False), clock_mode=data.get("clock_mode"), + fixed_time_increment_on_tool_call_seconds=data.get("fixed_time_increment_on_tool_call_seconds"), ) async def _backing_servers(self, deployed) -> list[BackingServer]: @@ -187,7 +202,9 @@ 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") - fixed = await start_fixed(deployed, self.env_id, self.timeout_seconds) if self.clock_mode is not None else None + increment = seconds_per_call(self.fixed_time_increment_on_tool_call_seconds) + fixed = (await start_fixed(deployed, self.env_id, self.timeout_seconds, increment) + if self.clock_mode is not None else None) 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 " @@ -219,7 +236,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: configuration.update(timezone=self.timezone, armed_at=self.armed_virtual_time, get_time_zone=state.get("time_zone")) if self.clock_mode is not None: - configuration.update(clock_mode=self.clock_mode, fixed=fixed) + configuration.update(clock_mode=self.clock_mode, fixed_time_increment_on_tool_call_seconds=increment, + fixed=fixed) context.metadata.setdefault("clock_configurations", []).append(configuration) mode = f" in {self.clock_mode} mode" if self.clock_mode else "" logger.info(f"sync_env_clock env={self.env_id}: armed rate={self.virtual_seconds_per_real_second}{mode}; " diff --git a/tst/unit/env/gateway/fixed_clock_socket_test.py b/tst/unit/env/gateway/fixed_clock_socket_test.py index d17a4d06f..cd2b419f6 100644 --- a/tst/unit/env/gateway/fixed_clock_socket_test.py +++ b/tst/unit/env/gateway/fixed_clock_socket_test.py @@ -35,7 +35,7 @@ def app_lookup() -> str: async with httpx.AsyncClient(base_url=url) as http: r = await http.put("/clock/set-time", json={"virtual_time": T0, "virtual_seconds_per_real_second": 0}) assert r.status_code == 200, r.text - assert (await http.put("/clock/fixed", json={"on": True})).status_code == 200 + assert (await http.put("/clock/fixed", json={"on": True, "seconds_per_tool_call": 60})).status_code == 200 r = await http.put("/clock/fixed/window", json={"window": "turn-1", "roles": ["solver"]}) assert r.status_code == 200, r.text diff --git a/tst/unit/env/gateway/fixed_clock_test.py b/tst/unit/env/gateway/fixed_clock_test.py index 7ed4d12a3..755b67aa9 100644 --- a/tst/unit/env/gateway/fixed_clock_test.py +++ b/tst/unit/env/gateway/fixed_clock_test.py @@ -1,5 +1,6 @@ -"""Fixed mode (FD-7183): a frozen clock moved on by a fixed charge for each answered tool call the agent makes, so the -world lives through the agent's work. Clock.advance_by, the /clock/fixed switch, the work windows the agent-running +"""Fixed mode (FD-7183): a frozen clock moved on by a charge for each answered tool call the agent makes (the +seconds_per_tool_call it was turned on with), so the world lives through the agent's work. Clock.advance_by, the +/clock/fixed switch, the work windows the agent-running steps open for the agent's roles, the charge on every call path inside a window and on no one else's, and the hold until the world's work runnable now has landed.""" from __future__ import annotations @@ -9,6 +10,7 @@ import time import httpx +import jsonschema import pytest from mcp.types import CallToolResult, TextContent @@ -125,8 +127,11 @@ async def _arm(client: httpx.AsyncClient) -> None: assert r.status_code == 200, r.text -async def _fixed(client: httpx.AsyncClient, on: bool = True) -> httpx.Response: - return await client.put("/clock/fixed", json={"on": on}) +async def _fixed(client: httpx.AsyncClient, on: bool = True, seconds: float = 60) -> httpx.Response: + """Turn fixed mode on, charging ``seconds`` for each call, as the clock steps do (60 unless the task sets it); or + off.""" + body = {"on": True, "seconds_per_tool_call": seconds} if on else {"on": False} + return await client.put("/clock/fixed", json=body) async def _open(client: httpx.AsyncClient, roles=("default",), window: str = "turn-1") -> httpx.Response: @@ -176,21 +181,25 @@ def _logged(gateway: Gateway, event_type: str) -> list[dict]: @pytest.mark.asyncio async def test_state_shows_fixed_mode_off_until_turned_on(gw): + """The charge per call is the one fixed mode was turned on with, and none (null) while it is off.""" async with _client(gw) as client: await _arm(client) - assert await _fixed_state(client) == {"on": False, "seconds_per_call": 60.0, "windows": [], + assert await _fixed_state(client) == {"on": False, "seconds_per_call": None, "windows": [], "calls": 0, "virtual_seconds": 0.0, "by_role": {}} r = await _fixed(client) assert r.status_code == 200, r.text - assert r.json()["fixed"]["on"] is True + assert (r.json()["fixed"]["on"], r.json()["fixed"]["seconds_per_call"]) == (True, 60.0) assert (await _fixed_state(client))["on"] is True - assert (await _fixed(client, on=False)).json()["fixed"]["on"] is False + off = (await _fixed(client, on=False)).json()["fixed"] + assert (off["on"], off["seconds_per_call"]) == (False, None) @pytest.mark.asyncio @pytest.mark.parametrize("body", [ [], {}, {"on": "yes"}, {"on": 1}, {"on": None}, {"on": True, "seconds_per_call": 30}, - {"on": True, "roles": ["default"]}, {"on": True, "hold_seconds": 5}, {"on": True, "tool_seconds": {"x": 1}}, + {"on": True, "seconds_per_tool_call": 60, "roles": ["default"]}, {"on": True, "hold_seconds": 5}, + {"on": True, "seconds_per_tool_call": 60, "tool_seconds": {"x": 1}}, + {"on": False, "seconds_per_tool_call": 60}, # a charge is what fixed mode makes while on: turning it off takes none ]) async def test_a_bad_body_is_refused_and_changes_nothing(gw, body): async with _client(gw) as client: @@ -202,6 +211,66 @@ async def test_a_bad_body_is_refused_and_changes_nothing(gw, body): assert (await client.put("/clock/fixed", content=b"not json")).status_code == 400 +@pytest.mark.asyncio +@pytest.mark.parametrize("seconds", [ + True, False, float("nan"), float("inf"), float("-inf"), 0, 0.0, -0.0, -1, -0.5, "60", None, [60], {"s": 60}, + 86400.001, 86401, 1e9, +], ids=repr) +async def test_turning_it_on_refuses_a_charge_per_call_that_is_no_finite_number_above_0_and_at_most_a_day(gw, seconds): + """Refused, the switch changes nothing: off stays off, and on stays on at the charge it had.""" + body = json.dumps({"on": True, "seconds_per_tool_call": seconds}) + async with _client(gw) as client: + await _arm(client) + r = await client.put("/clock/fixed", content=body) + assert r.status_code == 400 and "seconds_per_tool_call" in r.json()["error"], r.text + assert (await _fixed_state(client))["on"] is False + assert (await _fixed(client, seconds=30)).status_code == 200 + assert (await client.put("/clock/fixed", content=body)).status_code == 400 + fixed = await _fixed_state(client) + assert (fixed["on"], fixed["seconds_per_call"]) == (True, 30.0) + + +@pytest.mark.asyncio +async def test_turning_it_on_without_a_charge_per_call_is_refused(gw): + async with _client(gw) as client: + await _arm(client) + r = await client.put("/clock/fixed", json={"on": True}) + assert r.status_code == 400, r.text + assert "seconds_per_tool_call" in r.json()["error"] + assert (await _fixed_state(client))["on"] is False + + +@pytest.mark.asyncio +@pytest.mark.parametrize("seconds", [0.001, 1, 15, 15.5, 60, 86400]) +async def test_turning_it_on_takes_any_charge_per_call_above_0_up_to_a_day(gw, seconds): + async with _client(gw) as client: + await _arm(client) + r = await _fixed(client, seconds=seconds) + assert r.status_code == 200, r.text + assert r.json()["fixed"]["seconds_per_call"] == seconds + + +@pytest.mark.asyncio +async def test_each_call_in_a_window_is_charged_the_seconds_fixed_mode_was_turned_on_with(gw): + async with _client(gw) as client: + await _arm(client) + assert (await _fixed(client, seconds=15)).status_code == 200 + assert (await _open(client)).status_code == 200 + await _call(client, "app_lookup") + await _mcp(gw, "app_lookup") + assert await _now(client) == "2026-11-08T17:00:30Z" + fixed = await _fixed_state(client) + assert (fixed["seconds_per_call"], fixed["calls"], fixed["virtual_seconds"]) == (15.0, 2, 30.0) + assert fixed["by_role"] == {"default": {"calls": 2, "virtual_seconds": 30.0}} + assert (await _close(client)).json()["window"]["virtual_seconds"] == 30.0 + # Turned on again at another charge, the calls after are charged that. + assert (await _fixed(client, seconds=90)).status_code == 200 + await _open(client, window="turn-2") + await _call(client, "app_lookup") + assert await _now(client) == "2026-11-08T17:02:00Z" + assert [e["seconds"] for e in _logged(gw, "fixed_clock_charge")] == [15.0, 15.0, 90.0] + + @pytest.mark.asyncio async def test_turning_it_on_needs_an_armed_frozen_clock_and_keeps_the_clocks_version(gw): async with _client(gw) as client: @@ -263,7 +332,9 @@ def test_the_card_offers_fixed_and_its_windows(): methods = clock_ext["params"]["methods"] fixed = methods["fixed"] assert (fixed["method"], fixed["endpoint"]) == ("PUT", "/clock/fixed") - assert set(fixed["request"]["properties"]) == {"on"} and fixed["request"]["required"] == ["on"] + assert set(fixed["request"]["properties"]) == {"on", "seconds_per_tool_call"} + assert fixed["request"]["required"] == ["on"] + assert fixed["request"]["then"] == {"required": ["seconds_per_tool_call"]} # when on is true opened, closed = methods["open_work_window"], methods["close_work_window"] assert (opened["method"], opened["endpoint"]) == ("PUT", "/clock/fixed/window") assert set(opened["request"]["required"]) == {"window", "roles"} @@ -272,6 +343,33 @@ def test_the_card_offers_fixed_and_its_windows(): assert "fixed" in clock_ext["description"] and "window" in clock_ext["description"] +@pytest.mark.asyncio +@pytest.mark.parametrize("body,valid", [ + ({"on": True, "seconds_per_tool_call": 60}, True), + ({"on": True, "seconds_per_tool_call": 0.5}, True), + ({"on": True, "seconds_per_tool_call": 86400}, True), + ({"on": False}, True), + ({"on": True}, False), + ({"on": True, "seconds_per_tool_call": 0}, False), + ({"on": True, "seconds_per_tool_call": -1}, False), + ({"on": True, "seconds_per_tool_call": 86400.5}, False), + ({"on": True, "seconds_per_tool_call": "60"}, False), + ({"on": True, "seconds_per_tool_call": True}, False), + ({"on": True, "seconds_per_tool_call": None}, False), + ({"on": False, "seconds_per_tool_call": 60}, False), + ({"on": True, "seconds_per_tool_call": 60, "roles": ["a"]}, False), + ({}, False), +]) +async def test_the_cards_fixed_schema_admits_exactly_the_bodies_the_switch_takes(gw, body, valid): + """The advertised request schema requires seconds_per_tool_call when on is true, as the gateway does.""" + clock_ext = next(e for e in GATEWAY_EXTENSIONS if e["uri"] == EXT_CLOCK_URI) + schema = clock_ext["params"]["methods"]["fixed"]["request"] + assert jsonschema.Draft202012Validator(schema).is_valid(body) is valid + async with _client(gw) as client: + await _arm(client) + assert ((await client.put("/clock/fixed", json=body)).status_code == 200) is valid + + def test_the_fixed_routes_are_control_routes(): assert {"/clock/fixed", "/clock/fixed/window"} <= CONTROL_ROUTES diff --git a/tst/unit/task_step/clock_mode_test.py b/tst/unit/task_step/clock_mode_test.py index 838c787cd..6a2d43e0c 100644 --- a/tst/unit/task_step/clock_mode_test.py +++ b/tst/unit/task_step/clock_mode_test.py @@ -1,8 +1,8 @@ """The clock setup steps' ``clock_mode`` (FD-7183): ``"fixed"`` arms the clock frozen (rate 0) and turns on the -gateway's fixed mode, where each tool call the agent makes inside a work window moves task time on by a fixed charge, -so a frozen world still lives through the agent's work. sync_env_clock and set_env_clock_rate both take it, and -prompt_agent opens the window around the agent's turns, each driving a real in-process gateway here. Without -clock_mode, every step does exactly what it did before.""" +gateway's fixed mode, where each tool call the agent makes inside a work window moves task time on by a charge (60 s +by default, or the step's fixed_time_increment_on_tool_call_seconds), so a frozen world still lives through the agent's +work. sync_env_clock and set_env_clock_rate both take it, and prompt_agent opens the window around the agent's turns, +each driving a real in-process gateway here. Without clock_mode, every step does exactly what it did before.""" from __future__ import annotations import json @@ -125,13 +125,14 @@ async def test_sync_env_clock_in_fixed_mode_arms_frozen_then_turns_fixed_on(worl assert world.clock_calls() == [ ("PUT", "/clock/set-time", {"virtual_time": T0, "virtual_seconds_per_real_second": 0}), ("GET", "/clock/state", None), - ("PUT", "/clock/fixed", {"on": True}), + ("PUT", "/clock/fixed", {"on": True, "seconds_per_tool_call": 60}), # the default charge ] state = await world.state() assert state["virtual_seconds_per_real_second"] == 0 assert state["fixed"]["on"] is True and state["fixed"]["seconds_per_call"] == 60 record = context.metadata["clock_configurations"][0] assert record["clock_mode"] == "fixed" and record["virtual_seconds_per_real_second"] == 0 + assert record["fixed_time_increment_on_tool_call_seconds"] == 60 assert record["fixed"]["on"] is True and record["deploy_step_id"] == "deploy" await world.call() # no agent's turn has opened a work window yet: setup's calls take no time @@ -199,11 +200,12 @@ async def test_set_env_clock_rate_in_fixed_mode_freezes_the_clock_then_turns_fix assert world.clock_calls() == [ ("PUT", "/clock/set-rate", {"virtual_seconds_per_real_second": 0}), - ("PUT", "/clock/fixed", {"on": True}), + ("PUT", "/clock/fixed", {"on": True, "seconds_per_tool_call": 60}), ] assert (await world.state())["fixed"]["on"] is True record = context.metadata["clock_configurations"][0] assert (record["clock_mode"], record["deploy_step_id"]) == ("fixed", "deploy") + assert record["fixed_time_increment_on_tool_call_seconds"] == 60 await world.call() assert (await world.state())["virtual_time"] == T0 @@ -242,6 +244,72 @@ async def test_set_env_clock_rate_to_zero_ends_fixed_mode_and_the_agents_window( assert (await world.state())["virtual_time"] == state["virtual_time"] +# ---- the charge per call: fixed_time_increment_on_tool_call_seconds ------------------------------------------------- + +INCREMENT = "fixed_time_increment_on_tool_call_seconds" + + +def _clock_step(kind: str, **kw): + return _sync(**kw) if kind == "sync" else _rate(**kw) + + +@pytest.mark.parametrize("kind", ["sync", "rate"]) +def test_the_charge_per_call_defaults_to_60_and_is_left_out_of_the_step_json_unset(kind): + step = _clock_step(kind, clock_mode="fixed") + assert getattr(step, INCREMENT) is None + assert INCREMENT not in step.to_dict() + assert getattr(type(step).from_dict(step.to_dict()), INCREMENT) is None + + +@pytest.mark.parametrize("kind", ["sync", "rate"]) +@pytest.mark.parametrize("seconds", [15, 0.5, 86400]) +def test_a_charge_per_call_the_task_sets_is_in_the_step_json_and_round_trips(kind, seconds): + d = _clock_step(kind, clock_mode="fixed", **{INCREMENT: seconds}).to_dict() + assert d[INCREMENT] == seconds + again = type(_clock_step(kind, clock_mode="fixed")).from_dict(d) + assert getattr(again, INCREMENT) == seconds and again.to_dict() == d + + +@pytest.mark.parametrize("kind", ["sync", "rate"]) +def test_a_charge_per_call_without_fixed_mode_is_refused_at_load(kind): + rate = {} if kind == "sync" else {"virtual_seconds_per_real_second": 0} + with pytest.raises(ValueError, match=f"{INCREMENT}.*clock_mode 'fixed'"): + _clock_step(kind, **rate, **{INCREMENT: 15}) + d = _clock_step(kind, **rate).to_dict() + with pytest.raises(ValueError, match=INCREMENT): + type(_clock_step(kind, **rate)).from_dict({**d, INCREMENT: 15}) + + +@pytest.mark.parametrize("kind", ["sync", "rate"]) +@pytest.mark.parametrize("seconds", [ + True, False, float("nan"), float("inf"), float("-inf"), 0, 0.0, -1, -0.5, "60", [60], {"s": 60}, 86400.001, 1e9, +], ids=repr) +def test_a_charge_per_call_the_gateway_would_refuse_is_refused_at_load(kind, seconds): + with pytest.raises(ValueError, match=INCREMENT): + _clock_step(kind, clock_mode="fixed", **{INCREMENT: seconds}) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["sync", "rate"]) +async def test_the_clock_step_sends_the_charge_the_task_set_and_the_gateway_charges_it(world, kind): + context = await world.context() + if kind == "rate": + await _sync(virtual_seconds_per_real_second=0).execute(context) # armed frozen during setup + world.forget() + + await _clock_step(kind, clock_mode="fixed", **{INCREMENT: 15}).execute(context) + + assert world.clock_calls()[-1] == ("PUT", "/clock/fixed", {"on": True, "seconds_per_tool_call": 15}) + assert (await world.state())["fixed"]["seconds_per_call"] == 15 + record = context.metadata["clock_configurations"][-1] + assert (record["clock_mode"], record[INCREMENT]) == ("fixed", 15) + async with world.http() as client: + await client.put("/clock/fixed/window", json={"window": "turn", "roles": ["solver"]}) + await world.call(role="solver") + await world.call(role="solver") + assert (await world.state())["virtual_time"] == "2026-11-09T14:00:30Z" + + # ---- no clock_mode: exactly as before ------------------------------------------------------------------------------- @pytest.mark.asyncio diff --git a/tst/unit/task_step/test_always_on_fixed_clock.py b/tst/unit/task_step/test_always_on_fixed_clock.py index 86f0462f4..a58f1e94a 100644 --- a/tst/unit/task_step/test_always_on_fixed_clock.py +++ b/tst/unit/task_step/test_always_on_fixed_clock.py @@ -1,8 +1,9 @@ """Fixed mode (FD-7183) in an always_on run. The task's clock step puts the clock in fixed mode (sync_env_clock with -``clock_mode: "fixed"``): frozen, and moved on a minute by the gateway for each tool call the agent makes inside a work -window, so the world lives through the agent's work and what comes due mid-wake lands then. always_on opens the window -for the agent's role around each turn, nudges included, and closes it at the turn's end: each wake records what its -work took, the run's record sums it, and the judge reads it. No one but the agent is charged, inside its turns or out.""" +``clock_mode: "fixed"``): frozen, and moved on a minute (the default charge) by the gateway for each tool call the agent +makes inside a work window, so the world lives through the agent's work and what comes due mid-wake lands then. +always_on opens the window for the agent's role around each turn, nudges included, and closes it at the turn's end: each +wake records what its work took, the run's record sums it, and the judge reads it. No one but the agent is charged, +inside its turns or out.""" from __future__ import annotations @@ -29,12 +30,12 @@ pytestmark = pytest.mark.usefixtures("local_stores") -async def _fixed_mode(monkeypatch, rig: Rig, ctx) -> None: +async def _fixed_mode(monkeypatch, rig: Rig, ctx, **kw) -> None: """Arm the clock in fixed mode as the task's clock step does: sync_env_clock with clock_mode "fixed".""" monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace(mcp_server_envs=[], website_envs=[])) await SyncEnvClockTaskStep(id="clock", version=1, env_id="world", virtual_time=rig.t0, - clock_mode="fixed").execute(ctx) + clock_mode="fixed", **kw).execute(ctx) async def _fixed_state(rig: Rig) -> dict: @@ -79,6 +80,28 @@ async def agent(n, texts, rig): assert fixed["by_role"] == {ROLE: {"calls": 3, "virtual_seconds": 180.0}} +@pytest.mark.asyncio +async def test_a_charge_per_call_the_task_sets_is_what_each_wakes_work_takes_and_what_the_record_names(monkeypatch, + tmp_path): + async def agent(n, texts, rig): + for _ in range(3): + await rig.call("market_search") + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + rig.tool("market_search", "Chicago: 2 left") + ctx = rig.context() + await _fixed_mode(monkeypatch, rig, ctx, fixed_time_increment_on_tool_call_seconds=15) + await rig.run(rig.step(settle_timeout_seconds=0.2, max_wakes=1), ctx) + + (turn,) = rig.events(ctx, "agent_turn_end") + assert turn["work"] == {"calls": 3, "virtual_seconds": 45.0} + record = rig.record(ctx) + assert record["counts"]["fixed_clock"] == {"calls": 3, "virtual_seconds": 45.0} + assert record["settings"]["clock"]["fixed"] == {"seconds_per_call": 15.0, "envs": ["world"]} + + @pytest.mark.asyncio async def test_what_comes_due_mid_wake_lands_before_the_agents_next_call(monkeypatch, tmp_path): status: list[str] = []