@anuma/sdk 6.7.2 → 6.8.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.
Files changed (32) hide show
  1. package/dist/{react/chunk-B5UPJRCU.mjs → expo/chunk-CJ32HO6Q.mjs} +62 -11
  2. package/dist/expo/{chunk-VOMDHMKH.mjs → chunk-OUFITMDL.mjs} +1 -1
  3. package/dist/expo/{chunk-2YHVYDEL.mjs → chunk-YO5UXOC4.mjs} +3 -2
  4. package/dist/{react/consolidate-ZCGS7QUA.mjs → expo/consolidate-4BMNVOL4.mjs} +3 -2
  5. package/dist/expo/index.cjs +101 -18
  6. package/dist/expo/index.d.mts +105 -2
  7. package/dist/expo/index.d.ts +105 -2
  8. package/dist/expo/index.mjs +34 -10
  9. package/dist/expo/{recall-M3JVFTZL.mjs → recall-IEKVX4JL.mjs} +2 -2
  10. package/dist/index.cjs +10 -0
  11. package/dist/index.d.mts +49 -1
  12. package/dist/index.d.ts +49 -1
  13. package/dist/index.mjs +8 -0
  14. package/dist/{expo/chunk-B5UPJRCU.mjs → react/chunk-CJ32HO6Q.mjs} +62 -11
  15. package/dist/react/{chunk-2ARMO2NN.mjs → chunk-DY5VGC6K.mjs} +1 -1
  16. package/dist/react/{chunk-S6WPXD5N.mjs → chunk-POCLKALT.mjs} +3 -2
  17. package/dist/{expo/consolidate-TWE6OSSZ.mjs → react/consolidate-5TP3J6BY.mjs} +3 -2
  18. package/dist/react/index.cjs +101 -18
  19. package/dist/react/index.d.mts +105 -2
  20. package/dist/react/index.d.ts +105 -2
  21. package/dist/react/index.mjs +34 -10
  22. package/dist/react/{recall-ROEK55FJ.mjs → recall-B2AIAPCM.mjs} +2 -2
  23. package/dist/server/{chunk-TD7SMY7C.mjs → chunk-FS6DNUNT.mjs} +3 -2
  24. package/dist/server/{chunk-VHWLLYKO.mjs → chunk-KF5OU4IN.mjs} +62 -11
  25. package/dist/server/{chunk-CR5P3YIK.mjs → chunk-MEQ2PAEX.mjs} +1 -1
  26. package/dist/server/{consolidate-FWYK5KXB.mjs → consolidate-QDWEYFTZ.mjs} +3 -2
  27. package/dist/server/index.cjs +101 -18
  28. package/dist/server/index.d.mts +105 -2
  29. package/dist/server/index.d.ts +105 -2
  30. package/dist/server/index.mjs +34 -10
  31. package/dist/server/{recall-CGDEW2LQ.mjs → recall-2GAPE2XH.mjs} +2 -2
  32. package/package.json +1 -1
@@ -4862,6 +4862,44 @@ interface EntityOperationsContext {
4862
4862
  allowUnscopedRows?: boolean;
4863
4863
  }
4864
4864
 
