@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.
Files changed (32) hide show
  1. package/dist/client/index.cjs +66 -0
  2. package/dist/client/index.d.mts +472 -1
  3. package/dist/client/index.d.ts +472 -1
  4. package/dist/client/index.mjs +58 -0
  5. package/dist/expo/{chunk-2YHVYDEL.mjs → chunk-37VWRZTL.mjs} +2 -2
  6. package/dist/{react/chunk-B5UPJRCU.mjs → expo/chunk-5GBYOWRY.mjs} +48 -10
  7. package/dist/expo/{chunk-VOMDHMKH.mjs → chunk-ITRFWFNS.mjs} +1 -1
  8. package/dist/{react/consolidate-ZCGS7QUA.mjs → expo/consolidate-H6YD36XI.mjs} +2 -2
  9. package/dist/expo/index.cjs +67 -16
  10. package/dist/expo/index.d.mts +67 -2
  11. package/dist/expo/index.d.ts +67 -2
  12. package/dist/expo/index.mjs +22 -9
  13. package/dist/expo/{recall-M3JVFTZL.mjs → recall-FZ7JC4AX.mjs} +2 -2
  14. package/dist/{expo/chunk-B5UPJRCU.mjs → react/chunk-5GBYOWRY.mjs} +48 -10
  15. package/dist/react/{chunk-S6WPXD5N.mjs → chunk-NC7BZEEF.mjs} +2 -2
  16. package/dist/react/{chunk-2ARMO2NN.mjs → chunk-ZZDMEEHO.mjs} +1 -1
  17. package/dist/{expo/consolidate-TWE6OSSZ.mjs → react/consolidate-FNFIDL37.mjs} +2 -2
  18. package/dist/react/index.cjs +67 -16
  19. package/dist/react/index.d.mts +67 -2
  20. package/dist/react/index.d.ts +67 -2
  21. package/dist/react/index.mjs +22 -9
  22. package/dist/react/{recall-ROEK55FJ.mjs → recall-546HTUPK.mjs} +2 -2
  23. package/dist/server/{chunk-CR5P3YIK.mjs → chunk-5KIUGHQZ.mjs} +1 -1
  24. package/dist/server/{chunk-TD7SMY7C.mjs → chunk-G6IH6QTZ.mjs} +2 -2
  25. package/dist/server/{chunk-VHWLLYKO.mjs → chunk-I2U35Z3O.mjs} +48 -10
  26. package/dist/server/{consolidate-FWYK5KXB.mjs → consolidate-S7QZ7V6T.mjs} +2 -2
  27. package/dist/server/index.cjs +67 -16
  28. package/dist/server/index.d.mts +67 -2
  29. package/dist/server/index.d.ts +67 -2
  30. package/dist/server/index.mjs +22 -9
  31. package/dist/server/{recall-CGDEW2LQ.mjs → recall-BIPVQMG4.mjs} +2 -2
  32. package/package.json +2 -2
