/** * SQLite Storage Implementation for Agent World System * * Features: * - Full implementation of StorageAPI interface for SQLite backend * - Chat metadata persistence aligned with aggregated agent-memory chat state * - Enhanced archive management with rich metadata and search capabilities * - Optimized queries with prepared statements and transactions * - Data integrity with foreign key constraints and validation * - Migration support from file-based storage * - Performance monitoring and analytics * * Enhanced Chat Features: * - Full CRUD operations for world chats with proper type safety * - Foreign key relationships ensuring data consistency * - Efficient querying with indexed columns * * Enhanced Archive Features: * - Rich archive metadata (session names, reasons, statistics) * - Content-based search across archived conversations * - Archive usage analytics and trends * - Efficient querying by date, agent, participants * - Export capabilities in various formats * * Implementation: * - Maintains compatibility with existing storage interfaces * - Uses proper async/await patterns for SQLite operations * - Implements batch operations for efficiency * - Provides transaction support for data consistency * - Includes comprehensive error handling and validation * - Complete type safety with proper TypeScript interfaces * * Recent Changes: * - 2026-03-12: Removed dormant chat snapshot reads/writes; SQLite chat metadata now matches file and memory backends. * - 2026-02-25: Fixed `listAgents` memory hydration to parse aliased `toolCalls`/`toolCallId` fields so runtime agent memory preserves persisted tool-call metadata. * - 2026-02-13: Added atomic compare-and-set chat title update helper (`updateChatNameIfCurrent`). * - 2026-02-13: Fixed migration directory resolution so Electron runtimes launched from `electron/` still run root `migrations/`. * - 2025-08-01: Added proper TypeScript types for all chat operations * - 2025-08-01: Implemented restoreFromSnapshot with atomic transactions * - 2025-08-01: Enhanced type safety removing any types * - 2025-08-06: Fixed initialization order - migration check before schema initialization * - 2025-11-02: Integrated SQL migration runner, removed legacy migrations */ import type { Database } from 'sqlite3'; import { createSQLiteSchemaContext, ArchiveMetadata, ArchiveStatistics, SQLiteConfig } from './sqlite-schema.js'; import type { World, Agent, AgentMessage, Chat, UpdateChatParams, QueuedMessage, QueueMessageStatus } from '../types.js'; /** * Enhanced archive query options */ export interface ArchiveQueryOptions { worldId?: string; agentId?: string; startDate?: Date; endDate?: Date; sessionName?: string; tags?: string[]; participants?: string[]; searchContent?: string; limit?: number; offset?: number; sortBy?: 'created_at' | 'message_count' | 'session_name'; sortOrder?: 'ASC' | 'DESC'; } /** * Archive search result */ export interface ArchiveSearchResult { archives: ArchiveInfo[]; totalCount: number; hasMore: boolean; } /** * Archive information with metadata */ export interface ArchiveInfo { id: number; agentId: string; worldId: string; sessionName?: string; archiveReason?: string; messageCount: number; startTime?: Date; endTime?: Date; participants: string[]; tags: string[]; createdAt: Date; } /** * Archive export options */ export interface ArchiveExportOptions { format: 'json' | 'csv' | 'txt' | 'markdown'; includeMetadata?: boolean; includeMessages?: boolean; compression?: 'none' | 'gzip'; } export interface SQLiteStorageContext { schemaCtx: Awaited>; db: Database; isInitialized: boolean; } export declare function createSQLiteStorageContext(config: SQLiteConfig): Promise; /** * Utility to initialize the database schema and insert a default world and agent if not present. * This is useful for first-time setup or testing. */ export declare function initializeWithDefaults(ctx: SQLiteStorageContext): Promise; export declare function saveWorld(ctx: SQLiteStorageContext, worldData: World): Promise; export declare function loadWorld(ctx: SQLiteStorageContext, worldId: string): Promise; export declare function deleteWorld(ctx: SQLiteStorageContext, worldId: string): Promise; export declare function listWorlds(ctx: SQLiteStorageContext): Promise; export declare function saveAgent(ctx: SQLiteStorageContext, worldId: string, agent: Agent): Promise; export declare function loadAgent(ctx: SQLiteStorageContext, worldId: string, agentId: string): Promise; export declare function deleteAgent(ctx: SQLiteStorageContext, worldId: string, agentId: string): Promise; export declare function listAgents(ctx: SQLiteStorageContext, worldId: string): Promise; export declare function saveAgentMemory(ctx: SQLiteStorageContext, worldId: string, agentId: string, memory: AgentMessage[]): Promise; export declare function deleteMemoryByChatId(ctx: SQLiteStorageContext, worldId: string, chatId: string): Promise; export declare function getMemory(ctx: SQLiteStorageContext, worldId: string, chatId: string): Promise; export declare function saveAgentsBatch(ctx: SQLiteStorageContext, worldId: string, agents: Agent[]): Promise; export declare function loadAgentsBatch(ctx: SQLiteStorageContext, worldId: string, agentIds: string[]): Promise; export declare function validateIntegrity(ctx: SQLiteStorageContext, worldId: string, agentId?: string): Promise; export declare function repairData(ctx: SQLiteStorageContext, worldId: string, agentId?: string): Promise; export declare function saveChatData(ctx: SQLiteStorageContext, worldId: string, chat: Chat): Promise; export declare function loadChatData(ctx: SQLiteStorageContext, worldId: string, chatId: string): Promise; export declare function deleteChatData(ctx: SQLiteStorageContext, worldId: string, chatId: string): Promise; export declare function listChatHistories(ctx: SQLiteStorageContext, worldId: string): Promise; export declare function updateChatData(ctx: SQLiteStorageContext, worldId: string, chatId: string, updates: UpdateChatParams): Promise; export declare function updateChatNameIfCurrent(ctx: SQLiteStorageContext, worldId: string, chatId: string, expectedName: string, nextName: string, nextProvenance?: import('../chat-constants.js').TitleProvenance): Promise; export declare function archiveAgentMemory(ctx: SQLiteStorageContext, worldId: string, agentId: string, memory: AgentMessage[], metadata?: ArchiveMetadata): Promise; export declare function searchArchives(ctx: SQLiteStorageContext, options: ArchiveQueryOptions): Promise; export declare function getArchiveStatistics(ctx: SQLiteStorageContext, worldId: string, agentId?: string): Promise; export declare function exportArchive(ctx: SQLiteStorageContext, archiveId: number, options: ArchiveExportOptions): Promise; export declare function close(ctx: SQLiteStorageContext): Promise; export declare function getQueuedMessages(ctx: SQLiteStorageContext, worldId: string, chatId: string): Promise; export declare function addQueuedMessage(ctx: SQLiteStorageContext, worldId: string, chatId: string, messageId: string, content: string, sender: string): Promise; export declare function updateMessageQueueStatus(ctx: SQLiteStorageContext, messageId: string, status: QueueMessageStatus): Promise; export declare function incrementQueueMessageRetry(ctx: SQLiteStorageContext, messageId: string): Promise; export declare function resetQueueMessageForRetry(ctx: SQLiteStorageContext, messageId: string): Promise; export declare function removeQueuedMessage(ctx: SQLiteStorageContext, messageId: string): Promise; export declare function cancelQueuedMessages(ctx: SQLiteStorageContext, worldId: string, chatId: string): Promise; export declare function recoverSendingMessages(ctx: SQLiteStorageContext): Promise; export declare function deleteQueueForChat(ctx: SQLiteStorageContext, worldId: string, chatId: string): Promise; export declare function getDatabaseStats(ctx: SQLiteStorageContext): Promise<{ worldCount: number; agentCount: number; activeMemoryCount: number; archiveCount: number; archivedMessageCount: number; databaseSize: number; }>;