Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
165c83f
feat(usage): a run's colleagues, its env triggers' executors, count i…
earakely-scale Dec 1, 2026
ebbabfb
fix(usage): list an executor call while it runs, keep the later copy …
earakely-scale Dec 1, 2026
34cbfb9
feat(usage): a reply past its time limit is still read for its usage
earakely-scale Dec 1, 2026
94c08bb
docs(agents): a reply past its time limit is still read for its usage
earakely-scale Dec 1, 2026
7e75a47
Merge remote-tracking branch 'origin/main' into edgararakelyan/env-si…
earakely-scale Dec 1, 2026
fc8e82e
fix(gateway): a call cancelled while its task is polled is still read…
earakely-scale Dec 1, 2026
e9baa62
feat(usage): the teardown waits for colleague replies still being rea…
earakely-scale Dec 1, 2026
74c4fb3
fix(usage): a teardown wait whose later read fails records the list i…
earakely-scale Dec 1, 2026
9f6c62b
fix(registry): a read the network dropped is sent once more
earakely-scale Dec 1, 2026
d77941d
refactor(usage): name the role of a trigger executor's usage `executo…
earakely-scale Dec 1, 2026
1067a58
refactor(usage): one task owns each executor call, teardown ends reco…
earakely-scale Dec 1, 2026
33e776e
refactor(usage): core names only the executor role; an embedder recor…
earakely-scale Dec 2, 2026
8e8c3ac
refactor(usage): the executor role is a constant, not an enum
earakely-scale Dec 2, 2026
2d6605d
refactor(usage): a gateway reads its own executor calls; the step tha…
earakely-scale Dec 2, 2026
a5ae24d
fix(usage): read executor calls from any env whose card offers the li…
earakely-scale Dec 4, 2026
4348040
test(usage): an always_on step records its env's executors' usage und…
earakely-scale Dec 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,20 @@ orchestrators call it the same way. What callers rely on:
runner that doesn't set `ATTEMPT_EPOCH` writes entries with no attempt, kept by step and role alone: exact for a run
without retries, a lower bound for one with. A runner that writes the instance some other way loses that spend
from the ledger.
- A run's trigger executors, the agents an env's gateway calls when a trigger fires, spend outside any prompt: the
gateway lists every such call as it starts, with the usage its final message reported once it ends (`GET
/triggers/usage`, under its own boot id and a version every change raises, kept through a `clear`), a reply past its
time limit still read for that usage in the background, for up to ten minutes more. `prompt_agent` and `always_on` as
they end, and the teardown, write the list as one `executor` entry per env and gateway boot
(`register_env_triggers.record_executor_usage`, from `DeployedEnv.executor_calls`), the teardown waiting up to
a minute, while it ends the run's recordings, for calls the gateway is still reading (`reading`), with no attempt,
under the `register_env_triggers` step that set the executors up, an env whose gateway doesn't list its calls counting
as one call of unknown usage; the ledger keeps it by `gateway_boot` too, so each write is the whole list and replaces
the last, a call counts once whichever step or attempt wrote it, and a gateway a retry redeployed is kept beside the
first. A step's completion takes the context's executor entries with its own, and the teardown writes its own through
`record_usage()`, which merges any finished entries into the ledger alone, so an embedder can record usage of its own
under a role it names. `executor` is no `[model.roles]` key; `summarize` lists it after the solver, user simulator and
judge, and any other role after that.
- The runner writes its run identifier to `context.metadata["workflow_id"]` before calling `run()`;
core stores it opaquely with the instance.
- Each step runs under `protocol_v1.authorized` for the deployed envs in its context: a protocol-client
Expand Down
49 changes: 48 additions & 1 deletion src/agent_env/env/env.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import asyncio
import copy
import logging
import posixpath
Expand All @@ -20,7 +21,7 @@

from .gateway import GatewayMode
from .gateway.console_session import LINK_DEFAULT_SECONDS, LINK_PARAM, ConsoleSession
from .gateway.constants import WELL_KNOWN_PATH
from .gateway.constants import EXT_TRIGGERS_URI, WELL_KNOWN_PATH
from .store import get_env_store

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -185,6 +186,35 @@ async def invoke(self, uri: str, method: str, params: Optional[dict] = None, *,
self.environment_url, card, uri, params, timeout, method=method,
headers=self.control_headers_for(f"{self.environment_url.rstrip('/')}{op.get('endpoint') or ''}"))

@property
def lists_executor_calls(self) -> bool:
"""Whether the gateway serving the env's triggers, ours or one outside our sandboxes, lists the calls it makes
to their executors (``executor_calls``), as its card says; one older than the list doesn't."""
return self.supports(EXT_TRIGGERS_URI, "usage")

