Session Management API
Below is a REST API documentation for managing Session data in your application. The Session entity references a single conversation or session with a specific agent (and optionally includes user name/email).
Note: There is an API client plus example available on: https://github.com/CatchTheTornado/open-agents-builder-client and https://github.com/CatchTheTornado/open-agents-builder-example
1. Overview
The Session endpoints let you:
- List all sessions (with optional filters).
- Create a session or retrieve an existing one by ID (via
/api/exec/session/[id]
). - Delete a session by ID.
By default, certain fields (userName
, userEmail
, messages
) may be encrypted at rest if a storageKey
is provided. The server automatically encrypts/decrypts these fields.
2. Data Schema (SessionDTO)
From sessionDTOSchema
in src/data/dto.ts
:
export const sessionDTOSchema = z.object({ id: z.string().min(1), // A unique session identifier agentId: z.string().min(1), // The agent to which this session belongs userName: z.string().optional().nullable(), userEmail: z.string().optional().nullable(), acceptTerms: z.string().optional().nullable(), messages: z.string().optional().nullable(), // JSON-serialized chat data promptTokens: z.number().optional().nullable(), completionTokens: z.number().optional().nullable(), createdAt: z.string().default(() => getCurrentTS()), updatedAt: z.string().default(() => getCurrentTS()), finalizedAt: z.string().optional().nullable(),});export type SessionDTO = z.infer<typeof sessionDTOSchema>;
Key Fields:
id
: The session’s primary key (string).agentId
: Ties this session to a specific agent.userName
,userEmail
: Potentially sensitive data, often encrypted.messages
: A JSON string representing chat messages or conversation steps.promptTokens
,completionTokens
: Keep track of usage for LLM tokens.acceptTerms
: If user accepted terms of use.createdAt
&updatedAt
: Timestamps.finalizedAt
: If set, indicates session is no longer active.
3. Endpoints
3.1 GET /api/session
-
Description
Returns all sessions, optionally filtered by query parameters:id
: filter by session IDagentId
: filter by specific agent.
Internally uses
genericGET<SessionDTO>
andServerSessionRepository.findAll()
. -
cURL Example:
Terminal window curl -X GET \"https://app.openagentsbuilder.com/api/session?agentId=agent-123" \-H "Authorization: Bearer <YOUR_API_KEY>" \-H "database-id-hash: <YOUR_DATABASE_ID_HASH>" -
Success Response (HTTP 200):
[{"id": "session-001","agentId": "agent-123","userName": "Alice","userEmail": "[email protected]","acceptTerms": "true","messages": "[{\"role\":\"user\",\"content\":\"Hello\"}]","promptTokens": 34,"completionTokens": 76,"createdAt": "2025-03-21T10:00:00.000Z","updatedAt": "2025-03-21T10:05:00.000Z","finalizedAt": null},...]Each session is a decrypted
SessionDTO
. -
Error Response (e.g., 499 or 500):
{"message": "Server error details","status": 499}
Using the TypeScript API Client
Below is an example illustrating how to retrieve session data using the official open-agents-builder-client:
import { OpenAgentsBuilderClient } from "open-agents-builder-client";
const client = new OpenAgentsBuilderClient({ apiKey: "YOUR_API_KEY", databaseIdHash: "YOUR_DATABASE_ID_HASH"});
async function listSessions() { // Optionally pass filtering parameters, e.g. { agentId: "agent-123" } const sessions = await client.session.listSessions({ agentId: "agent-123" }); console.log("Sessions:", sessions);}
listSessions();
3.2 DELETE /api/session/[id]
-
Description
Deletes the session record whoseid
matches[id]
.
Also logs an audit entry (eventName: 'deleteSession'
). -
cURL Example:
Terminal window curl -X DELETE \"https://app.openagentsbuilder.com/api/session/session-001" \-H "Authorization: Bearer <YOUR_API_KEY>" \-H "database-id-hash: <YOUR_DATABASE_ID_HASH>" -
Success Response (HTTP 200) if found and deleted:
{"message": "Data deleted successfully!","status": 200} -
Not Found (HTTP 400 if no record is deleted):
{"message": "Data not found!","status": 400} -
Missing ID (HTTP 400 if
[id]
is invalid):{"message": "Invalid request, no id provided within request url","status": 400}
Using the TypeScript API Client
import { OpenAgentsBuilderClient } from "open-agents-builder-client";
const client = new OpenAgentsBuilderClient({ apiKey: "YOUR_API_KEY", databaseIdHash: "YOUR_DATABASE_ID_HASH"});
async function deleteSessionById(sessionId: string) { await client.session.deleteSession(sessionId); console.log(`Session ${sessionId} deleted.`);}
// Usage exampledeleteSessionById("session-001");
3.3 POST /api/exec/session/[id]
-
Description
This endpoint is slightly different. It creates a new session (with the providedid
), or returns an existing session if it’s already present. -
Request Body:
{"agentId": "agent-123","userName": "Alice","userEmail": "[email protected]","acceptTerms": "true"}agentId
: RequireduserName
&userEmail
: Required in this example.acceptTerms
: A string that can be"true"
or"false"
.
-
Behavior:
- If a session with
[id]
already exists, return:{ "message": "Session already exists", "data": { "id": "session-XYZ" } } - If it does not exist, create it (encrypting
userName
,userEmail
ifstorageKey
is set) and return:{ "message": "Session created", "data": { "id": "session-XYZ" }, "status": 200 }
- If a session with
-
cURL Example:
Terminal window curl -X POST \"https://app.openagentsbuilder.com/api/exec/session/session-XYZ" \-H "Authorization: Bearer <YOUR_API_KEY>" \-H "database-id-hash: <YOUR_DATABASE_ID_HASH>" \-H "Content-Type: application/json" \-d '{"agentId": "agent-123","userName": "Alice","userEmail": "[email protected]","acceptTerms": "true"}' -
Success (200 OK):
{"message": "Session created","data": { "id": "session-XYZ" },"status": 200}Or if it already exists:
{"message": "Session already exists","data": { "id": "session-XYZ" }} -
Error (400 if required fields missing):
{"message": "Invalid request, missing required fields","status": 400}or if
[id]
is missing in the URL.
Using the TypeScript API Client
By default, the
open-agents-builder-client
does not provide a direct method forPOST /api/exec/session/[id]
. You can either use a custom method or fallback tofetch
/axios
for this particular endpoint.
Example (using fetch
):
async function createOrGetSession(sessionId: string) { const response = await fetch(`https://app.openagentsbuilder.com/api/exec/session/${sessionId}`, { method: "POST", headers: { "Authorization": `Bearer ${process.env.OPEN_AGENTS_BUILDER_API_KEY}`, "database-id-hash": "YOUR_DATABASE_ID_HASH", "Content-Type": "application/json" }, body: JSON.stringify({ agentId: "agent-123", userName: "Alice", userEmail: "[email protected]", acceptTerms: "true" }) });
if (!response.ok) { throw new Error(`Error creating or retrieving session: ${response.status} ${response.statusText}`); }
const data = await response.json(); console.log("Session response:", data);}
createOrGetSession("session-XYZ");
4. Encryption Details
In ServerSessionRepository
, the fields userName
, userEmail
, and messages
are automatically encrypted/decrypted:
if (this.encUtils) { if (item.userName) item.userName = await this.encUtils.encrypt(item.userName); if (item.userEmail) item.userEmail = await this.encUtils.encrypt(item.userEmail); if (item.messages) item.messages = await this.encUtils.encrypt(item.messages);}
- Database will store ciphertext for these fields if a
storageKey
is set. - Responses return the fields decrypted.
5. Searching & Pagination for Sessions
You may see a queryAll(agentId, { limit, offset, orderBy, query })
method in ServerSessionRepository
. If you want to expose a paginated endpoint (similar to how Agent
or Result
endpoints do it), you can create a route such as:
GET /api/agent/[agentId]/session?limit=10&offset=0&orderBy=updatedAt&query=alice
limit
&offset
: numeric pagination.orderBy
: can beuserName
,userEmail
,createdAt
, orupdatedAt
. Defaults toupdatedAt
descending.query
: partial match for (encrypted)userEmail
,userName
, or sessionid
.
Such an endpoint would return a structure:
{ "rows": [ { ... SessionDTO ... }, ... ], "total": 25, "limit": 10, "offset": 0, "orderBy": "updatedAt", "query": "alice"}
(Implementation details vary depending on how you set up the route.)
6. Typical Use Cases
- User starts a new conversation – A front-end calls
POST /api/exec/session/[sessionId]
with user details and an agent ID. - List all sessions – A back-end or admin panel calls
GET /api/session
, optionally filtering byagentId
. - Delete a session – Admin or system calls
DELETE /api/session/[sessionId]
if it’s no longer needed. - View session data – The system or admin might retrieve sessions or decrypt messages for analysis.
7. Error Handling
- 400 Bad Request: Missing or invalid parameters, e.g.,
[id]
not provided, or required fields absent. - 499 / 500: Internal server or encryption errors, or unexpected conditions.
- 401 / 403: If authorization or
database-id-hash
headers are incorrect or missing.
Error responses typically have a JSON body with a "message"
and "status"
.
8. Summary
GET /api/session
: Retrieve all sessions (filter withagentId
,id
).DELETE /api/session/[id]
: Remove a session by ID.POST /api/exec/session/[id]
: Create a new session (if none exists) or return an existing one.- Encryption:
userName
,userEmail
,messages
can be stored encrypted if astorageKey
is provided. - Auditing: Deletion triggers an
auditLog
entry.
This covers the main endpoints and usage patterns for Session data. If you want paginated queries per agent, you can extend the logic with queryAll()
, similarly to the Agent
or Result
endpoints.