Repository navigation
feat(gateway): make the tool calls a server's result defers, on the gateway clock - #907
Merged
Merged
Conversation
…ateway clock
The trigger engine reacts only to tool calls that pass through the gateway, so an action a
server takes later by itself (a chat server posting a scheduled message at its time) provokes
no trigger and no simulated party reacts to it.
A server's successful tools/call result may now carry, in its _meta, the key
"agentenv.io/deferredCalls": a list of {key, at, call {tool, arguments}, report_as {tool,
arguments}}. GatewayServer._call_child_tool, which every child call goes through (MCP proxy,
/step, the trigger engine's own calls), takes the key off the result before anyone sees it and
schedules each entry once per key. When the gateway clock reaches `at` (its virtual time while
armed: held at rate 0, followed through advance, set-time, rate changes and clear by the
trigger engine's wake; wall UTC while unarmed), the gateway calls call.tool on the same server
as the role that made the declaring call, retrying a transport failure with bounded backoff,
logs a deferred_call trajectory event, and, unless the result is an error, feeds that result
to the trigger engine as that role's call of report_as.tool with report_as.arguments.
GET /triggers/state lists them under deferred_calls (key, at, tool, role, status, attempts),
which prompt_agent's settle check does not read; the card declares the deferred_calls trigger
feature; pending calls are cancelled at shutdown with the scheduled trigger actions. A result
without the key is answered exactly as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…time Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… error limit is named Two servers behind one gateway may declare the same key (each its own scheduled id, say); keyed by key alone, the second was ignored while the first was pending or done. Calls are now kept by (server, key), and /triggers/state names each call's server. The error text limit is DeferredCalls.ERROR_TEXT_LIMIT. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…g, and each call is attributed and seen by clock movers - A call a trigger engine internal call declares is made and logged but reported to no trigger, as the internal call itself is not: `_call_child_tool` takes `report` (False from `_internal_call`) and the record keeps it. A trigger on the agent's sends whose action schedules a message no longer takes that message for the agent's and loops. - Each attempt runs under the gateway's tool-call guard, as a live call does, and the `deferred_call` event carries `changelog_id_before`/`changelog_id_after` (from before the first attempt to after the last); changes/v1 attributes the rows in that window to a `deferred_call` actor (key, tool, role). - `GET /triggers/state` counts the earliest pending call in `next_event_at`, so advance-to-next-event, next-env-event and always_on stop at it, and marks each entry `due` while the gateway clock has reached it and it is still to make, so a client can wait for it without clock math of its own. - Shutdown cancels the deferred calls before the scheduled trigger actions and schedules none after. - A catch-all in `_make` leaves an unexpected failure `failed`, never `pending`. - History is bounded: state lists the calls still to make plus the latest `FINISHED_KEPT` (100) finished; every key made stays known, so it is still never made twice. - The `deferred_call` event also carries `at`, the `report_as` tool, `reported` and `result_sha256`. - agentenv_protocol exports `DEFERRED_CALLS_META_KEY`; the gateway keeps its literal mirror, as for the hidden-by-default key, since its container ships without the protocol (a test pins them equal). - The protocol README's retry text matches what happens: five attempts 1, 2, 4 and 8 s apart, each reopening the server's session if it must, about 51 s end to end against a server that stays down. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rks due, and a capture is not final while one is pending - prompt_agent's settle poll (`_is_settling`), always_on's settle and the next-env-event and advance-to-next-event hooks' settles count a deferred call the gateway marks `due` (its clock has reached it and the call is still to make) as work under way, so none reads the world as settled between an advance that made a call due and the trigger fire its report sets off. They read the gateway's flag, not their own clock read, which a running clock can have left behind. A call not yet due keeps nothing waiting. - always_on names the due calls it gave up on (`deferred_calls_due`) when its settle times out. - `_capture_is_final` is False while any deferred call is pending: the call, and the triggers it provokes, will still change the record. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tool(defers=Defers(call, report_as, using)) builds the deferred-calls declaration a server used to assemble by hand. After each successful call of the registered tool, the environment's `using` method receives the call's arguments and the tool's result (JSON text parsed, a dict as is, a CallToolResult's structured content or parsed text) and returns a DeferredCall, a list of them, or None. Each becomes an entry under DEFERRED_CALLS_META_KEY on the reply, merged with any _meta it has; the reply's content and structured content are unchanged, on mcp's FastMCP and fastmcp alike. `at` is normalised to a UTC RFC 3339 instant from an aware datetime, epoch seconds or an offset string; a naive or offset-less time, a raising `using` or an invalid return is logged and declares nothing. The method called in process returns its plain value. The mount refuses a Defers whose call is not a served hidden_by_default tool, whose report_as is not a served tool, or whose using is not a plain method, and the card lists {"call", "report_as"} under the tool's `defers`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s are named The per-call record DeferredCalls kept as an 8-key dict is now a private dataclass, and the statuses GET /triggers/state lists for each deferred call are constants beside the trigger statuses, which prompt_agent's capture check compares against. The wire format is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…lls are reported Gateway._call_child_tool's `report` flag is what keeps a trigger action's deferred call from provoking triggers again, and it defaulted to True, so an internal caller that forgot report=False would silently bring the loop back. It is now keyword-only with no default, and every call site passes it: the MCP proxy and /step (True), the trigger engine (False) and the deferred calls themselves (the declaring call's value). The tests' fakes follow the signature, and the session tests that call it directly pass report=True, the old default. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…k waits for prompt_agent's settle check, always_on's settle and the two example post-turn hooks each wrote out that a deferred call the gateway marks `due` counts as work under way. due_deferred_calls(state), beside the deferred-call statuses in the gateway constants, now says it once and all four use it. The hooks run in the control-plane process, which has agent_env, as the advance-to-next-event hook's existing import of it already relies on. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DeferredCalls._make read the changelog before the first attempt and after the last, but released the tool-call lock between attempts, so another role's write during a retry's backoff fell inside the one window and changes/v1 credited the deferred call's role with it, even on a consistent gateway. Each attempt now reads its own window under its lock, the deferred_call event lists them as changelog_windows, and ChangeAttribution adds each. A write by an attempt that then lost its transport stays credited, as it falls inside that attempt's window. changelog_id_before and changelog_id_after still give the span from the first attempt to the last. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…esult declared itself A tool returning a CallToolResult that already carried deferred calls had that list replaced by the ones its Defers added, so the gateway never made them. The decorator's calls are now appended after the result's own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…osely enough for a loaded CI box CI measured 2.1 s for a 0.2 s settle timeout under parallel load, past the test's 1.5 s ceiling. The bound only has to tell this step's timeout from the 300 s default, so it is now 10 s. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ond of lag at 3600x Ten virtual minutes at 3600x is 0.17 s of real time, which a loaded CI box can exceed between the call coming due and being made. A virtual hour (one real second) still shows the call was made at its time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What and why
A tool result can now ask the gateway to call the same server later, on the gateway clock, and a tool can declare that in its
@tooldecorator.The gap it closes. The gateway's triggers react only to tool calls that pass through it. When a server acts at a time of its own, nothing marks it. Take a chat server posting a scheduled message at its time: no call happens, so no trigger fires and no simulated colleague reacts, or one reacts only when something happens to read the channel later. With this change the server declares the later action in the result that scheduled it. The gateway makes that call when its virtual clock reaches the declared time, as the role that scheduled it, and reports it to its triggers as the call it stands for.
The contract (
packages/agentenv-protocol/README.md, next tohidden_by_default;DEFERRED_CALLS_META_KEY):Declaring it in the decorator (agentenv_protocol):
@tool(..., defers=Defers(call=..., report_as=..., using="method")). Theusingmethod gets the call's arguments and its reply and returns aDeferredCall(or a list, or None). The decorator handles the rest:_meta, leaving the text,structuredContent, other meta and any calls the result declared itself unchanged;atto UTC;usingfails;callis a hidden tool of the same environment and thatreport_asis served;deferson the EnvironmentCard.What the gateway does (
src/agent_env/env/gateway/deferred_calls.py):Gateway._call_child_tool, the single path for the MCP proxy,/step, trigger internal calls and the deferred calls themselves. No caller, trajectory or trigger sees the key. (The first commit's body saysGatewayServer._call_child_tool; the class isGateway.)key. A failed call may be declared again. Contract breaks are logged and skipped one by one, and nothing is scheduled from an error result.changes/v1credits the write to that role and never claims writes made between attempts. Transport errors are retried 5 times with 1/2/4/8 s backoff; each attempt also includes the child session's reconnect, about 51 s end to end. AnisErrorresult is final._fire_triggers(role, report_as.tool, report_as.arguments, result), the same entry point live calls use. There is one exception: a call declared by a trigger action's own tool call is made but not reported. Internal calls never provoke triggers, and this keeps a trigger from looping on its own messages. Every child call states explicitly whether its declarations report.GET /triggers/statelists calls underdeferred_calls: pending ones, plus the latest 100 finished. Each hasduewhile the clock has reached it and it is still to make.next_event_atcounts the earliest pending call, so advance-to-next-event, next-env-event andalways_onstop at it.always_on, both example hooks) wait for a due call through one shared rule,due_deferred_calls, and never for one still to come.deferred_calltrajectory event per call: key, at, tool, report_as, role, ok, reported, attempts, result digest and change-log windows.deferred_callsamong the card's triggers features.A result without the key is answered exactly as before. Behind no gateway, or one that ignores the key, the server acts by itself on its own fallback (its next read, say).
For review:
"defers": nullfor tools that don't defer, asdescriptionandinputSchemaalready can.agent_env, as advance-to-next-event already did.Defersnames are matched against served tool names ({environment_name}resolved), not renames made byserve_tools_as.usingmust be a plain method.How it was tested
Unit tests:
deferred_calls_test.py, plus a socket test with the real gateway app in front of a real MCP child and one in front of an@tool(defers=...)environment);test_tool_defers.pyin the protocol package (44 cases on both FastMCPs);changes_test.py.Each was written to fail first on the commit before it.
Unit tier on Linux (
tst/unit+packages/agentenv-protocol/tests,-n 16): main has 3 failed and 18891 passed; this branch has 3 failed and 18975 passed. The same 3 environment failures appear on both, and no outcome differs.Integration, on the local provider: the gateway trigger, barrier, clock, MCP, consistent-mode, tool-disable, notification and deadline tests, plus
test_register_env_triggers_local.py. 22 passed on both trees, with identical per-test outcomes. Remote-sandbox parameters were skipped.Checks:
ruff check,check_plugin_api.py("no break to the plugin surface") andimport_graph_test.End to end, local processes on Linux. The real gateway is in front of a real chat server that schedules messages, with main's gateway and server as controls.
/triggers/statestays ~23 KB.🤖 Generated with Claude Code


Confidence Score: 5/5
The PR appears safe to merge; the latest changes only widen test timing bounds.Summary
Adds server-declared calls that run later on the gateway clock.
Diagram
%%{init: {'theme': 'neutral'}}%% flowchart TD A[Child tool result] --> B[Remove deferred-call metadata] B --> C[Wait for gateway clock] C --> D[Call same server as declaring role] D --> E{Successful and reporting enabled?} E -->|Yes| F[Notify triggers as report_as] E -->|No| G[Record outcome] F --> GReviews (11) · Last reviewed commit: "test(gateway): the running-clock deferre..." · Reviewed by Greptile