async def executor_calls(self, *, wait_seconds: float = 0) -> Optional[ExecutorCalls]:
"""The calls the gateway serving the env's triggers has made to their executors so far. With ``wait_seconds``, a list with calls
still being read, a late reply's included, is read again until none is, for at most that long, and the last
list read stands when a later read fails. None when the gateway doesn't list them or its list couldn't be read;
a failed read is logged, never raised."""
if not self.lists_executor_calls:
return None
until = asyncio.get_running_loop().time() + wait_seconds
try:
report = await self.invoke(EXT_TRIGGERS_URI, "usage", timeout=EXECUTOR_CALLS_READ_TIMEOUT_S)
except Exception as e: # noqa: BLE001 - executor usage never fails a step or a teardown
logger.warning("env %s's executor calls weren't read: %s", self.env_id, e)
return None
while report.get("reading") and asyncio.get_running_loop().time() < until:
await asyncio.sleep(EXECUTOR_CALLS_POLL_S)
try:
report = await self.invoke(EXT_TRIGGERS_URI, "usage", timeout=EXECUTOR_CALLS_READ_TIMEOUT_S)
except Exception as e: # noqa: BLE001 - the last list read stands
logger.warning("env %s's executor calls weren't read again, so its last read stands: %s", self.env_id, e)
break
return ExecutorCalls(boot=str(report.get("boot")), version=int(report.get("version") or 0),
calls=tuple(report.get("calls") or ()))

async def readiness(self, timeout: float = READY_TIMEOUT_S) -> WebsiteReadiness:
"""Whether the env is ready, as the protocol determines a website env's health (``env_readiness``): every site
its card, the stored one or, for a record without it, the card it serves now, advertises ``website/v1``'s
Expand Down Expand Up @@ -235,6 +265,23 @@ def _fields_from(cls, data: dict) -> dict:
}


#: How long one read of a gateway's executor calls may take, in seconds.
EXECUTOR_CALLS_READ_TIMEOUT_S = 15
#: How often a wait for executor calls still being read reads the list again, in seconds.
EXECUTOR_CALLS_POLL_S = 2


@dataclass(frozen=True)
class ExecutorCalls:
"""The calls a gateway made to its triggers' executors (``GET /triggers/usage``): each call's executor ``role`` and
the ``usage`` its final message reported, as sent, None while it runs or when it reported none; under the gateway's
own ``boot`` id, which tells a restarted gateway's list apart, and a ``version`` every change to the list raises."""

boot: str
version: int
calls: tuple[dict, ...]


@dataclass(kw_only=True)
class DeployedGatewayEnv(DeployedSandboxEnv):
"""A deployed env fronted by a gateway: the gateway's URLs and mode, and the state store its deploy holds."""
Expand Down
5 changes: 3 additions & 2 deletions src/agent_env/env/gateway/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,13 +293,14 @@ def random_mcp_server_name() -> str:
},
{
"uri": EXT_TRIGGERS_URI,
"description": "Register (additive add-by-id), remove, clear, or read (state) typed Action/State triggers + the firing log (harness control path). config sets the engine's opt-in setting concurrent_fires (a repeat trigger whose actions are all contact replies (nl) or notifications (notify) runs its fires side by side instead of queueing).",
"description": "Register (additive add-by-id), remove, clear, or read (state) typed Action/State triggers + the firing log (harness control path); usage lists every call made to an executor so far with the usage it reported, under the gateway's boot id. config sets the engine's opt-in setting concurrent_fires (a repeat trigger whose actions are all contact replies (nl) or notifications (notify) runs its fires side by side instead of queueing).",
"params": {"endpoint": "/triggers/register", "features": list(TRIGGER_FEATURES), "methods": {
"register": {"method": "POST", "endpoint": "/triggers/register", "request": {"type": "object", "properties": {"watch_roles": {"type": "array", "items": {"type": "string"}}, "executor": {"type": "object"}, "executors": {"type": "object"}, "triggers": {"type": "array"}}, "required": ["triggers"]}},
"config": {"method": "POST", "endpoint": "/triggers/config", "request": {"type": "object", "properties": {"concurrent_fires": {"type": "boolean"}}}},
"remove": {"method": "POST", "endpoint": "/triggers/remove", "request": {"type": "object", "properties": {"ids": {"type": "array", "items": {"type": "string"}}}, "required": ["ids"]}},
"clear": {"method": "POST", "endpoint": "/triggers/clear", "request": {"type": "object", "properties": {}}},
"state": {"method": "GET", "endpoint": "/triggers/state", "request": {"type": "object", "properties": {}}}}},
"state": {"method": "GET", "endpoint": "/triggers/state", "request": {"type": "object", "properties": {}}},
"usage": {"method": "GET", "endpoint": "/triggers/usage", "request": {"type": "object", "properties": {}}}}},
"required": False,
},
{
Expand Down
4 changes: 4 additions & 0 deletions src/agent_env/env/gateway/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,10 @@ async def triggers_clear(request: Request) -> Response:
async def triggers_state(request: Request) -> Response:
return self._json_response(self._deferred.in_state(self._trigger_engine.state()), 200)

@self._mcp.custom_route("/triggers/usage", methods=["GET"])
async def triggers_usage(request: Request) -> Response:
return self._json_response(self._trigger_engine.usage(), 200)

@self._mcp.custom_route("/clock/set-time", methods=["PUT"])
async def clock_set_time(request: Request) -> Response:
if GET_TIME_TOOL_NAME in self._tool_server_urls:
Expand Down
Loading
Loading