@anuma/sdk 6.5.0 → 6.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  callPortalJsonCompletion,
3
3
  getLogger
4
- } from "./chunk-ILAWDQDE.mjs";
4
+ } from "./chunk-B5UPJRCU.mjs";
5
5
  import {
6
6
  BASE_URL,
7
7
  createClientConfig
@@ -2880,6 +2880,29 @@ async function getAllVaultMemoriesOp(ctx, options) {
2880
2880
  (raw) => vaultMemoryRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
2881
2881
  );
2882
2882
  }
2883
+ function vaultMemoryRawToRankable(raw) {
2884
+ return {
2885
+ uniqueId: raw.id,
2886
+ // @text coerces NULL→"" on the Model path; unsafeFetchRaw returns raw NULL, so guard.
2887
+ scope: raw.scope ?? "",
2888
+ folderId: raw.folder_id ?? null,
2889
+ embedding: raw.embedding ?? null,
2890
+ embeddingModel: raw.embedding_model ?? null,
2891
+ createdAt: new Date(raw.created_at),
2892
+ updatedAt: new Date(raw.updated_at)
2893
+ };
2894
+ }
2895
+ async function getVaultRankingProjectionsOp(ctx, options) {
2896
+ const conditions = [
2897
+ ...baseVaultConditions(ctx, options),
2898
+ ...options?.scopes?.length ? [Q3.where("scope", Q3.oneOf(options.scopes))] : [],
2899
+ ...options?.folderId !== void 0 ? [Q3.where("folder_id", options.folderId)] : [],
2900
+ Q3.sortBy(options?.since ? "updated_at" : "created_at", Q3.desc),
2901
+ ...options?.limit !== null && options?.limit !== void 0 && options.limit > 0 ? [Q3.take(options.limit)] : []
2902
+ ];
2903
+ const results = await ctx.vaultMemoryCollection.query(...conditions).unsafeFetchRaw();
2904
+ return results.map(vaultMemoryRawToRankable);
2905
+ }
2883
2906
  function baseVaultSql(ctx, options) {
2884
2907
  const clauses = [
2885
2908
  '"is_deleted" = 0',
@@ -6784,7 +6807,7 @@ function createMemoryVaultSearchTool(vaultCtx, embeddingOptions, cache, searchOp
6784
6807
  subQueries = decomp.subQueries;
6785
6808
  }
6786
6809
  }
6787
- const { recall: recall2 } = await import("./recall-ISSI7RMD.mjs");
6810
+ const { recall: recall2 } = await import("./recall-M3JVFTZL.mjs");
6788
6811
  let recallDegraded = [];
6789
6812
  const result = await recall2(
6790
6813
  query,
@@ -7815,6 +7838,8 @@ export {
7815
7838
  createVaultMemoriesBatchOp,
7816
7839
  getVaultMemoryOp,
7817
7840
  getAllVaultMemoriesOp,
7841
+ getVaultRankingProjectionsOp,
7842
+ getVaultMemoriesByIdsOp,
7818
7843
  getAllVaultMemoryContentsOp,
7819
7844
  updateVaultMemoryOp,
7820
7845
  setMemoryVisibilityOp,
@@ -45,6 +45,14 @@ function validateEndpointOverride(override) {
45
45
  return { valid: true, endpoint: trimmed.startsWith("/") ? trimmed : `/${trimmed}` };
46
46
  }
47
47
 
48
+ // src/lib/internalFlowMarker.ts
49
+ var INTERNAL_FLOW_MARKER = "Anuma internal first-party flow (not user chat).";
50
+ function withInternalFlowMarker(systemPrompt) {
51
+ if (systemPrompt.includes(INTERNAL_FLOW_MARKER)) return systemPrompt;
52
+ return `${INTERNAL_FLOW_MARKER}
53
+ ${systemPrompt}`;
54
+ }
55
+
48
56
  // src/lib/memory/portalLlm.ts
49
57
  function defaultBaseUrl() {
50
58
  return typeof process !== "undefined" && process.env?.ANUMA_PORTAL_BASE_URL || BASE_URL;
@@ -151,7 +159,12 @@ async function attemptPortalJson(req, endpoint) {
151
159
  const isAnthropic = req.model.startsWith("anthropic/");
152
160
  const prefill = isAnthropic ? "{" : "";
153
161
  const messages = [
154
- { role: "system", content: req.systemPrompt },
162
+ // Every caller of this helper is a first-party BACKGROUND op (fact extraction,
163
+ // topic sweep, consolidation, classifiers, graph traversal, query
164
+ // decomposition). Marking here — the one place they all funnel through — is what
165
+ // keeps the portal's detector reading them as genuine rather than markerless.
166
+ // See ../internalFlowMarker.
167
+ { role: "system", content: withInternalFlowMarker(req.systemPrompt) },
155
168
  { role: "user", content: req.userMessage }
156
169
  ];
157
170
  if (prefill) messages.push({ role: "assistant", content: prefill });
@@ -290,6 +303,8 @@ export {
290
303
  setLogger,
291
304
  getLogger,
292
305
  validateEndpointOverride,
306
+ INTERNAL_FLOW_MARKER,
307
+ withInternalFlowMarker,
293
308
  supportsResponseFormat,
294
309
  resolvePortalAuthHeaders,
295
310
  callPortalJsonCompletion,
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getLogger
3
- } from "./chunk-ILAWDQDE.mjs";
3
+ } from "./chunk-B5UPJRCU.mjs";
4
4
 
5
5
  // src/lib/pii/patterns.ts
6
6
  function luhnCheck(digits) {
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  notifyConsolidationFallback,
3
3
  resolvePiiRedactor
4
- } from "./chunk-VMI74IUX.mjs";
4
+ } from "./chunk-VOMDHMKH.mjs";
5
5
  import {
6
6
  callPortalJsonCompletion
7
- } from "./chunk-ILAWDQDE.mjs";
7
+ } from "./chunk-B5UPJRCU.mjs";
8
8
  import "./chunk-GYKJOWEO.mjs";
9
9
 
10
10
  // src/lib/memory/consolidate.ts
@@ -4564,6 +4564,20 @@ var init_endpointOverride = __esm({
4564
4564
  }
4565
4565
  });
4566
4566
 
4567
+ // src/lib/internalFlowMarker.ts
4568
+ function withInternalFlowMarker(systemPrompt) {
4569
+ if (systemPrompt.includes(INTERNAL_FLOW_MARKER)) return systemPrompt;
4570
+ return `${INTERNAL_FLOW_MARKER}
4571
+ ${systemPrompt}`;
4572
+ }
4573
+ var INTERNAL_FLOW_MARKER;
4574
+ var init_internalFlowMarker = __esm({
4575
+ "src/lib/internalFlowMarker.ts"() {
4576
+ "use strict";
4577
+ INTERNAL_FLOW_MARKER = "Anuma internal first-party flow (not user chat).";
4578
+ }
4579
+ });
4580
+
4567
4581
  // src/lib/db/entities/types.ts
4568
4582
  function normalizeEntityName(name) {
4569
4583
  return name.trim().toLowerCase();
@@ -5366,6 +5380,29 @@ async function getAllVaultMemoriesOp(ctx, options) {
5366
5380
  (raw) => vaultMemoryRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
5367
5381
  );
5368
5382
  }
5383
+ function vaultMemoryRawToRankable(raw) {
5384
+ return {
5385
+ uniqueId: raw.id,
5386
+ // @text coerces NULL→"" on the Model path; unsafeFetchRaw returns raw NULL, so guard.
5387
+ scope: raw.scope ?? "",
5388
+ folderId: raw.folder_id ?? null,
5389
+ embedding: raw.embedding ?? null,
5390
+ embeddingModel: raw.embedding_model ?? null,
5391
+ createdAt: new Date(raw.created_at),
5392
+ updatedAt: new Date(raw.updated_at)
5393
+ };
5394
+ }
5395
+ async function getVaultRankingProjectionsOp(ctx, options) {
5396
+ const conditions = [
5397
+ ...baseVaultConditions(ctx, options),
5398
+ ...options?.scopes?.length ? [import_watermelondb9.Q.where("scope", import_watermelondb9.Q.oneOf(options.scopes))] : [],
5399
+ ...options?.folderId !== void 0 ? [import_watermelondb9.Q.where("folder_id", options.folderId)] : [],
5400
+ import_watermelondb9.Q.sortBy(options?.since ? "updated_at" : "created_at", import_watermelondb9.Q.desc),
5401
+ ...options?.limit !== null && options?.limit !== void 0 && options.limit > 0 ? [import_watermelondb9.Q.take(options.limit)] : []
5402
+ ];
5403
+ const results = await ctx.vaultMemoryCollection.query(...conditions).unsafeFetchRaw();
5404
+ return results.map(vaultMemoryRawToRankable);
5405
+ }
5369
5406
  function baseVaultSql(ctx, options) {
5370
5407
  const clauses = [
5371
5408
  '"is_deleted" = 0',
@@ -6158,7 +6195,12 @@ async function attemptPortalJson(req, endpoint) {
6158
6195
  const isAnthropic = req.model.startsWith("anthropic/");
6159
6196
  const prefill = isAnthropic ? "{" : "";
6160
6197
  const messages = [
6161
- { role: "system", content: req.systemPrompt },
6198
+ // Every caller of this helper is a first-party BACKGROUND op (fact extraction,
6199
+ // topic sweep, consolidation, classifiers, graph traversal, query
6200
+ // decomposition). Marking here — the one place they all funnel through — is what
6201
+ // keeps the portal's detector reading them as genuine rather than markerless.
6202
+ // See ../internalFlowMarker.
6203
+ { role: "system", content: withInternalFlowMarker(req.systemPrompt) },
6162
6204
  { role: "user", content: req.userMessage }
6163
6205
  ];
6164
6206
  if (prefill) messages.push({ role: "assistant", content: prefill });
@@ -6296,6 +6338,7 @@ var init_portalLlm = __esm({
6296
6338
  "use strict";
6297
6339
  init_clientConfig();
6298
6340
  init_endpointOverride();
6341
+ init_internalFlowMarker();
6299
6342
  init_logger();
6300
6343
  RESPONSE_FORMAT_OK = /* @__PURE__ */ new Set(["openai", "inclusionai", "deepseek"]);
6301
6344
  RESPONSE_SCHEMA_OK = /* @__PURE__ */ new Set(["openai"]);
@@ -9453,7 +9496,9 @@ __export(index_exports, {
9453
9496
  getServerTools: () => getServerTools,
9454
9497
  getUnfiledVaultMemoriesOp: () => getUnfiledVaultMemoriesOp,
9455
9498
  getVaultFolderMemoryCountOp: () => getVaultFolderMemoryCountOp,
9499
+ getVaultMemoriesByIdsOp: () => getVaultMemoriesByIdsOp,
9456
9500
  getVaultMemoryOp: () => getVaultMemoryOp,
9501
+ getVaultRankingProjectionsOp: () => getVaultRankingProjectionsOp,
9457
9502
  hardDeleteDecayedOp: () => hardDeleteDecayedOp,
9458
9503
  hasEncryptionKey: () => hasEncryptionKey,
9459
9504
  ingestPublishedPhotoMemoriesOp: () => ingestPublishedPhotoMemoriesOp,
@@ -13995,6 +14040,7 @@ async function deleteConversationSummaryOp(ctx, conversationId) {
13995
14040
  }
13996
14041
 
13997
14042
  // src/lib/chat/summarize.ts
14043
+ init_internalFlowMarker();
13998
14044
  init_logger();
13999
14045
  var DEFAULT_SUMMARY_TOKEN_THRESHOLD = 4e3;
14000
14046
  var DEFAULT_SUMMARY_MIN_WINDOW_MESSAGES = 4;
@@ -14187,7 +14233,17 @@ async function callSummarizationLlm(prompt, model, token, baseUrl) {
14187
14233
  body: JSON.stringify({
14188
14234
  model,
14189
14235
  stream: false,
14190
- messages: [{ role: "user", content: prompt }]
14236
+ // The marker rides a system message because this call has no other
14237
+ // provenance: it posts to the MAIN chat endpoint (not /utility/*), carries no
14238
+ // conversationId, and its prompt is neither the app's chat base prompt nor any
14239
+ // registered flow fingerprint — so without this it reads as markerless, i.e.
14240
+ // as a scripted abuser. Progressive summarization runs for every free-tier
14241
+ // long conversation, so at the PORTAL_DETECTION_REJECT_MARKERLESS flip it
14242
+ // would 403 and silently fall back to verbatim history (context bloat + cost).
14243
+ messages: [
14244
+ { role: "system", content: INTERNAL_FLOW_MARKER },
14245
+ { role: "user", content: prompt }
14246
+ ]
14191
14247
  }),
14192
14248
  signal: controller.signal
14193
14249
  });
@@ -17664,6 +17720,7 @@ init_reranker();
17664
17720
 
17665
17721
  // src/lib/memory/synthesizeProfile.ts
17666
17722
  init_operations3();
17723
+ init_internalFlowMarker();
17667
17724
  init_logger();
17668
17725
  init_constants();
17669
17726
  init_embeddings();
@@ -18025,7 +18082,10 @@ async function synthesizeFacet(facet, ctx, options, prior) {
18025
18082
  limit,
18026
18083
  types: ["fact"],
18027
18084
  maxTokens: DEFAULT_FACET_MAX_TOKENS,
18028
- systemPrompt: buildFacetSystemPrompt(facet),
18085
+ // Profile-facet synthesis is a background op, so it marks its own prompt.
18086
+ // reflect() itself must NOT mark — it also serves the user's own questions,
18087
+ // and that traffic is chat, not an internal flow. See ../internalFlowMarker.
18088
+ systemPrompt: withInternalFlowMarker(buildFacetSystemPrompt(facet)),
18029
18089
  responseSchema: facetResponseSchema(facet.key),
18030
18090
  memories
18031
18091
  });
@@ -24373,7 +24433,9 @@ function createNotionTools(getAccessToken, requestNotionAccess) {
24373
24433
  getServerTools,
24374
24434
  getUnfiledVaultMemoriesOp,
24375
24435
  getVaultFolderMemoryCountOp,
24436
+ getVaultMemoriesByIdsOp,
24376
24437
  getVaultMemoryOp,
24438
+ getVaultRankingProjectionsOp,
24377
24439
  hardDeleteDecayedOp,
24378
24440
  hasEncryptionKey,
24379
24441
  ingestPublishedPhotoMemoriesOp,
@@ -6212,6 +6212,29 @@ interface StoredVaultMemory {
6212
6212
  updatedAt: Date;
6213
6213
  isDeleted: boolean;
6214
6214
  }
6215
+ /**
6216
+ * Content-free projection of a vault memory, used to RANK candidates for recall
6217
+ * WITHOUT decrypting the (encrypted) `content` column. Everything here is a
6218
+ * plaintext-at-rest column — `embedding` is stored plaintext (schema v21), and
6219
+ * `folderId`/`updatedAt` drive source-filtering + tie-breaks. There is
6220
+ * deliberately NO `content` field: a ranking pass must never carry ciphertext
6221
+ * masquerading as the plaintext `StoredVaultMemory.content`. Decrypt the top-N
6222
+ * winners on demand via {@link getVaultMemoryOp}.
6223
+ */
6224
+ interface RankableVaultMemory {
6225
+ /** WatermelonDB internal ID — pass to `getVaultMemoryOp` to decrypt on demand. */
6226
+ uniqueId: string;
6227
+ /** Scope for partitioning memories (e.g., "private", "shared"). */
6228
+ scope: string;
6229
+ /** Folder ID for organization, null if unfiled. */
6230
+ folderId: string | null;
6231
+ /** JSON-stringified embedding vector, null if not yet computed. */
6232
+ embedding: string | null;
6233
+ /** Model that produced `embedding`. Null on legacy rows. */
6234
+ embeddingModel: string | null;
6235
+ createdAt: Date;
6236
+ updatedAt: Date;
6237
+ }
6215
6238
  /**
6216
6239
  * A photo a server-extracted memory came from, as
6217
6240
  * GET /api/memories/published returns it in `media[]`.
@@ -6402,6 +6425,45 @@ declare function getAllVaultMemoriesOp(ctx: VaultMemoryOperationsContext, option
6402
6425
  */
6403
6426
  visibility?: VaultMemoryVisibility[];
6404
6427
  }): Promise<StoredVaultMemory[]>;
6428
+ /**
6429
+ * Return content-free {@link RankableVaultMemory} projections for recall
6430
+ * ranking — the "rank first, decrypt last" half of on-demand recall (#5017).
6431
+ *
6432
+ * Mirrors {@link getAllVaultMemoriesOp}'s query EXACTLY (same
6433
+ * `baseVaultConditions` — `is_deleted=false` + `user_id` scoping — plus the
6434
+ * same scope/folder filters and ordering) so the candidate SET is identical to
6435
+ * the whole-vault read; the ONLY difference is that `content` is never
6436
+ * decrypted (and never returned). Callers rank on `embedding`, then decrypt the
6437
+ * top-N winners on demand via {@link getVaultMemoryOp}.
6438
+ *
6439
+ * Because it reuses `baseVaultConditions`, deleted and cross-user rows are
6440
+ * excluded here just as they are from every other read path — a no-decrypt op
6441
+ * that skipped these would leak embeddings for rows the caller can't see.
6442
+ */
6443
+ declare function getVaultRankingProjectionsOp(ctx: VaultMemoryOperationsContext, options?: {
6444
+ scopes?: string[];
6445
+ since?: Date;
6446
+ limit?: number;
6447
+ folderId?: string | null;
6448
+ }): Promise<RankableVaultMemory[]>;
6449
+ /**
6450
+ * Bulk-decrypt a KNOWN set of memories by ID — the "decrypt last" half of
6451
+ * on-demand recall (#5017) for lanes whose size is NOT bounded to the top-N
6452
+ * (e.g. the keyword lane over un-embedded rows). Uses `unsafeFetchRaw` + a
6453
+ * single `id oneOf` query so it does NOT pin a WatermelonDB Model per row into
6454
+ * the never-evicted RecordCache — unlike calling {@link getVaultMemoryOp} N
6455
+ * times, which `.find()`s each row and is only appropriate for the bounded
6456
+ * top-N winners (web Pile-2 tab-memory).
6457
+ *
6458
+ * Reuses `baseVaultConditions`, so deleted / superseded / cross-user rows are
6459
+ * excluded exactly as they are from recall — a caller can pass any id list and
6460
+ * only its own live rows come back.
6461
+ */
6462
+ declare function getVaultMemoriesByIdsOp(ctx: VaultMemoryOperationsContext, ids: string[],
6463
+ /** See {@link getVaultEmbeddingsByIdsOp} — must match what admitted these ids. */
6464
+ options?: {
6465
+ includeArchived?: boolean;
6466
+ }): Promise<StoredVaultMemory[]>;
6405
6467
  declare function getAllVaultMemoryContentsOp(ctx: VaultMemoryOperationsContext, options?: {
6406
6468
  since?: Date;
6407
6469
  }): Promise<string[]>;
@@ -10170,4 +10232,4 @@ declare function refreshNotionAccessToken(params: NotionRefreshTokenParams): Pro
10170
10232
  */
10171
10233
  declare function createNotionTools(getAccessToken: () => string | null, requestNotionAccess: () => Promise<string>): ToolConfig[];
10172
10234
 
10173
- 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 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, getVaultMemoryOp, 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 };
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 };
@@ -6212,6 +6212,29 @@ interface StoredVaultMemory {
6212
6212
  updatedAt: Date;
6213
6213
  isDeleted: boolean;
6214
6214
  }
6215
+ /**
6216
+ * Content-free projection of a vault memory, used to RANK candidates for recall
6217
+ * WITHOUT decrypting the (encrypted) `content` column. Everything here is a
6218
+ * plaintext-at-rest column — `embedding` is stored plaintext (schema v21), and
6219
+ * `folderId`/`updatedAt` drive source-filtering + tie-breaks. There is
6220
+ * deliberately NO `content` field: a ranking pass must never carry ciphertext
6221
+ * masquerading as the plaintext `StoredVaultMemory.content`. Decrypt the top-N
6222
+ * winners on demand via {@link getVaultMemoryOp}.
6223
+ */
6224
+ interface RankableVaultMemory {
6225
+ /** WatermelonDB internal ID — pass to `getVaultMemoryOp` to decrypt on demand. */
6226
+ uniqueId: string;
6227
+ /** Scope for partitioning memories (e.g., "private", "shared"). */
6228
+ scope: string;
6229
+ /** Folder ID for organization, null if unfiled. */
6230
+ folderId: string | null;
6231
+ /** JSON-stringified embedding vector, null if not yet computed. */
6232
+ embedding: string | null;
6233
+ /** Model that produced `embedding`. Null on legacy rows. */
6234
+ embeddingModel: string | null;
6235
+ createdAt: Date;
6236
+ updatedAt: Date;
6237
+ }
6215
6238
  /**
6216
6239
  * A photo a server-extracted memory came from, as
6217
6240
  * GET /api/memories/published returns it in `media[]`.
@@ -6402,6 +6425,45 @@ declare function getAllVaultMemoriesOp(ctx: VaultMemoryOperationsContext, option
6402
6425
  */
6403
6426
  visibility?: VaultMemoryVisibility[];
6404
6427
  }): Promise<StoredVaultMemory[]>;
6428
+ /**
6429
+ * Return content-free {@link RankableVaultMemory} projections for recall
6430
+ * ranking — the "rank first, decrypt last" half of on-demand recall (#5017).
6431
+ *
6432
+ * Mirrors {@link getAllVaultMemoriesOp}'s query EXACTLY (same
6433
+ * `baseVaultConditions` — `is_deleted=false` + `user_id` scoping — plus the
6434
+ * same scope/folder filters and ordering) so the candidate SET is identical to
6435
+ * the whole-vault read; the ONLY difference is that `content` is never
6436
+ * decrypted (and never returned). Callers rank on `embedding`, then decrypt the
6437
+ * top-N winners on demand via {@link getVaultMemoryOp}.
6438
+ *
6439
+ * Because it reuses `baseVaultConditions`, deleted and cross-user rows are
6440
+ * excluded here just as they are from every other read path — a no-decrypt op
6441
+ * that skipped these would leak embeddings for rows the caller can't see.
6442
+ */
6443
+ declare function getVaultRankingProjectionsOp(ctx: VaultMemoryOperationsContext, options?: {
6444
+ scopes?: string[];
6445
+ since?: Date;
6446
+ limit?: number;
6447
+ folderId?: string | null;
6448
+ }): Promise<RankableVaultMemory[]>;
6449
+ /**
6450
+ * Bulk-decrypt a KNOWN set of memories by ID — the "decrypt last" half of
6451
+ * on-demand recall (#5017) for lanes whose size is NOT bounded to the top-N
6452
+ * (e.g. the keyword lane over un-embedded rows). Uses `unsafeFetchRaw` + a
6453
+ * single `id oneOf` query so it does NOT pin a WatermelonDB Model per row into
6454
+ * the never-evicted RecordCache — unlike calling {@link getVaultMemoryOp} N
6455
+ * times, which `.find()`s each row and is only appropriate for the bounded
6456
+ * top-N winners (web Pile-2 tab-memory).
6457
+ *
6458
+ * Reuses `baseVaultConditions`, so deleted / superseded / cross-user rows are
6459
+ * excluded exactly as they are from recall — a caller can pass any id list and
6460
+ * only its own live rows come back.
6461
+ */
6462
+ declare function getVaultMemoriesByIdsOp(ctx: VaultMemoryOperationsContext, ids: string[],
6463
+ /** See {@link getVaultEmbeddingsByIdsOp} — must match what admitted these ids. */
6464
+ options?: {
6465
+ includeArchived?: boolean;
6466
+ }): Promise<StoredVaultMemory[]>;
6405
6467
  declare function getAllVaultMemoryContentsOp(ctx: VaultMemoryOperationsContext, options?: {
6406
6468
  since?: Date;
6407
6469
  }): Promise<string[]>;
@@ -10170,4 +10232,4 @@ declare function refreshNotionAccessToken(params: NotionRefreshTokenParams): Pro
10170
10232
  */
10171
10233
  declare function createNotionTools(getAccessToken: () => string | null, requestNotionAccess: () => Promise<string>): ToolConfig[];
10172
10234
 
10173
- 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 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, getVaultMemoryOp, 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 };
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 };
@@ -87,7 +87,9 @@ import {
87
87
  getToolCallEvents,
88
88
  getToolsChecksum,
89
89
  getUnfiledVaultMemoriesOp,
90
+ getVaultMemoriesByIdsOp,
90
91
  getVaultMemoryOp,
92
+ getVaultRankingProjectionsOp,
91
93
  hardDeleteDecayedOp,
92
94
  hasEncryptionKey,
93
95
  isEncrypted,
@@ -130,7 +132,7 @@ import {
130
132
  upsertMessageOp,
131
133
  useEncryption,
132
134
  vaultMemoryToStored
133
- } from "./chunk-NCP3VGRX.mjs";
135
+ } from "./chunk-2YHVYDEL.mjs";
134
136
  import {
135
137
  PII_PATTERNS,
136
138
  PiiRedactor,
@@ -138,8 +140,9 @@ import {
138
140
  isPiiRedactor,
139
141
  notifyConsolidationFallback,
140
142
  resolvePiiRedactor
141
- } from "./chunk-DT6QNRZL.mjs";
143
+ } from "./chunk-VOMDHMKH.mjs";
142
144
  import {
145
+ INTERNAL_FLOW_MARKER,
143
146
  callPortalJsonCompletion,
144
147
  consoleLogger,
145
148
  extractJsonCandidate,
@@ -148,8 +151,9 @@ import {
148
151
  resolvePortalAuthHeaders,
149
152
  setLogger,
150
153
  supportsResponseFormat,
151
- validateEndpointOverride
152
- } from "./chunk-ILAWDQDE.mjs";
154
+ validateEndpointOverride,
155
+ withInternalFlowMarker
156
+ } from "./chunk-B5UPJRCU.mjs";
153
157
  import {
154
158
  BASE_URL,
155
159
  MCP_R2_DOMAIN,
@@ -4789,7 +4793,17 @@ async function callSummarizationLlm(prompt, model, token, baseUrl) {
4789
4793
  body: JSON.stringify({
4790
4794
  model,
4791
4795
  stream: false,
4792
- messages: [{ role: "user", content: prompt }]
4796
+ // The marker rides a system message because this call has no other
4797
+ // provenance: it posts to the MAIN chat endpoint (not /utility/*), carries no
4798
+ // conversationId, and its prompt is neither the app's chat base prompt nor any
4799
+ // registered flow fingerprint — so without this it reads as markerless, i.e.
4800
+ // as a scripted abuser. Progressive summarization runs for every free-tier
4801
+ // long conversation, so at the PORTAL_DETECTION_REJECT_MARKERLESS flip it
4802
+ // would 403 and silently fall back to verbatim history (context bloat + cost).
4803
+ messages: [
4804
+ { role: "system", content: INTERNAL_FLOW_MARKER },
4805
+ { role: "user", content: prompt }
4806
+ ]
4793
4807
  }),
4794
4808
  signal: controller.signal
4795
4809
  });
