diff --git a/api-reference/messaging/sessions-api-reference.mdx b/api-reference/messaging/sessions-api-reference.mdx deleted file mode 100644 index 84441af..0000000 --- a/api-reference/messaging/sessions-api-reference.mdx +++ /dev/null @@ -1,608 +0,0 @@ ---- -title: Sessions API Reference -description: Complete API reference for the Sessions messaging system -icon: comments ---- - -The Sessions API provides a comprehensive set of endpoints for managing stateful conversations with ElizaOS agents. This reference covers all available endpoints, request/response schemas, and error handling. - -## Base URL - -``` -http://localhost:3000/api/messaging/sessions -``` - -## Authentication - -Currently, the Sessions API does not require authentication. In production environments, you should implement appropriate authentication mechanisms. - -## Endpoints - -### Create Session - -Creates a new conversation session with an agent. - - - Create a new session with configurable timeout policies - - -**Request Body:** - -```typescript -interface CreateSessionRequest { - agentId: string; // UUID of the agent - userId: string; // UUID of the user - metadata?: { // Optional session metadata - [key: string]: any; - }; - timeoutConfig?: { // Optional timeout configuration - timeoutMinutes?: number; // 5-1440 minutes - autoRenew?: boolean; // Default: true - maxDurationMinutes?: number; // Maximum session duration - warningThresholdMinutes?: number; // When to warn about expiration - }; -} -``` - -**Response (201 Created):** - -```typescript -interface CreateSessionResponse { - sessionId: string; - agentId: string; - userId: string; - createdAt: Date; - metadata: object; - expiresAt: Date; - timeoutConfig: SessionTimeoutConfig; -} -``` - -**Example:** - -```bash -curl -X POST http://localhost:3000/api/messaging/sessions \ - -H "Content-Type: application/json" \ - -d '{ - "agentId": "123e4567-e89b-12d3-a456-426614174000", - "userId": "987f6543-e21b-12d3-a456-426614174000", - "timeoutConfig": { - "timeoutMinutes": 30, - "autoRenew": true - } - }' -``` - ---- - -### Get Session Information - -Retrieves detailed information about a session including its current status. - - - Get session details and current status - - -**Response (200 OK):** - -```typescript -interface SessionInfoResponse { - sessionId: string; - agentId: string; - userId: string; - createdAt: Date; - lastActivity: Date; - metadata: object; - expiresAt: Date; - timeoutConfig: SessionTimeoutConfig; - renewalCount: number; - timeRemaining: number; // Milliseconds until expiration - isNearExpiration: boolean; // True if within warning threshold -} -``` - -**Errors:** -- `404 Not Found` - Session does not exist -- `410 Gone` - Session has expired - ---- - -### Send Message - -Sends a message within a session. Automatically renews the session if auto-renewal is enabled. - - - Send a message in the conversation - - -**Request Body:** - -```typescript -interface SendMessageRequest { - content: string; // Message content (max 4000 chars) - metadata?: { // Optional message metadata - [key: string]: any; - }; - attachments?: any[]; // Optional attachments -} -``` - -**Response (201 Created):** - -```typescript -interface MessageResponse { - id: string; - content: string; - authorId: string; - createdAt: Date; - metadata: object; - sessionStatus?: { // Session renewal information - expiresAt: Date; - renewalCount: number; - wasRenewed: boolean; - isNearExpiration: boolean; - }; -} -``` - -**Errors:** -- `400 Bad Request` - Invalid content or metadata -- `404 Not Found` - Session not found -- `410 Gone` - Session expired - ---- - -### Get Messages - -Retrieves messages from a session with pagination support. - - - Retrieve conversation history - - -**Query Parameters:** - -```typescript -interface GetMessagesQuery { - limit?: string; // Number of messages (1-100, default: 50) - before?: string; // Timestamp for pagination (older messages) - after?: string; // Timestamp for pagination (newer messages) -} -``` - -**Response (200 OK):** - -```typescript -interface GetMessagesResponse { - messages: SimplifiedMessage[]; - hasMore: boolean; - cursors?: { - before?: number; // Use for getting older messages - after?: number; // Use for getting newer messages - }; -} - -interface SimplifiedMessage { - id: string; - content: string; - authorId: string; - isAgent: boolean; - createdAt: Date; - metadata: { - thought?: string; // Agent's internal reasoning - actions?: string[]; // Actions taken by agent - [key: string]: any; - }; -} -``` - ---- - -### Renew Session - -Manually renews a session to extend its expiration time. - - - Manually extend session lifetime - - -**Response (200 OK):** - -```typescript -interface SessionInfoResponse { - sessionId: string; - agentId: string; - userId: string; - createdAt: Date; - lastActivity: Date; - expiresAt: Date; - timeoutConfig: SessionTimeoutConfig; - renewalCount: number; - timeRemaining: number; - isNearExpiration: boolean; -} -``` - -**Errors:** -- `404 Not Found` - Session not found -- `410 Gone` - Session expired -- `422 Unprocessable Entity` - Cannot renew (max duration reached) - ---- - -### Update Timeout Configuration - -Updates the timeout configuration for an active session. - - - Modify session timeout settings - - -**Request Body:** - -```typescript -interface SessionTimeoutConfig { - timeoutMinutes?: number; // 5-1440 minutes - autoRenew?: boolean; - maxDurationMinutes?: number; - warningThresholdMinutes?: number; -} -``` - -**Response (200 OK):** - -Returns updated `SessionInfoResponse` - -**Errors:** -- `400 Bad Request` - Invalid timeout configuration -- `404 Not Found` - Session not found -- `410 Gone` - Session expired - ---- - -### Send Heartbeat - -Keeps a session alive and optionally renews it if auto-renewal is enabled. - - - Keep session alive with periodic heartbeat - - -**Response (200 OK):** - -Returns `SessionInfoResponse` with updated expiration information. - -**Errors:** -- `404 Not Found` - Session not found -- `410 Gone` - Session expired - ---- - -### Delete Session - -Explicitly ends and removes a session. - - - End and delete a session - - -**Response (200 OK):** - -```typescript -{ - success: true, - message: "Session {sessionId} deleted successfully" -} -``` - -**Errors:** -- `404 Not Found` - Session not found - ---- - -### List Sessions (Admin) - -Lists all active sessions in the system. This is an administrative endpoint. - - - List all active sessions - - -**Response (200 OK):** - -```typescript -interface ListSessionsResponse { - sessions: SessionInfoResponse[]; - total: number; - stats: { - totalSessions: number; - activeSessions: number; - expiredSessions: number; - }; -} -``` - ---- - -### Health Check - -Checks the health status of the Sessions API service. - - - Check service health - - -**Response (200 OK):** - -```typescript -interface HealthCheckResponse { - status: 'healthy' | 'degraded' | 'unhealthy'; - activeSessions: number; - timestamp: string; - expiringSoon?: number; // Sessions near expiration - invalidSessions?: number; // Corrupted sessions detected - uptime?: number; // Service uptime in seconds -} -``` - -## Error Responses - -All error responses follow a consistent format: - -```typescript -interface ErrorResponse { - error: string; // Error message - details?: { // Additional context - [key: string]: any; - }; -} -``` - -### Common Error Codes - -| Status Code | Error Type | Description | -|------------|------------|-------------| -| `400` | Bad Request | Invalid input parameters or request body | -| `404` | Not Found | Session or resource not found | -| `410` | Gone | Session has expired | -| `422` | Unprocessable Entity | Operation cannot be completed (e.g., max duration reached) | -| `500` | Internal Server Error | Unexpected server error | - -### Error Classes - -The API uses specific error classes for different scenarios: - -- `SessionNotFoundError` - Session does not exist -- `SessionExpiredError` - Session has exceeded its timeout -- `SessionCreationError` - Failed to create session -- `AgentNotFoundError` - Specified agent not found -- `InvalidUuidError` - Invalid UUID format -- `MissingFieldsError` - Required fields missing -- `InvalidContentError` - Message content validation failed -- `InvalidMetadataError` - Metadata exceeds size limit -- `InvalidPaginationError` - Invalid pagination parameters -- `InvalidTimeoutConfigError` - Invalid timeout configuration -- `SessionRenewalError` - Cannot renew session -- `MessageSendError` - Failed to send message - -## Rate Limiting - -Currently, the Sessions API does not implement rate limiting. In production, you should implement appropriate rate limiting based on your requirements. - -## WebSocket Events - -When using WebSocket connections alongside the Sessions API, the following events are available: - -```typescript -// Join a session for real-time updates -socket.emit('join', { roomId: sessionId }); - -// Listen for new messages -socket.on('messageBroadcast', (message) => { - // Handle new message -}); - -// Session expiration warning -socket.on('sessionExpirationWarning', (data) => { - // data.sessionId, data.minutesRemaining -}); - -// Session expired -socket.on('sessionExpired', (data) => { - // data.sessionId, data.expiredAt -}); - -// Session renewed -socket.on('sessionRenewed', (data) => { - // data.sessionId, data.expiresAt, data.renewalCount -}); -``` - -## Environment Variables - -Configure the Sessions API behavior using these environment variables: - -| Variable | Default | Description | -|----------|---------|-------------| -| `SESSION_DEFAULT_TIMEOUT_MINUTES` | 30 | Default session timeout | -| `SESSION_MIN_TIMEOUT_MINUTES` | 5 | Minimum allowed timeout | -| `SESSION_MAX_TIMEOUT_MINUTES` | 1440 | Maximum allowed timeout (24 hours) | -| `SESSION_MAX_DURATION_MINUTES` | 720 | Maximum total session duration (12 hours) | -| `SESSION_WARNING_THRESHOLD_MINUTES` | 5 | When to trigger expiration warning | -| `SESSION_CLEANUP_INTERVAL_MINUTES` | 5 | How often to clean expired sessions | -| `CLEAR_SESSIONS_ON_SHUTDOWN` | false | Clear all sessions on server shutdown | - -## SDK Examples - -### JavaScript/TypeScript Client - -```typescript -class SessionsAPIClient { - constructor(private baseUrl: string = 'http://localhost:3000') {} - - async createSession(agentId: string, userId: string, config?: SessionTimeoutConfig) { - const response = await fetch(`${this.baseUrl}/api/messaging/sessions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ agentId, userId, timeoutConfig: config }) - }); - - if (!response.ok) throw new Error(`Failed to create session: ${response.status}`); - return response.json(); - } - - async sendMessage(sessionId: string, content: string, metadata?: object) { - const response = await fetch( - `${this.baseUrl}/api/messaging/sessions/${sessionId}/messages`, - { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ content, metadata }) - } - ); - - if (!response.ok) throw new Error(`Failed to send message: ${response.status}`); - return response.json(); - } - - async getMessages(sessionId: string, limit = 50, before?: number) { - const params = new URLSearchParams({ limit: limit.toString() }); - if (before) params.append('before', before.toString()); - - const response = await fetch( - `${this.baseUrl}/api/messaging/sessions/${sessionId}/messages?${params}` - ); - - if (!response.ok) throw new Error(`Failed to get messages: ${response.status}`); - return response.json(); - } - - async renewSession(sessionId: string) { - const response = await fetch( - `${this.baseUrl}/api/messaging/sessions/${sessionId}/renew`, - { method: 'POST' } - ); - - if (!response.ok) throw new Error(`Failed to renew session: ${response.status}`); - return response.json(); - } - - async sendHeartbeat(sessionId: string) { - const response = await fetch( - `${this.baseUrl}/api/messaging/sessions/${sessionId}/heartbeat`, - { method: 'POST' } - ); - - if (!response.ok) throw new Error(`Heartbeat failed: ${response.status}`); - return response.json(); - } -} -``` - -### Python Client - -```python -import requests -from typing import Optional, Dict, Any - -class SessionsAPIClient: - def __init__(self, base_url: str = "http://localhost:3000"): - self.base_url = base_url - self.session = requests.Session() - - def create_session( - self, - agent_id: str, - user_id: str, - timeout_config: Optional[Dict[str, Any]] = None - ) -> Dict[str, Any]: - """Create a new session with an agent.""" - payload = { - "agentId": agent_id, - "userId": user_id - } - - if timeout_config: - payload["timeoutConfig"] = timeout_config - - response = self.session.post( - f"{self.base_url}/api/messaging/sessions", - json=payload - ) - response.raise_for_status() - return response.json() - - def send_message( - self, - session_id: str, - content: str, - metadata: Optional[Dict[str, Any]] = None - ) -> Dict[str, Any]: - """Send a message in a session.""" - payload = {"content": content} - - if metadata: - payload["metadata"] = metadata - - response = self.session.post( - f"{self.base_url}/api/messaging/sessions/{session_id}/messages", - json=payload - ) - response.raise_for_status() - return response.json() - - def get_messages( - self, - session_id: str, - limit: int = 50, - before: Optional[int] = None, - after: Optional[int] = None - ) -> Dict[str, Any]: - """Retrieve messages from a session.""" - params = {"limit": str(limit)} - - if before: - params["before"] = str(before) - if after: - params["after"] = str(after) - - response = self.session.get( - f"{self.base_url}/api/messaging/sessions/{session_id}/messages", - params=params - ) - response.raise_for_status() - return response.json() - - def renew_session(self, session_id: str) -> Dict[str, Any]: - """Manually renew a session.""" - response = self.session.post( - f"{self.base_url}/api/messaging/sessions/{session_id}/renew" - ) - response.raise_for_status() - return response.json() - - def send_heartbeat(self, session_id: str) -> Dict[str, Any]: - """Send a heartbeat to keep session alive.""" - response = self.session.post( - f"{self.base_url}/api/messaging/sessions/{session_id}/heartbeat" - ) - response.raise_for_status() - return response.json() -``` - -## Next Steps - - - - Learn best practices and advanced patterns - - - Add real-time capabilities to your sessions - - - Understand ElizaOS architecture - - - Build custom plugins for your agents - - diff --git a/docs.json b/docs.json index 57c918d..174cb44 100644 --- a/docs.json +++ b/docs.json @@ -87,7 +87,7 @@ "runtime/models", "runtime/services", "runtime/messaging", - "runtime/sessions" + "runtime/sessions-api" ] } ] @@ -123,7 +123,7 @@ ] }, { - "group": "Messaging", + "group": "MESSAGING", "pages": [ "api-reference/messaging/create-server", "api-reference/messaging/create-channel", @@ -140,22 +140,6 @@ "api-reference/messaging/delete-channel-message", "api-reference/messaging/delete-all-channel-messages", "api-reference/messaging/delete-all-channel-messages-by-user", - { - "group": "Sessions API", - "pages": [ - "api-reference/messaging/sessions-api-reference", - "api-reference/messaging/create-session", - "api-reference/messaging/get-session", - "api-reference/messaging/send-session-message", - "api-reference/messaging/get-session-messages", - "api-reference/messaging/renew-session", - "api-reference/messaging/update-session-timeout", - "api-reference/messaging/session-heartbeat", - "api-reference/messaging/end-session", - "api-reference/messaging/list-sessions", - "api-reference/messaging/sessions-health-check" - ] - }, "api-reference/messaging/add-agent-to-server", "api-reference/messaging/add-agent-to-channel", "api-reference/messaging/remove-agent-from-server", @@ -170,7 +154,22 @@ ] }, { - "group": "Memory", + "group": "SESSIONS API", + "pages": [ + "api-reference/messaging/create-session", + "api-reference/messaging/get-session", + "api-reference/messaging/send-session-message", + "api-reference/messaging/get-session-messages", + "api-reference/messaging/renew-session", + "api-reference/messaging/update-session-timeout", + "api-reference/messaging/session-heartbeat", + "api-reference/messaging/end-session", + "api-reference/messaging/list-sessions", + "api-reference/messaging/sessions-health-check" + ] + }, + { + "group": "MEMORY", "pages": [ "api-reference/memory/get-agent-memories", "api-reference/memory/get-room-memories", @@ -181,7 +180,7 @@ ] }, { - "group": "Rooms", + "group": "ROOMS", "pages": [ "api-reference/rooms/create-a-room", "api-reference/rooms/get-room-details", @@ -191,14 +190,14 @@ ] }, { - "group": "Media", + "group": "MEDIA", "pages": [ "api-reference/media/upload-media-for-agent", "api-reference/media/upload-media-to-channel" ] }, { - "group": "Logs", + "group": "LOGS", "pages": [ "api-reference/logs/get-agent-logs", "api-reference/logs/get-system-logs", @@ -208,7 +207,7 @@ ] }, { - "group": "System", + "group": "SYSTEM", "pages": [ "api-reference/system/basic-health-check", "api-reference/system/health-check-endpoint", @@ -222,7 +221,7 @@ ] }, { - "group": "WebSocket", + "group": "WEBSOCKET", "pages": ["api-reference/websocket/socketio-real-time-connection"] } ] diff --git a/installation.mdx b/installation.mdx index 65e7a22..9249f47 100644 --- a/installation.mdx +++ b/installation.mdx @@ -176,7 +176,3 @@ You should see the version number of the installed CLI. - Windows: Run Git Bash as Administrator - -## Next Steps - -Continue to the [Quickstart](/quickstart) to build and run your first project in a few commands. diff --git a/quickstart.mdx b/quickstart.mdx index 6f99046..cbb0bf5 100644 --- a/quickstart.mdx +++ b/quickstart.mdx @@ -110,21 +110,4 @@ Let's create a project with our default Eliza character that can chat and take a ``` - Follow the Quickstart steps again carefully - - -## What's Next? - - - - Learn how to modify your agent's personality, add knowledge, and configure settings - - - Create projects with multiple agents working together - - - Learn how to test your elizaOS agents and plugins - - - Ready to go live? Learn how to deploy your elizaOS agent to production - - \ No newline at end of file + \ No newline at end of file diff --git a/runtime/messaging.mdx b/runtime/messaging.mdx index 441b46a..90500d4 100644 --- a/runtime/messaging.mdx +++ b/runtime/messaging.mdx @@ -559,7 +559,7 @@ class SocketIOService extends Service { ## What's Next? - + Build persistent conversations on messaging diff --git a/runtime/models.mdx b/runtime/models.mdx index 3cca074..c921d00 100644 --- a/runtime/models.mdx +++ b/runtime/models.mdx @@ -710,7 +710,7 @@ async function modelCallWithFallback( Stream model responses in real-time - + Use models in conversations diff --git a/runtime/providers.mdx b/runtime/providers.mdx index 2f2f0dd..4738e57 100644 --- a/runtime/providers.mdx +++ b/runtime/providers.mdx @@ -548,7 +548,7 @@ async function debugComposeState(runtime: IAgentRuntime, message: Memory, includ Real-time provider updates - + See providers in conversational context diff --git a/runtime/services.mdx b/runtime/services.mdx index ca86130..5b70ea9 100644 --- a/runtime/services.mdx +++ b/runtime/services.mdx @@ -819,7 +819,7 @@ it('should notify through multiple channels', async () => { Build real-time messaging services - + Manage stateful conversations diff --git a/runtime/sessions.mdx b/runtime/sessions-api.mdx similarity index 68% rename from runtime/sessions.mdx rename to runtime/sessions-api.mdx index c27274a..2482b63 100644 --- a/runtime/sessions.mdx +++ b/runtime/sessions-api.mdx @@ -1,6 +1,6 @@ --- -title: "Sessions" -description: "Session management architecture, implementation, and usage" +title: "Sessions API" +description: "Complete API reference, architecture, implementation, and usage guide for the Sessions messaging system" --- ## Overview @@ -1362,37 +1362,607 @@ const agentConfig = { }; ``` -## API Reference +## Complete API Reference + +The Sessions API provides a comprehensive set of endpoints for managing stateful conversations with ElizaOS agents. This reference covers all available endpoints, request/response schemas, and error handling. + +### Base URL + +``` +http://localhost:3000/api/messaging/sessions +``` + +### Authentication + +Currently, the Sessions API does not require authentication. In production environments, you should implement appropriate authentication mechanisms. ### Endpoints -- **POST** `/api/messaging/sessions` - Create a new session -- **GET** `/api/messaging/sessions/:sessionId` - Get session information -- **POST** `/api/messaging/sessions/:sessionId/messages` - Send a message -- **GET** `/api/messaging/sessions/:sessionId/messages` - Get message history -- **POST** `/api/messaging/sessions/:sessionId/renew` - Manually renew session -- **PATCH** `/api/messaging/sessions/:sessionId/timeout` - Update timeout configuration -- **POST** `/api/messaging/sessions/:sessionId/heartbeat` - Send heartbeat to keep alive -- **DELETE** `/api/messaging/sessions/:sessionId` - End session -- **GET** `/api/messaging/sessions` - List all active sessions (admin) -- **GET** `/api/messaging/sessions/health` - Health check endpoint +#### Create Session + +Creates a new conversation session with an agent. + + + Create a new session with configurable timeout policies + + +**Request Body:** + +```typescript +interface CreateSessionRequest { + agentId: string; // UUID of the agent + userId: string; // UUID of the user + metadata?: { // Optional session metadata + [key: string]: any; + }; + timeoutConfig?: { // Optional timeout configuration + timeoutMinutes?: number; // 5-1440 minutes + autoRenew?: boolean; // Default: true + maxDurationMinutes?: number; // Maximum session duration + warningThresholdMinutes?: number; // When to warn about expiration + }; +} +``` + +**Response (201 Created):** + +```typescript +interface CreateSessionResponse { + sessionId: string; + agentId: string; + userId: string; + createdAt: Date; + metadata: object; + expiresAt: Date; + timeoutConfig: SessionTimeoutConfig; +} +``` + +**Example:** + +```bash +curl -X POST http://localhost:3000/api/messaging/sessions \ + -H "Content-Type: application/json" \ + -d '{ + "agentId": "123e4567-e89b-12d3-a456-426614174000", + "userId": "987f6543-e21b-12d3-a456-426614174000", + "timeoutConfig": { + "timeoutMinutes": 30, + "autoRenew": true + } + }' +``` + +--- + +#### Get Session Information + +Retrieves detailed information about a session including its current status. + + + Get session details and current status + + +**Response (200 OK):** + +```typescript +interface SessionInfoResponse { + sessionId: string; + agentId: string; + userId: string; + createdAt: Date; + lastActivity: Date; + metadata: object; + expiresAt: Date; + timeoutConfig: SessionTimeoutConfig; + renewalCount: number; + timeRemaining: number; // Milliseconds until expiration + isNearExpiration: boolean; // True if within warning threshold +} +``` + +**Errors:** +- `404 Not Found` - Session does not exist +- `410 Gone` - Session has expired + +--- + +#### Send Message + +Sends a message within a session. Automatically renews the session if auto-renewal is enabled. + + + Send a message in the conversation + + +**Request Body:** + +```typescript +interface SendMessageRequest { + content: string; // Message content (max 4000 chars) + metadata?: { // Optional message metadata + [key: string]: any; + }; + attachments?: any[]; // Optional attachments +} +``` + +**Response (201 Created):** + +```typescript +interface MessageResponse { + id: string; + content: string; + authorId: string; + createdAt: Date; + metadata: object; + sessionStatus?: { // Session renewal information + expiresAt: Date; + renewalCount: number; + wasRenewed: boolean; + isNearExpiration: boolean; + }; +} +``` + +**Errors:** +- `400 Bad Request` - Invalid content or metadata +- `404 Not Found` - Session not found +- `410 Gone` - Session expired + +--- + +#### Get Messages + +Retrieves messages from a session with pagination support. + + + Retrieve conversation history + + +**Query Parameters:** + +```typescript +interface GetMessagesQuery { + limit?: string; // Number of messages (1-100, default: 50) + before?: string; // Timestamp for pagination (older messages) + after?: string; // Timestamp for pagination (newer messages) +} +``` + +**Response (200 OK):** + +```typescript +interface GetMessagesResponse { + messages: SimplifiedMessage[]; + hasMore: boolean; + cursors?: { + before?: number; // Use for getting older messages + after?: number; // Use for getting newer messages + }; +} + +interface SimplifiedMessage { + id: string; + content: string; + authorId: string; + isAgent: boolean; + createdAt: Date; + metadata: { + thought?: string; // Agent's internal reasoning + actions?: string[]; // Actions taken by agent + [key: string]: any; + }; +} +``` + +--- + +#### Renew Session + +Manually renews a session to extend its expiration time. + + + Manually extend session lifetime + + +**Response (200 OK):** + +```typescript +interface SessionInfoResponse { + sessionId: string; + agentId: string; + userId: string; + createdAt: Date; + lastActivity: Date; + expiresAt: Date; + timeoutConfig: SessionTimeoutConfig; + renewalCount: number; + timeRemaining: number; + isNearExpiration: boolean; +} +``` + +**Errors:** +- `404 Not Found` - Session not found +- `410 Gone` - Session expired +- `422 Unprocessable Entity` - Cannot renew (max duration reached) + +--- + +#### Update Timeout Configuration + +Updates the timeout configuration for an active session. + + + Modify session timeout settings + + +**Request Body:** + +```typescript +interface SessionTimeoutConfig { + timeoutMinutes?: number; // 5-1440 minutes + autoRenew?: boolean; + maxDurationMinutes?: number; + warningThresholdMinutes?: number; +} +``` + +**Response (200 OK):** + +Returns updated `SessionInfoResponse` + +**Errors:** +- `400 Bad Request` - Invalid timeout configuration +- `404 Not Found` - Session not found +- `410 Gone` - Session expired + +--- + +#### Send Heartbeat + +Keeps a session alive and optionally renews it if auto-renewal is enabled. + + + Keep session alive with periodic heartbeat + + +**Response (200 OK):** + +Returns `SessionInfoResponse` with updated expiration information. + +**Errors:** +- `404 Not Found` - Session not found +- `410 Gone` - Session expired + +--- -## What's Next? +#### Delete Session + +Explicitly ends and removes a session. + + + End and delete a session + + +**Response (200 OK):** + +```typescript +{ + success: true, + message: "Session {sessionId} deleted successfully" +} +``` + +**Errors:** +- `404 Not Found` - Session not found + +--- + +#### List Sessions (Admin) + +Lists all active sessions in the system. This is an administrative endpoint. + + + List all active sessions + + +**Response (200 OK):** + +```typescript +interface ListSessionsResponse { + sessions: SessionInfoResponse[]; + total: number; + stats: { + totalSessions: number; + activeSessions: number; + expiredSessions: number; + }; +} +``` + +--- + +#### Health Check + +Checks the health status of the Sessions API service. + + + Check service health + + +**Response (200 OK):** + +```typescript +interface HealthCheckResponse { + status: 'healthy' | 'degraded' | 'unhealthy'; + activeSessions: number; + timestamp: string; + expiringSoon?: number; // Sessions near expiration + invalidSessions?: number; // Corrupted sessions detected + uptime?: number; // Service uptime in seconds +} +``` + +### Error Responses + +All error responses follow a consistent format: + +```typescript +interface ErrorResponse { + error: string; // Error message + details?: { // Additional context + [key: string]: any; + }; +} +``` + +#### Common Error Codes + +| Status Code | Error Type | Description | +|------------|------------|-------------| +| `400` | Bad Request | Invalid input parameters or request body | +| `404` | Not Found | Session or resource not found | +| `410` | Gone | Session has expired | +| `422` | Unprocessable Entity | Operation cannot be completed (e.g., max duration reached) | +| `500` | Internal Server Error | Unexpected server error | + +#### Error Classes + +The API uses specific error classes for different scenarios: + +- `SessionNotFoundError` - Session does not exist +- `SessionExpiredError` - Session has exceeded its timeout +- `SessionCreationError` - Failed to create session +- `AgentNotFoundError` - Specified agent not found +- `InvalidUuidError` - Invalid UUID format +- `MissingFieldsError` - Required fields missing +- `InvalidContentError` - Message content validation failed +- `InvalidMetadataError` - Metadata exceeds size limit +- `InvalidPaginationError` - Invalid pagination parameters +- `InvalidTimeoutConfigError` - Invalid timeout configuration +- `SessionRenewalError` - Cannot renew session +- `MessageSendError` - Failed to send message + +### Rate Limiting + +Currently, the Sessions API does not implement rate limiting. In production, you should implement appropriate rate limiting based on your requirements. + +### WebSocket Events + +When using WebSocket connections alongside the Sessions API, the following events are available: + +```typescript +// Join a session for real-time updates +socket.emit('join', { roomId: sessionId }); + +// Listen for new messages +socket.on('messageBroadcast', (message) => { + // Handle new message +}); + +// Session expiration warning +socket.on('sessionExpirationWarning', (data) => { + // data.sessionId, data.minutesRemaining +}); + +// Session expired +socket.on('sessionExpired', (data) => { + // data.sessionId, data.expiredAt +}); + +// Session renewed +socket.on('sessionRenewed', (data) => { + // data.sessionId, data.expiresAt, data.renewalCount +}); +``` + +### Environment Variables + +Configure the Sessions API behavior using these environment variables: + +| Variable | Default | Description | +|----------|---------|-------------| +| `SESSION_DEFAULT_TIMEOUT_MINUTES` | 30 | Default session timeout | +| `SESSION_MIN_TIMEOUT_MINUTES` | 5 | Minimum allowed timeout | +| `SESSION_MAX_TIMEOUT_MINUTES` | 1440 | Maximum allowed timeout (24 hours) | +| `SESSION_MAX_DURATION_MINUTES` | 720 | Maximum total session duration (12 hours) | +| `SESSION_WARNING_THRESHOLD_MINUTES` | 5 | When to trigger expiration warning | +| `SESSION_CLEANUP_INTERVAL_MINUTES` | 5 | How often to clean expired sessions | +| `CLEAR_SESSIONS_ON_SHUTDOWN` | false | Clear all sessions on server shutdown | + +### SDK Examples + +#### JavaScript/TypeScript Client + +```typescript +class SessionsAPIClient { + constructor(private baseUrl: string = 'http://localhost:3000') {} + + async createSession(agentId: string, userId: string, config?: SessionTimeoutConfig) { + const response = await fetch(`${this.baseUrl}/api/messaging/sessions`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ agentId, userId, timeoutConfig: config }) + }); + + if (!response.ok) throw new Error(`Failed to create session: ${response.status}`); + return response.json(); + } + + async sendMessage(sessionId: string, content: string, metadata?: object) { + const response = await fetch( + `${this.baseUrl}/api/messaging/sessions/${sessionId}/messages`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ content, metadata }) + } + ); + + if (!response.ok) throw new Error(`Failed to send message: ${response.status}`); + return response.json(); + } + + async getMessages(sessionId: string, limit = 50, before?: number) { + const params = new URLSearchParams({ limit: limit.toString() }); + if (before) params.append('before', before.toString()); + + const response = await fetch( + `${this.baseUrl}/api/messaging/sessions/${sessionId}/messages?${params}` + ); + + if (!response.ok) throw new Error(`Failed to get messages: ${response.status}`); + return response.json(); + } + + async renewSession(sessionId: string) { + const response = await fetch( + `${this.baseUrl}/api/messaging/sessions/${sessionId}/renew`, + { method: 'POST' } + ); + + if (!response.ok) throw new Error(`Failed to renew session: ${response.status}`); + return response.json(); + } + + async sendHeartbeat(sessionId: string) { + const response = await fetch( + `${this.baseUrl}/api/messaging/sessions/${sessionId}/heartbeat`, + { method: 'POST' } + ); + + if (!response.ok) throw new Error(`Heartbeat failed: ${response.status}`); + return response.json(); + } +} +``` + +#### Python Client + +```python +import requests +from typing import Optional, Dict, Any + +class SessionsAPIClient: + def __init__(self, base_url: str = "http://localhost:3000"): + self.base_url = base_url + self.session = requests.Session() + + def create_session( + self, + agent_id: str, + user_id: str, + timeout_config: Optional[Dict[str, Any]] = None + ) -> Dict[str, Any]: + """Create a new session with an agent.""" + payload = { + "agentId": agent_id, + "userId": user_id + } + + if timeout_config: + payload["timeoutConfig"] = timeout_config + + response = self.session.post( + f"{self.base_url}/api/messaging/sessions", + json=payload + ) + response.raise_for_status() + return response.json() + + def send_message( + self, + session_id: str, + content: str, + metadata: Optional[Dict[str, Any]] = None + ) -> Dict[str, Any]: + """Send a message in a session.""" + payload = {"content": content} + + if metadata: + payload["metadata"] = metadata + + response = self.session.post( + f"{self.base_url}/api/messaging/sessions/{session_id}/messages", + json=payload + ) + response.raise_for_status() + return response.json() + + def get_messages( + self, + session_id: str, + limit: int = 50, + before: Optional[int] = None, + after: Optional[int] = None + ) -> Dict[str, Any]: + """Retrieve messages from a session.""" + params = {"limit": str(limit)} + + if before: + params["before"] = str(before) + if after: + params["after"] = str(after) + + response = self.session.get( + f"{self.base_url}/api/messaging/sessions/{session_id}/messages", + params=params + ) + response.raise_for_status() + return response.json() + + def renew_session(self, session_id: str) -> Dict[str, Any]: + """Manually renew a session.""" + response = self.session.post( + f"{self.base_url}/api/messaging/sessions/{session_id}/renew" + ) + response.raise_for_status() + return response.json() + + def send_heartbeat(self, session_id: str) -> Dict[str, Any]: + """Send a heartbeat to keep session alive.""" + response = self.session.post( + f"{self.base_url}/api/messaging/sessions/{session_id}/heartbeat" + ) + response.raise_for_status() + return response.json() +``` + +## Next Steps - - Build plugins that extend sessions + + Add real-time capabilities to your sessions - - - Create session-based plugins + + Understand ElizaOS runtime architecture - - - Review runtime architecture + + Build custom plugins for your agents - - - Deep dive into conversation memory + + Build plugins that extend sessions diff --git a/what-you-can-build.mdx b/what-you-can-build.mdx index 9045a0a..67ce10d 100644 --- a/what-you-can-build.mdx +++ b/what-you-can-build.mdx @@ -89,47 +89,4 @@ description: 'Here are some popular agent types to get you started. Build anythi Lead Generatorplugin-browser+4}> Scrapes B2B data, enriches prospect information, prioritizes leads by fit and intent - - -## What's Next? - -**Ready to get started coding?** Jump into building your first agent. - - - - - - - - \ No newline at end of file