4865
+ /**
4866
+ * Shared portal LLM call for the memory pipeline.
4867
+ *
4868
+ * The three LLM-driven steps (`extractFacts`, `consolidateMemory`,
4869
+ * `decomposeQuery`) share the same shape: POST to `/api/v1/chat/completions`
4870
+ * with a system+user prompt and `response_format: json_object`, parse
4871
+ * `choices[0].message.content` as JSON, validate, return null on any failure.
4872
+ * This helper owns the fetch+timeout+parse+log boilerplate so each caller
4873
+ * stays focused on its prompt and validator.
4874
+ *
4875
+ * PROMPT CACHING. The portal inserts explicit prompt-cache breakpoints only for
4876
+ * `anthropic/` models. Its request schema does carry OpenAI's
4877
+ * `prompt_cache_key`, but that is a routing hint for OpenAI's own implicit
4878
+ * cache rather than a switch that enables caching, and we deliberately don't
4879
+ * send it: the memory pipeline runs open-weights models by default (gpt-oss for
4880
+ * extraction/topics, ling for consolidation), and this module already has one
4881
+ * hard lesson about OpenAI-standard fields a non-OpenAI provider hard-400s on
4882
+ * (`response_format`, below). Revisit only with a verified per-provider gate.
4883
+ *
4884
+ * So on the models this pipeline actually uses, the only cache that can hit is
4885
+ * the provider's own implicit prefix cache — which makes prefix stability the
4886
+ * one lever a caller controls. Messages are assembled system-first (below), so
4887
+ * every caller must pass a CONSTANT `systemPrompt` and keep all per-call
4888
+ * material in `userMessage`: a single interpolated timestamp, id, or count in a
4889
+ * system prompt shifts every byte after it and misses the cache on every
4890
+ * request thereafter. The memory callers are regression-gated on that property
4891
+ * in `promptPrefixStability.test.ts`.
4892
+ *
4893
+ * Whether those implicit caches hit is observable: each successful response
4894
+ * logs the portal's reported token counts at debug level, including
4895
+ * `portal.cached_tokens` (the prompt tokens the provider served from cache —
4896
+ * the portal omits the field when there was no hit). See {@link logPortalUsage}.
4897
+ *
4898
+ * There is no batch/async-bulk route on the portal, so a backfill or reindex
4899
+ * has no discounted-throughput path either; its only levers are the same stable
4900
+ * prefix and caller-side batching (e.g. topicExtract's 10-memories-per-call).
4901
+ */
4902
+
4865
4903
  /**
4866
4904
  * Auth for portal LLM calls (extraction, consolidation, decomposition,
4867
4905
  * reflection). Mirrors `memoryEngine`'s `EmbeddingOptions` dual-auth:
@@ -4880,6 +4918,60 @@ interface PortalLlmAuth {
4880
4918
  /** Function to get an auth token (e.g., Privy's getIdentityToken). Token is sent as `Authorization: Bearer`. */
4881
4919
  getToken?: () => Promise<string | null>;
4882
4920
  }
4921
+ /**
4922
+ * Why a portal JSON completion gave up, as a STABLE low-cardinality code.
4923
+ *
4924
+ * The retry loop has always classified its failures precisely, but only as an
4925
+ * interpolated `reason` string for `log.warn` — and prod ships no SDK log
4926
+ * (sdk#883), so in production every one of these collapsed into a single
4927
+ * `empty-after-retry` with no way to tell them apart. That is what made the
4928
+ * 2026-08-11 audit need a Prometheus cross-check to discover that the portal
4929
+ * was returning HTTP 200 with an empty body on ~60% of extraction turns.
4930
+ *
4931
+ * Codes are deliberately an enum, not the `reason` string: the strings embed
4932
+ * status codes and error messages, so they are unbounded and useless as an
4933
+ * analytics property. Keep this list SHORT and stable — it is a telemetry
4934
+ * contract, and a value added here has to mean the same thing in six months.
4935
+ *
4936
+ * @public
4937
+ */
4938
+ type PortalLlmFailureReason =
4939
+ /** No usable credential — `getToken` returned null or threw. Terminal. */
4940
+ "auth-unavailable"
4941
+ /** Non-retryable HTTP status (400/403/404, or 401 on the static-apiKey path). */
4942
+ | "http-terminal"
4943
+ /** Retryable status (408/409/425/429/5xx) that never succeeded. */
4944
+ | "http-retryable"
4945
+ /** Network error or the per-attempt timeout aborted the fetch. */
4946
+ | "network"
4947
+ /** HTTP 200 but the envelope itself wasn't JSON. */
4948
+ | "body-parse-failed"
4949
+ /**
4950
+ * HTTP 200 with NO completion content. The reasoning-class failure mode:
4951
+ * the model spends its budget on unreturned thinking and answers empty.
4952
+ */
4953
+ | "empty-content"
4954
+ /** Content present, but no parseable JSON in it (prose, a clarifying question). */
4955
+ | "invalid-json"
4956
+ /** Content parsed to a literal `null`, which is never a valid response. */
4957
+ | "null-completion"
4958
+ /** `totalTimeoutMs` was spent before the next attempt could run. */
4959
+ | "time-budget-exhausted";
4960
+ /**
4961
+ * A give-up report: the classified {@link PortalLlmFailureReason} plus the
4962
+ * little context worth carrying into telemetry. Both extra fields are bounded
4963
+ * (a status code, a small attempt count), so both are safe as event properties.
4964
+ *
4965
+ * @public
4966
+ */
4967
+ interface PortalLlmFailure {
4968
+ /** Stable code for the last failure observed. */
4969
+ reason: PortalLlmFailureReason;
4970
+ /** HTTP status, when the failure was an HTTP one. */
4971
+ httpStatus?: number;
4972
+ /** How many attempts ran before giving up (1-based, ≥ 1). */
4973
+ attempts: number;
4974
+ }
4883
4975
 