@@ -20617,9 +20617,15 @@ async function callPortalJsonCompletion(req) {
20617
20617
  const maxAttempts = Math.max(1, req.maxAttempts ?? 3);
20618
20618
  const startedAt = Date.now();
20619
20619
  const overBudget = () => req.totalTimeoutMs !== void 0 && Date.now() - startedAt >= req.totalTimeoutMs;
20620
+ let lastFailure;
20621
+ const giveUp = () => {
20622
+ req.onFailure?.(lastFailure ?? { reason: "network", attempts: maxAttempts });
20623
+ return null;
20624
+ };
20620
20625
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
20621
20626
  if (attempt > 1 && overBudget()) {
20622
20627
  log.warn(`[${req.tag}] over time budget before attempt ${attempt}, giving up`);
20628
+ lastFailure = { reason: "time-budget-exhausted", attempts: attempt - 1 };
20623
20629
  break;
20624
20630
  }
20625
20631
  const attemptReq = req.totalTimeoutMs !== void 0 ? {
@@ -20631,9 +20637,14 @@ async function callPortalJsonCompletion(req) {
20631
20637
  } : req;
20632
20638
  const outcome = await attemptPortalJson(attemptReq, endpoint);
20633
20639
  if (outcome.kind === "ok") return outcome.value;
20640
+ lastFailure = {
20641
+ reason: outcome.code,
20642
+ ...outcome.httpStatus !== void 0 && { httpStatus: outcome.httpStatus },
20643
+ attempts: attempt
20644
+ };
20634
20645
  if (outcome.kind === "terminal") {
20635
20646
  log.warn(`[${req.tag}] ${outcome.reason}`);
20636
- return null;
20647
+ return giveUp();
20637
20648
  }
20638
20649
  if (attempt >= maxAttempts) {
20639
20650
  log.warn(`[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, giving up`);
@@ -20645,19 +20656,21 @@ async function callPortalJsonCompletion(req) {
20645
20656
  log.warn(
20646
20657
  `[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, over time budget, giving up`
20647
20658
  );
20659
+ lastFailure = { reason: "time-budget-exhausted", attempts: attempt };
20648
20660
  break;
20649
20661
  }
20650
20662
  log.warn(`[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, retrying`);
20651
20663
  if (delay > 0) await sleep(delay);
20652
20664
  }
20653
- return null;
20665
+ return giveUp();
20654
20666
  }
20655
20667
  async function attemptPortalJson(req, endpoint) {
20656
20668
  const baseUrl = req.baseUrl ?? defaultBaseUrl();
20657
20669
  const fetchImpl = req.fetchFn ?? fetch;
20658
20670
  const timeoutMs = req.timeoutMs ?? 6e4;
20659
20671
  const authHeaders = await resolvePortalAuthHeaders(req, req.tag);
20660
- if (authHeaders === null) return { kind: "terminal", reason: "auth unavailable (no token)" };
20672
+ if (authHeaders === null)
20673
+ return { kind: "terminal", code: "auth-unavailable", reason: "auth unavailable (no token)" };
20661
20674
  const isAnthropic = req.model.startsWith("anthropic/");
20662
20675
  const prefill = isAnthropic ? "{" : "";
20663
20676
  const messages = [
@@ -20690,31 +20703,55 @@ async function attemptPortalJson(req, endpoint) {
20690
20703
  });
20691
20704
  } catch (err) {
20692
20705
  clearTimeout(timer);
20693
- return { kind: "retryable", reason: `fetch failed: ${err.message}` };
20706
+ return {
20707
+ kind: "retryable",
20708
+ code: "network",
20709
+ reason: `fetch failed: ${err.message}`
20710
+ };
20694
20711
  }
20695
20712
  if (!response.ok) {
20696
20713
  clearTimeout(timer);
20697
20714
  const reason = `portal returned ${response.status}`;
20698
20715
  if (response.status === 401) {
20699
20716
  const tokenAuth = !req.apiKey && !!req.getToken;
20700
- return tokenAuth ? { kind: "retryable", reason: `${reason} (token may be expired; refreshing)` } : { kind: "terminal", reason };
20701
- }
20702
- if (!isRetryableStatus(response.status)) return { kind: "terminal", reason };
20717
+ return tokenAuth ? {
20718
+ kind: "retryable",
20719
+ code: "http-retryable",
20720
+ reason: `${reason} (token may be expired; refreshing)`,
20721
+ httpStatus: response.status
20722
+ } : { kind: "terminal", code: "http-terminal", reason, httpStatus: response.status };
20723
+ }
20724
+ if (!isRetryableStatus(response.status))
20725
+ return { kind: "terminal", code: "http-terminal", reason, httpStatus: response.status };
20703
20726
  const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
20704
- return retryAfterMs !== null ? { kind: "retryable", reason, retryAfterMs } : { kind: "retryable", reason };
20727
+ return {
20728
+ kind: "retryable",
20729
+ code: "http-retryable",
20730
+ reason,
20731
+ httpStatus: response.status,
20732
+ ...retryAfterMs !== null && { retryAfterMs }
20733
+ };
20705
20734
  }
