@anuma/sdk 6.15.2 → 6.17.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.
@@ -9749,6 +9749,7 @@ __export(index_exports, {
9749
9749
  isDegradedTopicSkip: () => isDegradedTopicSkip,
9750
9750
  isPiiRedactor: () => isPiiRedactor,
9751
9751
  isRerankerAvailable: () => isRerankerAvailable,
9752
+ maskScopedEmbeddingCache: () => maskScopedEmbeddingCache,
9752
9753
  moveMemoriesToFolderOp: () => moveMemoriesToFolderOp,
9753
9754
  noopLogger: () => noopLogger,
9754
9755
  onKeyAvailable: () => onKeyAvailable,
@@ -13485,6 +13486,28 @@ var xhrTransport = (options) => {
13485
13486
  return { stream: createStream() };
13486
13487
  };
13487
13488
 
13489
+ // src/lib/db/chat/embeddingCache.ts
13490
+ var MaskScopedEmbeddingCache = class extends Map {
13491
+ constructor(inner, masked) {
13492
+ super();
13493
+ this.inner = inner;
13494
+ this.masked = masked;
13495
+ }
13496
+ key(text12) {
13497
+ return `${this.masked ? "m" : "r"}:${text12}`;
13498
+ }
13499
+ get(text12) {
13500
+ return this.inner.get(this.key(text12));
13501
+ }
13502
+ set(text12, value) {
13503
+ this.inner.set(this.key(text12), value);
13504
+ return this;
13505
+ }
13506
+ };
13507
+ function maskScopedEmbeddingCache(cache, masked) {
13508
+ return new MaskScopedEmbeddingCache(cache, masked);
13509
+ }
13510
+
13488
13511
  // src/react/useCredits.ts
13489
13512
  var import_react = require("react");
13490
13513
  init_sdk_gen();
@@ -21091,6 +21114,7 @@ function useChatStorage(options) {
21091
21114
  summaryModel = DEFAULT_SUMMARY_MODEL,
21092
21115
  files,
21093
21116
  storedUserContent,
21117
+ embeddingCache,
21094
21118
  onData: perRequestOnData,
21095
21119
  onThinking: perRequestOnThinking,
21096
21120
  memoryContext,
@@ -21130,12 +21154,18 @@ function useChatStorage(options) {
21130
21154
  };
21131
21155
  pendingResumeRef.current = null;
21132
21156
  const effectiveAssistantUniqueId = assistantUniqueId ?? (resumable ? `msg_${(0, import_uuid5.v7)()}` : void 0);
21133
- const embedToolText = (text12, mask, token) => {
21134
- const opts = { getToken: token, baseUrl, model: embeddingModel };
21157
+ const embedToolText = (text12, mask, masked, token) => {
21158
+ const opts = {
21159
+ getToken: token,
21160
+ baseUrl,
21161
+ model: embeddingModel,
21162
+ maskInput: mask,
21163
+ cache: embeddingCache ? maskScopedEmbeddingCache(embeddingCache, masked) : void 0
21164
+ };
21135
21165
  return shouldChunkMessage(text12, DEFAULT_CHUNK_SIZE) ? generateEmbeddings(
21136
- chunkText(text12).map((c) => mask(c.text)),
21166
+ chunkText(text12).map((c) => c.text),
21137
21167
  opts
21138
- ) : generateEmbedding(mask(text12), opts);
21168
+ ) : generateEmbedding(text12, opts);
21139
21169
  };
21140
21170
  if (walletAddress && signMessage && !hasEncryptionKey(walletAddress)) {
21141
21171
  try {
@@ -21175,6 +21205,7 @@ function useChatStorage(options) {
21175
21205
  skipUserEmbedding = await embedToolText(
21176
21206
  messageContent,
21177
21207
  maskForCall2,
21208
+ Boolean(callPiiRedaction2),
21178
21209
  getTokenRef.current
21179
21210
  );
21180
21211
  const toolNames = serverToolsFilter(skipUserEmbedding, allServerTools);
@@ -21195,6 +21226,7 @@ function useChatStorage(options) {
21195
21226
  skipUserEmbedding = await embedToolText(
21196
21227
  messageContent,
21197
21228
  maskForCall2,
21229
+ Boolean(callPiiRedaction2),
21198
21230
  getTokenRef.current
21199
21231
  );
21200
21232
  } catch {
@@ -21343,7 +21375,14 @@ function useChatStorage(options) {
21343
21375
  };
21344
21376
  const embedForToolsSettled = async (token) => {
21345
21377
  try {
21346
- return { embedding: await embedToolText(contentForStorage, maskForCall, token) };
21378
+ return {
21379
+ embedding: await embedToolText(
21380
+ contentForStorage,
21381
+ maskForCall,
21382
+ Boolean(callPiiRedaction),
21383
+ token
21384
+ )
21385
+ };
21347
21386
  } catch (error) {
21348
21387
  return { error };
21349
21388
  }
@@ -24825,6 +24864,7 @@ function createNotionTools(getAccessToken, requestNotionAccess) {
24825
24864
  isDegradedTopicSkip,
24826
24865
  isPiiRedactor,
24827
24866
  isRerankerAvailable,
24867
+ maskScopedEmbeddingCache,
24828
24868
  moveMemoriesToFolderOp,
24829
24869
  noopLogger,
24830
24870
  onKeyAvailable,
@@ -2755,6 +2755,38 @@ declare function resumeStream(options: ResumeStreamOptions): Promise<ResumeStrea
2755
2755
  */
2756
2756
  declare const xhrTransport: StreamingTransport;
2757
2757
 
2758
+ /**
2759
+ * Namespacing for a caller-shared embedding cache.
2760
+ *
2761
+ * Lives here, next to the `embeddingCache` send-arg it serves, rather than in either platform hook:
2762
+ * react and expo both thread the option through their own send paths, and a copy per platform is how
2763
+ * the two drift.
2764
+ */
2765
+ /**
2766
+ * Build the same namespaced view over `cache` that a send with this masking decision uses.
2767
+ *
2768
+ * REQUIRED FOR SHARING, and the reason this is exported at all. `embeddingCache`'s whole purpose is
2769
+ * that a caller who also needs the prompt vector passes one `Map` to both `sendMessage` and its own
2770
+ * `generateEmbedding` call, so the turn embeds once. But the send namespaces its entries by masking
2771
+ * decision (see {@link MaskScopedEmbeddingCache}) while `generateEmbedding` keys on the text alone —
2772
+ * so a caller handing the RAW `Map` to its own call writes `"hello"` where the send looks for
2773
+ * `"r:hello"`, and neither side ever hits. The dedupe silently does not happen.
2774
+ *
2775
+ * So: pass the plain `Map` as `embeddingCache`, and wrap it with this for your own call.
2776
+ *
2777
+ * ```ts
2778
+ * const shared = new Map<string, Float32Array>();
2779
+ * // your own ranking embed, same masking decision as the send:
2780
+ * await generateEmbedding(text, { getToken, cache: maskScopedEmbeddingCache(shared, masked) });
2781
+ * await sendMessage({ ..., embeddingCache: shared, piiRedaction: masked });
2782
+ * ```
2783
+ *
2784
+ * `masked` must match what the send resolves for the same turn — i.e. whether PII redaction is on.
2785
+ * Get it wrong and you simply miss the cache; you cannot be served the other decision's vector,
2786
+ * which is the property the namespacing exists to guarantee.
2787
+ */
2788
+ declare function maskScopedEmbeddingCache(cache: Map<string, Float32Array>, masked: boolean): Map<string, Float32Array>;
2789
+
2758
2790
  /**
2759
2791
  * @inline
2760
2792
  */
@@ -4071,6 +4103,37 @@ interface BaseSendMessageWithStorageArgs {
4071
4103
  * user content (matching a textless turn), NOT a request to fall back.
4072
4104
  */
4073
4105
  storedUserContent?: string;
4106
+ /**
4107
+ * Optional embedding cache, shared with the caller.
4108
+ *
4109
+ * Every send that needs tool selection embeds the user text once (see
4110
+ * `storedUserContent`). A caller that ALSO needs that vector — to rank tools itself, say, or to
4111
+ * hand a server a prompt-aware shortlist — otherwise pays for a second, identical embedding of
4112
+ * the same text in the same turn. Pass a `Map` here and into your own
4113
+ * `generateEmbedding`/`generateEmbeddings` call and whichever runs first fills it; the other is a
4114
+ * cache hit, so the turn embeds once.
4115
+ *
4116
+ * Keyed on the text **as passed in** (before `maskInput` is applied to the request body), prefixed
4117
+ * with a marker for this send's masking decision — `"r:"` raw, `"m:"` masked — so a mismatched
4118
+ * masking decision cannot silently serve the wrong vector: masked and unmasked occupy different
4119
+ * entries. `generateEmbedding`'s own contract is unchanged; it still keys on the text alone, and
4120
+ * the prefixing is a view this send wraps around the `Map` you hand it.
4121
+ *
4122
+ * WHICH MEANS SHARING TAKES ONE MORE STEP, and skipping it costs you the dedupe silently: pass
4123
+ * the plain `Map` here, and wrap it with `maskScopedEmbeddingCache(map, masked)` for your OWN
4124
+ * `generateEmbedding` call, so both sides look under the same key. Hand the raw `Map` to both and
4125
+ * your call writes `"hello"` while this one reads `"r:hello"` — no hit, and the second embedding
4126
+ * you were trying to avoid still happens.
4127
+ *
4128
+ * **Long messages are not deduped.** Past `DEFAULT_CHUNK_SIZE` (400 chars) the send embeds one
4129
+ * vector per chunk and keys each entry on its chunk text, so a caller that embedded the whole
4130
+ * prompt in one call finds nothing and both sides still pay. Making that hit would mean the caller
4131
+ * reproducing the SDK's chunking, which is a worse contract than admitting the gap: short prompts
4132
+ * — the overwhelming majority — dedupe, long ones do not.
4133
+ *
4134
+ * Omit it and nothing changes: every send embeds independently, exactly as before.
4135
+ */
4136
+ embeddingCache?: Map<string, Float32Array>;
4074
4137
  /**
4075
4138
  * Per-request callback invoked with each streamed response chunk.
4076
4139
  * Overrides the hook-level `onData` callback for this request only.
@@ -10591,4 +10654,4 @@ declare function refreshNotionAccessToken(params: NotionRefreshTokenParams): Pro
10591
10654
  */
10592
10655
  declare function createNotionTools(getAccessToken: () => string | null, requestNotionAccess: () => Promise<string>): ToolConfig[];
10593
10656
 
10594
- 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 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, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type FactType, type FileMetadata, 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 Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, type MemoriesNeedingTopicExtraction, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryQuarantinedEvent, type MemoryToVerify, 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 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 RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RequestEncryptionKeyOptions, RerankerUnavailableError, 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 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 VaultFolderOperationsContext, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultSaveOperation, type VaultSearchResult, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, backfillMemoryTopicsOp, 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, createLlmDecayClassifier, createLlmNeighborRefiner, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionTools, createPlatformCursorStore, createRecallTool, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, 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, isDegradedTopicSkip, isPiiRedactor, isRerankerAvailable, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
10657
+ 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 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, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type FactType, type FileMetadata, 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 Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, type MemoriesNeedingTopicExtraction, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryQuarantinedEvent, type MemoryToVerify, 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 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 RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RequestEncryptionKeyOptions, RerankerUnavailableError, 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 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 VaultFolderOperationsContext, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultSaveOperation, type VaultSearchResult, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, backfillMemoryTopicsOp, 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, createLlmDecayClassifier, createLlmNeighborRefiner, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionTools, createPlatformCursorStore, createRecallTool, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, 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, isDegradedTopicSkip, isPiiRedactor, isRerankerAvailable, maskScopedEmbeddingCache, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
@@ -2755,6 +2755,38 @@ declare function resumeStream(options: ResumeStreamOptions): Promise<ResumeStrea
2755
2755
  */
2756
2756
  declare const xhrTransport: StreamingTransport;
2757
2757
 
2758
+ /**
2759
+ * Namespacing for a caller-shared embedding cache.
2760
+ *
2761
+ * Lives here, next to the `embeddingCache` send-arg it serves, rather than in either platform hook:
2762
+ * react and expo both thread the option through their own send paths, and a copy per platform is how
2763
+ * the two drift.
2764
+ */
2765
+ /**
2766
+ * Build the same namespaced view over `cache` that a send with this masking decision uses.
2767
+ *
2768
+ * REQUIRED FOR SHARING, and the reason this is exported at all. `embeddingCache`'s whole purpose is
2769
+ * that a caller who also needs the prompt vector passes one `Map` to both `sendMessage` and its own
2770
+ * `generateEmbedding` call, so the turn embeds once. But the send namespaces its entries by masking
2771
+ * decision (see {@link MaskScopedEmbeddingCache}) while `generateEmbedding` keys on the text alone —
2772
+ * so a caller handing the RAW `Map` to its own call writes `"hello"` where the send looks for
2773
+ * `"r:hello"`, and neither side ever hits. The dedupe silently does not happen.
2774
+ *
2775
+ * So: pass the plain `Map` as `embeddingCache`, and wrap it with this for your own call.
2776
+ *
2777
+ * ```ts
2778
+ * const shared = new Map<string, Float32Array>();
2779
+ * // your own ranking embed, same masking decision as the send:
2780
+ * await generateEmbedding(text, { getToken, cache: maskScopedEmbeddingCache(shared, masked) });
2781
+ * await sendMessage({ ..., embeddingCache: shared, piiRedaction: masked });
2782
+ * ```
2783
+ *
2784
+ * `masked` must match what the send resolves for the same turn — i.e. whether PII redaction is on.
2785
+ * Get it wrong and you simply miss the cache; you cannot be served the other decision's vector,
2786
+ * which is the property the namespacing exists to guarantee.
2787
+ */
2788
+ declare function maskScopedEmbeddingCache(cache: Map<string, Float32Array>, masked: boolean): Map<string, Float32Array>;
2789
+
2758
2790
  /**
2759
2791
  * @inline
2760
2792
  */
@@ -4071,6 +4103,37 @@ interface BaseSendMessageWithStorageArgs {
4071
4103
  * user content (matching a textless turn), NOT a request to fall back.
4072
4104
  */
4073
4105
  storedUserContent?: string;
4106
+ /**
4107
+ * Optional embedding cache, shared with the caller.
4108
+ *
4109
+ * Every send that needs tool selection embeds the user text once (see
4110
+ * `storedUserContent`). A caller that ALSO needs that vector — to rank tools itself, say, or to
4111
+ * hand a server a prompt-aware shortlist — otherwise pays for a second, identical embedding of
4112
+ * the same text in the same turn. Pass a `Map` here and into your own
4113
+ * `generateEmbedding`/`generateEmbeddings` call and whichever runs first fills it; the other is a
4114
+ * cache hit, so the turn embeds once.
4115
+ *
4116
+ * Keyed on the text **as passed in** (before `maskInput` is applied to the request body), prefixed
4117
+ * with a marker for this send's masking decision — `"r:"` raw, `"m:"` masked — so a mismatched
4118
+ * masking decision cannot silently serve the wrong vector: masked and unmasked occupy different
4119
+ * entries. `generateEmbedding`'s own contract is unchanged; it still keys on the text alone, and
4120
+ * the prefixing is a view this send wraps around the `Map` you hand it.
4121
+ *
4122
+ * WHICH MEANS SHARING TAKES ONE MORE STEP, and skipping it costs you the dedupe silently: pass
4123
+ * the plain `Map` here, and wrap it with `maskScopedEmbeddingCache(map, masked)` for your OWN
4124
+ * `generateEmbedding` call, so both sides look under the same key. Hand the raw `Map` to both and
4125
+ * your call writes `"hello"` while this one reads `"r:hello"` — no hit, and the second embedding
4126
+ * you were trying to avoid still happens.
4127
+ *
4128
+ * **Long messages are not deduped.** Past `DEFAULT_CHUNK_SIZE` (400 chars) the send embeds one
4129
+ * vector per chunk and keys each entry on its chunk text, so a caller that embedded the whole
4130
+ * prompt in one call finds nothing and both sides still pay. Making that hit would mean the caller
4131
+ * reproducing the SDK's chunking, which is a worse contract than admitting the gap: short prompts
4132
+ * — the overwhelming majority — dedupe, long ones do not.
4133
+ *
4134
+ * Omit it and nothing changes: every send embeds independently, exactly as before.
4135
+ */
4136
+ embeddingCache?: Map<string, Float32Array>;
4074
4137
  /**
4075
4138
  * Per-request callback invoked with each streamed response chunk.
4076
4139
  * Overrides the hook-level `onData` callback for this request only.
@@ -10591,4 +10654,4 @@ declare function refreshNotionAccessToken(params: NotionRefreshTokenParams): Pro
10591
10654
  */
10592
10655
  declare function createNotionTools(getAccessToken: () => string | null, requestNotionAccess: () => Promise<string>): ToolConfig[];
10593
10656
 
10594
- 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 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, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type FactType, type FileMetadata, 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 Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, type MemoriesNeedingTopicExtraction, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryQuarantinedEvent, type MemoryToVerify, 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 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 RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RequestEncryptionKeyOptions, RerankerUnavailableError, 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 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 VaultFolderOperationsContext, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultSaveOperation, type VaultSearchResult, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, backfillMemoryTopicsOp, 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, createLlmDecayClassifier, createLlmNeighborRefiner, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionTools, createPlatformCursorStore, createRecallTool, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, 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, isDegradedTopicSkip, isPiiRedactor, isRerankerAvailable, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
10657
+ 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 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, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type FactType, type FileMetadata, 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 Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, type MemoriesNeedingTopicExtraction, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryQuarantinedEvent, type MemoryToVerify, 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 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 RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RequestEncryptionKeyOptions, RerankerUnavailableError, 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 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 VaultFolderOperationsContext, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultSaveOperation, type VaultSearchResult, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, backfillMemoryTopicsOp, 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, createLlmDecayClassifier, createLlmNeighborRefiner, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionTools, createPlatformCursorStore, createRecallTool, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, 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, isDegradedTopicSkip, isPiiRedactor, isRerankerAvailable, maskScopedEmbeddingCache, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
@@ -3818,6 +3818,28 @@ var xhrTransport = (options) => {
3818
3818
  return { stream: createStream() };
3819
3819
  };
3820
3820
 
3821
+ // src/lib/db/chat/embeddingCache.ts
3822
+ var MaskScopedEmbeddingCache = class extends Map {
3823
+ constructor(inner, masked) {
3824
+ super();
3825
+ this.inner = inner;
3826
+ this.masked = masked;
3827
+ }
3828
+ key(text12) {
3829
+ return `${this.masked ? "m" : "r"}:${text12}`;
3830
+ }
3831
+ get(text12) {
3832
+ return this.inner.get(this.key(text12));
3833
+ }
3834
+ set(text12, value) {
3835
+ this.inner.set(this.key(text12), value);
3836
+ return this;
3837
+ }
3838
+ };
3839
+ function maskScopedEmbeddingCache(cache, masked) {
3840
+ return new MaskScopedEmbeddingCache(cache, masked);
3841
+ }
3842
+
3821
3843
  // src/react/useCredits.ts
3822
3844
  import { useCallback, useEffect, useRef, useState } from "react";
3823
3845
  function useCredits(options = {}) {
@@ -11291,6 +11313,7 @@ function useChatStorage(options) {
11291
11313
  summaryModel = DEFAULT_SUMMARY_MODEL,
11292
11314
  files,
11293
11315
  storedUserContent,
11316
+ embeddingCache,
11294
11317
  onData: perRequestOnData,
11295
11318
  onThinking: perRequestOnThinking,
11296
11319
  memoryContext,
@@ -11330,12 +11353,18 @@ function useChatStorage(options) {
11330
11353
  };
11331
11354
  pendingResumeRef.current = null;
11332
11355
  const effectiveAssistantUniqueId = assistantUniqueId ?? (resumable ? `msg_${uuidv73()}` : void 0);
11333
- const embedToolText = (text12, mask, token) => {
11334
- const opts = { getToken: token, baseUrl, model: embeddingModel };
11356
+ const embedToolText = (text12, mask, masked, token) => {
11357
+ const opts = {
11358
+ getToken: token,
11359
+ baseUrl,
11360
+ model: embeddingModel,
11361
+ maskInput: mask,
11362
+ cache: embeddingCache ? maskScopedEmbeddingCache(embeddingCache, masked) : void 0
11363
+ };
11335
11364
  return shouldChunkMessage(text12, DEFAULT_CHUNK_SIZE) ? generateEmbeddings(
11336
- chunkText(text12).map((c) => mask(c.text)),
11365
+ chunkText(text12).map((c) => c.text),
11337
11366
  opts
11338
- ) : generateEmbedding(mask(text12), opts);
11367
+ ) : generateEmbedding(text12, opts);
11339
11368
  };
11340
11369
  if (walletAddress && signMessage && !hasEncryptionKey(walletAddress)) {
11341
11370
  try {
@@ -11375,6 +11404,7 @@ function useChatStorage(options) {
11375
11404
  skipUserEmbedding = await embedToolText(
11376
11405
  messageContent,
11377
11406
  maskForCall2,
11407
+ Boolean(callPiiRedaction2),
11378
11408
  getTokenRef.current
11379
11409
  );
11380
11410
  const toolNames = serverToolsFilter(skipUserEmbedding, allServerTools);
@@ -11395,6 +11425,7 @@ function useChatStorage(options) {
11395
11425
  skipUserEmbedding = await embedToolText(
11396
11426
  messageContent,
11397
11427
  maskForCall2,
11428
+ Boolean(callPiiRedaction2),
11398
11429
  getTokenRef.current
11399
11430
  );
11400
11431
  } catch {
@@ -11543,7 +11574,14 @@ function useChatStorage(options) {
11543
11574
  };
11544
11575
  const embedForToolsSettled = async (token) => {
11545
11576
  try {
11546
- return { embedding: await embedToolText(contentForStorage, maskForCall, token) };
11577
+ return {
11578
+ embedding: await embedToolText(
11579
+ contentForStorage,
11580
+ maskForCall,
11581
+ Boolean(callPiiRedaction),
11582
+ token
11583
+ )
11584
+ };
11547
11585
  } catch (error) {
11548
11586
  return { error };
11549
11587
  }
@@ -15017,6 +15055,7 @@ export {
15017
15055
  isDegradedTopicSkip,
15018
15056
  isPiiRedactor,
15019
15057
  isRerankerAvailable,
15058
+ maskScopedEmbeddingCache,
15020
15059
  moveMemoriesToFolderOp,
15021
15060
  noopLogger,
15022
15061
  onKeyAvailable,
@@ -10208,6 +10208,7 @@ __export(index_exports, {
10208
10208
  isSupportedFile: () => isSupportedFile,
10209
10209
  isSupportedMediaType: () => isSupportedMediaType,
10210
10210
  linkMemoryEntitiesOp: () => linkMemoryEntitiesOp,
10211
+ maskScopedEmbeddingCache: () => maskScopedEmbeddingCache,
10211
10212
  mediaToStored: () => mediaToStored,
10212
10213
  migrateCalendarToken: () => migrateCalendarToken,
10213
10214
  migrateDisplayResult: () => migrateDisplayResult,
@@ -15851,6 +15852,28 @@ var chatStorageMigrations = (0, import_migrations.schemaMigrations)({
15851
15852
  // src/lib/db/chat/index.ts
15852
15853
  init_types2();
15853
15854
 
15855
+ // src/lib/db/chat/embeddingCache.ts
15856
+ var MaskScopedEmbeddingCache = class extends Map {
15857
+ constructor(inner, masked) {
15858
+ super();
15859
+ this.inner = inner;
15860
+ this.masked = masked;
15861
+ }
15862
+ key(text12) {
15863
+ return `${this.masked ? "m" : "r"}:${text12}`;
15864
+ }
15865
+ get(text12) {
15866
+ return this.inner.get(this.key(text12));
15867
+ }
15868
+ set(text12, value) {
15869
+ this.inner.set(this.key(text12), value);
15870
+ return this;
15871
+ }
15872
+ };
15873
+ function maskScopedEmbeddingCache(cache, masked) {
15874
+ return new MaskScopedEmbeddingCache(cache, masked);
15875
+ }
15876
+
15854
15877
  // src/lib/db/media/models.ts
15855
15878
  var import_watermelondb5 = require("@nozbe/watermelondb");
15856
15879
  var import_decorators2 = require("@nozbe/watermelondb/decorators");
@@ -23689,6 +23712,7 @@ function useChatStorage(options) {
23689
23712
  summaryModel = DEFAULT_SUMMARY_MODEL,
23690
23713
  files,
23691
23714
  storedUserContent,
23715
+ embeddingCache,
23692
23716
  onData: perRequestOnData,
23693
23717
  headers,
23694
23718
  memoryContext,
@@ -23750,19 +23774,22 @@ function useChatStorage(options) {
23750
23774
  extracted2?.content ?? ""
23751
23775
  );
23752
23776
  if (messageContent.length >= MIN_CONTENT_LENGTH_FOR_TOOLS) {
23753
- const embeddingOptions = { getToken, baseUrl, model: embeddingModel };
23777
+ const embeddingOptions = {
23778
+ getToken,
23779
+ baseUrl,
23780
+ model: embeddingModel,
23781
+ maskInput: maskForCall2,
23782
+ cache: embeddingCache ? maskScopedEmbeddingCache(embeddingCache, Boolean(callPiiRedaction2)) : void 0
23783
+ };
23754
23784
  try {
23755
23785
  if (shouldChunkMessage(messageContent, DEFAULT_CHUNK_SIZE)) {
23756
23786
  const textChunks = chunkText(messageContent);
23757
23787
  skipStorageEmbeddings = await generateEmbeddings(
23758
- textChunks.map((c) => maskForCall2(c.text)),
23788
+ textChunks.map((c) => c.text),
23759
23789
  embeddingOptions
23760
23790
  );
23761
23791
  } else {
23762
- skipStorageEmbeddings = await generateEmbedding(
23763
- maskForCall2(messageContent),
23764
- embeddingOptions
23765
- );
23792
+ skipStorageEmbeddings = await generateEmbedding(messageContent, embeddingOptions);
23766
23793
  }
23767
23794
  } catch {
23768
23795
  skipStorageEmbeddingsFailed = true;
@@ -23952,21 +23979,26 @@ function useChatStorage(options) {
23952
23979
  const needsEmbeddings = isServerToolsFunction || !!clientToolsFilter || !!clientTools?.length;
23953
23980
  const embeddingsPromise = needsEmbeddings && getToken ? (async () => {
23954
23981
  try {
23955
- const embeddingOptions = { getToken, baseUrl, model: embeddingModel };
23982
+ const embeddingOptions = {
23983
+ getToken,
23984
+ baseUrl,
23985
+ model: embeddingModel,
23986
+ maskInput: maskForCall,
23987
+ cache: embeddingCache ? maskScopedEmbeddingCache(embeddingCache, Boolean(callPiiRedaction)) : void 0
23988
+ };
23956
23989
  if (shouldChunkMessage(contentForStorage, DEFAULT_CHUNK_SIZE)) {
23957
23990
  const textChunks = chunkText(contentForStorage);
23958
- const chunkTexts = textChunks.map((c) => maskForCall(c.text));
23959
23991
  return {
23960
- embeddings: await generateEmbeddings(chunkTexts, embeddingOptions),
23992
+ embeddings: await generateEmbeddings(
23993
+ textChunks.map((c) => c.text),
23994
+ embeddingOptions
23995
+ ),
23961
23996
  failed: false
23962
23997
  };
23963
23998
  }
23964
23999
  if (contentForStorage.length >= MIN_CONTENT_LENGTH_FOR_TOOLS) {
23965
24000
  return {
23966
- embeddings: await generateEmbedding(
23967
- maskForCall(contentForStorage),
23968
- embeddingOptions
23969
- ),
24001
+ embeddings: await generateEmbedding(contentForStorage, embeddingOptions),
23970
24002
  failed: false
23971
24003
  };
23972
24004
  }
@@ -35760,6 +35792,7 @@ function renderAnumaJsx(jsx3) {
35760
35792
  isSupportedFile,
35761
35793
  isSupportedMediaType,
35762
35794
  linkMemoryEntitiesOp,
35795
+ maskScopedEmbeddingCache,
35763
35796
  mediaToStored,
35764
35797
  migrateCalendarToken,
35765
35798
  migrateDisplayResult,