Sessions enable multi-turn conversations with agents. Messages sent within a session share context and history, allowing the agent to reference previous messages and maintain state across interactions.
Creating a Session
Use client.createSession() to create a new session:
import Superserve from '@superserve/sdk'
const client = new Superserve ({ apiKey: 'ss_...' })
const session = await client . createSession ( 'my-agent' , {
title: 'Debug Session' ,
idleTimeout: 1800 // 30 minutes
})
console . log ( 'Session ID:' , session . id )
Options
Agent name or ID to create the session with
Optional title for the session. Useful for organizing conversations in logs or UIs.
Idle timeout in seconds. Defaults to 1740 (29 minutes). The session will automatically end after this period of inactivity.
Session Properties
Once created, a Session instance provides access to metadata:
const session = await client . createSession ( 'my-agent' )
console . log ( session . id ) // Session ID (ses_...)
console . log ( session . agentId ) // Agent ID (agt_...)
console . log ( session . info ) // Full session metadata
Session ID (format: ses_...)
ID of the agent this session is connected to
Complete session metadata Show SessionInfo properties
Human-readable agent name
Session status: active or ended
Number of messages sent in this session
ISO timestamp of session creation
Sending Messages
run()
Send a message and wait for the full response:
const result = await session . run ( 'What files are in the project?' )
console . log ( result . text )
console . log ( 'Tools used:' , result . toolCalls . length )
console . log ( 'Duration:' , result . duration , 'ms' )
Parameters
The message to send to the agent
Returns
The complete response from the agent Show RunResult properties
Array of tool invocations
finishReason
'completed' | 'failed' | 'cancelled'
Why the run finished
Total duration in milliseconds
Whether the agent hit its maximum turn limit
stream()
Send a message and get a streaming response:
const stream = session . stream ( 'Refactor the main module' , {
onText : ( text ) => process . stdout . write ( text ),
onFinish : ( result ) => console . log ( ' \n Done!' )
})
for await ( const chunk of stream . textStream ) {
process . stdout . write ( chunk )
}
Parameters
The message to send to the agent
Stream configuration and callbacks
Callback for each text chunk
options.onToolStart
(event: ToolStartEvent) => void
Callback when a tool starts
options.onToolEnd
(event: ToolEndEvent) => void
Callback when a tool completes
options.onFinish
(result: RunResult) => void
Callback when the run completes
Returns
An async iterable stream. See Streaming for details.
Ending a Session
Explicitly end a session when you’re done:
This frees up resources on the server. If you don’t call end(), the session will automatically timeout after the configured idleTimeout period (default: 29 minutes).
Multi-Turn Example
Here’s a complete example of a multi-turn conversation:
import Superserve from '@superserve/sdk'
const client = new Superserve ({
apiKey: process . env . SUPERSERVE_API_KEY !
})
const session = await client . createSession ( 'my-agent' , {
title: 'Code Review'
})
try {
// First turn: analyze the code
const r1 = await session . run ( 'What files are in the project?' )
console . log ( 'Agent:' , r1 . text )
// Second turn: ask about a specific file
const r2 = await session . run ( 'What does src/index.ts do?' )
console . log ( 'Agent:' , r2 . text )
// Third turn: request changes
const r3 = await session . run ( 'Add error handling to that file' )
console . log ( 'Agent:' , r3 . text )
console . log ( ` \n Total messages: ${ session . info . messageCount * 2 } ` ) // User + agent messages
} finally {
await session . end ()
}
Streaming Multi-Turn Conversations
Combine sessions with streaming for real-time multi-turn chats:
const session = await client . createSession ( 'my-agent' )
const questions = [
'What files are here?' ,
'Explain the main function' ,
'Add documentation to it'
]
for ( const question of questions ) {
console . log ( ` \n User: ${ question } ` )
console . log ( 'Agent: ' )
const stream = session . stream ( question )
for await ( const chunk of stream . textStream ) {
process . stdout . write ( chunk )
}
console . log () // Newline after response
}
await session . end ()
Reusing Sessions
You can reuse an existing session ID with client.run() or client.stream() instead of creating a new session:
// Create a session
const session = await client . createSession ( 'my-agent' )
const sessionId = session . id
// Later, reuse the session ID without the Session object
const result = await client . run ( 'my-agent' , {
message: 'Continue our conversation' ,
sessionId: sessionId
})
This is useful when you need to store the session ID and resume later (e.g., across HTTP requests in a web server).
Session Lifecycle
Created — createSession() returns a new Session instance
Active — Messages can be sent via run() or stream()
Ended — Either explicitly via end() or automatically after idleTimeout
Once a session is ended, you cannot send more messages to it. Create a new session to continue the conversation.
Best Practices
Always end sessions when done
Call session.end() to clean up resources immediately. Use a try/finally block to ensure cleanup happens even if errors occur: const session = await client . createSession ( 'my-agent' )
try {
await session . run ( 'Hello' )
} finally {
await session . end ()
}
Set idleTimeout based on your use case:
Chat interfaces : 30-60 minutes
API integrations : 5-10 minutes
Long-running tasks : 60+ minutes
const session = await client . createSession ( 'my-agent' , {
idleTimeout: 3600 // 1 hour
})
Store session IDs for resumption
For web applications, store the session ID in user state (e.g., cookies, database) to resume conversations across page loads: // On first load
const session = await client . createSession ( 'my-agent' )
saveToDatabase ( userId , session . id )
// On subsequent loads
const sessionId = loadFromDatabase ( userId )
const result = await client . run ( 'my-agent' , {
message: userInput ,
sessionId
})
Handle session expiration gracefully
If a session expires, the API will return an error. Catch this and create a new session: import { APIError } from '@superserve/sdk'
try {
await client . run ( 'my-agent' , {
message: 'Hello' ,
sessionId: oldSessionId
})
} catch ( error ) {
if ( error instanceof APIError && error . status === 404 ) {
// Session expired, create a new one
const session = await client . createSession ( 'my-agent' )
const result = await session . run ( 'Hello' )
}
}
Next Steps
Streaming Learn about streaming responses
React Hooks Build chat UIs with sessions