20706
20735
  let body;
20707
20736
  try {
20708
20737
  body = await response.json();
20709
20738
  } catch (err) {
20710
20739
  clearTimeout(timer);
20711
- return { kind: "retryable", reason: `response body parse failed: ${err.message}` };
20740
+ return {
20741
+ kind: "retryable",
20742
+ code: "body-parse-failed",
20743
+ reason: `response body parse failed: ${err.message}`
20744
+ };
20712
20745
  }
20713
20746
  clearTimeout(timer);
20714
20747
  logPortalUsage(body, req.tag);
20715
20748
  const rawContent = extractCompletionContent(body);
20716
20749
  if (!rawContent) {
20717
- return { kind: "retryable", reason: "portal response had no completion content" };
20750
+ return {
20751
+ kind: "retryable",
20752
+ code: "empty-content",
20753
+ reason: "portal response had no completion content"
20754
+ };
20718
20755
  }
20719
20756
  const looksLikeContinuation = prefill && /^\s*"/.test(rawContent);
20720
20757
  const content = looksLikeContinuation ? prefill + rawContent : rawContent;
@@ -20725,11 +20762,12 @@ async function attemptPortalJson(req, endpoint) {
20725
20762
  } catch (err) {
20726
20763
  return {
20727
20764
  kind: "retryable",
20765
+ code: "invalid-json",
20728
20766
  reason: `completion was not valid JSON: ${err.message}`
20729
20767
  };
20730
20768
  }
20731
20769
  if (value === null) {
20732
- return { kind: "retryable", reason: "completion parsed to null" };
20770
+ return { kind: "retryable", code: "null-completion", reason: "completion parsed to null" };
20733
20771
  }
20734
20772
  return { kind: "ok", value };
20735
20773
  }
@@ -29478,7 +29516,11 @@ async function extractFacts(messages, options) {
29478
29516
  }
29479
29517
  const transcript = transcriptLines.join("\n");
29480
29518
  const today = formatLocalDate(options.now ?? Date.now());