4884
4976
  /**
4885
4977
  * Optional LLM injection classifier — Tier-0 security second layer (PR5).
@@ -5984,8 +6076,14 @@ interface ExtractFactsOptions extends PortalLlmAuth {
5984
6076
  * `{candidates: []}` "nothing durable here". Lets callers distinguish a
5985
6077
  * silently-degrading extractor from quiet turns (the two are otherwise
5986
6078
  * indistinguishable). See {@link extractAndRetain}'s `outcome`.
6079
+ *
6080
+ * Receives the classified {@link PortalLlmFailure}. Knowing THAT extraction
6081
+ * failed was not enough: the 2026-08-11 audit found ~60% of production turns
6082
+ * ending here and had to cross-check Prometheus to learn that the cause was
6083
+ * HTTP-200-with-empty-body rather than the 403 everyone assumed. Forward
6084
+ * `failure.reason` into analytics so the next such question is a query.
5987
6085
  */
5988
- onExhaustedEmpty?: () => void;
6086
+ onExhaustedEmpty?: (failure: PortalLlmFailure) => void;
5989
6087
  /**
5990
6088
  * Called when the extractor DID produce candidates but PII de-anonymization
5991
6089
  * dropped every one of them — the model mangled its placeholders (so they
@@ -6108,6 +6206,11 @@ declare function extractAndRetain(messages: AutoExtractMessage[], retainCtx: Ret
6108
6206
  * "extracted but held for review".
6109
6207
  */
6110
6208
  quarantined: QuarantinedMemoryInfo[];
6209
+ /**
6210
+ * Present only when `outcome` is `empty-after-retry` — the classified cause of
6211
+ * the give-up, so "extraction is failing" can be reported as *why* it failed.
6212
+ */
6213
+ failure?: PortalLlmFailure;
6111
6214
  }>;
6112
6215
 
6113
6216
  /**
@@ -10232,4 +10335,4 @@ declare function refreshNotionAccessToken(params: NotionRefreshTokenParams): Pro
10232
10335
  */
10233
10336
  declare function createNotionTools(getAccessToken: () => string | null, requestNotionAccess: () => Promise<string>): ToolConfig[];
10234
10337
 
10235
- 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 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 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, 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 };
10338
+ 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 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, 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 };
@@ -4862,6 +4862,44 @@ interface EntityOperationsContext {
4862
4862
  allowUnscopedRows?: boolean;
4863
4863
  }
4864
4864
 
