@anuma/sdk 6.39.0 → 6.39.2

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.
@@ -2002,6 +2002,127 @@ declare function createStreamingDeAnonymizer(redactor: PiiRedactor, emit: (chunk
2002
2002
  flush: () => void;
2003
2003
  };
2004
2004
 
2005
+ type LlmTokenUsage = {
2006
+ inputTokens?: number;
2007
+ outputTokens?: number;
2008
+ };
2009
+ type ModelCallStartEvent = {
2010
+ runId: string;
2011
+ stepIndex: number;
2012
+ model: string;
2013
+ messages: Array<LlmapiMessage>;
2014
+ tools: Array<LlmapiChatCompletionTool>;
2015
+ requestBody: Record<string, unknown>;
2016
+ };
2017
+ type ModelCallEndEvent = {
2018
+ runId: string;
2019
+ stepIndex: number;
2020
+ content: string;
2021
+ toolCalls: Array<{
2022
+ id: string;
2023
+ name: string;
2024
+ arguments: string;
2025
+ }>;
2026
+ usage?: LlmTokenUsage;
2027
+ finishReason?: string;
2028
+ error?: string;
2029
+ };
2030
+ type ToolUseStartEvent = {
2031
+ runId: string;
2032
+ stepIndex: number;
2033
+ toolCallId: string;
2034
+ name: string;
2035
+ rawArguments: string;
2036
+ parsedArguments?: Record<string, unknown>;
2037
+ };
2038
+ type ToolUseEndEvent = {
2039
+ runId: string;
2040
+ stepIndex: number;
2041
+ toolCallId: string;
2042
+ name: string;
2043
+ result?: unknown;
2044
+ error?: string;
2045
+ errorType?: "parse" | "timeout" | "execution" | "cancelled";
2046
+ };
2047
+ type RunStartEvent = {
2048
+ runId: string;
2049
+ model: string;
2050
+ messages: Array<LlmapiMessage>;
2051
+ tools: Array<LlmapiChatCompletionTool>;
2052
+ };
2053
+ type RunEndEvent = {
2054
+ runId: string;
2055
+ finalContent: string;
2056
+ /** Number of LLM rounds executed. */
2057
+ totalSteps: number;
2058
+ };
2059
+ type RunErrorEvent = {
2060
+ runId: string;
2061
+ error: string;
2062
+ /**
2063
+ * Only `"model"` today. Tool failures surface on {@link RunHooks.afterToolUse}
2064
+ * with `errorType`, not on `onRunError`, so a tool stage isn't needed yet.
2065
+ * Left as a union to leave room for `"validation"` or `"tool"` later
2066
+ * without a breaking change.
2067
+ */
2068
+ stage: "model";
2069
+ /**
2070
+ * The underlying `Error` when one is available. `RunErrorEvent` predates
2071
+ * this field, so `error` (a string message) is kept for backwards
2072
+ * compatibility; new consumers should prefer `errorObject` when present
2073
+ * for stack traces and `cause`.
2074
+ */
2075
+ errorObject?: Error;
2076
+ };
2077
+ type RunHooks = {
2078
+ /**
2079
+ * Fires once per `runToolLoop` invocation, before any pre-processor or
2080
+ * model call. The `messages` payload is the raw caller-supplied
2081
+ * conversation — pre-processors that enrich it (e.g. web search context)
2082
+ * run afterwards, so `beforeModelCall.messages` reflects the
2083
+ * post-enrichment state.
2084
+ */
2085
+ onRunStart?: (e: RunStartEvent) => Promise<void> | void;
2086
+ /**
2087
+ * Fires exactly once per run on clean completion. Mutually exclusive
2088
+ * with `onRunError` — a run that completes fires `onRunEnd`; a run that
2089
+ * errors or is aborted fires `onRunError`. Consumers can rely on
2090
+ * exactly one terminal hook per `onRunStart`.
2091
+ */
2092
+ onRunEnd?: (e: RunEndEvent) => Promise<void> | void;
2093
+ /**
2094
+ * Fires exactly once per run when the loop errors or is aborted.
2095
+ * `stage` is `"model"` for stream/provider errors and for aborts;
2096
+ * tool execution failures surface as structured `{ error, errorType }`
2097
+ * results on `afterToolUse` rather than firing `onRunError`.
2098
+ * Mutually exclusive with `onRunEnd`.
2099
+ */
2100
+ onRunError?: (e: RunErrorEvent) => Promise<void> | void;
2101
+ beforeModelCall?: (e: ModelCallStartEvent) => Promise<void> | void;
2102
+ afterModelCall?: (e: ModelCallEndEvent) => Promise<void> | void;
2103
+ /**
2104
+ * Fires before each tool the model invoked — including server-side
2105
+ * tools that have no client executor. Today this is observe-only.
2106
+ * TODO(follow-up PR): allow returning { args?, abort?: { reason } } to
2107
+ * mutate arguments or short-circuit the tool call.
2108
+ *
2109
+ * Pairing with {@link afterToolUse} is asymmetric: server-side tools
2110
+ * routed via `onToolCall` get `beforeToolUse` but no `afterToolUse`,
2111
+ * because they don't execute in-process. Tools blocked by a failed
2112
+ * dependency or a dependency cycle DO get `afterToolUse` with
2113
+ * `errorType: "execution"` — consumers tallying matched pairs should
2114
+ * filter on executor-backed tools to avoid spurious imbalances.
2115
+ */
2116
+ beforeToolUse?: (e: ToolUseStartEvent) => Promise<void> | void;
2117
+ /**
2118
+ * Fires after each executor-backed tool finishes (success or failure)
2119
+ * and after each dependency-blocked tool is skipped (`errorType:
2120
+ * "execution"`). Does NOT fire for server-side tools routed via
2121
+ * `onToolCall`. See {@link beforeToolUse} for the pairing contract.
2122
+ */
2123
+ afterToolUse?: (e: ToolUseEndEvent) => Promise<void> | void;
2124
+ };
2125
+
2005
2126
  /**
2006
2127
  * Configuration for stream output smoothing.
2007
2128
  *
@@ -2196,6 +2317,8 @@ type BaseSendMessageArgs = ResponsesApiOptions & {
2196
2317
  type BaseUseChatOptions = {
2197
2318
  getToken?: () => Promise<string | null>;
2198
2319
  baseUrl?: string;
2320
+ /** Run lifecycle hooks for telemetry and tracing, for example from `createMetricsHooks` */
2321
+ hooks?: RunHooks | RunHooks[];
2199
2322
  /**
2200
2323
  * Callback function to be called when a new data chunk is received.
2201
2324
  */
@@ -6615,6 +6738,8 @@ interface CachedServerTools {
6615
6738
  version: string;
6616
6739
  /** Checksum from the server for cache invalidation */
6617
6740
  checksum?: string;
6741
+ /** ETag from the server. The next refresh sends it in an If-None-Match header. */
6742
+ etag?: string;
6618
6743
  }
6619
6744
  /**
6620
6745
  * Pluggable persistence for the fetched server-tools list.
@@ -6684,7 +6809,9 @@ declare function clearServerToolsCache(cache: ToolsCacheBackend): void | Promise
6684
6809
  * Flow:
6685
6810
  * 1. Check the cache backend (localStorage by default; override via `cache`)
6686
6811
  * 2. If cache valid and not force refresh, return cached tools
6687
- * 3. Otherwise, fetch from API, cache, and return
6812
+ * 3. Otherwise, fetch from API, cache, and return. When the cache holds an ETag,
6813
+ * the request sends If-None-Match. On 304 the cached tools stay and only the
6814
+ * stored timestamp changes.
6688
6815
  * 4. On fetch failure, return cached tools if available (stale-while-error)
6689
6816
  */
6690
6817
  declare function getServerTools(options: ServerToolsOptions): Promise<ServerTool[]>;
@@ -7131,6 +7258,8 @@ interface CreateConversationOptions {
7131
7258
  * @inline
7132
7259
  */
7133
7260
  interface BaseUseChatStorageOptions {
7261
+ /** Run lifecycle hooks for telemetry and tracing, for example from `createMetricsHooks` */
7262
+ hooks?: RunHooks | RunHooks[];
7134
7263
  /** WatermelonDB database instance for storing conversations and messages */
7135
7264
  database: Database;
7136
7265
  /** Route memory reads, writes, recall and the memory tools through this store instead of the database's vault; folders are unsupported. With `piiRedaction` on, build the store with `embeddingOptions.maskInput` (e.g. `(text) => redactor.maskText(text)` with any `PiiRedactor`) or its memory calls throw. */
@@ -10551,6 +10680,8 @@ type UseCreditsResult = {
10551
10680
  */
10552
10681
  declare function useCredits(options?: UseCreditsOptions): UseCreditsResult;
10553
10682
 
10683
+ /** Clear all cached model lists. */
10684
+ declare function clearModelsCache(): void;
10554
10685
  /**
10555
10686
  * @inline
10556
10687
  */
@@ -11147,4 +11278,4 @@ interface UseChatStorageResult extends BaseUseChatStorageResult {
11147
11278
  */
11148
11279
  declare function useChatStorage(options: UseChatStorageOptions): UseChatStorageResult;
11149
11280
 
11150
- 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 MemoryQuarantinedEvent, type MemoryRecallOptions, type MemoryRetainOptions, type MemoryStore, type MemorySubscribeOptions, type MemoryToVerify, type MemoryTopic, 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 RecallToolCallbacks, type RecallToolOptions, 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 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, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, 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, 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, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, 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, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
11281
+ 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 MemoryQuarantinedEvent, type MemoryRecallOptions, type MemoryRetainOptions, type MemoryStore, type MemorySubscribeOptions, type MemoryToVerify, type MemoryTopic, 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 RecallToolCallbacks, type RecallToolOptions, 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 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, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, 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, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, 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, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
@@ -4296,15 +4296,17 @@ Build ONLY when the user gives an explicit instruction to build, create, generat
4296
4296
 
4297
4297
  Once the user HAS given an explicit build instruction, you are in App Builder mode: you produce polished, production-quality React apps that feel designed \u2014 not generic.
4298
4298
 
4299
- DESIGN: on the initial build, before writing code, briefly state (2-3 sentences) what you want this app to feel like \u2014 name the specific fonts, the palette in hex, and one signature detail. Be concrete: "Fraunces display + Inter body + JetBrains Mono metadata, terracotta #b75432 accent on bone #f3efe6, paper-grain texture via inline SVG noise" is the kind of specificity that anchors the build. Default to nothing: don't pick "safe modern productivity" unless the brief literally asks for utilitarian. On later turns, state a design brief only when the change is visual (a restyle, new theme, or new UI); for a logic, data, or behavior-only change, skip the brief and just make the change.
4299
+ DESIGN: on the initial build, before writing code, briefly state (2-3 sentences) what you want this app to feel like \u2014 name the specific fonts, the palette in hex, and one signature detail. Be concrete: "Fraunces display + Inter body + JetBrains Mono metadata, terracotta #b75432 accent on bone #f3efe6, paper-grain texture via inline SVG noise" is the kind of specificity that anchors the build. Default to nothing: don't pick "safe modern productivity" unless the brief literally asks for utilitarian. On later turns, state a design brief only when the change is visual (a restyle, new theme, or new UI); for a text, logic, data, or behavior-only change, skip the brief and just make the change.
4300
+
4301
+ EDIT SCOPE: Change only the files and lines required by the current user request. A title rename is a text edit, not a design change. Preserve styles, dependencies, and unrelated logic on text edits. Design feedback does not authorize unrelated edits.
4300
4302
 
4301
4303
  WORKFLOW:
4302
4304
  1. NEVER output code as text or markdown. ALWAYS use tools.
4303
4305
  2. Initial build: state your design brief, then create_file with a "files" array writing ALL files in one call. The preview renders automatically.
4304
4306
  3. patch_file requires read_file for that path earlier in the conversation (or create_file in the same conversation, which counts). read_file output is numbered "42: <text>" \u2014 the prefix is display-only; never copy it into "find". Each "find" must match exactly one location \u2014 include 2-3 lines of surrounding context. Pass multiple patches per call to change distinct locations.
4305
4307
  4. Prefer patch_file for changes to existing files \u2014 surgical, reviewable, preserves surrounding code. Reserve create_file overwrites for substantial restructuring. Inserts: find the line before, replace with that line + the new line. Deletes: empty replace.
4306
- 5. After substantial changes, call critique_design first (taste, hierarchy, distinctiveness, weakest decision) and then audit_design (mechanical: tokens, focus states, aria-labels, alt, heading order). Patch what each surfaces. critique catches taste issues no checklist would; audit catches mechanics you'd miss. Run both; act on both.
4307
- 6. Before declaring done, call verify_app. The host's preview runtime reports whether your app actually mounted and surfaces any errors it captured \u2014 hallucinated imports, syntax the bundler rejected, undefined components, runtime crashes. If \`rendered\` is false or \`errors\` is non-empty, fix every error before the next message. If the response includes a \`note\` that verify_app isn't wired in this host, skip \u2014 audit + critique are your feedback in that case.
4308
+ 5. On the initial build, when adding new UI, or after user-requested design changes, call critique_design first and then audit_design. Critique checks taste, hierarchy, and distinctiveness. Audit checks tokens, focus states, aria-labels, alt text, and heading order. Patch only issues within the current user request. For text, logic, or data edits, skip both design tools.
4309
+ 6. Before declaring done, call verify_app. The host's preview runtime reports whether your app actually mounted and surfaces any errors it captured \u2014 hallucinated imports, syntax the bundler rejected, undefined components, runtime crashes. If \`rendered\` is false or \`errors\` is non-empty, fix every error before the next message. If the response includes a \`note\` that verify_app isn't wired in this host, skip runtime verification. An unavailable runtime verifier does not authorize design changes. Use audit_design and critique_design only for the initial build, adding new UI, or user-requested design changes.
4308
4310
  7. Keep responses to a sentence or two. Exception: when responding to critique_design, write a substantive paragraph per rubric question.
4309
4311
 
4310
4312
  STRUCTURE:
@@ -4470,12 +4472,13 @@ function isCacheExpired(cache, expirationMs = DEFAULT_CACHE_EXPIRATION_MS) {
4470
4472
  if (!cache) return true;
4471
4473
  return Date.now() - cache.timestamp > expirationMs;
4472
4474
  }
4473
- function buildCacheEntry(tools, checksum) {
4475
+ function buildCacheEntry(tools, checksum, etag) {
4474
4476
  return {
4475
4477
  tools,
4476
4478
  timestamp: Date.now(),
4477
4479
  version: CACHE_VERSION,
4478
- ...checksum && { checksum }
4480
+ ...checksum && { checksum },
4481
+ ...etag && { etag }
4479
4482
  };
4480
4483
  }
4481
4484
  function writeLocalStorageCache(entry) {
@@ -4510,19 +4513,36 @@ function shouldRefreshTools(responseChecksum, cache = localStorageToolsCache) {
4510
4513
  const cachedChecksum = getToolsChecksum2(cache);
4511
4514
  return cachedChecksum instanceof Promise ? cachedChecksum.then(decide) : decide(cachedChecksum);
4512
4515
  }
4513
- async function fetchServerToolsFromApi(baseUrl, token) {
4514
- const response = await fetch(`${baseUrl}/api/v1/tools`, {
4516
+ async function fetchServerToolsFromApi(baseUrl, authHeaders, etag) {
4517
+ const request = (validator) => fetch(`${baseUrl}/api/v1/tools`, {
4515
4518
  method: "GET",
4516
4519
  headers: {
4517
- Authorization: `Bearer ${token}`,
4518
- "Content-Type": "application/json"
4520
+ ...authHeaders,
4521
+ "Content-Type": "application/json",
4522
+ ...validator && { "If-None-Match": validator }
4519
4523
  }
4520
4524
  });
4525
+ let response;
4526
+ try {
4527
+ response = await request(etag);
4528
+ } catch (error) {
4529
+ if (!etag || !(error instanceof TypeError)) throw error;
4530
+ etag = void 0;
4531
+ response = await request();
4532
+ }
4533
+ if (etag && response.status === 304) {
4534
+ return { notModified: true };
4535
+ }
4521
4536
  if (!response.ok) {
4522
4537
  throw new Error(`Failed to fetch server tools: ${response.status}`);
4523
4538
  }
4524
4539
  const data = await response.json();
4525
- return convertServerToolsResponse(data);
4540
+ const responseEtag = response.headers?.get("ETag") ?? void 0;
4541
+ return {
4542
+ notModified: false,
4543
+ ...convertServerToolsResponse(data),
4544
+ ...responseEtag && { etag: responseEtag }
4545
+ };
4526
4546
  }
4527
4547
  async function getServerTools(options) {
4528
4548
  const {
@@ -4554,34 +4574,30 @@ async function getServerTools(options) {
4554
4574
  try {
4555
4575
  const { BASE_URL: BASE_URL2 } = await import("./clientConfig-VPOGQRNP.mjs");
4556
4576
  const effectiveBaseUrl = baseUrl ?? BASE_URL2;
4577
+ const validator = cached && !forceRefresh ? cached.etag : void 0;
4578
+ let authHeaders;
4557
4579
  if (apiKey) {
4558
- const response = await fetch(`${effectiveBaseUrl}/api/v1/tools`, {
4559
- method: "GET",
4560
- headers: {
4561
- "X-API-Key": apiKey,
4562
- "Content-Type": "application/json"
4563
- }
4564
- });
4565
- if (!response.ok) {
4566
- throw new Error(`Failed to fetch server tools: ${response.status}`);
4580
+ authHeaders = { "X-API-Key": apiKey };
4581
+ } else {
4582
+ if (!getToken) {
4583
+ getLogger().warn("[serverTools] No auth method available for fetching tools");
4584
+ return cached?.tools ?? [];
4567
4585
  }
4568
- const data = await response.json();
4569
- const { tools: tools2, checksum: checksum2 } = convertServerToolsResponse(data);
4570
- await persistCache(buildCacheEntry(tools2, checksum2));
4571
- return tools2;
4572
- }
4573
- if (!getToken) {
4574
- getLogger().warn("[serverTools] No auth method available for fetching tools");
4575
- return cached?.tools ?? [];
4586
+ const token = await getToken();
4587
+ if (!token) {
4588
+ getLogger().warn("[serverTools] No auth token available for fetching tools");
4589
+ return cached?.tools ?? [];
4590
+ }
4591
+ authHeaders = { Authorization: `Bearer ${token}` };
4576
4592
  }
4577
- const token = await getToken();
4578
- if (!token) {
4579
- getLogger().warn("[serverTools] No auth token available for fetching tools");
4580
- return cached?.tools ?? [];
4593
+ const result = await fetchServerToolsFromApi(effectiveBaseUrl, authHeaders, validator);
4594
+ if (result.notModified) {
4595
+ const confirmed = cached;
4596
+ await persistCache({ ...confirmed, timestamp: Date.now() });
4597
+ return confirmed.tools;
4581
4598
  }
4582
- const { tools, checksum } = await fetchServerToolsFromApi(effectiveBaseUrl, token);
4583
- await persistCache(buildCacheEntry(tools, checksum));
4584
- return tools;
4599
+ await persistCache(buildCacheEntry(result.tools, result.checksum, result.etag));
4600
+ return result.tools;
4585
4601
  } catch (error) {
4586
4602
  getLogger().error("[serverTools] Failed to fetch server tools:", error);
4587
4603
  if (cached?.tools) {
@@ -22032,6 +22048,128 @@ function useCredits(options = {}) {
22032
22048
 
22033
22049
  // src/react/useModels.ts
22034
22050
  import { useCallback as useCallback2, useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
22051
+ var MODELS_CACHE_TTL_MS = 5 * 60 * 1e3;
22052
+ var modelsCache = /* @__PURE__ */ new Map();
22053
+ var modelsInFlight = /* @__PURE__ */ new Map();
22054
+ var cacheGeneration = 0;
22055
+ function clearModelsCache() {
22056
+ cacheGeneration++;
22057
+ modelsCache.clear();
22058
+ modelsInFlight.clear();
22059
+ }
22060
+ function pruneStaleTokenEntries(newKey) {
22061
+ const [newBaseUrl, newProvider] = JSON.parse(newKey);
22062
+ for (const existingKey of modelsCache.keys()) {
22063
+ if (existingKey === newKey) continue;
22064
+ const [existingBaseUrl, existingProvider] = JSON.parse(existingKey);
22065
+ if (existingBaseUrl === newBaseUrl && existingProvider === newProvider) {
22066
+ modelsCache.delete(existingKey);
22067
+ }
22068
+ }
22069
+ }
22070
+ function fingerprintToken(token) {
22071
+ if (!token) return "anon";
22072
+ let h1 = 3735928559;
22073
+ let h2 = 1103547991;
22074
+ for (let i = 0; i < token.length; i++) {
22075
+ const ch = token.charCodeAt(i);
22076
+ h1 = Math.imul(h1 ^ ch, 2654435761);
22077
+ h2 = Math.imul(h2 ^ ch, 1597334677);
22078
+ }
22079
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
22080
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
22081
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
22082
+ }
22083
+ function modelsCacheKey(baseUrl, provider, token) {
22084
+ return JSON.stringify([baseUrl, provider ?? null, fingerprintToken(token)]);
22085
+ }
22086
+ async function fetchAllModelPages(baseUrl, provider, headers, previous, signal) {
22087
+ const pages = /* @__PURE__ */ new Map();
22088
+ const models = [];
22089
+ let pageToken;
22090
+ do {
22091
+ const pageKey = pageToken ?? "";
22092
+ const stored2 = previous?.pages.get(pageKey);
22093
+ const request = (etag) => getApiV1Models({
22094
+ baseUrl,
22095
+ headers: etag ? { ...headers, "If-None-Match": etag } : headers,
22096
+ query: { provider, page_token: pageToken },
22097
+ signal
22098
+ });
22099
+ let response = await request(stored2?.etag);
22100
+ if (stored2?.etag && !response.response && response.error) {
22101
+ response = await request();
22102
+ }
22103
+ let page;
22104
+ if (response.response?.status === 304) {
22105
+ if (!stored2) throw new Error("Failed to fetch models");
22106
+ page = stored2;
22107
+ } else {
22108
+ if (response.error) {
22109
+ const errorMsg = response.error.error ?? "Failed to fetch models";
22110
+ throw new Error(errorMsg);
22111
+ }
22112
+ page = {
22113
+ body: response.data ?? {},
22114
+ etag: response.response?.headers?.get("ETag") ?? void 0
22115
+ };
22116
+ }
22117
+ pages.set(pageKey, page);
22118
+ models.push(...page.body.data || []);
22119
+ pageToken = page.body.next_page_token;
22120
+ } while (pageToken);
22121
+ return { pages, models, fetchedAt: Date.now() };
22122
+ }
22123
+ function loadModels(key, baseUrl, provider, headers, force, signal) {
22124
+ const cached = modelsCache.get(key);
22125
+ if (cached && !force && Date.now() - cached.fetchedAt < MODELS_CACHE_TTL_MS) {
22126
+ return Promise.resolve([...cached.models]);
22127
+ }
22128
+ const shared = (force ? void 0 : modelsInFlight.get(key)) ?? startSharedRequest(key, baseUrl, provider, headers, cached);
22129
+ return waitForSharedRequest(key, shared, signal).then((models) => [...models]);
22130
+ }
22131
+ function startSharedRequest(key, baseUrl, provider, headers, previous) {
22132
+ const controller = new AbortController();
22133
+ const generation = cacheGeneration;
22134
+ const shared = {
22135
+ controller,
22136
+ waiters: 0,
22137
+ promise: Promise.resolve([])
22138
+ };
22139
+ shared.promise = fetchAllModelPages(baseUrl, provider, headers, previous, controller.signal).then((entry) => {
22140
+ if (modelsInFlight.get(key) === shared && generation === cacheGeneration) {
22141
+ pruneStaleTokenEntries(key);
22142
+ modelsCache.set(key, entry);
22143
+ }
22144
+ return entry.models;
22145
+ }).finally(() => {
22146
+ if (modelsInFlight.get(key) === shared) modelsInFlight.delete(key);
22147
+ });
22148
+ modelsInFlight.set(key, shared);
22149
+ return shared;
22150
+ }
22151
+ function waitForSharedRequest(key, shared, signal) {
22152
+ shared.waiters++;
22153
+ let left = false;
22154
+ const leave = () => {
22155
+ if (left) return;
22156
+ left = true;
22157
+ shared.waiters--;
22158
+ if (shared.waiters === 0) {
22159
+ shared.controller.abort();
22160
+ if (modelsInFlight.get(key) === shared) modelsInFlight.delete(key);
22161
+ }
22162
+ };
22163
+ if (signal.aborted) {
22164
+ leave();
22165
+ } else {
22166
+ signal.addEventListener("abort", leave, { once: true });
22167
+ }
22168
+ return shared.promise.finally(() => {
22169
+ left = true;
22170
+ signal.removeEventListener("abort", leave);
22171
+ });
22172
+ }
22035
22173
  function useModels(options = {}) {
22036
22174
  const { getToken, baseUrl = BASE_URL, provider, autoFetch = true } = options;
22037
22175
  const [models, setModels] = useState2([]);
@@ -22054,7 +22192,7 @@ function useModels(options = {}) {
22054
22192
  }
22055
22193
  };
22056
22194
  }, []);
22057
- const fetchModels = useCallback2(async () => {
22195
+ const fetchModels = useCallback2(async (force = false) => {
22058
22196
  if (abortControllerRef.current) {
22059
22197
  abortControllerRef.current.abort();
22060
22198
  }
@@ -22073,35 +22211,17 @@ function useModels(options = {}) {
22073
22211
  if (token) {
22074
22212
  headers["Authorization"] = `Bearer ${token}`;
22075
22213
  }
22076
- let allModels = [];
22077
- let nextPageToken;
22078
- do {
22079
- if (signal.aborted) return;
22080
- const response = await getApiV1Models({
22081
- baseUrl: baseUrlRef.current,
22082
- headers,
22083
- query: {
22084
- provider: providerRef.current,
22085
- page_token: nextPageToken
22086
- },
22087
- signal
22088
- });
22089
- if (response.error) {
22090
- const errorMsg = response.error.error ?? "Failed to fetch models";
22091
- throw new Error(errorMsg);
22092
- }
22093
- if (response.data) {
22094
- const newModels = response.data.data || [];
22095
- allModels = [...allModels, ...newModels];
22096
- nextPageToken = response.data.next_page_token;
22097
- }
22098
- } while (nextPageToken);
22214
+ const baseUrl2 = baseUrlRef.current;
22215
+ const provider2 = providerRef.current;
22216
+ const key = modelsCacheKey(baseUrl2, provider2, token);
22217
+ const allModels = await loadModels(key, baseUrl2, provider2, headers, force, signal);
22099
22218
  if (signal.aborted) return;
22100
22219
  setModels(allModels);
22101
22220
  } catch (err) {
22102
22221
  if (err instanceof Error && err.name === "AbortError") {
22103
22222
  return;
22104
22223
  }
22224
+ if (signal.aborted) return;
22105
22225
  setError(err instanceof Error ? err : new Error(String(err)));
22106
22226
  } finally {
22107
22227
  if (!signal.aborted) {
@@ -22114,7 +22234,7 @@ function useModels(options = {}) {
22114
22234
  }, []);
22115
22235
  const refetch = useCallback2(async () => {
22116
22236
  setModels([]);
22117
- await fetchModels();
22237
+ await fetchModels(true);
22118
22238
  }, [fetchModels]);
22119
22239
  const hasFetchedRef = useRef2(false);
22120
22240
  useEffect2(() => {
@@ -22840,6 +22960,7 @@ function useChat(options) {
22840
22960
  apiType: defaultApiType = "auto",
22841
22961
  smoothing,
22842
22962
  preProcessors,
22963
+ hooks,
22843
22964
  piiRedaction,
22844
22965
  onPiiRedacted,
22845
22966
  resumable = false,
@@ -23093,6 +23214,7 @@ function useChat(options) {
23093
23214
  onToolCallArgumentsDelta,
23094
23215
  onStepFinish,
23095
23216
  preProcessors,
23217
+ hooks,
23096
23218
  piiRedaction: requestPiiRedaction ?? resolvedPiiRedaction,
23097
23219
  onPiiRedacted
23098
23220
  });
@@ -23132,6 +23254,7 @@ function useChat(options) {
23132
23254
  defaultApiType,
23133
23255
  smoothing,
23134
23256
  preProcessors,
23257
+ hooks,
23135
23258
  resolvedPiiRedaction,
23136
23259
  onPiiRedacted,
23137
23260
  resumable,
@@ -24092,6 +24215,7 @@ function useChatStorage(options) {
24092
24215
  embeddingModel = DEFAULT_API_EMBEDDING_MODEL,
24093
24216
  minContentLength = DEFAULT_MIN_CONTENT_LENGTH,
24094
24217
  preProcessors,
24218
+ hooks,
24095
24219
  smoothing,
24096
24220
  resumable = false,
24097
24221
  onCancelResult,
@@ -24551,6 +24675,7 @@ function useChatStorage(options) {
24551
24675
  onError,
24552
24676
  apiType,
24553
24677
  preProcessors,
24678
+ hooks,
24554
24679
  smoothing,
24555
24680
  resumable,
24556
24681
  onCancelResult,
@@ -25899,6 +26024,7 @@ export {
25899
26024
  clearConversationMemoriesOp,
25900
26025
  clearEncryptionKey,
25901
26026
  clearLazyTitleCache,
26027
+ clearModelsCache,
25902
26028
  clearServerToolsCache,
25903
26029
  consoleLogger,
25904
26030
  conversationMemoryToStored,