/** * `DatabaseAdapter` — the abstract base every concrete persistence adapter * (plugin-sql's Drizzle adapters, `SQLiteDatabaseAdapter`, …) extends to * satisfy the {@link IDatabaseAdapter} contract declared in `types/database.ts`. * It carries no storage logic: it re-declares the batch-first CRUD surface * (arrays in, arrays out) as `abstract` methods, so a missing override is a * compile-time error, and centralizes the JSDoc adapter authors see in their * IDE. Optional domains an adapter need not support (connector-account and * OAuth-flow storage) default here to throwing a clear adapter-level error * rather than silently succeeding. */ import type { AccessContext } from "./types/access-context.js"; import type { Agent } from "./types/agent.js"; import type { AppendConnectorAccountAuditEventParams, AtomicMemoryPublicationParams, AtomicMemoryPublicationResult, ConnectorAccountAuditEventRecord, ConnectorAccountCredentialRefRecord, ConnectorAccountRecord, ConsumeOAuthFlowStateParams, CreateOAuthFlowStateParams, DeleteConnectorAccountCredentialRefsParams, DeleteConnectorAccountParams, DeleteOAuthFlowStateParams, DocumentCompareAndSwapParams, DocumentDeleteParams, DocumentDirectGrantUpdateParams, DocumentFragmentQueryParams, DocumentGetQueryParams, DocumentListQueryParams, DocumentListQueryResult, DocumentMutationResult, DocumentRevisionReplaceParams, GetConnectorAccountCredentialRefParams, GetConnectorAccountParams, GetOAuthFlowStateParams, IDatabaseAdapter, ListConnectorAccountCredentialRefsParams, ListConnectorAccountsParams, Log, LogBody, LogInventoryRow, MessageContentPublicationParams, MessageContentPublicationResult, MessageContentRangeReadParams, MessageContentRangeReadResult, MessageSearchHit, OAuthFlowRecord, ParticipantUpdateFields, ParticipantUserState, PatchOp, SetConnectorAccountCredentialRefParams, UpdateOAuthFlowStateParams, UpsertConnectorAccountParams, WorldMetadataCompareAndSwapParams, WorldMetadataMutationResult } from "./types/database.js"; import type { Component, Entity, Participant, Relationship, Room, World } from "./types/environment.js"; import type { Memory, MemoryMetadata } from "./types/memory.js"; import type { PairingAllowlistEntry, PairingAllowlistQuery, PairingRequest, PairingRequestQuery } from "./types/pairing.js"; import type { JsonValue, Metadata, UUID } from "./types/primitives.js"; import type { Task } from "./types/task.js"; type PaginationParams = { limit?: number; offset?: number; }; /** Enforces the shared pagination contract for entity-query boundaries. */ export declare function validateQueryEntitiesPagination(params: PaginationParams): void; /** Enforces the portable pagination contract for task-query boundaries. */ export declare function validateTaskQueryPagination(params: PaginationParams): void; /** * Compares UUID-backed memory ids in the same order as PostgreSQL's `uuid` * type. PostgreSQL normalizes hexadecimal case before ordering, so in-memory * adapters and cross-table merges must do the same instead of using the * locale-sensitive `localeCompare`; otherwise a valid uppercase UUID can be * skipped or repeated at a keyset boundary. */ export declare function compareMemoryIds(left: string, right: string): number; /** Matches PostgreSQL's ascending `(created_at, id)` task-query order. */ export declare function compareTasksForQuery(left: Task, right: Task): number; /** * Abstract base class for database adapters. * * WHY this exists as an abstract class (not just the IDatabaseAdapter interface): * - Provides a single place for JSDoc on every abstract method, so adapter * authors get documentation in their IDE without reading the interface. * - Serves as the compile-time contract: if you extend this class and miss * a method, TypeScript tells you immediately. * - Contains no persistence logic. Concrete adapters (plugin-sql's Drizzle * adapters, SQLiteDatabaseAdapter, etc.) own storage behavior; unsupported * optional domains throw a clear adapter-level error. * * All CRUD methods are batch-first (arrays in, arrays out). See * IDatabaseAdapter in types/database.ts for the full design rationale. * * @template DB - The type of the database instance (e.g. PgDatabase, BetterSQLite3Database). * @abstract */ export declare abstract class DatabaseAdapter implements IDatabaseAdapter { abstract readonly messageContentSegmentCapability: 1; abstract publishMessageContentSegments(params: MessageContentPublicationParams): Promise; abstract readMessageContentRange(params: MessageContentRangeReadParams): Promise; compareAndSwapMemoryPublication(_params: AtomicMemoryPublicationParams): Promise; /** * Exact document-store contract implemented by every first-class adapter. * Version 4 adds storage-enforced direct-grant replacement. */ abstract readonly documentListQueryCapability: 4; abstract queryDocuments(params: DocumentListQueryParams): Promise; abstract getDocument(params: DocumentGetQueryParams): Promise; abstract queryDocumentFragments(params: DocumentFragmentQueryParams): Promise; abstract compareAndSwapDocument(params: DocumentCompareAndSwapParams): Promise; abstract updateDocumentDirectGrants(params: DocumentDirectGrantUpdateParams): Promise; /** * Optional world-metadata CAS capability. This concrete fail-closed default * preserves compatibility for existing third-party subclasses while role * writes refuse to fall back to an unsafe whole-world overwrite. */ compareAndSwapWorldMetadata(params: WorldMetadataCompareAndSwapParams): Promise; abstract replaceDocumentRevision(params: DocumentRevisionReplaceParams): Promise; abstract deleteDocumentWithSnapshot(params: DocumentDeleteParams): Promise; /** * The database instance. */ db: DB; /** * Initialize the database adapter. * @param config - Optional configuration object * @returns A Promise that resolves when initialization is complete. */ abstract initialize(config?: Record): Promise; /** * Run plugin schema migrations for all registered plugins * @param plugins Array of plugins with their schemas * @param options Migration options (verbose, force, dryRun, etc.) * @returns A Promise that resolves when migrations are complete. */ abstract runPluginMigrations(plugins: Array<{ name: string; schema?: Record; }>, options?: { verbose?: boolean; force?: boolean; dryRun?: boolean; }): Promise; /** * Check if the database connection is ready. * @returns A Promise that resolves to true if the database is ready, false otherwise. */ abstract isReady(): Promise; /** * Optional close method for the database adapter. * @returns A Promise that resolves when closing is complete. */ abstract close(): Promise; /** * Retrieves a connection to the database. * @returns A Promise that resolves to the database connection. */ abstract getConnection(): Promise; /** * Execute a callback within a database transaction. * InMemory adapter runs the callback directly without atomicity guarantees. * @param options.entityContext When set (Postgres + ENABLE_DATA_ISOLATION), runs under RLS for this entity. */ abstract transaction(callback: (tx: IDatabaseAdapter) => Promise, options?: { entityContext?: UUID; }): Promise; abstract getEntitiesForRooms(roomIds: UUID[], includeComponents?: boolean): Promise; /** * Creates a new entities in the database. * @param entities The entity objects to create. * @returns A Promise that resolves when the account creation is complete. */ abstract createEntities(entities: Entity[]): Promise; /** * Upsert entities (insert or update by ID). * @param entities - An array of entities to upsert (ID required for each). * @returns A Promise that resolves when the upsert is complete. */ abstract upsertEntities(entities: Entity[]): Promise; /** * Search entities by name substring match. * @param params - Search parameters (query, agentId, limit). * @returns A Promise that resolves to matching entities. */ abstract searchEntitiesByName(params: { query: string; agentId: UUID; limit?: number; }): Promise; /** * Get entities by exact name match. * @param params - Lookup parameters (names array, agentId). * @returns A Promise that resolves to matching entities. */ abstract getEntitiesByNames(params: { names: string[]; agentId: UUID; }): Promise; /** * Query entities by component type and optional JSONB data filter. * @param params.entityContext RLS only: when set (Postgres + ENABLE_DATA_ISOLATION), query runs under this entity context. WHY optional: adapters that don't support RLS accept and ignore it. */ abstract queryEntities(params: { componentType?: string; componentDataFilter?: Record; agentId?: UUID; entityIds?: UUID[]; worldId?: UUID; limit?: number; offset?: number; includeAllComponents?: boolean; entityContext?: UUID; }): Promise; abstract getComponentsByNaturalKeys(keys: Array<{ entityId: UUID; type: string; worldId?: UUID; sourceEntityId?: UUID; }>): Promise<(Component | null)[]>; abstract getComponentsForEntities(entityIds: UUID[], worldId?: UUID, sourceEntityId?: UUID): Promise; abstract getEntitiesByIds(entityIds: UUID[]): Promise; abstract updateEntities(entities: Entity[]): Promise; abstract deleteEntities(entityIds: UUID[]): Promise; abstract createComponents(components: Component[]): Promise; abstract getComponentsByIds(componentIds: UUID[]): Promise; abstract updateComponents(components: Component[]): Promise; abstract deleteComponents(componentIds: UUID[]): Promise; /** * Upsert components (insert or update by natural key). * @param options.entityContext When set (Postgres + ENABLE_DATA_ISOLATION), runs under RLS for this entity. */ abstract upsertComponents(components: Component[], options?: { entityContext?: UUID; }): Promise; abstract patchComponents(updates: Array<{ componentId: UUID; ops: PatchOp[]; }>, options?: { entityContext?: UUID; }): Promise; /** * Retrieves memories based on the specified parameters. * @param params An object containing parameters for the memory retrieval. * @returns A Promise that resolves to an array of Memory objects. */ abstract getMemories(params: { entityId?: UUID; authorEntityIds?: UUID[]; agentId?: UUID; limit?: number; count?: number; offset?: number; cursor?: { createdAt: number; id: UUID; }; unique?: boolean; tableName: string; start?: number; end?: number; roomId?: UUID; excludeRoomIds?: UUID[]; worldId?: UUID; metadata?: Record; textContains?: string; orderBy?: "createdAt"; orderDirection?: "asc" | "desc"; includeEmbedding?: boolean; accessContext?: AccessContext; }): Promise; abstract getMemoriesByRoomIds(params: { roomIds: UUID[]; tableName: string; limit?: number; offset?: number; textContains?: string; includeEmbedding?: boolean; accessContext?: AccessContext; }): Promise; /** * Corpus-wide full-text + trigram message search across a set of rooms, * ranked in the store rather than after a recency-truncated window. */ abstract searchMessages(params: { roomIds: UUID[]; query: string; tableName?: string; limit?: number; offset?: number; since?: number; until?: number; accessContext?: AccessContext; }): Promise; /** * Retrieves multiple memories by their IDs * @param memoryIds Array of UUIDs of the memories to retrieve * @param tableName Optional table name to filter memories by type * @returns Promise resolving to array of Memory objects */ abstract getMemoriesByIds(memoryIds: UUID[], tableName?: string): Promise; /** * Retrieves cached embeddings based on the specified query parameters. * @param params An object containing parameters for the embedding retrieval. * @returns A Promise that resolves to an array of objects containing embeddings and levenshtein scores. */ abstract getCachedEmbeddings({ query_table_name, query_threshold, query_input, query_field_name, query_field_sub_name, query_match_count, }: { query_table_name: string; query_threshold: number; query_input: string; query_field_name: string; query_field_sub_name: string; query_match_count: number; }): Promise<{ embedding: number[]; levenshtein_score: number; }[]>; /** * Retrieves logs based on the specified parameters. * @param params An object containing parameters for the log retrieval. * @returns A Promise that resolves to an array of Log objects. */ abstract getLogs(params: { entityId?: UUID; roomId?: UUID; type?: string; limit?: number; offset?: number; }): Promise; abstract getLogInventory(params: { excludeTypes?: readonly string[]; }): Promise; abstract createLogs(params: Array<{ body: LogBody; entityId: UUID; roomId: UUID; type: string; createdAt?: Date; }>): Promise; abstract getLogsByIds(logIds: UUID[]): Promise; abstract updateLogs(logs: Array<{ id: UUID; updates: Partial; }>): Promise; abstract deleteLogs(logIds: UUID[]): Promise; /** * Searches for memories based on embeddings and other specified parameters. * @param params An object containing parameters for the memory search. * @returns A Promise that resolves to an array of Memory objects. */ abstract searchMemories(params: { tableName: string; embedding: number[]; /** Omit returned vectors only; similarity still uses the stored embedding. */ includeEmbedding?: boolean; /** Narrow eligible rooms before ranking and pagination. */ excludeRoomIds?: UUID[]; match_threshold?: number; count?: number; limit?: number; offset?: number; unique?: boolean; query?: string; roomId?: UUID; worldId?: UUID; entityId?: UUID; accessContext?: AccessContext; }): Promise; abstract createMemories(memories: Array<{ memory: Memory; tableName: string; unique?: boolean; }>): Promise; abstract updateMemories(memories: Array & { id: UUID; metadata?: MemoryMetadata; }>): Promise; /** * Upsert memories (insert or update by ID). * @param options.entityContext When set (Postgres + ENABLE_DATA_ISOLATION), runs under RLS for this entity. */ abstract upsertMemories(memories: Array<{ memory: Memory; tableName: string; }>, options?: { entityContext?: UUID; }): Promise; abstract updateMemoryEmbedding(update: import("./types/database.js").MemoryEmbeddingUpdate): Promise; abstract deleteMemories(memoryIds: UUID[]): Promise; abstract deleteAllMemories(roomIds: UUID[], tableName: string): Promise; abstract countMemories(params: { roomIds?: UUID[]; unique?: boolean; tableName?: string; entityId?: UUID; agentId?: UUID; metadata?: Record; }): Promise; /** * Retrieves all worlds for an agent. * @returns A Promise that resolves to an array of World objects. */ abstract getAllWorlds(): Promise; abstract getWorldsByIds(worldIds: UUID[]): Promise; abstract createWorlds(worlds: World[]): Promise; abstract deleteWorlds(worldIds: UUID[]): Promise; abstract updateWorlds(worlds: World[]): Promise; /** * Upsert worlds (insert or update by ID). * @param worlds - An array of worlds to upsert (ID required for each). * @returns A Promise that resolves when the upsert is complete. */ abstract upsertWorlds(worlds: World[]): Promise; /** * Retrieves the room ID for a given room, if it exists. * @param roomIds The UUIDs of the rooms to retrieve. * @returns A Promise that resolves to the room ID or null if not found. */ abstract getRoomsByIds(roomIds: UUID[]): Promise; abstract deleteRoomsByWorldIds(worldIds: UUID[]): Promise; abstract getRoomsForParticipants(entityIds: UUID[]): Promise; abstract getRoomsByWorlds(worldIds: UUID[], limit?: number, offset?: number): Promise; /** * Creates new rooms in the database. * @param rooms Array of Room objects to create. * @returns A Promise that resolves to the UUIDs of the created rooms. */ abstract createRooms(rooms: Room[]): Promise; /** * Upsert rooms (insert or update by ID). * @param rooms - An array of rooms to upsert (ID required for each). * @returns A Promise that resolves when the upsert is complete. */ abstract upsertRooms(rooms: Room[]): Promise; /** * Creates room participants for the specified entities. * @param entityIds The UUIDs of the entities to add as participants. * @param roomId The UUID of the room to which the entities will be added. * @returns A Promise that resolves to the UUIDs of the created participant records. */ abstract createRoomParticipants(entityIds: UUID[], roomId: UUID): Promise; /** WHY boolean: Callers need success/failure for error handling/UX; see IDatabaseAdapter in types/database.ts. */ abstract deleteParticipants(participants: Array<{ entityId: UUID; roomId: UUID; }>): Promise; abstract updateParticipants(participants: Array<{ entityId: UUID; roomId: UUID; updates: ParticipantUpdateFields; }>): Promise; abstract updateRooms(rooms: Room[]): Promise; abstract deleteRooms(roomIds: UUID[]): Promise; abstract getParticipantsForEntities(entityIds: UUID[]): Promise; abstract getParticipantsForRooms(roomIds: UUID[]): Promise; abstract areRoomParticipants(pairs: Array<{ roomId: UUID; entityId: UUID; }>): Promise; abstract getParticipantUserStates(pairs: Array<{ roomId: UUID; entityId: UUID; }>): Promise; abstract updateParticipantUserStates(updates: Array<{ roomId: UUID; entityId: UUID; state: ParticipantUserState; }>): Promise; abstract getRelationshipsByPairs(pairs: Array<{ sourceEntityId: UUID; targetEntityId: UUID; }>): Promise<(Relationship | null)[]>; abstract getRelationships(params: { entityIds?: UUID[]; tags?: string[]; limit?: number; offset?: number; }): Promise; abstract createRelationships(relationships: Array<{ sourceEntityId: UUID; targetEntityId: UUID; tags?: string[]; metadata?: Metadata; }>): Promise; abstract getRelationshipsByIds(relationshipIds: UUID[]): Promise; abstract updateRelationships(relationships: Relationship[]): Promise; abstract deleteRelationships(relationshipIds: UUID[]): Promise; /** * Retrieves all agents from the database. * @returns A Promise that resolves to an array of Agent objects. */ abstract getAgents(): Promise[]>; abstract getAgentsByIds(agentIds: UUID[]): Promise; abstract createAgents(agents: Partial[]): Promise; /** WHY boolean: Success/failure signal for callers; see IDatabaseAdapter in types/database.ts. */ abstract updateAgents(updates: Array<{ agentId: UUID; agent: Partial; }>): Promise; abstract upsertAgents(agents: Partial[]): Promise; /** WHY boolean: Success/failure signal for callers; see IDatabaseAdapter in types/database.ts. */ abstract deleteAgents(agentIds: UUID[]): Promise; abstract countAgents(): Promise; abstract cleanupAgents(): Promise; /** * Ensures an embedding dimension exists in the database. * @param dimension The dimension to ensure exists. * @returns A Promise that resolves when the embedding dimension has been ensured to exist. */ abstract ensureEmbeddingDimension(dimension: number): Promise; abstract clearEmbeddingsOutsideActiveDimension(): Promise; abstract getCaches(keys: string[]): Promise>; abstract setCaches(entries: Array<{ key: string; value: T; }>): Promise; abstract deleteCaches(keys: string[]): Promise; compareAndSetCache(_key: string, _expected: unknown, _replacement: T): Promise; /** * Retrieves tasks based on specified parameters. * @param params Object containing optional roomId and tags to filter tasks * @returns Promise resolving to an array of Task objects */ abstract getTasks(params: { roomId?: UUID; worldId?: UUID; tags?: string[]; entityId?: UUID; agentIds: UUID[]; limit?: number; offset?: number; }): Promise; /** * Retrieves a specific task by its name. * @param name The name of the task to retrieve * @returns Promise resolving to the Task object if found, null otherwise */ abstract getTasksByName(name: string): Promise; abstract createTasks(tasks: Task[]): Promise; abstract getTasksByIds(taskIds: UUID[]): Promise; /** * Optional-adapter compatibility default. Official adapters override this * with a storage-atomic transition; returning false fails closed. */ updatePendingTask(_id: UUID, _task: Partial): Promise; abstract updateTasks(updates: Array<{ id: UUID; task: Partial; }>): Promise; abstract deleteTasks(taskIds: UUID[]): Promise; abstract getMemoriesByWorldId(params: { worldIds?: UUID[]; limit?: number; tableName?: string; }): Promise; abstract getPairingRequests(queries: PairingRequestQuery[]): Promise; abstract getPairingAllowlists(queries: PairingAllowlistQuery[]): Promise; abstract createPairingRequests(requests: PairingRequest[]): Promise; abstract updatePairingRequests(requests: PairingRequest[]): Promise; abstract deletePairingRequests(ids: UUID[]): Promise; abstract createPairingAllowlistEntries(entries: PairingAllowlistEntry[]): Promise; abstract updatePairingAllowlistEntries(entries: PairingAllowlistEntry[]): Promise; abstract deletePairingAllowlistEntries(ids: UUID[]): Promise; protected unsupportedConnectorAccountStorage(): never; listConnectorAccounts(_params?: ListConnectorAccountsParams): Promise; getConnectorAccount(_params: GetConnectorAccountParams): Promise; upsertConnectorAccount(_params: UpsertConnectorAccountParams): Promise; deleteConnectorAccount(_params: DeleteConnectorAccountParams): Promise; setConnectorAccountCredentialRef(_params: SetConnectorAccountCredentialRefParams): Promise; getConnectorAccountCredentialRef(_params: GetConnectorAccountCredentialRefParams): Promise; listConnectorAccountCredentialRefs(_params: ListConnectorAccountCredentialRefsParams): Promise; deleteConnectorAccountCredentialRefs(_params: DeleteConnectorAccountCredentialRefsParams): Promise; appendConnectorAccountAuditEvent(_params: AppendConnectorAccountAuditEventParams): Promise; createOAuthFlowState(_params: CreateOAuthFlowStateParams): Promise; consumeOAuthFlowState(_params: ConsumeOAuthFlowStateParams): Promise; getOAuthFlowState(_params: GetOAuthFlowStateParams): Promise; updateOAuthFlowState(_params: UpdateOAuthFlowStateParams): Promise; deleteOAuthFlowState(_params: DeleteOAuthFlowStateParams): Promise; } export {};