@anuma/sdk 6.19.2 → 6.20.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.
@@ -5795,6 +5795,15 @@ interface RecallDiagnostics {
5795
5795
  degraded: RecallDegradation[];
5796
5796
  }
5797
5797
  type RetainAction = "create" | "merge" | "update" | "skip" | "suppressed" | "supersede";
5798
+ /**
5799
+ * The consolidation LLM's decision for a candidate, when it made one. Reported
5800
+ * on {@link RetainResult.consolidation} so a host can tell an LLM `noop` (the
5801
+ * fact already exists) from a cosine auto-merge — both arrive as
5802
+ * `action: "merge"` — and can read how often the model reaches for `supersede`
5803
+ * or `update` versus `create`. A degraded fallback create (LLM error, bad
5804
+ * response) carries no decision; `onFallback` reports those.
5805
+ */
5806
+ type ConsolidationAction = "create" | "update" | "noop" | "supersede";
5798
5807
  type RetainSource = "manual" | "auto-extracted" | "capsule";
5799
5808
  /**
5800
5809
  * Why a retain returned "create" instead of applying a consolidation decision.
@@ -5934,6 +5943,33 @@ interface RetainResult {
5934
5943
  tombstoneId?: string;
5935
5944
  /** Updated proof_count after this write. 0 when nothing was written (suppressed). */
5936
5945
  proofCount: number;
5946
+ /**
5947
+ * How close the write was to the threshold that allowed it. Absent on the
5948
+ * actions that have no such score (`create`, `update`, `supersede`, `skip`).
5949
+ *
5950
+ * The two paths report DIFFERENT things and a dashboard has to know which:
5951
+ *
5952
+ * - `suppressed` — an exact cosine against the tombstone, computed in
5953
+ * `findTombstoneMatch`.
5954
+ * - `merge` — the RANKER's score for the target, not a pure cosine. The
5955
+ * cosine is what cleared `minSimilarity`, but the supersession pass may
5956
+ * then adjust it (`oldScore - delta` / `newScore + delta`) before this
5957
+ * value is read, and can in principle reorder the winner. Read it as
5958
+ * "the score the merge was chosen on", within the supersession delta of
5959
+ * the cosine — not as the raw pairwise similarity.
5960
+ */
5961
+ similarity?: number;
5962
+ /**
5963
+ * What the consolidation LLM decided for this candidate, when consolidation
5964
+ * ran — see {@link ConsolidationAction}.
5965
+ *
5966
+ * Reported for the DECISION, not for what the write ended up doing, so the
5967
+ * two can disagree and be read as such: a `merge` carrying
5968
+ * `consolidation: "create"` is the model saying "new fact" and the strict
5969
+ * cosine stage merging anyway. Absent when consolidation did not run, and
5970
+ * absent on a degraded fallback create (`onFallback` owns that signal).
5971
+ */
5972
+ consolidation?: ConsolidationAction;
5937
5973
  }
5938
5974
 
5939
5975
  /**
@@ -6160,6 +6196,61 @@ interface ExtractFactsOptions extends PortalLlmAuth {
6160
6196
  * callers may leave it unset.
6161
6197
  */
6162
6198
  onAttempt?: (attempt: PortalLlmAttempt) => void;
6199
+ /**
6200
+ * Fired once per successful completion with how many candidates the model
6201
+ * emitted (`rawCount`) and how many survived {@link validateCandidates}
6202
+ * (`validCount`) — the non-string / empty / over-cap / low-signal / bad-
6203
+ * confidence drops that until now were a bare `continue` nobody counted.
6204
+ *
6205
+ * Without it a `no-facts` turn cannot be split into "the model found nothing"
6206
+ * and "the model found things we threw away", which is the difference between
6207
+ * a prompt problem and a validator problem. Counts only; never content.
6208
+ */
6209
+ onCandidatesParsed?: (stats: {
6210
+ rawCount: number;
6211
+ validCount: number;
6212
+ }) => void;
6213
+ }
6214
+ /**
6215
+ * Where a turn's candidates went between the model's completion and the vault —
6216
+ * every stage that can drop one, as a count. Returned by {@link extractAndRetain}
6217
+ * and forwarded on `TurnCompleteEvent` so a host can emit it; nothing here is
6218
+ * content.
6219
+ *
6220
+ * Reads as a funnel: `raw ≥ valid ≥ afterRedaction ≥ aboveConfidence`, then
6221
+ * `aboveConfidence = quarantined + retained + failed`.
6222
+ * @public
6223
+ */
6224
+ interface ExtractionFunnel {
6225
+ /** Candidates in the model's completion, before any validation. */
6226
+ rawCandidateCount: number;
6227
+ /** Survivors of {@link validateCandidates} (shape, length, low-signal, confidence-is-a-number). */
6228
+ validCandidateCount: number;
6229
+ /** Survivors of PII de-anonymization (equals `validCandidateCount` when redaction is off). */
6230
+ afterRedactionCount: number;
6231
+ /** Survivors of the `minConfidence` floor — the candidates that reached the injection screen. */
6232
+ aboveConfidenceCount: number;
6233
+ /**
6234
+ * Held for review by the injection screen and SUCCESSFULLY persisted — the
6235
+ * same set as `extractAndRetain`'s `quarantined`. A screened candidate whose
6236
+ * `retain()` threw is in `failedCount` instead, never both.
6237
+ */
6238
+ quarantinedCount: number;
6239
+ /** Written through `retain()` (any disposition). */
6240
+ retainedCount: number;
6241
+ /** `retain()` threw. */
6242
+ failedCount: number;
6243
+ }
6244
+ /**
6245
+ * Wall-clock split of one {@link extractAndRetain} call. The worker's
6246
+ * `durationMs` is the sum plus the screen; these say which half is slow.
6247
+ * @public
6248
+ */
6249
+ interface ExtractionTimings {
6250
+ /** The extraction LLM call, all attempts and backoff included. */
6251
+ extractMs: number;
6252
+ /** The retain loop — embeddings, consolidation LLM calls, writes — over every candidate. */
6253
+ retainMs: number;
6163
6254
  }
6164
6255
  /**
6165
6256
  * Stage 1 — call the LLM to extract candidate facts from the recent
@@ -6277,6 +6368,12 @@ declare function extractAndRetain(messages: AutoExtractMessage[], retainCtx: Ret
6277
6368
  * the give-up, so "extraction is failing" can be reported as *why* it failed.
6278
6369
  */
6279
6370
  failure?: PortalLlmFailure;
6371
+ /** Where the candidates went, stage by stage — see {@link ExtractionFunnel}. */
6372
+ funnel: ExtractionFunnel;
6373
+ /** Extract vs. retain wall-clock — see {@link ExtractionTimings}. */
6374
+ timings: ExtractionTimings;
6375
+ /** The extraction model this call asked for (the resolved default when unset). */
6376
+ model: string;
6280
6377
  }>;
6281
6378
 
6282
6379
  /**
@@ -8072,6 +8169,16 @@ interface TurnCompleteEvent {
8072
8169
  * carries content.
8073
8170
  */
8074
8171
  failure?: PortalLlmFailure;
8172
+ /**
8173
+ * Where the candidates went between the model and the vault, as counts — the
8174
+ * drops before `retain()` that `candidates`/`results` cannot show. See
8175
+ * {@link ExtractionFunnel}.
8176
+ */
8177
+ funnel?: ExtractionFunnel;
8178
+ /** Extract vs. retain wall-clock split of `durationMs`. See {@link ExtractionTimings}. */
8179
+ timings?: ExtractionTimings;
8180
+ /** The extraction model this turn asked for. */
8181
+ model?: string;
8075
8182
  }
8076
8183
  /** @public */