@@ -6847,7 +6861,7 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
6847
6861
  content: m.content,
6848
6862
  similarity: m.similarity
6849
6863
  }));
6850
- const { consolidateMemory: doConsolidate } = await import("./consolidate-3MEWQNM3.mjs");
6864
+ const { consolidateMemory: doConsolidate } = await import("./consolidate-TWE6OSSZ.mjs");
6851
6865
  const decision = await doConsolidate(trimmed, candidates, consolidateOptions);
6852
6866
  if (decision.action === "create") return null;
6853
6867
  if (decision.action === "supersede" && decision.content) {
@@ -8549,7 +8563,10 @@ async function synthesizeFacet(facet, ctx, options, prior) {
8549
8563
  limit,
8550
8564
  types: ["fact"],
8551
8565
  maxTokens: DEFAULT_FACET_MAX_TOKENS,
8552
- systemPrompt: buildFacetSystemPrompt(facet),
8566
+ // Profile-facet synthesis is a background op, so it marks its own prompt.
8567
+ // reflect() itself must NOT mark — it also serves the user's own questions,
8568
+ // and that traffic is chat, not an internal flow. See ../internalFlowMarker.
8569
+ systemPrompt: withInternalFlowMarker(buildFacetSystemPrompt(facet)),
8553
8570
  responseSchema: facetResponseSchema(facet.key),
8554
8571
  memories
8555
8572
  });
