Initializes the storage adapter.
This should:
Must be called before any other methods.
Resolves when initialization is complete
If initialization fails (connection errors, invalid config, etc.)
const storage = new SqlStorageAdapter(config);
await storage.initialize(); // Sets up database schema
Closes the storage adapter and releases resources.
This should:
Call during application shutdown for graceful cleanup.
Resolves when cleanup is complete
process.on('SIGTERM', async () => {
await storage.close();
process.exit(0);
});
Creates a new conversation record.
The conversation object to create
The created conversation (may include defaults)
If conversation with same ID already exists or validation fails
const conversation = await storage.createConversation({
id: uuidv4(),
userId: 'user-123',
agentId: 'agent-coding',
createdAt: Date.now(),
lastActivity: Date.now(),
title: 'New coding project'
});
Retrieves a conversation by its ID.
The unique conversation identifier
The conversation or null if not found
const conv = await storage.getConversation('conv-123');
if (conv) {
console.log('Found:', conv.title);
}
Updates an existing conversation's metadata.
Only provided fields will be updated. Omitted fields remain unchanged.
The conversation to update
Fields to update
The updated conversation
If conversation doesn't exist
// Update title and last activity
const updated = await storage.updateConversation('conv-123', {
title: 'Renamed conversation',
lastActivity: Date.now()
});
Deletes a conversation and all its messages.
Warning: This is a destructive operation that cannot be undone. Consider implementing soft deletes in production.
The conversation to delete
True if deleted, false if not found
const deleted = await storage.deleteConversation('conv-123');
if (deleted) {
console.log('Conversation deleted successfully');
}
Lists all conversations for a specific user.
Results are typically ordered by lastActivity (most recent first).
The user whose conversations to retrieve
Optional options: { Optional filtering/pagination
Optional limit?: numberMaximum conversations to return
Optional offset?: numberNumber of conversations to skip
Optional agentFilter by specific agent
Array of conversations
// Get user's 20 most recent conversations
const conversations = await storage.listConversations('user-123', {
limit: 20
});
// Get conversations for specific agent
const codingConvs = await storage.listConversations('user-123', {
agentId: 'agent-coding'
});
Stores a new message in a conversation.
Note: This also updates the parent conversation's lastActivity timestamp.
The message to store
The stored message
If conversation doesn't exist or validation fails
await storage.storeMessage({
id: uuidv4(),
conversationId: 'conv-123',
role: 'user',
content: 'Explain async/await',
timestamp: Date.now()
});
Retrieves a single message by its ID.
The unique message identifier
The message or null if not found
const msg = await storage.getMessage('msg-456');
if (msg) {
console.log(`[${msg.role}]: ${msg.content}`);
}
Retrieves all messages for a conversation with optional filtering.
This is the primary method for loading conversation history.
The conversation to query
Optional options: IMessageQueryOptionsQuery options for filtering/pagination
Array of messages matching criteria
// Get all messages (oldest first)
const allMessages = await storage.getMessages('conv-123');
// Get last 50 messages (newest first)
const recent = await storage.getMessages('conv-123', {
limit: 50,
order: 'desc'
});
// Get only assistant responses from last hour
const assistantRecent = await storage.getMessages('conv-123', {
roles: ['assistant'],
since: Date.now() - 3600000
});
Deletes a specific message.
Note: This does NOT update the conversation's lastActivity timestamp.
The message to delete
True if deleted, false if not found
const deleted = await storage.deleteMessage('msg-456');
Deletes all messages in a conversation.
Warning: Destructive operation. Consider soft deletes in production.
The conversation whose messages to delete
Number of messages deleted
const deletedCount = await storage.deleteMessagesForConversation('conv-123');
console.log(`Deleted ${deletedCount} messages`);
Counts total messages in a conversation.
Useful for pagination and UI indicators.
The conversation to count
Total message count
const count = await storage.getMessageCount('conv-123');
console.log(`This conversation has ${count} messages`);
Calculates total token usage for a conversation.
Sums up all message usage statistics.
The conversation to analyze
Aggregated token usage
const usage = await storage.getConversationTokenUsage('conv-123');
console.log(`Total tokens: ${usage.totalTokens}`);
console.log(`Cost estimate: $${usage.totalTokens * 0.00001}`);
Core storage adapter interface for AgentOS persistence.
Implementations of this interface provide the actual storage mechanism (SQL database, NoSQL, in-memory, etc.) while AgentOS remains storage-agnostic.
Design Principles:
Lifecycle:
initialize()to set up database/schemaclose()when shutting down (optional cleanup)IStorageAdapter
Example