@anuma/sdk 7.0.0 → 7.0.1

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.
@@ -1495,6 +1495,7 @@ __export(index_exports, {
1495
1495
  embedAllMessages: () => embedAllMessages,
1496
1496
  embedMessage: () => embedMessage,
1497
1497
  encodeChunkVector: () => encodeChunkVector,
1498
+ encryptToolCallEventsOp: () => encryptToolCallEventsOp,
1498
1499
  ensureDefaultFoldersOp: () => ensureDefaultFoldersOp,
1499
1500
  exchangeNotionCode: () => exchangeNotionCode,
1500
1501
  extractAndLinkEntitiesForMemoriesOp: () => extractAndLinkEntitiesForMemoriesOp,
@@ -2892,6 +2893,11 @@ function isEncrypted(value) {
2892
2893
  const payload = value.slice(prefix.length);
2893
2894
  return payload.length >= 56 && /^[0-9a-f]+$/i.test(payload);
2894
2895
  }
2896
+ function hasEncryptedToolPayload(event) {
2897
+ return [event.arguments, event.output].some(
2898
+ (value) => typeof value === "string" && isEncrypted(value)
2899
+ );
2900
+ }
2895
2901
  function detectEncryptionVersion(value) {
2896
2902
  if (value.startsWith("enc:v3:")) {
2897
2903
  return { version: "v3", encryptedData: value.slice("enc:v3:".length) };
@@ -3029,6 +3035,12 @@ async function encryptMessageFields(message, address, signMessage, embeddedWalle
3029
3035
  const encryptedChunks = msg.chunks ? await encryptJsonField(msg.chunks, address, signMessage, embeddedWalletSigner, true) : void 0;
3030
3036
  const encryptedSources = msg.sources ? await encryptJsonField(msg.sources, address, signMessage, embeddedWalletSigner, true) : void 0;
3031
3037
  const encryptedThoughtProcess = msg.thoughtProcess ? await encryptJsonField(msg.thoughtProcess, address, signMessage, embeddedWalletSigner, true) : void 0;
3038
+ const encryptedToolCallEvents = Array.isArray(msg.toolCallEvents) ? await encryptToolCallEvents(
3039
+ msg.toolCallEvents,
3040
+ address,
3041
+ signMessage,
3042
+ embeddedWalletSigner
3043
+ ) : void 0;
3032
3044
  return {
3033
3045
  ...message,
3034
3046
  ...encryptedContent !== void 0 && { content: encryptedContent },
@@ -3036,13 +3048,31 @@ async function encryptMessageFields(message, address, signMessage, embeddedWalle
3036
3048
  ...encryptedVector !== void 0 && { vector: encryptedVector },
3037
3049
  ...encryptedChunks !== void 0 && { chunks: encryptedChunks },
3038
3050
  ...encryptedSources !== void 0 && { sources: encryptedSources },
3039
- ...encryptedThoughtProcess !== void 0 && { thoughtProcess: encryptedThoughtProcess }
3051
+ ...encryptedThoughtProcess !== void 0 && { thoughtProcess: encryptedThoughtProcess },
3052
+ ...encryptedToolCallEvents !== void 0 && { toolCallEvents: encryptedToolCallEvents }
3040
3053
  };
3041
3054
  } catch (error) {
3042
3055
  getLogger().warn("Failed to encrypt message fields:", error);
3043
3056
  throw error;
3044
3057
  }
3045
3058
  }
3059
+ function mapToolCallPayloads(events, transform) {
3060
+ return Promise.all(
3061
+ events.map(async (event) => {
3062
+ if (!event || typeof event !== "object") return event;
3063
+ const mapped = { ...event };
3064
+ if (typeof event.arguments === "string") mapped.arguments = await transform(event.arguments);
3065
+ if (typeof event.output === "string") mapped.output = await transform(event.output);
3066
+ return mapped;
3067
+ })
3068
+ );
3069
+ }
3070
+ function encryptToolCallEvents(events, address, signMessage, embeddedWalletSigner) {
3071
+ return mapToolCallPayloads(
3072
+ events,
3073
+ (value) => encryptField(value, address, signMessage, embeddedWalletSigner, true)
3074
+ );
3075
+ }
3046
3076
  async function decryptMaybeJsonFieldDetailed(value, address) {
3047
3077
  if (value === void 0) return { value: void 0, status: "plaintext" };
3048
3078
  if (value === null) return { value, status: "plaintext" };
@@ -3128,6 +3158,10 @@ async function assembleDecryptedMessage(message, address) {
3128
3158
  message.thoughtProcess,
3129
3159
  address
3130
3160
  );
3161
+ const toolCallEventsResult = await decryptMaybeJsonFieldDetailed(
3162
+ message.toolCallEvents,
3163
+ address
3164
+ );
3131
3165
  let decryptionStatus;
3132
3166
  let refreshProbe;
3133
3167
  const consider = (status, probe) => {
@@ -3146,6 +3180,14 @@ async function assembleDecryptedMessage(message, address) {
3146
3180
  if (thoughtProcessResult.probe) {
3147
3181
  consider(thoughtProcessResult.status, thoughtProcessResult.probe);
3148
3182
  }
3183
+ if (toolCallEventsResult.probe) {
3184
+ consider(toolCallEventsResult.status, toolCallEventsResult.probe);
3185
+ }
3186
+ const toolCallEvents = Array.isArray(toolCallEventsResult.value) ? await mapToolCallPayloads(toolCallEventsResult.value, async (value) => {
3187
+ const detailed = await decryptFieldDetailed(value, address);
3188
+ consider(detailed.status, isEncrypted(value) ? value : void 0);
3189
+ return detailed.value;
3190
+ }) : void 0;
3149
3191
  const statusForConsumer = decryptionStatus === "ok" || decryptionStatus === "plaintext" || !decryptionStatus ? void 0 : decryptionStatus;
3150
3192
  const result = {
3151
3193
  ...message,
@@ -3154,7 +3196,8 @@ async function assembleDecryptedMessage(message, address) {
3154
3196
  vector: vectorResult.value,
3155
3197
  chunks: chunksResult.value,
3156
3198
  sources: sourcesResult.value,
3157
- thoughtProcess: thoughtProcessResult.value
3199
+ thoughtProcess: thoughtProcessResult.value,
3200
+ toolCallEvents
3158
3201
  };
3159
3202
  if (statusForConsumer) {
3160
3203
  result.decryptionStatus = statusForConsumer;
@@ -3950,7 +3993,7 @@ async function updateMessageChunksOp(ctx, uniqueId, chunks3, embeddingModel) {
3950
3993
  });
3951
3994
  return messageToStored(message, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner);
3952
3995
  }
3953
- var STRIP_CHUNK_TEXT_PAGE_SIZE = 100;
3996
+ var RAW_REPAIR_PAGE_SIZE = 100;
3954
3997
  function chunksWithoutText(raw) {
3955
3998
  if (typeof raw !== "string") return null;
3956
3999
  let parsed;
@@ -3973,8 +4016,8 @@ function chunksWithoutText(raw) {
3973
4016
  async function stripLegacyChunkTextOp(ctx) {
3974
4017
  const candidateIds = await ctx.messagesCollection.query(import_watermelondb2.Q.where("chunks", import_watermelondb2.Q.like(`%${import_watermelondb2.Q.sanitizeLikeString('"text":')}%`))).fetchIds();
3975
4018
  let stripped = 0;
3976
- for (let start = 0; start < candidateIds.length; start += STRIP_CHUNK_TEXT_PAGE_SIZE) {
3977
- const pageIds = candidateIds.slice(start, start + STRIP_CHUNK_TEXT_PAGE_SIZE);
4019
+ for (let start = 0; start < candidateIds.length; start += RAW_REPAIR_PAGE_SIZE) {
4020
+ const pageIds = candidateIds.slice(start, start + RAW_REPAIR_PAGE_SIZE);
3978
4021
  const rows = await ctx.messagesCollection.query(import_watermelondb2.Q.where("id", import_watermelondb2.Q.oneOf(pageIds))).unsafeFetchRaw();
3979
4022
  const changedIds = rows.filter((row) => chunksWithoutText(row.chunks) !== null).map((row) => String(row.id));
3980
4023
  if (changedIds.length === 0) continue;
@@ -3998,6 +4041,88 @@ async function stripLegacyChunkTextOp(ctx) {
3998
4041
  }
3999
4042
  return stripped;
4000
4043
  }
4044
+ async function encryptedToolCallEventsColumn(raw, address, signMessage, embeddedWalletSigner) {
4045
+ if (typeof raw !== "string") return null;
4046
+ let parsed;
4047
+ try {
4048
+ parsed = JSON.parse(raw);
4049
+ } catch {
4050
+ return null;
4051
+ }
4052
+ if (!Array.isArray(parsed)) return null;
4053
+ const column = JSON.stringify(
4054
+ await encryptToolCallEvents(
4055
+ parsed,
4056
+ address,
4057
+ signMessage,
4058
+ embeddedWalletSigner
4059
+ )
4060
+ );
4061
+ return column === JSON.stringify(parsed) ? null : column;
4062
+ }
4063
+ async function encryptToolCallEventsOp(ctx) {
4064
+ const { walletAddress: address, signMessage, embeddedWalletSigner } = ctx;
4065
+ if (!address || !signMessage) return 0;
4066
+ if (!await requestEncryptionKey(address, signMessage, embeddedWalletSigner)) return 0;
4067
+ if (!hasEncryptionKey(address)) return 0;
4068
+ if (!await savedKeyOpensExistingData(ctx, address, signMessage, embeddedWalletSigner)) {
4069
+ return 0;
4070
+ }
4071
+ const candidateIds = await ctx.messagesCollection.query(
4072
+ import_watermelondb2.Q.where("tool_call_events", import_watermelondb2.Q.notEq(null)),
4073
+ import_watermelondb2.Q.where("tool_call_events", import_watermelondb2.Q.notIn(["", "[]"]))
4074
+ ).fetchIds();
4075
+ let encrypted = 0;
4076
+ for (let start = 0; start < candidateIds.length; start += RAW_REPAIR_PAGE_SIZE) {
4077
+ const pageIds = candidateIds.slice(start, start + RAW_REPAIR_PAGE_SIZE);
4078
+ const rows = await ctx.messagesCollection.query(import_watermelondb2.Q.where("id", import_watermelondb2.Q.oneOf(pageIds))).unsafeFetchRaw();
4079
+ const repairs = /* @__PURE__ */ new Map();
4080
+ for (const row of rows) {
4081
+ const column = await encryptedToolCallEventsColumn(
4082
+ row.tool_call_events,
4083
+ address,
4084
+ signMessage,
4085
+ embeddedWalletSigner
4086
+ );
4087
+ if (column !== null) repairs.set(String(row.id), { raw: row.tool_call_events, column });
4088
+ }
4089
+ if (repairs.size === 0) continue;
4090
+ await ctx.database.write(async () => {
4091
+ const messages = (await ctx.messagesCollection.query(import_watermelondb2.Q.where("id", import_watermelondb2.Q.oneOf([...repairs.keys()]))).fetch()).filter(
4092
+ (message) => message._raw.tool_call_events === repairs.get(message.id)?.raw
4093
+ );
4094
+ if (messages.length === 0) return;
4095
+ const conversationIds = [...new Set(messages.map((message) => message.conversationId))];
4096
+ const conversations = await ctx.conversationsCollection.query(import_watermelondb2.Q.where("conversation_id", import_watermelondb2.Q.oneOf(conversationIds))).fetch();
4097
+ await ctx.database.batch(
4098
+ ...messages.map(
4099
+ (message) => message.prepareUpdate((msg) => {
4100
+ msg._setRaw("tool_call_events", repairs.get(message.id).column);
4101
+ })
4102
+ ),
4103
+ ...conversations.map((conversation) => conversation.prepareUpdate(() => {
4104
+ }))
4105
+ );
4106
+ encrypted += messages.length;
4107
+ });
4108
+ }
4109
+ return encrypted;
4110
+ }
4111
+ async function savedKeyOpensExistingData(ctx, address, signMessage, embeddedWalletSigner) {
4112
+ const v3Probe = await findEncryptedContent(ctx, "enc:v3:%");
4113
+ if (v3Probe) {
4114
+ const { status } = await decryptFieldDetailed(v3Probe, address);
4115
+ if (status !== "auth_mismatch" && status !== "key_missing") return true;
4116
+ return refreshEncryptionKeyIfMatches(address, v3Probe, signMessage, embeddedWalletSigner);
4117
+ }
4118
+ const v2Probe = await findEncryptedContent(ctx, "enc:v2:%");
4119
+ if (!v2Probe) return true;
4120
+ return refreshEncryptionKeyIfMatches(address, v2Probe, signMessage, embeddedWalletSigner);
4121
+ }
4122
+ async function findEncryptedContent(ctx, pattern) {
4123
+ const [row] = await ctx.messagesCollection.query(import_watermelondb2.Q.where("content", import_watermelondb2.Q.like(pattern)), import_watermelondb2.Q.take(1)).unsafeFetchRaw();
4124
+ return row ? String(row.content) : null;
4125
+ }
4001
4126
  async function updateMessageErrorOp(ctx, uniqueId, error) {
4002
4127
  let message;
4003
4128
  try {
@@ -5752,7 +5877,8 @@ function extractReservationReceipts(toolCallEvents) {
5752
5877
  for (const event of toolCallEvents ?? []) {
5753
5878
  const action = ACTIONS.find((a) => event.name?.endsWith(a.tool));
5754
5879
  const output = event.output ?? "";
5755
- if (!action || !output || NOT_AN_ATTEMPT.test(output)) continue;
5880
+ if (!action || !output || hasEncryptedToolPayload(event) || NOT_AN_ATTEMPT.test(output))
5881
+ continue;
5756
5882
  const kept = latest.get(action.kind)?.status;
5757
5883
  if (kept === "made") continue;
5758
5884
  const receipt = toReceipt(action, event.arguments ?? "", output);
@@ -26831,11 +26957,12 @@ function storedToLlmapiMessage(stored2) {
26831
26957
  }
26832
26958
  }
26833
26959
  const messages = [];
26834
- if (stored2.role === "assistant" && stored2.toolCallEvents?.length) {
26960
+ const toolCallEvents = Array.isArray(stored2.toolCallEvents) ? stored2.toolCallEvents.filter((event) => !hasEncryptedToolPayload(event)) : [];
26961
+ if (stored2.role === "assistant" && toolCallEvents.length) {
26835
26962
  messages.push({
26836
26963
  role: stored2.role,
26837
26964
  content: void 0,
26838
- tool_calls: stored2.toolCallEvents.map((event) => ({
26965
+ tool_calls: toolCallEvents.map((event) => ({
26839
26966
  id: event.id,
26840
26967
  type: "function",
26841
26968
  function: {
@@ -26844,7 +26971,7 @@ function storedToLlmapiMessage(stored2) {
26844
26971
  }
26845
26972
  }))
26846
26973
  });
26847
- for (const event of stored2.toolCallEvents) {
26974
+ for (const event of toolCallEvents) {
26848
26975
  if (event.id && event.output !== void 0 && event.output !== null) {
26849
26976
  messages.push({
26850
26977
  role: "tool",
@@ -28848,6 +28975,7 @@ function useChatStorage(options) {
28848
28975
  embedAllMessages,
28849
28976
  embedMessage,
28850
28977
  encodeChunkVector,
28978
+ encryptToolCallEventsOp,
28851
28979
  ensureDefaultFoldersOp,
28852
28980
  exchangeNotionCode,
28853
28981
  extractAndLinkEntitiesForMemoriesOp,
@@ -4203,6 +4203,13 @@ declare function upsertMessageOp(ctx: StorageOperationsContext, opts: CreateMess
4203
4203
  * @returns Number of rows stripped.
4204
4204
  */
4205
4205
  declare function stripLegacyChunkTextOp(ctx: StorageOperationsContext): Promise<number>;
4206
+ /**
4207
+ * Encrypts tool call arguments and results still stored in plaintext and
4208
+ * returns how many rows changed, giving each touched conversation a new
4209
+ * `updatedAt` so backups re-upload it, which moves it to the top of any list
4210
+ * sorted by `updatedAt`.
4211
+ */
4212
+ declare function encryptToolCallEventsOp(ctx: StorageOperationsContext): Promise<number>;
4206
4213
  /**
4207
4214
  * Decrypted, model-native chunk vectors for one message, cached across recall
4208
4215
  * calls so the chunk lane doesn't re-decrypt + re-JSON.parse every message's
@@ -11417,4 +11424,4 @@ interface UseChatStorageResult extends BaseUseChatStorageResult {
11417
11424
  */
11418
11425
  declare function useChatStorage(options: UseChatStorageOptions): UseChatStorageResult;
11419
11426
 
11420
- 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 ConsolidationAction, 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, type DurableAutoExtractorOptions, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type ExtractionFunnel, type ExtractionTimings, type FactType, type FileMetadata, type FileProcessingReason, type FileProcessingStatus, 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 LocalMemoryStoreOptions, type Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, MEMORY_KINDS, MEMORY_LEVELS, type ManualFactType, type MemoriesNeedingTopicExtraction, type MemoryContextItem, type MemoryContextLane, type MemoryContextOptions, type MemoryContextResult, type MemoryCreate, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, MemoryKeyError, type MemoryKeyRing, type MemoryKind, type MemoryLevel, MemoryLevelError, type MemoryListOptions, type MemoryMaintenance, type MemoryMigrationOptions, type MemoryMigrationProgress, type MemoryMigrationResult, type MemoryMigrationSkip, type MemoryQuarantinedEvent, type MemoryRecallOptions, type MemoryRetainOptions, type MemoryStore, type MemorySubscribeOptions, type MemoryToVerify, type MemoryTopic, type MemoryTopicBacklog, type MemoryTopicMaintenance, type MemoryUpdate, 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 NotionMcpCaller, type NotionOAuthEndpoints, type NotionPKCEChallenge, type NotionRefreshTokenParams, type NotionTokenResponse, type NowSource, type ObservationTrend, type ObservationTrendInput, PAST_EVENT_GRACE_MS, PII_PATTERNS, PROFILE_DOC_VERSION, type PhotoIngestResult, type PhotoMediaRef, type PiiCategory, type PiiMatch, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type PromptPreProcessor, type PromptPreProcessorContext, type PublishedPhotoMemory, type QuantizedEmbedding, type QuarantinedMemoryInfo, QueueManager, type QueueStatus, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankableVaultMemory, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallEmptyReason, type RecallOptions, type RecallResult, type RecallTelemetryCallbacks, type RecallToolCallbacks, type RecallToolOptions, type RecallTruncation, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RemoteMemoryCandidateOptions, type RemoteMemoryDecodeFailure, RemoteMemoryError, type RemoteMemoryListOptions, type RemoteMemoryMetadataPage, type RemoteMemoryMetadataRecord, type RemoteMemoryPage, RemoteMemoryPartialCreateError, type RemoteMemoryPersistence, type RemoteMemoryPersistenceOptions, type RemoteMemoryPipeline, type RemoteMemoryPipelineOptions, type RemoteMemoryQueryOptions, type RemoteMemoryQueryPage, type RemoteMemoryReadFilters, type RemoteMemoryRecord, type RemoteMemoryRow, type RemoteMemoryStoreOptions, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ReservationReceipt, 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 StoredTopic, type StoredVaultFolder, VaultFolder as StoredVaultFolderModel, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type StreamSmoothingConfig, type SynthesizeProfileOptions, TOOL_RESULT_ORIGIN, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TOPIC_SALIENCE_WEIGHTS, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionBatchDiagnostics, type TopicExtractionInput, type TopicExtractionRunResult, type TopicSalience, type TopicSkipReason, 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 VaultEmbeddingExpectation, type VaultFolderOperationsContext, type VaultMemoryKind, type VaultMemoryOperationsContext, type VaultMemoryProjection, type VaultMemoryVisibility, type VaultMemoryWriter, type VaultSaveOperation, type VaultSearchResult, type VaultWriteAction, type VaultWriteInput, type VaultWriteOutcome, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, assembleMemoryContext, attachFileContextToLastUserMessage, backfillMemoryTopicsOp, buildAttachedFilesText, buildNotionAuthUrl, capHopsForDensity, chatStorageMigrations, chatStorageSchema, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, clearAllEncryptionKeys, clearAllEncryptionState, clearConversationMemoriesOp, clearEncryptionKey, clearLazyTitleCache, clearModelsCache, clearServerToolsCache, consoleLogger, conversationMemoryToStored, cosineInt8, createAutoExtractor, createChunkVectorCache, createCryptoPricePreProcessor, createDecaySweeper, createDurableAutoExtractor, createLlmDecayClassifier, createLlmNeighborRefiner, createLocalMemoryStore, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionProxyTools, createNotionTools, createPlatformCursorStore, createRecallTool, createRemoteMemoryPersistence, createRemoteMemoryPipeline, createRemoteMemoryStore, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteMessageOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, deriveKeyFromSignatureBytes, deriveMemoryKeyRing, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, extractReservationReceipts, formatFileProcessingNotes, 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, isAttachedFilesText, isDegradedTopicSkip, isEncrypted, isPiiRedactor, isRerankerAvailable, maskScopedEmbeddingCache, memoryCipher, migrateMemoriesToRemote, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, primaryTopic, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reencryptMemoryField, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, shouldRecallMemory, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, stripLegacyChunkTextOp, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, topicWeight, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
11427
+ 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 ConsolidationAction, 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, type DurableAutoExtractorOptions, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type ExtractionFunnel, type ExtractionTimings, type FactType, type FileMetadata, type FileProcessingReason, type FileProcessingStatus, 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 LocalMemoryStoreOptions, type Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, MEMORY_KINDS, MEMORY_LEVELS, type ManualFactType, type MemoriesNeedingTopicExtraction, type MemoryContextItem, type MemoryContextLane, type MemoryContextOptions, type MemoryContextResult, type MemoryCreate, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, MemoryKeyError, type MemoryKeyRing, type MemoryKind, type MemoryLevel, MemoryLevelError, type MemoryListOptions, type MemoryMaintenance, type MemoryMigrationOptions, type MemoryMigrationProgress, type MemoryMigrationResult, type MemoryMigrationSkip, type MemoryQuarantinedEvent, type MemoryRecallOptions, type MemoryRetainOptions, type MemoryStore, type MemorySubscribeOptions, type MemoryToVerify, type MemoryTopic, type MemoryTopicBacklog, type MemoryTopicMaintenance, type MemoryUpdate, 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 NotionMcpCaller, type NotionOAuthEndpoints, type NotionPKCEChallenge, type NotionRefreshTokenParams, type NotionTokenResponse, type NowSource, type ObservationTrend, type ObservationTrendInput, PAST_EVENT_GRACE_MS, PII_PATTERNS, PROFILE_DOC_VERSION, type PhotoIngestResult, type PhotoMediaRef, type PiiCategory, type PiiMatch, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type PromptPreProcessor, type PromptPreProcessorContext, type PublishedPhotoMemory, type QuantizedEmbedding, type QuarantinedMemoryInfo, QueueManager, type QueueStatus, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankableVaultMemory, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallEmptyReason, type RecallOptions, type RecallResult, type RecallTelemetryCallbacks, type RecallToolCallbacks, type RecallToolOptions, type RecallTruncation, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RemoteMemoryCandidateOptions, type RemoteMemoryDecodeFailure, RemoteMemoryError, type RemoteMemoryListOptions, type RemoteMemoryMetadataPage, type RemoteMemoryMetadataRecord, type RemoteMemoryPage, RemoteMemoryPartialCreateError, type RemoteMemoryPersistence, type RemoteMemoryPersistenceOptions, type RemoteMemoryPipeline, type RemoteMemoryPipelineOptions, type RemoteMemoryQueryOptions, type RemoteMemoryQueryPage, type RemoteMemoryReadFilters, type RemoteMemoryRecord, type RemoteMemoryRow, type RemoteMemoryStoreOptions, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ReservationReceipt, 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 StoredTopic, type StoredVaultFolder, VaultFolder as StoredVaultFolderModel, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type StreamSmoothingConfig, type SynthesizeProfileOptions, TOOL_RESULT_ORIGIN, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TOPIC_SALIENCE_WEIGHTS, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionBatchDiagnostics, type TopicExtractionInput, type TopicExtractionRunResult, type TopicSalience, type TopicSkipReason, 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 VaultEmbeddingExpectation, type VaultFolderOperationsContext, type VaultMemoryKind, type VaultMemoryOperationsContext, type VaultMemoryProjection, type VaultMemoryVisibility, type VaultMemoryWriter, type VaultSaveOperation, type VaultSearchResult, type VaultWriteAction, type VaultWriteInput, type VaultWriteOutcome, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, assembleMemoryContext, attachFileContextToLastUserMessage, backfillMemoryTopicsOp, buildAttachedFilesText, buildNotionAuthUrl, capHopsForDensity, chatStorageMigrations, chatStorageSchema, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, clearAllEncryptionKeys, clearAllEncryptionState, clearConversationMemoriesOp, clearEncryptionKey, clearLazyTitleCache, clearModelsCache, clearServerToolsCache, consoleLogger, conversationMemoryToStored, cosineInt8, createAutoExtractor, createChunkVectorCache, createCryptoPricePreProcessor, createDecaySweeper, createDurableAutoExtractor, createLlmDecayClassifier, createLlmNeighborRefiner, createLocalMemoryStore, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionProxyTools, createNotionTools, createPlatformCursorStore, createRecallTool, createRemoteMemoryPersistence, createRemoteMemoryPipeline, createRemoteMemoryStore, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteMessageOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, deriveKeyFromSignatureBytes, deriveMemoryKeyRing, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, encryptToolCallEventsOp, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, extractReservationReceipts, formatFileProcessingNotes, 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, isAttachedFilesText, isDegradedTopicSkip, isEncrypted, isPiiRedactor, isRerankerAvailable, maskScopedEmbeddingCache, memoryCipher, migrateMemoriesToRemote, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, primaryTopic, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reencryptMemoryField, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, shouldRecallMemory, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, stripLegacyChunkTextOp, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, topicWeight, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
@@ -4203,6 +4203,13 @@ declare function upsertMessageOp(ctx: StorageOperationsContext, opts: CreateMess
4203
4203
  * @returns Number of rows stripped.
4204
4204
  */
4205
4205
  declare function stripLegacyChunkTextOp(ctx: StorageOperationsContext): Promise<number>;
4206
+ /**
4207
+ * Encrypts tool call arguments and results still stored in plaintext and
4208
+ * returns how many rows changed, giving each touched conversation a new
4209
+ * `updatedAt` so backups re-upload it, which moves it to the top of any list
4210
+ * sorted by `updatedAt`.
4211
+ */
4212
+ declare function encryptToolCallEventsOp(ctx: StorageOperationsContext): Promise<number>;
4206
4213
  /**
4207
4214
  * Decrypted, model-native chunk vectors for one message, cached across recall
4208
4215
  * calls so the chunk lane doesn't re-decrypt + re-JSON.parse every message's
@@ -11417,4 +11424,4 @@ interface UseChatStorageResult extends BaseUseChatStorageResult {
11417
11424
  */
11418
11425
  declare function useChatStorage(options: UseChatStorageOptions): UseChatStorageResult;
11419
11426
 
11420
- 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 ConsolidationAction, 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, type DurableAutoExtractorOptions, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type ExtractionFunnel, type ExtractionTimings, type FactType, type FileMetadata, type FileProcessingReason, type FileProcessingStatus, 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 LocalMemoryStoreOptions, type Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, MEMORY_KINDS, MEMORY_LEVELS, type ManualFactType, type MemoriesNeedingTopicExtraction, type MemoryContextItem, type MemoryContextLane, type MemoryContextOptions, type MemoryContextResult, type MemoryCreate, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, MemoryKeyError, type MemoryKeyRing, type MemoryKind, type MemoryLevel, MemoryLevelError, type MemoryListOptions, type MemoryMaintenance, type MemoryMigrationOptions, type MemoryMigrationProgress, type MemoryMigrationResult, type MemoryMigrationSkip, type MemoryQuarantinedEvent, type MemoryRecallOptions, type MemoryRetainOptions, type MemoryStore, type MemorySubscribeOptions, type MemoryToVerify, type MemoryTopic, type MemoryTopicBacklog, type MemoryTopicMaintenance, type MemoryUpdate, 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 NotionMcpCaller, type NotionOAuthEndpoints, type NotionPKCEChallenge, type NotionRefreshTokenParams, type NotionTokenResponse, type NowSource, type ObservationTrend, type ObservationTrendInput, PAST_EVENT_GRACE_MS, PII_PATTERNS, PROFILE_DOC_VERSION, type PhotoIngestResult, type PhotoMediaRef, type PiiCategory, type PiiMatch, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type PromptPreProcessor, type PromptPreProcessorContext, type PublishedPhotoMemory, type QuantizedEmbedding, type QuarantinedMemoryInfo, QueueManager, type QueueStatus, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankableVaultMemory, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallEmptyReason, type RecallOptions, type RecallResult, type RecallTelemetryCallbacks, type RecallToolCallbacks, type RecallToolOptions, type RecallTruncation, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RemoteMemoryCandidateOptions, type RemoteMemoryDecodeFailure, RemoteMemoryError, type RemoteMemoryListOptions, type RemoteMemoryMetadataPage, type RemoteMemoryMetadataRecord, type RemoteMemoryPage, RemoteMemoryPartialCreateError, type RemoteMemoryPersistence, type RemoteMemoryPersistenceOptions, type RemoteMemoryPipeline, type RemoteMemoryPipelineOptions, type RemoteMemoryQueryOptions, type RemoteMemoryQueryPage, type RemoteMemoryReadFilters, type RemoteMemoryRecord, type RemoteMemoryRow, type RemoteMemoryStoreOptions, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ReservationReceipt, 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 StoredTopic, type StoredVaultFolder, VaultFolder as StoredVaultFolderModel, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type StreamSmoothingConfig, type SynthesizeProfileOptions, TOOL_RESULT_ORIGIN, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TOPIC_SALIENCE_WEIGHTS, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionBatchDiagnostics, type TopicExtractionInput, type TopicExtractionRunResult, type TopicSalience, type TopicSkipReason, 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 VaultEmbeddingExpectation, type VaultFolderOperationsContext, type VaultMemoryKind, type VaultMemoryOperationsContext, type VaultMemoryProjection, type VaultMemoryVisibility, type VaultMemoryWriter, type VaultSaveOperation, type VaultSearchResult, type VaultWriteAction, type VaultWriteInput, type VaultWriteOutcome, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, assembleMemoryContext, attachFileContextToLastUserMessage, backfillMemoryTopicsOp, buildAttachedFilesText, buildNotionAuthUrl, capHopsForDensity, chatStorageMigrations, chatStorageSchema, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, clearAllEncryptionKeys, clearAllEncryptionState, clearConversationMemoriesOp, clearEncryptionKey, clearLazyTitleCache, clearModelsCache, clearServerToolsCache, consoleLogger, conversationMemoryToStored, cosineInt8, createAutoExtractor, createChunkVectorCache, createCryptoPricePreProcessor, createDecaySweeper, createDurableAutoExtractor, createLlmDecayClassifier, createLlmNeighborRefiner, createLocalMemoryStore, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionProxyTools, createNotionTools, createPlatformCursorStore, createRecallTool, createRemoteMemoryPersistence, createRemoteMemoryPipeline, createRemoteMemoryStore, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteMessageOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, deriveKeyFromSignatureBytes, deriveMemoryKeyRing, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, extractReservationReceipts, formatFileProcessingNotes, 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, isAttachedFilesText, isDegradedTopicSkip, isEncrypted, isPiiRedactor, isRerankerAvailable, maskScopedEmbeddingCache, memoryCipher, migrateMemoriesToRemote, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, primaryTopic, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reencryptMemoryField, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, shouldRecallMemory, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, stripLegacyChunkTextOp, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, topicWeight, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
11427
+ 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 ConsolidationAction, 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, type DurableAutoExtractorOptions, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type ExtractionFunnel, type ExtractionTimings, type FactType, type FileMetadata, type FileProcessingReason, type FileProcessingStatus, 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 LocalMemoryStoreOptions, type Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, MEMORY_KINDS, MEMORY_LEVELS, type ManualFactType, type MemoriesNeedingTopicExtraction, type MemoryContextItem, type MemoryContextLane, type MemoryContextOptions, type MemoryContextResult, type MemoryCreate, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, MemoryKeyError, type MemoryKeyRing, type MemoryKind, type MemoryLevel, MemoryLevelError, type MemoryListOptions, type MemoryMaintenance, type MemoryMigrationOptions, type MemoryMigrationProgress, type MemoryMigrationResult, type MemoryMigrationSkip, type MemoryQuarantinedEvent, type MemoryRecallOptions, type MemoryRetainOptions, type MemoryStore, type MemorySubscribeOptions, type MemoryToVerify, type MemoryTopic, type MemoryTopicBacklog, type MemoryTopicMaintenance, type MemoryUpdate, 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 NotionMcpCaller, type NotionOAuthEndpoints, type NotionPKCEChallenge, type NotionRefreshTokenParams, type NotionTokenResponse, type NowSource, type ObservationTrend, type ObservationTrendInput, PAST_EVENT_GRACE_MS, PII_PATTERNS, PROFILE_DOC_VERSION, type PhotoIngestResult, type PhotoMediaRef, type PiiCategory, type PiiMatch, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type PromptPreProcessor, type PromptPreProcessorContext, type PublishedPhotoMemory, type QuantizedEmbedding, type QuarantinedMemoryInfo, QueueManager, type QueueStatus, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankableVaultMemory, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallEmptyReason, type RecallOptions, type RecallResult, type RecallTelemetryCallbacks, type RecallToolCallbacks, type RecallToolOptions, type RecallTruncation, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RemoteMemoryCandidateOptions, type RemoteMemoryDecodeFailure, RemoteMemoryError, type RemoteMemoryListOptions, type RemoteMemoryMetadataPage, type RemoteMemoryMetadataRecord, type RemoteMemoryPage, RemoteMemoryPartialCreateError, type RemoteMemoryPersistence, type RemoteMemoryPersistenceOptions, type RemoteMemoryPipeline, type RemoteMemoryPipelineOptions, type RemoteMemoryQueryOptions, type RemoteMemoryQueryPage, type RemoteMemoryReadFilters, type RemoteMemoryRecord, type RemoteMemoryRow, type RemoteMemoryStoreOptions, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ReservationReceipt, 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 StoredTopic, type StoredVaultFolder, VaultFolder as StoredVaultFolderModel, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type StreamSmoothingConfig, type SynthesizeProfileOptions, TOOL_RESULT_ORIGIN, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TOPIC_SALIENCE_WEIGHTS, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionBatchDiagnostics, type TopicExtractionInput, type TopicExtractionRunResult, type TopicSalience, type TopicSkipReason, 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 VaultEmbeddingExpectation, type VaultFolderOperationsContext, type VaultMemoryKind, type VaultMemoryOperationsContext, type VaultMemoryProjection, type VaultMemoryVisibility, type VaultMemoryWriter, type VaultSaveOperation, type VaultSearchResult, type VaultWriteAction, type VaultWriteInput, type VaultWriteOutcome, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, assembleMemoryContext, attachFileContextToLastUserMessage, backfillMemoryTopicsOp, buildAttachedFilesText, buildNotionAuthUrl, capHopsForDensity, chatStorageMigrations, chatStorageSchema, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, clearAllEncryptionKeys, clearAllEncryptionState, clearConversationMemoriesOp, clearEncryptionKey, clearLazyTitleCache, clearModelsCache, clearServerToolsCache, consoleLogger, conversationMemoryToStored, cosineInt8, createAutoExtractor, createChunkVectorCache, createCryptoPricePreProcessor, createDecaySweeper, createDurableAutoExtractor, createLlmDecayClassifier, createLlmNeighborRefiner, createLocalMemoryStore, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionProxyTools, createNotionTools, createPlatformCursorStore, createRecallTool, createRemoteMemoryPersistence, createRemoteMemoryPipeline, createRemoteMemoryStore, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteMessageOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, deriveKeyFromSignatureBytes, deriveMemoryKeyRing, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, encryptToolCallEventsOp, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, extractReservationReceipts, formatFileProcessingNotes, 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, isAttachedFilesText, isDegradedTopicSkip, isEncrypted, isPiiRedactor, isRerankerAvailable, maskScopedEmbeddingCache, memoryCipher, migrateMemoriesToRemote, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, primaryTopic, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reencryptMemoryField, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, shouldRecallMemory, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, stripLegacyChunkTextOp, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, topicWeight, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
@@ -1322,6 +1322,11 @@ function isEncrypted(value) {
1322
1322
  const payload = value.slice(prefix.length);
1323
1323
  return payload.length >= 56 && /^[0-9a-f]+$/i.test(payload);
1324
1324
  }
1325
+ function hasEncryptedToolPayload(event) {
1326
+ return [event.arguments, event.output].some(
1327
+ (value) => typeof value === "string" && isEncrypted(value)
1328
+ );
1329
+ }
1325
1330
  function detectEncryptionVersion(value) {
1326
1331
  if (value.startsWith("enc:v3:")) {
1327
1332
  return { version: "v3", encryptedData: value.slice("enc:v3:".length) };
@@ -1457,6 +1462,12 @@ async function encryptMessageFields(message, address, signMessage, embeddedWalle
1457
1462
  const encryptedChunks = msg.chunks ? await encryptJsonField(msg.chunks, address, signMessage, embeddedWalletSigner, true) : void 0;
1458
1463
  const encryptedSources = msg.sources ? await encryptJsonField(msg.sources, address, signMessage, embeddedWalletSigner, true) : void 0;
1459
1464
  const encryptedThoughtProcess = msg.thoughtProcess ? await encryptJsonField(msg.thoughtProcess, address, signMessage, embeddedWalletSigner, true) : void 0;
1465
+ const encryptedToolCallEvents = Array.isArray(msg.toolCallEvents) ? await encryptToolCallEvents(
1466
+ msg.toolCallEvents,
1467
+ address,
1468
+ signMessage,
1469
+ embeddedWalletSigner
1470
+ ) : void 0;
1460
1471
  return {
1461
1472
  ...message,
1462
1473
  ...encryptedContent !== void 0 && { content: encryptedContent },
@@ -1464,13 +1475,31 @@ async function encryptMessageFields(message, address, signMessage, embeddedWalle
1464
1475
  ...encryptedVector !== void 0 && { vector: encryptedVector },
1465
1476
  ...encryptedChunks !== void 0 && { chunks: encryptedChunks },
1466
1477
  ...encryptedSources !== void 0 && { sources: encryptedSources },
1467
- ...encryptedThoughtProcess !== void 0 && { thoughtProcess: encryptedThoughtProcess }
1478
+ ...encryptedThoughtProcess !== void 0 && { thoughtProcess: encryptedThoughtProcess },
1479
+ ...encryptedToolCallEvents !== void 0 && { toolCallEvents: encryptedToolCallEvents }
1468
1480
  };
1469
1481
  } catch (error) {
1470
1482
  getLogger().warn("Failed to encrypt message fields:", error);
1471
1483
  throw error;
1472
1484
  }
1473
1485
  }
1486
+ function mapToolCallPayloads(events, transform) {
1487
+ return Promise.all(
1488
+ events.map(async (event) => {
1489
+ if (!event || typeof event !== "object") return event;
1490
+ const mapped = { ...event };
1491
+ if (typeof event.arguments === "string") mapped.arguments = await transform(event.arguments);
1492
+ if (typeof event.output === "string") mapped.output = await transform(event.output);
1493
+ return mapped;
1494
+ })
1495
+ );
1496
+ }
1497
+ function encryptToolCallEvents(events, address, signMessage, embeddedWalletSigner) {
1498
+ return mapToolCallPayloads(
1499
+ events,
1500
+ (value) => encryptField(value, address, signMessage, embeddedWalletSigner, true)
1501
+ );
1502
+ }
1474
1503
  async function decryptMaybeJsonFieldDetailed(value, address) {
1475
1504
  if (value === void 0) return { value: void 0, status: "plaintext" };
1476
1505
  if (value === null) return { value, status: "plaintext" };
@@ -1556,6 +1585,10 @@ async function assembleDecryptedMessage(message, address) {
1556
1585
  message.thoughtProcess,
1557
1586
  address
1558
1587
  );
1588
+ const toolCallEventsResult = await decryptMaybeJsonFieldDetailed(
1589
+ message.toolCallEvents,
1590
+ address
1591
+ );
1559
1592
  let decryptionStatus;
1560
1593
  let refreshProbe;
1561
1594
  const consider = (status, probe) => {
@@ -1574,6 +1607,14 @@ async function assembleDecryptedMessage(message, address) {
1574
1607
  if (thoughtProcessResult.probe) {
1575
1608
  consider(thoughtProcessResult.status, thoughtProcessResult.probe);
1576
1609
  }
1610
+ if (toolCallEventsResult.probe) {
1611
+ consider(toolCallEventsResult.status, toolCallEventsResult.probe);
1612
+ }
1613
+ const toolCallEvents = Array.isArray(toolCallEventsResult.value) ? await mapToolCallPayloads(toolCallEventsResult.value, async (value) => {
1614
+ const detailed = await decryptFieldDetailed(value, address);
1615
+ consider(detailed.status, isEncrypted(value) ? value : void 0);
1616
+ return detailed.value;
1617
+ }) : void 0;
1577
1618
  const statusForConsumer = decryptionStatus === "ok" || decryptionStatus === "plaintext" || !decryptionStatus ? void 0 : decryptionStatus;
1578
1619
  const result = {
1579
1620
  ...message,
@@ -1582,7 +1623,8 @@ async function assembleDecryptedMessage(message, address) {
1582
1623
  vector: vectorResult.value,
1583
1624
  chunks: chunksResult.value,
1584
1625
  sources: sourcesResult.value,
1585
- thoughtProcess: thoughtProcessResult.value
1626
+ thoughtProcess: thoughtProcessResult.value,
1627
+ toolCallEvents
1586
1628
  };
1587
1629
  if (statusForConsumer) {
1588
1630
  result.decryptionStatus = statusForConsumer;
@@ -2378,7 +2420,7 @@ async function updateMessageChunksOp(ctx, uniqueId, chunks3, embeddingModel) {
2378
2420
  });
2379
2421
  return messageToStored(message, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner);
2380
2422
  }
2381
- var STRIP_CHUNK_TEXT_PAGE_SIZE = 100;
2423
+ var RAW_REPAIR_PAGE_SIZE = 100;
2382
2424
  function chunksWithoutText(raw) {
2383
2425
  if (typeof raw !== "string") return null;
2384
2426
  let parsed;
@@ -2401,8 +2443,8 @@ function chunksWithoutText(raw) {
2401
2443
  async function stripLegacyChunkTextOp(ctx) {
2402
2444
  const candidateIds = await ctx.messagesCollection.query(Q.where("chunks", Q.like(`%${Q.sanitizeLikeString('"text":')}%`))).fetchIds();
2403
2445
  let stripped = 0;
2404
- for (let start = 0; start < candidateIds.length; start += STRIP_CHUNK_TEXT_PAGE_SIZE) {
2405
- const pageIds = candidateIds.slice(start, start + STRIP_CHUNK_TEXT_PAGE_SIZE);
2446
+ for (let start = 0; start < candidateIds.length; start += RAW_REPAIR_PAGE_SIZE) {
2447
+ const pageIds = candidateIds.slice(start, start + RAW_REPAIR_PAGE_SIZE);
2406
2448
  const rows = await ctx.messagesCollection.query(Q.where("id", Q.oneOf(pageIds))).unsafeFetchRaw();
2407
2449
  const changedIds = rows.filter((row) => chunksWithoutText(row.chunks) !== null).map((row) => String(row.id));
2408
2450
  if (changedIds.length === 0) continue;
@@ -2426,6 +2468,88 @@ async function stripLegacyChunkTextOp(ctx) {
2426
2468
  }
2427
2469
  return stripped;
2428
2470
  }
2471
+ async function encryptedToolCallEventsColumn(raw, address, signMessage, embeddedWalletSigner) {
2472
+ if (typeof raw !== "string") return null;
2473
+ let parsed;
2474
+ try {
2475
+ parsed = JSON.parse(raw);
2476
+ } catch {
2477
+ return null;
2478
+ }
2479
+ if (!Array.isArray(parsed)) return null;
2480
+ const column = JSON.stringify(
2481
+ await encryptToolCallEvents(
2482
+ parsed,
2483
+ address,
2484
+ signMessage,
2485
+ embeddedWalletSigner
2486
+ )
2487
+ );
2488
+ return column === JSON.stringify(parsed) ? null : column;
2489
+ }
2490
+ async function encryptToolCallEventsOp(ctx) {
2491
+ const { walletAddress: address, signMessage, embeddedWalletSigner } = ctx;
2492
+ if (!address || !signMessage) return 0;
2493
+ if (!await requestEncryptionKey(address, signMessage, embeddedWalletSigner)) return 0;
2494
+ if (!hasEncryptionKey(address)) return 0;
2495
+ if (!await savedKeyOpensExistingData(ctx, address, signMessage, embeddedWalletSigner)) {
2496
+ return 0;
2497
+ }
2498
+ const candidateIds = await ctx.messagesCollection.query(
2499
+ Q.where("tool_call_events", Q.notEq(null)),
2500
+ Q.where("tool_call_events", Q.notIn(["", "[]"]))
2501
+ ).fetchIds();
2502
+ let encrypted = 0;
2503
+ for (let start = 0; start < candidateIds.length; start += RAW_REPAIR_PAGE_SIZE) {
2504
+ const pageIds = candidateIds.slice(start, start + RAW_REPAIR_PAGE_SIZE);
2505
+ const rows = await ctx.messagesCollection.query(Q.where("id", Q.oneOf(pageIds))).unsafeFetchRaw();
2506
+ const repairs = /* @__PURE__ */ new Map();
2507
+ for (const row of rows) {
2508
+ const column = await encryptedToolCallEventsColumn(
2509
+ row.tool_call_events,
2510
+ address,
2511
+ signMessage,
2512
+ embeddedWalletSigner
2513
+ );
2514
+ if (column !== null) repairs.set(String(row.id), { raw: row.tool_call_events, column });
2515
+ }
2516
+ if (repairs.size === 0) continue;
2517
+ await ctx.database.write(async () => {
2518
+ const messages = (await ctx.messagesCollection.query(Q.where("id", Q.oneOf([...repairs.keys()]))).fetch()).filter(
2519
+ (message) => message._raw.tool_call_events === repairs.get(message.id)?.raw
2520
+ );
2521
+ if (messages.length === 0) return;
2522
+ const conversationIds = [...new Set(messages.map((message) => message.conversationId))];
2523
+ const conversations = await ctx.conversationsCollection.query(Q.where("conversation_id", Q.oneOf(conversationIds))).fetch();
2524
+ await ctx.database.batch(
2525
+ ...messages.map(
2526
+ (message) => message.prepareUpdate((msg) => {
2527
+ msg._setRaw("tool_call_events", repairs.get(message.id).column);
2528
+ })
2529
+ ),
2530
+ ...conversations.map((conversation) => conversation.prepareUpdate(() => {
2531
+ }))
2532
+ );
2533
+ encrypted += messages.length;
2534
+ });
2535
+ }
2536
+ return encrypted;
2537
+ }
2538
+ async function savedKeyOpensExistingData(ctx, address, signMessage, embeddedWalletSigner) {
2539
+ const v3Probe = await findEncryptedContent(ctx, "enc:v3:%");
2540
+ if (v3Probe) {
2541
+ const { status } = await decryptFieldDetailed(v3Probe, address);
2542
+ if (status !== "auth_mismatch" && status !== "key_missing") return true;
2543
+ return refreshEncryptionKeyIfMatches(address, v3Probe, signMessage, embeddedWalletSigner);
2544
+ }
2545
+ const v2Probe = await findEncryptedContent(ctx, "enc:v2:%");
2546
+ if (!v2Probe) return true;
2547
+ return refreshEncryptionKeyIfMatches(address, v2Probe, signMessage, embeddedWalletSigner);
2548
+ }
2549
+ async function findEncryptedContent(ctx, pattern) {
2550
+ const [row] = await ctx.messagesCollection.query(Q.where("content", Q.like(pattern)), Q.take(1)).unsafeFetchRaw();
2551
+ return row ? String(row.content) : null;
2552
+ }
2429
2553
  async function updateMessageErrorOp(ctx, uniqueId, error) {
2430
2554
  let message;
2431
2555
  try {
@@ -4174,7 +4298,8 @@ function extractReservationReceipts(toolCallEvents) {
4174
4298
  for (const event of toolCallEvents ?? []) {
4175
4299
  const action = ACTIONS.find((a) => event.name?.endsWith(a.tool));
4176
4300
  const output = event.output ?? "";
4177
- if (!action || !output || NOT_AN_ATTEMPT.test(output)) continue;
4301
+ if (!action || !output || hasEncryptedToolPayload(event) || NOT_AN_ATTEMPT.test(output))
4302
+ continue;
4178
4303
  const kept = latest.get(action.kind)?.status;
4179
4304
  if (kept === "made") continue;
4180
4305
  const receipt = toReceipt(action, event.arguments ?? "", output);
@@ -25169,11 +25294,12 @@ function storedToLlmapiMessage(stored2) {
25169
25294
  }
25170
25295
  }
25171
25296
  const messages = [];
25172
- if (stored2.role === "assistant" && stored2.toolCallEvents?.length) {
25297
+ const toolCallEvents = Array.isArray(stored2.toolCallEvents) ? stored2.toolCallEvents.filter((event) => !hasEncryptedToolPayload(event)) : [];
25298
+ if (stored2.role === "assistant" && toolCallEvents.length) {
25173
25299
  messages.push({
25174
25300
  role: stored2.role,
25175
25301
  content: void 0,
25176
- tool_calls: stored2.toolCallEvents.map((event) => ({
25302
+ tool_calls: toolCallEvents.map((event) => ({
25177
25303
  id: event.id,
25178
25304
  type: "function",
25179
25305
  function: {
@@ -25182,7 +25308,7 @@ function storedToLlmapiMessage(stored2) {
25182
25308
  }
25183
25309
  }))
25184
25310
  });
25185
- for (const event of stored2.toolCallEvents) {
25311
+ for (const event of toolCallEvents) {
25186
25312
  if (event.id && event.output !== void 0 && event.output !== null) {
25187
25313
  messages.push({
25188
25314
  role: "tool",
@@ -27185,6 +27311,7 @@ export {
27185
27311
  embedAllMessages,
27186
27312
  embedMessage,
27187
27313
  encodeChunkVector,
27314
+ encryptToolCallEventsOp,
27188
27315
  ensureDefaultFoldersOp,
27189
27316
  exchangeNotionCode,
27190
27317
  extractAndLinkEntitiesForMemoriesOp,