@@ -14850,7 +14867,9 @@ export {
14850
14867
  getServerTools,
14851
14868
  getUnfiledVaultMemoriesOp,
14852
14869
  getVaultFolderMemoryCountOp,
14870
+ getVaultMemoriesByIdsOp,
14853
14871
  getVaultMemoryOp,
14872
+ getVaultRankingProjectionsOp,
14854
14873
  hardDeleteDecayedOp,
14855
14874
  hasEncryptionKey,
14856
14875
  ingestPublishedPhotoMemoriesOp,
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  recall
3
- } from "./chunk-NCP3VGRX.mjs";
4
- import "./chunk-ILAWDQDE.mjs";
3
+ } from "./chunk-2YHVYDEL.mjs";
4
+ import "./chunk-B5UPJRCU.mjs";
5
5
  import "./chunk-GYKJOWEO.mjs";
6
6
  export {
7
7
  recall
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getLogger
3
- } from "./chunk-ILAWDQDE.mjs";
3
+ } from "./chunk-B5UPJRCU.mjs";
4
4
 
5
5
  // src/lib/pii/patterns.ts
6
6
  function luhnCheck(digits) {
@@ -45,6 +45,14 @@ function validateEndpointOverride(override) {
45
45
  return { valid: true, endpoint: trimmed.startsWith("/") ? trimmed : `/${trimmed}` };
46
46
  }
47
47
 
48
+ // src/lib/internalFlowMarker.ts
49
+ var INTERNAL_FLOW_MARKER = "Anuma internal first-party flow (not user chat).";
50
+ function withInternalFlowMarker(systemPrompt) {
51
+ if (systemPrompt.includes(INTERNAL_FLOW_MARKER)) return systemPrompt;
52
+ return `${INTERNAL_FLOW_MARKER}
53
+ ${systemPrompt}`;
54
+ }
55
+
48
56
  // src/lib/memory/portalLlm.ts
49
57
  function defaultBaseUrl() {
50
58
  return typeof process !== "undefined" && process.env?.ANUMA_PORTAL_BASE_URL || BASE_URL;
@@ -151,7 +159,12 @@ async function attemptPortalJson(req, endpoint) {
151
159
  const isAnthropic = req.model.startsWith("anthropic/");
152
160
  const prefill = isAnthropic ? "{" : "";
153
161
  const messages = [
154
- { role: "system", content: req.systemPrompt },
162
+ // Every caller of this helper is a first-party BACKGROUND op (fact extraction,
163
+ // topic sweep, consolidation, classifiers, graph traversal, query
164
+ // decomposition). Marking here — the one place they all funnel through — is what
165
+ // keeps the portal's detector reading them as genuine rather than markerless.
166
+ // See ../internalFlowMarker.
167
+ { role: "system", content: withInternalFlowMarker(req.systemPrompt) },
155
168
  { role: "user", content: req.userMessage }
156
169
  ];
157
170
  if (prefill) messages.push({ role: "assistant", content: prefill });
@@ -290,6 +303,8 @@ export {
290
303
  setLogger,
291
304
  getLogger,
292
305
  validateEndpointOverride,
306
+ INTERNAL_FLOW_MARKER,
307
+ withInternalFlowMarker,
293
308
  supportsResponseFormat,
294
309
  resolvePortalAuthHeaders,
295
310
  callPortalJsonCompletion,
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  callPortalJsonCompletion,
3
3
  getLogger
4
- } from "./chunk-ILAWDQDE.mjs";
4
+ } from "./chunk-B5UPJRCU.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-DQJINKEY.mjs");
7088
+ const { recall: recall2 } = await import("./recall-ROEK55FJ.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-DT6QNRZL.mjs";
4
+ } from "./chunk-2ARMO2NN.mjs";
5
5
  import {
6
6
  callPortalJsonCompletion
7
- } from "./chunk-ILAWDQDE.mjs";
7
+ } from "./chunk-B5UPJRCU.mjs";
8
8
  import "./chunk-GYKJOWEO.mjs";