8077
8184
  /**
@@ -10734,4 +10841,4 @@ declare function sanitizeQuotes(s: string): string;
10734
10841
  declare function renderTemplate(value: string | null | undefined, template: string): string | null;
10735
10842
  declare function buildSystemPrompt(ctx: PromptContext, options?: BuildPromptOptions): BuildPromptResult;
10736
10843
 
10737
- export { type AnalyzeStyleOptions, type AnalyzeStyleResult, type ApiResponse, type ApiType, type AutoExecutedToolResult, type AutoExtractMessage, type AutoExtractor, type Budget, type BuildPromptOptions, type BuildPromptResult, type CachedChunkVectors, type CachedServerTools, type ChatCompletionUsage, type ChatRole, type ChunkSearchResult, type ChunkVectorCache, type ChunkingOptions, type ConnectorGuidance, type ConnectorGuidanceInput, type ConsolidationFallbackReason, Conversation, ConversationSummary, type CreateAutoExtractorOptions, type CreateConversationOptions, type CreateDecaySweeperOptions, type CreateMediaOptions, type CreateMessageOptions, type CreateModelPreferenceOptions, type CreateProjectOptions, type CreateUserPreferenceOptions, type CreateVaultMemoryOptions, type CryptoPriceClassification, type CryptoPricePreProcessorOptions, DEFAULT_ANALYSIS_PROMPT, DEFAULT_ANALYZE_AFTER_MESSAGES, DEFAULT_CACHE_EXPIRATION_MS, DEFAULT_CHUNK_CACHE_SIZE, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DECAY_POLICY, DEFAULT_DOCUMENT_PATTERN, DEFAULT_EXCLUDED_SERVER_TOOLS, DEFAULT_MAX_CLASSIFIER_CALLS_PER_SWEEP, DEFAULT_MAX_INPUT_MESSAGES, DEFAULT_MAX_PROFILE_LENGTH, DEFAULT_MIN_CHUNK_SIZE, DEFAULT_MIN_MESSAGES, DEFAULT_PERSONALITY_SETTINGS, DEFAULT_PROFILE_FACETS, DEFAULT_PROFILE_FACT_TYPE_WEIGHTS, DEFAULT_PROFILE_PROOF_ALPHA, DEFAULT_PROFILE_TREND_MULTIPLIERS, DEFAULT_PROMPT_TEMPLATES, DEFAULT_REFRESH_EVERY_MESSAGES, DEFAULT_SERVER_TOOLS_MATCH_OPTIONS, DEFAULT_SUMMARY_MIN_WINDOW_MESSAGES, DEFAULT_SUMMARY_MODEL, DEFAULT_SUMMARY_TOKEN_THRESHOLD, 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, ExcelProcessor, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type FactType, type FileMetadata, type FileProcessor, type FileTypeQuery, type FileWithData, type FlushResult, type GetConversationsPageOptions, type GraphTraversalOptions, HARD_DELETE_WINDOW_MS, INFERENCE_ID_HEADER, type InjectionClassifierOptions, type InjectionReason, type LazyStoredConversation, type LlmDecayClassifierOptions, type LlmNeighborRefinerOptions, type LlmTokenUsage, MAX_HOPS, MAX_MESSAGES_PER_SUMMARIZATION, MEDIUM_TTL_MS, Media, type MediaDimensions, type MediaFilterOptions, type MediaMetadata, type MediaOperationsContext, type MediaRole, type MediaType, type MemoriesNeedingTopicExtraction, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryQuarantinedEvent, type MemoryToVerify, type MemoryVaultSearchOptions, type MemoryVaultToolOptions, type MemoryVerification, Message, type MessageChunk, type MessageFeedback, type MessageOrigin, type ModelCallEndEvent, type ModelCallStartEvent, ModelPreference, NEVER_TTL_MS, NODE_BUDGET, type NeighborRefiner, type NowSource, type ObservationTrend, type ObservationTrendInput, type OperationExecutor, PAST_EVENT_GRACE_MS, PROFILE_DOC_VERSION, type ParsedServerToolsResponse, PdfProcessor, type PersonalitySettings, type PersonalitySliders, type PersonalityStyle, type PgClientLike, type PgPoolLike, type PhotoIngestResult, type PhotoMediaRef, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, PostgreSQLAdapter, type PostgreSQLAdapterOptions, type PreprocessingOptions, type PreprocessingResult, type ProcessedFileResult, ProcessorRegistry, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type ProfileUpdate, Project, type ProjectOperationsContext, type PromptContext, type PromptPreProcessor, type PromptPreProcessorContext, type PromptSection, type PromptTemplates, type PublishedPhotoMemory, type QuarantinedMemoryInfo, type QueueEncryptionContext, QueueManager, type QueueStatus, type QueuedOperation, type QueuedOperationType, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type ReflectOptions, type ReflectResult, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ResumeStreamOptions, type ResumeStreamResult, type RetainAction, type RetainContext, type RetainOptions, type RetainResult, type RetainSource, type RunEndEvent, type RunErrorEvent, type RunHooks, type RunStartEvent, type RunTerminalState, type RunToolLoopOptions, type RunToolLoopResult, SDK_SCHEMA_VERSION, SERVER_TOOL_DEPENDENCY_SETS, SHORT_TTL_MS, SLIDER_CONFIG, STREAM_RESUMABLE_HEADER, type ScoreBreakdown, type ScoreProfileSalienceOptions, type ScreenResult, type ScreenedCandidate, type SearchSource, type SelectServerToolsForPromptOptions, type ServerTool, type ServerToolCallEvent, type ServerToolsFilterFunction, type ServerToolsOptions, type ServerToolsResponse, type SettingsStorageOperationsContext, type SignMessageFn, type StepFinishEvent, type StockPriceClassification, type StockPricePreProcessorOptions, type StorageOperationsContext, type StoredConversation, type StoredConversationSummary, type StoredFileWithContext, type StoredMedia, type StoredMessage, type StoredMessageWithSimilarity, type StoredModelPreference, type StoredProject, type StoredUserPreference, type StoredVaultMemory, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type StreamSmoothingConfig, type StreamingTransport, type StreamingTransportOptions, type StreamingTransportResult, type StyleAnalysisSchedule, type SynthesizeProfileOptions, TOOL_CATALOG, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, TextProcessor, type ToolConfig, type ToolExecutor, type ToolMatchOptions, type ToolMatchResult, type ToolSet, type ToolUseEndEvent, type ToolUseStartEvent, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, type TopicSkipReason, type TurnCompleteEvent, type TurnSkippedEvent, type UncheckedReason, type UnverifiableReason, type UpdateMediaOptions, type UpdateModelPreferenceOptions, type UpdateProjectOptions, type UpdateUserPreferenceOptions, type UpdateVaultMemoryOptions, UserPreference, type UserPreferencesStorageOperationsContext, VAULT_SIZE_HOP_CAP, type VaultEmbeddingCache, VaultMemory, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultSaveOperation, type VaultSearchResult, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, WordProcessor, ZipProcessor, type ZipProcessorOptions, activatedToolSetNames, analyzeStyle, archiveVaultMemoryOp, backfillMemoryTopicsOp, buildConnectorGuidance, buildDeniedToolsRider, buildSystemPrompt, capHopsForDensity, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, cleanupConversationSummary, clearAllEncryptionKeys, clearAllEncryptionState, clearAllKeyPairs, clearEncryptionKey, clearKeyPair, clearLazyTitleCache, clearMessagesOp, clearServerToolsCache, composeHooks, createAutoExtractor, createChunkVectorCache, createConversationOp, createCryptoPricePreProcessor, createDecaySweeper, createLlmDecayClassifier, createLlmNeighborRefiner, createMediaBatchOp, createMediaOp, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageOp, createMessageSourceResolver, createPlatformCursorStore, createProjectOp, createRecallTool, createServerToolsFilter, createStockPricePreProcessor, createSummaryContext, createVaultEmbeddingCache, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decryptConversationTitle, decryptData, decryptDataBatch, decryptDataBytes, decryptDataBytesFromBytes, decryptDataWithKey, defaultServerToolsFilter, deleteAllVaultMemoriesForUserOp, deleteConversationOp, deleteConversationSummaryOp, deleteMediaByConversationOp, deleteMediaByMessageOp, deleteMediaOp, deleteModelPreferenceOp, deleteProjectOp, deleteUserPreferenceOp, deleteVaultMemoryOp, eagerEmbedContent, embedAllMessages, embedMessage, encryptData, encryptDataBatch, encryptDataBytes, encryptDataWithKey, estimateMessagesTokens, estimateTokens, exportPublicKey, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, findMatchingTools, generateConversationId, generateEmbedding, generateEmbeddings, generateMediaId, generateProjectId, getAIGeneratedMediaOp, getAllFilesOp, getAllVaultMemoriesOp, getAllVaultMemoryContentsOp, getAudioOp, getCachedServerTools, getConversationOp, getConversationSummaryOp, getConversationsByProjectLazyOp, getConversationsByProjectOp, getConversationsLazyOp, getConversationsOp, getConversationsPageOp, getDecayCandidatesRawOp, getDocumentsOp, getEncryptionKey, getImagesOp, getMediaByConversationOp, getMediaByIdOp, getMediaByIdsOp, getMediaByMessageOp, getMediaByModelOp, getMediaByRoleOp, getMediaBySourceUrlOp, getMediaByTypeOp, getMediaCountOp, getMediaCountsByTypeOp, getMediaOp, getMediaTypeFromMime, getMemoriesNeedingTopicExtractionOp, getMessageOp, getMessagesOp, getModelPreferenceOp, getProjectConversationCountOp, getProjectConversationsOp, getProjectOp, getProjectsOp, getRecentMediaOp, getServerTools, getSupportedFileTypes, getToolsChecksum, getUnfiledVaultMemoriesOp, getUserPreferenceOp, getUserUploadedMediaOp, getVaultMemoryOp, getVideosOp, hardDeleteDecayedOp, hardDeleteMediaOp, hasEncryptionKey, hasKeyPair, ingestPublishedPhotoMemoriesOp, injectionSignatureCatalog, isDegradedTopicSkip, isRerankerAvailable, isSupportedFile, isSupportedMediaType, makeSyntheticStoredConversation, makeSyntheticStoredMessage, maybeSummarizeHistory, mediaToStored, migrateFromModelPreferencesOp, onKeyAvailable, parseMedia, preEmbedVaultMemories, preprocessFiles, progressiveSummarize, projectToStored, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, relinkMemoryTopicsOp, relinkMisclassifiedVideosOp, renderTemplate, requestEncryptionKey, requestKeyPair, restoreVaultMemoryOp, resumeStream, retain, runToolLoop, sanitizeQuotes, schemaToCreateSQL, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchChunksOp, searchMediaOp, searchMessagesOp, searchVaultMemories, seedEncryptionKeys, selectServerToolsForPrompt, serverPlatformStorage, setMemoryVisibilityOp, setModelPreferenceOp, setUserPreferenceOp, shouldAnalyzeStyle, shouldChunkMessage, shouldRefreshTools, splitMessagesAtThreshold, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, summarizeObservationTrends, summaryToSystemMessage, supersedeVaultMemoryOp, synthesizeProfile, toolSetSystemPrompts, traverseGraphLane, ttlForType, updateConversationProjectOp, updateConversationTitleOp, updateMediaMessageIdBatchOp, updateMediaOp, updateMessageChunksOp, updateMessageEmbeddingOp, updateMessageErrorOp, updateMessageFeedbackOp, updateModelsOp, updatePersonalityOp, updateProfileOp, updateProjectNameOp, updateProjectOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertConversationSummaryOp, upsertMessageOp, verifyMemoriesForPublish };
10844
+ export { type AnalyzeStyleOptions, type AnalyzeStyleResult, type ApiResponse, type ApiType, type AutoExecutedToolResult, type AutoExtractMessage, type AutoExtractor, type Budget, type BuildPromptOptions, type BuildPromptResult, type CachedChunkVectors, type CachedServerTools, type ChatCompletionUsage, type ChatRole, type ChunkSearchResult, type ChunkVectorCache, type ChunkingOptions, type ConnectorGuidance, type ConnectorGuidanceInput, type ConsolidationAction, type ConsolidationFallbackReason, Conversation, ConversationSummary, type CreateAutoExtractorOptions, type CreateConversationOptions, type CreateDecaySweeperOptions, type CreateMediaOptions, type CreateMessageOptions, type CreateModelPreferenceOptions, type CreateProjectOptions, type CreateUserPreferenceOptions, type CreateVaultMemoryOptions, type CryptoPriceClassification, type CryptoPricePreProcessorOptions, DEFAULT_ANALYSIS_PROMPT, DEFAULT_ANALYZE_AFTER_MESSAGES, DEFAULT_CACHE_EXPIRATION_MS, DEFAULT_CHUNK_CACHE_SIZE, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DECAY_POLICY, DEFAULT_DOCUMENT_PATTERN, DEFAULT_EXCLUDED_SERVER_TOOLS, DEFAULT_MAX_CLASSIFIER_CALLS_PER_SWEEP, DEFAULT_MAX_INPUT_MESSAGES, DEFAULT_MAX_PROFILE_LENGTH, DEFAULT_MIN_CHUNK_SIZE, DEFAULT_MIN_MESSAGES, DEFAULT_PERSONALITY_SETTINGS, DEFAULT_PROFILE_FACETS, DEFAULT_PROFILE_FACT_TYPE_WEIGHTS, DEFAULT_PROFILE_PROOF_ALPHA, DEFAULT_PROFILE_TREND_MULTIPLIERS, DEFAULT_PROMPT_TEMPLATES, DEFAULT_REFRESH_EVERY_MESSAGES, DEFAULT_SERVER_TOOLS_MATCH_OPTIONS, DEFAULT_SUMMARY_MIN_WINDOW_MESSAGES, DEFAULT_SUMMARY_MODEL, DEFAULT_SUMMARY_TOKEN_THRESHOLD, 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, ExcelProcessor, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type ExtractionFunnel, type ExtractionTimings, type FactType, type FileMetadata, type FileProcessor, type FileTypeQuery, type FileWithData, type FlushResult, type GetConversationsPageOptions, type GraphTraversalOptions, HARD_DELETE_WINDOW_MS, INFERENCE_ID_HEADER, type InjectionClassifierOptions, type InjectionReason, type LazyStoredConversation, type LlmDecayClassifierOptions, type LlmNeighborRefinerOptions, type LlmTokenUsage, MAX_HOPS, MAX_MESSAGES_PER_SUMMARIZATION, MEDIUM_TTL_MS, Media, type MediaDimensions, type MediaFilterOptions, type MediaMetadata, type MediaOperationsContext, type MediaRole, type MediaType, type MemoriesNeedingTopicExtraction, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryQuarantinedEvent, type MemoryToVerify, type MemoryVaultSearchOptions, type MemoryVaultToolOptions, type MemoryVerification, Message, type MessageChunk, type MessageFeedback, type MessageOrigin, type ModelCallEndEvent, type ModelCallStartEvent, ModelPreference, NEVER_TTL_MS, NODE_BUDGET, type NeighborRefiner, type NowSource, type ObservationTrend, type ObservationTrendInput, type OperationExecutor, PAST_EVENT_GRACE_MS, PROFILE_DOC_VERSION, type ParsedServerToolsResponse, PdfProcessor, type PersonalitySettings, type PersonalitySliders, type PersonalityStyle, type PgClientLike, type PgPoolLike, type PhotoIngestResult, type PhotoMediaRef, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, PostgreSQLAdapter, type PostgreSQLAdapterOptions, type PreprocessingOptions, type PreprocessingResult, type ProcessedFileResult, ProcessorRegistry, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type ProfileUpdate, Project, type ProjectOperationsContext, type PromptContext, type PromptPreProcessor, type PromptPreProcessorContext, type PromptSection, type PromptTemplates, type PublishedPhotoMemory, type QuarantinedMemoryInfo, type QueueEncryptionContext, QueueManager, type QueueStatus, type QueuedOperation, type QueuedOperationType, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type ReflectOptions, type ReflectResult, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ResumeStreamOptions, type ResumeStreamResult, type RetainAction, type RetainContext, type RetainOptions, type RetainResult, type RetainSource, type RunEndEvent, type RunErrorEvent, type RunHooks, type RunStartEvent, type RunTerminalState, type RunToolLoopOptions, type RunToolLoopResult, SDK_SCHEMA_VERSION, SERVER_TOOL_DEPENDENCY_SETS, SHORT_TTL_MS, SLIDER_CONFIG, STREAM_RESUMABLE_HEADER, type ScoreBreakdown, type ScoreProfileSalienceOptions, type ScreenResult, type ScreenedCandidate, type SearchSource, type SelectServerToolsForPromptOptions, type ServerTool, type ServerToolCallEvent, type ServerToolsFilterFunction, type ServerToolsOptions, type ServerToolsResponse, type SettingsStorageOperationsContext, type SignMessageFn, type StepFinishEvent, type StockPriceClassification, type StockPricePreProcessorOptions, type StorageOperationsContext, type StoredConversation, type StoredConversationSummary, type StoredFileWithContext, type StoredMedia, type StoredMessage, type StoredMessageWithSimilarity, type StoredModelPreference, type StoredProject, type StoredUserPreference, type StoredVaultMemory, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type StreamSmoothingConfig, type StreamingTransport, type StreamingTransportOptions, type StreamingTransportResult, type StyleAnalysisSchedule, type SynthesizeProfileOptions, TOOL_CATALOG, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, TextProcessor, type ToolConfig, type ToolExecutor, type ToolMatchOptions, type ToolMatchResult, type ToolSet, type ToolUseEndEvent, type ToolUseStartEvent, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, type TopicSkipReason, type TurnCompleteEvent, type TurnSkippedEvent, type UncheckedReason, type UnverifiableReason, type UpdateMediaOptions, type UpdateModelPreferenceOptions, type UpdateProjectOptions, type UpdateUserPreferenceOptions, type UpdateVaultMemoryOptions, UserPreference, type UserPreferencesStorageOperationsContext, VAULT_SIZE_HOP_CAP, type VaultEmbeddingCache, VaultMemory, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultSaveOperation, type VaultSearchResult, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, WordProcessor, ZipProcessor, type ZipProcessorOptions, activatedToolSetNames, analyzeStyle, archiveVaultMemoryOp, backfillMemoryTopicsOp, buildConnectorGuidance, buildDeniedToolsRider, buildSystemPrompt, capHopsForDensity, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, cleanupConversationSummary, clearAllEncryptionKeys, clearAllEncryptionState, clearAllKeyPairs, clearEncryptionKey, clearKeyPair, clearLazyTitleCache, clearMessagesOp, clearServerToolsCache, composeHooks, createAutoExtractor, createChunkVectorCache, createConversationOp, createCryptoPricePreProcessor, createDecaySweeper, createLlmDecayClassifier, createLlmNeighborRefiner, createMediaBatchOp, createMediaOp, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageOp, createMessageSourceResolver, createPlatformCursorStore, createProjectOp, createRecallTool, createServerToolsFilter, createStockPricePreProcessor, createSummaryContext, createVaultEmbeddingCache, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decryptConversationTitle, decryptData, decryptDataBatch, decryptDataBytes, decryptDataBytesFromBytes, decryptDataWithKey, defaultServerToolsFilter, deleteAllVaultMemoriesForUserOp, deleteConversationOp, deleteConversationSummaryOp, deleteMediaByConversationOp, deleteMediaByMessageOp, deleteMediaOp, deleteModelPreferenceOp, deleteProjectOp, deleteUserPreferenceOp, deleteVaultMemoryOp, eagerEmbedContent, embedAllMessages, embedMessage, encryptData, encryptDataBatch, encryptDataBytes, encryptDataWithKey, estimateMessagesTokens, estimateTokens, exportPublicKey, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, findMatchingTools, generateConversationId, generateEmbedding, generateEmbeddings, generateMediaId, generateProjectId, getAIGeneratedMediaOp, getAllFilesOp, getAllVaultMemoriesOp, getAllVaultMemoryContentsOp, getAudioOp, getCachedServerTools, getConversationOp, getConversationSummaryOp, getConversationsByProjectLazyOp, getConversationsByProjectOp, getConversationsLazyOp, getConversationsOp, getConversationsPageOp, getDecayCandidatesRawOp, getDocumentsOp, getEncryptionKey, getImagesOp, getMediaByConversationOp, getMediaByIdOp, getMediaByIdsOp, getMediaByMessageOp, getMediaByModelOp, getMediaByRoleOp, getMediaBySourceUrlOp, getMediaByTypeOp, getMediaCountOp, getMediaCountsByTypeOp, getMediaOp, getMediaTypeFromMime, getMemoriesNeedingTopicExtractionOp, getMessageOp, getMessagesOp, getModelPreferenceOp, getProjectConversationCountOp, getProjectConversationsOp, getProjectOp, getProjectsOp, getRecentMediaOp, getServerTools, getSupportedFileTypes, getToolsChecksum, getUnfiledVaultMemoriesOp, getUserPreferenceOp, getUserUploadedMediaOp, getVaultMemoryOp, getVideosOp, hardDeleteDecayedOp, hardDeleteMediaOp, hasEncryptionKey, hasKeyPair, ingestPublishedPhotoMemoriesOp, injectionSignatureCatalog, isDegradedTopicSkip, isRerankerAvailable, isSupportedFile, isSupportedMediaType, makeSyntheticStoredConversation, makeSyntheticStoredMessage, maybeSummarizeHistory, mediaToStored, migrateFromModelPreferencesOp, onKeyAvailable, parseMedia, preEmbedVaultMemories, preprocessFiles, progressiveSummarize, projectToStored, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, relinkMemoryTopicsOp, relinkMisclassifiedVideosOp, renderTemplate, requestEncryptionKey, requestKeyPair, restoreVaultMemoryOp, resumeStream, retain, runToolLoop, sanitizeQuotes, schemaToCreateSQL, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchChunksOp, searchMediaOp, searchMessagesOp, searchVaultMemories, seedEncryptionKeys, selectServerToolsForPrompt, serverPlatformStorage, setMemoryVisibilityOp, setModelPreferenceOp, setUserPreferenceOp, shouldAnalyzeStyle, shouldChunkMessage, shouldRefreshTools, splitMessagesAtThreshold, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, summarizeObservationTrends, summaryToSystemMessage, supersedeVaultMemoryOp, synthesizeProfile, toolSetSystemPrompts, traverseGraphLane, ttlForType, updateConversationProjectOp, updateConversationTitleOp, updateMediaMessageIdBatchOp, updateMediaOp, updateMessageChunksOp, updateMessageEmbeddingOp, updateMessageErrorOp, updateMessageFeedbackOp, updateModelsOp, updatePersonalityOp, updateProfileOp, updateProjectNameOp, updateProjectOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertConversationSummaryOp, upsertMessageOp, verifyMemoriesForPublish };
@@ -5795,6 +5795,15 @@ interface RecallDiagnostics {
5795
5795
  degraded: RecallDegradation[];
5796
5796
  }
5797
5797
  type RetainAction = "create" | "merge" | "update" | "skip" | "suppressed" | "supersede";
5798
+ /**
5799
+ * The consolidation LLM's decision for a candidate, when it made one. Reported
5800
+ * on {@link RetainResult.consolidation} so a host can tell an LLM `noop` (the
5801
+ * fact already exists) from a cosine auto-merge — both arrive as
5802
+ * `action: "merge"` — and can read how often the model reaches for `supersede`
5803
+ * or `update` versus `create`. A degraded fallback create (LLM error, bad
5804
+ * response) carries no decision; `onFallback` reports those.
5805
+ */
5806
+ type ConsolidationAction = "create" | "update" | "noop" | "supersede";
5798
5807
  type RetainSource = "manual" | "auto-extracted" | "capsule";