29519
+ let failure;
29481
29520
  const parsed = await callPortalJsonCompletion({
29521
+ onFailure: (f) => {
29522
+ failure = f;
29523
+ },
29482
29524
  ...options.apiKey !== void 0 && { apiKey: options.apiKey },
29483
29525
  ...options.getToken !== void 0 && { getToken: options.getToken },
29484
29526
  ...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
@@ -29501,7 +29543,7 @@ Extract durable user facts.`,
29501
29543
  ...options.backoffMs && { backoffMs: options.backoffMs }
29502
29544
  });
29503
29545
  if (parsed === null) {
29504
- options.onExhaustedEmpty?.();
29546
+ options.onExhaustedEmpty?.(failure ?? { reason: "empty-content", attempts: 1 });
29505
29547
  return [];
29506
29548
  }
29507
29549
  const fallbackSourceId = [...messages].reverse().find((m) => m.role === "user")?.id;
@@ -29545,14 +29587,16 @@ async function extractAndRetain(messages, retainCtx, options) {
29545
29587
  ...resolvedConsolidatePii !== void 0 && { piiRedaction: resolvedConsolidatePii }
29546
29588
  } : void 0;
29547
29589
  let exhaustedEmpty = false;
29590
+ let exhaustedFailure;
29548
29591
  let droppedAfterRedaction = false;
29549
29592
  const callerOnExhaustedEmpty = options.extract.onExhaustedEmpty;
29550
29593
  const callerOnCandidatesDropped = options.extract.onCandidatesDropped;
29551
29594
  const candidates = await extractFacts(messages, {
29552
29595
  ...options.extract,
29553
- onExhaustedEmpty: () => {
29596
+ onExhaustedEmpty: (failure) => {
29554
29597
  exhaustedEmpty = true;
29555
- callerOnExhaustedEmpty?.();
29598
+ exhaustedFailure = failure;
29599
+ callerOnExhaustedEmpty?.(failure);
29556
29600
  },
29557
29601
  onCandidatesDropped: () => {
29558
29602
  droppedAfterRedaction = true;
@@ -29671,12 +29715,19 @@ async function extractAndRetain(messages, retainCtx, options) {
29671
29715
  results,
29672
29716
  failedCount: failedWrites,
29673
29717
  outcome,
29674
- quarantined: quarantinedInfo
29718
+ quarantined: quarantinedInfo,
29719
+ // Only meaningful alongside `outcome: "empty-after-retry"`. Returned as well
29720
+ // as pushed through the callback so a consumer that only inspects the result
29721
+ // (rather than wiring a hook) can still report WHY.
29722
+ ...exhaustedFailure !== void 0 && { failure: exhaustedFailure }
29675
29723
  };
29676
29724
  }
29725
+ var UTTERANCE_ECHO_RE = /^(?:said|says|asked|answered|replied|guessed|typed)\s*:\s*(?:'[^']*'|"[^"]*"|‘[^’]*’|“[^”]*”)[\s.!?]*$/iu;
29677
29726
  function isLowSignalContent(content, ownNames) {
29678
- const normalized = content.trim().replace(/[.!?]+$/, "").toLowerCase();
29727
+ const trimmed = content.trim();
29728
+ const normalized = trimmed.replace(/[.!?]+$/, "").toLowerCase();
29679
29729
  if (normalized.length < MIN_CONTENT_LENGTH) return true;
29730
+ if (UTTERANCE_ECHO_RE.test(trimmed)) return true;
29680
29731
  if (ownNames.some(
29681
29732
  (n) => normalized === n.trim().replace(/[.!?]+$/, "").toLowerCase()
29682
29733
  )) {
@@ -4698,6 +4698,60 @@ interface PortalLlmAuth {
4698
4698
  /** Function to get an auth token (e.g., Privy's getIdentityToken). Token is sent as `Authorization: Bearer`. */
4699
4699
  getToken?: () => Promise<string | null>;
4700
4700
  }
4701
+ /**
4702
+ * Why a portal JSON completion gave up, as a STABLE low-cardinality code.
4703
+ *
4704
+ * The retry loop has always classified its failures precisely, but only as an
4705
+ * interpolated `reason` string for `log.warn` — and prod ships no SDK log
4706
+ * (sdk#883), so in production every one of these collapsed into a single
4707
+ * `empty-after-retry` with no way to tell them apart. That is what made the
4708
+ * 2026-08-11 audit need a Prometheus cross-check to discover that the portal
4709
+ * was returning HTTP 200 with an empty body on ~60% of extraction turns.
4710
+ *
4711
+ * Codes are deliberately an enum, not the `reason` string: the strings embed
4712
+ * status codes and error messages, so they are unbounded and useless as an
4713
+ * analytics property. Keep this list SHORT and stable — it is a telemetry
4714
+ * contract, and a value added here has to mean the same thing in six months.
4715
+ *
4716
+ * @public
4717
+ */
4718
+ type PortalLlmFailureReason =
4719
+ /** No usable credential — `getToken` returned null or threw. Terminal. */
4720
+ "auth-unavailable"
4721
+ /** Non-retryable HTTP status (400/403/404, or 401 on the static-apiKey path). */
4722
+ | "http-terminal"
4723
+ /** Retryable status (408/409/425/429/5xx) that never succeeded. */
4724
+ | "http-retryable"
4725
+ /** Network error or the per-attempt timeout aborted the fetch. */
4726
+ | "network"
4727
+ /** HTTP 200 but the envelope itself wasn't JSON. */
4728
+ | "body-parse-failed"
4729
+ /**
4730
+ * HTTP 200 with NO completion content. The reasoning-class failure mode:
4731
+ * the model spends its budget on unreturned thinking and answers empty.
4732
+ */
4733
+ | "empty-content"
4734
+ /** Content present, but no parseable JSON in it (prose, a clarifying question). */
4735
+ | "invalid-json"
4736
+ /** Content parsed to a literal `null`, which is never a valid response. */
4737
+ | "null-completion"
4738
+ /** `totalTimeoutMs` was spent before the next attempt could run. */
4739
+ | "time-budget-exhausted";
4740
+ /**
4741
+ * A give-up report: the classified {@link PortalLlmFailureReason} plus the
4742
+ * little context worth carrying into telemetry. Both extra fields are bounded
4743
+ * (a status code, a small attempt count), so both are safe as event properties.
4744
+ *
4745
+ * @public
4746
+ */
4747
+ interface PortalLlmFailure {
4748
+ /** Stable code for the last failure observed. */
4749
+ reason: PortalLlmFailureReason;
4750
+ /** HTTP status, when the failure was an HTTP one. */
4751
+ httpStatus?: number;
4752
+ /** How many attempts ran before giving up (1-based, ≥ 1). */
4753
+ attempts: number;
4754
+ }
4701
4755
 
4702
4756
  /**
4703
4757
  * Optional LLM injection classifier — Tier-0 security second layer (PR5).
@@ -5893,8 +5947,14 @@ interface ExtractFactsOptions extends PortalLlmAuth {
5893
5947
  * `{candidates: []}` "nothing durable here". Lets callers distinguish a
5894
5948
  * silently-degrading extractor from quiet turns (the two are otherwise
5895
5949
  * indistinguishable). See {@link extractAndRetain}'s `outcome`.
5950
+ *
5951
+ * Receives the classified {@link PortalLlmFailure}. Knowing THAT extraction
5952
+ * failed was not enough: the 2026-08-11 audit found ~60% of production turns
5953
+ * ending here and had to cross-check Prometheus to learn that the cause was
5954
+ * HTTP-200-with-empty-body rather than the 403 everyone assumed. Forward
5955
+ * `failure.reason` into analytics so the next such question is a query.
5896
5956
  */
5897
- onExhaustedEmpty?: () => void;
5957
+ onExhaustedEmpty?: (failure: PortalLlmFailure) => void;
5898
5958
  /**
5899
5959
  * Called when the extractor DID produce candidates but PII de-anonymization
5900
5960
  * dropped every one of them — the model mangled its placeholders (so they
@@ -6017,6 +6077,11 @@ declare function extractAndRetain(messages: AutoExtractMessage[], retainCtx: Ret
6017
6077
  * "extracted but held for review".
6018
6078
  */
6019
6079
  quarantined: QuarantinedMemoryInfo[];
6080
+ /**
6081
+ * Present only when `outcome` is `empty-after-retry` — the classified cause of
6082
+ * the give-up, so "extraction is failing" can be reported as *why* it failed.
6083
+ */
6084
+ failure?: PortalLlmFailure;
6020
6085
  }>;
6021
6086
 
6022
6087
  /**
@@ -10275,4 +10340,4 @@ declare function sanitizeQuotes(s: string): string;
10275
10340
  declare function renderTemplate(value: string | null | undefined, template: string): string | null;
10276
10341
  declare function buildSystemPrompt(ctx: PromptContext, options?: BuildPromptOptions): BuildPromptResult;
10277
10342
 
10278
- 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, 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 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, 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 };
10343
+ 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 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, 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 };
@@ -4698,6 +4698,60 @@ interface PortalLlmAuth {
4698
4698
  /** Function to get an auth token (e.g., Privy's getIdentityToken). Token is sent as `Authorization: Bearer`. */
4699
4699
  getToken?: () => Promise<string | null>;
4700
4700
  }
4701
+ /**
4702
+ * Why a portal JSON completion gave up, as a STABLE low-cardinality code.
4703
+ *
4704
+ * The retry loop has always classified its failures precisely, but only as an
4705
+ * interpolated `reason` string for `log.warn` — and prod ships no SDK log
4706
+ * (sdk#883), so in production every one of these collapsed into a single
4707
+ * `empty-after-retry` with no way to tell them apart. That is what made the
4708
+ * 2026-08-11 audit need a Prometheus cross-check to discover that the portal
4709
+ * was returning HTTP 200 with an empty body on ~60% of extraction turns.
4710
+ *
4711
+ * Codes are deliberately an enum, not the `reason` string: the strings embed
4712
+ * status codes and error messages, so they are unbounded and useless as an
4713
+ * analytics property. Keep this list SHORT and stable — it is a telemetry
4714
+ * contract, and a value added here has to mean the same thing in six months.
4715
+ *
4716
+ * @public
4717
+ */
4718
+ type PortalLlmFailureReason =
4719
+ /** No usable credential — `getToken` returned null or threw. Terminal. */
4720
+ "auth-unavailable"
4721
+ /** Non-retryable HTTP status (400/403/404, or 401 on the static-apiKey path). */
4722
+ | "http-terminal"
4723
+ /** Retryable status (408/409/425/429/5xx) that never succeeded. */
4724
+ | "http-retryable"
4725
+ /** Network error or the per-attempt timeout aborted the fetch. */
4726
+ | "network"
4727
+ /** HTTP 200 but the envelope itself wasn't JSON. */
4728
+ | "body-parse-failed"
4729
+ /**
4730
+ * HTTP 200 with NO completion content. The reasoning-class failure mode:
4731
+ * the model spends its budget on unreturned thinking and answers empty.
4732
+ */
4733
+ | "empty-content"
4734
+ /** Content present, but no parseable JSON in it (prose, a clarifying question). */
4735
+ | "invalid-json"
4736
+ /** Content parsed to a literal `null`, which is never a valid response. */
4737
+ | "null-completion"
4738
+ /** `totalTimeoutMs` was spent before the next attempt could run. */
4739
+ | "time-budget-exhausted";
4740
+ /**
4741
+ * A give-up report: the classified {@link PortalLlmFailureReason} plus the
4742
+ * little context worth carrying into telemetry. Both extra fields are bounded
4743
+ * (a status code, a small attempt count), so both are safe as event properties.
4744
+ *
4745
+ * @public
4746
+ */
4747
+ interface PortalLlmFailure {
4748
+ /** Stable code for the last failure observed. */
4749
+ reason: PortalLlmFailureReason;
4750
+ /** HTTP status, when the failure was an HTTP one. */
4751
+ httpStatus?: number;
4752
+ /** How many attempts ran before giving up (1-based, ≥ 1). */
4753
+ attempts: number;
4754
+ }
4701
4755
 
4702
4756
  /**
4703
4757
  * Optional LLM injection classifier — Tier-0 security second layer (PR5).
@@ -5893,8 +5947,14 @@ interface ExtractFactsOptions extends PortalLlmAuth {
5893
5947
  * `{candidates: []}` "nothing durable here". Lets callers distinguish a
5894
5948
  * silently-degrading extractor from quiet turns (the two are otherwise
5895
5949
  * indistinguishable). See {@link extractAndRetain}'s `outcome`.
5950
+ *
5951
+ * Receives the classified {@link PortalLlmFailure}. Knowing THAT extraction
5952
+ * failed was not enough: the 2026-08-11 audit found ~60% of production turns
5953
+ * ending here and had to cross-check Prometheus to learn that the cause was
5954
+ * HTTP-200-with-empty-body rather than the 403 everyone assumed. Forward
5955
+ * `failure.reason` into analytics so the next such question is a query.
5896
5956
  */
5897
- onExhaustedEmpty?: () => void;
5957
+ onExhaustedEmpty?: (failure: PortalLlmFailure) => void;
5898
5958
  /**
5899
5959
  * Called when the extractor DID produce candidates but PII de-anonymization
5900
5960
  * dropped every one of them — the model mangled its placeholders (so they
@@ -6017,6 +6077,11 @@ declare function extractAndRetain(messages: AutoExtractMessage[], retainCtx: Ret
6017
6077
  * "extracted but held for review".
6018
6078
  */
6019
6079
  quarantined: QuarantinedMemoryInfo[];
6080
+ /**
6081
+ * Present only when `outcome` is `empty-after-retry` — the classified cause of
6082
+ * the give-up, so "extraction is failing" can be reported as *why* it failed.
6083
+ */
6084
+ failure?: PortalLlmFailure;
6020
6085
  }>;
6021
6086
 
6022
6087
  /**
@@ -10275,4 +10340,4 @@ declare function sanitizeQuotes(s: string): string;
10275
10340
  declare function renderTemplate(value: string | null | undefined, template: string): string | null;
10276
10341
  declare function buildSystemPrompt(ctx: PromptContext, options?: BuildPromptOptions): BuildPromptResult;
10277
10342
 
10278
- 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, 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 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, 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 };
10343
+ 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 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, 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 };
@@ -141,12 +141,12 @@ import {
141
141
  updateVaultMemoryOp,
142
142
  upsertMessageOp,
143
143
  vaultMemoryToStored
144
- } from "./chunk-TD7SMY7C.mjs";
144
+ } from "./chunk-G6IH6QTZ.mjs";
145
145
  import {
146
146
  createStreamingDeAnonymizer,
147
147
  notifyConsolidationFallback,
148
148
  resolvePiiRedactor
149
- } from "./chunk-CR5P3YIK.mjs";
149
+ } from "./chunk-5KIUGHQZ.mjs";
150
150
  import {
151
151
  INTERNAL_FLOW_MARKER,
152
152
  callPortalJsonCompletion,
@@ -156,7 +156,7 @@ import {
156
156
  supportsResponseFormat,
157
157
  validateEndpointOverride,
158
158
  withInternalFlowMarker
159
- } from "./chunk-VHWLLYKO.mjs";
159
+ } from "./chunk-I2U35Z3O.mjs";
160
160
  import {
161
161
  BASE_URL,
162
162
  __commonJS,
@@ -5693,7 +5693,7 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
5693
5693
  content: m.content,
5694
5694
  similarity: m.similarity
5695
5695
  }));
5696
- const { consolidateMemory: doConsolidate } = await import("./consolidate-FWYK5KXB.mjs");
5696
+ const { consolidateMemory: doConsolidate } = await import("./consolidate-S7QZ7V6T.mjs");
5697
5697
  const decision = await doConsolidate(trimmed, candidates, consolidateOptions);
5698
5698
  if (decision.action === "create") return null;
5699
5699
  if (decision.action === "supersede" && decision.content) {
@@ -5910,7 +5910,11 @@ async function extractFacts(messages, options) {
5910
5910
  }
5911
5911
  const transcript = transcriptLines.join("\n");
5912
5912
  const today = formatLocalDate(options.now ?? Date.now());
5913
+ let failure;
5913
5914
  const parsed = await callPortalJsonCompletion({
5915
+ onFailure: (f) => {
5916
+ failure = f;
5917
+ },
5914
5918
  ...options.apiKey !== void 0 && { apiKey: options.apiKey },
5915
5919
  ...options.getToken !== void 0 && { getToken: options.getToken },
5916
5920
  ...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
@@ -5933,7 +5937,7 @@ Extract durable user facts.`,
5933
5937
  ...options.backoffMs && { backoffMs: options.backoffMs }
5934
5938
  });
