@anuma/sdk 6.7.1 → 6.7.3
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.
- package/dist/client/index.cjs +66 -0
- package/dist/client/index.d.mts +472 -1
- package/dist/client/index.d.ts +472 -1
- package/dist/client/index.mjs +58 -0
- package/dist/expo/{chunk-2YHVYDEL.mjs → chunk-37VWRZTL.mjs} +2 -2
- package/dist/{react/chunk-B5UPJRCU.mjs → expo/chunk-5GBYOWRY.mjs} +48 -10
- package/dist/expo/{chunk-VOMDHMKH.mjs → chunk-ITRFWFNS.mjs} +1 -1
- package/dist/{react/consolidate-ZCGS7QUA.mjs → expo/consolidate-H6YD36XI.mjs} +2 -2
- package/dist/expo/index.cjs +67 -16
- package/dist/expo/index.d.mts +67 -2
- package/dist/expo/index.d.ts +67 -2
- package/dist/expo/index.mjs +22 -9
- package/dist/expo/{recall-M3JVFTZL.mjs → recall-FZ7JC4AX.mjs} +2 -2
- package/dist/{expo/chunk-B5UPJRCU.mjs → react/chunk-5GBYOWRY.mjs} +48 -10
- package/dist/react/{chunk-S6WPXD5N.mjs → chunk-NC7BZEEF.mjs} +2 -2
- package/dist/react/{chunk-2ARMO2NN.mjs → chunk-ZZDMEEHO.mjs} +1 -1
- package/dist/{expo/consolidate-TWE6OSSZ.mjs → react/consolidate-FNFIDL37.mjs} +2 -2
- package/dist/react/index.cjs +67 -16
- package/dist/react/index.d.mts +67 -2
- package/dist/react/index.d.ts +67 -2
- package/dist/react/index.mjs +22 -9
- package/dist/react/{recall-ROEK55FJ.mjs → recall-546HTUPK.mjs} +2 -2
- package/dist/server/{chunk-CR5P3YIK.mjs → chunk-5KIUGHQZ.mjs} +1 -1
- package/dist/server/{chunk-TD7SMY7C.mjs → chunk-G6IH6QTZ.mjs} +2 -2
- package/dist/server/{chunk-VHWLLYKO.mjs → chunk-I2U35Z3O.mjs} +48 -10
- package/dist/server/{consolidate-FWYK5KXB.mjs → consolidate-S7QZ7V6T.mjs} +2 -2
- package/dist/server/index.cjs +67 -16
- package/dist/server/index.d.mts +67 -2
- package/dist/server/index.d.ts +67 -2
- package/dist/server/index.mjs +22 -9
- package/dist/server/{recall-CGDEW2LQ.mjs → recall-BIPVQMG4.mjs} +2 -2
- package/package.json +2 -2
package/dist/expo/index.d.ts
CHANGED
|
@@ -4880,6 +4880,60 @@ interface PortalLlmAuth {
|
|
|
4880
4880
|
/** Function to get an auth token (e.g., Privy's getIdentityToken). Token is sent as `Authorization: Bearer`. */
|
|
4881
4881
|
getToken?: () => Promise<string | null>;
|
|
4882
4882
|
}
|
|
4883
|
+
/**
|
|
4884
|
+
* Why a portal JSON completion gave up, as a STABLE low-cardinality code.
|
|
4885
|
+
*
|
|
4886
|
+
* The retry loop has always classified its failures precisely, but only as an
|
|
4887
|
+
* interpolated `reason` string for `log.warn` — and prod ships no SDK log
|
|
4888
|
+
* (sdk#883), so in production every one of these collapsed into a single
|
|
4889
|
+
* `empty-after-retry` with no way to tell them apart. That is what made the
|
|
4890
|
+
* 2026-08-11 audit need a Prometheus cross-check to discover that the portal
|
|
4891
|
+
* was returning HTTP 200 with an empty body on ~60% of extraction turns.
|
|
4892
|
+
*
|
|
4893
|
+
* Codes are deliberately an enum, not the `reason` string: the strings embed
|
|
4894
|
+
* status codes and error messages, so they are unbounded and useless as an
|
|
4895
|
+
* analytics property. Keep this list SHORT and stable — it is a telemetry
|
|
4896
|
+
* contract, and a value added here has to mean the same thing in six months.
|
|
4897
|
+
*
|
|
4898
|
+
* @public
|
|
4899
|
+
*/
|
|
4900
|
+
type PortalLlmFailureReason =
|
|
4901
|
+
/** No usable credential — `getToken` returned null or threw. Terminal. */
|
|
4902
|
+
"auth-unavailable"
|
|
4903
|
+
/** Non-retryable HTTP status (400/403/404, or 401 on the static-apiKey path). */
|
|
4904
|
+
| "http-terminal"
|
|
4905
|
+
/** Retryable status (408/409/425/429/5xx) that never succeeded. */
|
|
4906
|
+
| "http-retryable"
|
|
4907
|
+
/** Network error or the per-attempt timeout aborted the fetch. */
|
|
4908
|
+
| "network"
|
|
4909
|
+
/** HTTP 200 but the envelope itself wasn't JSON. */
|
|
4910
|
+
| "body-parse-failed"
|
|
4911
|
+
/**
|
|
4912
|
+
* HTTP 200 with NO completion content. The reasoning-class failure mode:
|
|
4913
|
+
* the model spends its budget on unreturned thinking and answers empty.
|
|
4914
|
+
*/
|
|
4915
|
+
| "empty-content"
|
|
4916
|
+
/** Content present, but no parseable JSON in it (prose, a clarifying question). */
|
|
4917
|
+
| "invalid-json"
|
|
4918
|
+
/** Content parsed to a literal `null`, which is never a valid response. */
|
|
4919
|
+
| "null-completion"
|
|
4920
|
+
/** `totalTimeoutMs` was spent before the next attempt could run. */
|
|
4921
|
+
| "time-budget-exhausted";
|
|
4922
|
+
/**
|
|
4923
|
+
* A give-up report: the classified {@link PortalLlmFailureReason} plus the
|
|
4924
|
+
* little context worth carrying into telemetry. Both extra fields are bounded
|
|
4925
|
+
* (a status code, a small attempt count), so both are safe as event properties.
|
|
4926
|
+
*
|
|
4927
|
+
* @public
|
|
4928
|
+
*/
|
|
4929
|
+
interface PortalLlmFailure {
|
|
4930
|
+
/** Stable code for the last failure observed. */
|
|
4931
|
+
reason: PortalLlmFailureReason;
|
|
4932
|
+
/** HTTP status, when the failure was an HTTP one. */
|
|
4933
|
+
httpStatus?: number;
|
|
4934
|
+
/** How many attempts ran before giving up (1-based, ≥ 1). */
|
|
4935
|
+
attempts: number;
|
|
4936
|
+
}
|
|
4883
4937
|
|
|
4884
4938
|
/**
|
|
4885
4939
|
* Optional LLM injection classifier — Tier-0 security second layer (PR5).
|
|
@@ -5984,8 +6038,14 @@ interface ExtractFactsOptions extends PortalLlmAuth {
|
|
|
5984
6038
|
* `{candidates: []}` "nothing durable here". Lets callers distinguish a
|
|
5985
6039
|
* silently-degrading extractor from quiet turns (the two are otherwise
|
|
5986
6040
|
* indistinguishable). See {@link extractAndRetain}'s `outcome`.
|
|
6041
|
+
*
|
|
6042
|
+
* Receives the classified {@link PortalLlmFailure}. Knowing THAT extraction
|
|
6043
|
+
* failed was not enough: the 2026-08-11 audit found ~60% of production turns
|
|
6044
|
+
* ending here and had to cross-check Prometheus to learn that the cause was
|
|
6045
|
+
* HTTP-200-with-empty-body rather than the 403 everyone assumed. Forward
|
|
6046
|
+
* `failure.reason` into analytics so the next such question is a query.
|
|
5987
6047
|
*/
|
|
5988
|
-
onExhaustedEmpty?: () => void;
|
|
6048
|
+
onExhaustedEmpty?: (failure: PortalLlmFailure) => void;
|
|
5989
6049
|
/**
|
|
5990
6050
|
* Called when the extractor DID produce candidates but PII de-anonymization
|
|
5991
6051
|
* dropped every one of them — the model mangled its placeholders (so they
|
|
@@ -6108,6 +6168,11 @@ declare function extractAndRetain(messages: AutoExtractMessage[], retainCtx: Ret
|
|
|
6108
6168
|
* "extracted but held for review".
|
|
6109
6169
|
*/
|
|
6110
6170
|
quarantined: QuarantinedMemoryInfo[];
|
|
6171
|
+
/**
|
|
6172
|
+
* Present only when `outcome` is `empty-after-retry` — the classified cause of
|
|
6173
|
+
* the give-up, so "extraction is failing" can be reported as *why* it failed.
|
|
6174
|
+
*/
|
|
6175
|
+
failure?: PortalLlmFailure;
|
|
6111
6176
|
}>;
|
|
6112
6177
|
|
|
6113
6178
|
/**
|
|
@@ -10232,4 +10297,4 @@ declare function refreshNotionAccessToken(params: NotionRefreshTokenParams): Pro
|
|
|
10232
10297
|
*/
|
|
10233
10298
|
declare function createNotionTools(getAccessToken: () => string | null, requestNotionAccess: () => Promise<string>): ToolConfig[];
|
|
10234
10299
|
|
|
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 };
|
|
10300
|
+
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 };
|
package/dist/expo/index.mjs
CHANGED
|
@@ -132,7 +132,7 @@ import {
|
|
|
132
132
|
upsertMessageOp,
|
|
133
133
|
useEncryption,
|
|
134
134
|
vaultMemoryToStored
|
|
135
|
-
} from "./chunk-
|
|
135
|
+
} from "./chunk-37VWRZTL.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-
|
|
143
|
+
} from "./chunk-ITRFWFNS.mjs";
|
|
144
144
|
import {
|
|
145
145
|
INTERNAL_FLOW_MARKER,
|
|
146
146
|
callPortalJsonCompletion,
|
|
@@ -153,7 +153,7 @@ import {
|
|
|
153
153
|
supportsResponseFormat,
|
|
154
154
|
validateEndpointOverride,
|
|
155
155
|
withInternalFlowMarker
|
|
156
|
-
} from "./chunk-
|
|
156
|
+
} from "./chunk-5GBYOWRY.mjs";
|
|
157
157
|
import {
|
|
158
158
|
BASE_URL,
|
|
159
159
|
MCP_R2_DOMAIN,
|
|
@@ -6861,7 +6861,7 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
|
|
|
6861
6861
|
content: m.content,
|
|
6862
6862
|
similarity: m.similarity
|
|
6863
6863
|
}));
|
|
6864
|
-
const { consolidateMemory: doConsolidate } = await import("./consolidate-
|
|
6864
|
+
const { consolidateMemory: doConsolidate } = await import("./consolidate-H6YD36XI.mjs");
|
|
6865
6865
|
const decision = await doConsolidate(trimmed, candidates, consolidateOptions);
|
|
6866
6866
|
if (decision.action === "create") return null;
|
|
6867
6867
|
if (decision.action === "supersede" && decision.content) {
|
|
@@ -7078,7 +7078,11 @@ async function extractFacts(messages, options) {
|
|
|
7078
7078
|
}
|
|
7079
7079
|
const transcript = transcriptLines.join("\n");
|
|
7080
7080
|
const today = formatLocalDate(options.now ?? Date.now());
|
|
7081
|
+
let failure;
|
|
7081
7082
|
const parsed = await callPortalJsonCompletion({
|
|
7083
|
+
onFailure: (f) => {
|
|
7084
|
+
failure = f;
|
|
7085
|
+
},
|
|
7082
7086
|
...options.apiKey !== void 0 && { apiKey: options.apiKey },
|
|
7083
7087
|
...options.getToken !== void 0 && { getToken: options.getToken },
|
|
7084
7088
|
...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
|
|
@@ -7101,7 +7105,7 @@ Extract durable user facts.`,
|
|
|
7101
7105
|
...options.backoffMs && { backoffMs: options.backoffMs }
|
|
7102
7106
|
});
|
|
7103
7107
|
if (parsed === null) {
|
|
7104
|
-
options.onExhaustedEmpty?.();
|
|
7108
|
+
options.onExhaustedEmpty?.(failure ?? { reason: "empty-content", attempts: 1 });
|
|
7105
7109
|
return [];
|
|
7106
7110
|
}
|
|
7107
7111
|
const fallbackSourceId = [...messages].reverse().find((m) => m.role === "user")?.id;
|
|
@@ -7145,14 +7149,16 @@ async function extractAndRetain(messages, retainCtx, options) {
|
|
|
7145
7149
|
...resolvedConsolidatePii !== void 0 && { piiRedaction: resolvedConsolidatePii }
|
|
7146
7150
|
} : void 0;
|
|
7147
7151
|
let exhaustedEmpty = false;
|
|
7152
|
+
let exhaustedFailure;
|
|
7148
7153
|
let droppedAfterRedaction = false;
|
|
7149
7154
|
const callerOnExhaustedEmpty = options.extract.onExhaustedEmpty;
|
|
7150
7155
|
const callerOnCandidatesDropped = options.extract.onCandidatesDropped;
|
|
7151
7156
|
const candidates = await extractFacts(messages, {
|
|
7152
7157
|
...options.extract,
|
|
7153
|
-
onExhaustedEmpty: () => {
|
|
7158
|
+
onExhaustedEmpty: (failure) => {
|
|
7154
7159
|
exhaustedEmpty = true;
|
|
7155
|
-
|
|
7160
|
+
exhaustedFailure = failure;
|
|
7161
|
+
callerOnExhaustedEmpty?.(failure);
|
|
7156
7162
|
},
|
|
7157
7163
|
onCandidatesDropped: () => {
|
|
7158
7164
|
droppedAfterRedaction = true;
|
|
@@ -7271,12 +7277,19 @@ async function extractAndRetain(messages, retainCtx, options) {
|
|
|
7271
7277
|
results,
|
|
7272
7278
|
failedCount: failedWrites,
|
|
7273
7279
|
outcome,
|
|
7274
|
-
quarantined: quarantinedInfo
|
|
7280
|
+
quarantined: quarantinedInfo,
|
|
7281
|
+
// Only meaningful alongside `outcome: "empty-after-retry"`. Returned as well
|
|
7282
|
+
// as pushed through the callback so a consumer that only inspects the result
|
|
7283
|
+
// (rather than wiring a hook) can still report WHY.
|
|
7284
|
+
...exhaustedFailure !== void 0 && { failure: exhaustedFailure }
|
|
7275
7285
|
};
|
|
7276
7286
|
}
|
|
7287
|
+
var UTTERANCE_ECHO_RE = /^(?:said|says|asked|answered|replied|guessed|typed)\s*:\s*(?:'[^']*'|"[^"]*"|‘[^’]*’|“[^”]*”)[\s.!?]*$/iu;
|
|
7277
7288
|
function isLowSignalContent(content, ownNames) {
|
|
7278
|
-
const
|
|
7289
|
+
const trimmed = content.trim();
|
|
7290
|
+
const normalized = trimmed.replace(/[.!?]+$/, "").toLowerCase();
|
|
7279
7291
|
if (normalized.length < MIN_CONTENT_LENGTH) return true;
|
|
7292
|
+
if (UTTERANCE_ECHO_RE.test(trimmed)) return true;
|
|
7280
7293
|
if (ownNames.some(
|
|
7281
7294
|
(n) => normalized === n.trim().replace(/[.!?]+$/, "").toLowerCase()
|
|
7282
7295
|
)) {
|
|
@@ -115,9 +115,15 @@ async function callPortalJsonCompletion(req) {
|
|
|
115
115
|
const maxAttempts = Math.max(1, req.maxAttempts ?? 3);
|
|
116
116
|
const startedAt = Date.now();
|
|
117
117
|
const overBudget = () => req.totalTimeoutMs !== void 0 && Date.now() - startedAt >= req.totalTimeoutMs;
|
|
118
|
+
let lastFailure;
|
|
119
|
+
const giveUp = () => {
|
|
120
|
+
req.onFailure?.(lastFailure ?? { reason: "network", attempts: maxAttempts });
|
|
121
|
+
return null;
|
|
122
|
+
};
|
|
118
123
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
119
124
|
if (attempt > 1 && overBudget()) {
|
|
120
125
|
log.warn(`[${req.tag}] over time budget before attempt ${attempt}, giving up`);
|
|
126
|
+
lastFailure = { reason: "time-budget-exhausted", attempts: attempt - 1 };
|
|
121
127
|
break;
|
|
122
128
|
}
|
|
123
129
|
const attemptReq = req.totalTimeoutMs !== void 0 ? {
|
|
@@ -129,9 +135,14 @@ async function callPortalJsonCompletion(req) {
|
|
|
129
135
|
} : req;
|
|
130
136
|
const outcome = await attemptPortalJson(attemptReq, endpoint);
|
|
131
137
|
if (outcome.kind === "ok") return outcome.value;
|
|
138
|
+
lastFailure = {
|
|
139
|
+
reason: outcome.code,
|
|
140
|
+
...outcome.httpStatus !== void 0 && { httpStatus: outcome.httpStatus },
|
|
141
|
+
attempts: attempt
|
|
142
|
+
};
|
|
132
143
|
if (outcome.kind === "terminal") {
|
|
133
144
|
log.warn(`[${req.tag}] ${outcome.reason}`);
|
|
134
|
-
return
|
|
145
|
+
return giveUp();
|
|
135
146
|
}
|
|
136
147
|
if (attempt >= maxAttempts) {
|
|
137
148
|
log.warn(`[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, giving up`);
|
|
@@ -143,19 +154,21 @@ async function callPortalJsonCompletion(req) {
|
|
|
143
154
|
log.warn(
|
|
144
155
|
`[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, over time budget, giving up`
|
|
145
156
|
);
|
|
157
|
+
lastFailure = { reason: "time-budget-exhausted", attempts: attempt };
|
|
146
158
|
break;
|
|
147
159
|
}
|
|
148
160
|
log.warn(`[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, retrying`);
|
|
149
161
|
if (delay > 0) await sleep(delay);
|
|
150
162
|
}
|
|
151
|
-
return
|
|
163
|
+
return giveUp();
|
|
152
164
|
}
|
|
153
165
|
async function attemptPortalJson(req, endpoint) {
|
|
154
166
|
const baseUrl = req.baseUrl ?? defaultBaseUrl();
|
|
155
167
|
const fetchImpl = req.fetchFn ?? fetch;
|
|
156
168
|
const timeoutMs = req.timeoutMs ?? 6e4;
|
|
157
169
|
const authHeaders = await resolvePortalAuthHeaders(req, req.tag);
|
|
158
|
-
if (authHeaders === null)
|
|
170
|
+
if (authHeaders === null)
|
|
171
|
+
return { kind: "terminal", code: "auth-unavailable", reason: "auth unavailable (no token)" };
|
|
159
172
|
const isAnthropic = req.model.startsWith("anthropic/");
|
|
160
173
|
const prefill = isAnthropic ? "{" : "";
|
|
161
174
|
const messages = [
|
|
@@ -188,31 +201,55 @@ async function attemptPortalJson(req, endpoint) {
|
|
|
188
201
|
});
|
|
189
202
|
} catch (err) {
|
|
190
203
|
clearTimeout(timer);
|
|
191
|
-
return {
|
|
204
|
+
return {
|
|
205
|
+
kind: "retryable",
|
|
206
|
+
code: "network",
|
|
207
|
+
reason: `fetch failed: ${err.message}`
|
|
208
|
+
};
|
|
192
209
|
}
|
|
193
210
|
if (!response.ok) {
|
|
194
211
|
clearTimeout(timer);
|
|
195
212
|
const reason = `portal returned ${response.status}`;
|
|
196
213
|
if (response.status === 401) {
|
|
197
214
|
const tokenAuth = !req.apiKey && !!req.getToken;
|
|
198
|
-
return tokenAuth ? {
|
|
215
|
+
return tokenAuth ? {
|
|
216
|
+
kind: "retryable",
|
|
217
|
+
code: "http-retryable",
|
|
218
|
+
reason: `${reason} (token may be expired; refreshing)`,
|
|
219
|
+
httpStatus: response.status
|
|
220
|
+
} : { kind: "terminal", code: "http-terminal", reason, httpStatus: response.status };
|
|
199
221
|
}
|
|
200
|
-
if (!isRetryableStatus(response.status))
|
|
222
|
+
if (!isRetryableStatus(response.status))
|
|
223
|
+
return { kind: "terminal", code: "http-terminal", reason, httpStatus: response.status };
|
|
201
224
|
const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
|
|
202
|
-
return
|
|
225
|
+
return {
|
|
226
|
+
kind: "retryable",
|
|
227
|
+
code: "http-retryable",
|
|
228
|
+
reason,
|
|
229
|
+
httpStatus: response.status,
|
|
230
|
+
...retryAfterMs !== null && { retryAfterMs }
|
|
231
|
+
};
|
|
203
232
|
}
|
|
204
233
|
let body;
|
|
205
234
|
try {
|
|
206
235
|
body = await response.json();
|
|
207
236
|
} catch (err) {
|
|
208
237
|
clearTimeout(timer);
|
|
209
|
-
return {
|
|
238
|
+
return {
|
|
239
|
+
kind: "retryable",
|
|
240
|
+
code: "body-parse-failed",
|
|
241
|
+
reason: `response body parse failed: ${err.message}`
|
|
242
|
+
};
|
|
210
243
|
}
|
|
211
244
|
clearTimeout(timer);
|
|
212
245
|
logPortalUsage(body, req.tag);
|
|
213
246
|
const rawContent = extractCompletionContent(body);
|
|
214
247
|
if (!rawContent) {
|
|
215
|
-
return {
|
|
248
|
+
return {
|
|
249
|
+
kind: "retryable",
|
|
250
|
+
code: "empty-content",
|
|
251
|
+
reason: "portal response had no completion content"
|
|
252
|
+
};
|
|
216
253
|
}
|
|
217
254
|
const looksLikeContinuation = prefill && /^\s*"/.test(rawContent);
|
|
218
255
|
const content = looksLikeContinuation ? prefill + rawContent : rawContent;
|
|
@@ -223,11 +260,12 @@ async function attemptPortalJson(req, endpoint) {
|
|
|
223
260
|
} catch (err) {
|
|
224
261
|
return {
|
|
225
262
|
kind: "retryable",
|
|
263
|
+
code: "invalid-json",
|
|
226
264
|
reason: `completion was not valid JSON: ${err.message}`
|
|
227
265
|
};
|
|
228
266
|
}
|
|
229
267
|
if (value === null) {
|
|
230
|
-
return { kind: "retryable", reason: "completion parsed to null" };
|
|
268
|
+
return { kind: "retryable", code: "null-completion", reason: "completion parsed to null" };
|
|
231
269
|
}
|
|
232
270
|
return { kind: "ok", value };
|
|
233
271
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
callPortalJsonCompletion,
|
|
3
3
|
getLogger
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-5GBYOWRY.mjs";
|
|
5
5
|
import {
|
|
6
6
|
BASE_URL,
|
|
7
7
|
createClientConfig
|
|
@@ -7085,7 +7085,7 @@ function createMemoryVaultSearchTool(vaultCtx, embeddingOptions, cache, searchOp
|
|
|
7085
7085
|
subQueries = decomp.subQueries;
|
|
7086
7086
|
}
|
|
7087
7087
|
}
|
|
7088
|
-
const { recall: recall2 } = await import("./recall-
|
|
7088
|
+
const { recall: recall2 } = await import("./recall-546HTUPK.mjs");
|
|
7089
7089
|
let recallDegraded = [];
|
|
7090
7090
|
const result = await recall2(
|
|
7091
7091
|
query,
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
notifyConsolidationFallback,
|
|
3
3
|
resolvePiiRedactor
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-ZZDMEEHO.mjs";
|
|
5
5
|
import {
|
|
6
6
|
callPortalJsonCompletion
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-5GBYOWRY.mjs";
|
|
8
8
|
import "./chunk-GYKJOWEO.mjs";
|
|
9
9
|
|
|
10
10
|
// src/lib/memory/consolidate.ts
|
package/dist/react/index.cjs
CHANGED
|
@@ -6429,9 +6429,15 @@ async function callPortalJsonCompletion(req) {
|
|
|
6429
6429
|
const maxAttempts = Math.max(1, req.maxAttempts ?? 3);
|
|
6430
6430
|
const startedAt = Date.now();
|
|
6431
6431
|
const overBudget = () => req.totalTimeoutMs !== void 0 && Date.now() - startedAt >= req.totalTimeoutMs;
|
|
6432
|
+
let lastFailure;
|
|
6433
|
+
const giveUp = () => {
|
|
6434
|
+
req.onFailure?.(lastFailure ?? { reason: "network", attempts: maxAttempts });
|
|
6435
|
+
return null;
|
|
6436
|
+
};
|
|
6432
6437
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
6433
6438
|
if (attempt > 1 && overBudget()) {
|
|
6434
6439
|
log.warn(`[${req.tag}] over time budget before attempt ${attempt}, giving up`);
|
|
6440
|
+
lastFailure = { reason: "time-budget-exhausted", attempts: attempt - 1 };
|
|
6435
6441
|
break;
|
|
6436
6442
|
}
|
|
6437
6443
|
const attemptReq = req.totalTimeoutMs !== void 0 ? {
|
|
@@ -6443,9 +6449,14 @@ async function callPortalJsonCompletion(req) {
|
|
|
6443
6449
|
} : req;
|
|
6444
6450
|
const outcome = await attemptPortalJson(attemptReq, endpoint);
|
|
6445
6451
|
if (outcome.kind === "ok") return outcome.value;
|
|
6452
|
+
lastFailure = {
|
|
6453
|
+
reason: outcome.code,
|
|
6454
|
+
...outcome.httpStatus !== void 0 && { httpStatus: outcome.httpStatus },
|
|
6455
|
+
attempts: attempt
|
|
6456
|
+
};
|
|
6446
6457
|
if (outcome.kind === "terminal") {
|
|
6447
6458
|
log.warn(`[${req.tag}] ${outcome.reason}`);
|
|
6448
|
-
return
|
|
6459
|
+
return giveUp();
|
|
6449
6460
|
}
|
|
6450
6461
|
if (attempt >= maxAttempts) {
|
|
6451
6462
|
log.warn(`[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, giving up`);
|
|
@@ -6457,19 +6468,21 @@ async function callPortalJsonCompletion(req) {
|
|
|
6457
6468
|
log.warn(
|
|
6458
6469
|
`[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, over time budget, giving up`
|
|
6459
6470
|
);
|
|
6471
|
+
lastFailure = { reason: "time-budget-exhausted", attempts: attempt };
|
|
6460
6472
|
break;
|
|
6461
6473
|
}
|
|
6462
6474
|
log.warn(`[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, retrying`);
|
|
6463
6475
|
if (delay > 0) await sleep3(delay);
|
|
6464
6476
|
}
|
|
6465
|
-
return
|
|
6477
|
+
return giveUp();
|
|
6466
6478
|
}
|
|
6467
6479
|
async function attemptPortalJson(req, endpoint) {
|
|
6468
6480
|
const baseUrl = req.baseUrl ?? defaultBaseUrl();
|
|
6469
6481
|
const fetchImpl = req.fetchFn ?? fetch;
|
|
6470
6482
|
const timeoutMs = req.timeoutMs ?? 6e4;
|
|
6471
6483
|
const authHeaders = await resolvePortalAuthHeaders(req, req.tag);
|
|
6472
|
-
if (authHeaders === null)
|
|
6484
|
+
if (authHeaders === null)
|
|
6485
|
+
return { kind: "terminal", code: "auth-unavailable", reason: "auth unavailable (no token)" };
|
|
6473
6486
|
const isAnthropic = req.model.startsWith("anthropic/");
|
|
6474
6487
|
const prefill = isAnthropic ? "{" : "";
|
|
6475
6488
|
const messages = [
|
|
@@ -6502,31 +6515,55 @@ async function attemptPortalJson(req, endpoint) {
|
|
|
6502
6515
|
});
|
|
6503
6516
|
} catch (err) {
|
|
6504
6517
|
clearTimeout(timer);
|
|
6505
|
-
return {
|
|
6518
|
+
return {
|
|
6519
|
+
kind: "retryable",
|
|
6520
|
+
code: "network",
|
|
6521
|
+
reason: `fetch failed: ${err.message}`
|
|
6522
|
+
};
|
|
6506
6523
|
}
|
|
6507
6524
|
if (!response.ok) {
|
|
6508
6525
|
clearTimeout(timer);
|
|
6509
6526
|
const reason = `portal returned ${response.status}`;
|
|
6510
6527
|
if (response.status === 401) {
|
|
6511
6528
|
const tokenAuth = !req.apiKey && !!req.getToken;
|
|
6512
|
-
return tokenAuth ? {
|
|
6513
|
-
|
|
6514
|
-
|
|
6529
|
+
return tokenAuth ? {
|
|
6530
|
+
kind: "retryable",
|
|
6531
|
+
code: "http-retryable",
|
|
6532
|
+
reason: `${reason} (token may be expired; refreshing)`,
|
|
6533
|
+
httpStatus: response.status
|
|
6534
|
+
} : { kind: "terminal", code: "http-terminal", reason, httpStatus: response.status };
|
|
6535
|
+
}
|
|
6536
|
+
if (!isRetryableStatus(response.status))
|
|
6537
|
+
return { kind: "terminal", code: "http-terminal", reason, httpStatus: response.status };
|
|
6515
6538
|
const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
|
|
6516
|
-
return
|
|
6539
|
+
return {
|
|
6540
|
+
kind: "retryable",
|
|
6541
|
+
code: "http-retryable",
|
|
6542
|
+
reason,
|
|
6543
|
+
httpStatus: response.status,
|
|
6544
|
+
...retryAfterMs !== null && { retryAfterMs }
|
|
6545
|
+
};
|
|
6517
6546
|
}
|
|
6518
6547
|
let body;
|
|
6519
6548
|
try {
|
|
6520
6549
|
body = await response.json();
|
|
6521
6550
|
} catch (err) {
|
|
6522
6551
|
clearTimeout(timer);
|
|
6523
|
-
return {
|
|
6552
|
+
return {
|
|
6553
|
+
kind: "retryable",
|
|
6554
|
+
code: "body-parse-failed",
|
|
6555
|
+
reason: `response body parse failed: ${err.message}`
|
|
6556
|
+
};
|
|
6524
6557
|
}
|
|
6525
6558
|
clearTimeout(timer);
|
|
6526
6559
|
logPortalUsage(body, req.tag);
|
|
6527
6560
|
const rawContent = extractCompletionContent(body);
|
|
6528
6561
|
if (!rawContent) {
|
|
6529
|
-
return {
|
|
6562
|
+
return {
|
|
6563
|
+
kind: "retryable",
|
|
6564
|
+
code: "empty-content",
|
|
6565
|
+
reason: "portal response had no completion content"
|
|
6566
|
+
};
|
|
6530
6567
|
}
|
|
6531
6568
|
const looksLikeContinuation = prefill && /^\s*"/.test(rawContent);
|
|
6532
6569
|
const content = looksLikeContinuation ? prefill + rawContent : rawContent;
|
|
@@ -6537,11 +6574,12 @@ async function attemptPortalJson(req, endpoint) {
|
|
|
6537
6574
|
} catch (err) {
|
|
6538
6575
|
return {
|
|
6539
6576
|
kind: "retryable",
|
|
6577
|
+
code: "invalid-json",
|
|
6540
6578
|
reason: `completion was not valid JSON: ${err.message}`
|
|
6541
6579
|
};
|
|
6542
6580
|
}
|
|
6543
6581
|
if (value === null) {
|
|
6544
|
-
return { kind: "retryable", reason: "completion parsed to null" };
|
|
6582
|
+
return { kind: "retryable", code: "null-completion", reason: "completion parsed to null" };
|
|
6545
6583
|
}
|
|
6546
6584
|
return { kind: "ok", value };
|
|
6547
6585
|
}
|
|
@@ -17854,7 +17892,11 @@ async function extractFacts(messages, options) {
|
|
|
17854
17892
|
}
|
|
17855
17893
|
const transcript = transcriptLines.join("\n");
|
|
17856
17894
|
const today = formatLocalDate(options.now ?? Date.now());
|
|
17895
|
+
let failure;
|
|
17857
17896
|
const parsed = await callPortalJsonCompletion({
|
|
17897
|
+
onFailure: (f) => {
|
|
17898
|
+
failure = f;
|
|
17899
|
+
},
|
|
17858
17900
|
...options.apiKey !== void 0 && { apiKey: options.apiKey },
|
|
17859
17901
|
...options.getToken !== void 0 && { getToken: options.getToken },
|
|
17860
17902
|
...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
|
|
@@ -17877,7 +17919,7 @@ Extract durable user facts.`,
|
|
|
17877
17919
|
...options.backoffMs && { backoffMs: options.backoffMs }
|
|
17878
17920
|
});
|
|
17879
17921
|
if (parsed === null) {
|
|
17880
|
-
options.onExhaustedEmpty?.();
|
|
17922
|
+
options.onExhaustedEmpty?.(failure ?? { reason: "empty-content", attempts: 1 });
|
|
17881
17923
|
return [];
|
|
17882
17924
|
}
|
|
17883
17925
|
const fallbackSourceId = [...messages].reverse().find((m) => m.role === "user")?.id;
|
|
@@ -17921,14 +17963,16 @@ async function extractAndRetain(messages, retainCtx, options) {
|
|
|
17921
17963
|
...resolvedConsolidatePii !== void 0 && { piiRedaction: resolvedConsolidatePii }
|
|
17922
17964
|
} : void 0;
|
|
17923
17965
|
let exhaustedEmpty = false;
|
|
17966
|
+
let exhaustedFailure;
|
|
17924
17967
|
let droppedAfterRedaction = false;
|
|
17925
17968
|
const callerOnExhaustedEmpty = options.extract.onExhaustedEmpty;
|
|
17926
17969
|
const callerOnCandidatesDropped = options.extract.onCandidatesDropped;
|
|
17927
17970
|
const candidates = await extractFacts(messages, {
|
|
17928
17971
|
...options.extract,
|
|
17929
|
-
onExhaustedEmpty: () => {
|
|
17972
|
+
onExhaustedEmpty: (failure) => {
|
|
17930
17973
|
exhaustedEmpty = true;
|
|
17931
|
-
|
|
17974
|
+
exhaustedFailure = failure;
|
|
17975
|
+
callerOnExhaustedEmpty?.(failure);
|
|
17932
17976
|
},
|
|
17933
17977
|
onCandidatesDropped: () => {
|
|
17934
17978
|
droppedAfterRedaction = true;
|
|
@@ -18047,12 +18091,19 @@ async function extractAndRetain(messages, retainCtx, options) {
|
|
|
18047
18091
|
results,
|
|
18048
18092
|
failedCount: failedWrites,
|
|
18049
18093
|
outcome,
|
|
18050
|
-
quarantined: quarantinedInfo
|
|
18094
|
+
quarantined: quarantinedInfo,
|
|
18095
|
+
// Only meaningful alongside `outcome: "empty-after-retry"`. Returned as well
|
|
18096
|
+
// as pushed through the callback so a consumer that only inspects the result
|
|
18097
|
+
// (rather than wiring a hook) can still report WHY.
|
|
18098
|
+
...exhaustedFailure !== void 0 && { failure: exhaustedFailure }
|
|
18051
18099
|
};
|
|
18052
18100
|
}
|
|
18101
|
+
var UTTERANCE_ECHO_RE = /^(?:said|says|asked|answered|replied|guessed|typed)\s*:\s*(?:'[^']*'|"[^"]*"|‘[^’]*’|“[^”]*”)[\s.!?]*$/iu;
|
|
18053
18102
|
function isLowSignalContent(content, ownNames) {
|
|
18054
|
-
const
|
|
18103
|
+
const trimmed = content.trim();
|
|
18104
|
+
const normalized = trimmed.replace(/[.!?]+$/, "").toLowerCase();
|
|
18055
18105
|
if (normalized.length < MIN_CONTENT_LENGTH) return true;
|
|
18106
|
+
if (UTTERANCE_ECHO_RE.test(trimmed)) return true;
|
|
18056
18107
|
if (ownNames.some(
|
|
18057
18108
|
(n) => normalized === n.trim().replace(/[.!?]+$/, "").toLowerCase()
|
|
18058
18109
|
)) {
|