5799
5808
  /**
5800
5809
  * Why a retain returned "create" instead of applying a consolidation decision.
@@ -5934,6 +5943,33 @@ interface RetainResult {
5934
5943
  tombstoneId?: string;
5935
5944
  /** Updated proof_count after this write. 0 when nothing was written (suppressed). */
5936
5945
  proofCount: number;
5946
+ /**
5947
+ * How close the write was to the threshold that allowed it. Absent on the
5948
+ * actions that have no such score (`create`, `update`, `supersede`, `skip`).
5949
+ *
5950
+ * The two paths report DIFFERENT things and a dashboard has to know which:
5951
+ *
5952
+ * - `suppressed` — an exact cosine against the tombstone, computed in
5953
+ * `findTombstoneMatch`.
5954
+ * - `merge` — the RANKER's score for the target, not a pure cosine. The
5955
+ * cosine is what cleared `minSimilarity`, but the supersession pass may
5956
+ * then adjust it (`oldScore - delta` / `newScore + delta`) before this
5957
+ * value is read, and can in principle reorder the winner. Read it as
5958
+ * "the score the merge was chosen on", within the supersession delta of
5959
+ * the cosine — not as the raw pairwise similarity.
5960
+ */
5961
+ similarity?: number;
5962
+ /**
5963
+ * What the consolidation LLM decided for this candidate, when consolidation
5964
+ * ran — see {@link ConsolidationAction}.
5965
+ *
5966
+ * Reported for the DECISION, not for what the write ended up doing, so the
5967
+ * two can disagree and be read as such: a `merge` carrying
5968
+ * `consolidation: "create"` is the model saying "new fact" and the strict
5969
+ * cosine stage merging anyway. Absent when consolidation did not run, and
5970
+ * absent on a degraded fallback create (`onFallback` owns that signal).
5971
+ */
5972
+ consolidation?: ConsolidationAction;
5937
5973
  }
