diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index fa2a66cbd..e43ce0c7b 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -90,6 +90,59 @@ step names it. Steps that name it show and hide it as they do any tool. Steps fo that role's earlier named steps, and a full reset (`role: "*", tools: "*"`) clears all of them, so grant a hidden tool after such steps. Trigger tool actions call it as usual. +A tool's successful result can ask the gateway to call the same server later, for something the +server does at a time of its own (a scheduled message posted at its time) that no tool call would +otherwise mark. Its `_meta` `"agentenv.io/deferredCalls"` (`DEFERRED_CALLS_META_KEY`) is a list of +`{"key", "at", "call", "report_as"}`: `at` an RFC 3339 instant with an offset, `call` and +`report_as` each `{"tool", "arguments"}`. The gateway takes the key off the result, so no caller sees +it, and schedules each entry once per server and `key` (one its server declares again while pending +or done is ignored). When the gateway clock reaches `at` (its virtual time while armed, wall UTC +while not) it calls `call.tool` as the role that made the declaring call, as it makes a live call +(under the consistent mode's lock, its write attributed to it). After a transport failure it calls +again: five attempts in all, 1, 2, 4 and 8 s apart, each of which first reopens the server's session +if it must (retrying the connection for about ten seconds), so against a server that stays down the +call fails about 51 s after its first attempt (as observed). So make that tool idempotent (and +`hidden_by_default`, as plumbing). Unless the result is an error, the gateway hands its triggers that +result as that role's call of `report_as.tool` with `report_as.arguments`; a trigger action's own +call provokes no trigger, and neither does one it declares. `GET /triggers/state` lists each under +`deferred_calls` (`due` marks one the clock has reached that is still to make, which settle checks +wait for), and counts the earliest still to make in `next_event_at`. Behind no gateway, or one that +ignores the key, nothing calls it, so a server still acts by itself once the time has passed (on its +next read, say). + +`@tool(..., defers=Defers(call=..., report_as=..., using=...))` builds that declaration for you, and +the tool returns its reply as before: + +```python +from agentenv_protocol import DeferredCall, Defers, tool + +@tool(hidden_by_default=True) +def deliver_reminder(self, reminder_id: str) -> str: ... + +@tool(defers=Defers(call="deliver_reminder", report_as="send_notification", using="_reminder_delivery")) +def schedule_reminder(self, event_id: str, remind_at: str) -> str: ... + +def _reminder_delivery(self, arguments: dict, result) -> DeferredCall | list[DeferredCall] | None: + if not result.get("ok"): + return None + return DeferredCall(key=result["reminder_id"], at=result["remind_at"], + arguments={"reminder_id": result["reminder_id"]}, + report_arguments={"event_id": arguments["event_id"]}) +``` + +After each successful call of the registered tool, the SDK calls `self.(arguments, result)` +with the call's arguments and the tool's result: a JSON text reply parsed to its dict or list, a dict +as is, a `CallToolResult`'s `structuredContent` or else its text so parsed, anything else as it is. +Each `DeferredCall` it returns becomes one entry, with the named tools as its `call` and `report_as`; +`at` is an aware datetime, epoch seconds or an RFC 3339 string with an offset, declared in UTC. The +reply's content and structured content are unchanged, and the entries join any `_meta` it has. An +error reply declares nothing, and a declaration that fails (`using` raises, or returns a wrong type, +an empty key or an `at` without an offset) is logged and left out rather than breaking the reply. +The method called in process still returns its plain value. The mount raises unless `call` is a +`hidden_by_default` tool and `report_as` a tool the environment serves (by served name, +`{environment_name}` resolved), and `using` a plain method; the card lists both tools under the +tool's `defers`. + `@tool(..., annotations={"readOnlyHint": True}, structured_output=True, meta={...})` lists the tool with MCP `ToolAnnotations`, an output schema and `_meta`, on mcp's FastMCP and on fastmcp alike. `structured_output` follows mcp's FastMCP (None derives an output schema from the return annotation diff --git a/packages/agentenv-protocol/src/agentenv_protocol/__init__.py b/packages/agentenv-protocol/src/agentenv_protocol/__init__.py index 6ec86820f..e2551eb9d 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/__init__.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/__init__.py @@ -6,11 +6,14 @@ from .preflight import intake_fit_check from .tool_client import ToolResult, ToolSession, ToolSessionError from .agent_env_environment import ( + DEFERRED_CALLS_META_KEY, HIDDEN_BY_DEFAULT_META_KEY, AgentEnvApplication, AgentEnvEnvironment, AgentEnvFastMCPApplication, AgentEnvStarletteApplication, + DeferredCall, + Defers, ForwardedTool, add_data, agent_skill, @@ -114,6 +117,9 @@ "ROLE_META_KEY", "SESSION_META_KEY", "HIDDEN_BY_DEFAULT_META_KEY", + "DEFERRED_CALLS_META_KEY", + "Defers", + "DeferredCall", "ROLE_HEADER", "DEFAULT_ROLE", "EnvironmentCapabilities", diff --git a/packages/agentenv-protocol/src/agentenv_protocol/agent_env_environment.py b/packages/agentenv-protocol/src/agentenv_protocol/agent_env_environment.py index c57a6ad77..9934b03be 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/agent_env_environment.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/agent_env_environment.py @@ -1,6 +1,9 @@ """Server SDK: decorate a handler's methods with @reset_data/@add_data/@get_data (JSON-RPC data plane at /agentenv; each optional, advertised as capabilities.operations), @extension (card-advertised REST routes), and @tool (MCP tools; FastMCP-backed apps only; a parameter annotated ToolContext receives the caller and is never advertised). Mount onto a FastMCP, Starlette, or FastAPI app via a per-framework AgentEnvApplication subclass — or subclass AgentEnvEnvironment, configure its card with @environment_card(...), and serve() it.""" from __future__ import annotations +import contextlib +import contextvars +import dataclasses import datetime import decimal import enum @@ -15,8 +18,8 @@ import types import uuid from abc import ABC, abstractmethod -from typing import (Annotated, Any, Callable, ClassVar, Literal, NamedTuple, Optional, Union, get_args, get_origin, - get_type_hints) +from typing import (Annotated, Any, Callable, ClassVar, Iterator, Literal, NamedTuple, Optional, Union, get_args, + get_origin, get_type_hints) from pydantic import TypeAdapter, ValidationError from pydantic.fields import FieldInfo @@ -39,6 +42,7 @@ _EXT_OP_ATTR = "_aee_ext_op" _TOOL_ATTR = "_aee_tool" _HIDDEN_BY_DEFAULT_ATTR = "_aee_hidden_by_default" +_DEFERS_ATTR = "_aee_defers" _TOOL_OPTIONS_ATTR = "_aee_tool_options" _FORWARDED_ATTR = "_aee_forwarded" _INSTRUCTIONS_ATTR = "_aee_instructions" @@ -49,6 +53,8 @@ #: MCP tools/list ``_meta`` key marking a tool a gateway hides from every role until a tool-access step names it. HIDDEN_BY_DEFAULT_META_KEY = "agentenv.io/hiddenByDefault" +#: MCP tools/call result ``_meta`` key by which a server declares calls on itself for a gateway to make later. +DEFERRED_CALLS_META_KEY = "agentenv.io/deferredCalls" OP_RESET_DATA = "reset_data" OP_ADD_DATA = "add_data" @@ -195,7 +201,8 @@ def _extension_slug(uri: str) -> str: def tool(name: str | None = None, *, description: str | None = None, hidden_by_default: bool = False, - annotations: dict | None = None, structured_output: bool | None = None, meta: dict | None = None) -> Callable: + annotations: dict | None = None, structured_output: bool | None = None, meta: dict | None = None, + defers: Defers | None = None) -> Callable: """Mark a handler method as an MCP tool. At mount the bound method is registered as a real MCP tool on the server app and advertised @@ -224,9 +231,23 @@ def tool(name: str | None = None, *, description: str | None = None, hidden_by_d where it can, True requires one, False lists none; on a fastmcp app it is fastmcp's own inference, off with False. A tool returning ``Annotated[CallToolResult, Model]`` sends its result as is on either, listed with ``Model``'s schema. + + ``defers=Defers(call, report_as, using)`` has each successful reply declare, under ``DEFERRED_CALLS_META_KEY``, the + calls a gateway is to make on this server later. After the tool returns, the SDK calls + ``self.(arguments, result)`` with the call's arguments as a dict and the tool's result: a JSON text reply + parsed to its dict or list, a dict as is, a ``CallToolResult``'s structured content or else its text so parsed, + anything else as it is. It returns a ``DeferredCall``, a list of them, or None for none; each declares a call of + ``call``, reported to the gateway's triggers as a call of ``report_as``. The reply is otherwise what the tool + returns, and an error reply declares nothing. A declaration that fails (``using`` raises or returns something + invalid) is logged and left out, so the reply never breaks. Only the registered tool declares: the method called in + process returns its plain value. ``call`` must be a ``hidden_by_default`` tool and ``report_as`` a tool this + environment serves, by their served names (``{environment_name}`` resolved), and ``using`` a plain method, or the + mount raises. The card lists them under the tool's ``defers``. """ if callable(name): raise TypeError("use @tool(...) with parentheses, not bare @tool") + if defers is not None and not isinstance(defers, Defers): + raise TypeError(f"defers takes a Defers, not a {type(defers).__name__}") def deco(fn: Callable) -> Callable: setattr(fn, _TOOL_ATTR, EnvironmentTool( @@ -236,6 +257,8 @@ def deco(fn: Callable) -> Callable: )) if hidden_by_default: setattr(fn, _HIDDEN_BY_DEFAULT_ATTR, True) + if defers is not None: + setattr(fn, _DEFERS_ATTR, defers) setattr(fn, _TOOL_OPTIONS_ATTR, _ToolOptions(annotations, structured_output, meta)) return fn @@ -263,6 +286,29 @@ def listed(cls, tool: dict, call: Callable[..., Any], *, hidden_by_default: bool call, tool.get("annotations"), tool.get("outputSchema"), hidden_by_default) +@dataclasses.dataclass(frozen=True) +class Defers: + """What a ``@tool(defers=...)`` defers: ``call``, the hidden tool a gateway calls on this server at each declared + call's time, ``report_as``, the tool its triggers see that call as, and ``using``, the name of the environment's + method that builds the calls from each reply (see ``tool``).""" + + call: str + report_as: str + using: str + + +@dataclasses.dataclass(frozen=True) +class DeferredCall: + """One call a ``Defers`` method declares. ``key`` names it on its server, which declaring it again does not + change; ``at`` is when, as an aware datetime, epoch seconds or an RFC 3339 string with an offset, declared as a UTC + instant; ``arguments`` are the ``call`` tool's and ``report_arguments`` the ``report_as`` tool's.""" + + key: str + at: datetime.datetime | int | float | str + arguments: dict = dataclasses.field(default_factory=dict) + report_arguments: dict = dataclasses.field(default_factory=dict) + + class _ResourceMarker(NamedTuple): uri: str name: str | None @@ -323,11 +369,12 @@ def __init__(self, environment_card: EnvironmentCard, handler: Any) -> None: handler, _with_forwarded(_discover_tools(handler, environment_card.name), handler))) if tool_handlers and not self.supports_tools: raise ValueError(f"@tool methods require a FastMCP-backed application; {type(self).__name__} cannot serve MCP tools") + self._defers = _resolved_defers(handler, tool_handlers, environment_card.name) self._resources = _discover_resources(handler) if self._resources and not self.supports_tools: raise ValueError(f"@resource methods require a FastMCP-backed application; {type(self).__name__} cannot " "serve MCP resources") - environment_card = _merge_tools(environment_card, tool_handlers) + environment_card = _merge_defers(_merge_tools(environment_card, tool_handlers), self._defers) self._tool_access = ( ToolAccess(descriptor.name for descriptor, fn in tool_handlers if getattr(fn, _HIDDEN_BY_DEFAULT_ATTR, False)) if self.supports_tools and getattr(handler, "tool_access", False) else None @@ -439,6 +486,8 @@ def _register_tool(self, app: Any, descriptor: EnvironmentTool, fn: Callable) -> elif options.structured_output is False: extra["output_schema"] = None registered = injecting(fn) + if (declares := self._defers.get(descriptor.name)) is not None: + registered = _declaring(registered, declares) if fastmcp and _returns_call_tool_result(fn): registered, schema = _fastmcp_returning(registered) extra["output_schema"] = None if options.structured_output is False else schema @@ -502,7 +551,8 @@ def _check_tool_binding(self, app: Any) -> None: raise RuntimeError("this FastMCP app already carries an AgentEnv tool dispatch; mount one handler per app") self._binding = "dispatch" return - readers = [descriptor.name for descriptor, fn in self._tools if _tool_context_slot(fn)] + readers = [descriptor.name for descriptor, fn in self._tools + if _tool_context_slot(fn) or descriptor.name in self._defers] readers += ["on_tool_call"] if self._hook is not None else [] readers += ["tool_access"] if self._tool_access is not None else [] if readers: @@ -545,7 +595,7 @@ async def call_tool(name: str, arguments: dict, *args: Any, **kwargs: Any) -> An if manager.get_tool(name) is None: return await inner(name, arguments, *args, **kwargs) context = kwargs.get("context", args[0] if args else None) - with bound(context_from_mcp(context, name, arguments)) as tool_context: + with bound(context_from_mcp(context, name, arguments)) as tool_context, _collecting() as declared: try: if access is not None: access.check_call(tool_context) @@ -554,7 +604,9 @@ async def call_tool(name: str, arguments: dict, *args: Any, **kwargs: Any) -> An if answer is not None: _check_call_tool_result(answer) return answer - return await inner(name, arguments, *args, **kwargs) + result = await inner(name, arguments, *args, **kwargs) + # an unconverted result is the tool's raw value, which has nowhere to carry a declaration + return _with_declared(result, declared) if kwargs.get("convert_result") else result except Exception as e: error = _agentenv_error(e) if error is None: @@ -967,7 +1019,8 @@ async def on_list_tools(self, context: Any, call_next: Callable) -> Any: async def on_call_tool(self, context: Any, call_next: Callable) -> Any: message = context.message arguments = dict(getattr(message, "arguments", None) or {}) - with bound(context_from_mcp(context.fastmcp_context, message.name, arguments)) as tool_context: + with (bound(context_from_mcp(context.fastmcp_context, message.name, arguments)) as tool_context, + _collecting() as declared): try: if access is not None: access.check_call(tool_context) @@ -976,7 +1029,7 @@ async def on_call_tool(self, context: Any, call_next: Callable) -> Any: if answer is not None: _check_call_tool_result(answer) return _fastmcp_tool_result(answer) - return await call_next(context) + return _with_declared(await call_next(context), declared) except Exception as e: error = _agentenv_error(e) if error is None: @@ -1726,3 +1779,180 @@ async def _maybe_await(result: Any) -> Any: if inspect.isawaitable(result): return await result return result + + +class _Declares(NamedTuple): + """A served tool's ``Defers`` as its replies declare it: the tool, the served names it defers, the bound method.""" + + tool: str + call: str + report_as: str + using: Callable + + +def _resolved_defers(handler: Any, tool_handlers: list, environment_name: str) -> dict[str, _Declares]: + """Each served tool's ``Defers`` by tool name, its names resolved as tool names are; one naming a tool the + environment does not serve, a ``call`` that is not hidden, or a ``using`` that is not a plain method raises.""" + served = {descriptor.name: fn for descriptor, fn in tool_handlers} + resolved = {} + for name, fn in served.items(): + defers = getattr(fn, _DEFERS_ATTR, None) + if defers is None: + continue + call, report_as = (n.replace(_ENV_NAME_TOKEN, environment_name) for n in (defers.call, defers.report_as)) + if call not in served: + raise ValueError(f"@tool {name!r} defers {call!r}, which is not a tool {environment_name} serves") + if not getattr(served[call], _HIDDEN_BY_DEFAULT_ATTR, False): + raise ValueError(f"@tool {name!r} defers {call!r}, which is not hidden_by_default: a deferred call is " + "plumbing the agent must not see") + if report_as not in served: + raise ValueError(f"@tool {name!r} reports its deferred calls as {report_as!r}, which is not a tool " + f"{environment_name} serves") + using = getattr(handler, defers.using, None) + if not callable(using): + raise ValueError(f"@tool {name!r} builds its deferred calls with {defers.using!r}, which is not a method of " + f"{type(handler).__name__}") + if inspect.iscoroutinefunction(using): + raise ValueError(f"@tool {name!r} builds its deferred calls with {defers.using!r}, a coroutine; it must be " + "a plain method") + resolved[name] = _Declares(name, call, report_as, using) + return resolved + + +def _merge_defers(card: EnvironmentCard, declares: dict[str, _Declares]) -> EnvironmentCard: + """List what each tool defers under its card entry's ``defers``.""" + if not declares: + return card + caps = card.capabilities + tools = [t.model_copy(update={"defers": {"call": d.call, "report_as": d.report_as}}) if (d := declares.get(t.name)) + else t for t in caps.tools or []] + return card.model_copy(update={"capabilities": caps.model_copy(update={"tools": tools})}) + + +def _declaring(fn: Callable, declares: _Declares) -> Callable: + """``fn`` as registered for a tool that defers: a twin of the same name, doc, sync/async nature, signature and + annotations (resolved, since the registry reads them verbatim) that hands each result to ``_declare``.""" + signature, annotations = _reduced_signature(fn, "") + if inspect.iscoroutinefunction(fn): + async def wrapper(*args: Any, **kwargs: Any) -> Any: + result = await fn(*args, **kwargs) + _declare(declares, result) + return result + else: + def wrapper(*args: Any, **kwargs: Any) -> Any: + result = fn(*args, **kwargs) + _declare(declares, result) + return result + functools.update_wrapper(wrapper, fn) + wrapper.__signature__, wrapper.__annotations__ = signature, annotations + return wrapper + + +def _declare(declares: _Declares, result: Any) -> None: + """Collect the calls ``declares.using`` builds from a tool's result for the dispatch to put on its reply. An error + result declares none, and a declaration that fails is logged and left out, so the reply never breaks.""" + collected = _declared.get() + result_type = getattr(sys.modules.get("mcp.types"), "CallToolResult", None) + if collected is None or (result_type is not None and isinstance(result, result_type) and result.isError): + return + try: + built = declares.using(dict(ToolContext.current().arguments), _replied(result)) + entries = [_declared_entry(declares, call) for call in ([] if built is None else + built if isinstance(built, list) else [built])] + except Exception as e: + logger.warning("@tool %r declares no deferred call: %s", declares.tool, e) + return + collected.extend(entries) + + +def _replied(result: Any) -> Any: + """A tool's result as its ``using`` receives it: a JSON text reply parsed to its dict or list, a dict as is, a + ``CallToolResult``'s structured content or else its text so parsed, anything else as it is.""" + if isinstance(result, str): + return _json_container(result, result) + result_type = getattr(sys.modules.get("mcp.types"), "CallToolResult", None) + if result_type is not None and isinstance(result, result_type): + if result.structuredContent is not None: + return result.structuredContent + return _json_container("\n".join(c.text for c in result.content if getattr(c, "type", None) == "text"), result) + return result + + +def _json_container(text: str, otherwise: Any) -> Any: + """``text`` parsed when it is a JSON object or array, else ``otherwise``.""" + try: + parsed = json.loads(text) + except ValueError: + return otherwise + return parsed if isinstance(parsed, (dict, list)) else otherwise + + +def _declared_entry(declares: _Declares, call: Any) -> dict: + """One ``DeferredCall`` as the declaration's contract entry, or the error naming what in it breaks the contract.""" + if not isinstance(call, DeferredCall): + raise TypeError(f"using returned a {type(call).__name__}, not a DeferredCall") + if not isinstance(call.key, str) or not call.key: + raise ValueError(f"a deferred call needs a non-empty string key, not {call.key!r}") + if not isinstance(call.arguments, dict) or not isinstance(call.report_arguments, dict): + raise TypeError(f"deferred call {call.key!r}: arguments and report_arguments must be dicts") + entry = {"key": call.key, "at": _utc_instant(call.at), + "call": {"tool": declares.call, "arguments": call.arguments}, + "report_as": {"tool": declares.report_as, "arguments": call.report_arguments}} + try: + json.dumps(entry) + except (TypeError, ValueError) as e: + raise ValueError(f"deferred call {call.key!r} is not JSON: {e}") from None + return entry + + +def _utc_instant(at: Any) -> str: + """``at`` as the UTC RFC 3339 instant a declaration carries (``...Z``): an aware datetime, epoch seconds, or an RFC + 3339 string with an offset, in the grammar a gateway parses; a naive datetime or a string without one is refused.""" + if isinstance(at, datetime.datetime): + if at.utcoffset() is None: + raise ValueError(f"at {at.isoformat()!r} has no UTC offset") + moment = at + elif isinstance(at, (int, float)) and not isinstance(at, bool): + moment = datetime.datetime.fromtimestamp(at, datetime.timezone.utc) + elif isinstance(at, str): + if not _RFC3339_INSTANT.match(at): + raise ValueError(f"at {at!r} is not an RFC 3339 instant with an offset (YYYY-MM-DDThh:mm:ss[.fff](Z|+hh:mm))") + moment = datetime.datetime.fromisoformat(at[:-1] + "+00:00" if at[-1] in "Zz" else at) + else: + raise TypeError(f"at {at!r} is not a time: give an aware datetime, epoch seconds or an RFC 3339 string") + return moment.astimezone(datetime.timezone.utc).isoformat().replace("+00:00", "Z") + + +# The grammar a gateway's clock parses: fromisoformat alone is looser than RFC 3339. +_RFC3339_INSTANT = re.compile(r"^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})$") + +#: The calls the tool of the current dispatch declared, collected for its reply; None outside a dispatch. +_declared: contextvars.ContextVar[list | None] = contextvars.ContextVar("agentenv_protocol.declared_calls", default=None) + + +@contextlib.contextmanager +def _collecting() -> Iterator[list]: + """Collect the calls the tool of this dispatch declares, in the list it yields.""" + collected: list = [] + token = _declared.set(collected) + try: + yield collected + finally: + _declared.reset(token) + + +def _with_declared(result: Any, declared: list) -> Any: + """A tool's reply with the calls it declared under ``DEFERRED_CALLS_META_KEY``, after any it declared itself and + beside any other ``_meta`` it has. mcp's + FastMCP replies with content and structured content, content alone, or a ``CallToolResult``; fastmcp with its + ``ToolResult``.""" + if not declared: + return result + if isinstance(result, (tuple, list)): + from mcp.types import CallToolResult + content, structured = result if isinstance(result, tuple) else (result, None) + result = CallToolResult(content=list(content), structuredContent=structured) + meta = result.meta or {} + own = meta.get(DEFERRED_CALLS_META_KEY) + calls = [*own, *declared] if isinstance(own, list) else declared + return result.model_copy(update={"meta": {**meta, DEFERRED_CALLS_META_KEY: calls}}) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/types.py b/packages/agentenv-protocol/src/agentenv_protocol/types.py index dff8e0f45..c29eeaf57 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/types.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/types.py @@ -185,6 +185,8 @@ class EnvironmentTool(BaseModel): name: str description: Optional[str] = None inputSchema: Optional[dict] = None + # {"call", "report_as"}: the tools of the same server that the calls its replies declare make and are reported as. + defers: Optional[dict] = None class EnvironmentCapabilities(BaseModel): diff --git a/packages/agentenv-protocol/tests/test_tool_defers.py b/packages/agentenv-protocol/tests/test_tool_defers.py new file mode 100644 index 000000000..e3149a0d6 --- /dev/null +++ b/packages/agentenv-protocol/tests/test_tool_defers.py @@ -0,0 +1,320 @@ +"""@tool(defers=Defers(...)): a tool's successful reply declares, under DEFERRED_CALLS_META_KEY, the deferred calls its +``using`` method builds, on both FastMCPs. The reply is otherwise unchanged, the method called in process returns its +plain value, a declaration that cannot be made leaves the reply as it is, and what a Defers names is checked at mount.""" +from __future__ import annotations + +import json +from datetime import datetime, timedelta, timezone + +import anyio +import httpx +import pytest + +pytest.importorskip("mcp.server.fastmcp") +fastmcp = pytest.importorskip("fastmcp") + +from mcp.shared.memory import create_connected_server_and_client_session # noqa: E402 +from mcp.types import CallToolResult, TextContent # noqa: E402 + +from agentenv_protocol import ( # noqa: E402 + DEFERRED_CALLS_META_KEY, + AgentEnvEnvironment, + DeferredCall, + Defers, + EnvironmentTool, + environment_card, + tool, +) + +AT = "2026-07-06T19:03:00Z" +_MOMENT = datetime(2026, 7, 6, 19, 3, tzinfo=timezone.utc) +_REMINDER = Defers(call="deliver_reminder", report_as="send_notification", using="_delivery") + + +def _reminder(arguments: dict, result) -> DeferredCall | None: + if not result.get("ok"): + return None + return DeferredCall(key=result["reminder_id"], at=result["remind_at"], + arguments={"reminder_id": result["reminder_id"]}, + report_arguments={"event_id": arguments["event_id"]}) + + +@environment_card(name="reminders") +class _Reminders(AgentEnvEnvironment): + def __init__(self, delivery=_reminder) -> None: + self.delivery = delivery + self.seen: list = [] + + @tool(hidden_by_default=True) + def deliver_reminder(self, reminder_id: str) -> str: + return json.dumps({"ok": True, "reminder_id": reminder_id}) + + @tool() + def send_notification(self, event_id: str) -> str: + return json.dumps({"ok": True}) + + @tool(defers=_REMINDER) + def schedule_reminder(self, event_id: str, remind_at: str) -> str: + return json.dumps({"ok": event_id != "none", "reminder_id": f"r-{event_id}", "remind_at": remind_at}) + + @tool(defers=_REMINDER) + async def schedule_result(self, event_id: str) -> CallToolResult: + return CallToolResult(content=[TextContent(type="text", text="scheduled")], + structuredContent={"ok": True, "reminder_id": f"r-{event_id}", "remind_at": AT}, + _meta={"agentenv.io/group": "reminders"}) + + def _delivery(self, arguments: dict, result): + self.seen.append((arguments, result)) + return self.delivery(arguments, result) + + +class _Undeclared(_Reminders): + @tool() + def schedule_reminder(self, event_id: str, remind_at: str) -> str: + return _Reminders.schedule_reminder(self, event_id, remind_at) + + @tool() + async def schedule_result(self, event_id: str) -> CallToolResult: + return await _Reminders.schedule_result(self, event_id) + + +async def _called(env: AgentEnvEnvironment, backend: str, name: str, arguments: dict) -> tuple[list, dict | None, dict]: + """The reply's text blocks, structured content and ``_meta``, through mcp's FastMCP or fastmcp.""" + with anyio.fail_after(30): + if backend == "mcp": + async with create_connected_server_and_client_session(env.create_app()) as session: + result = await session.call_tool(name, arguments) + return [c.text for c in result.content], result.structuredContent, dict(result.meta or {}) + app = fastmcp.FastMCP("reminders") + env.mount(app) + async with fastmcp.Client(app) as client: + result = await client.call_tool(name, arguments) + return [c.text for c in result.content], result.structured_content, dict(result.meta or {}) + + +_BACKENDS = pytest.mark.parametrize("backend", ["mcp", "fastmcp"]) + + +@_BACKENDS +@pytest.mark.asyncio +async def test_a_successful_reply_declares_its_deferred_call_and_is_otherwise_unchanged(backend): + env = _Reminders() + arguments = {"event_id": "e1", "remind_at": "2026-07-06T14:03:00-05:00"} + text, structured, meta = await _called(env, backend, "schedule_reminder", arguments) + plain = await _called(_Undeclared(), backend, "schedule_reminder", arguments) + + assert meta.pop(DEFERRED_CALLS_META_KEY) == [{ + "key": "r-e1", "at": AT, + "call": {"tool": "deliver_reminder", "arguments": {"reminder_id": "r-e1"}}, + "report_as": {"tool": "send_notification", "arguments": {"event_id": "e1"}}}] + assert (text, structured, meta) == plain + assert env.seen == [(arguments, {"ok": True, "reminder_id": "r-e1", "remind_at": arguments["remind_at"]})] + + +@_BACKENDS +@pytest.mark.asyncio +async def test_none_declares_nothing(backend): + text, _structured, meta = await _called(_Reminders(), backend, "schedule_reminder", {"event_id": "none", "remind_at": AT}) + assert DEFERRED_CALLS_META_KEY not in meta and json.loads(text[0])["ok"] is False + + +@_BACKENDS +@pytest.mark.asyncio +async def test_a_list_declares_each_of_its_calls(backend): + def twice(arguments: dict, result) -> list[DeferredCall]: + return [DeferredCall(key=f"{result['reminder_id']}-{n}", at=AT, arguments={"reminder_id": result["reminder_id"]}) + for n in (1, 2)] + + _text, _structured, meta = await _called(_Reminders(twice), backend, "schedule_reminder", {"event_id": "e1", "remind_at": AT}) + assert meta[DEFERRED_CALLS_META_KEY] == [ + {"key": f"r-e1-{n}", "at": AT, "call": {"tool": "deliver_reminder", "arguments": {"reminder_id": "r-e1"}}, + "report_as": {"tool": "send_notification", "arguments": {}}} for n in (1, 2)] + + +@_BACKENDS +@pytest.mark.asyncio +async def test_a_call_tool_result_keeps_its_meta_and_gains_the_declaration(backend): + env = _Reminders() + text, structured, meta = await _called(env, backend, "schedule_result", {"event_id": "e2"}) + plain_text, plain_structured, plain_meta = await _called(_Undeclared(), backend, "schedule_result", {"event_id": "e2"}) + + assert [entry["key"] for entry in meta.pop(DEFERRED_CALLS_META_KEY)] == ["r-e2"] + assert meta == plain_meta and meta["agentenv.io/group"] == "reminders" + assert (text, structured) == (plain_text, plain_structured) == (["scheduled"], {"ok": True, "reminder_id": "r-e2", "remind_at": AT}) + assert env.seen == [({"event_id": "e2"}, structured)] + + +class _SelfDeclared(_Reminders): + @tool(defers=_REMINDER) + async def schedule_result(self, event_id: str) -> CallToolResult: + own = {"key": "own-1", "at": AT, "call": {"tool": "deliver_reminder", "arguments": {"reminder_id": "own-1"}}, + "report_as": {"tool": "send_notification", "arguments": {"event_id": event_id}}} + return CallToolResult(content=[TextContent(type="text", text="scheduled")], + structuredContent={"ok": True, "reminder_id": f"r-{event_id}", "remind_at": AT}, + _meta={DEFERRED_CALLS_META_KEY: [own], "agentenv.io/group": "reminders"}) + + +@_BACKENDS +@pytest.mark.asyncio +async def test_calls_a_call_tool_result_declares_itself_are_kept_before_the_decorators(backend): + _, _, meta = await _called(_SelfDeclared(), backend, "schedule_result", {"event_id": "e3"}) + assert [entry["key"] for entry in meta[DEFERRED_CALLS_META_KEY]] == ["own-1", "r-e3"] + assert meta["agentenv.io/group"] == "reminders" + + +@pytest.mark.parametrize("at, expected", [ + (int(_MOMENT.timestamp()), AT), + (_MOMENT.timestamp() + 0.5, "2026-07-06T19:03:00.500000Z"), + (_MOMENT.astimezone(timezone(timedelta(hours=9))), AT), + ("2026-07-06T14:03:00-05:00", AT), + ("2026-07-06 19:03:00.25z", "2026-07-06T19:03:00.250000Z"), +]) +@pytest.mark.asyncio +async def test_at_is_declared_as_a_utc_instant(at, expected): + env = _Reminders(lambda arguments, result: DeferredCall(key="k", at=at)) + _text, _structured, meta = await _called(env, "mcp", "schedule_reminder", {"event_id": "e1", "remind_at": AT}) + assert meta[DEFERRED_CALLS_META_KEY][0]["at"] == expected + + +def _raises(arguments: dict, result) -> DeferredCall: + raise RuntimeError("the reminder store is down") + + +@_BACKENDS +@pytest.mark.parametrize("delivery, reason", [ + (lambda arguments, result: DeferredCall(key="k", at=datetime(2026, 7, 6, 19, 3)), "has no UTC offset"), + (lambda arguments, result: DeferredCall(key="k", at="2026-07-06T19:03:00"), "not an RFC 3339 instant with an offset"), + (lambda arguments, result: DeferredCall(key="k", at="tomorrow"), "not an RFC 3339 instant with an offset"), + (lambda arguments, result: DeferredCall(key="k", at=True), "not a time"), + (lambda arguments, result: DeferredCall(key="", at=AT), "a non-empty string key"), + (lambda arguments, result: {"key": "k", "at": AT}, "dict, not a DeferredCall"), + (lambda arguments, result: [DeferredCall(key="k", at=AT), "k2"], "str, not a DeferredCall"), + (lambda arguments, result: DeferredCall(key="k", at=AT, arguments={"when": _MOMENT}), "JSON"), + (_raises, "the reminder store is down"), +]) +@pytest.mark.asyncio +async def test_a_declaration_that_cannot_be_made_is_logged_and_the_reply_kept(backend, delivery, reason, caplog): + arguments = {"event_id": "e1", "remind_at": AT} + text, structured, meta = await _called(_Reminders(delivery), backend, "schedule_reminder", arguments) + + assert (text, structured, meta) == await _called(_Undeclared(), backend, "schedule_reminder", arguments) + warnings = [r.getMessage() for r in caplog.records if r.levelname == "WARNING" and "schedule_reminder" in r.getMessage()] + assert len(warnings) == 1 and reason in warnings[0], caplog.text + + +@environment_card(name="replies") +class _Replies(_Reminders): + @tool(defers=_REMINDER) + def as_dict(self, event_id: str) -> dict: + return {"ok": True, "reminder_id": event_id, "remind_at": AT} + + @tool(defers=_REMINDER) + def as_text(self, event_id: str) -> str: + return f"scheduled {event_id}" + + @tool(defers=_REMINDER) + def as_json_list(self, event_id: str) -> str: + return json.dumps([event_id]) + + @tool(defers=_REMINDER) + def as_text_result(self, event_id: str) -> CallToolResult: + return CallToolResult(content=[TextContent(type="text", text=json.dumps({"ok": False}))]) + + @tool(defers=_REMINDER) + def as_error(self, event_id: str) -> CallToolResult: + return CallToolResult(isError=True, content=[TextContent(type="text", text="no such event")]) + + +@pytest.mark.asyncio +async def test_using_gets_the_reply_parsed_when_it_is_json_and_as_it_is_otherwise_and_no_call_for_an_error(): + seen: list = [] + for name in ("as_dict", "as_text", "as_json_list", "as_text_result", "as_error"): + await _called(_Replies(lambda arguments, result: seen.append(result)), "mcp", name, {"event_id": "e3"}) + assert seen == [{"ok": True, "reminder_id": "e3", "remind_at": AT}, "scheduled e3", ["e3"], {"ok": False}] + + +@pytest.mark.asyncio +async def test_the_card_advertises_what_a_tool_defers(): + env = _Reminders() + app = env.create_app() + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app.streamable_http_app()), base_url="http://t") as http: + card = {t["name"]: t for t in (await http.get("/.well-known/agent-env.json")).json()["capabilities"]["tools"]} + assert card["schedule_reminder"]["defers"] == card["schedule_result"]["defers"] == { + "call": "deliver_reminder", "report_as": "send_notification"} + assert card["send_notification"].get("defers") is None and card["deliver_reminder"].get("defers") is None + assert {t.name: t.defers for t in env.mounted_card().capabilities.tools}["schedule_reminder"] == { + "call": "deliver_reminder", "report_as": "send_notification"} + + +def test_the_method_called_in_process_returns_its_plain_value(): + env = _Reminders() + env.create_app() + assert env.schedule_reminder("e1", AT) == json.dumps({"ok": True, "reminder_id": "r-e1", "remind_at": AT}) + assert env.seen == [] + + +@pytest.mark.asyncio +async def test_defers_names_resolve_environment_name_as_tool_names_do(): + @environment_card(name="cal") + class _Prefixed(AgentEnvEnvironment): + @tool(name="{environment_name}_deliver", hidden_by_default=True) + def deliver(self, reminder_id: str) -> str: + return "delivered" + + @tool(name="{environment_name}_schedule", + defers=Defers(call="{environment_name}_deliver", report_as="{environment_name}_schedule", using="_at")) + def schedule(self, event_id: str) -> str: + return "scheduled" + + def _at(self, arguments: dict, result) -> DeferredCall: + return DeferredCall(key=arguments["event_id"], at=AT, arguments={"reminder_id": arguments["event_id"]}) + + _text, _structured, meta = await _called(_Prefixed(), "mcp", "cal_schedule", {"event_id": "e4"}) + assert meta[DEFERRED_CALLS_META_KEY] == [{"key": "e4", "at": AT, + "call": {"tool": "cal_deliver", "arguments": {"reminder_id": "e4"}}, + "report_as": {"tool": "cal_schedule", "arguments": {}}}] + + +@pytest.mark.parametrize("defers, error", [ + (Defers(call="deliver_later", report_as="send_notification", using="_delivery"), + "'schedule_reminder' defers 'deliver_later', which is not a tool reminders serves"), + (Defers(call="send_notification", report_as="send_notification", using="_delivery"), + "'schedule_reminder' defers 'send_notification', which is not hidden_by_default"), + (Defers(call="deliver_reminder", report_as="notify", using="_delivery"), + "'schedule_reminder' reports its deferred calls as 'notify', which is not a tool reminders serves"), + (Defers(call="deliver_reminder", report_as="send_notification", using="_missing"), + "'schedule_reminder' builds its deferred calls with '_missing', which is not a method of _Bad"), + (Defers(call="deliver_reminder", report_as="send_notification", using="label"), + "'schedule_reminder' builds its deferred calls with 'label', which is not a method of _Bad"), + (Defers(call="deliver_reminder", report_as="send_notification", using="_later"), + "'schedule_reminder' builds its deferred calls with '_later', a coroutine; it must be a plain method"), +]) +def test_a_defers_naming_what_the_environment_does_not_serve_is_refused_at_mount(defers, error): + class _Bad(_Reminders): + label = "reminders" + + @tool(defers=defers) + def schedule_reminder(self, event_id: str, remind_at: str) -> str: + return "scheduled" + + async def _later(self, arguments: dict, result) -> None: + return None + + with pytest.raises(ValueError, match=error): + _Bad().create_app() + with pytest.raises(ValueError, match=error): + _Bad().mount(fastmcp.FastMCP("reminders")) + + +def test_a_deferred_call_the_served_tools_leave_out_is_refused_at_mount(): + class _Unserved(_Reminders): + def served_tools(self, tools: list[EnvironmentTool]) -> list[EnvironmentTool]: + return [t for t in tools if t.name != "deliver_reminder"] + + with pytest.raises(ValueError, match="defers 'deliver_reminder', which is not a tool reminders serves"): + _Unserved().create_app() + + +def test_defers_must_be_a_defers(): + with pytest.raises(TypeError, match="defers takes a Defers"): + tool(defers={"call": "deliver_reminder"}) diff --git a/src/agent_env/env/gateway/changes.py b/src/agent_env/env/gateway/changes.py index a3e860a00..17cd4b63f 100644 --- a/src/agent_env/env/gateway/changes.py +++ b/src/agent_env/env/gateway/changes.py @@ -32,6 +32,11 @@ def observe(self, event: dict) -> None: self._add(event.get("changelog_id_before"), event.get("changelog_id_after"), { "kind": "trigger_action", "event_id": event["event_id"], "trigger_id": event.get("trigger_id"), "action_index": event.get("action_index"), "tool": event.get("tool"), "role": event.get("as")}) + elif kind == "deferred_call" and event.get("tool") not in self._unwindowed(): + actor = {"kind": "deferred_call", "event_id": event["event_id"], "key": event.get("key"), + "tool": event.get("tool"), "role": event.get("role")} + for before, after in event.get("changelog_windows", []): # one per attempt: the lock is free between them + self._add(before, after, actor) elif kind == "http_request": self._add(event.get("changelog_id_before"), event.get("changelog_id_after"), { "kind": "request", "event_id": event["event_id"], diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index 35e4d6957..a95920533 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -149,6 +149,17 @@ def sources(names: list[str]) -> str: # A fire is in flight; `queued` also has further provoking calls already waiting to be drained. TRIGGER_IN_FLIGHT_STATUSES = ("firing", "queued") +# Deferred-call status vocabulary, part of the GET /triggers/state contract (each of `deferred_calls`). +DEFERRED_CALL_PENDING = "pending" +DEFERRED_CALL_DONE = "done" +DEFERRED_CALL_FAILED = "failed" + + +def due_deferred_calls(state: dict) -> list[dict]: + """The deferred calls a GET /triggers/state lists as ``due``: reached by the gateway clock and still to make, so + they and the triggers they provoke are under way, and a settle check waits for them.""" + return [call for call in state.get("deferred_calls", []) if call.get("due")] + # What triggers/v1 takes beyond its first release, declared on the card so a client can refuse an older gateway. TRIGGER_NAMED_EXECUTORS = "named_executors" TRIGGER_PROVOKING_ROLES = "provoking_roles" @@ -162,9 +173,12 @@ def sources(names: list[str]) -> str: TRIGGER_WEBSITE_OP = "website_op" # state reports each fire in flight (running, waits) and each executor call in progress (executor_calls). TRIGGER_FIRES_IN_STATE = "fires_in_state" +# a server's deferred calls (AGENT_ENV_DEFERRED_CALLS_META_KEY) are made, reported to the triggers, listed in state (each +# `due` once the clock reaches it and until it is made) and counted in its next_event_at. +TRIGGER_DEFERRED_CALLS = "deferred_calls" TRIGGER_FEATURES = (TRIGGER_NAMED_EXECUTORS, TRIGGER_PROVOKING_ROLES, TRIGGER_ACTION_DELAY, TRIGGER_EXECUTOR_HOURS, TRIGGER_UNLESS, TRIGGER_WEBSITE, TRIGGER_EXECUTOR_HOURS_TIME_ZONE, TRIGGER_NEXT_EVENT_AT, - TRIGGER_NOTIFY, TRIGGER_WEBSITE_OP, TRIGGER_FIRES_IN_STATE) + TRIGGER_NOTIFY, TRIGGER_WEBSITE_OP, TRIGGER_FIRES_IN_STATE, TRIGGER_DEFERRED_CALLS) # The one `source` a /step call may name instead of step_api, with the id of the hook artifact that made it. STEP_SOURCE_POST_TURN_HOOK = "post_turn_hook" @@ -193,6 +207,12 @@ def sources(names: list[str]) -> str: AGENT_ENV_SESSION_META_KEY = "agentenv.io/session" # MCP tools/list `_meta` key marking a tool hidden from every role until a rule names it; "*"-tool rules skip it. AGENT_ENV_HIDDEN_BY_DEFAULT_META_KEY = "agentenv.io/hiddenByDefault" +# MCP tools/call result `_meta` key by which a server declares calls on itself for the gateway to make later: a list of +# {key, at (RFC 3339), call {tool, arguments}, report_as {tool, arguments}}, each made once per server and key when +# the gateway clock reaches `at`, as the declaring call's role, and reported to the triggers as that role's call +# `report_as` (unless a trigger action's own call declared it). The gateway takes it off the result, so no caller sees +# it. agentenv_protocol.DEFERRED_CALLS_META_KEY, mirrored here as the gateway container ships without the protocol. +AGENT_ENV_DEFERRED_CALLS_META_KEY = "agentenv.io/deferredCalls" DEFAULT_ROLE = "default" WILDCARD = "*" TOOL_DISABLE_ACTION = "disable" diff --git a/src/agent_env/env/gateway/deferred_calls.py b/src/agent_env/env/gateway/deferred_calls.py new file mode 100644 index 000000000..7ad7b4e68 --- /dev/null +++ b/src/agent_env/env/gateway/deferred_calls.py @@ -0,0 +1,206 @@ +"""Calls a server's tool result declares (``AGENT_ENV_DEFERRED_CALLS_META_KEY``) for the gateway to make on that server +when its clock gets to their time, as the declaring call's role, each reported to the trigger engine as the call it +stands for, so what a server does later by itself (a scheduled message posted) provokes triggers as a live call would.""" +from __future__ import annotations + +import asyncio +import hashlib +import logging +from collections import deque +from dataclasses import dataclass +from datetime import datetime, timezone +from typing import Any + +from mcp.types import CallToolResult + +from .caller import Caller +from .clock import ClockError, _iso, _parse_rfc3339 +from .constants import AGENT_ENV_DEFERRED_CALLS_META_KEY, DEFERRED_CALL_DONE, DEFERRED_CALL_FAILED, DEFERRED_CALL_PENDING +from .triggers import _ECHO_DIGEST_CHARS, _VIRTUAL_RECHECK_S, _VIRTUAL_RESOLUTION_S, _result_text + +logger = logging.getLogger(__name__) + + +class DeferredCalls: + """The calls servers declared, by server and key. One made stays known, so its server declaring the key again is + ignored; one that failed may be declared afresh.""" + + RETRY_ATTEMPTS = 5 # a call a transport failure stopped is made again, so the tool a server defers is idempotent + RETRY_BACKOFF_S = 1.0 # real seconds before the second attempt, doubled before each later one + ERROR_TEXT_LIMIT = 300 # characters of a failed call's error kept in the log and the trajectory + FINISHED_KEPT = 100 # the latest calls made or failed that state lists; every key made stays known for good + + def __init__(self, gateway): + self._gw = gateway + self._calls: dict[tuple[str, str], _Call] = {} # the calls still to make + self._made: set[tuple[str, str]] = set() + self._finished: deque[tuple[tuple[str, str], _Call]] = deque(maxlen=self.FINISHED_KEPT) + self._tasks: set[asyncio.Task] = set() + self._closed = False + + def take(self, result: CallToolResult, server_url: str, role: str, report: bool = True) -> CallToolResult: + """``result`` without its declaration, which no caller sees, each call it declares scheduled as ``role``'s + unless the result is an error, and reported to the trigger engine once made unless ``report`` is False (the + engine's own calls, which provoke no trigger, declare calls that provoke none either).""" + meta = result.meta + if not meta or AGENT_ENV_DEFERRED_CALLS_META_KEY not in meta: + return result + declared = meta[AGENT_ENV_DEFERRED_CALLS_META_KEY] + rest = {k: v for k, v in meta.items() if k != AGENT_ENV_DEFERRED_CALLS_META_KEY} + result = result.model_copy(update={"meta": rest or None}) + if result.isError: + return result + if not isinstance(declared, list): + logger.warning(f"ignoring the deferred calls declared by {server_url}: {type(declared).__name__}, not a list") + return result + for entry in declared: + self._schedule(entry, server_url, role, report) + return result + + def state(self) -> list[dict]: + """The latest calls finished, then each still to make, for GET /triggers/state. ``due`` marks one still to make + whose time the gateway clock has reached: it, and the triggers it provokes, are under way, so a settle check + waits for it. One not yet due keeps nothing waiting.""" + now = _now(self._gw._clock) + return [{"key": key, "server": server, "at": _iso(call.at), "tool": call.tool, "role": call.role, + "status": call.status, "attempts": call.attempts, + "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 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.""" + upcoming = min((call.at for call in self._calls.values() if call.status == DEFERRED_CALL_PENDING), default=None) + if upcoming is not None and state.get("next_event_at") is not None: + upcoming = min(upcoming, _parse_rfc3339(state["next_event_at"])) + return {**state, **({"next_event_at": _iso(upcoming)} if upcoming is not None else {}), + "deferred_calls": self.state()} + + async def cancel(self) -> None: + """Cancel the calls still pending, and schedule none declared from now on. The gateway's process lifespan calls + it at shutdown before it cancels the scheduled trigger actions, so no call made then sets off a fire that + outlives the child sessions.""" + self._closed = True + tasks = list(self._tasks) + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + self._tasks.clear() + + def _schedule(self, entry: Any, server_url: str, role: str, report: bool) -> None: + if self._closed: + return + try: + key, at, call, report_as = _parse(entry) + except ValueError as e: + logger.warning(f"ignoring a deferred call declared by {server_url}: {e}") + return + if (server_url, key) in self._calls or (server_url, key) in self._made: + return + 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)) + self._tasks.add(task) + task.add_done_callback(self._tasks.discard) + + async def _make(self, key: str, record: _Call, server_url: str) -> None: + """Wait for the call's time and make it, again after a transport failure, each attempt under the tool-call lock + as a live call is, with a changelog window of its own read under that lock, so a write made between attempts is + not the call's; report it to the trigger engine when it went through, then log it. An error result is final, + and so is anything unexpected. A call finished leaves the calls to make for the latest finished, its key kept + for good once made.""" + try: + await self._until(record.at) + result, error, windows = None, None, [] + while result is None and record.attempts < self.RETRY_ATTEMPTS: + if record.attempts: + await asyncio.sleep(self.RETRY_BACKOFF_S * 2 ** (record.attempts - 1)) + record.attempts += 1 + async with self._gw._tool_call_guard(): + before = self._gw._query_changelog_id() + try: + result = await self._gw._call_child_tool(server_url, record.tool, record.arguments, + caller=Caller(role=record.role), report=record.report) + except Exception as e: + error = (str(e) or type(e).__name__)[:self.ERROR_TEXT_LIMIT] + logger.warning(f"deferred call {key!r} ({record.tool}) attempt {record.attempts} failed: {error}") + windows.append([before, self._gw._query_changelog_id()]) + ok = result is not None and not result.isError + text = None if result is None else _result_text(result) + if text is not None and not ok: + error = text[:self.ERROR_TEXT_LIMIT] + report_as = record.report_as + reported = ok and record.report + if reported: # before the status, so no state read sees the call made and its trigger not yet at work + self._gw._fire_triggers(record.role, report_as["tool"], report_as["arguments"], result) + record.status = DEFERRED_CALL_DONE if ok else DEFERRED_CALL_FAILED + await self._gw._log_event({ + "event_type": "deferred_call", "key": key, "at": _iso(record.at), "tool": record.tool, + "report_as": report_as["tool"], "role": record.role, "ok": ok, "reported": reported, + "attempts": record.attempts, **({} if text is None else {"result_sha256": _digest(text)}), + "changelog_id_before": windows[0][0], "changelog_id_after": windows[-1][1], "changelog_windows": windows, + **({} if ok else {"error": error})}) + except Exception: + logger.exception(f"deferred call {key!r} ({record.tool}) failed") + if record.status == DEFERRED_CALL_PENDING: + record.status = DEFERRED_CALL_FAILED + if record.status == DEFERRED_CALL_DONE: + self._made.add((server_url, key)) + self._calls.pop((server_url, key), None) + self._finished.append(((server_url, key), record)) + + async def _until(self, at: datetime) -> None: + """Wait until the gateway clock gets to ``at``: its virtual time while armed, held while frozen and read again + whenever it changes (the trigger engine's wake), and wall UTC while unarmed.""" + clock, engine = self._gw._clock, self._gw._trigger_engine + while True: + left = (at - _now(clock)).total_seconds() + if left < _VIRTUAL_RESOLUTION_S: + return + rate = clock.rate + await engine._nap(min(left / rate, _VIRTUAL_RECHECK_S) if rate else _VIRTUAL_RECHECK_S) + + +def _parse(entry: Any) -> tuple[str, datetime, dict, dict]: + """A declared call's key, time, call and report, or ValueError naming what in it breaks the contract.""" + if not isinstance(entry, dict) or not isinstance(entry.get("key"), str) or not entry["key"]: + raise ValueError(f"an entry must be an object with a non-empty string key, got {type(entry).__name__}") + key = entry["key"] + try: + at = _parse_rfc3339(entry.get("at")) + except ClockError as e: + raise ValueError(f"{key!r}: at: {e}") from None + calls = [] + for name in ("call", "report_as"): + call = entry.get(name) + if not isinstance(call, dict) or not isinstance(call.get("tool"), str) or not call["tool"] \ + or not isinstance(call.get("arguments", {}), dict): + raise ValueError(f"{key!r}: {name} must be an object with a tool name and its arguments") + calls.append({"tool": call["tool"], "arguments": call.get("arguments", {})}) + return key, at, calls[0], calls[1] + + +def _digest(text: str) -> str: + """A result's digest as the trigger engine's internal_tool_call events carry it.""" + return hashlib.sha256(text.encode("utf-8", "replace")).hexdigest()[:_ECHO_DIGEST_CHARS] + + +def _now(clock) -> datetime: + """The gateway clock's time: virtual while armed, wall UTC while not.""" + now = clock.now() + return datetime.now(timezone.utc) if now is None else now + + +@dataclass +class _Call: + """One declared call: when, which tool with what, the call its triggers see, as whom, whether its result is + reported, and how far it got.""" + + at: datetime + tool: str + arguments: dict + report_as: dict + role: str + report: bool + status: str = DEFERRED_CALL_PENDING + attempts: int = 0 diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index ae2af8ed6..7c6b4ba3b 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -83,6 +83,7 @@ from .clock import Clock, ClockError, _iso from .clock_followers import ClockFollowers, parse_wait from .console_session import ConsoleSession, LinkRedaction, without_session_cookie +from .deferred_calls import DeferredCalls from .get_time import GET_TIME_TOOL_NAME, build_get_time_tool from .rest_proxy import ( ROLE_HEADER_BYTES, @@ -261,6 +262,7 @@ def __init__( self._mcp.settings.port = port self._mcp.settings.transport_security.enable_dns_rebinding_protection = False self._trigger_engine = TriggerEngine(self) + self._deferred = DeferredCalls(self) if self.website_urls: @self._mcp.tool(name="list_website_urls", description="List available website URLs that can be browsed.") async def list_website_urls() -> list[str]: @@ -383,7 +385,7 @@ async def triggers_clear(request: Request) -> Response: @self._mcp.custom_route("/triggers/state", methods=["GET"]) async def triggers_state(request: Request) -> Response: - return self._json_response(self._trigger_engine.state(), 200) + return self._json_response(self._deferred.in_state(self._trigger_engine.state()), 200) @self._mcp.custom_route("/clock/set-time", methods=["PUT"]) async def clock_set_time(request: Request) -> Response: @@ -721,7 +723,8 @@ async def _session_lifespan(self, mcp: FastMCP): def _process_lifespan(self, mcp_lifespan): """Once per process (uvicorn's lifespan), outer to the MCP session manager's: at shutdown the MCP sessions end - first, then the driver stops and the scheduled trigger actions are cancelled, then the child sessions close.""" + first, then the driver stops, the deferred calls and then the scheduled trigger actions are cancelled, and the + child sessions close.""" @asynccontextmanager async def lifespan(app): try: @@ -738,6 +741,7 @@ async def lifespan(app): finally: self._sessions.closing = True await self._trigger_engine.stop_driver() + await self._deferred.cancel() await self._trigger_engine.cancel_scheduled() await self._close_child_sessions() @@ -805,8 +809,9 @@ async def filtered_call_tool(name, arguments, context=None, convert_result=False def _fire_triggers(self, role: str, name: str, arguments: dict | None, result: Any) -> tuple[list[asyncio.Task], float | None]: """Feed a completed external tool call to the trigger engine (fail-open). Hooked at every - external boundary (MCP filter + both `/step` handlers); the engine's `_internal_call` reads - bypass these, so internal reads never re-trigger (no recursion). Only watched roles fire.""" + external boundary (MCP filter + both `/step` handlers) and for each deferred call an external call declared, + once made, as the call it stands for; the engine's `_internal_call` reads, and the calls they declare, bypass + these, so internal reads never re-trigger (no recursion). Only watched roles fire.""" try: return self._trigger_engine.on_tool_call(role, name, arguments or {}, result) except Exception: @@ -1230,13 +1235,18 @@ async def _close_child_sessions(self) -> None: await self._sessions.close() async def _call_child_tool(self, server_url: str, tool_name: str, arguments: dict, *, - caller: Caller | None = None) -> CallToolResult: - """Every child tools/call (MCP proxy, /step, trigger engine), with the caller's `_meta` stamp (none for an - unattributed trigger action), on its child's session (see child_sessions). Discovery is not redone on a - reconnect; the registered proxies look their child up by URL.""" + caller: Caller | None = None, report: bool) -> CallToolResult: + """Every child tools/call (MCP proxy, /step, trigger engine, deferred calls), with the caller's `_meta` stamp + (none for an unattributed trigger action), on its child's session (see child_sessions). Discovery is not redone + on a reconnect; the registered proxies look their child up by URL. The deferred calls a result declares are taken + off it here, before anyone sees it, and scheduled as the caller's role, reported to the triggers once made unless + ``report`` is False (the trigger engine's own calls). It has no default: a trigger action's call that left it + out would have the calls it defers provoke triggers again.""" meta = caller.meta() if caller is not None else None - self._drive(caller.role if caller is not None else DEFAULT_ROLE, tool_name) - return await self._sessions.call(server_url, tool_name, arguments, meta, timeout=self.TOOL_CALL_TIMEOUT_S) + role = caller.role if caller is not None else DEFAULT_ROLE + self._drive(role, tool_name) + result = await self._sessions.call(server_url, tool_name, arguments, meta, timeout=self.TOOL_CALL_TIMEOUT_S) + return self._deferred.take(result, server_url, role, report=report) async def _ensure_tools_discovered(self) -> None: """Idempotent discovery over the process's child sessions (startup, MCP session start, /step, /state, triggers).""" @@ -1423,7 +1433,8 @@ async def _step_call_tool(self, body: dict, role: str, source: dict = _STEP_API) async with self._tool_call_guard(): changelog_before = self._query_changelog_id() try: - result = await self._call_child_tool(server_url, tool_name, arguments, caller=Caller(role=role)) + 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 @@ -1648,7 +1659,7 @@ async def proxy(**kwargs) -> CallToolResult: async with self._tool_call_guard(): changelog_before = self._query_changelog_id() try: - result = await self._call_child_tool(server_url, tool_name, kwargs, caller=caller) + result = await self._call_child_tool(server_url, tool_name, kwargs, caller=caller, report=True) except Exception as e: await self._log_failed_call(tool_call_event_id, changelog_before, e) raise diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index 4388ed14f..47f70dc9d 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -1450,7 +1450,8 @@ async def _run_check(self, check: dict, ctx: dict | None = None, role: str | Non async def _internal_call(self, tool_name: str, arguments: dict, role: str | None = None) -> CallToolResult: """A child call stamped as `role` when one is given (a tool action's `as`); the pin otherwise. Gateway-native - tools have no child and no identity, so the role is ignored there.""" + tools have no child and no identity, so the role is ignored there. A call its result defers is made but, as this + call itself, reported to no trigger.""" gw = self._gw await gw._ensure_tools_discovered() server_url = gw._tool_server_urls.get(tool_name) @@ -1464,7 +1465,7 @@ async def _internal_call(self, tool_name: str, arguments: dict, role: str | None text = result if isinstance(result, str) else json.dumps(result, default=str) return CallToolResult(content=[TextContent(type="text", text=text)], isError=False) caller = Caller(role=role) if role is not None else None - return await gw._call_child_tool(server_url, tool_name, arguments, caller=caller) + return await gw._call_child_tool(server_url, tool_name, arguments, caller=caller, report=False) async def _fire(self, tid: str, trig: dict, ctx: dict, since: float, ticket: dict) -> None: """Run the actions for one provoking call, then drain any calls queued while firing (repeat diff --git a/src/agent_env/examples/advance-to-next-event/artifacts/advance-to-next-event/hook.py b/src/agent_env/examples/advance-to-next-event/artifacts/advance-to-next-event/hook.py index 68732517c..e1db8e54f 100644 --- a/src/agent_env/examples/advance-to-next-event/artifacts/advance-to-next-event/hook.py +++ b/src/agent_env/examples/advance-to-next-event/artifacts/advance-to-next-event/hook.py @@ -8,6 +8,7 @@ import time from datetime import datetime, timedelta, timezone +from agent_env.env.gateway.constants import due_deferred_calls from agent_env.task_step.task_steps.notification_delivery import label_time CLOCK = "urn:agentenv:clock/v1" @@ -152,8 +153,9 @@ async def _advance(env, target): async def _settle(turn, envs, timeout): - """Wait until no trigger still fires (bar one waiting for a later time), so what an event set off has landed. - Returns the ids of the envs still firing when ``timeout`` ran out, empty when all settled.""" + """Wait until no trigger still fires (bar one waiting for a later time) and no deferred call the clock has reached + is still to make, so what an event set off has landed. Returns the ids of the envs still firing when ``timeout`` + ran out, empty when all settled.""" deadline = time.monotonic() + timeout waiting = {i for i, env in enumerate(envs) if env.supports(TRIGGERS, "state")} while waiting and time.monotonic() < deadline: @@ -163,7 +165,7 @@ async def _settle(turn, envs, timeout): now = _utc(clock["virtual_time"]) if state.get("next_event_at") is not None and _utc(state["next_event_at"]) <= now: await _advance(env, now) - elif not any(_busy(row, now) for row in state["triggers"]): + elif not any(_busy(row, now) for row in state["triggers"]) and not due_deferred_calls(state): waiting.discard(i) if waiting: turn.heartbeat() diff --git a/src/agent_env/examples/next-env-event/artifacts/next-env-event/hook.py b/src/agent_env/examples/next-env-event/artifacts/next-env-event/hook.py index e581e343b..67fd623d3 100644 --- a/src/agent_env/examples/next-env-event/artifacts/next-env-event/hook.py +++ b/src/agent_env/examples/next-env-event/artifacts/next-env-event/hook.py @@ -5,6 +5,8 @@ import time from datetime import datetime, timedelta, timezone +from agent_env.env.gateway.constants import due_deferred_calls + CLOCK = "urn:agentenv:clock/v1" TRIGGERS = "urn:agentenv:triggers/v1" IN_FLIGHT = ("firing", "queued") @@ -93,7 +95,8 @@ async def _advance(env, target): async def _settle(turn, envs, timeout): - """Wait until no trigger on each env still fires, bar one waiting for later; whether each settled in time.""" + """Wait until no trigger on each env still fires, bar one waiting for later, and no deferred call the env's clock + has reached is still to make; whether each settled in time.""" deadline = time.monotonic() + timeout waiting = set(range(len(envs))) while True: @@ -103,7 +106,7 @@ async def _settle(turn, envs, timeout): now = _utc(clock["virtual_time"]) if state["next_event_at"] is not None and _utc(state["next_event_at"]) <= now: await _advance(env, now) # an event already reached waits for the time check, so run it now - elif not any(_busy(row, now) for row in state["triggers"]): + elif not any(_busy(row, now) for row in state["triggers"]) and not due_deferred_calls(state): waiting.discard(i) if not waiting or time.monotonic() >= deadline: break 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 1797794cd..7bd4fdbf5 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -134,6 +134,7 @@ EXT_STATE_URI, EXT_TRIGGERS_URI, EXT_USER_CHAT_URI, + due_deferred_calls, ) from agent_env.config.model import ModelRole from agent_env.store import DuplicateKeyError, get_config @@ -994,7 +995,8 @@ async def advance(self, target: datetime, reason: str) -> None: f["last_still_at_work"] = stuck async def settle(self) -> list[dict]: - """Wait until the world has settled: no trigger still at work, bar a fire waiting for a later time. A contact's + """Wait until the world has settled: no trigger still at work, bar a fire waiting for a later time, and no + deferred call the clock has reached still to make. A contact's reply (a call to a trigger's executor) counts as in progress until it ends or its time limit passes (plus ``CONTACT_GRACE_SECONDS``); any other work, an event due that an advance to now doesn't set going among it, gets ``settle_timeout_seconds``, from the start or from the last contact call seen. A gateway that reports no @@ -1023,13 +1025,15 @@ async def settle(self) -> list[dict]: + max(c["seconds_left"] for c in live)) busy = [row for row in rows if _busy(row, now)] due = state.get("next_event_at") is not None and _utc(state["next_event_at"]) <= now + calls = [c["key"] for c in due_deferred_calls(state)] limit = min(cap, max(track["contact_until"], track["live_call_seen"] + self.step.settle_timeout_seconds)) - if not due and not busy: + if not due and not busy and not calls: waiting.pop(i) elif mono >= limit: # a due event that won't go, like other work, gets settle_timeout_seconds stuck.append({"env_id": env.env_id, "triggers": [_at_work(row) for row in busy], - **({"due_not_going": state["next_event_at"]} if due else {})}) + **({"due_not_going": state["next_event_at"]} if due else {}), + **({"deferred_calls_due": calls} if calls else {})}) waiting.pop(i) elif due: # an event already due: an advance to now sets it going try: 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 1b07933bf..3f58d60b0 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -31,10 +31,12 @@ from agent_env.config.model import MODEL_PARAMS_RESERVED, ModelRole, resolve_model from agent_env.env.gateway.constants import ( DEFAULT_ROLE, + DEFERRED_CALL_PENDING, EXT_CLOCK_URI, EXT_NOTIFICATIONS_URI, EXT_TRIGGERS_URI, TRIGGER_IN_FLIGHT_STATUSES, + due_deferred_calls, ) from agent_env.store import DuplicateKeyError, get_config from agent_env.store.object_store import ObjectStore @@ -1106,9 +1108,12 @@ async def _capture_env_trigger_state(self, context: TaskStepContext) -> None: @staticmethod def _is_settling(state: dict) -> bool: - """Whether a trigger still has fire work outstanding. + """Whether a trigger still has fire work outstanding, or a deferred call the gateway clock has reached is still + to make (it and the triggers it provokes are under way); one not yet due is not waited for. An unbounded recurrence is excluded: it re-enters ``firing`` every arrival and never settles.""" + if due_deferred_calls(state): + return True for t in state.get("triggers", []): # `pending` too: the queue itself, not a label, so it outlives a status we do not know. if t.get("status") not in TRIGGER_IN_FLIGHT_STATUSES and not t.get("pending"): @@ -1132,10 +1137,13 @@ def _capture_is_final(state: dict) -> Optional[bool]: """Whether the record can still change after this capture; None when not determinable. An older gateway has no ``type``, so an unresolved event-anchored trigger is - indistinguishable from an action trigger — claiming completeness there would be a false signal.""" + indistinguishable from an action trigger — claiming completeness there would be a false signal. + A deferred call still to make will change it too, though settling never waits for one.""" rows = state.get("triggers", []) if any("type" not in t for t in rows): return None + if any(c.get("status") == DEFERRED_CALL_PENDING for c in state.get("deferred_calls", [])): + return False return not any(t.get("status") in TRIGGER_IN_FLIGHT_STATUSES or t.get("pending") or (t["type"] == "time" and t.get("status") == "armed") for t in rows) diff --git a/tst/unit/env/gateway/changes_test.py b/tst/unit/env/gateway/changes_test.py index 5d9616877..9d0e9a30f 100644 --- a/tst/unit/env/gateway/changes_test.py +++ b/tst/unit/env/gateway/changes_test.py @@ -72,6 +72,15 @@ def test_overlapping_calls_both_name_a_row_written_between_them(): ["event_2", "event_1"], ["event_2", "event_1"], ["event_1"]] +def test_a_row_a_deferred_call_wrote_is_attributed_to_it(): + changes = ChangeAttribution() + changes.observe({"event_type": "deferred_call", "event_id": "event_4", "key": "m1", "tool": "chat_deliver", + "role": "alice", "ok": True, "changelog_id_before": 3, "changelog_id_after": 7, + "changelog_windows": [[3, 4], [6, 7]]}) + actor = {"kind": "deferred_call", "event_id": "event_4", "key": "m1", "tool": "chat_deliver", "role": "alice"} + assert changes.actors([4, 5, 7]) == [[actor], [], [actor]] + + def test_calls_without_a_write_window_attribute_nothing(): changes = ChangeAttribution() for event in ( diff --git a/tst/unit/env/gateway/child_outage_socket_test.py b/tst/unit/env/gateway/child_outage_socket_test.py index e12a5eb38..28851dd61 100644 --- a/tst/unit/env/gateway/child_outage_socket_test.py +++ b/tst/unit/env/gateway/child_outage_socket_test.py @@ -73,10 +73,10 @@ async def test_a_child_dying_mid_call_fails_the_call_fast_and_the_next_call_reop gw = Gateway(host="127.0.0.1", port=0, server_name="t", internal_mcp_servers=[InternalMCPServer("svc", url)]) try: await gw._ensure_tools_discovered() - assert _text(await gw._call_child_tool(url, "fast", {})) == "ok" + assert _text(await gw._call_child_tool(url, "fast", {}, report=True)) == "ok" first_session = gw._sessions.current[url] - in_flight = asyncio.create_task(gw._call_child_tool(url, "slow", {})) + in_flight = asyncio.create_task(gw._call_child_tool(url, "slow", {}, report=True)) await asyncio.wait_for(slow_started.wait(), 10) # the child holds the call assert not in_flight.done() @@ -90,7 +90,7 @@ async def test_a_child_dying_mid_call_fails_the_call_fast_and_the_next_call_reop assert url not in gw._sessions.current, "the session was retired" server = await _serve(_child(asyncio.Event()), _bind(port)) # the child is back on the same address - assert _text(await gw._call_child_tool(url, "fast", {})) == "ok", "the next call reopens" + assert _text(await gw._call_child_tool(url, "fast", {}, report=True)) == "ok", "the next call reopens" assert gw._sessions.current[url] is not first_session finally: await gw._close_child_sessions() @@ -116,11 +116,11 @@ async def test_a_call_arriving_while_the_child_is_still_down_waits_for_the_recon await gw._ensure_tools_discovered() await server.shutdown() with pytest.raises(McpError) as info: # the call that finds the child gone retires its session - await asyncio.wait_for(gw._call_child_tool(url, "fast", {}), timeout=10) + await asyncio.wait_for(gw._call_child_tool(url, "fast", {}, report=True), timeout=10) assert info.value.error.code == CONNECTION_CLOSED started = time.monotonic() - during = asyncio.create_task(gw._call_child_tool(url, "fast", {})) # reconnects; refused until the child is back + during = asyncio.create_task(gw._call_child_tool(url, "fast", {}, report=True)) # reconnects; refused until the child is back await asyncio.sleep(1.2) assert not during.done() server = await _serve(_child(asyncio.Event()), _bind(port)) @@ -129,13 +129,13 @@ async def test_a_call_arriving_while_the_child_is_still_down_waits_for_the_recon await server.shutdown() with pytest.raises(McpError): - await asyncio.wait_for(gw._call_child_tool(url, "fast", {}), timeout=10) + await asyncio.wait_for(gw._call_child_tool(url, "fast", {}, report=True), timeout=10) started = time.monotonic() with pytest.raises(RuntimeError, match="could not open a session"): # the child stays down: 4 refused attempts - await asyncio.wait_for(gw._call_child_tool(url, "fast", {}), timeout=20) + await asyncio.wait_for(gw._call_child_tool(url, "fast", {}, report=True), timeout=20) assert time.monotonic() - started < 10 server = await _serve(_child(asyncio.Event()), _bind(port)) - assert _text(await gw._call_child_tool(url, "fast", {})) == "ok" + assert _text(await gw._call_child_tool(url, "fast", {}, report=True)) == "ok" finally: await gw._close_child_sessions() await server.shutdown() @@ -176,10 +176,10 @@ async def test_after_a_child_restarts_a_burst_of_calls_to_it_succeeds_and_anothe b_session = gw._sessions.current[urls["b"]] await servers["a"].shutdown() servers["a"] = await _serve(_counting_child("a", writes["a"]), _bind(ports["a"])) # back, its sessions gone - slow = asyncio.create_task(gw._call_child_tool(urls["b"], "b_slow_place", {"item": "slow"})) + slow = asyncio.create_task(gw._call_child_tool(urls["b"], "b_slow_place", {"item": "slow"}, report=True)) results = await asyncio.gather( - *(gw._call_child_tool(urls["a"], "a_place", {"item": f"a{i}"}) for i in range(20)), - *(gw._call_child_tool(urls["b"], "b_place", {"item": f"b{i}"}) for i in range(10))) + *(gw._call_child_tool(urls["a"], "a_place", {"item": f"a{i}"}, report=True) for i in range(20)), + *(gw._call_child_tool(urls["b"], "b_place", {"item": f"b{i}"}, report=True) for i in range(10))) assert all(not result.isError for result in results) assert not (await slow).isError assert sorted(writes["a"]) == sorted(f"a{i}" for i in range(20)) diff --git a/tst/unit/env/gateway/child_sessions_test.py b/tst/unit/env/gateway/child_sessions_test.py index 8e593e386..5083bcbad 100644 --- a/tst/unit/env/gateway/child_sessions_test.py +++ b/tst/unit/env/gateway/child_sessions_test.py @@ -150,7 +150,7 @@ async def test_a_dead_session_is_reopened_once_and_the_call_retried_without_redi try: await gw._ensure_tools_discovered() first_owner, proxy = _owner(gw), gw._mcp._tool_manager._tools["svc_thing"] - result = await gw._call_child_tool(URL, "svc_thing", {}) + result = await gw._call_child_tool(URL, "svc_thing", {}, report=True) assert not result.isError and session.calls == ["svc_thing", "svc_thing"] assert opener.opened == 2 and first_owner.done() assert _owner(gw) is not first_owner and not _owner(gw).done() @@ -169,11 +169,11 @@ async def test_a_call_lost_in_flight_retires_the_session_but_is_not_retried(): await gw._ensure_child_sessions() first_owner = _owner(gw) with pytest.raises(McpError, match="Connection closed"): - await gw._call_child_tool(URL, "svc_thing", {}) + await gw._call_child_tool(URL, "svc_thing", {}, report=True) assert session.calls == ["svc_thing"] # the child may already have written; a retry could write twice await asyncio.gather(*gw._sessions.retirements) assert first_owner.done() and URL not in gw._sessions.current and opener.opened == 1 - assert not (await gw._call_child_tool(URL, "svc_thing", {})).isError # the next call reopens + assert not (await gw._call_child_tool(URL, "svc_thing", {}, report=True)).isError # the next call reopens assert opener.opened == 2 and session.calls == ["svc_thing", "svc_thing"] finally: await gw._close_child_sessions() @@ -187,7 +187,7 @@ async def test_any_other_error_is_the_caller_s_and_keeps_the_session(): gw = _gateway(opener) try: with pytest.raises(McpError, match="Invalid params"): - await gw._call_child_tool(URL, "svc_thing", {}) + await gw._call_child_tool(URL, "svc_thing", {}, report=True) assert session.calls == ["svc_thing"] and opener.opened == 1 and not _owner(gw).done() finally: await gw._close_child_sessions() @@ -207,7 +207,8 @@ async def call_tool(name, arguments, *args, meta=None, **kwargs): # every call session.call_tool = call_tool try: - results = await asyncio.gather(gw._call_child_tool(URL, "a", {}), gw._call_child_tool(URL, "b", {})) + results = await asyncio.gather(gw._call_child_tool(URL, "a", {}, report=True), + gw._call_child_tool(URL, "b", {}, report=True)) assert all(not r.isError for r in results) and opener.opened == 2 finally: await gw._close_child_sessions() @@ -399,7 +400,7 @@ async def test_shutdown_cancels_scheduled_actions_and_nothing_reopens_the_child_ async def late_action(): # a trigger action still waiting when the process shuts down try: await asyncio.sleep(60) - await gw._call_child_tool(URL, "svc_thing", {}) + await gw._call_child_tool(URL, "svc_thing", {}, report=True) except asyncio.CancelledError: outcome.append("cancelled") raise @@ -464,7 +465,7 @@ async def rejects(name, arguments, *args, meta=None, **kwargs): try: old = await gw._sessions.ensure(URL) opener.session = second - calls = [asyncio.create_task(gw._call_child_tool(URL, f"t{i}", {})) for i in range(5)] + calls = [asyncio.create_task(gw._call_child_tool(URL, f"t{i}", {}, report=True)) for i in range(5)] while len(first.calls) < 5: await asyncio.sleep(0) rejected.set() @@ -500,12 +501,12 @@ async def opener(server, stack, report): internal_mcp_servers=[InternalMCPServer("svc", URL), InternalMCPServer("other", OTHER)]) gw._sessions.open_session = opener # type: ignore[method-assign] try: - in_flight = asyncio.create_task(gw._call_child_tool(OTHER, "other_thing", {})) + in_flight = asyncio.create_task(gw._call_child_tool(OTHER, "other_thing", {}, report=True)) while not slow.calls: await asyncio.sleep(0) other_owner = _owner(gw, OTHER) with pytest.raises(McpError, match="Connection closed"): - await gw._call_child_tool(URL, "svc_thing", {}) + await gw._call_child_tool(URL, "svc_thing", {}, report=True) release.set() assert not (await in_flight).isError await asyncio.gather(*gw._sessions.retirements) @@ -531,7 +532,7 @@ async def held(name, arguments, *args, meta=None, **kwargs): gw = _gateway(opener) try: old = await gw._sessions.ensure(URL) - pending = asyncio.create_task(gw._call_child_tool(URL, "svc_thing", {})) + pending = asyncio.create_task(gw._call_child_tool(URL, "svc_thing", {}, report=True)) while not session.calls: await asyncio.sleep(0) await gw._sessions.replace(old) # as a call the child answered 404 does @@ -563,7 +564,7 @@ async def held(name, arguments, *args, meta=None, **kwargs): opening = None try: old = await gw._sessions.ensure(URL) - pending = asyncio.create_task(gw._call_child_tool(URL, "svc_thing", {})) + pending = asyncio.create_task(gw._call_child_tool(URL, "svc_thing", {}, report=True)) while not session.calls: await asyncio.sleep(0) await gw._sessions.replace(old) diff --git a/tst/unit/env/gateway/deferred_calls_socket_test.py b/tst/unit/env/gateway/deferred_calls_socket_test.py new file mode 100644 index 000000000..a29f6204d --- /dev/null +++ b/tst/unit/env/gateway/deferred_calls_socket_test.py @@ -0,0 +1,219 @@ +"""A deferred call end to end over real loopback sockets: a FastMCP chat server declares a scheduled message in its +result, the agent's MCP client never sees the declaration, the gateway posts the message when its clock gets there +and its trigger engine reacts as to the agent's own post, and a call still pending ends with the gateway. The same +holds for a server built with agentenv_protocol whose tool declares the call in its decorator.""" +from __future__ import annotations + +import asyncio +import json +import socket +import time +from contextlib import asynccontextmanager + +import httpx +import pytest +import uvicorn +from mcp import ClientSession +from mcp.client.streamable_http import streamable_http_client +from mcp.server.fastmcp import FastMCP +from mcp.types import CallToolResult, TextContent +from pytest_socket import enable_socket + +from agent_env.env.gateway import AGENT_ENV_ROLE_HEADER, InternalMCPServer +from agent_env.env.gateway import gateway as gw_mod +from agent_env.env.gateway.gateway import Gateway +from agentenv_protocol import AgentEnvEnvironment, DeferredCall, Defers, environment_card, tool + +DEFERRED = "agentenv.io/deferredCalls" +T0 = "2026-07-06T19: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 + + +def _chat(posted: list[dict], notes: list[str]) -> FastMCP: + app = FastMCP("chat") + scheduled: dict[str, dict] = {} + + @app.tool() + async def chat_schedule(channel_id: str, message: str, post_at: str) -> CallToolResult: + sid = f"Q{len(scheduled) + 1}" + scheduled[sid] = {"channel": channel_id, "text": message} + return CallToolResult( + content=[TextContent(type="text", text=json.dumps({"ok": True, "scheduled_message_id": sid}))], + _meta={DEFERRED: [{"key": sid, "at": post_at, + "call": {"tool": "chat_deliver", "arguments": {"scheduled_message_id": sid}}, + "report_as": {"tool": "chat_send", + "arguments": {"channel_id": channel_id, "message": message}}}]}) + + @app.tool() + async def chat_deliver(scheduled_message_id: str) -> str: + message = scheduled.pop(scheduled_message_id) + posted.append(message) + return json.dumps({"ok": True, "channel": message["channel"], "ts": f"{len(posted)}.000100"}) + + @app.tool() + async def chat_send(channel_id: str, message: str) -> str: + return json.dumps({"ok": True}) + + @app.tool() + async def chat_note(text: str) -> str: + notes.append(text) + return "noted" + + return app + + +async def _serve(app) -> tuple[uvicorn.Server, str]: + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(("127.0.0.1", 0)) + config = uvicorn.Config(app, log_level="critical", access_log=False, timeout_graceful_shutdown=3) + config.load() + server = uvicorn.Server(config) + server.lifespan = config.lifespan_class(config) + await server.startup(sockets=[sock]) + return server, f"http://127.0.0.1:{sock.getsockname()[1]}" + + +@asynccontextmanager +async def _client(url: str, role: str): + async with ( + httpx.AsyncClient(headers={AGENT_ENV_ROLE_HEADER: role}, timeout=httpx.Timeout(10, read=60)) as http, + streamable_http_client(f"{url}/mcp", http_client=http) as (read, write, _), + ClientSession(read, write) as session, + ): + await session.initialize() + yield session + + +async def _until(predicate, seconds: float = 10.0) -> None: + deadline = time.monotonic() + seconds + while not predicate(): + assert time.monotonic() < deadline, "condition not reached" + await asyncio.sleep(0.02) + + +@pytest.mark.asyncio +@pytest.mark.timeout(60) +async def test_a_scheduled_message_is_posted_at_its_time_and_answered_as_the_sender_s_post(tmp_path, monkeypatch): + monkeypatch.setattr(gw_mod, "GATEWAY_TRAJECTORY_FILE", str(tmp_path / "trajectory.jsonl")) + posted: list[dict] = [] + notes: list[str] = [] + child, child_url = await _serve(_chat(posted, notes).streamable_http_app()) + gw = Gateway(host="127.0.0.1", port=0, server_name="t", + internal_mcp_servers=[InternalMCPServer("chat", f"{child_url}/mcp")]) + gateway, 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 + r = await http.post("/triggers/register", json={"watch_roles": ["alice"], "triggers": [ + {"id": "reply", "when": {"type": "action", "tool": "chat_send", "repeat": True}, + "actions": [{"type": "tool", "tool": "chat_note", "as": "bob", + "args": {"text": "bob read '${args.message}' at ${result.ts}"}}]}]}) + assert r.status_code == 200, r.text + + async with _client(url, "alice") as alice: + result = await alice.call_tool("chat_schedule", {"channel_id": "C1", "message": "see you at 3", + "post_at": "2026-07-06T19:03:00Z"}) + assert not result.isError and DEFERRED not in (result.meta or {}) + await alice.call_tool("chat_schedule", {"channel_id": "C1", "message": "tomorrow", + "post_at": "2026-07-07T09:00:00Z"}) + await asyncio.sleep(0.2) + assert posted == [] and notes == [] + + r = await http.put("/clock/advance", json={"virtual_time": "2026-07-06T19:03:00Z"}) + assert r.status_code == 200, r.text + await _until(lambda: notes) + assert posted == [{"channel": "C1", "text": "see you at 3"}] + assert notes == ["bob read 'see you at 3' at 1.000100"] + state = (await http.get("/triggers/state")).json() + assert [(c["key"], c["status"], c["role"]) for c in state["deferred_calls"]] == [ + ("Q1", "done", "alice"), ("Q2", "pending", "alice")] + finally: + await gateway.shutdown() + await child.shutdown() + assert not gw._deferred._tasks and posted == [{"channel": "C1", "text": "see you at 3"}] + + +@environment_card(name="chat") +class _ChatEnv(AgentEnvEnvironment): + """The chat server above built with agentenv_protocol: its scheduling tool declares the delivery in its decorator.""" + + def __init__(self, posted: list[dict], notes: list[str]) -> None: + self.posted, self.notes, self.scheduled = posted, notes, {} + + @tool(defers=Defers(call="chat_deliver", report_as="chat_send", using="_delivery")) + def chat_schedule(self, channel_id: str, message: str, post_at: str) -> str: + sid = f"Q{len(self.scheduled) + 1}" + self.scheduled[sid] = {"channel": channel_id, "text": message} + return json.dumps({"ok": True, "scheduled_message_id": sid, "post_at": post_at}) + + @tool(hidden_by_default=True) + def chat_deliver(self, scheduled_message_id: str) -> str: + message = self.scheduled.pop(scheduled_message_id) + self.posted.append(message) + return json.dumps({"ok": True, "channel": message["channel"], "ts": f"{len(self.posted)}.000100"}) + + @tool() + def chat_send(self, channel_id: str, message: str) -> str: + return json.dumps({"ok": True}) + + @tool() + def chat_note(self, text: str) -> str: + self.notes.append(text) + return "noted" + + def _delivery(self, arguments: dict, result) -> DeferredCall: + return DeferredCall(key=result["scheduled_message_id"], at=result["post_at"], + arguments={"scheduled_message_id": result["scheduled_message_id"]}, + report_arguments={"channel_id": arguments["channel_id"], "message": arguments["message"]}) + + +@pytest.mark.asyncio +@pytest.mark.timeout(60) +async def test_a_call_a_protocol_tool_defers_in_its_decorator_is_made_at_its_time_and_reported(tmp_path, monkeypatch): + monkeypatch.setattr(gw_mod, "GATEWAY_TRAJECTORY_FILE", str(tmp_path / "trajectory.jsonl")) + posted: list[dict] = [] + notes: list[str] = [] + child, child_url = await _serve(_ChatEnv(posted, notes).create_app().streamable_http_app()) + gw = Gateway(host="127.0.0.1", port=0, server_name="t", + internal_mcp_servers=[InternalMCPServer("chat", f"{child_url}/mcp")]) + gateway, 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 + r = await http.post("/triggers/register", json={"watch_roles": ["alice"], "triggers": [ + {"id": "reply", "when": {"type": "action", "tool": "chat_send", "repeat": True}, + "actions": [{"type": "tool", "tool": "chat_note", "as": "bob", + "args": {"text": "bob read '${args.message}' at ${result.ts}"}}]}]}) + assert r.status_code == 200, r.text + + async with _client(url, "alice") as alice: + listed = {t.name for t in (await alice.list_tools()).tools} + result = await alice.call_tool("chat_schedule", {"channel_id": "C1", "message": "see you at 3", + "post_at": "2026-07-06T14:03:00-05:00"}) + assert "chat_deliver" not in listed and "chat_schedule" in listed + assert not result.isError and DEFERRED not in (result.meta or {}) + assert json.loads(result.content[0].text)["scheduled_message_id"] == "Q1" + await asyncio.sleep(0.2) + assert posted == [] and notes == [] + + r = await http.put("/clock/advance", json={"virtual_time": "2026-07-06T19:03:00Z"}) + assert r.status_code == 200, r.text + await _until(lambda: notes) + assert posted == [{"channel": "C1", "text": "see you at 3"}] + assert notes == ["bob read 'see you at 3' at 1.000100"] + state = (await http.get("/triggers/state")).json() + assert [(c["key"], c["at"], c["tool"], c["status"], c["role"]) for c in state["deferred_calls"]] == [ + ("Q1", "2026-07-06T19:03:00Z", "chat_deliver", "done", "alice")] + finally: + await gateway.shutdown() + await child.shutdown() + assert not gw._deferred._tasks diff --git a/tst/unit/env/gateway/deferred_calls_test.py b/tst/unit/env/gateway/deferred_calls_test.py new file mode 100644 index 000000000..ff6aab750 --- /dev/null +++ b/tst/unit/env/gateway/deferred_calls_test.py @@ -0,0 +1,696 @@ +"""A tool result's `_meta` "agentenv.io/deferredCalls" asks the gateway to make a call on the same server later, at a time +on its clock, as the role that made the declaring call, and to report it to the trigger engine as the call it stands +for (a chat server's scheduled message posted at its time, as if its sender had posted it then). The declaration is +taken off the result before any caller sees it, each key is scheduled once, and a pending call ends with the +gateway.""" +from __future__ import annotations + +import asyncio +import itertools +import json +import time +from contextlib import asynccontextmanager +from datetime import datetime, timedelta, timezone +from types import SimpleNamespace + +import agentenv_protocol +import httpx +import pytest +from mcp.types import CallToolResult, TextContent, Tool as MCPTool + +from agent_env.env.gateway import AGENT_ENV_ROLE_HEADER, AGENT_ENV_ROLE_META_KEY, InternalMCPServer +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 _iso +from agent_env.env.gateway.constants import AGENT_ENV_DEFERRED_CALLS_META_KEY, GatewayMode +from agent_env.env.gateway.deferred_calls import DeferredCalls +from agent_env.env.gateway.gateway import Gateway +from agent_env.env.gateway.triggers import _ECHO_DIGEST_CHARS +from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep + +DEFERRED = "agentenv.io/deferredCalls" +URL = "http://chat/mcp" +OTHER_URL = "http://other-chat/mcp" +SEND, SCHEDULE, DELIVER, NOTE = "chat_send", "chat_schedule", "chat_deliver", "chat_note" +T0 = "2026-07-06T19:00:00Z" +AT = "2026-07-06T19:03:00Z" + + +def _at(text: str) -> datetime: + return datetime.fromisoformat(text.replace("Z", "+00:00")) + + +def _declared(key: str = "m1", at: str = AT, channel: str = "C1", text: str = "hi") -> dict: + return {"key": key, "at": at, "call": {"tool": DELIVER, "arguments": {"id": key}}, + "report_as": {"tool": SEND, "arguments": {"channel": channel, "message": text}}} + + +def _json(data, *, is_error: bool = False, meta: dict | None = None) -> CallToolResult: + return CallToolResult(content=[TextContent(type="text", text=json.dumps(data))], isError=is_error, _meta=meta) + + +class _Chat: + """A chat server: chat_schedule declares what `declare` holds (or returns, when it is a function), chat_deliver + answers as `deliveries` say (an exception to raise or a result to return, else a posted message, a changelog row), + and every call is recorded with the gateway clock's time.""" + + def __init__(self): + self.gw: Gateway | None = None + self.calls: list[dict] = [] + self.declare = [] + self.schedule_error = False + self.deliveries: list = [] + self.rows = 0 + + async def list_tools(self): + schema = {"type": "object", "properties": {}} + return SimpleNamespace(tools=[MCPTool(name=n, description="", inputSchema=schema) + for n in (SEND, SCHEDULE, DELIVER, NOTE)]) + + async def call_tool(self, name, arguments, *args, meta=None, **kwargs): + self.calls.append({"tool": name, "args": dict(arguments or {}), "meta": meta, + "virtual": self.gw._clock.now(), "wall": datetime.now(timezone.utc)}) + if name == SCHEDULE: + declared = self.declare() if callable(self.declare) else list(self.declare) + return _json({"ok": True, "scheduled": True}, is_error=self.schedule_error, + meta={DEFERRED: declared, "other": 1}) + if name == DELIVER: + outcome = self.deliveries.pop(0) if self.deliveries else None + if isinstance(outcome, BaseException): + raise outcome + if outcome is not None: + return outcome + self.rows += 1 + return _json({"ok": True, "channel": "C1", "ts": "1783364580.000100", "message": {"text": "hi"}}) + return _json({"ok": True}) + + def made(self, tool: str) -> list[dict]: + return [c for c in self.calls if c["tool"] == tool] + + +@asynccontextmanager +async def _chat(tmp_path, monkeypatch, mode: GatewayMode = GatewayMode.PERFORMANCE): + """A gateway in front of the chat server, inside its process lifespan, whose shutdown unwinds it at the end.""" + monkeypatch.setattr(gw_mod, "GATEWAY_TRAJECTORY_FILE", str(tmp_path / "trajectory.jsonl")) + chat = _Chat() + gw = Gateway(host="127.0.0.1", port=0, server_name="unit", internal_mcp_servers=[InternalMCPServer("chat", URL)], + gateway_mode=mode) + chat.gw = gw + + async def open_session(server, stack, report): + return chat + + @asynccontextmanager + async def no_mcp_sessions(app): + yield + + gw._sessions.open_session = open_session # type: ignore[method-assign] + try: + async with gw._process_lifespan(no_mcp_sessions)(None): + yield gw, chat + finally: + gw._close_trajectory_file() + + +async def _request(gw: Gateway, method: str, path: str, **kw) -> httpx.Response: + transport = httpx.ASGITransport(app=gw._mcp.streamable_http_app()) + async with httpx.AsyncClient(transport=transport, base_url="http://gateway") as client: + response = await client.request(method, path, **kw) + assert response.status_code == 200, response.text + return response + + +async def _mcp_call(gw: Gateway, role: str, tool: str, arguments: dict | None = None): + token = Caller(role=role).bind() + try: + return await gw._mcp._tool_manager.call_tool(tool, arguments or {}) + finally: + Caller.reset(token) + + +async def _schedule(gw: Gateway, chat: _Chat, *declared: dict, role: str = "alice"): + chat.declare = list(declared) + return await _mcp_call(gw, role, SCHEDULE) + + +async def _arm(gw: Gateway, virtual_time: str = T0, rate: float = 0) -> None: + await _request(gw, "PUT", "/clock/set-time", json={"virtual_time": virtual_time, + "virtual_seconds_per_real_second": rate}) + + +async def _deferred(gw: Gateway) -> list[dict]: + return (await _request(gw, "GET", "/triggers/state")).json()["deferred_calls"] + + +async def _until(predicate, seconds: float = 5.0) -> None: + deadline = time.monotonic() + seconds + while not predicate(): + assert time.monotonic() < deadline, "condition not reached" + await asyncio.sleep(0.01) + + +async def _status(gw: Gateway, key: str = "m1") -> str: + return next(c["status"] for c in await _deferred(gw) if c["key"] == key) + + +def _events(tmp_path, kind: str) -> list[dict]: + lines = (tmp_path / "trajectory.jsonl").read_text().splitlines() + return [e for e in map(json.loads, lines) if e.get("event_type") == kind] + + +def _reply_trigger(**when) -> dict: + """An action trigger on the reported tool, its tool action echoing the call's arguments and its result.""" + return {"watch_roles": ["alice"], "triggers": [ + {"id": "reply", "when": {"type": "action", "tool": SEND, "repeat": True, **when}, + "actions": [{"type": "tool", "tool": NOTE, "as": "bob", + "args": {"text": "${args.message}", "channel": "${args.channel}", "ts": "${result.ts}"}}]}]} + + +async def _fired(gw: Gateway) -> int: + state = (await _request(gw, "GET", "/triggers/state")).json() + return next(t["fire_count"] for t in state["triggers"] if t["id"] == "reply") + + +async def _next_event_at(gw: Gateway) -> str | None: + return (await _request(gw, "GET", "/triggers/state")).json()["next_event_at"] + + +def test_the_meta_key_is_the_protocols(): + """The gateway container ships without agentenv_protocol, so its key is a literal; it must stay the protocol's.""" + assert AGENT_ENV_DEFERRED_CALLS_META_KEY == agentenv_protocol.DEFERRED_CALLS_META_KEY == DEFERRED + + +# ---- the declaration on the result ---------------------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_the_declaration_is_taken_off_the_result_on_the_mcp_and_step_paths_and_out_of_the_trajectory( + tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + result = await _schedule(gw, chat, _declared("m1")) + assert result.meta == {"other": 1} + + chat.declare = [_declared("m2")] + step = await _request(gw, "POST", "/step", headers={AGENT_ENV_ROLE_HEADER: "alice"}, + json={"action": "call_tool", "tool_name": SCHEDULE, "arguments": {}}) + assert step.json()["meta"] == {"other": 1} + assert DEFERRED not in step.text + + assert [c["key"] for c in await _deferred(gw)] == ["m1", "m2"] + assert DEFERRED not in (tmp_path / "trajectory.jsonl").read_text() + + +@pytest.mark.asyncio +async def test_a_result_without_the_declaration_is_answered_as_before(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + result = await _mcp_call(gw, "alice", SEND, {"channel": "C1"}) + assert result == _json({"ok": True}) + step = await _request(gw, "POST", "/step", json={"action": "call_tool", "tool_name": SEND, "arguments": {}}) + assert "meta" not in step.json() + assert await _deferred(gw) == [] + + +@pytest.mark.asyncio +async def test_an_error_result_has_the_declaration_taken_off_but_nothing_scheduled(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + chat.schedule_error = True + result = await _schedule(gw, chat, _declared()) + assert result.isError and result.meta == {"other": 1} + assert await _deferred(gw) == [] + + +@pytest.mark.asyncio +async def test_each_key_is_scheduled_once_while_pending_and_once_done(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _schedule(gw, chat, _declared("m1"), _declared("m1", at="2026-07-06T19:01:00Z")) + await _schedule(gw, chat, _declared("m1")) + assert [(c["key"], c["at"]) for c in await _deferred(gw)] == [("m1", AT)] + + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + await _until(lambda: chat.made(DELIVER)) + await _schedule(gw, chat, _declared("m1", at=T0)) + await asyncio.sleep(0.1) + assert len(chat.made(DELIVER)) == 1 + assert [(c["key"], c["status"]) for c in await _deferred(gw)] == [("m1", "done")] + + +@pytest.mark.asyncio +async def test_state_keeps_the_latest_calls_finished_and_every_key_made_stays_known(tmp_path, monkeypatch): + monkeypatch.setattr(DeferredCalls, "FINISHED_KEPT", 2) + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _schedule(gw, chat, *(_declared(f"m{i}", at=T0) for i in range(4))) + await _until(lambda: len(_events(tmp_path, "deferred_call")) == 4) + first, *_, last_but_one, last = [e["key"] for e in _events(tmp_path, "deferred_call")] + await _schedule(gw, chat, _declared(first, at=T0), _declared("m4")) # one no longer listed, and a new one + await asyncio.sleep(0.1) + assert len(chat.made(DELIVER)) == 4 + assert [(c["key"], c["status"]) for c in await _deferred(gw)] == [(last_but_one, "done"), (last, "done"), + ("m4", "pending")] + + +@pytest.mark.asyncio +async def test_the_same_key_from_two_servers_is_two_calls(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _schedule(gw, chat, _declared("m1")) + gw._deferred.take(_json({"ok": True}, meta={DEFERRED: [_declared("m1")]}), OTHER_URL, "alice") + assert [(c["server"], c["key"], c["status"]) for c in await _deferred(gw)] == [ + (URL, "m1", "pending"), (OTHER_URL, "m1", "pending")] + + +@pytest.mark.asyncio +async def test_an_entry_that_breaks_the_contract_is_skipped_and_its_neighbours_scheduled(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + no_offset = {**_declared("bad-at"), "at": "2026-07-06T19:03:00"} + no_call = {k: v for k, v in _declared("no-call").items() if k != "call"} + await _schedule(gw, chat, no_offset, no_call, {"key": ""}, "junk", _declared("ok")) + assert [c["key"] for c in await _deferred(gw)] == ["ok"] + + +# ---- when it is made ------------------------------------------------------------------------------------------------ + +@pytest.mark.asyncio +async def test_it_is_made_once_the_clock_is_advanced_to_its_time_as_the_role_that_declared_it(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _schedule(gw, chat, _declared(), role="alice") + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": "2026-07-06T19:02:59Z"}) + await asyncio.sleep(0.2) + assert chat.made(DELIVER) == [] and await _status(gw) == "pending" + + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + await _until(lambda: chat.made(DELIVER)) + [delivery] = chat.made(DELIVER) + assert delivery["args"] == {"id": "m1"} and delivery["virtual"] >= _at(AT) + assert delivery["meta"] == {AGENT_ENV_ROLE_META_KEY: "alice"} + await _until(lambda: _events(tmp_path, "deferred_call")) + assert [(c["status"], c["attempts"], c["role"], c["tool"]) for c in await _deferred(gw)] == [ + ("done", 1, "alice", DELIVER)] + + +@pytest.mark.asyncio +async def test_a_rearm_past_its_time_makes_it_and_one_before_its_time_holds_it(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _schedule(gw, chat, _declared("soon"), _declared("later", at="2026-07-08T09:00:00Z")) + await _arm(gw, "2026-07-07T00:00:00Z") + await _until(lambda: len(chat.made(DELIVER)) == 1) + assert chat.made(DELIVER)[0]["args"] == {"id": "soon"} + + await _arm(gw, "2026-07-01T00:00:00Z") + await asyncio.sleep(0.2) + assert len(chat.made(DELIVER)) == 1 and await _status(gw, "later") == "pending" + await _arm(gw, "2026-07-08T09:00:00Z") + await _until(lambda: len(chat.made(DELIVER)) == 2) + + +@pytest.mark.asyncio +async def test_a_running_clock_makes_it_at_its_time_holds_it_at_rate_0_and_resumes_with_the_rate( + tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw, rate=3600) # a virtual hour per real second + await _request(gw, "PUT", "/clock/set-rate", json={"virtual_seconds_per_real_second": 0}) + await _schedule(gw, chat, _declared(at=_iso(gw._clock.now() + timedelta(minutes=30)))) + await asyncio.sleep(0.8) + assert chat.made(DELIVER) == [] and await _status(gw) == "pending" + + await _request(gw, "PUT", "/clock/set-rate", json={"virtual_seconds_per_real_second": 3600}) + await _until(lambda: chat.made(DELIVER)) + at = _at((await _deferred(gw))[0]["at"]) + assert at <= chat.made(DELIVER)[0]["virtual"] < at + timedelta(hours=1) # within a real second at 3600x + + +@pytest.mark.asyncio +async def test_clearing_the_clock_moves_a_waiting_call_onto_wall_time(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _schedule(gw, chat, _declared()) # due in three virtual minutes, months before the wall clock + await asyncio.sleep(0.2) + assert chat.made(DELIVER) == [] + await _request(gw, "POST", "/clock/clear") + await _until(lambda: chat.made(DELIVER)) + assert chat.made(DELIVER)[0]["virtual"] is None + + +@pytest.mark.asyncio +async def test_an_unarmed_clock_makes_it_at_its_wall_time(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + soon = datetime.now(timezone.utc) + timedelta(seconds=0.3) + await _schedule(gw, chat, _declared("soon", at=_iso(soon)), + _declared("next-hour", at=_iso(soon + timedelta(hours=1)))) + await _until(lambda: chat.made(DELIVER)) + await asyncio.sleep(0.1) + [delivery] = chat.made(DELIVER) + assert delivery["args"] == {"id": "soon"} and delivery["wall"] >= soon and delivery["virtual"] is None + assert await _status(gw, "next-hour") == "pending" + + +# ---- what the trigger engine sees ------------------------------------------------------------------------------------ + +@pytest.mark.asyncio +async def test_it_is_reported_to_the_trigger_engine_as_the_declared_call_with_the_delivery_result( + tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _request(gw, "POST", "/triggers/register", json=_reply_trigger(where={"args.channel": {"equals": "C1"}})) + await _schedule(gw, chat, _declared("m1", channel="C1", text="see you at 3"), + _declared("m2", channel="C2", at="2026-07-06T19:04:00Z")) + assert chat.made(NOTE) == [] # declaring is not posting + + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": "2026-07-06T19:05:00Z"}) + await _until(lambda: len(chat.made(DELIVER)) == 2 and chat.made(NOTE)) + await asyncio.sleep(0.1) + [note] = chat.made(NOTE) + assert note["args"] == {"text": "see you at 3", "channel": "C1", "ts": "1783364580.000100"} + assert note["meta"] == {AGENT_ENV_ROLE_META_KEY: "bob"} + assert await _fired(gw) == 1 + assert chat.made(SEND) == [] # reported as a send, never made as one + + +@pytest.mark.asyncio +async def test_it_is_reported_as_the_declaring_role_which_a_trigger_s_roles_select(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _request(gw, "POST", "/triggers/register", json=_reply_trigger(roles=["carol"])) + await _schedule(gw, chat, _declared("by-alice"), role="alice") + await _schedule(gw, chat, _declared("by-carol"), role="carol") + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + await _until(lambda: len(chat.made(DELIVER)) == 2 and chat.made(NOTE)) + await asyncio.sleep(0.1) + assert await _fired(gw) == 1 + assert {c["key"]: c["role"] for c in await _deferred(gw)} == {"by-alice": "alice", "by-carol": "carol"} + + +@pytest.mark.asyncio +async def test_a_trigger_tool_action_s_declaration_is_made_as_its_role_and_the_default_without_one( + tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + chat.declare = [_declared("as-dave")] + await gw._trigger_engine._internal_call(SCHEDULE, {}, role="dave") + chat.declare = [_declared("unattributed")] + await gw._trigger_engine._internal_call(SCHEDULE, {}) + assert {c["key"]: c["role"] for c in await _deferred(gw)} == {"as-dave": "dave", "unattributed": "default"} + + +@pytest.mark.asyncio +async def test_a_call_a_trigger_action_declared_is_made_but_provokes_no_trigger(tmp_path, monkeypatch): + """A trigger action's own calls provoke no trigger, nor does a call it defers: a trigger on the agent's sends whose + action schedules a message, with no `as`, would otherwise take that message for the agent's, and so on without + end.""" + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + keys = itertools.count() + chat.declare = lambda: [_declared(f"k{next(keys)}", at=T0)] # each a new key, due at once + await _request(gw, "POST", "/triggers/register", json={"watch_roles": ["default"], "triggers": [ + {"id": "echo", "when": {"type": "action", "tool": SEND, "repeat": True}, + "actions": [{"type": "tool", "tool": SCHEDULE, "args": {}}]}]}) + await _mcp_call(gw, "default", SEND, {"channel": "C1"}) + await _until(lambda: _events(tmp_path, "deferred_call")) + await asyncio.sleep(0.3) + assert (len(chat.made(SCHEDULE)), len(chat.made(DELIVER))) == (1, 1) + assert [(c["key"], c["status"]) for c in await _deferred(gw)] == [("k0", "done")] + [event] = _events(tmp_path, "deferred_call") + assert event["ok"] is True and event["reported"] is False + + +@pytest.mark.asyncio +async def test_an_error_delivery_is_final_logged_and_not_reported(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _request(gw, "POST", "/triggers/register", json=_reply_trigger()) + chat.deliveries = [_json({"ok": False, "error": "message_not_found"}, is_error=True)] + await _schedule(gw, chat, _declared()) + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + await _until(lambda: chat.made(DELIVER)) + await asyncio.sleep(0.2) + assert len(chat.made(DELIVER)) == 1 and chat.made(NOTE) == [] and await _fired(gw) == 0 + assert [(c["status"], c["attempts"]) for c in await _deferred(gw)] == [("failed", 1)] + [event] = _events(tmp_path, "deferred_call") + assert (event["key"], event["tool"], event["role"], event["ok"]) == ("m1", DELIVER, "alice", False) + assert "message_not_found" in event["error"] + + await _schedule(gw, chat, _declared(at="2026-07-06T19:10:00Z")) # a failed key may be declared afresh + assert [(c["status"], c["at"]) for c in await _deferred(gw)] == [("failed", AT), + ("pending", "2026-07-06T19:10:00Z")] + + +@pytest.mark.asyncio +async def test_a_transport_failure_is_retried_and_the_delivery_reported_once(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + monkeypatch.setattr(gw._deferred, "RETRY_BACKOFF_S", 0.01) + await _arm(gw) + await _request(gw, "POST", "/triggers/register", json=_reply_trigger()) + chat.deliveries = [ConnectionError("chat restarting"), RuntimeError("socket closed")] + await _schedule(gw, chat, _declared()) + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + await _until(lambda: chat.made(NOTE)) + await asyncio.sleep(0.1) + assert len(chat.made(DELIVER)) == 3 and len(chat.made(NOTE)) == 1 and await _fired(gw) == 1 + assert [(c["status"], c["attempts"]) for c in await _deferred(gw)] == [("done", 3)] + + +@pytest.mark.asyncio +async def test_retries_are_bounded_and_a_call_that_never_goes_through_fails(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + monkeypatch.setattr(gw._deferred, "RETRY_BACKOFF_S", 0.01) + await _arm(gw) + chat.deliveries = [ConnectionError("down")] * 50 + await _schedule(gw, chat, _declared()) + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + await _until(lambda: _events(tmp_path, "deferred_call")) + assert len(chat.made(DELIVER)) == gw._deferred.RETRY_ATTEMPTS > 1 + assert [(c["status"], c["attempts"]) for c in await _deferred(gw)] == [("failed", gw._deferred.RETRY_ATTEMPTS)] + assert _events(tmp_path, "deferred_call")[0]["ok"] is False + + +# ---- state, trajectory, shutdown ------------------------------------------------------------------------------------ + +@pytest.mark.asyncio +async def test_state_lists_each_deferred_call_and_prompt_agent_does_not_wait_for_one_not_yet_due(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _schedule(gw, chat, _declared()) + state = (await _request(gw, "GET", "/triggers/state")).json() + assert state["deferred_calls"] == [ + {"key": "m1", "server": URL, "at": AT, "tool": DELIVER, "role": "alice", "status": "pending", + "attempts": 0, "due": False}] + assert state["triggers"] == [] and state["next_event_at"] == AT + assert PromptAgentTaskStep._is_settling(state) is False + + +@pytest.mark.asyncio +async def test_a_call_the_clock_has_reached_is_due_and_prompt_agent_waits_for_it_until_it_is_made( + tmp_path, monkeypatch): + """The gateway says which calls its clock has reached and are still to make, so a client needs no clock of its own + to wait for them.""" + async with _chat(tmp_path, monkeypatch) as (gw, chat): + released = asyncio.Event() + call_tool = chat.call_tool + + async def held_delivery(name, arguments, *args, **kwargs): + if name == DELIVER: + await released.wait() + return await call_tool(name, arguments, *args, **kwargs) + + chat.call_tool = held_delivery + await _arm(gw) + await _schedule(gw, chat, _declared()) + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + state = (await _request(gw, "GET", "/triggers/state")).json() + assert [(c["status"], c["due"]) for c in state["deferred_calls"]] == [("pending", True)] + assert PromptAgentTaskStep._is_settling(state) is True + + released.set() + await _until(lambda: _events(tmp_path, "deferred_call")) + state = (await _request(gw, "GET", "/triggers/state")).json() + assert [(c["status"], c["due"]) for c in state["deferred_calls"]] == [("done", False)] + assert PromptAgentTaskStep._is_settling(state) is False + + +@pytest.mark.asyncio +async def test_next_event_at_counts_the_earliest_call_still_to_make(tmp_path, monkeypatch): + """A harness jumping the clock to the next event stops at a deferred call's time rather than past it; once made, the + call counts no more.""" + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _request(gw, "POST", "/triggers/register", json={"triggers": [ + {"id": "later", "when": {"type": "time", "at": "2026-07-06T19:10:00Z"}, + "actions": [{"type": "tool", "tool": NOTE, "args": {}}]}]}) + assert await _next_event_at(gw) == "2026-07-06T19:10:00Z" + await _schedule(gw, chat, _declared("m1"), _declared("m2", at="2026-07-06T19:20:00Z")) + assert await _next_event_at(gw) == AT + + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + await _until(lambda: _events(tmp_path, "deferred_call")) + assert await _next_event_at(gw) == "2026-07-06T19:10:00Z" + + +@pytest.mark.asyncio +async def test_no_state_reads_settled_between_an_advance_that_makes_a_call_due_and_the_fire_it_provokes( + tmp_path, monkeypatch): + """From the advance until the reply has fired, every state read is still settling: the call due, then the trigger it + provoked at work, however long the call's trajectory event takes to write.""" + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _request(gw, "POST", "/triggers/register", json=_reply_trigger()) + await _schedule(gw, chat, _declared()) + log_event = gw._log_event + + async def slow_log(event): + if event.get("event_type") == "deferred_call": + await asyncio.sleep(0.2) + return await log_event(event) + + monkeypatch.setattr(gw, "_log_event", slow_log) + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + deadline = time.monotonic() + 5 + while True: + state = (await _request(gw, "GET", "/triggers/state")).json() + [reply] = state["triggers"] + if reply["fire_count"]: + break + assert PromptAgentTaskStep._is_settling(state), state + assert time.monotonic() < deadline, "the reply never fired" + await asyncio.sleep(0.005) + + +@pytest.mark.asyncio +async def test_a_call_on_a_consistent_gateway_waits_its_turn_and_its_write_is_attributed_to_it(tmp_path, monkeypatch): + """Like a live call it takes the tool-call lock and logs its changelog window, so changes/v1 names it, not whichever + call ran alongside.""" + async with _chat(tmp_path, monkeypatch, mode=GatewayMode.CONSISTENT) as (gw, chat): + monkeypatch.setattr(gw, "_query_changelog_id", lambda: chat.rows) + await _arm(gw) + await _schedule(gw, chat, _declared()) + await gw._tool_call_lock.acquire() # a live call under way + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + await asyncio.sleep(0.2) + assert chat.made(DELIVER) == [] + gw._tool_call_lock.release() + await _until(lambda: _events(tmp_path, "deferred_call")) + [event] = _events(tmp_path, "deferred_call") + assert (event["changelog_id_before"], event["changelog_id_after"]) == (0, 1) + assert gw._changes.actors([1]) == [[{"kind": "deferred_call", "event_id": event["event_id"], "key": "m1", + "tool": DELIVER, "role": "alice"}]] + + +def _writing(chat: _Chat, *, note: bool = False, failing_deliveries: int = 0) -> None: + """Make chat_note write a row when ``note``, and the first ``failing_deliveries`` deliveries write one and then lose + their transport.""" + real = chat.call_tool + failing = itertools.repeat(None, failing_deliveries) + + async def call_tool(name, arguments, *args, **kwargs): + if name == NOTE and note: + chat.rows += 1 + if name == DELIVER and next(failing, True) is None: + chat.calls.append({"tool": name, "args": dict(arguments or {})}) + chat.rows += 1 + raise ConnectionError("connection lost after the write") + return await real(name, arguments, *args, **kwargs) + + chat.call_tool = call_tool + + +@pytest.mark.asyncio +async def test_a_write_another_role_makes_between_attempts_is_not_credited_to_the_deferred_call(tmp_path, monkeypatch): + """Each attempt has a window of its own, read under its lock: the lock is free during a retry's backoff, so a window + from the first attempt to the last would hold a live call's write made then.""" + async with _chat(tmp_path, monkeypatch, mode=GatewayMode.CONSISTENT) as (gw, chat): + monkeypatch.setattr(gw, "_query_changelog_id", lambda: chat.rows) + monkeypatch.setattr(gw._deferred, "RETRY_BACKOFF_S", 0.5) + _writing(chat, note=True) + chat.deliveries = [ConnectionError("chat restarting")] + await _arm(gw) + await _schedule(gw, chat, _declared()) + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + await _until(lambda: chat.made(DELIVER)) + await _mcp_call(gw, "bob", NOTE) + assert len(chat.made(DELIVER)) == 1 and chat.rows == 1 + await _until(lambda: _events(tmp_path, "deferred_call")) + [event] = _events(tmp_path, "deferred_call") + assert event["changelog_windows"] == [[0, 0], [1, 2]] and event["attempts"] == 2 + actors = gw._changes.actors([1, 2]) + assert [[(a["kind"], a["role"]) for a in row] for row in actors] == [[("tool_call", "bob")], + [("deferred_call", "alice")]] + + +@pytest.mark.asyncio +async def test_a_write_by_an_attempt_that_then_lost_its_transport_is_credited_to_the_deferred_call(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch, mode=GatewayMode.CONSISTENT) as (gw, chat): + monkeypatch.setattr(gw, "_query_changelog_id", lambda: chat.rows) + monkeypatch.setattr(gw._deferred, "RETRY_BACKOFF_S", 0.01) + _writing(chat, failing_deliveries=1) + await _arm(gw) + await _schedule(gw, chat, _declared()) + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + await _until(lambda: _events(tmp_path, "deferred_call")) + [event] = _events(tmp_path, "deferred_call") + assert event["changelog_windows"] == [[0, 1], [1, 2]] and event["ok"] is True + credited = {"kind": "deferred_call", "event_id": event["event_id"], "key": "m1", "tool": DELIVER, "role": "alice"} + assert gw._changes.actors([1, 2]) == [[credited], [credited]] + + +@pytest.mark.asyncio +async def test_the_trajectory_records_each_deferred_call_on_both_clocks(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _schedule(gw, chat, _declared()) + await _request(gw, "PUT", "/clock/advance", json={"virtual_time": AT}) + await _until(lambda: _events(tmp_path, "deferred_call")) + [event] = _events(tmp_path, "deferred_call") + assert (event["key"], event["tool"], event["role"], event["ok"]) == ("m1", DELIVER, "alice", True) + assert (event["at"], event["report_as"], event["reported"]) == (AT, SEND, True) + assert len(event["result_sha256"]) == _ECHO_DIGEST_CHARS + assert event["virtual_time"] == AT and event["timestamp_utc"] + + +@pytest.mark.asyncio +async def test_an_unexpected_error_leaves_the_call_failed_not_pending(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + async def broken(at): + raise RuntimeError("clock gone") + + monkeypatch.setattr(gw._deferred, "_until", broken) + await _schedule(gw, chat, _declared()) + await _until(lambda: not gw._deferred._tasks) + assert await _status(gw) == "failed" and chat.made(DELIVER) == [] + + +@pytest.mark.asyncio +async def test_a_pending_call_is_cancelled_when_the_gateway_shuts_down(tmp_path, monkeypatch): + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _schedule(gw, chat, _declared()) + tasks = set(gw._deferred._tasks) + assert len(tasks) == 1 + assert all(task.cancelled() for task in tasks) and not gw._deferred._tasks + gw._clock.advance("2026-07-07T00:00:00Z") + gw._trigger_engine.clock_changed() + await asyncio.sleep(0.1) + assert chat.made(DELIVER) == [] + + +@pytest.mark.asyncio +async def test_shutdown_ends_the_deferred_calls_before_the_trigger_actions_and_schedules_none_after( + tmp_path, monkeypatch): + """No call made at shutdown can set off a trigger fire the gateway has stopped cancelling, and none a trigger action + declares as it is cancelled is left waiting.""" + seen = {} + async with _chat(tmp_path, monkeypatch) as (gw, chat): + await _arm(gw) + await _schedule(gw, chat, _declared()) + cancel_scheduled = gw._trigger_engine.cancel_scheduled + + async def cancelling_trigger_actions(): + seen["deferred_left"] = len(gw._deferred._tasks) + gw._deferred.take(_json({"ok": True}, meta={DEFERRED: [_declared("late")]}), URL, "alice") + await cancel_scheduled() + + monkeypatch.setattr(gw._trigger_engine, "cancel_scheduled", cancelling_trigger_actions) + assert seen["deferred_left"] == 0 and not gw._deferred._tasks + assert [c["key"] for c in gw._deferred.state()] == ["m1"] diff --git a/tst/unit/env/gateway/next_event_test.py b/tst/unit/env/gateway/next_event_test.py index 7391daae0..f4f4ecfbd 100644 --- a/tst/unit/env/gateway/next_event_test.py +++ b/tst/unit/env/gateway/next_event_test.py @@ -266,7 +266,7 @@ def gateway(tmp_path, monkeypatch) -> Gateway: gw._clock = Clock(now_fn=FakeNow()) gw._tool_server_urls = {"send_email": "http://svc/mcp"} - async def call_child_tool(server_url, tool_name, arguments, *, caller=None): + async def call_child_tool(server_url, tool_name, arguments, *, caller=None, report): return _result() gw._call_child_tool = call_child_tool diff --git a/tst/unit/env/gateway/triggers_test.py b/tst/unit/env/gateway/triggers_test.py index 161fc952e..282200b74 100644 --- a/tst/unit/env/gateway/triggers_test.py +++ b/tst/unit/env/gateway/triggers_test.py @@ -1340,7 +1340,7 @@ def _step_gateway(): internal_mcp_servers=[], rest_proxy_urls={}) gw._tool_server_urls = {"gdocs_create_document": "http://svc/mcp"} - async def _fake_call_child_tool(server_url, tool_name, arguments, *, caller=None): + async def _fake_call_child_tool(server_url, tool_name, arguments, *, caller=None, report): return _result() gw._call_child_tool = _fake_call_child_tool # type: ignore[assignment] diff --git a/tst/unit/task_step/test_advance_to_next_event_hook.py b/tst/unit/task_step/test_advance_to_next_event_hook.py index 73192431c..71c5265f4 100644 --- a/tst/unit/task_step/test_advance_to_next_event_hook.py +++ b/tst/unit/task_step/test_advance_to_next_event_hook.py @@ -6,6 +6,7 @@ import asyncio import importlib.util from pathlib import Path +from types import SimpleNamespace import httpx import pytest @@ -45,7 +46,7 @@ def gateway(tmp_path, monkeypatch): gw._tool_server_urls = {"items_add_item": "http://items/mcp"} gw.calls = [] - async def call_child_tool(server_url, tool_name, arguments, *, caller=None): + async def call_child_tool(server_url, tool_name, arguments, *, caller=None, report): gw.calls.append((arguments["item"], gw._clock.read()["virtual_time"])) return CallToolResult(content=[TextContent(type="text", text="ok")], isError=False) @@ -278,6 +279,17 @@ async def invoke(self, extension, method, args=None): return {"armed": False} +@pytest.mark.asyncio +async def test_settling_waits_for_a_deferred_call_the_gateway_says_is_due_and_not_for_one_still_to_come(hook): + """A running clock may reach a call's time between the hook's clock read and its state read, so the gateway's + ``due``, not the hook's reading of the time, says the call is under way.""" + turn = SimpleNamespace(heartbeat=lambda: None) + due = _StateEnv(hook, due_reads=2) + assert await hook._settle(turn, [due], 5) == [] and due.reads == 3 + later = _StateEnv(hook, due_reads=0) + assert await hook._settle(turn, [later], 5) == [] and later.reads == 1 + + @pytest.mark.asyncio async def test_an_env_whose_clock_was_never_armed_is_left_out(hook, gateway): armed = _turn(hook, _context()).envs[0] @@ -289,3 +301,26 @@ async def test_an_env_whose_clock_was_never_armed_is_left_out(hook, gateway): def test_unknown_params_are_refused(hook): with pytest.raises(ValueError, match="takes"): hook._params({"nudge": "x"}) + + +class _StateEnv: + """An env whose clock reads 09:00:00 while its gateway, a moment on, lists a deferred call at 09:00:01: due and still + to make for the first ``due_reads`` reads of its triggers state, made after; never due when ``due_reads`` is 0.""" + + env_id = "items" + + def __init__(self, hook, due_reads: int): + self.hook, self.due_reads, self.reads = hook, due_reads, 0 + + def supports(self, uri, op): + return True + + async def invoke(self, uri, op, args=None): + assert op == "state", op + if uri == self.hook.CLOCK: + return {"armed": True, "virtual_time": "2026-03-03T09:00:00Z"} + self.reads += 1 + due = self.reads <= self.due_reads + made = self.due_reads and not due + return {"triggers": [], "next_event_at": None if made else "2026-03-03T09:00:01Z", "deferred_calls": [ + {"key": "m1", "at": "2026-03-03T09:00:01Z", "status": "done" if made else "pending", "due": due}]} diff --git a/tst/unit/task_step/test_always_on_settle.py b/tst/unit/task_step/test_always_on_settle.py index 9afe68419..b8a0ca861 100644 --- a/tst/unit/task_step/test_always_on_settle.py +++ b/tst/unit/task_step/test_always_on_settle.py @@ -4,6 +4,7 @@ from __future__ import annotations +import asyncio import random from datetime import timedelta @@ -175,6 +176,24 @@ def texts_a_friend(n, texts, rig): assert trigger["waits"] == [{"resumes_at": "2026-11-09T14:30:58.882035Z"}] +@pytest.mark.asyncio +async def test_a_deferred_call_the_clock_has_reached_is_waited_for_and_one_that_never_goes_gets_the_settle_timeout( + monkeypatch, tmp_path): + """The gateway's ``due`` says a call is under way, however the step's own read of the clock compares with its + time.""" + rig = Rig(monkeypatch, tmp_path) + await rig.arm() + call = {"key": "m1", "server": "http://chat/mcp", "at": rig.now(), "tool": "chat_deliver", "role": "default", + "status": "pending", "attempts": 1, "due": True} + monkeypatch.setattr(rig.gw._deferred, "state", lambda: [call]) # due, never made + ctx = await asyncio.wait_for(rig.run(rig.step(settle_timeout_seconds=0.2)), 10) + + [timeout] = rig.events(ctx, "settle_timeout") + [env] = timeout["still_at_work"] + assert env["deferred_calls_due"] == ["m1"] and "due_not_going" not in env + assert 0.2 <= timeout["settle"]["seconds"] < 10 # this step's 0.2 s timeout, not the 300 s default + + def test_the_contact_setting_survives_a_round_trip_and_the_step_sets_no_contact_time_limit(): step = ao.AlwaysOnTaskStep("week", None, user_sim="linda", prompt_id="p", agent_name="a", contact_replies_in_parallel=False) diff --git a/tst/unit/task_step/test_next_env_event_hook.py b/tst/unit/task_step/test_next_env_event_hook.py index fee8fa400..32e363c70 100644 --- a/tst/unit/task_step/test_next_env_event_hook.py +++ b/tst/unit/task_step/test_next_env_event_hook.py @@ -5,6 +5,7 @@ import asyncio import importlib.util from pathlib import Path +from types import SimpleNamespace import httpx import pytest @@ -48,7 +49,7 @@ def gateway(tmp_path, monkeypatch): gw._tool_server_urls = {"items_add_item": "http://items/mcp"} gw.calls = [] - async def call_child_tool(server_url, tool_name, arguments, *, caller=None): + async def call_child_tool(server_url, tool_name, arguments, *, caller=None, report): gw.calls.append((arguments["item"], gw._clock.read()["virtual_time"])) return CallToolResult(content=[TextContent(type="text", text="ok")], isError=False) @@ -148,9 +149,9 @@ async def test_a_recurring_trigger_whose_action_outlasts_its_interval_still_move async def test_a_fire_the_agents_turn_set_off_lands_before_the_clock_jumps(hook, gateway, monkeypatch): real = gateway._call_child_tool - async def slow(server_url, tool_name, arguments, *, caller=None): + async def slow(server_url, tool_name, arguments, *, caller=None, report): await asyncio.sleep(0.3) - return await real(server_url, tool_name, arguments, caller=caller) + return await real(server_url, tool_name, arguments, caller=caller, report=report) gateway._call_child_tool = slow _register(gateway, {"id": "ack", "when": {"type": "action", "tool": "send_email"}, "actions": _add("ack")}, @@ -163,6 +164,34 @@ async def slow(server_url, tool_name, arguments, *, caller=None): assert gateway.calls == [("ack", MONDAY), ("tue", "2026-03-03T09:00:00Z")] +@pytest.mark.asyncio +async def test_a_call_a_server_deferred_gets_a_wake_at_its_time_and_the_reply_it_provokes_lands_first(hook, gateway): + """A message an agent scheduled is an env event: the clock jumps to its time, not past it, and the agent wakes once + the trigger its posting set off has run.""" + _register(gateway, {"id": "ack", "when": {"type": "action", "tool": "items_post"}, "actions": _add("ack")}, + {"id": "wed", "when": {"type": "time", "at": "2026-03-04T09:00:00Z"}, "actions": _add("wed")}) + gateway._deferred.take(CallToolResult(content=[], isError=False, _meta={"agentenv.io/deferredCalls": [ + {"key": "m1", "at": "2026-03-03T09:00:00Z", "call": {"tool": "items_add_item", "arguments": {"item": "posted"}}, + "report_as": {"tool": "items_post", "arguments": {}}}]}), "http://items/mcp", "default") + + decisions = await _turns(hook, _context()) + + assert decisions == [_nudge("2026-03-03T09:00:00Z"), _nudge("2026-03-04T09:00:00Z"), {"end": "no_pending_events"}] + assert gateway.calls == [("posted", "2026-03-03T09:00:00Z"), ("ack", "2026-03-03T09:00:00Z"), + ("wed", "2026-03-04T09:00:00Z")] + + +@pytest.mark.asyncio +async def test_settling_waits_for_a_deferred_call_the_gateway_says_is_due_and_not_for_one_still_to_come(hook): + """A running clock may reach a call's time between the hook's clock read and its state read, so the gateway's + ``due``, not the hook's reading of the time, says the call is under way.""" + turn = SimpleNamespace(heartbeat=lambda: None) + due = _StateEnv(hook, due_reads=2) + assert await hook._settle(turn, [(due, None, None)], 5) == [True] and due.reads == 3 + later = _StateEnv(hook, due_reads=0) + assert await hook._settle(turn, [(later, None, None)], 5) == [True] and later.reads == 1 + + @pytest.mark.asyncio async def test_a_state_check_the_agents_turn_set_off_finishes_before_the_clock_jumps(hook, gateway, monkeypatch): async def slow_check(check, ctx=None, role=None): @@ -264,3 +293,26 @@ async def test_params_the_hook_cannot_use_are_refused(hook, gateway, params, fra with pytest.raises(ValueError) as e: await _turns(hook, _context(), params) assert fragment in str(e.value) + + +class _StateEnv: + """An env whose clock reads 09:00:00 while its gateway, a moment on, lists a deferred call at 09:00:01: due and still + to make for the first ``due_reads`` reads of its triggers state, made after; never due when ``due_reads`` is 0.""" + + env_id = "items" + + def __init__(self, hook, due_reads: int): + self.hook, self.due_reads, self.reads = hook, due_reads, 0 + + def supports(self, uri, op): + return True + + async def invoke(self, uri, op, args=None): + assert op == "state", op + if uri == self.hook.CLOCK: + return {"armed": True, "virtual_time": "2026-03-03T09:00:00Z"} + self.reads += 1 + due = self.reads <= self.due_reads + made = self.due_reads and not due + return {"triggers": [], "next_event_at": None if made else "2026-03-03T09:00:01Z", "deferred_calls": [ + {"key": "m1", "at": "2026-03-03T09:00:01Z", "status": "done" if made else "pending", "due": due}]} diff --git a/tst/unit/task_step/test_prompt_agent_triggers.py b/tst/unit/task_step/test_prompt_agent_triggers.py index b770980b5..3f4e16634 100644 --- a/tst/unit/task_step/test_prompt_agent_triggers.py +++ b/tst/unit/task_step/test_prompt_agent_triggers.py @@ -484,6 +484,36 @@ def test_settle_poll_does_not_wait_out_a_delay_or_working_hours(): assert PromptAgentTaskStep._capture_is_final(waiting) is False +def test_settle_poll_does_not_wait_for_a_deferred_call_the_gateway_has_yet_to_make(): + """A server's deferred call may be due hours of virtual time on, so until the clock reaches it it keeps the capture + waiting no more than an armed trigger does.""" + state = {"triggers": [{"id": "t", "type": "action", "status": "armed", "when": {"type": "action", "tool": "x"}}], + "deferred_calls": [{"key": "m1", "at": "2026-07-06T19:03:00Z", "tool": "deliver", "role": "default", + "status": "pending", "attempts": 0, "due": False}]} + assert PromptAgentTaskStep._is_settling(state) is False + + +def test_settle_poll_waits_for_a_deferred_call_the_clock_has_reached_until_the_gateway_makes_it(): + """Once due, the call and the triggers it provokes are under way, as a trigger firing is.""" + call = {"key": "m1", "at": "2026-07-06T19:03:00Z", "tool": "deliver", "role": "default", "status": "pending", + "attempts": 1, "due": True} + rows = [{"id": "t", "type": "action", "status": "armed", "when": {"type": "action", "tool": "x"}}] + assert PromptAgentTaskStep._is_settling({"triggers": rows, "deferred_calls": [call]}) is True + assert PromptAgentTaskStep._is_settling( + {"triggers": rows, "deferred_calls": [{**call, "status": "done", "due": False}]}) is False + + +def test_a_deferred_call_still_to_make_keeps_the_capture_from_being_final(): + """Settling aside, the call and any trigger it provokes will still change the record.""" + rows = [{"id": "t", "type": "action", "status": "armed", "when": {"type": "action", "tool": "x"}}] + pending = {"key": "m1", "at": "2026-07-06T19:03:00Z", "tool": "deliver", "role": "default", "status": "pending", + "attempts": 0} + assert PromptAgentTaskStep._capture_is_final({"triggers": rows, "deferred_calls": [pending]}) is False + assert PromptAgentTaskStep._capture_is_final( + {"triggers": rows, "deferred_calls": [{**pending, "status": "done"}, {**pending, "status": "failed"}]}) is True + assert PromptAgentTaskStep._capture_is_final({"triggers": rows}) is True + + @pytest.mark.asyncio async def test_capture_noop_without_registrations(): calls = {"n": 0}