Skip to main content

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:

typescript

Getting Session Messages

To restore a conversation on page load, use getMessages() to retrieve UI-ready messages:

typescript

The returned messages can be passed directly to the client SDK's initialMessages option.

UISessionState Interface

typescript

Full Session State (Debug)

For debugging or internal use, you can retrieve the complete session state including all variables and internal message format:

typescript

Note: Use getMessages() for client-facing code. The get() method returns internal message format that includes hidden content not intended for end users.

Getting Execution Logs

getLogs() returns the chronological execution trace for a session - triggers, messages, tool calls, LLM responses, errors, and other events emitted while the agent ran. Useful for debugging, observability, and building custom timeline views.

typescript

Each entry is a typed variant of ExecutionLogEntry (a discriminated union) so consumers can narrow on entry.type:

typescript

Excluding Model Request Payloads

Model-request entries include the full provider request body and can be large. Pass excludeModelRequests: true to skip them:

typescript

Truncation

Responses are capped at 1000 entries (most recent). When the log exceeds that cap, the response includes total and truncated so consumers can detect this:

typescript

Response Types

StatusTypeDescription
activeExecutionLogsResult{ sessionId, entries, total?, truncated? }. total and truncated are present when known
expiredExpiredSessionState{ sessionId, agentId, status: 'expired', createdAt }

Forward-compatible types: ExecutionLogEntry may gain new variants over time. Include a default case when switching on entry.type so unknown variants are handled gracefully.

Attaching to Sessions

To trigger actions on a session, you need to attach to it first:

typescript

Attach Options

OptionTypeDescription
toolsToolHandlersServer-side tool handler functions
resourcesResource[]Resource watchers for real-time updates
onToolResults(results: ToolResult[]) => voidCallback invoked after server-side tool results are produced
rejectClientToolCallsbooleanIf true, reject tool calls that have no server handler (no client forwarding)

For MCP tool integration (browser, filesystem, shell via @octavus/computer), register dynamic tools after attaching with session.setDynamicTools(). See Computer for details.

Executing Requests

Once attached, execute requests on the session using execute():

typescript

Request Types

The execute() method accepts a discriminated union:

typescript

This makes it easy to pass requests through from the client:

typescript

Stop Support

Pass an abort signal to allow clients to stop generation:

typescript

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:

typescript

The handleSocketMessage() method:

  • Handles trigger, continue, and stop messages
  • Automatically aborts previous requests when a new one arrives
  • Streams events via the onEvent callback
  • Calls onFinish after 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:

typescript

Response Types

StatusTypeDescription
activeUISessionStateSession is active, includes messages array
expiredExpiredSessionStateSession expired, includes sessionId, agentId, createdAt

Persisting Chat History

To enable session restoration, store the chat messages in your own database after each interaction:

typescript

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:

typescript

Restore Response

typescript

Complete Example

Here's a complete session management flow:

typescript

Clearing Sessions

To programmatically clear a session's state (e.g., for testing reset/restore flows), use clear():

typescript

After clearing, the session transitions to expired status. You can then restore it with restore() or create a new session.

typescript

This is idempotent - calling clear() on an already expired session succeeds without error.

Error Handling

typescript