9
9
 
10
10
  // src/lib/memory/consolidate.ts
@@ -4781,6 +4781,20 @@ var init_endpointOverride = __esm({
4781
4781
  }
4782
4782
  });
4783
4783
 
4784
+ // src/lib/internalFlowMarker.ts
4785
+ function withInternalFlowMarker(systemPrompt) {
4786
+ if (systemPrompt.includes(INTERNAL_FLOW_MARKER)) return systemPrompt;
4787
+ return `${INTERNAL_FLOW_MARKER}
4788
+ ${systemPrompt}`;
4789
+ }
4790
+ var INTERNAL_FLOW_MARKER;
4791
+ var init_internalFlowMarker = __esm({
4792
+ "src/lib/internalFlowMarker.ts"() {
4793
+ "use strict";
4794
+ INTERNAL_FLOW_MARKER = "Anuma internal first-party flow (not user chat).";
4795
+ }
4796
+ });
4797
+
4784
4798
  // src/lib/db/entities/types.ts
4785
4799
  function normalizeEntityName(name) {
4786
4800
  return name.trim().toLowerCase();
@@ -6459,7 +6473,12 @@ async function attemptPortalJson(req, endpoint) {
6459
6473
  const isAnthropic = req.model.startsWith("anthropic/");
6460
6474
  const prefill = isAnthropic ? "{" : "";
6461
6475
  const messages = [
6462
- { role: "system", content: req.systemPrompt },
6476
+ // Every caller of this helper is a first-party BACKGROUND op (fact extraction,
6477
+ // topic sweep, consolidation, classifiers, graph traversal, query
6478
+ // decomposition). Marking here — the one place they all funnel through — is what
6479
+ // keeps the portal's detector reading them as genuine rather than markerless.
6480
+ // See ../internalFlowMarker.
6481
+ { role: "system", content: withInternalFlowMarker(req.systemPrompt) },
6463
6482
  { role: "user", content: req.userMessage }
6464
6483
  ];
6465
6484
  if (prefill) messages.push({ role: "assistant", content: prefill });
@@ -6597,6 +6616,7 @@ var init_portalLlm = __esm({
6597
6616
  "use strict";
6598
6617
  init_clientConfig();
6599
6618
  init_endpointOverride();
6619
+ init_internalFlowMarker();
6600
6620
  init_logger();
6601
6621
  RESPONSE_FORMAT_OK = /* @__PURE__ */ new Set(["openai", "inclusionai", "deepseek"]);
6602
6622
  RESPONSE_SCHEMA_OK = /* @__PURE__ */ new Set(["openai"]);
@@ -14853,6 +14873,7 @@ async function deleteConversationSummaryOp(ctx, conversationId) {
14853
14873
  }
14854
14874
 
14855
14875
  // src/lib/chat/summarize.ts
14876
+ init_internalFlowMarker();
14856
14877
  init_logger();
14857
14878
  var DEFAULT_SUMMARY_TOKEN_THRESHOLD = 4e3;
14858
14879
  var DEFAULT_SUMMARY_MIN_WINDOW_MESSAGES = 4;
@@ -15045,7 +15066,17 @@ async function callSummarizationLlm(prompt, model, token, baseUrl) {
15045
15066
  body: JSON.stringify({
15046
15067
  model,
15047
15068
  stream: false,
15048
- messages: [{ role: "user", content: prompt }]
15069
+ // The marker rides a system message because this call has no other
15070
+ // provenance: it posts to the MAIN chat endpoint (not /utility/*), carries no
15071
+ // conversationId, and its prompt is neither the app's chat base prompt nor any
15072
+ // registered flow fingerprint — so without this it reads as markerless, i.e.
15073
+ // as a scripted abuser. Progressive summarization runs for every free-tier
15074
+ // long conversation, so at the PORTAL_DETECTION_REJECT_MARKERLESS flip it
15075
+ // would 403 and silently fall back to verbatim history (context bloat + cost).
15076
+ messages: [
15077
+ { role: "system", content: INTERNAL_FLOW_MARKER },
15078
+ { role: "user", content: prompt }
15079
+ ]
15049
15080
  }),
15050
15081
  signal: controller.signal
15051
15082
  });
@@ -18981,6 +19012,7 @@ init_reranker();
18981
19012
 
18982
19013
  // src/lib/memory/synthesizeProfile.ts
18983
19014
  init_operations3();
19015
+ init_internalFlowMarker();
18984
19016
  init_logger();
18985
19017
  init_constants();
18986
19018
  init_embeddings();
@@ -19342,7 +19374,10 @@ async function synthesizeFacet(facet, ctx, options, prior) {
19342
19374
  limit,
19343
19375
  types: ["fact"],
19344
19376
  maxTokens: DEFAULT_FACET_MAX_TOKENS,
19345
- systemPrompt: buildFacetSystemPrompt(facet),
19377
+ // Profile-facet synthesis is a background op, so it marks its own prompt.
19378
+ // reflect() itself must NOT mark — it also serves the user's own questions,
19379
+ // and that traffic is chat, not an internal flow. See ../internalFlowMarker.
19380
+ systemPrompt: withInternalFlowMarker(buildFacetSystemPrompt(facet)),
19346
19381
  responseSchema: facetResponseSchema(facet.key),
19347
19382
  memories
19348
19383
  });
@@ -178,15 +178,16 @@ import {
178
178
  updateVaultMemoryOp,
179
179
  useEncryption,
180
180
  vaultMemoryToStored
181
- } from "./chunk-OB5HFCLB.mjs";
181
+ } from "./chunk-S6WPXD5N.mjs";
182
182
  import {
183
183
  PiiRedactor,
184
184
  createStreamingDeAnonymizer,
185
185
  isPiiRedactor,
186
186
  notifyConsolidationFallback,
187
187
  resolvePiiRedactor
188
- } from "./chunk-VMI74IUX.mjs";
188
+ } from "./chunk-2ARMO2NN.mjs";
189
189
  import {
190
+ INTERNAL_FLOW_MARKER,
190
191
  callPortalJsonCompletion,
191
192
  consoleLogger,
192
193
  extractJsonCandidate,
@@ -195,8 +196,9 @@ import {
195
196
  resolvePortalAuthHeaders,
196
197
  setLogger,
197
198
  supportsResponseFormat,
198
- validateEndpointOverride
199
- } from "./chunk-ILAWDQDE.mjs";
199
+ validateEndpointOverride,
200
+ withInternalFlowMarker
201
+ } from "./chunk-B5UPJRCU.mjs";
200
202
  import {
201
203
  BASE_URL,
202
204
  MCP_R2_DOMAIN,
@@ -5152,7 +5154,17 @@ async function callSummarizationLlm(prompt, model, token, baseUrl) {
5152
5154
  body: JSON.stringify({
5153
5155
  model,
5154
5156
  stream: false,
5155
- messages: [{ role: "user", content: prompt }]
5157
+ // The marker rides a system message because this call has no other
5158
+ // provenance: it posts to the MAIN chat endpoint (not /utility/*), carries no
5159
+ // conversationId, and its prompt is neither the app's chat base prompt nor any
5160
+ // registered flow fingerprint — so without this it reads as markerless, i.e.
5161
+ // as a scripted abuser. Progressive summarization runs for every free-tier
5162
+ // long conversation, so at the PORTAL_DETECTION_REJECT_MARKERLESS flip it
5163
+ // would 403 and silently fall back to verbatim history (context bloat + cost).
5164
+ messages: [
5165
+ { role: "system", content: INTERNAL_FLOW_MARKER },
5166
+ { role: "user", content: prompt }
5167
+ ]
5156
5168
  }),
5157
5169
  signal: controller.signal
5158
5170
  });
