@anuma/sdk 6.37.0 → 6.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7065,6 +7065,10 @@ interface RankableVaultMemory {
7065
7065
  * required. `vaultMemoryRawToRankable` still always sets it. */
7066
7066
  lastObservedAt?: number | null;
7067
7067
  }
7068
+ /** @public */
7069
+ interface VaultMemoryProjection extends RankableVaultMemory {
7070
+ topicsUserManaged: boolean;
7071
+ }
7068
7072
  /**
7069
7073
  * A photo a server-extracted memory came from, as
7070
7074
  * GET /api/memories/published returns it in `media[]`.
@@ -9090,7 +9094,7 @@ interface MemoryListOptions {
9090
9094
  * passing provenance, trust or publication metadata through manual creation.
9091
9095
  * @public
9092
9096
  */
9093
- type MemoryCreate = Pick<CreateVaultMemoryOptions, "content" | "scope" | "factType" | "eventTime" | "embedding" | "embeddingModel" | "geohash">;
9097
+ type MemoryCreate = Pick<CreateVaultMemoryOptions, "content" | "scope" | "factType" | "eventTime" | "embedding" | "embeddingModel" | "geohash" | "kind" | "kindValue" | "level">;
9094
9098
  /**
9095
9099
  * The edits an app makes to an existing memory. Deliberately narrower than
9096
9100
  * {@link UpdateVaultMemoryOptions}: the re-observation knobs (`proofCountIncrement`,
@@ -9106,7 +9110,7 @@ type MemoryCreate = Pick<CreateVaultMemoryOptions, "content" | "scope" | "factTy
9106
9110
  * `embedding` (with `embeddingModel`) only when you already have the new one.
9107
9111
  * @public
9108
9112
  */
9109
- type MemoryUpdate = Pick<UpdateVaultMemoryOptions, "content" | "scope" | "factType" | "eventTime" | "embedding" | "embeddingModel">;
9113
+ type MemoryUpdate = Pick<UpdateVaultMemoryOptions, "content" | "scope" | "factType" | "eventTime" | "embedding" | "embeddingModel" | "kind" | "kindValue" | "level">;
9110
9114
  /**
9111
9115
  * Fact-only recall. Conversation chunks are message storage, not memory, so
9112
9116
  * the chunk-lane knobs are not part of this surface; nor is `folderId` (see
@@ -9132,6 +9136,15 @@ type MemoryRecallOptions = Omit<RecallOptions, "types" | "includeChunks" | "conv
9132
9136
  * @public
9133
9137
  */
9134
9138
  type MemoryRetainOptions = Omit<RetainOptions, "folderId">;
9139
+ /**
9140
+ * A topic and how many memories link to it.
9141
+ * @public
9142
+ */
9143
+ interface MemoryTopic {
9144
+ name: string;
9145
+ kind: string | null;
9146
+ memoryCount: number;
9147
+ }
9135
9148
  /** @public */