4865
+ /**
4866
+ * Shared portal LLM call for the memory pipeline.
4867
+ *
4868
+ * The three LLM-driven steps (`extractFacts`, `consolidateMemory`,
4869
+ * `decomposeQuery`) share the same shape: POST to `/api/v1/chat/completions`
4870
+ * with a system+user prompt and `response_format: json_object`, parse
4871
+ * `choices[0].message.content` as JSON, validate, return null on any failure.
4872
+ * This helper owns the fetch+timeout+parse+log boilerplate so each caller
4873
+ * stays focused on its prompt and validator.
4874
+ *
4875
+ * PROMPT CACHING. The portal inserts explicit prompt-cache breakpoints only for
4876
+ * `anthropic/` models. Its request schema does carry OpenAI's
4877
+ * `prompt_cache_key`, but that is a routing hint for OpenAI's own implicit
4878
+ * cache rather than a switch that enables caching, and we deliberately don't
4879
+ * send it: the memory pipeline runs open-weights models by default (gpt-oss for
4880
+ * extraction/topics, ling for consolidation), and this module already has one
4881
+ * hard lesson about OpenAI-standard fields a non-OpenAI provider hard-400s on
4882
+ * (`response_format`, below). Revisit only with a verified per-provider gate.
4883
+ *
4884
+ * So on the models this pipeline actually uses, the only cache that can hit is
4885
+ * the provider's own implicit prefix cache — which makes prefix stability the
4886
+ * one lever a caller controls. Messages are assembled system-first (below), so
4887
+ * every caller must pass a CONSTANT `systemPrompt` and keep all per-call
4888
+ * material in `userMessage`: a single interpolated timestamp, id, or count in a
4889
+ * system prompt shifts every byte after it and misses the cache on every
4890
+ * request thereafter. The memory callers are regression-gated on that property
4891
+ * in `promptPrefixStability.test.ts`.
4892
+ *
4893
+ * Whether those implicit caches hit is observable: each successful response
4894
+ * logs the portal's reported token counts at debug level, including
4895
+ * `portal.cached_tokens` (the prompt tokens the provider served from cache —
4896
+ * the portal omits the field when there was no hit). See {@link logPortalUsage}.
4897
+ *
4898
+ * There is no batch/async-bulk route on the portal, so a backfill or reindex
4899
+ * has no discounted-throughput path either; its only levers are the same stable
4900
+ * prefix and caller-side batching (e.g. topicExtract's 10-memories-per-call).
4901
+ */
4902
+
4865
4903
  /**
4866
4904
  * Auth for portal LLM calls (extraction, consolidation, decomposition,
4867
4905
  * reflection). Mirrors `memoryEngine`'s `EmbeddingOptions` dual-auth:
@@ -4880,6 +4918,60 @@ interface PortalLlmAuth {
4880
4918
  /** Function to get an auth token (e.g., Privy's getIdentityToken). Token is sent as `Authorization: Bearer`. */
4881
4919
  getToken?: () => Promise<string | null>;
4882
4920
  }