5935
5939
  if (parsed === null) {
5936
- options.onExhaustedEmpty?.();
5940
+ options.onExhaustedEmpty?.(failure ?? { reason: "empty-content", attempts: 1 });
5937
5941
  return [];
5938
5942
  }
5939
5943
  const fallbackSourceId = [...messages].reverse().find((m) => m.role === "user")?.id;
@@ -5977,14 +5981,16 @@ async function extractAndRetain(messages, retainCtx, options) {
5977
5981
  ...resolvedConsolidatePii !== void 0 && { piiRedaction: resolvedConsolidatePii }
5978
5982
  } : void 0;
5979
5983
  let exhaustedEmpty = false;
5984
+ let exhaustedFailure;
5980
5985
  let droppedAfterRedaction = false;
5981
5986
  const callerOnExhaustedEmpty = options.extract.onExhaustedEmpty;
5982
5987
  const callerOnCandidatesDropped = options.extract.onCandidatesDropped;
5983
5988
  const candidates = await extractFacts(messages, {
5984
5989
  ...options.extract,
5985
- onExhaustedEmpty: () => {
5990
+ onExhaustedEmpty: (failure) => {
5986
5991
  exhaustedEmpty = true;
5987
- callerOnExhaustedEmpty?.();
5992
+ exhaustedFailure = failure;
5993
+ callerOnExhaustedEmpty?.(failure);
5988
5994
  },
5989
5995
  onCandidatesDropped: () => {
5990
5996
  droppedAfterRedaction = true;
@@ -6103,12 +6109,19 @@ async function extractAndRetain(messages, retainCtx, options) {
6103
6109
  results,
6104
6110
  failedCount: failedWrites,
6105
6111
  outcome,
6106
- quarantined: quarantinedInfo
6112
+ quarantined: quarantinedInfo,
6113
+ // Only meaningful alongside `outcome: "empty-after-retry"`. Returned as well
6114
+ // as pushed through the callback so a consumer that only inspects the result
6115
+ // (rather than wiring a hook) can still report WHY.
6116
+ ...exhaustedFailure !== void 0 && { failure: exhaustedFailure }
6107
6117
  };
6108
6118
  }
6119
+ var UTTERANCE_ECHO_RE = /^(?:said|says|asked|answered|replied|guessed|typed)\s*:\s*(?:'[^']*'|"[^"]*"|‘[^’]*’|“[^”]*”)[\s.!?]*$/iu;
6109
6120
  function isLowSignalContent(content, ownNames) {
6110
- const normalized = content.trim().replace(/[.!?]+$/, "").toLowerCase();
6121
+ const trimmed = content.trim();
6122
+ const normalized = trimmed.replace(/[.!?]+$/, "").toLowerCase();
6111
6123
  if (normalized.length < MIN_CONTENT_LENGTH) return true;
6124
+ if (UTTERANCE_ECHO_RE.test(trimmed)) return true;
6112
6125
  if (ownNames.some(
6113
6126
  (n) => normalized === n.trim().replace(/[.!?]+$/, "").toLowerCase()
6114
6127
  )) {
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  recall
3
- } from "./chunk-TD7SMY7C.mjs";
4
- import "./chunk-VHWLLYKO.mjs";
3
+ } from "./chunk-G6IH6QTZ.mjs";
4
+ import "./chunk-I2U35Z3O.mjs";
5
5
  import "./chunk-3RPGXXPZ.mjs";
6
6
  export {
7
7
  recall
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anuma/sdk",
3
- "version": "6.7.1",
3
+ "version": "6.7.3",
4
4
  "description": "",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.mjs",
@@ -160,7 +160,7 @@
160
160
  "homepage": "https://github.com/anuma-ai/sdk#readme",
161
161
  "packageManager": "pnpm@10.23.0",
162
162
  "dependencies": {
163
- "@anuma/portal": "1.0.0-next.20260801075204",
163
+ "@anuma/portal": "1.0.0-next.20260806040449",
164
164
  "@babel/parser": "^7.29.2",
165
165
  "@babel/types": "^7.29.0",
166
166
  "ai": "6.0.202",