Asks between objects
A deferred tool's call in one object can ask another object's agent (core's
Deferred tools). The two objects reach each other over RPC, with two methods
of the app's on its object class: ask, which submits with the caller's reply address, and reply,
which hands a reply to the instance. deliverReply is the asked object's way back to the asker:
export class NotesAgent extends Agent<Env> {
readonly motoko = new MotokoCapability<NotesPorts>({
// ...the options of the Usage example, and the way back to the object that asked:
deliverReply: async ({ to, text, isError }) => {
const reply = { toolCallId: to.toolCallId, token: to.token, text, isError };
await this.env.NOTES.getByName(to.scope.name).reply(to.sessionId, reply);
},
});
/** Another object's call asks this agent: the run's answer goes to `replyTo` when the run ends. */
async ask(sessionId: string, text: string, requestId: string, replyTo: ReplyAddress): Promise<string> {
return (await (await this.motoko.instance()).session(sessionId).submit({ text, requestId, replyTo })).submissionId;
}
/** The asked object's reply. One refused for good resolves, so the asked object stops trying. */
async reply(sessionId: string, input: ReplyInput): Promise<string> {
try {
return (await (await this.motoko.instance()).session(sessionId).reply(input)).outcome;
} catch (error) {
if (error instanceof ReplyNotPendingError || error instanceof SessionNotFoundError) return "refused";
throw error;
}
}
}The asking tool's start calls env.NOTES.getByName(user).ask(sessionId, question, requestId, replyTo)
with its context's requestId and replyTo. The asking object maps the refusals itself, so the asked
object needs no error class to cross RPC: a rejection of reply means "try again later". A failed
delivery sleeps until its retry, so the asked object's alarm brings it back after an eviction, and
the asking object reopens for the reply as it does for any call. A browser may send reply over the
socket too, but only the work the call started holds its token; authorize can refuse it outright.