4921
+ /**
4922
+ * Why a portal JSON completion gave up, as a STABLE low-cardinality code.
4923
+ *
4924
+ * The retry loop has always classified its failures precisely, but only as an
4925
+ * interpolated `reason` string for `log.warn` — and prod ships no SDK log
4926
+ * (sdk#883), so in production every one of these collapsed into a single
4927
+ * `empty-after-retry` with no way to tell them apart. That is what made the
4928
+ * 2026-08-11 audit need a Prometheus cross-check to discover that the portal
4929
+ * was returning HTTP 200 with an empty body on ~60% of extraction turns.
4930
+ *
4931
+ * Codes are deliberately an enum, not the `reason` string: the strings embed
4932
+ * status codes and error messages, so they are unbounded and useless as an
4933
+ * analytics property. Keep this list SHORT and stable — it is a telemetry
4934
+ * contract, and a value added here has to mean the same thing in six months.
4935
+ *
4936
+ * @public
4937
+ */
4938
+ type PortalLlmFailureReason =
4939
+ /** No usable credential — `getToken` returned null or threw. Terminal. */
4940
+ "auth-unavailable"
4941
+ /** Non-retryable HTTP status (400/403/404, or 401 on the static-apiKey path). */
4942
+ | "http-terminal"
4943
+ /** Retryable status (408/409/425/429/5xx) that never succeeded. */
4944
+ | "http-retryable"
4945
+ /** Network error or the per-attempt timeout aborted the fetch. */
4946
+ | "network"
4947
+ /** HTTP 200 but the envelope itself wasn't JSON. */
4948
+ | "body-parse-failed"
4949
+ /**
4950
+ * HTTP 200 with NO completion content. The reasoning-class failure mode:
4951
+ * the model spends its budget on unreturned thinking and answers empty.
4952
+ */
4953
+ | "empty-content"
4954
+ /** Content present, but no parseable JSON in it (prose, a clarifying question). */
4955
+ | "invalid-json"
4956
+ /** Content parsed to a literal `null`, which is never a valid response. */
4957
+ | "null-completion"
4958
+ /** `totalTimeoutMs` was spent before the next attempt could run. */
4959
+ | "time-budget-exhausted";
4960
+ /**
4961
+ * A give-up report: the classified {@link PortalLlmFailureReason} plus the
4962
+ * little context worth carrying into telemetry. Both extra fields are bounded
4963
+ * (a status code, a small attempt count), so both are safe as event properties.
4964
+ *
4965
+ * @public
4966
+ */
4967
+ interface PortalLlmFailure {
4968
+ /** Stable code for the last failure observed. */
4969
+ reason: PortalLlmFailureReason;
4970
+ /** HTTP status, when the failure was an HTTP one. */
4971
+ httpStatus?: number;
4972
+ /** How many attempts ran before giving up (1-based, ≥ 1). */
4973
+ attempts: number;
4974
+ }
4883
4975
 
4884
4976
  /**
4885
4977
  * Optional LLM injection classifier — Tier-0 security second layer (PR5).
@@ -5984,8 +6076,14 @@ interface ExtractFactsOptions extends PortalLlmAuth {
5984
6076
  * `{candidates: []}` "nothing durable here". Lets callers distinguish a
5985
6077
  * silently-degrading extractor from quiet turns (the two are otherwise
5986
6078
  * indistinguishable). See {@link extractAndRetain}'s `outcome`.
6079
+ *
6080
+ * Receives the classified {@link PortalLlmFailure}. Knowing THAT extraction
6081
+ * failed was not enough: the 2026-08-11 audit found ~60% of production turns
6082
+ * ending here and had to cross-check Prometheus to learn that the cause was
6083
+ * HTTP-200-with-empty-body rather than the 403 everyone assumed. Forward
6084
+ * `failure.reason` into analytics so the next such question is a query.
5987
6085
  */
5988
- onExhaustedEmpty?: () => void;
6086
+ onExhaustedEmpty?: (failure: PortalLlmFailure) => void;
5989
6087
  /**
5990
6088
  * Called when the extractor DID produce candidates but PII de-anonymization
5991
6089
  * dropped every one of them — the model mangled its placeholders (so they
@@ -6108,6 +6206,11 @@ declare function extractAndRetain(messages: AutoExtractMessage[], retainCtx: Ret
6108
6206
  * "extracted but held for review".
6109
6207
  */
6110
6208
  quarantined: QuarantinedMemoryInfo[];
6209
+ /**
6210
+ * Present only when `outcome` is `empty-after-retry` — the classified cause of
6211
+ * the give-up, so "extraction is failing" can be reported as *why* it failed.
6212
+ */
6213
+ failure?: PortalLlmFailure;
6111
6214
  }>;
6112
6215
 
6113
6216
  /**
@@ -10232,4 +10335,4 @@ declare function refreshNotionAccessToken(params: NotionRefreshTokenParams): Pro
10232
10335
  */
10233
10336
  declare function createNotionTools(getAccessToken: () => string | null, requestNotionAccess: () => Promise<string>): ToolConfig[];
10234
10337
 