5938
5974
 
5939
5975
  /**
@@ -6160,6 +6196,61 @@ interface ExtractFactsOptions extends PortalLlmAuth {
6160
6196
  * callers may leave it unset.
6161
6197
  */
6162
6198
  onAttempt?: (attempt: PortalLlmAttempt) => void;
6199
+ /**
6200
+ * Fired once per successful completion with how many candidates the model
6201
+ * emitted (`rawCount`) and how many survived {@link validateCandidates}
6202
+ * (`validCount`) — the non-string / empty / over-cap / low-signal / bad-
6203
+ * confidence drops that until now were a bare `continue` nobody counted.
6204
+ *
6205
+ * Without it a `no-facts` turn cannot be split into "the model found nothing"
6206
+ * and "the model found things we threw away", which is the difference between
6207
+ * a prompt problem and a validator problem. Counts only; never content.
6208
+ */
6209
+ onCandidatesParsed?: (stats: {
6210
+ rawCount: number;
6211
+ validCount: number;
6212
+ }) => void;
6213
+ }
6214
+ /**
6215
+ * Where a turn's candidates went between the model's completion and the vault —
6216
+ * every stage that can drop one, as a count. Returned by {@link extractAndRetain}
6217
+ * and forwarded on `TurnCompleteEvent` so a host can emit it; nothing here is
6218
+ * content.
6219
+ *
6220
+ * Reads as a funnel: `raw ≥ valid ≥ afterRedaction ≥ aboveConfidence`, then
6221
+ * `aboveConfidence = quarantined + retained + failed`.
6222
+ * @public
6223
+ */
6224
+ interface ExtractionFunnel {
6225
+ /** Candidates in the model's completion, before any validation. */
6226
+ rawCandidateCount: number;
6227
+ /** Survivors of {@link validateCandidates} (shape, length, low-signal, confidence-is-a-number). */
6228
+ validCandidateCount: number;
6229
+ /** Survivors of PII de-anonymization (equals `validCandidateCount` when redaction is off). */
6230
+ afterRedactionCount: number;
6231
+ /** Survivors of the `minConfidence` floor — the candidates that reached the injection screen. */
6232
+ aboveConfidenceCount: number;
6233
+ /**
6234
+ * Held for review by the injection screen and SUCCESSFULLY persisted — the
6235
+ * same set as `extractAndRetain`'s `quarantined`. A screened candidate whose
6236
+ * `retain()` threw is in `failedCount` instead, never both.
6237
+ */
6238
+ quarantinedCount: number;
6239
+ /** Written through `retain()` (any disposition). */
6240
+ retainedCount: number;
6241
+ /** `retain()` threw. */
6242
+ failedCount: number;
6243
+ }
6244
+ /**
6245
+ * Wall-clock split of one {@link extractAndRetain} call. The worker's
6246
+ * `durationMs` is the sum plus the screen; these say which half is slow.
6247
+ * @public
6248
+ */
6249
+ interface ExtractionTimings {
6250
+ /** The extraction LLM call, all attempts and backoff included. */
6251
+ extractMs: number;
6252
+ /** The retain loop — embeddings, consolidation LLM calls, writes — over every candidate. */
6253
+ retainMs: number;
6163
6254
  }
6164
6255
  /**
6165
6256
  * Stage 1 — call the LLM to extract candidate facts from the recent
@@ -6277,6 +6368,12 @@ declare function extractAndRetain(messages: AutoExtractMessage[], retainCtx: Ret
6277
6368
  * the give-up, so "extraction is failing" can be reported as *why* it failed.
6278
6369
  */
6279
6370
  failure?: PortalLlmFailure;
6371
+ /** Where the candidates went, stage by stage — see {@link ExtractionFunnel}. */
6372
+ funnel: ExtractionFunnel;
6373
+ /** Extract vs. retain wall-clock — see {@link ExtractionTimings}. */
6374
+ timings: ExtractionTimings;
6375
+ /** The extraction model this call asked for (the resolved default when unset). */
6376
+ model: string;
6280
6377
  }>;