@@ -7667,7 +7679,7 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
7667
7679
  content: m.content,
7668
7680
  similarity: m.similarity
7669
7681
  }));
7670
- const { consolidateMemory: doConsolidate } = await import("./consolidate-AMPKH6YJ.mjs");
7682
+ const { consolidateMemory: doConsolidate } = await import("./consolidate-ZCGS7QUA.mjs");
7671
7683
  const decision = await doConsolidate(trimmed, candidates, consolidateOptions);
7672
7684
  if (decision.action === "create") return null;
7673
7685
  if (decision.action === "supersede" && decision.content) {
@@ -9369,7 +9381,10 @@ async function synthesizeFacet(facet, ctx, options, prior) {
9369
9381
  limit,
9370
9382
  types: ["fact"],
9371
9383
  maxTokens: DEFAULT_FACET_MAX_TOKENS,
9372
- systemPrompt: buildFacetSystemPrompt(facet),
9384
+ // Profile-facet synthesis is a background op, so it marks its own prompt.
9385
+ // reflect() itself must NOT mark — it also serves the user's own questions,
9386
+ // and that traffic is chat, not an internal flow. See ../internalFlowMarker.
9387
+ systemPrompt: withInternalFlowMarker(buildFacetSystemPrompt(facet)),
9373
9388
  responseSchema: facetResponseSchema(facet.key),
9374
9389
  memories
9375
9390
  });
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  recall
3
- } from "./chunk-OB5HFCLB.mjs";
4
- import "./chunk-ILAWDQDE.mjs";
3
+ } from "./chunk-S6WPXD5N.mjs";
4
+ import "./chunk-B5UPJRCU.mjs";
5
5
  import "./chunk-GYKJOWEO.mjs";
