Agent / Expose, do not reimplement
Waiting for Commands and state changes to finish
When a Message triggers asynchronous Commands, "dispatched" finishes before the real operation completes. Declare a completion rule on the capability using one of two styles:
- Correlated fact Message: Best when
updatemints a new ID and emits a distinct success (or failure) fact Message. Passcorrelateand an optionaltimeoutso concurrent invocations resolve their own call:
ts
const TimedAddAgent = AgentBuilder.make({
name: 'timed-add',
context: Overview,
messages: AgentBuilder.expose(Message, {
RequestedTodo: Agent.variant({
name: 'add_todo',
description: 'Add a todo and wait for persistence',
input: Schema.Struct({ title: Schema.String }),
toMessage: ({ title }) => ({ title }),
completion: {
success: Message.SubmittedTodo,
correlate: (request, result) => request.title.trim() === result.title,
timeout: Duration.seconds(10),
},
}),
}),
})- State condition (
Agent.when): Best when completion is a checkable condition on aProjection(Overview) or an externalsource(such as Sync'smounted.committed), regardless of whether a Command, live stream, or peer edit satisfied it:
ts
const StateCompletionAgent = AgentBuilder.make({
name: 'state-completion',
context: Overview,
messages: AgentBuilder.expose(Message, {
RequestedDeleteTodo: {
description: 'Delete a todo',
completion: Agent.when({
projection: Overview,
predicate: (value, request) => value.todos.every(todo => todo.id !== request.id),
}),
},
RequestedTodo: Agent.variant({
name: 'add_todo',
description: 'Add a todo confirmed by Sync',
input: Schema.Struct({ title: Schema.String }),
toMessage: ({ title }) => ({ title }),
completion: Agent.when({
source: mounted.committed,
predicate: (shared, request) => shared.todos.some(todo => todo.title === request.title),
timeout: Duration.seconds(10),
}),
}),
}),
})Two safeguards when writing Agent.when predicates:
- Condition-based: Because the runtime subscribes before dispatch and immediately checks the current snapshot, write predicates that hold only after this specific call's effect lands.
- Safe key lookups: Use
Object.hasOwnor aMapinstead ofobj[userInput]so keys like'constructor'never match prototype properties. Any exception thrown in a predicate fails only that invocation.
Completion waits for an outcome without making external side effects transactional. Timeouts cover both dispatch and waiting: timing out after dispatch returns leaves the Message in update, while cancelling before dispatch completes reports AgentCancelledError with dispatched: false and decision: 'unknown'.