Skip to main content
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
string
required
Agent name or ID to create the session with
options.title
string
Optional title for the session. Useful for organizing conversations in logs or UIs.
options.idleTimeout
number
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
id
string
Session ID (format: ses_...)
agentId
string
ID of the agent this session is connected to
info
SessionInfo
Complete session metadata

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

message
string
required
The message to send to the agent

Returns

result
RunResult
The complete response from the agent

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('\nDone!')
})

for await (const chunk of stream.textStream) {
  process.stdout.write(chunk)
}

Parameters

message
string
required
The message to send to the agent
options
StreamOptions
Stream configuration and callbacks
options.onText
(text: string) => void
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
options.onError
(error: Error) => void
Callback on errors

Returns

stream
AgentStream
An async iterable stream. See Streaming for details.

Ending a Session

Explicitly end a session when you’re done:
await session.end()
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(`\nTotal 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(`\nUser: ${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

  1. CreatedcreateSession() returns a new Session instance
  2. Active — Messages can be sent via run() or stream()
  3. 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

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
})
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
})
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

Build docs developers (and LLMs) love