6281
6378
 
6282
6379
  /**
@@ -8072,6 +8169,16 @@ interface TurnCompleteEvent {
8072
8169
  * carries content.
8073
8170
  */
8074
8171
  failure?: PortalLlmFailure;
8172
+ /**
8173
+ * Where the candidates went between the model and the vault, as counts — the
8174
+ * drops before `retain()` that `candidates`/`results` cannot show. See
8175
+ * {@link ExtractionFunnel}.
8176
+ */
8177
+ funnel?: ExtractionFunnel;
8178
+ /** Extract vs. retain wall-clock split of `durationMs`. See {@link ExtractionTimings}. */
8179
+ timings?: ExtractionTimings;
8180
+ /** The extraction model this turn asked for. */
8181
+ model?: string;
8075
8182
  }
8076
8183
  /** @public */
8077
8184
  /**
@@ -10734,4 +10841,4 @@ declare function sanitizeQuotes(s: string): string;
10734
10841
  declare function renderTemplate(value: string | null | undefined, template: string): string | null;
10735
10842
  declare function buildSystemPrompt(ctx: PromptContext, options?: BuildPromptOptions): BuildPromptResult;
10736
10843
 
10737
- export { type AnalyzeStyleOptions, type AnalyzeStyleResult, type ApiResponse, type ApiType, type AutoExecutedToolResult, type AutoExtractMessage, type AutoExtractor, type Budget, type BuildPromptOptions, type BuildPromptResult, type CachedChunkVectors, type CachedServerTools, type ChatCompletionUsage, type ChatRole, type ChunkSearchResult, type ChunkVectorCache, type ChunkingOptions, type ConnectorGuidance, type ConnectorGuidanceInput, type ConsolidationFallbackReason, Conversation, ConversationSummary, type CreateAutoExtractorOptions, type CreateConversationOptions, type CreateDecaySweeperOptions, type CreateMediaOptions, type CreateMessageOptions, type CreateModelPreferenceOptions, type CreateProjectOptions, type CreateUserPreferenceOptions, type CreateVaultMemoryOptions, type CryptoPriceClassification, type CryptoPricePreProcessorOptions, DEFAULT_ANALYSIS_PROMPT, DEFAULT_ANALYZE_AFTER_MESSAGES, DEFAULT_CACHE_EXPIRATION_MS, DEFAULT_CHUNK_CACHE_SIZE, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DECAY_POLICY, DEFAULT_DOCUMENT_PATTERN, DEFAULT_EXCLUDED_SERVER_TOOLS, DEFAULT_MAX_CLASSIFIER_CALLS_PER_SWEEP, DEFAULT_MAX_INPUT_MESSAGES, DEFAULT_MAX_PROFILE_LENGTH, DEFAULT_MIN_CHUNK_SIZE, DEFAULT_MIN_MESSAGES, DEFAULT_PERSONALITY_SETTINGS, DEFAULT_PROFILE_FACETS, DEFAULT_PROFILE_FACT_TYPE_WEIGHTS, DEFAULT_PROFILE_PROOF_ALPHA, DEFAULT_PROFILE_TREND_MULTIPLIERS, DEFAULT_PROMPT_TEMPLATES, DEFAULT_REFRESH_EVERY_MESSAGES, DEFAULT_SERVER_TOOLS_MATCH_OPTIONS, DEFAULT_SUMMARY_MIN_WINDOW_MESSAGES, DEFAULT_SUMMARY_MODEL, DEFAULT_SUMMARY_TOKEN_THRESHOLD, 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, ExcelProcessor, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type FactType, type FileMetadata, type FileProcessor, type FileTypeQuery, type FileWithData, type FlushResult, type GetConversationsPageOptions, type GraphTraversalOptions, HARD_DELETE_WINDOW_MS, INFERENCE_ID_HEADER, type InjectionClassifierOptions, type InjectionReason, type LazyStoredConversation, type LlmDecayClassifierOptions, type LlmNeighborRefinerOptions, type LlmTokenUsage, MAX_HOPS, MAX_MESSAGES_PER_SUMMARIZATION, MEDIUM_TTL_MS, Media, type MediaDimensions, type MediaFilterOptions, type MediaMetadata, type MediaOperationsContext, type MediaRole, type MediaType, type MemoriesNeedingTopicExtraction, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryQuarantinedEvent, type MemoryToVerify, type MemoryVaultSearchOptions, type MemoryVaultToolOptions, type MemoryVerification, Message, type MessageChunk, type MessageFeedback, type MessageOrigin, type ModelCallEndEvent, type ModelCallStartEvent, ModelPreference, NEVER_TTL_MS, NODE_BUDGET, type NeighborRefiner, type NowSource, type ObservationTrend, type ObservationTrendInput, type OperationExecutor, PAST_EVENT_GRACE_MS, PROFILE_DOC_VERSION, type ParsedServerToolsResponse, PdfProcessor, type PersonalitySettings, type PersonalitySliders, type PersonalityStyle, type PgClientLike, type PgPoolLike, type PhotoIngestResult, type PhotoMediaRef, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, PostgreSQLAdapter, type PostgreSQLAdapterOptions, type PreprocessingOptions, type PreprocessingResult, type ProcessedFileResult, ProcessorRegistry, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type ProfileUpdate, Project, type ProjectOperationsContext, type PromptContext, type PromptPreProcessor, type PromptPreProcessorContext, type PromptSection, type PromptTemplates, type PublishedPhotoMemory, type QuarantinedMemoryInfo, type QueueEncryptionContext, QueueManager, type QueueStatus, type QueuedOperation, type QueuedOperationType, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type ReflectOptions, type ReflectResult, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ResumeStreamOptions, type ResumeStreamResult, type RetainAction, type RetainContext, type RetainOptions, type RetainResult, type RetainSource, type RunEndEvent, type RunErrorEvent, type RunHooks, type RunStartEvent, type RunTerminalState, type RunToolLoopOptions, type RunToolLoopResult, SDK_SCHEMA_VERSION, SERVER_TOOL_DEPENDENCY_SETS, SHORT_TTL_MS, SLIDER_CONFIG, STREAM_RESUMABLE_HEADER, type ScoreBreakdown, type ScoreProfileSalienceOptions, type ScreenResult, type ScreenedCandidate, type SearchSource, type SelectServerToolsForPromptOptions, type ServerTool, type ServerToolCallEvent, type ServerToolsFilterFunction, type ServerToolsOptions, type ServerToolsResponse, type SettingsStorageOperationsContext, type SignMessageFn, type StepFinishEvent, type StockPriceClassification, type StockPricePreProcessorOptions, type StorageOperationsContext, type StoredConversation, type StoredConversationSummary, type StoredFileWithContext, type StoredMedia, type StoredMessage, type StoredMessageWithSimilarity, type StoredModelPreference, type StoredProject, type StoredUserPreference, type StoredVaultMemory, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type StreamSmoothingConfig, type StreamingTransport, type StreamingTransportOptions, type StreamingTransportResult, type StyleAnalysisSchedule, type SynthesizeProfileOptions, TOOL_CATALOG, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, TextProcessor, type ToolConfig, type ToolExecutor, type ToolMatchOptions, type ToolMatchResult, type ToolSet, type ToolUseEndEvent, type ToolUseStartEvent, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, type TopicSkipReason, type TurnCompleteEvent, type TurnSkippedEvent, type UncheckedReason, type UnverifiableReason, type UpdateMediaOptions, type UpdateModelPreferenceOptions, type UpdateProjectOptions, type UpdateUserPreferenceOptions, type UpdateVaultMemoryOptions, UserPreference, type UserPreferencesStorageOperationsContext, VAULT_SIZE_HOP_CAP, type VaultEmbeddingCache, VaultMemory, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultSaveOperation, type VaultSearchResult, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, WordProcessor, ZipProcessor, type ZipProcessorOptions, activatedToolSetNames, analyzeStyle, archiveVaultMemoryOp, backfillMemoryTopicsOp, buildConnectorGuidance, buildDeniedToolsRider, buildSystemPrompt, capHopsForDensity, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, cleanupConversationSummary, clearAllEncryptionKeys, clearAllEncryptionState, clearAllKeyPairs, clearEncryptionKey, clearKeyPair, clearLazyTitleCache, clearMessagesOp, clearServerToolsCache, composeHooks, createAutoExtractor, createChunkVectorCache, createConversationOp, createCryptoPricePreProcessor, createDecaySweeper, createLlmDecayClassifier, createLlmNeighborRefiner, createMediaBatchOp, createMediaOp, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageOp, createMessageSourceResolver, createPlatformCursorStore, createProjectOp, createRecallTool, createServerToolsFilter, createStockPricePreProcessor, createSummaryContext, createVaultEmbeddingCache, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decryptConversationTitle, decryptData, decryptDataBatch, decryptDataBytes, decryptDataBytesFromBytes, decryptDataWithKey, defaultServerToolsFilter, deleteAllVaultMemoriesForUserOp, deleteConversationOp, deleteConversationSummaryOp, deleteMediaByConversationOp, deleteMediaByMessageOp, deleteMediaOp, deleteModelPreferenceOp, deleteProjectOp, deleteUserPreferenceOp, deleteVaultMemoryOp, eagerEmbedContent, embedAllMessages, embedMessage, encryptData, encryptDataBatch, encryptDataBytes, encryptDataWithKey, estimateMessagesTokens, estimateTokens, exportPublicKey, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, findMatchingTools, generateConversationId, generateEmbedding, generateEmbeddings, generateMediaId, generateProjectId, getAIGeneratedMediaOp, getAllFilesOp, getAllVaultMemoriesOp, getAllVaultMemoryContentsOp, getAudioOp, getCachedServerTools, getConversationOp, getConversationSummaryOp, getConversationsByProjectLazyOp, getConversationsByProjectOp, getConversationsLazyOp, getConversationsOp, getConversationsPageOp, getDecayCandidatesRawOp, getDocumentsOp, getEncryptionKey, getImagesOp, getMediaByConversationOp, getMediaByIdOp, getMediaByIdsOp, getMediaByMessageOp, getMediaByModelOp, getMediaByRoleOp, getMediaBySourceUrlOp, getMediaByTypeOp, getMediaCountOp, getMediaCountsByTypeOp, getMediaOp, getMediaTypeFromMime, getMemoriesNeedingTopicExtractionOp, getMessageOp, getMessagesOp, getModelPreferenceOp, getProjectConversationCountOp, getProjectConversationsOp, getProjectOp, getProjectsOp, getRecentMediaOp, getServerTools, getSupportedFileTypes, getToolsChecksum, getUnfiledVaultMemoriesOp, getUserPreferenceOp, getUserUploadedMediaOp, getVaultMemoryOp, getVideosOp, hardDeleteDecayedOp, hardDeleteMediaOp, hasEncryptionKey, hasKeyPair, ingestPublishedPhotoMemoriesOp, injectionSignatureCatalog, isDegradedTopicSkip, isRerankerAvailable, isSupportedFile, isSupportedMediaType, makeSyntheticStoredConversation, makeSyntheticStoredMessage, maybeSummarizeHistory, mediaToStored, migrateFromModelPreferencesOp, onKeyAvailable, parseMedia, preEmbedVaultMemories, preprocessFiles, progressiveSummarize, projectToStored, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, relinkMemoryTopicsOp, relinkMisclassifiedVideosOp, renderTemplate, requestEncryptionKey, requestKeyPair, restoreVaultMemoryOp, resumeStream, retain, runToolLoop, sanitizeQuotes, schemaToCreateSQL, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchChunksOp, searchMediaOp, searchMessagesOp, searchVaultMemories, seedEncryptionKeys, selectServerToolsForPrompt, serverPlatformStorage, setMemoryVisibilityOp, setModelPreferenceOp, setUserPreferenceOp, shouldAnalyzeStyle, shouldChunkMessage, shouldRefreshTools, splitMessagesAtThreshold, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, summarizeObservationTrends, summaryToSystemMessage, supersedeVaultMemoryOp, synthesizeProfile, toolSetSystemPrompts, traverseGraphLane, ttlForType, updateConversationProjectOp, updateConversationTitleOp, updateMediaMessageIdBatchOp, updateMediaOp, updateMessageChunksOp, updateMessageEmbeddingOp, updateMessageErrorOp, updateMessageFeedbackOp, updateModelsOp, updatePersonalityOp, updateProfileOp, updateProjectNameOp, updateProjectOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertConversationSummaryOp, upsertMessageOp, verifyMemoriesForPublish };
10844
+ export { type AnalyzeStyleOptions, type AnalyzeStyleResult, type ApiResponse, type ApiType, type AutoExecutedToolResult, type AutoExtractMessage, type AutoExtractor, type Budget, type BuildPromptOptions, type BuildPromptResult, type CachedChunkVectors, type CachedServerTools, type ChatCompletionUsage, type ChatRole, type ChunkSearchResult, type ChunkVectorCache, type ChunkingOptions, type ConnectorGuidance, type ConnectorGuidanceInput, type ConsolidationAction, type ConsolidationFallbackReason, Conversation, ConversationSummary, type CreateAutoExtractorOptions, type CreateConversationOptions, type CreateDecaySweeperOptions, type CreateMediaOptions, type CreateMessageOptions, type CreateModelPreferenceOptions, type CreateProjectOptions, type CreateUserPreferenceOptions, type CreateVaultMemoryOptions, type CryptoPriceClassification, type CryptoPricePreProcessorOptions, DEFAULT_ANALYSIS_PROMPT, DEFAULT_ANALYZE_AFTER_MESSAGES, DEFAULT_CACHE_EXPIRATION_MS, DEFAULT_CHUNK_CACHE_SIZE, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DECAY_POLICY, DEFAULT_DOCUMENT_PATTERN, DEFAULT_EXCLUDED_SERVER_TOOLS, DEFAULT_MAX_CLASSIFIER_CALLS_PER_SWEEP, DEFAULT_MAX_INPUT_MESSAGES, DEFAULT_MAX_PROFILE_LENGTH, DEFAULT_MIN_CHUNK_SIZE, DEFAULT_MIN_MESSAGES, DEFAULT_PERSONALITY_SETTINGS, DEFAULT_PROFILE_FACETS, DEFAULT_PROFILE_FACT_TYPE_WEIGHTS, DEFAULT_PROFILE_PROOF_ALPHA, DEFAULT_PROFILE_TREND_MULTIPLIERS, DEFAULT_PROMPT_TEMPLATES, DEFAULT_REFRESH_EVERY_MESSAGES, DEFAULT_SERVER_TOOLS_MATCH_OPTIONS, DEFAULT_SUMMARY_MIN_WINDOW_MESSAGES, DEFAULT_SUMMARY_MODEL, DEFAULT_SUMMARY_TOKEN_THRESHOLD, 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, ExcelProcessor, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type ExtractionFunnel, type ExtractionTimings, type FactType, type FileMetadata, type FileProcessor, type FileTypeQuery, type FileWithData, type FlushResult, type GetConversationsPageOptions, type GraphTraversalOptions, HARD_DELETE_WINDOW_MS, INFERENCE_ID_HEADER, type InjectionClassifierOptions, type InjectionReason, type LazyStoredConversation, type LlmDecayClassifierOptions, type LlmNeighborRefinerOptions, type LlmTokenUsage, MAX_HOPS, MAX_MESSAGES_PER_SUMMARIZATION, MEDIUM_TTL_MS, Media, type MediaDimensions, type MediaFilterOptions, type MediaMetadata, type MediaOperationsContext, type MediaRole, type MediaType, type MemoriesNeedingTopicExtraction, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryQuarantinedEvent, type MemoryToVerify, type MemoryVaultSearchOptions, type MemoryVaultToolOptions, type MemoryVerification, Message, type MessageChunk, type MessageFeedback, type MessageOrigin, type ModelCallEndEvent, type ModelCallStartEvent, ModelPreference, NEVER_TTL_MS, NODE_BUDGET, type NeighborRefiner, type NowSource, type ObservationTrend, type ObservationTrendInput, type OperationExecutor, PAST_EVENT_GRACE_MS, PROFILE_DOC_VERSION, type ParsedServerToolsResponse, PdfProcessor, type PersonalitySettings, type PersonalitySliders, type PersonalityStyle, type PgClientLike, type PgPoolLike, type PhotoIngestResult, type PhotoMediaRef, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, PostgreSQLAdapter, type PostgreSQLAdapterOptions, type PreprocessingOptions, type PreprocessingResult, type ProcessedFileResult, ProcessorRegistry, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type ProfileUpdate, Project, type ProjectOperationsContext, type PromptContext, type PromptPreProcessor, type PromptPreProcessorContext, type PromptSection, type PromptTemplates, type PublishedPhotoMemory, type QuarantinedMemoryInfo, type QueueEncryptionContext, QueueManager, type QueueStatus, type QueuedOperation, type QueuedOperationType, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type ReflectOptions, type ReflectResult, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ResumeStreamOptions, type ResumeStreamResult, type RetainAction, type RetainContext, type RetainOptions, type RetainResult, type RetainSource, type RunEndEvent, type RunErrorEvent, type RunHooks, type RunStartEvent, type RunTerminalState, type RunToolLoopOptions, type RunToolLoopResult, SDK_SCHEMA_VERSION, SERVER_TOOL_DEPENDENCY_SETS, SHORT_TTL_MS, SLIDER_CONFIG, STREAM_RESUMABLE_HEADER, type ScoreBreakdown, type ScoreProfileSalienceOptions, type ScreenResult, type ScreenedCandidate, type SearchSource, type SelectServerToolsForPromptOptions, type ServerTool, type ServerToolCallEvent, type ServerToolsFilterFunction, type ServerToolsOptions, type ServerToolsResponse, type SettingsStorageOperationsContext, type SignMessageFn, type StepFinishEvent, type StockPriceClassification, type StockPricePreProcessorOptions, type StorageOperationsContext, type StoredConversation, type StoredConversationSummary, type StoredFileWithContext, type StoredMedia, type StoredMessage, type StoredMessageWithSimilarity, type StoredModelPreference, type StoredProject, type StoredUserPreference, type StoredVaultMemory, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type StreamSmoothingConfig, type StreamingTransport, type StreamingTransportOptions, type StreamingTransportResult, type StyleAnalysisSchedule, type SynthesizeProfileOptions, TOOL_CATALOG, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, TextProcessor, type ToolConfig, type ToolExecutor, type ToolMatchOptions, type ToolMatchResult, type ToolSet, type ToolUseEndEvent, type ToolUseStartEvent, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, type TopicSkipReason, type TurnCompleteEvent, type TurnSkippedEvent, type UncheckedReason, type UnverifiableReason, type UpdateMediaOptions, type UpdateModelPreferenceOptions, type UpdateProjectOptions, type UpdateUserPreferenceOptions, type UpdateVaultMemoryOptions, UserPreference, type UserPreferencesStorageOperationsContext, VAULT_SIZE_HOP_CAP, type VaultEmbeddingCache, VaultMemory, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultSaveOperation, type VaultSearchResult, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, WordProcessor, ZipProcessor, type ZipProcessorOptions, activatedToolSetNames, analyzeStyle, archiveVaultMemoryOp, backfillMemoryTopicsOp, buildConnectorGuidance, buildDeniedToolsRider, buildSystemPrompt, capHopsForDensity, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, cleanupConversationSummary, clearAllEncryptionKeys, clearAllEncryptionState, clearAllKeyPairs, clearEncryptionKey, clearKeyPair, clearLazyTitleCache, clearMessagesOp, clearServerToolsCache, composeHooks, createAutoExtractor, createChunkVectorCache, createConversationOp, createCryptoPricePreProcessor, createDecaySweeper, createLlmDecayClassifier, createLlmNeighborRefiner, createMediaBatchOp, createMediaOp, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageOp, createMessageSourceResolver, createPlatformCursorStore, createProjectOp, createRecallTool, createServerToolsFilter, createStockPricePreProcessor, createSummaryContext, createVaultEmbeddingCache, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decryptConversationTitle, decryptData, decryptDataBatch, decryptDataBytes, decryptDataBytesFromBytes, decryptDataWithKey, defaultServerToolsFilter, deleteAllVaultMemoriesForUserOp, deleteConversationOp, deleteConversationSummaryOp, deleteMediaByConversationOp, deleteMediaByMessageOp, deleteMediaOp, deleteModelPreferenceOp, deleteProjectOp, deleteUserPreferenceOp, deleteVaultMemoryOp, eagerEmbedContent, embedAllMessages, embedMessage, encryptData, encryptDataBatch, encryptDataBytes, encryptDataWithKey, estimateMessagesTokens, estimateTokens, exportPublicKey, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, findMatchingTools, generateConversationId, generateEmbedding, generateEmbeddings, generateMediaId, generateProjectId, getAIGeneratedMediaOp, getAllFilesOp, getAllVaultMemoriesOp, getAllVaultMemoryContentsOp, getAudioOp, getCachedServerTools, getConversationOp, getConversationSummaryOp, getConversationsByProjectLazyOp, getConversationsByProjectOp, getConversationsLazyOp, getConversationsOp, getConversationsPageOp, getDecayCandidatesRawOp, getDocumentsOp, getEncryptionKey, getImagesOp, getMediaByConversationOp, getMediaByIdOp, getMediaByIdsOp, getMediaByMessageOp, getMediaByModelOp, getMediaByRoleOp, getMediaBySourceUrlOp, getMediaByTypeOp, getMediaCountOp, getMediaCountsByTypeOp, getMediaOp, getMediaTypeFromMime, getMemoriesNeedingTopicExtractionOp, getMessageOp, getMessagesOp, getModelPreferenceOp, getProjectConversationCountOp, getProjectConversationsOp, getProjectOp, getProjectsOp, getRecentMediaOp, getServerTools, getSupportedFileTypes, getToolsChecksum, getUnfiledVaultMemoriesOp, getUserPreferenceOp, getUserUploadedMediaOp, getVaultMemoryOp, getVideosOp, hardDeleteDecayedOp, hardDeleteMediaOp, hasEncryptionKey, hasKeyPair, ingestPublishedPhotoMemoriesOp, injectionSignatureCatalog, isDegradedTopicSkip, isRerankerAvailable, isSupportedFile, isSupportedMediaType, makeSyntheticStoredConversation, makeSyntheticStoredMessage, maybeSummarizeHistory, mediaToStored, migrateFromModelPreferencesOp, onKeyAvailable, parseMedia, preEmbedVaultMemories, preprocessFiles, progressiveSummarize, projectToStored, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, relinkMemoryTopicsOp, relinkMisclassifiedVideosOp, renderTemplate, requestEncryptionKey, requestKeyPair, restoreVaultMemoryOp, resumeStream, retain, runToolLoop, sanitizeQuotes, schemaToCreateSQL, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchChunksOp, searchMediaOp, searchMessagesOp, searchVaultMemories, seedEncryptionKeys, selectServerToolsForPrompt, serverPlatformStorage, setMemoryVisibilityOp, setModelPreferenceOp, setUserPreferenceOp, shouldAnalyzeStyle, shouldChunkMessage, shouldRefreshTools, splitMessagesAtThreshold, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, summarizeObservationTrends, summaryToSystemMessage, supersedeVaultMemoryOp, synthesizeProfile, toolSetSystemPrompts, traverseGraphLane, ttlForType, updateConversationProjectOp, updateConversationTitleOp, updateMediaMessageIdBatchOp, updateMediaOp, updateMessageChunksOp, updateMessageEmbeddingOp, updateMessageErrorOp, updateMessageFeedbackOp, updateModelsOp, updatePersonalityOp, updateProfileOp, updateProjectNameOp, updateProjectOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertConversationSummaryOp, upsertMessageOp, verifyMemoriesForPublish };
@@ -5496,6 +5496,7 @@ async function retain(content, ctx, options = {}) {
5496
5496
  const threshold = options.autoMergeThreshold ?? DEFAULT_AUTO_MERGE_THRESHOLD;
5497
5497
  const resolvedScope = options.scope ?? DEFAULT_SCOPE;
5498
5498
  let supersedeTargetIds = [];
5499
+ let consolidationDecidedCreate = false;
5499
5500
  let supersedeContent;
5500
5501
  let prepared;
5501
5502
  if (enableAutoMerge) {
@@ -5523,8 +5524,12 @@ async function retain(content, ctx, options = {}) {
5523
5524
  const outcome = await tryConsolidate(trimmed, ctx, options, prepared);
5524
5525
  if (outcome) {
5525
5526
  if ("done" in outcome) return outcome.done;
5526
- supersedeTargetIds = outcome.supersede;
5527
- supersedeContent = outcome.content;
5527
+ if ("create" in outcome) {
5528
+ consolidationDecidedCreate = true;
5529
+ } else {
5530
+ supersedeTargetIds = outcome.supersede;
5531
+ supersedeContent = outcome.content;
5532
+ }
5528
5533
  }
5529
5534
  }
5530
5535
  if (supersedeTargetIds.length === 0) {
@@ -5574,7 +5579,14 @@ async function retain(content, ctx, options = {}) {
5574
5579
  action: "merge",
5575
5580
  memoryId: targetId,
5576
5581
  targetId,
5577
- proofCount: updated.proofCount ?? (existing.proofCount ?? 1) + 1
5582
+ proofCount: updated.proofCount ?? (existing.proofCount ?? 1) + 1,
5583
+ similarity: matches[0].similarity,
5584
+ // Stage 1 may have run and explicitly said `create`, and Stage 2
5585
+ // then found a strict-cosine match anyway. Reporting the decision
5586
+ // here is what makes that DISAGREEMENT visible — without it the
5587
+ // model's create silently vanished from the distribution whenever
5588
+ // the cosine stage won.
5589
+ ...consolidationDecidedCreate && { consolidation: "create" }
5578
5590
  };
5579
5591
  }
5580
5592
  await assertMergeTargetGoneOrThrow(ctx, targetId);
@@ -5587,12 +5599,18 @@ async function retain(content, ctx, options = {}) {
5587
5599
  const embedding = reusableQueryEmbedding ?? await generateEmbedding(contentToWrite, ctx.embeddingOptions);
5588
5600
  const embeddingModel = ctx.embeddingOptions.model ?? DEFAULT_API_EMBEDDING_MODEL;
5589
5601
  if (options.respectTombstones) {
5590
- const tombstoneId = await findTombstoneMatch(embedding, embeddingModel, resolvedScope, ctx, {
5602
+ const tombstone = await findTombstoneMatch(embedding, embeddingModel, resolvedScope, ctx, {
5591
5603
  threshold,
5592
5604
  folderId: options.folderId
5593
5605
  });
5594
- if (tombstoneId) {
5595
- return { action: "suppressed", memoryId: tombstoneId, tombstoneId, proofCount: 0 };
5606
+ if (tombstone) {
5607
+ return {
5608
+ action: "suppressed",
5609
+ memoryId: tombstone.id,
5610
+ tombstoneId: tombstone.id,
5611
+ proofCount: 0,
5612
+ similarity: tombstone.similarity
5613
+ };
5596
5614
  }
5597
5615
  }
5598
5616
  const createOpts = {
@@ -5659,7 +5677,8 @@ async function retain(content, ctx, options = {}) {
5659
5677
  action: "supersede",
5660
5678
  memoryId: created2.uniqueId,
5661
5679
  targetId: primaryTargetId,
5662
- proofCount: 1
5680
+ proofCount: 1,
5681
+ consolidation: "supersede"
5663
5682
  };
5664
5683
  }
5665
5684
  notifyConsolidationFallback(
@@ -5673,7 +5692,8 @@ async function retain(content, ctx, options = {}) {
5673
5692
  return {
5674
5693
  action: "create",
5675
5694
  memoryId: created.uniqueId,
5676
- proofCount: 1
5695
+ proofCount: 1,
5696
+ ...consolidationDecidedCreate && { consolidation: "create" }
5677
5697
  };
5678
5698
  }
5679
5699
  function unionStrings(a, b) {
@@ -5703,7 +5723,7 @@ async function findTombstoneMatch(embedding, embeddingModel, scope, ctx, opts) {
5703
5723
  bestId = row.uniqueId;
5704
5724
  }
5705
5725
  }
5706
- return bestId;
5726
+ return bestId === null ? null : { id: bestId, similarity: bestSim };
5707
5727
  }
5708
5728
  function pickEventTimeUpdate(existing, incoming) {
5709
5729
  if (incoming === void 0 || incoming === null) return void 0;
@@ -5745,7 +5765,7 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
5745
5765
  }));
5746
5766
  const { consolidateMemory: doConsolidate } = await import("./consolidate-54P6QZKU.mjs");
5747
5767
  const decision = await doConsolidate(trimmed, candidates, consolidateOptions);
5748
- if (decision.action === "create") return null;
5768
+ if (decision.action === "create") return decision.fallbackReason ? null : { create: true };
5749
5769
  if (decision.action === "supersede" && decision.content) {
5750
5770
  const requestedIds = decision.targetIds?.length ? decision.targetIds : decision.targetId ? [decision.targetId] : [];
5751
5771
  if (requestedIds.length === 0) return null;
@@ -5804,7 +5824,8 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
5804
5824
  action: "merge",
5805
5825
  memoryId: decision.targetId,
5806
5826
  targetId: decision.targetId,
5807
- proofCount: updated.proofCount ?? (existing.proofCount ?? 1) + 1
5827
+ proofCount: updated.proofCount ?? (existing.proofCount ?? 1) + 1,
5828
+ consolidation: "noop"
5808
5829
  }
5809
5830
  };
5810
5831
  }
@@ -5857,7 +5878,8 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
5857
5878
  action: "update",
5858
5879
  memoryId: decision.targetId,
5859
5880
  targetId: decision.targetId,
5860
- proofCount: updated.proofCount ?? (existing.proofCount ?? 1) + 1
5881
+ proofCount: updated.proofCount ?? (existing.proofCount ?? 1) + 1,
5882
+ consolidation: "update"
5861
5883
  }
5862
5884
  };
5863
5885
  }
@@ -5999,6 +6021,11 @@ Extract durable user facts.`,
5999
6021
  fallbackSourceId,
6000
6022
  options.userIdentity ?? []
6001
6023
  );
6024
+ const rawCandidates = parsed.candidates;
6025
+ options.onCandidatesParsed?.({
6026
+ rawCount: Array.isArray(rawCandidates) ? rawCandidates.length : 0,
6027
+ validCount: candidates.length
6028
+ });
6002
6029
  if (!redactor) return candidates;
6003
6030
  const restored = restoreCandidates(candidates, redactor, options.userIdentity ?? []);
6004
6031
  if (candidates.length > 0 && restored.length === 0) {
@@ -6035,8 +6062,12 @@ async function extractAndRetain(messages, retainCtx, options) {
6035
6062
  let exhaustedEmpty = false;
6036
6063
  let exhaustedFailure;
6037
6064
  let droppedAfterRedaction = false;
6065
+ let rawCandidateCount = 0;
6066
+ let validCandidateCount = 0;
6038
6067
  const callerOnExhaustedEmpty = options.extract.onExhaustedEmpty;
6039
6068
  const callerOnCandidatesDropped = options.extract.onCandidatesDropped;
6069
+ const callerOnCandidatesParsed = options.extract.onCandidatesParsed;
6070
+ const tExtract = Date.now();
6040
6071
  const candidates = await extractFacts(messages, {
6041
6072
  ...options.extract,
6042
6073
  onExhaustedEmpty: (failure) => {
@@ -6047,8 +6078,14 @@ async function extractAndRetain(messages, retainCtx, options) {
6047
6078
  onCandidatesDropped: () => {
6048
6079
  droppedAfterRedaction = true;
6049
6080
  callerOnCandidatesDropped?.();
6081
+ },
6082
+ onCandidatesParsed: (stats) => {
6083
+ rawCandidateCount = stats.rawCount;
6084
+ validCandidateCount = stats.validCount;
6085
+ callerOnCandidatesParsed?.(stats);
6050
6086
  }
6051
6087
  });
6088
+ const extractMs = Date.now() - tExtract;
6052
6089
  const filtered = candidates.filter((c) => c.confidence >= minConfidence);
6053
6090
  const log = getLogger();
6054
6091
  const screened = screenCandidatesForInjection(filtered);
@@ -6096,6 +6133,7 @@ async function extractAndRetain(messages, retainCtx, options) {
6096
6133
  const results = [];
6097
6134
  const quarantinedInfo = [];
6098
6135
  let failedWrites = 0;
6136
+ const tRetain = Date.now();
6099
6137
  for (const { candidate, isQuarantined, reason, signature } of toRetain) {
6100
6138
  try {
6101
6139
  const result = await retain(candidate.content, retainCtx, {
@@ -6162,6 +6200,21 @@ async function extractAndRetain(messages, retainCtx, options) {
6162
6200
  failedCount: failedWrites,
6163
6201
  outcome,
6164
6202
  quarantined: quarantinedInfo,
6203
+ funnel: {
6204
+ rawCandidateCount,
6205
+ validCandidateCount,
6206
+ afterRedactionCount: candidates.length,
6207
+ aboveConfidenceCount: filtered.length,
6208
+ // The PERSISTED quarantines (`quarantinedInfo`), not the screened list: a
6209
+ // screened candidate whose retain() throws is counted in `failedCount`,
6210
+ // and counting it here too would double it and break the identity below.
6211
+ // This also keeps the count equal to `quarantined.length` on the result.
6212
+ quarantinedCount: quarantinedInfo.length,
6213
+ retainedCount: results.length,
6214
+ failedCount: failedWrites
6215
+ },
6216
+ timings: { extractMs, retainMs: Date.now() - tRetain },
6217
+ model: options.extract.model ?? DEFAULT_EXTRACTION_MODEL,
6165
6218
  // Only meaningful alongside `outcome: "empty-after-retry"`. Returned as well
6166
6219
  // as pushed through the callback so a consumer that only inspects the result
6167
6220
  // (rather than wiring a hook) can still report WHY.
@@ -6415,27 +6468,23 @@ function createAutoExtractor(options) {
6415
6468
  const t0 = Date.now();
6416
6469
  void (async () => {
6417
6470
  try {
6418
- const { candidates, results, failedCount, outcome, failure } = await extractAndRetain(
6419
- window2,
6420
- retainCtx,
6421
- {
6422
- extract,
6423
- ...options.minConfidence !== void 0 && { minConfidence: options.minConfidence },
6424
- ...options.entityCtx !== void 0 && { entityCtx: options.entityCtx },
6425
- ...options.scope !== void 0 && { scope: options.scope },
6426
- ...options.folderId !== void 0 && { folderId: options.folderId },
6427
- ...consolidateOptions !== void 0 && { consolidateOptions },
6428
- ...injectionClassifierOptions !== void 0 && {
6429
- injectionClassifier: injectionClassifierOptions
6430
- },
6431
- ...options.onCandidateFailed && {
6432
- onCandidateFailed: (candidate, error) => options.onCandidateFailed?.({ candidate, error, conversationId })
6433
- },
6434
- ...options.onMemoryQuarantined && {
6435
- onQuarantined: (info) => options.onMemoryQuarantined?.({ ...info, conversationId })
6436
- }
6471
+ const { candidates, results, failedCount, outcome, failure, funnel, timings, model } = await extractAndRetain(window2, retainCtx, {
6472
+ extract,
6473
+ ...options.minConfidence !== void 0 && { minConfidence: options.minConfidence },
6474
+ ...options.entityCtx !== void 0 && { entityCtx: options.entityCtx },
6475
+ ...options.scope !== void 0 && { scope: options.scope },
6476
+ ...options.folderId !== void 0 && { folderId: options.folderId },
6477
+ ...consolidateOptions !== void 0 && { consolidateOptions },
6478
+ ...injectionClassifierOptions !== void 0 && {
6479
+ injectionClassifier: injectionClassifierOptions
6480
+ },
6481
+ ...options.onCandidateFailed && {
6482
+ onCandidateFailed: (candidate, error) => options.onCandidateFailed?.({ candidate, error, conversationId })
6483
+ },
6484
+ ...options.onMemoryQuarantined && {
6485
+ onQuarantined: (info) => options.onMemoryQuarantined?.({ ...info, conversationId })
6437
6486
  }
6438
- );
6487
+ });
6439
6488
  if (outcome !== "empty-after-retry") {
6440
6489
  const advancedTo = window2[window2.length - 1].id;
6441
6490
  stateFor(conversationId).watermark = advancedTo;
@@ -6456,6 +6505,9 @@ function createAutoExtractor(options) {
6456
6505
  durationMs: Date.now() - t0,
6457
6506
  conversationId,
6458
6507
  outcome,
6508
+ funnel,
6509
+ timings,
6510
+ model,
6459
6511
  // Only set alongside `outcome: "empty-after-retry"`. Spread so the key
6460
6512
  // is absent rather than explicitly undefined on a healthy turn —
6461
6513
  // analytics backends store an explicit undefined as a real value.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anuma/sdk",
3
- "version": "6.19.2",
3
+ "version": "6.20.0",
4
4
  "description": "",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.mjs",