6
6
  export {
7
7
  recall
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getLogger
3
- } from "./chunk-OBDRKQQI.mjs";
3
+ } from "./chunk-VHWLLYKO.mjs";
4
4
 
5
5
  // src/lib/pii/patterns.ts
6
6
  function luhnCheck(digits) {
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  callPortalJsonCompletion,
3
3
  getLogger
4
- } from "./chunk-OBDRKQQI.mjs";
4
+ } from "./chunk-VHWLLYKO.mjs";
5
5
  import {
6
6
  BASE_URL,
7
7
  __commonJS,
@@ -20845,7 +20845,7 @@ function createMemoryVaultSearchTool(vaultCtx, embeddingOptions, cache, searchOp
20845
20845
  subQueries = decomp.subQueries;
20846
20846
  }
20847
20847
  }
20848
- const { recall: recall2 } = await import("./recall-CZFWWOVF.mjs");
20848
+ const { recall: recall2 } = await import("./recall-CGDEW2LQ.mjs");
20849
20849
  let recallDegraded = [];
20850
20850
  const result = await recall2(
20851
20851
  query,
@@ -32,6 +32,14 @@ function validateEndpointOverride(override) {
32
32
  return { valid: true, endpoint: trimmed.startsWith("/") ? trimmed : `/${trimmed}` };
33
33
  }
34
34
 
35
+ // src/lib/internalFlowMarker.ts
36
+ var INTERNAL_FLOW_MARKER = "Anuma internal first-party flow (not user chat).";
37
+ function withInternalFlowMarker(systemPrompt) {
38
+ if (systemPrompt.includes(INTERNAL_FLOW_MARKER)) return systemPrompt;
39
+ return `${INTERNAL_FLOW_MARKER}
40
+ ${systemPrompt}`;
41
+ }
42
+
35
43
  // src/lib/memory/portalLlm.ts
36
44
  function defaultBaseUrl() {
37
45
  return typeof process !== "undefined" && process.env?.ANUMA_PORTAL_BASE_URL || BASE_URL;
@@ -138,7 +146,12 @@ async function attemptPortalJson(req, endpoint) {
138
146
  const isAnthropic = req.model.startsWith("anthropic/");
139
147
  const prefill = isAnthropic ? "{" : "";
140
148
  const messages = [
141
- { role: "system", content: req.systemPrompt },
149
+ // Every caller of this helper is a first-party BACKGROUND op (fact extraction,
150
+ // topic sweep, consolidation, classifiers, graph traversal, query
151
+ // decomposition). Marking here — the one place they all funnel through — is what
152
+ // keeps the portal's detector reading them as genuine rather than markerless.
153
+ // See ../internalFlowMarker.
154
+ { role: "system", content: withInternalFlowMarker(req.systemPrompt) },
142
155
  { role: "user", content: req.userMessage }
143
156
  ];
144
157
  if (prefill) messages.push({ role: "assistant", content: prefill });
@@ -273,6 +286,8 @@ function extractCompletionContent(body) {
273
286
 
274
287
  export {
275
288
  getLogger,
289
+ INTERNAL_FLOW_MARKER,
290
+ withInternalFlowMarker,
276
291
  validateEndpointOverride,
277
292
  supportsResponseFormat,
278
293
  resolvePortalAuthHeaders,
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  notifyConsolidationFallback,
3
3
  resolvePiiRedactor
4
- } from "./chunk-KF4HV3QE.mjs";
4
+ } from "./chunk-CR5P3YIK.mjs";
5
5
  import {
6
6
  callPortalJsonCompletion
7
- } from "./chunk-OBDRKQQI.mjs";
7
+ } from "./chunk-VHWLLYKO.mjs";
8
8
  import "./chunk-3RPGXXPZ.mjs";
9
9
 
10
10
  // src/lib/memory/consolidate.ts
@@ -17118,6 +17118,20 @@ var init_clientConfig = __esm({
17118
17118
  }
17119
17119
  });
17120
17120
 
17121
+ // src/lib/internalFlowMarker.ts
17122
+ function withInternalFlowMarker(systemPrompt) {
17123
+ if (systemPrompt.includes(INTERNAL_FLOW_MARKER)) return systemPrompt;
17124
+ return `${INTERNAL_FLOW_MARKER}
17125
+ ${systemPrompt}`;
17126
+ }
17127
+ var INTERNAL_FLOW_MARKER;
17128
+ var init_internalFlowMarker = __esm({
17129
+ "src/lib/internalFlowMarker.ts"() {
17130
+ "use strict";
17131
+ INTERNAL_FLOW_MARKER = "Anuma internal first-party flow (not user chat).";
17132
+ }
17133
+ });
17134
+
17121
17135
  // src/lib/db/entities/types.ts
17122
17136
  function normalizeEntityName(name) {
17123
17137
  return name.trim().toLowerCase();
@@ -20647,7 +20661,12 @@ async function attemptPortalJson(req, endpoint) {
20647
20661
  const isAnthropic = req.model.startsWith("anthropic/");
20648
20662
  const prefill = isAnthropic ? "{" : "";
20649
20663
  const messages = [
20650
- { role: "system", content: req.systemPrompt },
20664
+ // Every caller of this helper is a first-party BACKGROUND op (fact extraction,
20665
+ // topic sweep, consolidation, classifiers, graph traversal, query
20666
+ // decomposition). Marking here — the one place they all funnel through — is what
20667
+ // keeps the portal's detector reading them as genuine rather than markerless.
20668
+ // See ../internalFlowMarker.
20669
+ { role: "system", content: withInternalFlowMarker(req.systemPrompt) },
20651
20670
  { role: "user", content: req.userMessage }
20652
20671
  ];
20653
20672
  if (prefill) messages.push({ role: "assistant", content: prefill });
@@ -20785,6 +20804,7 @@ var init_portalLlm = __esm({
20785
20804
  "use strict";
20786
20805
  init_clientConfig();
20787
20806
  init_endpointOverride();
20807
+ init_internalFlowMarker();
20788
20808
  init_logger();
20789
20809
  RESPONSE_FORMAT_OK = /* @__PURE__ */ new Set(["openai", "inclusionai", "deepseek"]);
20790
20810
  RESPONSE_SCHEMA_OK = /* @__PURE__ */ new Set(["openai"]);
@@ -26726,6 +26746,7 @@ init_types2();
26726
26746
 
26727
26747
  // src/lib/chat/summarize.ts
26728
26748
  init_clientConfig();
26749
+ init_internalFlowMarker();
26729
26750
  init_logger();
26730
26751
  var DEFAULT_SUMMARY_TOKEN_THRESHOLD = 4e3;
26731
26752
  var DEFAULT_SUMMARY_MIN_WINDOW_MESSAGES = 4;
@@ -26918,7 +26939,17 @@ async function callSummarizationLlm(prompt, model, token, baseUrl) {
26918
26939
  body: JSON.stringify({
26919
26940
  model,
26920
26941
  stream: false,
26921
- messages: [{ role: "user", content: prompt }]
26942
+ // The marker rides a system message because this call has no other
26943
+ // provenance: it posts to the MAIN chat endpoint (not /utility/*), carries no
26944
+ // conversationId, and its prompt is neither the app's chat base prompt nor any
26945
+ // registered flow fingerprint — so without this it reads as markerless, i.e.
26946
+ // as a scripted abuser. Progressive summarization runs for every free-tier
26947
+ // long conversation, so at the PORTAL_DETECTION_REJECT_MARKERLESS flip it
26948
+ // would 403 and silently fall back to verbatim history (context bloat + cost).
26949
+ messages: [
26950
+ { role: "system", content: INTERNAL_FLOW_MARKER },
26951
+ { role: "user", content: prompt }
26952
+ ]
26922
26953
  }),
26923
26954
  signal: controller.signal
26924
26955
  });
@@ -30605,6 +30636,7 @@ init_reranker();
30605
30636
 
30606
30637
  // src/lib/memory/synthesizeProfile.ts
30607
30638
  init_operations3();
30639
+ init_internalFlowMarker();
30608
30640
  init_logger();
30609
30641
  init_constants();
30610
30642
  init_embeddings();
@@ -30966,7 +30998,10 @@ async function synthesizeFacet(facet, ctx, options, prior) {
30966
30998
  limit,
30967
30999
  types: ["fact"],
30968
31000
  maxTokens: DEFAULT_FACET_MAX_TOKENS,
30969
- systemPrompt: buildFacetSystemPrompt(facet),
31001
+ // Profile-facet synthesis is a background op, so it marks its own prompt.
31002
+ // reflect() itself must NOT mark — it also serves the user's own questions,
31003
+ // and that traffic is chat, not an internal flow. See ../internalFlowMarker.
31004
+ systemPrompt: withInternalFlowMarker(buildFacetSystemPrompt(facet)),
30970
31005
  responseSchema: facetResponseSchema(facet.key),
30971
31006
  memories
30972
31007
  });
@@ -141,20 +141,22 @@ import {
141
141
  updateVaultMemoryOp,
142
142
  upsertMessageOp,
143
143
  vaultMemoryToStored
144
- } from "./chunk-BZEAYCBV.mjs";
144
+ } from "./chunk-TD7SMY7C.mjs";
145
145
  import {
146
146
  createStreamingDeAnonymizer,
147
147
  notifyConsolidationFallback,
148
148
  resolvePiiRedactor
149
- } from "./chunk-KF4HV3QE.mjs";
149
+ } from "./chunk-CR5P3YIK.mjs";
150
150
  import {
151
+ INTERNAL_FLOW_MARKER,
151
152
  callPortalJsonCompletion,
152
153
  extractJsonCandidate,
153
154
  getLogger,
154
155
  resolvePortalAuthHeaders,
155
156
  supportsResponseFormat,
156
- validateEndpointOverride
157
- } from "./chunk-OBDRKQQI.mjs";
157
+ validateEndpointOverride,
158
+ withInternalFlowMarker
159
+ } from "./chunk-VHWLLYKO.mjs";
158
160
  import {
159
161
  BASE_URL,
160
162
  __commonJS,
@@ -3411,7 +3413,17 @@ async function callSummarizationLlm(prompt, model, token, baseUrl) {
3411
3413
  body: JSON.stringify({
3412
3414
  model,
3413
3415
  stream: false,
3414
- messages: [{ role: "user", content: prompt }]
3416
+ // The marker rides a system message because this call has no other
3417
+ // provenance: it posts to the MAIN chat endpoint (not /utility/*), carries no
3418
+ // conversationId, and its prompt is neither the app's chat base prompt nor any
3419
+ // registered flow fingerprint — so without this it reads as markerless, i.e.
3420
+ // as a scripted abuser. Progressive summarization runs for every free-tier
3421
+ // long conversation, so at the PORTAL_DETECTION_REJECT_MARKERLESS flip it
3422
+ // would 403 and silently fall back to verbatim history (context bloat + cost).
3423
+ messages: [
3424
+ { role: "system", content: INTERNAL_FLOW_MARKER },
3425
+ { role: "user", content: prompt }
3426
+ ]
3415
3427
  }),
3416
3428
  signal: controller.signal
3417
3429
  });
