query() supports two input modes:
- Single-message query mode: submit one user message; the SDK closes the session after the current reply completes. See the Quickstart.
- Multi-message session mode: keep the session open and carry on a multi-turn conversation with the model.
Multi-message session
Define a sequence that yields user messages in order:
priority. The session closes automatically when the input message stream ends. For message field definitions see SDKUserMessage.
Steering a response
The async input stream can continue sending SDKUserMessage objects while the model is responding.
priority controls when a message is delivered:
| Value | Behavior |
|---|---|
now | Stop the current response and handle this message immediately |
next | Default; handle this message at the next suitable point |
later | Wait until the current response finishes |
priority: 'now' to change direction immediately. To stop the current response without sending another message, use q.interrupt().
Add context without starting a response
shouldQuery: false adds the message to the conversation without starting a response by itself. Its processing time still follows priority.
Interrupting the current response
Call await q.interrupt() to stop the current response without closing the session. You can continue the conversation afterward.
interrupt() does not clear queued messages. Use cancelAsyncMessage() when a specific queued message must not run. See Managing the session lifecycle to end the entire session.
Cancel a queued message
Give each tracked message a session-unique uuid, then call q.cancelAsyncMessage(uuid) to cancel it before execution starts:
true when the message is cancelled and false when the message is not found or can no longer be cancelled. Messages without a uuid cannot be cancelled this way. Do not reuse UUIDs within a session.
Managing the session lifecycle
The SDK closes the session automatically after a string input is handled or the input message stream ends. To end the session earlier, use an AbortController to define when it should end, or call q.close() directly.
Define when the session ends
To end the session when a custom business condition is met, create an AbortController and pass it through options.abortController when calling query(). Call abort() on the same controller when that condition is met. The condition can come from a user action, upstream request, task timeout, application shutdown, or other application logic:
abort() closes the entire session and ends message iteration. It cannot accept more messages afterward.
Close a session explicitly
When the current code no longer needs the session, call await q.close() directly. This works for normal completion, early exit, and error cleanup; placing it in finally ensures related resources finish closing: