Deferred tools
A deferred tool's call starts work elsewhere, typically another instance's run, and waits for its reply. It holds no process while it waits: it parks, so an idle close, a restart or an evicted Durable Object loses nothing.
import { defineDeferredTool } from "@chia1104/motoko-core";
import type { DeferredContext } from "@chia1104/motoko-core";
const askTeammate = defineDeferredTool({
name: "ask_teammate",
description: "Ask a teammate's agent a question; it answers when its own run ends.",
tier: "read",
parameters: z.object({ teammate: z.string(), sessionId: z.string(), question: z.string() }),
timeoutMs: 60 * 60_000, // an hour; default 24 hours
async start({ teammate, sessionId, question }, { ports, requestId, replyTo }: DeferredContext<TeamPorts>) {
// An ask: the teammate's instance answers to `replyTo` when the run this starts ends.
await ports.team.submit(teammate, sessionId, { text: question, requestId, replyTo });
},
});The call runs in this order:
- It passes the approval gate like any call: a gated tier asks before
startever runs. - It memoizes a token and its deadline, and records both in
runtime.callsin one commit. From then on its sleep is its own, not the gate's: it raises no question, andapprove()refuses it. - It resolves its ports, as an app tool's call does, and runs
startwith aDeferredContext:ports,signal,scope,sessionId,toolCallId,requestIdandreplyTo.replyTois the reply address,{ scope, sessionId, toolCallId, token }. Astartthat throws ends the call with its message as an error result. - It parks until a reply arrives or the deadline passes. The stream shows
reply:waitwith the deadline, and the view shows the callawaiting_replyuntil it runs again and ends. - Woken, it returns the reply's
textas its result, an error result if the reply saysisError, orNo reply came in time.once the deadline passed.
start may run again: a crash before the park reruns the call, with the same requestId and the
same reply address. So the work it starts must be idempotent by requestId, as submit is. The
requestId is made of the scope, the session and the call, so it is unique across instances.
cancel(args, context), when the tool has one, runs with the same context when the call is stopped
while it waits (its session is aborted), and may run more than once.
session.reply({ toolCallId, token, text, isError? }) answers the call. It reopens a closed instance,
and takes a child session's call too, since a sub-agent may make a deferred call. In one commit it
checks the token, in constant time, delivers the reply and records it. A reply may come before the
park, while start still runs: it is kept, and the park wakes at once. A second reply, also after
the call ended, is already_replied, so a delivery may be retried. Everything else is
ReplyNotPendingError (reply_not_pending): a wrong token, a call with no reply record, one that
ended without a reply, or passed its deadline. Nothing tells these apart, so a guess learns nothing.
Asks
An ask is a submission with replyTo: the asked instance delivers the answer of the run it starts to
that address. submit refuses replyTo with InvalidRequestError (invalid_request) on a runtime
without deliverReply, or with whenBusy: "reject" or "steer", since an ask always queues: its
answer is the answer of a run of its own. It refuses an ask with metadata the same way. Its asker
waits for that answer, so withdraw refuses an ask's submission the same way.
The asked side keeps a courier for each ask, a background task of the asked session:
submitcreates the courier in one commit, and records it in the session'sruntime.asksdocument by request ID. Then it submits, notifying the courier when the submission settles. A retry with the same request ID finds the courier and returns the first submission.- The courier submits the same ask itself, in the commit that parks it on the settlement. So a crash
between the two commits of
submitloses nothing: the courier makes the submission. - Once the run ends, the courier reads its answer as a delegate's call does (the last reply's text,
or why there is none, such as
aborted), and callsdeliverReply({ to, text, isError }, signal). deliverReplyresolving means done: the reply was delivered, or refused for good. Mapreply_not_pendingandsession_not_foundto resolving. A rejection is reported asreply_failed, and the courier sleeps before it tries again: 1 second, doubling, at most 5 minutes. It gives up a day after its first try, with a last report.- Deleting the asked session aborts its courier, which sends nothing: the asker's deadline ends its call. Aborting the asker stops its call, not the asked run; the reply that comes later is refused, and the courier ends.
deliverReply is the app's way to reach the asker's home: session.reply of the same runtime, a
client of the cluster (forwarding takes the call to the home), or a
Durable Object's stub (asks between objects).