@@ -5681,7 +5693,7 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
5681
5693
  content: m.content,
5682
5694
  similarity: m.similarity
5683
5695
  }));
5684
- const { consolidateMemory: doConsolidate } = await import("./consolidate-I6TOH7CB.mjs");
5696
+ const { consolidateMemory: doConsolidate } = await import("./consolidate-FWYK5KXB.mjs");
5685
5697
  const decision = await doConsolidate(trimmed, candidates, consolidateOptions);
5686
5698
  if (decision.action === "create") return null;
5687
5699
  if (decision.action === "supersede" && decision.content) {
@@ -7383,7 +7395,10 @@ async function synthesizeFacet(facet, ctx, options, prior) {
7383
7395
  limit,
7384
7396
  types: ["fact"],
7385
7397
  maxTokens: DEFAULT_FACET_MAX_TOKENS,
7386
- systemPrompt: buildFacetSystemPrompt(facet),
7398
+ // Profile-facet synthesis is a background op, so it marks its own prompt.
7399
+ // reflect() itself must NOT mark — it also serves the user's own questions,
7400
+ // and that traffic is chat, not an internal flow. See ../internalFlowMarker.
7401
+ systemPrompt: withInternalFlowMarker(buildFacetSystemPrompt(facet)),
7387
7402
  responseSchema: facetResponseSchema(facet.key),
7388
7403
  memories
7389
7404
  });
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  recall
3
- } from "./chunk-BZEAYCBV.mjs";
4
- import "./chunk-OBDRKQQI.mjs";
3
+ } from "./chunk-TD7SMY7C.mjs";
4
+ import "./chunk-VHWLLYKO.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.5.0",
3
+ "version": "6.7.0",
4
4
  "description": "",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.mjs",