Sessions
Sessions represent conversations with an agent. They store conversation history, track resources and variables, and enable stateful interactions.
Creating Sessions
Create a session by specifying the agent ID and initial input variables:
Getting Session Messages
To restore a conversation on page load, use getMessages() to retrieve UI-ready messages:
The returned messages can be passed directly to the client SDK's initialMessages option.
UISessionState Interface
Full Session State (Debug)
For debugging or internal use, you can retrieve the complete session state including all variables and internal message format:
Note: Use getMessages() for client-facing code. The get() method returns internal message format that includes hidden content not intended for end users.
Attaching to Sessions
To trigger actions on a session, you need to attach to it first:
Executing Requests
Once attached, execute requests on the session using execute():
Request Types
The execute() method accepts a discriminated union:
This makes it easy to pass requests through from the client:
Stop Support
Pass an abort signal to allow clients to stop generation:
When the client aborts the request, the signal propagates through to the LLM provider, stopping generation immediately. Any partial content is preserved.
WebSocket Handling
For WebSocket integrations, use handleSocketMessage() which manages abort controller lifecycle internally:
The handleSocketMessage() method:
- Handles
trigger,continue, andstopmessages - Automatically aborts previous requests when a new one arrives
- Streams events via the
onEventcallback - Calls
onFinishafter streaming completes (not called if aborted)
See Socket Chat Example for a complete implementation.
Session Lifecycle
Session Expiration
Sessions expire after a period of inactivity (default: 24 hours). When you call getMessages() or get(), the response includes a status field:
Response Types
| Status | Type | Description |
|---|---|---|
active | UISessionState | Session is active, includes messages array |
expired | ExpiredSessionState | Session expired, includes sessionId, agentId, createdAt |
Persisting Chat History
To enable session restoration, store the chat messages in your own database after each interaction:
Best Practice: Store the full UIMessage[] array. This preserves all message parts (text, tool calls, files, etc.) needed for accurate restoration.
Restoring Sessions
When a user returns to your app:
Restore Response
Complete Example
Here's a complete session management flow:
Clearing Sessions
To programmatically clear a session's state (e.g., for testing reset/restore flows), use clear():
After clearing, the session transitions to expired status. You can then restore it with restore() or create a new session.
This is idempotent — calling clear() on an already expired session succeeds without error.