Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
(`task_step/executors.py`), 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, as an embedder's chat with a run's agent outside its steps (`playground`).
`validator` is the role for a step that checks a run without grading it. None of the three (`UsageRole`) is a
`[model.roles]` key; `summarize` lists them after the solver, user simulator and judge.
- 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
10 changes: 10 additions & 0 deletions src/agent_env/config/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ def record_key(self) -> str:
return "user simulator" if self is ModelRole.USER_SIMULATOR else self.value


class UsageRole(StrEnum):
"""A role a run's usage is recorded under that no ``[model.roles]`` key configures: an env trigger's executor,
which the env's gateway calls (``executor``); a step that checks a run without grading it (``validator``); and a
chat an embedder holds with a run's agent outside its steps (``playground``)."""

EXECUTOR = "executor"
VALIDATOR = "validator"
PLAYGROUND = "playground"


ROLE_SYNONYMS: dict[str, ModelRole] = {"agent": ModelRole.SOLVER, "user": ModelRole.USER_SIMULATOR}

# What a run's overrides name for each role, read by the steps that call the role's model and by an eval's intent lock,
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
150 changes: 116 additions & 34 deletions src/agent_env/env/gateway/triggers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import math
import random
import re
import secrets
import uuid
from collections import deque
from datetime import datetime, time, timedelta, timezone, tzinfo
Expand Down Expand Up @@ -65,6 +66,8 @@
_VIRTUAL_RESOLUTION_S = 1e-6
# Seconds an executor call waits to connect, and for a task poll's answer.
_EXECUTOR_HTTP_TIMEOUT_S = 30.0
# How much longer a call past its time limit is still read, for the usage its reply reports, in seconds.
_LATE_REPLY_S = 600.0
# An allowlist, not a size bound: identifier/metadata keys only, since bodies and addresses are PII.
_ECHO_KEYS = frozenset({
"action", "createdTime", "fileName", "kind", "mimeType", "modifiedTime", "name", "role",
Expand Down Expand Up @@ -441,6 +444,15 @@ def _validate_check(check: Any, where: str) -> dict:
return {"steps": steps}



async def _task_status(client: httpx.AsyncClient, url: str, task_id: str) -> dict:
"""An executor's A2A task's status, polled with ``tasks/get``."""
poll = await client.post(url, json={"jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": "tasks/get",
"params": {"id": task_id}})
poll.raise_for_status()
return (poll.json().get("result") or {}).get("status") or {}


class TriggerEngine:
def __init__(self, gateway):
self._gw = gateway
Expand All @@ -464,6 +476,14 @@ def __init__(self, gateway):
# One turn at a time per executor conversation (its URL and context id): fires of one trigger running side by
# side would otherwise resume the same session at once.
self._executor_locks: dict[tuple[str, str], asyncio.Lock] = {}
# Every call made to an executor, with the usage it reported (`usage`), under this engine's own id and a
# version every change to the list raises.
self._executor_usage: list[dict] = []
self._usage_boot = secrets.token_hex(6)
self._usage_version = 0
# Each call's exchange with its executor still being read, past its time limit included, which a `clear` leaves
# to finish.
self._exchanges: set[asyncio.Task] = set()

def register(self, body: Any) -> dict:
"""Additively add each trigger by id (idempotent upsert; conflicting id or bad shape -> 400); watch_roles and
Expand Down Expand Up @@ -571,7 +591,8 @@ def remove(self, body: Any) -> dict:
return {"ok": True, "removed": removed}

def clear(self) -> dict:
"""Full reset — triggers, config, and the event log (setup/testing only; never mid-task)."""
"""Full reset — triggers, config, and the event log (setup/testing only; never mid-task). The executor calls
made so far stay in ``usage``: they were spent."""
for task in list(self._tasks):
task.cancel()
self._tasks.clear()
Expand Down Expand Up @@ -984,6 +1005,17 @@ def state(self) -> dict:
"events_dropped": max(0, self._seq - len(events)),
}

def usage(self) -> dict:
"""Every call made to an executor so far (GET /triggers/usage), a call still waiting for its reply included:
each one's ``role``, the executor's, and the ``usage`` its final message reported, as it sent it, None while it
runs and when it reported none or no reply was read. ``boot`` is this engine's own id, so a reader that keeps
the calls by it tells a restarted gateway's apart, and ``version`` rises with every change to the list, so a
reader holding two copies keeps the later. ``reading`` is how many calls are still being read, a late one's
included, which a reader about to close the env can wait out."""
return {"boot": self._usage_boot, "version": self._usage_version,
"reading": sum(not exchange.done() for exchange in self._exchanges),
"calls": [dict(call) for call in self._executor_usage]}

def on_tool_call(self, role: str, name: str, arguments: dict,
result: Any) -> tuple[list[asyncio.Task], float | None]:
"""Synchronous post-call detection hook (invoked from the gateway's role-filter wrapper).
Expand Down Expand Up @@ -1755,42 +1787,92 @@ async def _nap(self, seconds: float) -> None:
moved.cancel()

async def _call_executor(self, executor: dict | None, instruction: str, context_id: str) -> str | None:
"""The executor's reply to ``instruction``, None when it gave none in time. The call goes into ``usage`` as it
starts, with no usage while it runs, and takes the usage its final message reported when it ends, however it
ends: its exchange (``_exchange``) runs in a task of its own, which reads on past the time limit, or past a fire
that gave up on it, for up to ``_LATE_REPLY_S`` more, since a late reply is spent too."""
if executor is None:
return None
call: dict[str, Any] = {"role": executor["role"], "usage": None}
self._executor_usage.append(call)
self._usage_version += 1
answer: asyncio.Future = asyncio.get_running_loop().create_future()
exchange = asyncio.ensure_future(self._exchange(executor, instruction, context_id, call, answer))
self._exchanges.add(exchange)
exchange.add_done_callback(self._exchanges.discard)
return await answer

async def _exchange(self, executor: dict, instruction: str, context_id: str, call: dict,
answer: asyncio.Future) -> None:
"""Send ``instruction`` and read the executor's reply to its end for the usage its final message reports,
settling ``answer`` as the fire sees it: the reply; None for a task still working at the time limit;
``ReadTimeout`` for a reply still held past it; or the error it failed with. Once ``answer`` is settled the read
goes on for the usage alone, until ``_LATE_REPLY_S`` past the fire's wait; a read that fails then leaves the
call's usage unknown."""
def settle(reply: str | None = None, error: Exception | None = None) -> None:
if answer.done():
return
if error is not None:
answer.set_exception(error)
else:
answer.set_result(reply)

loop = asyncio.get_running_loop()
url = f"{executor['a2a_url']}/a2a"
deadline = asyncio.get_running_loop().time() + executor["timeout_seconds"]
async with httpx.AsyncClient(timeout=_EXECUTOR_HTTP_TIMEOUT_S) as client:
# An executor holds message/send open until its task ends, so the read waits as long as the executor may
# take, and a little longer, so a reply that completes just past the time limit is still read.
read_s = max(_EXECUTOR_HTTP_TIMEOUT_S, executor["timeout_seconds"]) + _EXECUTOR_HTTP_TIMEOUT_S
send = await client.post(url, timeout=httpx.Timeout(_EXECUTOR_HTTP_TIMEOUT_S, read=read_s), json={
"jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": "message/send",
"params": {"message": {"role": "user", "messageId": uuid.uuid4().hex,
"contextId": context_id,
"parts": [{"kind": "text", "text": instruction}]}},
})
send.raise_for_status()
result = send.json().get("result") or {}
task_id = result.get("id")
if not task_id:
return None
status = result.get("status") or {}
# Polled until the time limit, then once more: a reply that completed in the last poll's gap is kept.
last = False
while status.get("state") not in _TERMINAL_A2A_STATES:
if last:
return None
last = asyncio.get_running_loop().time() >= deadline
if not last:
await asyncio.sleep(2)
poll = await client.post(url, json={"jsonrpc": "2.0", "id": str(uuid.uuid4()),
"method": "tasks/get", "params": {"id": task_id}})
poll.raise_for_status()
status = ((poll.json().get("result") or {}).get("status") or {})
if status.get("state") != "completed":
return None
parts = (status.get("message") or {}).get("parts") or []
return "\n".join(p.get("text", "") for p in parts if p.get("kind") == "text")
deadline = loop.time() + executor["timeout_seconds"]
# An executor holds message/send open until its task ends, so the fire waits as long as the executor may take,
# and a little longer, so a reply that completes just past the time limit is still its reply.
read_s = max(_EXECUTOR_HTTP_TIMEOUT_S, executor["timeout_seconds"]) + _EXECUTOR_HTTP_TIMEOUT_S
until = loop.time() + read_s + _LATE_REPLY_S
try:
async with httpx.AsyncClient(timeout=_EXECUTOR_HTTP_TIMEOUT_S) as client:
held = loop.call_later(read_s, settle, None, httpx.ReadTimeout(""))
try:
response = await client.post(
url, timeout=httpx.Timeout(_EXECUTOR_HTTP_TIMEOUT_S, read=read_s + _LATE_REPLY_S), json={
"jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": "message/send",
"params": {"message": {"role": "user", "messageId": uuid.uuid4().hex,
"contextId": context_id,
"parts": [{"kind": "text", "text": instruction}]}},
})
finally:
held.cancel()
response.raise_for_status()
result = response.json().get("result") or {}
task_id, status = result.get("id"), result.get("status") or {}
if not task_id:
settle(None)
return
# Polled until the time limit, then once more at once, so a reply that completed in the last poll's
# gap is the fire's; after that, for the usage alone.
while status.get("state") not in _TERMINAL_A2A_STATES:
if loop.time() >= until:
return
last = not answer.done() and loop.time() >= deadline
if not last:
await asyncio.sleep(2)
status = await _task_status(client, url, task_id)
if last and status.get("state") not in _TERMINAL_A2A_STATES:
settle(None)
settle(self._replied(status, call))
except Exception as e: # noqa: BLE001 - the fire's error; once it has its answer, the usage stays unknown
settle(error=e)
finally:
if not answer.done():
answer.cancel()

def _replied(self, status: dict, call: dict) -> str | None:
"""The text of an ended executor task's final message when it completed; the usage that message reported goes
on ``call``."""
parts = (status.get("message") or {}).get("parts") or []
reported = [p["data"]["usage"] for p in parts if p.get("kind") == "data"
and isinstance(p.get("data"), dict) and p["data"].get("usage") is not None]
if reported:
call["usage"] = reported[-1]
self._usage_version += 1
if status.get("state") != "completed":
return None
return "\n".join(p.get("text", "") for p in parts if p.get("kind") == "text")

def _cancel(self, tid: str, trig: dict, **cause) -> None:
"""Retire a deadline its `unless` call answered, and the time triggers anchored on it, which can no longer fire."""
Expand Down
Loading
Loading