10235
- 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 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 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, 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 };
10338
+ 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 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, 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 };
@@ -132,7 +132,7 @@ import {
132
132
  upsertMessageOp,
133
133
  useEncryption,
134
134
  vaultMemoryToStored
135
- } from "./chunk-2YHVYDEL.mjs";
135
+ } from "./chunk-YO5UXOC4.mjs";
136
136
  import {
137
137
  PII_PATTERNS,
138
138
  PiiRedactor,
@@ -140,7 +140,7 @@ import {
140
140
  isPiiRedactor,
141
141
  notifyConsolidationFallback,
142
142
  resolvePiiRedactor
143
- } from "./chunk-VOMDHMKH.mjs";
143
+ } from "./chunk-OUFITMDL.mjs";
144
144
  import {
145
145
  INTERNAL_FLOW_MARKER,
146
146
  callPortalJsonCompletion,
@@ -151,9 +151,10 @@ import {
151
151
  resolvePortalAuthHeaders,
152
152
  setLogger,
153
153
  supportsResponseFormat,
154
+ taskTypeHeader,
154
155
  validateEndpointOverride,
155
156
  withInternalFlowMarker
156
- } from "./chunk-B5UPJRCU.mjs";
157
+ } from "./chunk-CJ32HO6Q.mjs";
157
158
  import {
158
159
  BASE_URL,
159
160
  MCP_R2_DOMAIN,
@@ -4788,7 +4789,12 @@ async function callSummarizationLlm(prompt, model, token, baseUrl) {
4788
4789
  method: "POST",
4789
4790
  headers: {
4790
4791
  "Content-Type": "application/json",
4791
- Authorization: `Bearer ${token}`
4792
+ Authorization: `Bearer ${token}`,
4793
+ // Names the task so the portal can own this prompt server-side instead of
4794
+ // trusting the one we build. Summarization is the archetypal Class-B flow:
4795
+ // one fixed purpose, no conversation, and today its instructions are ours
4796
+ // to reword.
4797
+ ...taskTypeHeader("summarize")
4792
4798
  },
4793
4799
  body: JSON.stringify({
4794
4800
  model,
@@ -6387,6 +6393,7 @@ async function classifyInjectionCandidates(candidates, options) {
6387
6393
  ...options.apiKey !== void 0 && { apiKey: options.apiKey },
6388
6394
  ...options.getToken !== void 0 && { getToken: options.getToken },
6389
6395
  ...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
6396
+ taskType: "memory_injection_check",
6390
6397
  model: options.model ?? DEFAULT_MODEL,
6391
6398
  systemPrompt: SYSTEM_PROMPT,
6392
6399
  userMessage: `Candidate facts:
@@ -6861,7 +6868,7 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
6861
6868
  content: m.content,
6862
6869
  similarity: m.similarity
6863
6870
  }));
6864
- const { consolidateMemory: doConsolidate } = await import("./consolidate-TWE6OSSZ.mjs");
6871
+ const { consolidateMemory: doConsolidate } = await import("./consolidate-4BMNVOL4.mjs");
6865
6872
  const decision = await doConsolidate(trimmed, candidates, consolidateOptions);
6866
6873
  if (decision.action === "create") return null;
6867
6874
  if (decision.action === "supersede" && decision.content) {
@@ -7078,10 +7085,15 @@ async function extractFacts(messages, options) {
7078
7085
  }
7079
7086
  const transcript = transcriptLines.join("\n");
7080
7087
  const today = formatLocalDate(options.now ?? Date.now());
7088
+ let failure;
7081
7089
  const parsed = await callPortalJsonCompletion({
7090
+ onFailure: (f) => {
7091
+ failure = f;
7092
+ },
7082
7093
  ...options.apiKey !== void 0 && { apiKey: options.apiKey },
7083
7094
  ...options.getToken !== void 0 && { getToken: options.getToken },
7084
7095
  ...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
7096
+ taskType: "memory_extract",
7085
7097
  ...options.endpointOverride !== void 0 && {
7086
7098
  endpointOverride: options.endpointOverride
7087
7099
  },
@@ -7101,7 +7113,7 @@ Extract durable user facts.`,
7101
7113
  ...options.backoffMs && { backoffMs: options.backoffMs }
7102
7114
  });
7103
7115
  if (parsed === null) {
7104
- options.onExhaustedEmpty?.();
7116
+ options.onExhaustedEmpty?.(failure ?? { reason: "empty-content", attempts: 1 });
7105
7117
  return [];
7106
7118
  }
7107
7119
  const fallbackSourceId = [...messages].reverse().find((m) => m.role === "user")?.id;
@@ -7145,14 +7157,16 @@ async function extractAndRetain(messages, retainCtx, options) {
7145
7157
  ...resolvedConsolidatePii !== void 0 && { piiRedaction: resolvedConsolidatePii }
7146
7158
  } : void 0;
7147
7159
  let exhaustedEmpty = false;
7160
+ let exhaustedFailure;
7148
7161
  let droppedAfterRedaction = false;
7149
7162
  const callerOnExhaustedEmpty = options.extract.onExhaustedEmpty;
7150
7163
  const callerOnCandidatesDropped = options.extract.onCandidatesDropped;
7151
7164
  const candidates = await extractFacts(messages, {
7152
7165
  ...options.extract,
7153
- onExhaustedEmpty: () => {
7166
+ onExhaustedEmpty: (failure) => {
7154
7167
  exhaustedEmpty = true;
7155
- callerOnExhaustedEmpty?.();
7168
+ exhaustedFailure = failure;
7169
+ callerOnExhaustedEmpty?.(failure);
7156
7170
  },
7157
7171
  onCandidatesDropped: () => {
7158
7172
  droppedAfterRedaction = true;
@@ -7271,12 +7285,19 @@ async function extractAndRetain(messages, retainCtx, options) {
7271
7285
  results,
7272
7286
  failedCount: failedWrites,
7273
7287
  outcome,
7274
- quarantined: quarantinedInfo
7288
+ quarantined: quarantinedInfo,
7289
+ // Only meaningful alongside `outcome: "empty-after-retry"`. Returned as well
7290
+ // as pushed through the callback so a consumer that only inspects the result
7291
+ // (rather than wiring a hook) can still report WHY.
7292
+ ...exhaustedFailure !== void 0 && { failure: exhaustedFailure }
7275
7293
  };
7276
7294
  }
7295
+ var UTTERANCE_ECHO_RE = /^(?:said|says|asked|answered|replied|guessed|typed)\s*:\s*(?:'[^']*'|"[^"]*"|‘[^’]*’|“[^”]*”)[\s.!?]*$/iu;
7277
7296
  function isLowSignalContent(content, ownNames) {
7278
- const normalized = content.trim().replace(/[.!?]+$/, "").toLowerCase();
7297
+ const trimmed = content.trim();
7298
+ const normalized = trimmed.replace(/[.!?]+$/, "").toLowerCase();
7279
7299
  if (normalized.length < MIN_CONTENT_LENGTH) return true;
7300
+ if (UTTERANCE_ECHO_RE.test(trimmed)) return true;
7280
7301
  if (ownNames.some(
7281
7302
  (n) => normalized === n.trim().replace(/[.!?]+$/, "").toLowerCase()
7282
7303
  )) {
@@ -7635,6 +7656,7 @@ function createLlmDecayClassifier(options) {
7635
7656
  ...options.apiKey !== void 0 && { apiKey: options.apiKey },
7636
7657
  ...options.getToken !== void 0 && { getToken: options.getToken },
7637
7658
  ...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
7659
+ taskType: "memory_decay",
7638
7660
  model: options.model ?? DEFAULT_MODEL2,
7639
7661
  systemPrompt: SYSTEM_PROMPT3,
7640
7662
  userMessage: `Memory content:
@@ -8758,6 +8780,7 @@ When a memory refers to one of these, reuse the EXACT existing name (same spelli
8758
8780
  ...options.apiKey !== void 0 && { apiKey: options.apiKey },
8759
8781
  ...options.getToken !== void 0 && { getToken: options.getToken },
8760
8782
  ...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
8783
+ taskType: "memory_topic",
8761
8784
  ...options.endpointOverride !== void 0 && {
8762
8785
  endpointOverride: options.endpointOverride
8763
8786
  },
@@ -8947,6 +8970,7 @@ ${evidence}`);
8947
8970
  ...options.apiKey !== void 0 && { apiKey: options.apiKey },
8948
8971
  ...options.getToken !== void 0 && { getToken: options.getToken },
8949
8972
  ...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
8973
+ taskType: "memory_verify_support",
8950
8974
  model: options.model ?? DEFAULT_MODEL4,
8951
8975
  systemPrompt: SYSTEM_PROMPT5,
8952
8976
  userMessage: `Stored facts and their sources:
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  recall
3
- } from "./chunk-2YHVYDEL.mjs";
4
- import "./chunk-B5UPJRCU.mjs";
3
+ } from "./chunk-YO5UXOC4.mjs";
4
+ import "./chunk-CJ32HO6Q.mjs";
5
5
  import "./chunk-GYKJOWEO.mjs";
6
6
  export {
7
7
  recall
package/dist/index.cjs CHANGED
@@ -76,6 +76,7 @@ __export(index_exports, {
76
76
  PII_PATTERNS: () => PII_PATTERNS,
77
77
  PiiRedactor: () => PiiRedactor,
78
78
  SseIdleTimeoutError: () => SseIdleTimeoutError,
79
+ TASK_TYPE_HEADER: () => TASK_TYPE_HEADER,
79
80
  TOOL_CATALOG: () => TOOL_CATALOG,
80
81
  TOOL_RESULT_ORIGIN: () => TOOL_RESULT_ORIGIN,
81
82
  activatedToolSetNames: () => activatedToolSetNames,
@@ -194,6 +195,7 @@ __export(index_exports, {
194
195
  selectServerSideTools: () => selectServerSideTools,
195
196
  setLogger: () => setLogger,
196
197
  shouldAnalyzeStyle: () => shouldAnalyzeStyle,
198
+ taskTypeHeader: () => taskTypeHeader,
197
199
  toolSetSystemPrompts: () => toolSetSystemPrompts,
198
200
  withSseKeepalive: () => withSseKeepalive
199
201
  });
@@ -3800,6 +3802,12 @@ function createStreamingDeAnonymizer(redactor, emit) {
3800
3802
  }
3801
3803
  };
3802
3804
  }
3805
+
3806
+ // src/lib/taskType.ts
3807
+ var TASK_TYPE_HEADER = "X-Anuma-Task-Type";
3808
+ function taskTypeHeader(taskType) {
3809
+ return taskType ? { [TASK_TYPE_HEADER]: taskType } : {};
3810
+ }
3803
3811
  // Annotate the CommonJS export names for ESM import in node:
3804
3812
  0 && (module.exports = {
3805
3813
  BUILT_IN_TOOL_SETS,
@@ -3818,6 +3826,7 @@ function createStreamingDeAnonymizer(redactor, emit) {
3818
3826
  PII_PATTERNS,
3819
3827
  PiiRedactor,
3820
3828
  SseIdleTimeoutError,
3829
+ TASK_TYPE_HEADER,
3821
3830
  TOOL_CATALOG,
3822
3831
  TOOL_RESULT_ORIGIN,
3823
3832
  activatedToolSetNames,
@@ -3936,6 +3945,7 @@ function createStreamingDeAnonymizer(redactor, emit) {
3936
3945
  selectServerSideTools,
3937
3946
  setLogger,
3938
3947
  shouldAnalyzeStyle,
3948
+ taskTypeHeader,
3939
3949
  toolSetSystemPrompts,
3940
3950
  withSseKeepalive
3941
3951
  });