import { type ReportedError } from "./errors.js"; import type { FetchLike } from "./media/fetch.js"; import type { ExecutionTrace, PromptOptimizationRuntimeHooks, ScoreSignal } from "./prompt-optimization.js"; import { ChatPreHandlerRegistry } from "./runtime/chat-pre-handler-registry.js"; import { RuntimeConnectorRegistry } from "./runtime/connector-registry.js"; import { ContextRegistry } from "./runtime/context-registry.js"; import { RuntimeEmbeddings } from "./runtime/embeddings.js"; import { RuntimePipelineHooks } from "./runtime/pipeline-hooks.js"; import type { ResponseHandlerEvaluator } from "./runtime/response-handler-evaluators.js"; import { type ResponseHandlerFieldEvaluator, ResponseHandlerFieldRegistry } from "./runtime/response-handler-fields.js"; import { RoomHandlerQueue } from "./runtime/room-handler-queue.js"; import { TurnControllerRegistry } from "./runtime/turn-controller.js"; import type { ConfidentialInferenceAuthority } from "./security/confidential-inference.js"; import { type SecretFragment, type SecretFragmentTaintProfile } from "./security/fragment-redaction.js"; import { type ProcessingPolicy } from "./security/processing-policy.js"; import type { AccessContext } from "./types/access-context.js"; import type { Agent, Character } from "./types/agent.js"; import type { ChatPreHandler, ChatPreHandlerContext, ChatPreHandlerResult } from "./types/chat-pre-handler.js"; import type { Action, ActionMode, ActionResult, HandlerCallback, Provider } from "./types/components.js"; import type { AgentContext } from "./types/contexts.js"; import type { AppendConnectorAccountAuditEventParams, ConnectorAccountAuditEventRecord, ConnectorAccountCredentialRefRecord, ConnectorAccountRecord, ConsumeOAuthFlowStateParams, CreateOAuthFlowStateParams, DeleteConnectorAccountCredentialRefsParams, DeleteConnectorAccountParams, DeleteOAuthFlowStateParams, GetConnectorAccountCredentialRefParams, GetConnectorAccountParams, GetOAuthFlowStateParams, IDatabaseAdapter, ListConnectorAccountCredentialRefsParams, ListConnectorAccountsParams, Log, LogBody, LogInventoryRow, MessageSearchHit, OAuthFlowRecord, PatchOp, SetConnectorAccountCredentialRefParams, UpdateOAuthFlowStateParams, UpsertConnectorAccountParams } from "./types/database.js"; import type { Component, Entity, Participant, Relationship, Room, World } from "./types/environment.js"; import type { RegisteredEvaluator } from "./types/evaluator.js"; import { type EventHandler, type EventPayload, type EventPayloadMap } from "./types/events.js"; import type { Memory, MemoryMetadata } from "./types/memory.js"; import type { IMessageService } from "./types/message-service.js"; import type { IMessagingAdapter } from "./types/messaging.js"; import { type GenerateTextOptions, type GenerateTextResult, type ModelHandler, type ModelParamsMap, type ModelRegistrationInfo, type ModelRegistrationMetadata, type ModelResultMap, type ModelTypeName } from "./types/model.js"; import type { PairingAllowlistEntry, PairingChannel, PairingRequest } from "./types/pairing.js"; import type { Plugin, PluginOwnership, RemotePluginInstallOptions, RemotePluginInstanceHandle, RuntimeEventStorage, ServiceClass } from "./types/plugin.js"; import { ChannelType, type Content, type JsonValue, type Metadata, type UUID } from "./types/primitives.js"; import type { IAgentRuntime, RuntimeStopOptions } from "./types/runtime.js"; import { type SearchCategoryEnumerationOptions, type SearchCategoryLookupOptions, type SearchCategoryRegistration } from "./types/search.js"; import { type Service, type ServiceTypeName } from "./types/service.js"; import type { RuntimeSettings } from "./types/settings.js"; import type { State } from "./types/state.js"; import type { Task, TaskMetadataPatch, TaskMetadataPatchOutcome, TaskWorker } from "./types/task.js"; /** Owns one agent’s public runtime identity, registries, settings, and initialization. Model dispatch, structured prompts, provider composition, service startup, embeddings, and data mutations have dedicated owners that share this runtime’s state. Settings remain agent-scoped, and embedding width stays pinned to the provider that passed the boot probe. */ export { EMBEDDING_STORE_ACCEPT_MODEL_SETTING, EMBEDDING_STORE_IDENTITY_CACHE_KEY, EmbeddingDimensionProbeError, type EmbeddingProbeAttempt, type EmbeddingStoreIdentity, } from "./runtime/embeddings.js"; export { NoModelProviderConfiguredError } from "./runtime/model-policy.js"; interface GetMemoriesParams { entityId?: UUID; authorEntityIds?: UUID[]; agentId?: UUID; roomId?: UUID; excludeRoomIds?: UUID[]; limit?: number; count?: number; offset?: number; cursor?: { createdAt: number; id: UUID; }; unique?: boolean; tableName: string; start?: number; end?: number; worldId?: UUID; metadata?: Record; textContains?: string; orderBy?: "createdAt"; orderDirection?: "asc" | "desc"; includeEmbedding?: boolean; accessContext?: AccessContext; } export declare class AgentRuntime implements IAgentRuntime { #private; static readonly ownerToolExecutionObserverVersion: 1; readonly ownerToolExecutionObserverVersion: 1; ownerToolExecutionObserver?: IAgentRuntime["ownerToolExecutionObserver"]; private readonly dataMutations; private readonly retirement; private readonly serviceLifecycle; private readonly embeddings; private readonly confidentialInference; private readonly modelDispatch; private readonly pipelineHooks; private sendHandlers; private readonly promptTraces; structuredPromptExecutor?: IAgentRuntime["dynamicPromptExecFromState"]; /** The runtime invokes request preparation before each resolved model handler. */ readonly supportsModelAttemptPreparation = true; readonly agentId: UUID; readonly runtimeInstanceId: UUID; readonly character: Character; adapter: IDatabaseAdapter; readonly actions: Action[]; readonly providers: Provider[]; readonly evaluators: RegisteredEvaluator[]; readonly responseHandlerEvaluators: ResponseHandlerEvaluator[]; readonly responseHandlerFieldEvaluators: ResponseHandlerFieldEvaluator[]; /** Chat pre-handlers, registered from `Plugin.chatPreHandlers`. */ readonly chatPreHandlerRegistry: ChatPreHandlerRegistry; readonly responseHandlerFieldRegistry: ResponseHandlerFieldRegistry; readonly turnControllers: TurnControllerRegistry; readonly roomHandlerQueue: RoomHandlerQueue; readonly plugins: Plugin[]; /** * Per-runtime context registry seeded with first-party context definitions * during `_initializeCore`. Plugins may register additional contexts before * Stage 1 runs. */ readonly contexts: ContextRegistry; unloadPlugin: (pluginName: string) => Promise; reloadPlugin: (plugin: Plugin) => Promise; applyPluginConfig: (pluginName: string, config: Record) => Promise; getPluginOwnership: (pluginName: string) => PluginOwnership | null; getAllPluginOwnership: () => PluginOwnership[]; events: RuntimeEventStorage; stateCache: Map; private readonly providerState; private static readonly READ_MEMO_TTL_MS; private static readonly READ_MEMO_MAX_ENTRIES; private static readonly ROOM_MESSAGES_MEMO_MIN_WINDOW; private readonly roomReadMemo; private readonly roomMessagesMemo; private invalidateTurnEntityDetails; private invalidateTurnIdentityClusters; readonly fetch: FetchLike; services: Map; private serviceTypes; /** * Bounded ring of failures surfaced via {@link reportError}. Read * by the RECENT_ERRORS provider and the owner-escalation threshold. Oldest * entries drop once the cap is exceeded. */ private reportedErrors; private static readonly REPORTED_ERROR_RING_CAP; /** Re-entrancy latch so a failure inside reportError stays warn-only (J7). */ private inReportError; models: Map, object | JsonValue>[]>; private secretRedactionProfileSignature; private secretRedactionProfileRevision; private taskWorkers; private searchCategories; private eventHandlers; /** Optional DPE-side prompt optimization I/O (merge, registry, baseline/failure traces). */ private promptOptimizationHooks; private allAvailablePlugins; private characterPlugins; private actionPlanningOption?; private llmModeOption?; private checkShouldRespondOption?; logger: import("./logging.js").Logger; enableAutonomy: boolean; private settings; private servicePromiseHandlers; private servicePromises; /** Full settlement of each type's current parallel startup set, used by teardown. */ private startingServices; private startingServiceClasses; private serviceInstancesByClass; private failedServiceClasses; private serviceRegistrationStatus; initPromise: Promise; private initResolver; private currentRunId?; private currentRoomId?; messageService: IMessageService | null; /** Set when stop() has completed service teardown. */ private stopped; /** Set permanently at the first stop request, before any drain can yield. */ private stopRequested; /** Records an initialization attempt that released waiters by failing. */ private initializationFailed; /** Typed cancellation boundary for deferred plugin/service startup. */ private readonly stopController; /** The active stop attempt; concurrent callers await the same teardown. */ private stopPromise; private strictStopPromise; constructor(opts: { /** Measured host authority; never populated from character or client settings. */ confidentialInference?: ConfidentialInferenceAuthority; /** * Host processing admission for every model attempt and action effect. * Absent means no admission is consulted. Never populated from character * or client settings; it cannot be replaced after construction. */ processingPolicy?: ProcessingPolicy; conversationLength?: number; agentId?: UUID; /** Host-persisted installation identity. Omitted only by ephemeral/test runtimes. */ runtimeInstanceId?: UUID; /** Optional character configuration. If not provided, an anonymous character is created. */ character?: Character; plugins?: Plugin[]; fetch?: FetchLike; /** Database adapter supplied by a persistence plugin or the host. WHY: Caller owns DB lifecycle; no plugin registration race; single source of truth. */ adapter?: IDatabaseAdapter; settings?: RuntimeSettings; allAvailablePlugins?: Plugin[]; /** * Log level for this runtime. Defaults to "error". * Valid levels: "trace", "debug", "info", "warn", "error", "fatal" */ logLevel?: "trace" | "debug" | "info" | "warn" | "error" | "fatal"; /** * Enable action planning mode for multi-action execution. * When true (default), agent can plan and execute multiple actions per response. * When false, agent executes only a single action per response (performance optimization * useful for game situations where state updates with every action). */ actionPlanning?: boolean; /** * LLM mode for overriding model selection. * - "DEFAULT": Use the model type specified in the useModel call (no override) * - "SMALL": Override all text generation model calls to use TEXT_SMALL * - "LARGE": Override all text generation model calls to use TEXT_LARGE * * This is useful for cost optimization (force SMALL) or quality (force LARGE). * While not recommended for production, it can be a fast way to make the agent run cheaper. */ llmMode?: import("./types/model.js").LLMModeType; /** * Enable or disable the shouldRespond evaluation. * When true (default), the agent evaluates whether to respond to each message. * When false, the agent always responds (ChatGPT mode) - useful for direct chat interfaces. */ checkShouldRespond?: boolean; /** * Enable autonomy capabilities for autonomous agent operation. * When true, the agent can operate autonomously with its own thinking loop, * communicating with admin users and running continuous background processing. * Can be enabled at construction time or lazily via settings. */ enableAutonomy?: boolean; }); private warnOnDuplicateServiceTypeRegistration; /** * Create a new run ID for tracking a sequence of model calls */ createRunId(): UUID; /** * Start a new run for tracking prompts * @param roomId Optional room ID to associate logs with this conversation */ startRun(roomId?: UUID): UUID; /** * End the current run */ endRun(): void; /** * Get the current run ID (creates one if it doesn't exist) */ getCurrentRunId(): UUID; private isSecretSwapEnabled; private createSecretSwapSession; private isPiiSwapEnabled; /** * Build the turn's PII pseudonymization session. The * recognizer is the composite of the runtime's built-in regex recognizer * (street addresses) and — if a plugin registered the * `PII_ENTITY_RECOGNIZER_SERVICE` — the local NER model (person/org/location). * With no model plugin present the layer runs regex-only: degraded coverage, * but still never leaks what it does detect. The agent's own name is added to * the blocklist so the model's identity is never pseudonymized. */ private createPiiSwapSession; registerPipelineHook(...args: Parameters): ReturnType; unregisterPipelineHook(...args: Parameters): ReturnType; applyPipelineHooks(...args: Parameters): ReturnType; registerPlugin(plugin: T): Promise; private _registerPlugin; getAllServices(): Map; /** * Stops all started services and clears runtime caches/handlers. * For full teardown (including DB/adapter connection), call close() after stop(). */ stop(options?: RuntimeStopOptions): Promise; private _stopAndDrain; private _stopBestEffort; private _stopAfterAdmissionCordon; private _stopServices; /** Initializes plugins, adapter readiness, and runtime services. Hosts own provisioning and embedding setup. */ initialize(options?: { skipMigrations?: boolean; }): Promise; private _initializeCore; /** * Fail-loud scan for the owner-private disclosure regression class: any world * whose `ownership.ownerId` (or an OWNER-role grant) is a non-UUID value — the * bare-snowflake shape that makes resolveCanonicalOwnerId return null and * denies owner-private recall with `owner_mismatch`. Logs each offender * loudly and reports one aggregated error; it is diagnostic, not fatal. */ assertResolvableWorldOwners(): Promise; registerDatabaseAdapter(adapter: IDatabaseAdapter): void; runPluginMigrations(): Promise; getConnection(): Promise; setSetting(key: string, value: string | boolean | null, secret?: boolean): void; private getCharacterEnvSetting; private getRuntimeSettingValue; getSetting(key: string): string | boolean | number | null; getConversationLength(): number; /** * Check if action planning mode is enabled. * * When enabled (default), the agent can plan and execute multiple actions per response. * When disabled, the agent executes only a single action per response - a performance * optimization useful for game situations where state updates with every action. * * Priority: constructor option > character setting ACTION_PLANNING > default (true) */ isActionPlanningEnabled(): boolean; /** * Get the LLM mode for model selection override. * * - `DEFAULT`: Use the model type specified in the useModel call (no override) * - `SMALL`: Override all text generation model calls to use TEXT_SMALL * - `LARGE`: Override all text generation model calls to use TEXT_LARGE * * Priority: constructor option > character setting LLM_MODE > default (DEFAULT) */ getLLMMode(): import("./types/model.js").LLMModeType; /** * Check if the shouldRespond evaluation is enabled. * * When enabled (default: true), the agent evaluates whether to respond to each message. * When disabled, the agent always responds (ChatGPT mode) - useful for direct chat interfaces. * * Priority: constructor option > character setting CHECK_SHOULD_RESPOND > default (true) */ isCheckShouldRespondEnabled(): boolean; getOptimizationDir(): string; registerPromptOptimizationHooks(hooks: PromptOptimizationRuntimeHooks | null): void; getPromptOptimizationHooks(): PromptOptimizationRuntimeHooks | null; resolveProviderModelString(resolvedModelType: string, optionsModel?: string, effectiveModelId?: string): string; recordPromptTrace(trace: ExecutionTrace): void; purgePromptTraces(): void; enrichTrace(runId: string, signal: ScoreSignal): void; getActiveTrace(runId: string): ExecutionTrace | undefined; getActiveTracesForRun(runId: string): ExecutionTrace[]; deleteActiveTrace(runId: string): void; deleteActiveTraceById(traceId: string): void; /** * Get the messaging adapter if available * * WHY: Messaging functionality is optional (only SQL adapters support it). * Client plugins check this before using messaging features. * * @returns IMessagingAdapter if the current adapter implements it, null otherwise */ getMessagingAdapter(): IMessagingAdapter | null; /** Resolves component-name collisions. First registration wins unless direct registration declares override; collisions warn and explicit replacements log at info level. */ private resolveComponentCollision; registerProvider(provider: Provider): void; registerAction(action: Action): void; /** Register a chat pre-handler into this runtime's registry. */ registerChatPreHandler(handler: ChatPreHandler): void; registerChatPreHandlers(handlers: readonly ChatPreHandler[]): void; unregisterChatPreHandler(id: string): void; /** * Drain registered chat pre-handlers by priority before normal action * processing; the first non-null result short-circuits the turn. */ drainChatPreHandlers(ctx: ChatPreHandlerContext): Promise; registerEvaluator(evaluator: RegisteredEvaluator): void; unregisterEvaluator(name: string): boolean; registerResponseHandlerEvaluator(evaluator: ResponseHandlerEvaluator): void; unregisterResponseHandlerEvaluator(name: string): boolean; registerResponseHandlerFieldEvaluator(evaluator: ResponseHandlerFieldEvaluator): void; unregisterResponseHandlerFieldEvaluator(name: string): boolean; /** * Abort the active turn for `roomId`. Convenience wrapper for * `turnControllers.abortTurn`. Returns true if a turn was aborted. */ abortTurn(roomId: string, reason: string): boolean; unregisterAction(name: string): boolean; getAllActions(): Action[]; getActionResults(messageId: UUID): ActionResult[]; /** * Run actions whose `mode` matches the given hook position. The runtime * fires this from fixed places in the message pipeline (see * services/message.ts). DURING modes execute handlers in parallel; all * other hook modes run sequentially in `modePriority` ascending order. * CONTEXT hooks are gated by `selectedContexts` overlapping the action's * `contexts`. */ runActionsByMode(mode: ActionMode, message: Memory, state?: State, options?: { didRespond?: boolean; callback?: HandlerCallback; responses?: Memory[]; selectedContexts?: readonly AgentContext[]; }): Promise; ensureConnections(entities: Entity[], rooms: Room[], source: string, world: World): Promise; ensureConnection(params: { entityId: UUID; roomId: UUID; roomName?: string; worldId?: UUID; worldName?: string; userName?: string; name?: string; source?: string; type?: ChannelType | string; channelId?: string; serverId?: string; messageServerId?: UUID; userId?: UUID; metadata?: Record; }): Promise; ensureParticipantInRoom(entityId: UUID, roomId: UUID): Promise; getParticipantsForEntity(entityId: UUID): Promise; getParticipantsForEntities(entityIds: UUID[]): Promise; getParticipantsForRoom(roomId: UUID): Promise; getParticipantsForRooms(roomIds: UUID[]): Promise; isRoomParticipant(roomId: UUID, entityId: UUID): Promise; areRoomParticipants(pairs: Array<{ roomId: UUID; entityId: UUID; }>): Promise; addParticipant(entityId: UUID, roomId: UUID): Promise; createRoomParticipants(entityIds: UUID[], roomId: UUID): Promise; /** Ensures a world exists while preserving persisted metadata and revision. */ ensureWorldExists({ id, name, messageServerId, metadata }: World): Promise; /** * Ensure the existence of a room. * * WHY upsert: Eliminates race condition where concurrent connection attempts * (e.g., Discord bot receiving messages in same channel simultaneously) could * both try to create the same room. Upsert is atomic. */ ensureRoomExists({ id, name, source, type, channelId, serverId, messageServerId, worldId, metadata, }: Room): Promise; composeState(...args: Parameters): ReturnType; /** Starts every pending implementation in parallel and waits for the full set. */ private _ensureServiceStarted; /** * RuntimeServiceLifecycle starts every service through this entry, which * plugin-lifecycle wraps to attribute start-time registrations to their plugin. */ private _runServiceStart; /** @internal Plugin unload stops through the same single-flight stop as shutdown. */ _stopServiceOnce(serviceType: string, service: Service): Promise; /** Returns the service instance or null. Synchronous lookup from the services map. */ getService(serviceName: ServiceTypeName | string): T | null; /** * Type-safe service getter that ensures the correct service type is returned * @template T - The expected service class type * @param serviceName - The service type name * @returns The service instance with proper typing, or null if not found */ getTypedService(serviceName: ServiceTypeName | string): T | null; /** * Get all services of a specific type * @template T - The expected service class type * @param serviceName - The service type name * @returns Array of service instances with proper typing */ getServicesByType(serviceName: ServiceTypeName | string): T[]; /** * Get all registered service types, including lazy-registered services * that have not started. * @returns Array of registered service type names */ getRegisteredServiceTypes(): ServiceTypeName[]; /** * Check if a service type is registered; its class may still be awaiting * startup. * @param serviceType - The service type to check * @returns true if the service is registered */ hasService(serviceType: ServiceTypeName | string): boolean; /** * Get the registration status of a service * @param serviceType - The service type to check * @returns the current registration status */ getServiceRegistrationStatus(serviceType: ServiceTypeName | string): "pending" | "registering" | "registered" | "failed" | "unknown"; getLifecycleState(): "initializing" | "running" | "failed" | "stopping" | "stopped"; getStopSignal(): AbortSignal; /** * Get service health information * @returns Object containing service health status */ getServiceHealth(): Record; registerService(serviceDef: ServiceClass): Promise; private _createServiceResolver; getServiceLoadPromise(serviceType: ServiceTypeName | string): Promise; registerModel(modelType: ModelTypeName | string, handler: (runtime: IAgentRuntime, params: Record) => Promise, provider: string, priority?: number, metadata?: ModelRegistrationMetadata): void; /** * Handler-free snapshot of every registered model handler, sorted by * priority (descending) then registration order within each model type — * the same order `getModel`/`useModel` select in. Exposes the private * `models` map as metadata so hosts and observers can render a routing * table or seed a mirror without touching handler functions. Pair with the * {@link EventType.MODEL_REGISTERED} event to stay live. */ getModelRegistrations(): ModelRegistrationInfo[]; /** * The provider name that served the most recent successful `useModel` call * for the given model type, or `undefined` if no such call has completed * (so callers can fail-closed rather than fabricate a provider). Lets the * trajectory stage recorders in `services/message.ts` name the real provider * that answered the messageHandler / factsAndRelationships call instead of * the hardcoded `"default"` literal. */ getLastResolvedModelProvider(modelType: ModelTypeName | string): string | undefined; getModel(modelType: ModelTypeName | string): ((runtime: IAgentRuntime, params: Record) => Promise) | undefined; useModel(modelType: T, params: ModelParamsMap[T], provider?: string): Promise; /** * Simplified text generation with optional character context. */ generateText(input: string, options?: GenerateTextOptions): Promise; dynamicPromptExecFromState(args: Parameters[0]): Promise | null>; registerEvent(event: T, handler: EventHandler): void; registerEvent

(event: string, handler: (params: P) => Promise): void; unregisterEvent(event: T, handler: EventHandler): void; unregisterEvent

(event: string, handler: (params: P) => Promise): void; getEvent(event: string): ((params: EventPayloadMap[keyof EventPayloadMap] | EventPayload) => Promise)[] | undefined; emitEvent(event: string | string[], params: JsonValue | object): Promise; /** * Diagnostic boundary for failures outside the action path. Logs * with a `[scope]` prefix, records the failure in the bounded ring, emits * {@link EventType.ERROR_REPORTED}, and forwards it into the * AgentEventService `"error"` stream when that service is registered. * * Self-safe: never throws. A failure inside this method (or inside an * `ERROR_REPORTED` handler it triggers) is caught and logged as a warning * without re-entering `reportError`, guarded by {@link inReportError}. * Reports from asynchronous subscribers remain recorded but never re-emit. */ reportError(scope: string, error: unknown, context?: Record): void; /** Snapshot copy of the reported-error ring (newest last). */ getRecentReportedErrors(): ReportedError[]; /** * Forward a reported error into the AgentEventService `"error"` stream when * that service is registered. Duck-typed via ServiceType.AGENT_EVENT so core * keeps no import edge to the service class. Best-effort: a missing or * throwing service is warn-only (still inside the reportError latch). */ private forwardToAgentEventStream; isEmbeddingGenerationDisabled(...args: Parameters): ReturnType; ensureEmbeddingDimension(...args: Parameters): ReturnType; registerTaskWorker(taskHandler: TaskWorker): void; getTaskWorker(name: string): TaskWorker | undefined; unregisterTaskWorker(name: string): boolean; get db(): object; init(): Promise; /** * Closes the database adapter. Call after stop() for full teardown (stops services then closes DB/connection). */ close(): Promise; /** A host that reuses this adapter's storage retains the outgoing cleanup * before publishing its first asynchronous continuation. Only this adopted * work also gates close(); ordinary fast-stop callbacks keep their budget. */ retainSharedAdapterRetirement(operation: () => Promise): Promise; getAgent(agentId: UUID): Promise; getAgents(): Promise[]>; createAgent(agent: Partial): Promise; updateAgent(agentId: UUID, agent: Partial): Promise; /** * Keeps the agent's own entity named after its character. Prompts label * speakers with `entity.names[0]`, so a rename (character PUT, CHARACTER * action, first-run) must move the new name to the front of `names`. */ private syncAgentEntityName; deleteAgent(agentId: UUID): Promise; countAgents(): Promise; cleanupAgents(): Promise; getAgentsByIds(agentIds: UUID[]): Promise; createAgents(agents: Partial[]): Promise; upsertAgents(agents: Partial[]): Promise; updateAgents(updates: Array<{ agentId: UUID; agent: Partial; }>): Promise; deleteAgents(agentIds: UUID[]): Promise; ensureAgentExists(agent: Partial): Promise; getEntityById(entityId: UUID): Promise; getEntitiesForRooms(roomIds: UUID[], includeComponents?: boolean): Promise; getEntitiesForRoom(roomId: UUID, includeComponents?: boolean): Promise; createEntity(entity: Entity): Promise; createEntities(entities: Entity[]): Promise; upsertEntities(entities: Entity[]): Promise; getComponents(entityId: UUID, worldId?: UUID, sourceEntityId?: UUID): Promise; getComponentsByNaturalKeys(keys: Array<{ entityId: UUID; type: string; worldId?: UUID; sourceEntityId?: UUID; }>): Promise<(Component | null)[]>; getComponentsForEntities(entityIds: UUID[], worldId?: UUID, sourceEntityId?: UUID): Promise; addEmbeddingToMemory(...args: Parameters): ReturnType; queueEmbeddingGeneration(...args: Parameters): ReturnType; getMemories(params: GetMemoriesParams): Promise; /** * Single-flight coalescing for the compose-time room messages-scan. Several * providers issue the same newest-first `messages` window at different * limits within one turn (RECENT_MESSAGES at conversationLength, FACTS at * 10, ATTACHMENTS at ≤50, REPLY_CONTEXT's dedupe window); one superset * fetch serves them all, sliced per caller. Only the exact newest-first * room-scoped shape is eligible — any filter, ordering, pagination, or * access-context variation falls through to the adapter untouched, so this * can narrow no query's semantics. * * Slicing is exact, not approximate: the adapter orders newest-first * (createdAt desc, id desc), so the superset's first `limit` rows are * byte-identical to a direct `limit`-bounded query. A `start` bound (the * compaction cutoff) is a pure suffix predicate on that ordering — every * row ≥ start is newer than every row < start — so filtering the superset * then slicing reproduces the adapter's start+limit result for any * requested limit ≤ the fetched window. Requests larger than the window * bypass the memo entirely rather than risk a truncated result. * * Returns null when the query shape is not eligible. */ private coalesceRoomMessagesScan; getAllMemories(): Promise; getMemoriesByIds(ids: UUID[], tableName?: string): Promise; getMemoriesByRoomIds(params: { tableName: string; roomIds: UUID[]; limit?: number; offset?: number; textContains?: string; includeEmbedding?: boolean; accessContext?: AccessContext; }): Promise; searchMessages(params: { roomIds: UUID[]; query: string; tableName?: string; limit?: number; offset?: number; since?: number; until?: number; accessContext?: AccessContext; }): Promise; clearEmbeddingsOutsideActiveDimension(...args: Parameters): ReturnType; getCachedEmbeddings(...args: Parameters): ReturnType; searchMemories(params: { embedding: number[]; /** Omit returned vectors when only message content and scores are needed. */ includeEmbedding?: boolean; query?: string; match_threshold?: number; count?: number; limit?: number; offset?: number; roomId?: UUID; /** Exclude these rooms before vector ranking and pagination. */ excludeRoomIds?: UUID[]; unique?: boolean; worldId?: UUID; entityId?: UUID; tableName: string; accessContext?: AccessContext; }): Promise; /** * Get the secrets to redact from character settings. * Returns an empty object if no secrets are configured. */ private getSecretsForRedaction; /** * Redact secrets from text content. * This prevents character secrets from appearing in outputs or memories. * * The pattern library runs even when the character configures no secrets: * default/minimal characters are exactly the ones whose reported errors and * provider texts can still carry credential-shaped values (API keys, Bearer * tokens, URI userinfo). `redactWithSecrets` treats an empty secrets map as * a no-op for the literal pass, and its pattern regexps are compiled once at * module load, so the always-on scrub costs one pattern sweep per call. */ redactSecrets(text: string): string; locateConfiguredSecretFragmentTaint(fragments: readonly SecretFragment[]): SecretFragmentTaintProfile; clearAllAgentMemories(): Promise; deleteAllMemories(roomIds: UUID[], tableName: string): Promise; countMemories(roomIdOrParams: UUID | { roomId?: UUID; /** Adapter count parameters, including roomIds, pass through without widening the query. */ roomIds?: UUID[]; unique?: boolean; tableName?: string; entityId?: UUID; agentId?: UUID; metadata?: Record; }, unique?: boolean, tableName?: string): Promise; getLogs(params: { entityId?: UUID; roomId?: UUID; type?: string; limit?: number; offset?: number; }): Promise; getLogInventory(params: { excludeTypes?: readonly string[]; }): Promise; getLogsByIds(logIds: UUID[]): Promise; createLogs(params: Array<{ body: LogBody; entityId: UUID; roomId: UUID; type: string; createdAt?: Date; }>): Promise; updateLogs(logs: Array<{ id: UUID; updates: Partial; }>): Promise; deleteLogs(logIds: UUID[]): Promise; createWorld(world: World): Promise; getWorld(id: UUID): Promise; deleteWorld(worldId: UUID): Promise; getAllWorlds(): Promise; updateWorld(world: World): Promise; getWorldsByIds(worldIds: UUID[]): Promise; createWorlds(worlds: World[]): Promise; upsertWorlds(worlds: World[]): Promise; deleteWorlds(worldIds: UUID[]): Promise; updateWorlds(worlds: World[]): Promise; getRoom(roomId: UUID): Promise; getRoomsByIds(roomIds: UUID[]): Promise; createRoom({ id, name, source, type, channelId, serverId, messageServerId, worldId, metadata, }: Room): Promise; createRooms(rooms: Room[]): Promise; upsertRooms(rooms: Room[]): Promise; deleteRoomsByWorldId(worldId: UUID): Promise; getRoomsForParticipant(entityId: UUID): Promise; getRoomsForParticipants(entityIds: UUID[]): Promise; getRooms(worldId: UUID): Promise; getRoomsByWorld(worldId: UUID): Promise; getParticipantUserState(roomId: UUID, entityId: UUID): Promise<"FOLLOWED" | "MUTED" | null>; updateParticipantUserState(roomId: UUID, entityId: UUID, state: "FOLLOWED" | "MUTED" | null): Promise; getParticipantUserStates(pairs: Array<{ roomId: UUID; entityId: UUID; }>): Promise<("FOLLOWED" | "MUTED" | null)[]>; updateParticipantUserStates(updates: Array<{ roomId: UUID; entityId: UUID; state: "FOLLOWED" | "MUTED" | null; }>): Promise; getRelationships(params: { entityIds?: UUID[]; entityId?: UUID; tags?: string[]; limit?: number; offset?: number; }): Promise; getCaches(keys: string[]): Promise>; setCaches(entries: Array<{ key: string; value: T; }>): Promise; compareAndSetCache(key: string, expected: unknown, replacement: T): Promise; deleteCaches(keys: string[]): Promise; getTasks(params: { roomId?: UUID; worldId?: UUID; tags?: string[]; entityId?: UUID; limit?: number; offset?: number; }): Promise; getTasksByName(name: string): Promise; /** Wake the registered task service after committed task mutations. */ private _markLocalTasksDirty; createTask(task: Task): Promise; getTask(id: UUID): Promise; updatePendingTask(id: UUID, task: Partial): Promise; patchTaskMetadata(id: UUID, patch: TaskMetadataPatch): Promise; updateTask(id: UUID, task: Partial): Promise; deleteTask(id: UUID): Promise; log(params: { body: LogBody; entityId: UUID; roomId: UUID; type: string; }): Promise; deleteLog(logId: UUID): Promise; getCache(key: string): Promise; setCache(key: string, value: T): Promise; deleteCache(key: string): Promise; createTasks(tasks: Task[]): Promise; getTasksByIds(taskIds: UUID[]): Promise; updateTasks(updates: Array<{ id: UUID; task: Partial; }>): Promise; deleteTasks(taskIds: UUID[]): Promise; /** * Run callback in a database transaction. Forwards options.entityContext to the adapter. * WHY forward only: RLS (withEntityContext) is implemented in the adapter (e.g. plugin-sql Postgres); * runtime does not touch Postgres or connection context. */ transaction(callback: (tx: IDatabaseAdapter) => Promise, options?: { entityContext?: UUID; }): Promise; queryEntities(params: { componentType?: string; componentDataFilter?: Record; agentId?: UUID; entityIds?: UUID[]; worldId?: UUID; limit?: number; offset?: number; includeAllComponents?: boolean; entityContext?: UUID; }): Promise; getEntitiesByIds(entityIds: UUID[]): Promise; updateEntities(entities: Entity[]): Promise; deleteEntities(entityIds: UUID[]): Promise; searchEntitiesByName(params: { query: string; agentId?: UUID; limit?: number; }): Promise; getEntitiesByNames(params: { names: string[]; agentId?: UUID; }): Promise; updateEntity(entity: Entity): Promise; createComponents(components: Component[]): Promise; getComponentsByIds(componentIds: UUID[]): Promise; updateComponents(components: Component[]): Promise; deleteComponents(componentIds: UUID[]): Promise; createComponent(component: Component): Promise; getComponent(entityId: UUID, type: string, worldId?: UUID, sourceEntityId?: UUID): Promise; updateComponent(component: Component): Promise; deleteComponent(componentId: UUID): Promise; upsertComponent(component: Component): Promise; upsertComponents(components: Component[], options?: { entityContext?: UUID; }): Promise; patchComponent(componentId: UUID, ops: PatchOp[], options?: { entityContext?: UUID; }): Promise; patchComponents(updates: Array<{ componentId: UUID; ops: PatchOp[]; }>, options?: { entityContext?: UUID; }): Promise; patchComponentField(componentId: UUID, op: PatchOp, options?: { entityContext?: UUID; }): Promise; getComponentsByType(type: string, agentId?: UUID, options?: { entityContext?: UUID; }): Promise; upsertMemory(memory: Memory, tableName: string, options?: { entityContext?: UUID; }): Promise; upsertMemories(memories: Array<{ memory: Memory; tableName: string; }>, options?: { entityContext?: UUID; }): Promise; createRelationships(relationships: Array<{ sourceEntityId: UUID; targetEntityId: UUID; tags?: string[]; metadata?: Metadata; }>): Promise; getRelationshipsByIds(relationshipIds: UUID[]): Promise; getRelationshipsByPairs(pairs: Array<{ sourceEntityId: UUID; targetEntityId: UUID; }>): Promise<(Relationship | null)[]>; updateRelationships(relationships: Relationship[]): Promise; deleteRelationships(relationshipIds: UUID[]): Promise; createRelationship(params: { sourceEntityId: UUID; targetEntityId: UUID; tags?: string[]; metadata?: Metadata; }): Promise; getRelationship(params: { sourceEntityId: UUID; targetEntityId: UUID; }): Promise; updateRelationship(relationship: Relationship): Promise; createMemories(memories: Array<{ memory: Memory; tableName: string; unique?: boolean; }>): Promise; updateMemories(memories: Array & { id: UUID; metadata?: MemoryMetadata; }>): Promise; deleteMemories(memoryIds: UUID[]): Promise; getMemoryById(id: UUID): Promise; createMessageMemory(memory: Memory, unique?: boolean): Promise; replaceMessageMemoryContent(id: UUID, content: Content): Promise; createMemory(memory: Memory, tableName: string, unique?: boolean): Promise; updateMemory(memory: Partial & { id: UUID; metadata?: MemoryMetadata; }): Promise; updateMemoryEmbedding(update: import("./types/database.js").MemoryEmbeddingUpdate): Promise; deleteMemory(memoryId: UUID): Promise; deleteParticipants(participants: Array<{ entityId: UUID; roomId: UUID; }>): Promise; updateParticipants(participants: Array<{ entityId: UUID; roomId: UUID; updates: Partial; }>): Promise; removeParticipant(entityId: UUID, roomId: UUID): Promise; updateRooms(rooms: Room[]): Promise; deleteRooms(roomIds: UUID[]): Promise; updateRoom(room: Room): Promise; deleteRoom(roomId: UUID): Promise; on(event: string, callback: (data: EventPayload) => void): void; off(event: string, callback: (data: EventPayload) => void): void; emit(event: string, data: EventPayload): void; sendControlMessage(params: { roomId: UUID; action: "enable_input" | "disable_input"; target?: string; }): Promise; registerSearchCategory(registration: SearchCategoryRegistration): void; getSearchCategories(options?: SearchCategoryEnumerationOptions): SearchCategoryRegistration[]; getSearchCategory(category: string, options?: SearchCategoryLookupOptions): SearchCategoryRegistration; registerSendHandler(...args: Parameters): ReturnType; registerInternalSendHandler(...args: Parameters): ReturnType; registerMessageConnector(...args: Parameters): ReturnType; unregisterMessageConnector(...args: Parameters): ReturnType; getMessageConnectors(...args: Parameters): ReturnType; registerPostConnector(...args: Parameters): ReturnType; unregisterPostConnector(...args: Parameters): ReturnType; getPostConnectors(...args: Parameters): ReturnType; sendMessageToTarget(...args: Parameters): ReturnType; editMessageOnTarget(...args: Parameters): ReturnType; sendTypingOnTarget(...args: Parameters): ReturnType; stopTypingOnTarget(...args: Parameters): ReturnType; createThreadOnTarget(...args: Parameters): ReturnType; postToThreadOnTarget(...args: Parameters): ReturnType; addReactionOnTarget(...args: Parameters): ReturnType; getMemoriesByWorldId(params: { worldId: UUID; limit?: number; tableName?: string; }): Promise; runMigrations(migrationsPaths?: string[]): Promise; isReady(): Promise; getPairingRequestsForChannel(channel: PairingChannel, agentId: UUID): Promise; getPairingRequests(queries: import("./types/pairing.js").PairingRequestQuery[]): Promise; getPairingAllowlistForChannel(channel: PairingChannel, agentId: UUID): Promise; getPairingAllowlists(queries: import("./types/pairing.js").PairingAllowlistQuery[]): Promise; createPairingRequests(requests: PairingRequest[]): Promise; updatePairingRequests(requests: PairingRequest[]): Promise; deletePairingRequests(ids: UUID[]): Promise; createPairingAllowlistEntries(entries: PairingAllowlistEntry[]): Promise; updatePairingAllowlistEntries(entries: PairingAllowlistEntry[]): Promise; deletePairingAllowlistEntries(ids: UUID[]): Promise; createPairingRequest(request: PairingRequest): Promise; updatePairingRequest(request: PairingRequest): Promise; deletePairingRequest(id: UUID): Promise; createPairingAllowlistEntry(entry: PairingAllowlistEntry): Promise; deletePairingAllowlistEntry(id: UUID): Promise; 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; deleteRoomsByWorldIds(worldIds: UUID[]): Promise; getRoomsByWorlds(worldIds: UUID[], limit?: number, offset?: number): Promise; installRemotePlugin(_plugin: Plugin, _options?: RemotePluginInstallOptions): Promise; }