9136
9149
  interface MemorySubscribeOptions {
9137
9150
  /**
@@ -9213,6 +9226,10 @@ interface MemoryStore {
9213
9226
  memoriesByTopics(names: readonly string[]): Promise<Map<string, Set<string>>>;
9214
9227
  /** Memory id → its canonical (lowercased) topic names. Unlinked ids are absent. */
9215
9228
  topicsByMemories(memoryIds: readonly string[]): Promise<Map<string, Set<string>>>;
9229
+ /** Every topic by canonical name, with its kind and linked-memory count. */
9230
+ listTopics(): Promise<MemoryTopic[]>;
9231
+ /** The memories {@link MemoryStore.list} would return, without decrypting content. */
9232
+ listProjections(options?: MemoryListOptions): Promise<VaultMemoryProjection[]>;
9216
9233
  /** Manual save; missing embeddings are filled in the background. */
9217
9234
  create(input: MemoryCreate): Promise<StoredVaultMemory>;
9218
9235
  /** One write for a batch of manual saves; migration/restore uses lower-level operations. */
@@ -9400,6 +9417,15 @@ interface RemoteMemoryQueryOptions extends RemoteMemoryReadFilters {
9400
9417
  interface RemoteMemoryQueryPage extends RemoteMemoryPage {
9401
9418
  changes_cursor?: string;
9402
9419
  }
9420
+ interface RemoteMemoryMetadataRecord {
9421
+ memory: Omit<RemoteMemoryRow, "content" | "kind_value">;
9422
+ version: number;
9423
+ server_updated_at: string;
9424
+ }
9425
+ interface RemoteMemoryMetadataPage {
9426
+ items: RemoteMemoryMetadataRecord[];
9427
+ next_cursor?: string;
9428
+ }
9403
9429
  interface RemoteMemoryCandidateOptions extends RemoteMemoryReadFilters {
9404
9430
  scopes?: string[];
9405
9431
  memory_ids?: string[];
@@ -9444,6 +9470,10 @@ interface RemoteMemoryPersistence {
9444
9470
  /** One stable memory-id page; follow next_cursor to enumerate. Embeddings are opt-in. */
9445
9471
  list(options?: RemoteMemoryListOptions): Promise<RemoteMemoryPage>;
9446
9472
  query(options?: RemoteMemoryQueryOptions): Promise<RemoteMemoryQueryPage>;
9473
+ /** Same page as `query`, with content and kind_value dropped instead of decrypted. */
9474
+ queryMetadata(options?: Omit<RemoteMemoryQueryOptions, "order"> & {
9475
+ order?: "created" | "updated" | "archived";
9476
+ }): Promise<RemoteMemoryMetadataPage>;
9447
9477
  /** Whole-row write. Pass a returned snapshot to avoid GET; a number retains the read-before-write path. Version 0 creates. is_deleted writes a tombstone. */
9448
9478
  put(memory: RemoteMemoryRow, expectedVersion: number | RemoteMemoryRecord, signal?: AbortSignal): Promise<RemoteMemoryRecord>;
9449
9479
  /** 1–50 writes in one server transaction; never split or replay a batch. */
@@ -11108,4 +11138,4 @@ interface UseChatStorageResult extends BaseUseChatStorageResult {
11108
11138
  */
11109
11139
  declare function useChatStorage(options: UseChatStorageOptions): UseChatStorageResult;
11110
11140
 
11111
- export { type AutoExtractMessage, type AutoExtractor, type Budget, CHUNKS_DISCARDED_ORIGIN, type CachedChunkVectors, type CachedServerTools, Conversation as ChatConversation, Message as ChatMessage, type ChatRole, type ChunkVectorCache, type ChunkingOptions, type ConsolidationAction, type ConsolidationFallbackReason, type ConversationMemoryInput, ConversationMemory as ConversationMemoryModel, type ConversationMemoryOperationsContext, type CreateAutoExtractorOptions, type CreateConversationOptions, type CreateDecaySweeperOptions, type CreateMessageOptions, type CreateVaultFolderOptions, type CreateVaultMemoryOptions, type CryptoPriceClassification, type CryptoPricePreProcessorOptions, DEFAULT_CACHE_EXPIRATION_MS, DEFAULT_CHUNK_CACHE_SIZE, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DECAY_POLICY, DEFAULT_MAX_CLASSIFIER_CALLS_PER_SWEEP, DEFAULT_MIN_CHUNK_SIZE, DEFAULT_PROFILE_FACETS, DEFAULT_PROFILE_FACT_TYPE_WEIGHTS, DEFAULT_PROFILE_PROOF_ALPHA, DEFAULT_PROFILE_TREND_MULTIPLIERS, DEFAULT_VAULT_CACHE_SIZE, DatabaseManager, type DatabaseManagerLogger, type DatabaseManagerOptions, type DecayCandidateRaw, type DecayClassifier, type DecayInput, type DecayPolicy, type DecaySweepResult, type DecaySweeper, type DecayVerdict, type DurableAutoExtractorOptions, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type ExtractionFunnel, type ExtractionTimings, type FactType, type FileMetadata, type FileProcessingReason, type FileProcessingStatus, type FlushResult, type GetConversationsPageOptions, type GetMessagesPageOptions, type GraphTraversalOptions, HARD_DELETE_WINDOW_MS, INFERENCE_ID_HEADER, type InjectionClassifierOptions, type InjectionReason, type LazyStoredConversation, type LlmDecayClassifierOptions, type LlmNeighborRefinerOptions, type LocalMemoryStoreOptions, type Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, MEMORY_KINDS, MEMORY_LEVELS, type ManualFactType, type MemoriesNeedingTopicExtraction, type MemoryContextItem, type MemoryContextLane, type MemoryContextOptions, type MemoryContextResult, type MemoryCreate, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, MemoryKeyError, type MemoryKeyRing, type MemoryKind, type MemoryLevel, MemoryLevelError, type MemoryListOptions, type MemoryMaintenance, type MemoryQuarantinedEvent, type MemoryRecallOptions, type MemoryRetainOptions, type MemoryStore, type MemorySubscribeOptions, type MemoryToVerify, type MemoryUpdate, type MemoryVaultSearchOptions, type MemoryVaultToolOptions, type MemoryVerification, type MessageRedactionResult, type MessageSkeleton, NEVER_TTL_MS, NODE_BUDGET, NOTION_OAUTH_CONFIG, type NeighborRefiner, type NotionAuthUrlParams, type NotionClientRegistration, type NotionExchangeCodeParams, type NotionMcpCaller, type NotionOAuthEndpoints, type NotionPKCEChallenge, type NotionRefreshTokenParams, type NotionTokenResponse, type NowSource, type ObservationTrend, type ObservationTrendInput, PAST_EVENT_GRACE_MS, PII_PATTERNS, PROFILE_DOC_VERSION, type PhotoIngestResult, type PhotoMediaRef, type PiiCategory, type PiiMatch, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type PromptPreProcessor, type PromptPreProcessorContext, type PublishedPhotoMemory, type QuantizedEmbedding, type QuarantinedMemoryInfo, QueueManager, type QueueStatus, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankableVaultMemory, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallEmptyReason, type RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RemoteMemoryCandidateOptions, type RemoteMemoryDecodeFailure, RemoteMemoryError, type RemoteMemoryListOptions, type RemoteMemoryPage, RemoteMemoryPartialCreateError, type RemoteMemoryPersistence, type RemoteMemoryPersistenceOptions, type RemoteMemoryPipeline, type RemoteMemoryPipelineOptions, type RemoteMemoryQueryOptions, type RemoteMemoryQueryPage, type RemoteMemoryReadFilters, type RemoteMemoryRecord, type RemoteMemoryRow, type RemoteMemoryStoreOptions, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ReservationReceipt, type ResumeStreamOptions, type ResumeStreamResult, type ResumeStreamWithStorageResult, type RetainAction, type RetainContext, type RetainOptions, type RetainResult, type RetainSource, SDK_SCHEMA_VERSION, SHORT_TTL_MS, STREAM_RESUMABLE_HEADER, type ScoreBreakdown, type ScoreProfileSalienceOptions, type ScreenResult, type ScreenedCandidate, type SearchSource, type SendMessageWithStorageArgs, type SendMessageWithStorageDetachedResult, type SendMessageWithStorageResult, type ServerToolsOptions, type ServerToolsResponse, type SignMessageFn, type StockPriceClassification, type StockPricePreProcessorOptions, type ChatCompletionUsage as StoredChatCompletionUsage, type StoredConversation, type StoredConversationMemory, type StoredMessage, type StoredMessageWithSimilarity, type StoredVaultFolder, VaultFolder as StoredVaultFolderModel, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type StreamSmoothingConfig, type SynthesizeProfileOptions, TOOL_RESULT_ORIGIN, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, type TopicSkipReason, type TurnCompleteEvent, type TurnSkippedEvent, type UncheckedReason, type UnverifiableReason, type UpdateVaultFolderOptions, type UpdateVaultMemoryOptions, type UseChatStorageOptions, type UseChatStorageResult, type UseCreditsOptions, type UseCreditsResult, type UseModelsOptions, type UseModelsResult, VAULT_SIZE_HOP_CAP, type VaultEmbeddingCache, type VaultEmbeddingExpectation, type VaultFolderOperationsContext, type VaultMemoryKind, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultMemoryWriter, type VaultSaveOperation, type VaultSearchResult, type VaultWriteAction, type VaultWriteInput, type VaultWriteOutcome, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, assembleMemoryContext, attachFileContextToLastUserMessage, backfillMemoryTopicsOp, buildAttachedFilesText, buildNotionAuthUrl, capHopsForDensity, chatStorageMigrations, chatStorageSchema, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, clearAllEncryptionKeys, clearAllEncryptionState, clearConversationMemoriesOp, clearEncryptionKey, clearLazyTitleCache, clearServerToolsCache, consoleLogger, conversationMemoryToStored, cosineInt8, createAutoExtractor, createChunkVectorCache, createCryptoPricePreProcessor, createDecaySweeper, createDurableAutoExtractor, createLlmDecayClassifier, createLlmNeighborRefiner, createLocalMemoryStore, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionProxyTools, createNotionTools, createPlatformCursorStore, createRecallTool, createRemoteMemoryPersistence, createRemoteMemoryPipeline, createRemoteMemoryStore, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteMessageOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, deriveKeyFromSignatureBytes, deriveMemoryKeyRing, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, extractReservationReceipts, formatFileProcessingNotes, generateConversationId, generateEmbedding, generateEmbeddings, generateNotionPKCE, getAllVaultFoldersOp, getAllVaultMemoriesOp, getAllVaultMemoryContentsOp, getCachedServerTools, getConversationMemoriesOp, getConversationsByProjectLazyOp, getConversationsLazyOp, getConversationsPageOp, getDecayCandidatesRawOp, getLogger, getMemoriesNeedingTopicExtractionOp, getServerTools, getUnfiledVaultMemoriesOp, getVaultFolderMemoryCountOp, getVaultMemoriesByIdsOp, getVaultMemoryOp, getVaultRankingProjectionsOp, hardDeleteDecayedOp, hasEncryptionKey, ingestPublishedPhotoMemoriesOp, injectionSignatureCatalog, isAttachedFilesText, isDegradedTopicSkip, isEncrypted, isPiiRedactor, isRerankerAvailable, maskScopedEmbeddingCache, memoryCipher, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reencryptMemoryField, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, shouldRecallMemory, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, stripLegacyChunkTextOp, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
11141
+ export { type AutoExtractMessage, type AutoExtractor, type Budget, CHUNKS_DISCARDED_ORIGIN, type CachedChunkVectors, type CachedServerTools, Conversation as ChatConversation, Message as ChatMessage, type ChatRole, type ChunkVectorCache, type ChunkingOptions, type ConsolidationAction, type ConsolidationFallbackReason, type ConversationMemoryInput, ConversationMemory as ConversationMemoryModel, type ConversationMemoryOperationsContext, type CreateAutoExtractorOptions, type CreateConversationOptions, type CreateDecaySweeperOptions, type CreateMessageOptions, type CreateVaultFolderOptions, type CreateVaultMemoryOptions, type CryptoPriceClassification, type CryptoPricePreProcessorOptions, DEFAULT_CACHE_EXPIRATION_MS, DEFAULT_CHUNK_CACHE_SIZE, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DECAY_POLICY, DEFAULT_MAX_CLASSIFIER_CALLS_PER_SWEEP, DEFAULT_MIN_CHUNK_SIZE, DEFAULT_PROFILE_FACETS, DEFAULT_PROFILE_FACT_TYPE_WEIGHTS, DEFAULT_PROFILE_PROOF_ALPHA, DEFAULT_PROFILE_TREND_MULTIPLIERS, DEFAULT_VAULT_CACHE_SIZE, DatabaseManager, type DatabaseManagerLogger, type DatabaseManagerOptions, type DecayCandidateRaw, type DecayClassifier, type DecayInput, type DecayPolicy, type DecaySweepResult, type DecaySweeper, type DecayVerdict, type DurableAutoExtractorOptions, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type ExtractionFunnel, type ExtractionTimings, type FactType, type FileMetadata, type FileProcessingReason, type FileProcessingStatus, type FlushResult, type GetConversationsPageOptions, type GetMessagesPageOptions, type GraphTraversalOptions, HARD_DELETE_WINDOW_MS, INFERENCE_ID_HEADER, type InjectionClassifierOptions, type InjectionReason, type LazyStoredConversation, type LlmDecayClassifierOptions, type LlmNeighborRefinerOptions, type LocalMemoryStoreOptions, type Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, MEMORY_KINDS, MEMORY_LEVELS, type ManualFactType, type MemoriesNeedingTopicExtraction, type MemoryContextItem, type MemoryContextLane, type MemoryContextOptions, type MemoryContextResult, type MemoryCreate, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, MemoryKeyError, type MemoryKeyRing, type MemoryKind, type MemoryLevel, MemoryLevelError, type MemoryListOptions, type MemoryMaintenance, type MemoryQuarantinedEvent, type MemoryRecallOptions, type MemoryRetainOptions, type MemoryStore, type MemorySubscribeOptions, type MemoryToVerify, type MemoryTopic, type MemoryUpdate, type MemoryVaultSearchOptions, type MemoryVaultToolOptions, type MemoryVerification, type MessageRedactionResult, type MessageSkeleton, NEVER_TTL_MS, NODE_BUDGET, NOTION_OAUTH_CONFIG, type NeighborRefiner, type NotionAuthUrlParams, type NotionClientRegistration, type NotionExchangeCodeParams, type NotionMcpCaller, type NotionOAuthEndpoints, type NotionPKCEChallenge, type NotionRefreshTokenParams, type NotionTokenResponse, type NowSource, type ObservationTrend, type ObservationTrendInput, PAST_EVENT_GRACE_MS, PII_PATTERNS, PROFILE_DOC_VERSION, type PhotoIngestResult, type PhotoMediaRef, type PiiCategory, type PiiMatch, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type PromptPreProcessor, type PromptPreProcessorContext, type PublishedPhotoMemory, type QuantizedEmbedding, type QuarantinedMemoryInfo, QueueManager, type QueueStatus, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankableVaultMemory, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallEmptyReason, type RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RemoteMemoryCandidateOptions, type RemoteMemoryDecodeFailure, RemoteMemoryError, type RemoteMemoryListOptions, type RemoteMemoryMetadataPage, type RemoteMemoryMetadataRecord, type RemoteMemoryPage, RemoteMemoryPartialCreateError, type RemoteMemoryPersistence, type RemoteMemoryPersistenceOptions, type RemoteMemoryPipeline, type RemoteMemoryPipelineOptions, type RemoteMemoryQueryOptions, type RemoteMemoryQueryPage, type RemoteMemoryReadFilters, type RemoteMemoryRecord, type RemoteMemoryRow, type RemoteMemoryStoreOptions, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ReservationReceipt, type ResumeStreamOptions, type ResumeStreamResult, type ResumeStreamWithStorageResult, type RetainAction, type RetainContext, type RetainOptions, type RetainResult, type RetainSource, SDK_SCHEMA_VERSION, SHORT_TTL_MS, STREAM_RESUMABLE_HEADER, type ScoreBreakdown, type ScoreProfileSalienceOptions, type ScreenResult, type ScreenedCandidate, type SearchSource, type SendMessageWithStorageArgs, type SendMessageWithStorageDetachedResult, type SendMessageWithStorageResult, type ServerToolsOptions, type ServerToolsResponse, type SignMessageFn, type StockPriceClassification, type StockPricePreProcessorOptions, type ChatCompletionUsage as StoredChatCompletionUsage, type StoredConversation, type StoredConversationMemory, type StoredMessage, type StoredMessageWithSimilarity, type StoredVaultFolder, VaultFolder as StoredVaultFolderModel, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type StreamSmoothingConfig, type SynthesizeProfileOptions, TOOL_RESULT_ORIGIN, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, type TopicSkipReason, type TurnCompleteEvent, type TurnSkippedEvent, type UncheckedReason, type UnverifiableReason, type UpdateVaultFolderOptions, type UpdateVaultMemoryOptions, type UseChatStorageOptions, type UseChatStorageResult, type UseCreditsOptions, type UseCreditsResult, type UseModelsOptions, type UseModelsResult, VAULT_SIZE_HOP_CAP, type VaultEmbeddingCache, type VaultEmbeddingExpectation, type VaultFolderOperationsContext, type VaultMemoryKind, type VaultMemoryOperationsContext, type VaultMemoryProjection, type VaultMemoryVisibility, type VaultMemoryWriter, type VaultSaveOperation, type VaultSearchResult, type VaultWriteAction, type VaultWriteInput, type VaultWriteOutcome, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, assembleMemoryContext, attachFileContextToLastUserMessage, backfillMemoryTopicsOp, buildAttachedFilesText, buildNotionAuthUrl, capHopsForDensity, chatStorageMigrations, chatStorageSchema, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, clearAllEncryptionKeys, clearAllEncryptionState, clearConversationMemoriesOp, clearEncryptionKey, clearLazyTitleCache, clearServerToolsCache, consoleLogger, conversationMemoryToStored, cosineInt8, createAutoExtractor, createChunkVectorCache, createCryptoPricePreProcessor, createDecaySweeper, createDurableAutoExtractor, createLlmDecayClassifier, createLlmNeighborRefiner, createLocalMemoryStore, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionProxyTools, createNotionTools, createPlatformCursorStore, createRecallTool, createRemoteMemoryPersistence, createRemoteMemoryPipeline, createRemoteMemoryStore, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteMessageOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, deriveKeyFromSignatureBytes, deriveMemoryKeyRing, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, extractReservationReceipts, formatFileProcessingNotes, generateConversationId, generateEmbedding, generateEmbeddings, generateNotionPKCE, getAllVaultFoldersOp, getAllVaultMemoriesOp, getAllVaultMemoryContentsOp, getCachedServerTools, getConversationMemoriesOp, getConversationsByProjectLazyOp, getConversationsLazyOp, getConversationsPageOp, getDecayCandidatesRawOp, getLogger, getMemoriesNeedingTopicExtractionOp, getServerTools, getUnfiledVaultMemoriesOp, getVaultFolderMemoryCountOp, getVaultMemoriesByIdsOp, getVaultMemoryOp, getVaultRankingProjectionsOp, hardDeleteDecayedOp, hasEncryptionKey, ingestPublishedPhotoMemoriesOp, injectionSignatureCatalog, isAttachedFilesText, isDegradedTopicSkip, isEncrypted, isPiiRedactor, isRerankerAvailable, maskScopedEmbeddingCache, memoryCipher, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reencryptMemoryField, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, shouldRecallMemory, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, stripLegacyChunkTextOp, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
@@ -1788,7 +1788,7 @@ function extractUserMessageFromMessages(messages) {
1788
1788
  }
1789
1789
 
1790
1790
  // src/lib/db/chat/operations.ts
1791
- function messageToStoredRaw(message, projection) {
1791
+ function messageToStoredRaw(message, projection2) {
1792
1792
  const convId = String(message._getRaw("conversation_id"));
1793
1793
  const parseJsonField = (rawValue) => {
1794
1794
  if (!rawValue) return void 0;
@@ -1802,7 +1802,7 @@ function messageToStoredRaw(message, projection) {
1802
1802
  }
1803
1803
  return rawValue;
1804
1804
  };
1805
- const skipEmbeddings = projection?.skipEmbeddings === true;
1805
+ const skipEmbeddings = projection2?.skipEmbeddings === true;
1806
1806
  const sourcesRaw = message._getRaw("sources");
1807
1807
  const vectorRaw = skipEmbeddings ? null : message._getRaw("vector");
1808
1808
  const chunksRaw = skipEmbeddings ? null : message._getRaw("chunks");
@@ -1836,8 +1836,8 @@ function messageToStoredRaw(message, projection) {
1836
1836
  origin: message.origin
1837
1837
  };
1838
1838
  }
1839
- async function messageToStored(message, walletAddress, signMessage, embeddedWalletSigner, projection) {
1840
- const baseMessage = messageToStoredRaw(message, projection);
1839
+ async function messageToStored(message, walletAddress, signMessage, embeddedWalletSigner, projection2) {
1840
+ const baseMessage = messageToStoredRaw(message, projection2);
1841
1841
  if (walletAddress) {
1842
1842
  return await decryptMessageFields(
1843
1843
  baseMessage,
@@ -1851,7 +1851,7 @@ async function messageToStored(message, walletAddress, signMessage, embeddedWall
1851
1851
  function rawDate(value) {
1852
1852
  return new Date(typeof value === "number" ? value : 0);
1853
1853
  }
1854
- function messageRawToStoredRaw(raw, projection) {
1854
+ function messageRawToStoredRaw(raw, projection2) {
1855
1855
  const parseJsonField = (rawValue) => {
1856
1856
  if (!rawValue) return void 0;
1857
1857
  if (typeof rawValue === "string") {
@@ -1864,7 +1864,7 @@ function messageRawToStoredRaw(raw, projection) {
1864
1864
  }
1865
1865
  return rawValue;
1866
1866
  };
1867
- const skipEmbeddings = projection?.skipEmbeddings === true;
1867
+ const skipEmbeddings = projection2?.skipEmbeddings === true;
1868
1868
  const vectorRaw = skipEmbeddings ? null : raw.vector;
1869
1869
  const chunksRaw = skipEmbeddings ? null : raw.chunks;
1870
1870
  return {
@@ -1895,8 +1895,8 @@ function messageRawToStoredRaw(raw, projection) {
1895
1895
  origin: raw.origin
1896
1896
  };
1897
1897
  }
1898
- async function messageRawToStored(raw, walletAddress, signMessage, embeddedWalletSigner, projection) {
1899
- const baseMessage = messageRawToStoredRaw(raw, projection);
1898
+ async function messageRawToStored(raw, walletAddress, signMessage, embeddedWalletSigner, projection2) {
1899
+ const baseMessage = messageRawToStoredRaw(raw, projection2);
1900
1900
  if (walletAddress) {
1901
1901
  return await decryptMessageFields(
1902
1902
  baseMessage,
@@ -11413,22 +11413,35 @@ async function vaultMemoryRawToStored(raw, walletAddress, signMessage, embeddedW
11413
11413
  return stored2;
11414
11414
  }
11415
11415
  async function getAllVaultMemoriesOp(ctx, options) {
11416
- const conditions = [
11416
+ const results = await ctx.vaultMemoryCollection.query(...vaultListConditions(ctx, options), ...vaultListOrder(options)).unsafeFetchRaw();
11417
+ return mapInBatches(
11418
+ results,
11419
+ (raw) => vaultMemoryRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
11420
+ );
11421
+ }
11422
+ function vaultListConditions(ctx, options) {
11423
+ return [
11417
11424
  ...baseVaultConditions(ctx, options),
11418
11425
  ...options?.scopes?.length ? [Q5.where("scope", Q5.oneOf(options.scopes))] : [],
11419
11426
  ...visibilityConditions(options?.visibility),
11420
11427
  ...levelConditions(options?.levels),
11421
11428
  ...options?.kinds?.length ? [Q5.where("kind", Q5.oneOf(options.kinds))] : [],
11422
11429
  ...options?.folderId !== void 0 ? [Q5.where("folder_id", options.folderId)] : [],
11423
- ...options?.factTypes?.length ? [Q5.where("fact_type", Q5.oneOf(options.factTypes))] : [],
11430
+ ...options?.factTypes?.length ? [Q5.where("fact_type", Q5.oneOf(options.factTypes))] : []
11431
+ ];
11432
+ }
11433
+ function vaultListOrder(options) {
11434
+ return [
11424
11435
  Q5.sortBy(options?.since ? "updated_at" : "created_at", Q5.desc),
11425
11436
  ...options?.limit !== null && options?.limit !== void 0 && options.limit > 0 ? [Q5.take(options.limit)] : []
11426
11437
  ];
11427
- const results = await ctx.vaultMemoryCollection.query(...conditions).unsafeFetchRaw();
11428
- return mapInBatches(
11429
- results,
11430
- (raw) => vaultMemoryRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
11431
- );
11438
+ }
11439
+ async function getVaultMemoryProjectionsOp(ctx, options) {
11440
+ const results = await ctx.vaultMemoryCollection.query(...vaultListConditions(ctx, options), ...vaultListOrder(options)).unsafeFetchRaw();
11441
+ return results.map((raw) => ({
11442
+ ...vaultMemoryRawToRankable(raw),
11443
+ topicsUserManaged: raw.topics_user_managed === true || raw.topics_user_managed === 1
11444
+ }));
11432
11445
  }
11433
11446
  function vaultMemoryRawToRankable(raw) {
11434
11447
  return {
@@ -18064,6 +18077,7 @@ function createLocalMemoryStore(options) {
18064
18077
  };
18065
18078
  const vaultCache = options.vaultCache ?? createVaultEmbeddingCache();
18066
18079
  const ownedBy = userId !== void 0 ? [Q8.where("user_id", userId)] : [];
18080
+ const linksOwnedBy = userId === void 0 ? [] : options.allowUnscopedRows ? [Q8.or(Q8.where("user_id", userId), Q8.where("user_id", null))] : [Q8.where("user_id", userId)];
18067
18081
  const watchedColumns = [
18068
18082
  "content",
18069
18083
  "scope",
@@ -18106,6 +18120,29 @@ function createLocalMemoryStore(options) {
18106
18120
  },
18107
18121
  memoriesByTopics: (names) => getMemoriesByEntityNamesOp(entityCtx, names),
18108
18122
  topicsByMemories: (memoryIds) => getEntitiesByMemoryIdsOp(entityCtx, memoryIds),
18123
+ listTopics: async () => {
18124
+ const links = await entityCtx.memoryEntityCollection.query(...linksOwnedBy).fetch();
18125
+ const members = /* @__PURE__ */ new Map();
18126
+ for (const link of links) {
18127
+ const entityId = String(link.entityId);
18128
+ const set = members.get(entityId) ?? /* @__PURE__ */ new Set();
18129
+ set.add(String(link.memoryId));
18130
+ members.set(entityId, set);
18131
+ }
18132
+ const entities = userId === void 0 ? await entityCtx.entityCollection.query().fetch() : members.size ? await entityCtx.entityCollection.query(Q8.where("id", Q8.oneOf([...members.keys()]))).fetch() : [];
18133
+ const byName = /* @__PURE__ */ new Map();
18134
+ for (const entity of entities) {
18135
+ const count2 = members.get(entity.id)?.size ?? 0;
18136
+ const existing = byName.get(entity.canonicalName);
18137
+ byName.set(entity.canonicalName, {
18138
+ name: entity.canonicalName,
18139
+ kind: existing?.kind ?? entity.kind ?? null,
18140
+ memoryCount: (existing?.memoryCount ?? 0) + count2
18141
+ });
18142
+ }
18143
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
18144
+ },
18145
+ listProjections: (listOptions) => getVaultMemoryProjectionsOp(vaultCtx, listOptions),
18109
18146
  create: async (input) => {
18110
18147
  const created = await createVaultMemoryOp(vaultCtx, input);
18111
18148
  if (input.embedding === void 0) embedInBackground(created);
@@ -18167,7 +18204,6 @@ function createLocalMemoryStore(options) {
18167
18204
  );
18168
18205
  const subscriptions = [memories.subscribe(afterFirst())];
18169
18206
  if (subscribeOptions?.topics) {
18170
- const linksOwnedBy = userId === void 0 ? [] : options.allowUnscopedRows ? [Q8.or(Q8.where("user_id", userId), Q8.where("user_id", null))] : [Q8.where("user_id", userId)];
18171
18207
  subscriptions.push(
18172
18208
  entityCtx.memoryEntityCollection.query(...linksOwnedBy).observe().subscribe(afterFirst())
18173
18209
  );
@@ -18577,6 +18613,31 @@ async function createRemoteMemoryPersistence(options) {
18577
18613
  throw new Error("Invalid nearby candidate response");
18578
18614
  return result;
18579
18615
  };
18616
+ const fetchQueryPage = async (queryOptions) => {
18617
+ const { signal, ...query } = queryOptions;
18618
+ if (query.limit !== void 0 && (!Number.isInteger(query.limit) || query.limit < 1 || query.limit > 200))
18619
+ throw new Error("Page limit must be 1\u2013200");
18620
+ for (const [key, max] of queryListLimits) {
18621
+ const values = query[key];
18622
+ if (values && values.length > max)
18623
+ throw new Error(`Query ${key} accepts at most ${max} entries (got ${values.length})`);
18624
+ }
18625
+ const page = await request(
18626
+ "/memories/query",
18627
+ {
18628
+ method: "POST",
18629
+ body: JSON.stringify(
18630
+ Object.fromEntries(
18631
+ queryFields.filter((key) => query[key] !== void 0).map((key) => [key, query[key]])
18632
+ )
18633
+ )
18634
+ },
18635
+ signal
18636
+ );
18637
+ if (!record(page) || !Array.isArray(page.items) || page.next_cursor !== void 0 && typeof page.next_cursor !== "string" || page.changes_cursor !== void 0 && typeof page.changes_cursor !== "string")
18638
+ throw new Error("Invalid nearby private-memory page");
18639
+ return page;
18640
+ };
18580
18641
  const candidateSet = async (embedding, candidateOptions = {}) => {
18581
18642
  const result = await fetchCandidates(embedding, candidateOptions, true);
18582
18643
  if (!Number.isSafeInteger(result.total_count) || result.total_count < 0 || !Number.isSafeInteger(result.unavailable_count) || result.unavailable_count < 0)
@@ -18655,34 +18716,27 @@ async function createRemoteMemoryPersistence(options) {
18655
18716
  return Promise.all(result.items.map((item, i) => decodeCommitted(item, prepared[i])));
18656
18717
  },
18657
18718
  query: async (queryOptions = {}) => {
18658
- const { signal, ...query } = queryOptions;
18659
- if (query.limit !== void 0 && (!Number.isInteger(query.limit) || query.limit < 1 || query.limit > 200))
18660
- throw new Error("Page limit must be 1\u2013200");
18661
- for (const [key, max] of queryListLimits) {
18662
- const values = query[key];
18663
- if (values && values.length > max)
18664
- throw new Error(`Query ${key} accepts at most ${max} entries (got ${values.length})`);
18665
- }
18666
- const page = await request(
18667
- "/memories/query",
18668
- {
18669
- method: "POST",
18670
- body: JSON.stringify(
18671
- Object.fromEntries(
18672
- queryFields.filter((key) => query[key] !== void 0).map((key) => [key, query[key]])
18673
- )
18674
- )
18675
- },
18676
- signal
18677
- );
18678
- if (!record(page) || !Array.isArray(page.items) || page.next_cursor !== void 0 && typeof page.next_cursor !== "string" || page.changes_cursor !== void 0 && typeof page.changes_cursor !== "string")
18679
- throw new Error("Invalid nearby private-memory page");
18719
+ const page = await fetchQueryPage(queryOptions);
18680
18720
  return {
18681
18721
  ...await decodeAll(page.items),
18682
18722
  ...page.next_cursor !== void 0 && { next_cursor: page.next_cursor },
18683
18723
  ...page.changes_cursor !== void 0 && { changes_cursor: page.changes_cursor }
18684
18724
  };
18685
18725
  },
18726
+ queryMetadata: async (queryOptions = {}) => {
18727
+ const page = await fetchQueryPage(queryOptions);
18728
+ return {
18729
+ items: page.items.map((item) => {
18730
+ const {
18731
+ memory: { content: _content, kind_value: _kindValue, ...memory },
18732
+ version,
18733
+ server_updated_at
18734
+ } = memoryRecord(item);
18735
+ return { memory, version, server_updated_at };
18736
+ }),
18737
+ ...page.next_cursor !== void 0 && { next_cursor: page.next_cursor }
18738
+ };
18739
+ },
18686
18740
  candidateSet,
18687
18741
  candidates: async (embedding, candidateOptions = {}) => decodeAll((await fetchCandidates(embedding, candidateOptions, false)).items)
18688
18742
  };
@@ -19073,6 +19127,19 @@ function createRemoteMemoryPipeline(options) {
19073
19127
 
19074
19128
  // src/lib/memory/store/remoteStore.ts
19075
19129
  import { v7 as uuidv75 } from "uuid";
19130
+ function projection({ memory }) {
19131
+ return {
19132
+ uniqueId: memory.memory_id,
19133
+ scope: memory.scope,
19134
+ folderId: memory.folder_id ?? null,
19135
+ embedding: memory.embedding?.length ? JSON.stringify(memory.embedding) : null,
19136
+ embeddingModel: memory.embedding_model ?? null,
19137
+ createdAt: new Date(memory.created_at),
19138
+ updatedAt: new Date(memory.updated_at),
19139
+ lastObservedAt: memory.last_observed_at ?? null,
19140
+ topicsUserManaged: memory.topics_user_managed ?? false
19141
+ };
19142
+ }
19076
19143
  function relevant(change, options) {
19077
19144
  return options.includeDeleted ? change === "membership" : change !== "embedding" || !!options.embeddings;
19078
19145
  }
@@ -19107,6 +19174,9 @@ function bounded(filters, key) {
19107
19174
  if (!values || values.length <= MAX_QUERY_FILTER) return [filters];
19108
19175
  return chunks(values, MAX_QUERY_FILTER).map((chunk) => ({ ...filters, [key]: chunk }));
19109
19176
  }
19177
+ function maxOf(options) {
19178
+ return options.limit && options.limit > 0 ? options.limit : Infinity;
19179
+ }
19110
19180
  function chunks(values, size) {
19111
19181
  const out = [];
19112
19182
  for (let i = 0; i < values.length; i += size) out.push(values.slice(i, i + size));
@@ -19178,26 +19248,49 @@ function createRemoteMemoryStore(options) {
19178
19248
  for (const subscriber of [...subscribers])
19179
19249
  if (relevant(change, subscriber.options)) safely(subscriber.onChange);
19180
19250
  };
19181
- const enumerate = async (filters, max = Infinity) => {
19251
+ const pages = async (read, filters, max = Infinity) => {
19182
19252
  const records = [];
19183
19253
  let cursor2;
19184
19254
  do {
19185
- const page = await persistence.query({
19255
+ const page = await read({
19186
19256
  ...filters,
19187
19257
  limit: Math.min(200, Math.max(1, max - records.length)),
19188
19258
  ...cursor2 && { cursor: cursor2 }
19189
19259
  });
19190
- warnFailed(page.failed);
19260
+ if (page.failed) warnFailed(page.failed);
19191
19261
  records.push(...page.items);
19192
19262
  cursor2 = page.next_cursor;
19193
19263
  } while (cursor2 && records.length < max);
19194
19264
  return records.slice(0, max);
19195
19265
  };
19196
- const enumerateIds = async (ids, filters) => (await Promise.all(
19266
+ const decrypted = (options2) => persistence.query(options2);
19267
+ const metadata = (options2) => persistence.queryMetadata(options2);
19268
+ const enumerate = (filters, max = Infinity) => pages(decrypted, filters, max);
19269
+ const enumerateIds = async (read, ids, filters) => (await Promise.all(
19197
19270
  chunks([...new Set(ids)], MAX_QUERY_IDS).map(
19198
- (memory_ids) => enumerate({ ...filters, memory_ids })
19271
+ (memory_ids) => pages(read, { ...filters, memory_ids })
19199
19272
  )
19200
19273
  )).flat();
19274
+ const listFilters = (listOptions) => ({
19275
+ ...stateFilters(listOptions),
19276
+ include_embeddings: true,
19277
+ order: listOptions.since ? "updated" : "created",
19278
+ ...listOptions.scopes?.length && { scopes: listOptions.scopes },
19279
+ ...listOptions.factTypes?.length && { fact_types: listOptions.factTypes },
19280
+ ...listOptions.visibility?.length && { visibility: listOptions.visibility },
19281
+ ...listOptions.since && { updated_after: listOptions.since.getTime() }
19282
+ });
19283
+ const listRows = async (read, listOptions, filters, max) => {
19284
+ const variants = bounded(filters, "scopes").flatMap((f) => bounded(f, "fact_types"));
19285
+ if (!listOptions.memoryIds && variants.length === 1) return pages(read, filters, max);
19286
+ const fetched = await Promise.all(
19287
+ variants.map(
19288
+ (variant) => listOptions.memoryIds ? enumerateIds(read, listOptions.memoryIds, variant) : pages(read, variant, max)
19289
+ )
19290
+ );
19291
+ const time = (row) => filters.order === "updated" ? row.memory.updated_at : row.memory.created_at;
19292
+ return [...new Map(fetched.flat().map((r) => [r.memory.memory_id, r])).values()].sort((a, b) => time(b) - time(a) || (a.memory.memory_id < b.memory.memory_id ? 1 : -1)).slice(0, max);
19293
+ };
19201
19294
  const queues = /* @__PURE__ */ new Map();
19202
19295
  const serialized = (id, task) => {
19203
19296
  const run = (queues.get(id) ?? Promise.resolve()).then(task, task);
@@ -19239,12 +19332,15 @@ function createRemoteMemoryStore(options) {
19239
19332
  };
19240
19333
  const newRow = (input) => {
19241
19334
  const now = Date.now();
19242
- const scope = input.scope ?? "private";
19335
+ const { level, scope } = resolveCreateLevel(input);
19336
+ assertValidKindLevel(input.kind, level);
19243
19337
  return {
19244
19338
  memory_id: uuidv75(),
19245
19339
  content: input.content,
19246
19340
  scope,
19247
- level: levelFromScope(scope),
19341
+ level,
19342
+ ...input.kind !== void 0 && input.kind !== null && { kind: input.kind },
19343
+ ...typeof input.kindValue === "string" && { kind_value: input.kindValue },
19248
19344
  created_at: now,
19249
19345
  updated_at: now,
19250
19346
  is_deleted: false,
@@ -19273,6 +19369,30 @@ function createRemoteMemoryStore(options) {
19273
19369
  return records.map((record2) => stored(record2.memory));
19274
19370
  };
19275
19371
  const asStored = (record2) => record2 ? stored(record2.memory) : null;
19372
+ const withKnownKinds = async (topics) => {
19373
+ const unkinded = [
19374
+ ...new Set(topics.filter((t) => !t.kind).map((t) => normalizeEntityName(t.name)))
19375
+ ];
19376
+ if (unkinded.length === 0) return topics;
19377
+ const kinds = /* @__PURE__ */ new Map();
19378
+ for (const names of chunks(unkinded, MAX_QUERY_TOPICS)) {
19379
+ for (const { memory } of await pages(metadata, {
19380
+ topics: names,
19381
+ include_archived: true,
19382
+ include_quarantined: true,
19383
+ include_superseded: true
19384
+ })) {
19385
+ for (const topic of parseTopics(memory.topics) ?? []) {
19386
+ const name = normalizeEntityName(topic.name);
19387
+ if (topic.kind && !kinds.has(name)) kinds.set(name, topic.kind);
19388
+ }
19389
+ }
19390
+ }
19391
+ return topics.map((topic) => {
19392
+ const kind = topic.kind ?? kinds.get(normalizeEntityName(topic.name));
19393
+ return kind ? { ...topic, kind } : topic;
19394
+ });
19395
+ };
19276
19396
  const everyState = {
19277
19397
  include_deleted: true,
19278
19398
  include_archived: true,
@@ -19349,30 +19469,34 @@ function createRemoteMemoryStore(options) {
19349
19469
  });
19350
19470
  };
19351
19471
  return {
19352
- list: async (listOptions = {}) => {
19353
- const order = listOptions.since ? "updated" : "created";
19354
- const filters = {
19355
- ...stateFilters(listOptions),
19356
- include_embeddings: true,
19357
- order,
19358
- ...listOptions.scopes?.length && { scopes: listOptions.scopes },
19359
- ...listOptions.factTypes?.length && { fact_types: listOptions.factTypes },
19360
- ...listOptions.visibility?.length && { visibility: listOptions.visibility },
19361
- ...listOptions.since && { updated_after: listOptions.since.getTime() }
19362
- };
19363
- const max = listOptions.limit && listOptions.limit > 0 ? listOptions.limit : Infinity;
19364
- const variants = bounded(filters, "scopes").flatMap((f) => bounded(f, "fact_types"));
19365
- if (!listOptions.memoryIds && variants.length === 1)
19366
- return (await enumerate(filters, max)).map((r) => stored(r.memory));
19367
- const fetched = await Promise.all(
19368
- variants.map(
19369
- (variant) => listOptions.memoryIds ? enumerateIds(listOptions.memoryIds, variant) : enumerate(variant, max)
19370
- )
19371
- );
19372
- const rows = [...new Map(fetched.flat().map((r) => [r.memory.memory_id, r])).values()].map((record2) => stored(record2.memory)).sort(
19373
- (a, b) => order === "updated" ? b.updatedAt.getTime() - a.updatedAt.getTime() || (a.uniqueId < b.uniqueId ? 1 : -1) : b.createdAt.getTime() - a.createdAt.getTime() || (a.uniqueId < b.uniqueId ? 1 : -1)
19374
- );
19375
- return rows.slice(0, max);
19472
+ list: async (listOptions = {}) => (await listRows(decrypted, listOptions, listFilters(listOptions), maxOf(listOptions))).map(
19473
+ (r) => stored(r.memory)
19474
+ ),
19475
+ listProjections: async (listOptions = {}) => (await listRows(metadata, listOptions, listFilters(listOptions), maxOf(listOptions))).map(
19476
+ projection
19477
+ ),
19478
+ listTopics: async () => {
19479
+ const topics = /* @__PURE__ */ new Map();
19480
+ for (const { memory } of await pages(metadata, {
19481
+ include_archived: true,
19482
+ include_quarantined: true,
19483
+ include_superseded: true
19484
+ })) {
19485
+ for (const topic of parseTopics(memory.topics) ?? []) {
19486
+ const name = normalizeEntityName(topic.name);
19487
+ if (!name) continue;
19488
+ const entry = topics.get(name) ?? {
19489
+ name,
19490
+ kind: null,
19491
+ memoryCount: 0,
19492
+ members: /* @__PURE__ */ new Set()
19493
+ };
19494
+ entry.kind ?? (entry.kind = topic.kind ?? null);
19495
+ entry.members.add(memory.memory_id);
19496
+ topics.set(name, entry);
19497
+ }
19498
+ }
19499
+ return [...topics.values()].map(({ members, ...topic }) => ({ ...topic, memoryCount: members.size })).sort((a, b) => a.name.localeCompare(b.name));
19376
19500
  },
19377
19501
  get: async (id) => asStored(await live(id)),
19378
19502
  listArchived: async () => (await enumerate({ archived_only: true, order: "archived", include_embeddings: true })).map(
@@ -19381,10 +19505,10 @@ function createRemoteMemoryStore(options) {
19381
19505
  memoriesByTopics: async (names) => {
19382
19506
  const wanted = new Set(names.map(normalizeEntityName).filter(Boolean));
19383
19507
  const out = /* @__PURE__ */ new Map();
19384
- const pages = await Promise.all(
19508
+ const pages2 = await Promise.all(
19385
19509
  chunks([...wanted], MAX_QUERY_TOPICS).map((topics) => enumerate({ topics }))
19386
19510
  );
19387
- for (const { memory } of pages.flat()) {
19511
+ for (const { memory } of pages2.flat()) {
19388
19512
  const matched = [...canonicalTopics(memory)].filter((name) => wanted.has(name));
19389
19513
  if (matched.length) out.set(memory.memory_id, new Set(matched));
19390
19514
  }
@@ -19392,7 +19516,7 @@ function createRemoteMemoryStore(options) {
19392
19516
  },
19393
19517
  topicsByMemories: async (memoryIds) => {
19394
19518
  const out = /* @__PURE__ */ new Map();
19395
- for (const { memory } of await enumerateIds(memoryIds, {
19519
+ for (const { memory } of await enumerateIds(decrypted, memoryIds, {
19396
19520
  include_archived: true,
19397
19521
  include_superseded: true,
19398
19522
  include_quarantined: true
@@ -19425,15 +19549,26 @@ function createRemoteMemoryStore(options) {
19425
19549
  update: async (id, patch) => {
19426
19550
  const saved = await mutate(id, "edit", (memory) => {
19427
19551
  if (memory.superseded_by) return null;
19552
+ const level = patch.level !== void 0 ? patch.level : patch.scope !== void 0 ? levelForScopeChange({ level: memory.level, scope: memory.scope }, patch.scope) : resolveMemoryLevel(memory.level, memory.scope);
19553
+ const kind = patch.kind !== void 0 ? patch.kind : memory.kind;
19554
+ assertValidKindLevel(kind, level);
19428
19555
  memory.content = patch.content;
19429
19556
  memory.updated_at = Date.now();
19430
- if (patch.scope !== void 0) {
19431
- memory.level = levelForScopeChange(
19432
- { level: memory.level, scope: memory.scope },
19433
- patch.scope
19434
- );
19557
+ if (patch.level !== void 0) {
19558
+ memory.level = level;
19559
+ memory.scope = scopeForLevel(level);
19560
+ } else if (patch.scope !== void 0) {
19561
+ memory.level = level;
19435
19562
  memory.scope = patch.scope;
19436
19563
  }
19564
+ if (patch.kind !== void 0) {
19565
+ if (patch.kind === null) delete memory.kind;
19566
+ else memory.kind = patch.kind;
19567
+ }
19568
+ if (patch.kindValue !== void 0) {
19569
+ if (patch.kindValue === null) delete memory.kind_value;
19570
+ else memory.kind_value = patch.kindValue;
19571
+ }
19437
19572
  if (patch.factType !== void 0) memory.fact_type = patch.factType ?? void 0;
19438
19573
  if (patch.eventTime !== void 0) {
19439
19574
  memory.event_time_start = patch.eventTime?.start ?? void 0;
@@ -19488,16 +19623,19 @@ function createRemoteMemoryStore(options) {
19488
19623
  notify("edit", [await persistence.put(memory, record2)]);
19489
19624
  return true;
19490
19625
  }),
19491
- setTopics: async (memoryId, topics) => asStored(
19492
- await mutate(memoryId, "edit", (memory) => ({
19493
- ...memory,
19494
- topics: serializeTopics(mergeTopics([], topicInputs(topics, "user"))),
19495
- topics_user_managed: true,
19496
- topics_updated_at: Date.now()
19497
- }))
19498
- ),
19626
+ setTopics: async (memoryId, topics) => {
19627
+ const chosen = await withKnownKinds(topicInputs(topics, "user"));
19628
+ return asStored(
19629
+ await mutate(memoryId, "edit", (memory) => ({
19630
+ ...memory,
19631
+ topics: serializeTopics(mergeTopics([], chosen)),
19632
+ topics_user_managed: true,
19633
+ topics_updated_at: Date.now()
19634
+ }))
19635
+ );
19636
+ },
19499
19637
  addTopics: async (memoryId, topics) => {
19500
- const added = topicInputs(topics, "auto");
19638
+ const added = await withKnownKinds(topicInputs(topics, "auto"));
19501
19639
  const saved = await mutate(memoryId, "edit", (memory) => ({
19502
19640
  ...memory,
19503
19641
  topics: serializeTopics(mergeTopics(parseTopics(memory.topics) ?? [], added)),