@anuma/sdk 1.0.0-next.20260224164627

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.
@@ -0,0 +1,2682 @@
1
+ import { Database, Model, Collection } from '@nozbe/watermelondb';
2
+ import * as _nozbe_watermelondb_Schema_migrations from '@nozbe/watermelondb/Schema/migrations';
3
+ import * as _nozbe_watermelondb_Schema from '@nozbe/watermelondb/Schema';
4
+ import Model$1, { Associations } from '@nozbe/watermelondb/Model';
5
+ import { Class } from '@nozbe/watermelondb/types';
6
+ import { DatabaseAdapter } from '@nozbe/watermelondb/adapters/type';
7
+
8
+ type HandlersClaimDailyCreditsResponse = {
9
+ /**
10
+ * Credits awarded (1 credit = $0.01)
11
+ */
12
+ credits_awarded?: number;
13
+ message?: string;
14
+ /**
15
+ * ISO8601 timestamp when next claim is available
16
+ */
17
+ next_claim_at?: string;
18
+ success?: boolean;
19
+ };
20
+ type HandlersCreditBalanceResponse = {
21
+ /**
22
+ * Available credits (1 credit = $0.01)
23
+ */
24
+ available_credits?: number;
25
+ can_claim_daily?: boolean;
26
+ /**
27
+ * Whether enrolled on-chain
28
+ */
29
+ is_enrolled?: boolean;
30
+ last_claim_at?: string;
31
+ /**
32
+ * Total credits ever received (1 credit = $0.01)
33
+ */
34
+ lifetime_credits?: number;
35
+ next_claim_at?: string;
36
+ /**
37
+ * "basic" or "pro"
38
+ */
39
+ subscription_tier?: string;
40
+ wallet_address?: string;
41
+ };
42
+ type HandlersCreditPack = {
43
+ bonus_percent?: number;
44
+ credits?: number;
45
+ currency?: string;
46
+ pro_credits?: number;
47
+ unit_amount?: number;
48
+ };
49
+ /**
50
+ * ExtraFields contains additional metadata
51
+ */
52
+ type LlmapiChatCompletionExtraFields = {
53
+ /**
54
+ * Latency is the request latency in milliseconds
55
+ */
56
+ latency?: number;
57
+ /**
58
+ * ModelRequested is the model that was requested
59
+ */
60
+ model_requested?: string;
61
+ /**
62
+ * Provider is the LLM provider used (e.g., "openai", "anthropic")
63
+ */
64
+ provider?: string;
65
+ /**
66
+ * RequestType is always "chat_completion"
67
+ */
68
+ request_type?: string;
69
+ };
70
+ type LlmapiChatCompletionResponse = {
71
+ /**
72
+ * Choices contains the completion choices
73
+ */
74
+ choices?: Array<LlmapiChoice>;
75
+ /**
76
+ * ClientInjectedTools are tool names the client provided in the original request.
77
+ */
78
+ client_injected_tools?: Array<string>;
79
+ extra_fields?: LlmapiChatCompletionExtraFields;
80
+ /**
81
+ * ID is the completion ID
82
+ */
83
+ id?: string;
84
+ /**
85
+ * InferenceID is the unique identifier for this inference request
86
+ */
87
+ inference_id?: string;
88
+ /**
89
+ * Messages contains the full conversation history when local tools need execution.
90
+ * This is populated when the model requests tools that are not MCP tools (local/client-side tools).
91
+ * The client should execute these tools and send a new request with this message history
92
+ * plus the tool results appended.
93
+ */
94
+ messages?: Array<LlmapiMessage>;
95
+ /**
96
+ * Model is the model used
97
+ */
98
+ model?: string;
99
+ /**
100
+ * PortalInjectedTools are tool names the portal's classifier added to the request.
101
+ */
102
+ portal_injected_tools?: Array<string>;
103
+ /**
104
+ * ToolCallEvents is an array of tool call events.
105
+ */
106
+ tool_call_events?: Array<LlmapiToolCallEvent>;
107
+ /**
108
+ * ToolsChecksum is the checksum of the tool schemas used by the AI Portal.
109
+ */
110
+ tools_checksum?: string;
111
+ usage?: LlmapiChatCompletionUsage;
112
+ };
113
+ type LlmapiChatCompletionTool = {
114
+ [key: string]: unknown;
115
+ };
116
+ /**
117
+ * Usage contains token usage information
118
+ */
119
+ type LlmapiChatCompletionUsage = {
120
+ /**
121
+ * CompletionTokens is the number of tokens in the completion
122
+ */
123
+ completion_tokens?: number;
124
+ /**
125
+ * CostMicroUSD is the cost of this completion in micro-dollars (USD × 1,000,000)
126
+ */
127
+ cost_micro_usd?: number;
128
+ /**
129
+ * CreditsUsed is the number of credits consumed by this completion (ceiling of cost / MicroUSDPerCredit)
130
+ */
131
+ credits_used?: number;
132
+ /**
133
+ * PromptTokens is the number of tokens in the prompt
134
+ */
135
+ prompt_tokens?: number;
136
+ /**
137
+ * ToolCostMicroUSD is the cost of MCP tool calls in micro-dollars (subset of CostMicroUSD)
138
+ */
139
+ tool_cost_micro_usd?: number;
140
+ /**
141
+ * TotalTokens is the total number of tokens used
142
+ */
143
+ total_tokens?: number;
144
+ };
145
+ type LlmapiChoice = {
146
+ /**
147
+ * FinishReason indicates why the completion stopped
148
+ */
149
+ finish_reason?: string;
150
+ /**
151
+ * Index is the choice index
152
+ */
153
+ index?: number;
154
+ message?: LlmapiMessage;
155
+ };
156
+ type LlmapiMcpTool = {
157
+ /**
158
+ * Description is the description of the tool
159
+ */
160
+ description?: string;
161
+ /**
162
+ * InputSchema is the JSON schema describing the tool's input
163
+ */
164
+ input_schema?: unknown;
165
+ /**
166
+ * Name is the name of the tool
167
+ */
168
+ name?: string;
169
+ };
170
+ /**
171
+ * Message is the generated message
172
+ */
173
+ type LlmapiMessage = {
174
+ /**
175
+ * Content is the message content
176
+ */
177
+ content?: Array<LlmapiMessageContentPart>;
178
+ role?: LlmapiRole;
179
+ /**
180
+ * ToolCallID is the ID of the tool call this message is responding to (only for tool role)
181
+ */
182
+ tool_call_id?: string;
183
+ /**
184
+ * ToolCalls contains tool/function calls made by the assistant (only for assistant role)
185
+ */
186
+ tool_calls?: Array<LlmapiToolCall>;
187
+ /**
188
+ * Type is the message type (for Responses API: "message")
189
+ */
190
+ type?: string;
191
+ };
192
+ /**
193
+ * File is used when Type=input_file (for Responses API)
194
+ */
195
+ type LlmapiMessageContentFile = {
196
+ /**
197
+ * FileData is the base64-encoded file content
198
+ */
199
+ file_data?: string;
200
+ /**
201
+ * FileID is the ID of an uploaded file
202
+ */
203
+ file_id?: string;
204
+ /**
205
+ * FileURL is the URL to the file
206
+ */
207
+ file_url?: string;
208
+ /**
209
+ * Filename is the name of the file
210
+ */
211
+ filename?: string;
212
+ };
213
+ /**
214
+ * ImageURL is used when Type=image_url or Type=input_image
215
+ */
216
+ type LlmapiMessageContentImage = {
217
+ /**
218
+ * Detail is the OpenAI detail hint (auto|low|high)
219
+ */
220
+ detail?: string;
221
+ /**
222
+ * URL is the image URL or data URI
223
+ */
224
+ url?: string;
225
+ };
226
+ type LlmapiMessageContentPart = {
227
+ file?: LlmapiMessageContentFile;
228
+ image_url?: LlmapiMessageContentImage;
229
+ /**
230
+ * Text holds the text content when Type=text or Type=input_text
231
+ */
232
+ text?: string;
233
+ /**
234
+ * Type is the block type (`text`, `image_url`, or `input_file`)
235
+ */
236
+ type?: string;
237
+ };
238
+ type LlmapiModel = {
239
+ architecture?: LlmapiModelArchitecture;
240
+ /**
241
+ * CanonicalSlug is the canonical slug for the model
242
+ */
243
+ canonical_slug?: string;
244
+ /**
245
+ * ContextLength is the maximum context length in tokens
246
+ */
247
+ context_length?: number;
248
+ /**
249
+ * Created is the Unix timestamp of when the model was created
250
+ */
251
+ created?: number;
252
+ /**
253
+ * DefaultParameters contains default parameter values
254
+ */
255
+ default_parameters?: {
256
+ [key: string]: unknown;
257
+ };
258
+ /**
259
+ * Description describes the model and its capabilities
260
+ */
261
+ description?: string;
262
+ /**
263
+ * HuggingFaceID is the Hugging Face model identifier
264
+ */
265
+ hugging_face_id?: string;
266
+ /**
267
+ * ID is the model identifier (e.g., "openai/gpt-4")
268
+ */
269
+ id?: string;
270
+ /**
271
+ * MaxInputTokens is the maximum input tokens
272
+ */
273
+ max_input_tokens?: number;
274
+ /**
275
+ * MaxOutputTokens is the maximum output tokens
276
+ */
277
+ max_output_tokens?: number;
278
+ /**
279
+ * Modalities is a list of supported modalities (e.g., ["llm", "vision"])
280
+ */
281
+ modalities?: Array<string>;
282
+ /**
283
+ * Name is the human-readable model name (optional)
284
+ */
285
+ name?: string;
286
+ /**
287
+ * OwnedBy is the organization that owns the model
288
+ */
289
+ owned_by?: string;
290
+ per_request_limits?: LlmapiModelPerRequestLimits;
291
+ pricing?: LlmapiModelPricing;
292
+ /**
293
+ * SupportedMethods is a list of supported API methods
294
+ */
295
+ supported_methods?: Array<string>;
296
+ /**
297
+ * SupportedParameters is a list of supported parameter names
298
+ */
299
+ supported_parameters?: Array<string>;
300
+ top_provider?: LlmapiModelTopProvider;
301
+ };
302
+ /**
303
+ * Architecture describes the model's technical capabilities
304
+ */
305
+ type LlmapiModelArchitecture = {
306
+ instruct_type?: string;
307
+ modality?: string;
308
+ prompt_formatting?: string;
309
+ tokenizer?: string;
310
+ };
311
+ /**
312
+ * PerRequestLimits contains rate limiting information
313
+ */
314
+ type LlmapiModelPerRequestLimits = {
315
+ completion_tokens?: number;
316
+ prompt_tokens?: number;
317
+ };
318
+ /**
319
+ * Pricing contains the pricing structure for using this model
320
+ */
321
+ type LlmapiModelPricing = {
322
+ completion?: string;
323
+ image?: string;
324
+ prompt?: string;
325
+ request?: string;
326
+ };
327
+ /**
328
+ * TopProvider contains configuration details for the primary provider
329
+ */
330
+ type LlmapiModelTopProvider = {
331
+ context_length?: number;
332
+ is_moderated?: boolean;
333
+ max_completion_tokens?: number;
334
+ };
335
+ /**
336
+ * ExtraFields contains additional metadata
337
+ */
338
+ type LlmapiResponseExtraFields = {
339
+ /**
340
+ * Latency is the request latency in milliseconds
341
+ */
342
+ latency?: number;
343
+ /**
344
+ * ModelRequested is the model that was requested
345
+ */
346
+ model_requested?: string;
347
+ /**
348
+ * Provider is the LLM provider used (e.g., "openai", "anthropic")
349
+ */
350
+ provider?: string;
351
+ /**
352
+ * RequestType is always "responses"
353
+ */
354
+ request_type?: string;
355
+ };
356
+ type LlmapiResponseOutputContent = {
357
+ /**
358
+ * Text is the text content
359
+ */
360
+ text?: string;
361
+ /**
362
+ * Type is the content type (e.g., "output_text")
363
+ */
364
+ type?: string;
365
+ };
366
+ type LlmapiResponseOutputItem = {
367
+ /**
368
+ * Arguments is the function arguments for function_call and mcp_call types
369
+ */
370
+ arguments?: string;
371
+ /**
372
+ * CallID is the call ID for function_call and mcp_call types
373
+ */
374
+ call_id?: string;
375
+ /**
376
+ * Content is the content array for message and reasoning types
377
+ */
378
+ content?: Array<LlmapiResponseOutputContent>;
379
+ /**
380
+ * Error is the MCP error message for mcp_call types
381
+ */
382
+ error?: string;
383
+ /**
384
+ * ID is the unique identifier for this output item
385
+ */
386
+ id?: string;
387
+ /**
388
+ * Name is the function name for function_call and mcp_call types
389
+ */
390
+ name?: string;
391
+ /**
392
+ * Output is the MCP tool output for mcp_call types
393
+ */
394
+ output?: string;
395
+ /**
396
+ * Role is the role for message types (e.g., "assistant")
397
+ */
398
+ role?: string;
399
+ /**
400
+ * ServerLabel is the MCP server label for mcp_call and mcp_list_tools types
401
+ */
402
+ server_label?: string;
403
+ /**
404
+ * Status is the status of this output item (e.g., "completed")
405
+ */
406
+ status?: string;
407
+ /**
408
+ * Summary is the reasoning summary for reasoning types
409
+ */
410
+ summary?: Array<LlmapiResponseOutputContent>;
411
+ /**
412
+ * Tools is the list of available tools for mcp_list_tools types
413
+ */
414
+ tools?: Array<LlmapiMcpTool>;
415
+ /**
416
+ * Type is the output item type (e.g., "message", "function_call", "reasoning", "mcp_call")
417
+ */
418
+ type?: string;
419
+ };
420
+ /**
421
+ * Reasoning configures reasoning for o-series and other reasoning models
422
+ */
423
+ type LlmapiResponseReasoning = {
424
+ /**
425
+ * Effort controls reasoning effort: "low", "medium", or "high"
426
+ */
427
+ effort?: string;
428
+ /**
429
+ * Summary controls reasoning summary: "auto", "concise", or "detailed"
430
+ */
431
+ summary?: string;
432
+ };
433
+ type LlmapiResponseResponse = {
434
+ /**
435
+ * ClientInjectedTools are tool names the client provided in the original request.
436
+ */
437
+ client_injected_tools?: Array<string>;
438
+ /**
439
+ * Created is the Unix timestamp of creation (created_at in OpenAI format)
440
+ */
441
+ created_at?: number;
442
+ extra_fields?: LlmapiResponseExtraFields;
443
+ /**
444
+ * ID is the unique response identifier
445
+ */
446
+ id?: string;
447
+ /**
448
+ * Messages contains the full conversation history when local tools need execution.
449
+ * This is populated when the model requests tools that are not MCP tools (local/client-side tools).
450
+ * The client should execute these tools and send a new request with this message history
451
+ * plus the tool results appended.
452
+ */
453
+ messages?: Array<LlmapiMessage>;
454
+ /**
455
+ * Model is the model used for generation
456
+ */
457
+ model?: string;
458
+ /**
459
+ * Object is the response type (e.g., "response")
460
+ */
461
+ object?: string;
462
+ /**
463
+ * Output is the array of output items (OpenAI Responses API format)
464
+ */
465
+ output?: Array<LlmapiResponseOutputItem>;
466
+ /**
467
+ * PortalInjectedTools are tool names the portal's classifier added to the request.
468
+ */
469
+ portal_injected_tools?: Array<string>;
470
+ /**
471
+ * ToolCallEvents is an array of tool call events.
472
+ */
473
+ tool_call_events?: Array<LlmapiToolCallEvent>;
474
+ /**
475
+ * ToolsChecksum is the checksum of the tool schemas used by the AI Portal.
476
+ */
477
+ tools_checksum?: string;
478
+ usage?: LlmapiResponseUsage;
479
+ };
480
+ /**
481
+ * Usage contains token usage information
482
+ */
483
+ type LlmapiResponseUsage = {
484
+ /**
485
+ * CompletionTokens is the number of tokens in the completion
486
+ */
487
+ completion_tokens?: number;
488
+ /**
489
+ * CostMicroUSD is the cost of this response in micro-dollars (USD × 1,000,000)
490
+ */
491
+ cost_micro_usd?: number;
492
+ /**
493
+ * CreditsUsed is the number of credits consumed by this response
494
+ */
495
+ credits_used?: number;
496
+ /**
497
+ * PromptTokens is the number of tokens in the prompt
498
+ */
499
+ prompt_tokens?: number;
500
+ /**
501
+ * ToolCostMicroUSD is the cost of MCP tool calls in micro-dollars (subset of CostMicroUSD)
502
+ */
503
+ tool_cost_micro_usd?: number;
504
+ /**
505
+ * TotalTokens is the total number of tokens used
506
+ */
507
+ total_tokens?: number;
508
+ };
509
+ /**
510
+ * Role is the message role (system, user, assistant, tool)
511
+ */
512
+ type LlmapiRole = string;
513
+ /**
514
+ * Thinking configures extended thinking for Anthropic models
515
+ */
516
+ type LlmapiThinkingOptions = {
517
+ /**
518
+ * BudgetTokens is the token budget for thinking
519
+ */
520
+ budget_tokens?: number;
521
+ /**
522
+ * Type indicates if thinking is enabled: "enabled" or "disabled"
523
+ */
524
+ type?: string;
525
+ };
526
+ type LlmapiToolCall = {
527
+ function?: LlmapiToolCallFunction;
528
+ /**
529
+ * ID is the unique identifier for this tool call
530
+ */
531
+ id?: string;
532
+ /**
533
+ * Type is the type of tool call (always "function" for now)
534
+ */
535
+ type?: string;
536
+ };
537
+ type LlmapiToolCallEvent = {
538
+ arguments?: string;
539
+ cost_micro_usd?: number;
540
+ id?: string;
541
+ name?: string;
542
+ output?: string;
543
+ };
544
+ /**
545
+ * Function contains the function call details
546
+ */
547
+ type LlmapiToolCallFunction = {
548
+ /**
549
+ * Arguments is the JSON string of arguments to pass to the function
550
+ */
551
+ arguments?: string;
552
+ /**
553
+ * Name is the name of the function to call
554
+ */
555
+ name?: string;
556
+ };
557
+
558
+ /**
559
+ * @inline
560
+ */
561
+ type UseCreditsOptions = {
562
+ /**
563
+ * Custom function to get auth token for API calls
564
+ */
565
+ getToken?: () => Promise<string | null>;
566
+ /**
567
+ * Optional base URL for the API requests.
568
+ */
569
+ baseUrl?: string;
570
+ /**
571
+ * Whether to fetch credit balance automatically on mount (default: true)
572
+ */
573
+ autoFetch?: boolean;
574
+ /**
575
+ * Optional callback for error handling
576
+ */
577
+ onError?: (error: Error) => void;
578
+ };
579
+ type UseCreditsResult = {
580
+ /**
581
+ * Current credit balance and related info
582
+ */
583
+ balance: HandlersCreditBalanceResponse | null;
584
+ /**
585
+ * Available credit packs for purchase
586
+ */
587
+ packs: HandlersCreditPack[];
588
+ /**
589
+ * Whether any operation is in progress
590
+ */
591
+ isLoading: boolean;
592
+ /**
593
+ * Error from the last operation
594
+ */
595
+ error: Error | null;
596
+ /**
597
+ * Refetch the credit balance
598
+ */
599
+ refetch: () => Promise<void>;
600
+ /**
601
+ * Fetch available credit packs
602
+ */
603
+ fetchPacks: () => Promise<void>;
604
+ /**
605
+ * Claim free daily credits (once per 24 hours)
606
+ * @returns The claim response or null on error
607
+ */
608
+ claimDailyCredits: () => Promise<HandlersClaimDailyCreditsResponse | null>;
609
+ /**
610
+ * Create a Stripe checkout session for purchasing a credit pack
611
+ * @param credits - Number of credits to purchase
612
+ * @returns The checkout URL or null on error
613
+ */
614
+ purchaseCredits: (credits: number, options?: {
615
+ successUrl?: string;
616
+ cancelUrl?: string;
617
+ }) => Promise<string | null>;
618
+ };
619
+ /**
620
+ * React hook for managing credits: checking balance, claiming daily credits,
621
+ * browsing packs, and purchasing credits.
622
+ * @category Hooks
623
+ */
624
+ declare function useCredits(options?: UseCreditsOptions): UseCreditsResult;
625
+
626
+ /**
627
+ * @inline
628
+ */
629
+ type UseModelsOptions = {
630
+ /**
631
+ * Custom function to get auth token for API calls
632
+ */
633
+ getToken?: () => Promise<string | null>;
634
+ /**
635
+ * Optional base URL for the API requests.
636
+ */
637
+ baseUrl?: string;
638
+ /**
639
+ * Optional filter for specific provider (e.g. "openai")
640
+ */
641
+ provider?: string;
642
+ /**
643
+ * Whether to fetch models automatically on mount (default: true)
644
+ */
645
+ autoFetch?: boolean;
646
+ };
647
+ type UseModelsResult = {
648
+ models: LlmapiModel[];
649
+ isLoading: boolean;
650
+ error: Error | null;
651
+ refetch: () => Promise<void>;
652
+ };
653
+ /**
654
+ * React hook for fetching available LLM models.
655
+ * Automatically fetches all available models.
656
+ * @category Hooks
657
+ */
658
+ declare function useModels(options?: UseModelsOptions): UseModelsResult;
659
+
660
+ /**
661
+ * Configuration for stream output smoothing.
662
+ *
663
+ * Controls the adaptive speed ramp that meters out streaming text
664
+ * at a consistent pace regardless of how fast the model produces tokens.
665
+ */
666
+ type StreamSmoothingConfig = {
667
+ /** Whether smoothing is enabled. Default: true */
668
+ enabled: boolean;
669
+ /** Minimum chars/sec at the start of streaming. Default: 60 */
670
+ minSpeed?: number;
671
+ /** Maximum chars/sec after ramp completes. Default: 600 */
672
+ maxSpeed?: number;
673
+ /** Duration in ms to ramp from minSpeed to maxSpeed. Default: 4000 */
674
+ rampDuration?: number;
675
+ };
676
+
677
+ /**
678
+ * Server tool call event emitted during streaming
679
+ */
680
+ type ServerToolCallEvent = {
681
+ /** Tool name (e.g., "BraveSearchMCP_brave_web_search") */
682
+ name: string;
683
+ /** Status: "started" when tool begins, "completed" when done */
684
+ status: "started" | "completed";
685
+ /** Arguments passed to the tool (JSON string) */
686
+ arguments?: string;
687
+ };
688
+
689
+ /**
690
+ * Tool executor function type
691
+ */
692
+ type ToolExecutor = (args: Record<string, unknown>) => Promise<unknown> | unknown;
693
+ /**
694
+ * Tool configuration with optional executor
695
+ */
696
+ type ToolConfig = LlmapiChatCompletionTool & {
697
+ /**
698
+ * Function to execute when the tool is called.
699
+ * If provided, the tool will be executed automatically when the LLM calls it.
700
+ * If not provided, an onToolCall event will be emitted instead.
701
+ */
702
+ executor?: ToolExecutor;
703
+ /**
704
+ * Whether to execute this tool automatically when called by the LLM.
705
+ * Default: true if executor is provided, false otherwise.
706
+ */
707
+ autoExecute?: boolean;
708
+ /**
709
+ * Whether to skip sending the tool result back to the model as a continuation.
710
+ * When true, the tool is executed but its result is not fed back to the model.
711
+ * Useful for display-only tools (charts, weather cards) that render client-side
712
+ * and don't need a model follow-up.
713
+ */
714
+ skipContinuation?: boolean;
715
+ /**
716
+ * Whether to remove this tool from the tools list after it has been
717
+ * successfully auto-executed. This prevents smaller models from calling
718
+ * the same tool repeatedly in continuation requests.
719
+ *
720
+ * Only applies when the tool is auto-executed (has an executor and
721
+ * autoExecute is not false). The tool is kept if execution fails,
722
+ * allowing the model to retry.
723
+ */
724
+ removeAfterExecution?: boolean;
725
+ };
726
+ /**
727
+ * Responses API options that can be passed to sendMessage
728
+ */
729
+ type ResponsesApiOptions = {
730
+ /**
731
+ * Controls randomness in the response (0.0 to 2.0).
732
+ * Lower values make output more deterministic.
733
+ */
734
+ temperature?: number;
735
+ /**
736
+ * Maximum number of tokens to generate in the response.
737
+ */
738
+ maxOutputTokens?: number;
739
+ /**
740
+ * Array of tool definitions available to the model.
741
+ * Can include executor functions for automatic tool execution.
742
+ */
743
+ tools?: Array<LlmapiChatCompletionTool | ToolConfig>;
744
+ /**
745
+ * Controls which tool to use: "auto", "any", "none", "required", or a specific tool name.
746
+ */
747
+ toolChoice?: string;
748
+ /**
749
+ * Reasoning configuration for o-series and other reasoning models.
750
+ * Controls reasoning effort and summary output.
751
+ */
752
+ reasoning?: LlmapiResponseReasoning;
753
+ /**
754
+ * Extended thinking configuration for Anthropic models (Claude).
755
+ * Enables the model to think through complex problems step by step.
756
+ */
757
+ thinking?: LlmapiThinkingOptions;
758
+ /** User-selected image generation model for server-side enforcement. */
759
+ imageModel?: string;
760
+ /**
761
+ * Maximum number of tool execution rounds before forcing the model to respond with text.
762
+ * After this many rounds, `toolChoice` is set to `"none"` on the next continuation,
763
+ * so the model produces a text answer using whatever tool results it has gathered.
764
+ * The absolute safety limit (MAX_TOOL_ITERATIONS = 10) still applies as a hard cap.
765
+ * @default 3
766
+ */
767
+ maxToolRounds?: number;
768
+ };
769
+ /**
770
+ * Base arguments for sending a message
771
+ */
772
+ type BaseSendMessageArgs = ResponsesApiOptions & {
773
+ messages: LlmapiMessage[];
774
+ model?: string;
775
+ /**
776
+ * Per-request callback for data chunks. Called in addition to the global
777
+ * `onData` callback if provided in `useChat` options.
778
+ *
779
+ * @param chunk - The content delta from the current chunk
780
+ */
781
+ onData?: (chunk: string) => void;
782
+ };
783
+ /**
784
+ * Base result type for sendMessage.
785
+ * Returns raw API response - either Responses API or Completions API format.
786
+ */
787
+ type BaseSendMessageResult = {
788
+ data: ApiResponse;
789
+ error: null;
790
+ } | {
791
+ data: null;
792
+ error: string;
793
+ };
794
+ /**
795
+ * Base options for useChat hook
796
+ * @inline
797
+ */
798
+ type BaseUseChatOptions = {
799
+ getToken?: () => Promise<string | null>;
800
+ baseUrl?: string;
801
+ /**
802
+ * Callback function to be called when a new data chunk is received.
803
+ */
804
+ onData?: (chunk: string) => void;
805
+ /**
806
+ * Callback function to be called when thinking/reasoning content is received.
807
+ * This is called with delta chunks as the model "thinks" through a problem.
808
+ */
809
+ onThinking?: (chunk: string) => void;
810
+ /**
811
+ * Callback function to be called when the chat completion finishes successfully.
812
+ * Receives raw API response - either Responses API or Completions API format.
813
+ */
814
+ onFinish?: (response: ApiResponse) => void;
815
+ /**
816
+ * Callback function to be called when an unexpected error is encountered.
817
+ *
818
+ * **Note:** This callback is NOT called for aborted requests (via `stop()` or
819
+ * component unmount). Aborts are intentional actions and are not considered
820
+ * errors. To detect aborts, check the `error` field in the `sendMessage` result:
821
+ * `result.error === "Request aborted"`.
822
+ *
823
+ * @param error - The error that occurred (never an AbortError)
824
+ */
825
+ onError?: (error: Error) => void;
826
+ /**
827
+ * Callback function to be called when a tool call is requested by the LLM.
828
+ * This is called for tools that don't have an executor or have autoExecute=false.
829
+ * The app should execute the tool and send the result back.
830
+ *
831
+ * @param toolCall - The tool call requested by the LLM
832
+ */
833
+ onToolCall?: (toolCall: LlmapiToolCall) => void;
834
+ /**
835
+ * Callback function to be called when a server-side tool (MCP) is invoked during streaming.
836
+ * Use this to show activity indicators like "Searching..." in the UI.
837
+ *
838
+ * @param toolCall - Info about the server tool being called
839
+ * @param toolCall.name - The tool name (e.g., "BraveSearchMCP_brave_web_search")
840
+ * @param toolCall.status - "started" when tool begins, "completed" when done
841
+ * @param toolCall.arguments - The arguments passed to the tool (JSON string)
842
+ */
843
+ onServerToolCall?: (toolCall: ServerToolCallEvent) => void;
844
+ /**
845
+ * Controls adaptive output smoothing for streaming responses.
846
+ * Fast models can return text faster than is comfortable to read — smoothing
847
+ * buffers incoming chunks and releases them at a consistent, adaptive pace.
848
+ *
849
+ * - `true` or omitted: enabled with defaults (200→400 chars/sec over 3s)
850
+ * - `false`: disabled, callbacks fire immediately with raw chunks
851
+ * - `StreamSmoothingConfig`: custom speed/ramp configuration
852
+ *
853
+ * @default true
854
+ */
855
+ smoothing?: StreamSmoothingConfig | boolean;
856
+ };
857
+ /**
858
+ * Base result type for useChat hook
859
+ */
860
+ type BaseUseChatResult = {
861
+ isLoading: boolean;
862
+ /**
863
+ * Aborts the current streaming request if one is in progress.
864
+ *
865
+ * When a request is aborted, `sendMessage` will return with
866
+ * `{ data: null, error: "Request aborted" }`. The `onError` callback
867
+ * will NOT be called, as aborts are intentional actions, not errors.
868
+ */
869
+ stop: () => void;
870
+ };
871
+
872
+ /**
873
+ * API type selector for useChat
874
+ * - "responses": OpenAI Responses API (supports thinking, reasoning, conversations)
875
+ * - "completions": OpenAI Chat Completions API (wider model compatibility)
876
+ */
877
+ type ApiType = "responses" | "completions";
878
+ /**
879
+ * Union type for API responses - raw pass-through from server.
880
+ * Responses API returns LlmapiResponseResponse (with output[]).
881
+ * Completions API returns LlmapiChatCompletionResponse (with choices[]).
882
+ */
883
+ type ApiResponse = LlmapiResponseResponse | LlmapiChatCompletionResponse;
884
+
885
+ type SendMessageArgs = BaseSendMessageArgs & {
886
+ /**
887
+ * Per-request callback for thinking/reasoning chunks.
888
+ */
889
+ onThinking?: (chunk: string) => void;
890
+ /**
891
+ * Memory context to inject as a system message.
892
+ * This is typically context from memory retrieval or other sources.
893
+ */
894
+ memoryContext?: string;
895
+ /**
896
+ * Search context to inject as a system message.
897
+ * This is typically formatted search results from useSearch.
898
+ */
899
+ searchContext?: string;
900
+ /**
901
+ * Override the API type for this request only.
902
+ * Useful when different models need different APIs.
903
+ * @default Uses the hook-level apiType or "responses"
904
+ */
905
+ apiType?: ApiType;
906
+ };
907
+ type SendMessageResult = BaseSendMessageResult;
908
+ /**
909
+ * @inline
910
+ */
911
+ interface UseChatOptions extends BaseUseChatOptions {
912
+ /**
913
+ * Which API endpoint to use. Default: "responses"
914
+ * - "responses": OpenAI Responses API (supports thinking, reasoning, conversations)
915
+ * - "completions": OpenAI Chat Completions API (wider model compatibility)
916
+ */
917
+ apiType?: ApiType;
918
+ }
919
+ type UseChatResult = BaseUseChatResult & {
920
+ sendMessage: (args: SendMessageArgs) => Promise<SendMessageResult>;
921
+ };
922
+ /**
923
+ * A React hook for managing chat completions with authentication.
924
+ *
925
+ * **React Native version** - This is a lightweight version that only supports
926
+ * API-based chat completions. Local chat and client-side tools are not available
927
+ * in React Native.
928
+ *
929
+ * @param options - Optional configuration object
930
+ * @param options.getToken - An async function that returns an authentication token.
931
+ * @param options.baseUrl - Optional base URL for the API requests.
932
+ * @param options.onData - Callback function to be called when a new data chunk is received.
933
+ * @param options.onFinish - Callback function to be called when the chat completion finishes successfully.
934
+ * @param options.onError - Callback function to be called when an unexpected error is encountered.
935
+ *
936
+ * @returns An object containing:
937
+ * - `isLoading`: A boolean indicating whether a request is currently in progress
938
+ * - `sendMessage`: An async function to send chat messages
939
+ * - `stop`: A function to abort the current request
940
+ *
941
+ * @category Hooks
942
+ *
943
+ * @example
944
+ * ```tsx
945
+ * const { isLoading, sendMessage, stop } = useChat({
946
+ * getToken: async () => await getAuthToken(),
947
+ * onFinish: (response) => console.log("Chat finished:", response),
948
+ * onError: (error) => console.error("Chat error:", error)
949
+ * });
950
+ *
951
+ * const handleSend = async () => {
952
+ * const result = await sendMessage({
953
+ * messages: [{ role: 'user', content: [{ type: 'text', text: 'Hello!' }] }],
954
+ * model: 'gpt-4o-mini'
955
+ * });
956
+ * };
957
+ * ```
958
+ */
959
+ declare function useChat(options?: UseChatOptions): UseChatResult;
960
+
961
+ /**
962
+ * Server-side tools caching module
963
+ *
964
+ * Fetches and caches tools from /api/v1/tools endpoint
965
+ * with configurable expiration and localStorage persistence.
966
+ */
967
+
968
+ /** Tool parameters schema */
969
+ interface ToolParameters {
970
+ properties: Record<string, unknown>;
971
+ required: string[];
972
+ type: "object";
973
+ }
974
+ /** Current API response format (description and parameters at top level) */
975
+ interface ServerToolsResponseItemCurrent {
976
+ description: string;
977
+ name: string;
978
+ parameters: ToolParameters;
979
+ }
980
+ /** New API response format with schema wrapper */
981
+ interface ServerToolsResponseItemNew {
982
+ name: string;
983
+ schema: {
984
+ name: string;
985
+ description: string;
986
+ parameters: ToolParameters;
987
+ };
988
+ cost?: number;
989
+ embedding?: number[];
990
+ }
991
+ /** Response item can be either format */
992
+ type ServerToolsResponseItem = ServerToolsResponseItemCurrent | ServerToolsResponseItemNew;
993
+ /** Tools object mapping tool names to their definitions */
994
+ type ServerToolsMap = {
995
+ [toolName: string]: ServerToolsResponseItem;
996
+ };
997
+ /**
998
+ * Response format from /api/v1/tools endpoint.
999
+ * New format includes checksum and tools wrapper.
1000
+ * Legacy format is just the tools map directly.
1001
+ */
1002
+ type ServerToolsResponse = {
1003
+ checksum: string;
1004
+ tools: ServerToolsMap;
1005
+ } | ServerToolsMap;
1006
+ /**
1007
+ * Server tool definition with parameters field.
1008
+ * This is the neutral format stored in cache.
1009
+ * Strategies transform this to the correct API format.
1010
+ */
1011
+ interface ServerTool {
1012
+ type: "function";
1013
+ name: string;
1014
+ description: string;
1015
+ parameters: {
1016
+ type: string;
1017
+ properties: Record<string, unknown>;
1018
+ required: string[];
1019
+ };
1020
+ /** Optional embedding vector for semantic matching */
1021
+ embedding?: number[];
1022
+ }
1023
+ /**
1024
+ * Cached tools structure stored in localStorage
1025
+ */
1026
+ interface CachedServerTools {
1027
+ tools: ServerTool[];
1028
+ timestamp: number;
1029
+ version: string;
1030
+ /** Checksum from the server for cache invalidation */
1031
+ checksum?: string;
1032
+ }
1033
+ /**
1034
+ * Options for fetching server tools
1035
+ */
1036
+ interface ServerToolsOptions {
1037
+ /** Base URL for the API (defaults to BASE_URL from clientConfig) */
1038
+ baseUrl?: string;
1039
+ /** Cache expiration time in milliseconds (default: 5 minutes) */
1040
+ cacheExpirationMs?: number;
1041
+ /** Force refresh even if cache is valid */
1042
+ forceRefresh?: boolean;
1043
+ /** Authentication token getter (uses Authorization: Bearer header) */
1044
+ getToken?: () => Promise<string | null>;
1045
+ /** Direct API key for server-side usage (uses X-API-Key header) */
1046
+ apiKey?: string;
1047
+ }
1048
+ /** Default cache expiration: 1 day */
1049
+ declare const DEFAULT_CACHE_EXPIRATION_MS: number;
1050
+ /**
1051
+ * Get cached tools from localStorage
1052
+ */
1053
+ declare function getCachedServerTools(): CachedServerTools | null;
1054
+ /**
1055
+ * Clear the server tools cache
1056
+ */
1057
+ declare function clearServerToolsCache(): void;
1058
+ /**
1059
+ * Get server tools with caching support.
1060
+ *
1061
+ * Flow:
1062
+ * 1. Check localStorage cache
1063
+ * 2. If cache valid and not force refresh, return cached tools
1064
+ * 3. Otherwise, fetch from API, cache, and return
1065
+ * 4. On fetch failure, return cached tools if available (stale-while-error)
1066
+ */
1067
+ declare function getServerTools(options: ServerToolsOptions): Promise<ServerTool[]>;
1068
+
1069
+ /**
1070
+ * Function type for dynamic server tools filtering based on prompt embeddings.
1071
+ * Receives the prompt embedding(s) and all available tools, returns tool names to include.
1072
+ *
1073
+ * @param embeddings - Single embedding or array of embeddings (for chunked messages)
1074
+ * @param tools - All available server tools with embeddings
1075
+ * @returns Array of tool names to include
1076
+ */
1077
+ type ServerToolsFilterFn = (embeddings: number[] | number[][], tools: ServerTool[]) => string[];
1078
+ /**
1079
+ * Server tools filter: static list of names or dynamic function.
1080
+ * - string[]: Static list of tool names to include
1081
+ * - ServerToolsFilterFn: Dynamic filter based on prompt embeddings
1082
+ */
1083
+ type ServerToolsFilter = string[] | ServerToolsFilterFn;
1084
+ /**
1085
+ * Function type for dynamic client tools filtering based on prompt embeddings.
1086
+ * Receives the prompt embedding(s) (or null for short messages where no embedding
1087
+ * was generated) and all client tools, returns tool names to include.
1088
+ *
1089
+ * @param embeddings - Single embedding, array of embeddings, or null (short message)
1090
+ * @param tools - All client tools passed to sendMessage
1091
+ * @returns Array of tool names to include
1092
+ */
1093
+ type ClientToolsFilterFn = (embeddings: number[] | number[][] | null, tools: any[]) => string[];
1094
+ type ChatRole = "user" | "assistant" | "system";
1095
+ /**
1096
+ * Feedback type for message like/dislike.
1097
+ * - 'like': User liked the response (thumbs up)
1098
+ * - 'dislike': User disliked the response (thumbs down)
1099
+ * - null/undefined: No feedback given
1100
+ */
1101
+ type MessageFeedback = "like" | "dislike" | null;
1102
+ /**
1103
+ * Metadata for files attached to messages.
1104
+ *
1105
+ * Note the distinction between `url` and `sourceUrl`:
1106
+ * - `url`: Content URL that gets sent to the AI as part of the message (e.g., data URIs for user uploads)
1107
+ * - `sourceUrl`: Original external URL for locally-cached files (for lookup only, never sent to AI)
1108
+ */
1109
+ interface FileMetadata {
1110
+ /** Unique identifier for the file (used as OPFS key for cached files) */
1111
+ id: string;
1112
+ /** Display name of the file */
1113
+ name: string;
1114
+ /** MIME type (e.g., "image/png") */
1115
+ type: string;
1116
+ /** File size in bytes */
1117
+ size: number;
1118
+ /**
1119
+ * Content URL to include when sending this message to the AI.
1120
+ * When present, this URL is added as an `image_url` content part.
1121
+ * Typically used for user-uploaded files (data URIs) that should be sent with the message.
1122
+ *
1123
+ * NOT used for MCP-cached files - those use `sourceUrl` for lookup and render from OPFS.
1124
+ */
1125
+ url?: string;
1126
+ /**
1127
+ * Original external URL for files downloaded and cached locally (e.g., from MCP R2).
1128
+ * Used purely for URL→OPFS mapping to enable fallback when the source returns 404.
1129
+ *
1130
+ * This is metadata for local lookup only - it is NOT sent to the AI or rendered directly.
1131
+ * The file content is served from OPFS using the `id` field.
1132
+ */
1133
+ sourceUrl?: string;
1134
+ }
1135
+ interface ChatCompletionUsage {
1136
+ promptTokens?: number;
1137
+ completionTokens?: number;
1138
+ totalTokens?: number;
1139
+ costMicroUsd?: number;
1140
+ creditsUsed?: number;
1141
+ }
1142
+ interface SearchSource {
1143
+ title?: string;
1144
+ url?: string;
1145
+ snippet?: string;
1146
+ date?: string;
1147
+ }
1148
+ interface StoredMessage {
1149
+ uniqueId: string;
1150
+ messageId: number;
1151
+ conversationId: string;
1152
+ role: ChatRole;
1153
+ content: string;
1154
+ model?: string;
1155
+ /** @deprecated Use fileIds with media table instead */
1156
+ files?: FileMetadata[];
1157
+ /** Array of media_id references for direct lookup in media table */
1158
+ fileIds?: string[];
1159
+ createdAt: Date;
1160
+ updatedAt: Date;
1161
+ vector?: number[];
1162
+ embeddingModel?: string;
1163
+ /** Chunks of this message with individual embeddings for fine-grained search */
1164
+ chunks?: MessageChunk[];
1165
+ usage?: ChatCompletionUsage;
1166
+ sources?: SearchSource[];
1167
+ responseDuration?: number;
1168
+ wasStopped?: boolean;
1169
+ /** If set, indicates the message failed with this error */
1170
+ error?: string;
1171
+ thoughtProcess?: ActivityPhase[];
1172
+ /** Reasoning/thinking content from models that support extended thinking */
1173
+ thinking?: string;
1174
+ /** Parent message ID for branching (edit/regenerate). Null for root messages. */
1175
+ parentMessageId?: string;
1176
+ /** User feedback: 'like', 'dislike', or null for no feedback */
1177
+ feedback?: MessageFeedback;
1178
+ }
1179
+ interface ActivityPhase {
1180
+ id: string;
1181
+ label: string;
1182
+ timestamp: number;
1183
+ status: "pending" | "active" | "completed";
1184
+ data?: unknown[];
1185
+ }
1186
+ interface StoredConversation {
1187
+ uniqueId: string;
1188
+ conversationId: string;
1189
+ title: string;
1190
+ /** Optional project ID this conversation belongs to */
1191
+ projectId?: string;
1192
+ createdAt: Date;
1193
+ updatedAt: Date;
1194
+ isDeleted: boolean;
1195
+ }
1196
+ interface StoredMessageWithSimilarity extends StoredMessage {
1197
+ similarity: number;
1198
+ }
1199
+ /**
1200
+ * A chunk of a message with its own embedding for fine-grained search
1201
+ */
1202
+ interface MessageChunk {
1203
+ /** The chunk text */
1204
+ text: string;
1205
+ /** Embedding vector for this chunk */
1206
+ vector: number[];
1207
+ /** Character offset where this chunk starts in the original message */
1208
+ startOffset: number;
1209
+ /** Character offset where this chunk ends in the original message */
1210
+ endOffset: number;
1211
+ }
1212
+ interface CreateMessageOptions {
1213
+ conversationId: string;
1214
+ role: ChatRole;
1215
+ content: string;
1216
+ model?: string;
1217
+ /** @deprecated Use fileIds with media table instead */
1218
+ files?: FileMetadata[];
1219
+ /** Array of media_id references for direct lookup in media table */
1220
+ fileIds?: string[];
1221
+ usage?: ChatCompletionUsage;
1222
+ sources?: SearchSource[];
1223
+ responseDuration?: number;
1224
+ vector?: number[];
1225
+ embeddingModel?: string;
1226
+ wasStopped?: boolean;
1227
+ /** If set, indicates the message failed with this error */
1228
+ error?: string;
1229
+ thoughtProcess?: ActivityPhase[];
1230
+ /** Reasoning/thinking content from models that support extended thinking */
1231
+ thinking?: string;
1232
+ /** Parent message ID for branching (edit/regenerate). */
1233
+ parentMessageId?: string;
1234
+ }
1235
+ interface CreateConversationOptions {
1236
+ conversationId?: string;
1237
+ title?: string;
1238
+ /** Optional project ID to associate this conversation with */
1239
+ projectId?: string;
1240
+ }
1241
+ /**
1242
+ * Base options for useChatStorage hook
1243
+ * @inline
1244
+ */
1245
+ interface BaseUseChatStorageOptions {
1246
+ /** WatermelonDB database instance for storing conversations and messages */
1247
+ database: Database;
1248
+ /** ID of an existing conversation to load and continue */
1249
+ conversationId?: string;
1250
+ /** Automatically create a new conversation if none is set (default: true) */
1251
+ autoCreateConversation?: boolean;
1252
+ /** Title for auto-created conversations (default: "New conversation") */
1253
+ defaultConversationTitle?: string;
1254
+ /** Function to retrieve the auth token for API requests */
1255
+ getToken?: () => Promise<string | null>;
1256
+ /** Base URL for the chat API endpoint */
1257
+ baseUrl?: string;
1258
+ /** Callback invoked with each streamed response chunk */
1259
+ onData?: (chunk: string) => void;
1260
+ /** Callback invoked when thinking/reasoning content is received (from `<think>` tags or API reasoning) */
1261
+ onThinking?: (chunk: string) => void;
1262
+ /** Callback invoked when the response completes successfully */
1263
+ onFinish?: (response: LlmapiResponseResponse) => void;
1264
+ /** Callback invoked when an error occurs during the request */
1265
+ onError?: (error: Error) => void;
1266
+ /**
1267
+ * Callback invoked when a server-side tool (MCP) is called during streaming.
1268
+ * Use this to show activity indicators like "Searching..." in the UI.
1269
+ */
1270
+ onServerToolCall?: (toolCall: ServerToolCallEvent) => void;
1271
+ /**
1272
+ * File preprocessors to use for automatic text extraction.
1273
+ * - undefined (default): Use all built-in processors (PDF, Excel, Word)
1274
+ * - null or []: Disable preprocessing
1275
+ * - FileProcessor[]: Use specific processors
1276
+ */
1277
+ fileProcessors?: any[] | null;
1278
+ /**
1279
+ * Options for file preprocessing behavior
1280
+ */
1281
+ fileProcessingOptions?: {
1282
+ /** Whether to keep original file attachments (default: true) */
1283
+ keepOriginalFiles?: boolean;
1284
+ /** Max file size to process in bytes (default: 10MB) */
1285
+ maxFileSizeBytes?: number;
1286
+ /** Callback for progress updates */
1287
+ onProgress?: (current: number, total: number, fileName: string) => void;
1288
+ /** Callback for errors (non-fatal) */
1289
+ onError?: (fileName: string, error: Error) => void;
1290
+ };
1291
+ /**
1292
+ * Configuration for server-side tools fetching and caching.
1293
+ * Server tools are fetched from /api/v1/tools and cached in localStorage.
1294
+ */
1295
+ serverTools?: {
1296
+ /** Cache expiration time in milliseconds (default: 86400000 = 1 day) */
1297
+ cacheExpirationMs?: number;
1298
+ };
1299
+ /**
1300
+ * Automatically generate embeddings for messages after saving.
1301
+ * Enables semantic search over past conversations via searchMessages().
1302
+ * @default true
1303
+ */
1304
+ autoEmbedMessages?: boolean;
1305
+ /**
1306
+ * Embedding model to use when autoEmbedMessages is enabled.
1307
+ * @default DEFAULT_API_EMBEDDING_MODEL
1308
+ */
1309
+ embeddingModel?: string;
1310
+ /**
1311
+ * Minimum content length required to generate embeddings.
1312
+ * Messages shorter than this are skipped as they provide limited semantic value.
1313
+ * @default 10
1314
+ */
1315
+ minContentLength?: number;
1316
+ /**
1317
+ * R2 domain for identifying MCP-generated image URLs.
1318
+ * When set, enables OPFS caching of generated images.
1319
+ * Defaults to the hardcoded MCP_R2_DOMAIN from clientConfig.
1320
+ */
1321
+ mcpR2Domain?: string;
1322
+ }
1323
+ /**
1324
+ * Base arguments for sending a message with automatic storage.
1325
+ *
1326
+ * These arguments control both the AI request and how the message
1327
+ * is persisted to the local database.
1328
+ * @inline
1329
+ */
1330
+ interface BaseSendMessageWithStorageArgs {
1331
+ /**
1332
+ * The message array to send to the AI.
1333
+ *
1334
+ * Uses the modern array format that supports multimodal content (text, images, files).
1335
+ * The last user message in this array will be extracted and stored in the database.
1336
+ *
1337
+ * When `includeHistory` is true (default), conversation history is prepended.
1338
+ * When `includeHistory` is false, only these messages are sent.
1339
+ *
1340
+ * @example
1341
+ * ```ts
1342
+ * // Simple usage
1343
+ * sendMessage({
1344
+ * messages: [
1345
+ * { role: "user", content: [{ type: "text", text: "Hello!" }] }
1346
+ * ]
1347
+ * })
1348
+ *
1349
+ * // With system prompt and history disabled
1350
+ * sendMessage({
1351
+ * messages: [
1352
+ * { role: "system", content: [{ type: "text", text: "You are helpful" }] },
1353
+ * { role: "user", content: [{ type: "text", text: "Question" }] },
1354
+ * ],
1355
+ * includeHistory: false
1356
+ * })
1357
+ *
1358
+ * // With images
1359
+ * sendMessage({
1360
+ * messages: [
1361
+ * { role: "user", content: [
1362
+ * { type: "text", text: "What's in this image?" },
1363
+ * { type: "image_url", image_url: { url: "data:image/png;base64,..." } }
1364
+ * ]}
1365
+ * ]
1366
+ * })
1367
+ * ```
1368
+ */
1369
+ messages: LlmapiMessage[];
1370
+ /**
1371
+ * The model identifier to use for this request (e.g., "gpt-4o", "claude-sonnet-4-20250514").
1372
+ * If not specified, uses the default model configured on the server.
1373
+ */
1374
+ model?: string;
1375
+ /**
1376
+ * Skip all storage operations (conversation, messages, embeddings, media).
1377
+ * Use this for one-off tasks like title generation where you don't want
1378
+ * to pollute the database with utility messages.
1379
+ *
1380
+ * When true:
1381
+ * - No conversation is created or required
1382
+ * - Messages are not stored in the database
1383
+ * - No embeddings are generated
1384
+ * - No media/files are processed for storage
1385
+ * - Result will not include userMessage or assistantMessage
1386
+ *
1387
+ * @default false
1388
+ *
1389
+ * @example
1390
+ * ```ts
1391
+ * // Generate a title without storing anything
1392
+ * const { data } = await sendMessage({
1393
+ * messages: [{ role: "user", content: [{ type: "text", text: "Generate a title for: ..." }] }],
1394
+ * skipStorage: true,
1395
+ * includeHistory: false,
1396
+ * });
1397
+ * ```
1398
+ */
1399
+ skipStorage?: boolean;
1400
+ /**
1401
+ * Whether to automatically include previous messages from the conversation as context.
1402
+ * When true, fetches stored messages and prepends them to the request.
1403
+ * Ignored if `messages` is provided.
1404
+ * @default true
1405
+ */
1406
+ includeHistory?: boolean;
1407
+ /**
1408
+ * Maximum number of historical messages to include when `includeHistory` is true.
1409
+ * Only the most recent N messages are included to manage context window size.
1410
+ * @default 50
1411
+ */
1412
+ maxHistoryMessages?: number;
1413
+ /**
1414
+ * File attachments to include with the message (images, documents, etc.).
1415
+ * Files with image MIME types and URLs are sent as image content parts.
1416
+ * File metadata is stored with the message (URLs are stripped if they're data URIs).
1417
+ */
1418
+ files?: FileMetadata[];
1419
+ /**
1420
+ * Per-request callback invoked with each streamed response chunk.
1421
+ * Overrides the hook-level `onData` callback for this request only.
1422
+ * Use this to update UI as the response streams in.
1423
+ */
1424
+ onData?: (chunk: string) => void;
1425
+ /**
1426
+ * Additional context from memory/RAG system to include in the request.
1427
+ * Typically contains retrieved relevant information from past conversations.
1428
+ */
1429
+ memoryContext?: string;
1430
+ /**
1431
+ * Additional context from search results to include in the request.
1432
+ * Typically contains relevant information from web or document searches.
1433
+ */
1434
+ searchContext?: string;
1435
+ /**
1436
+ * Additional context from preprocessed file attachments.
1437
+ * Contains extracted text from Excel, Word, PDF, and other document files.
1438
+ * Injected as a system message so it's available throughout the conversation.
1439
+ */
1440
+ fileContext?: string;
1441
+ /**
1442
+ * Search sources to attach to the stored message for citation/reference.
1443
+ * Note: Sources are also automatically extracted from tool_call_events in the response.
1444
+ */
1445
+ sources?: SearchSource[];
1446
+ /**
1447
+ * Activity phases for tracking the request lifecycle in the UI.
1448
+ * Each phase represents a step like "Searching", "Thinking", "Generating".
1449
+ * The final phase is automatically marked as completed when stored.
1450
+ *
1451
+ * Note: If you need activity phases that are added during streaming (e.g., server tool calls),
1452
+ * use `getThoughtProcess` callback instead, which captures phases AFTER streaming completes.
1453
+ */
1454
+ thoughtProcess?: ActivityPhase[];
1455
+ /**
1456
+ * Callback to get activity phases AFTER streaming completes.
1457
+ * Use this instead of `thoughtProcess` when phases are added dynamically during streaming
1458
+ * (e.g., via server tool call events like "Searching...", "Generating image...").
1459
+ *
1460
+ * If both `thoughtProcess` and `getThoughtProcess` are provided, `getThoughtProcess` takes precedence.
1461
+ */
1462
+ getThoughtProcess?: () => ActivityPhase[];
1463
+ /**
1464
+ * Controls randomness in the response (0.0 to 2.0).
1465
+ * Lower values make output more deterministic, higher values more creative.
1466
+ */
1467
+ temperature?: number;
1468
+ /**
1469
+ * Maximum number of tokens to generate in the response.
1470
+ * Use this to limit response length and control costs.
1471
+ */
1472
+ maxOutputTokens?: number;
1473
+ /**
1474
+ * Client-side tools with optional executors.
1475
+ * These tools run in the browser/app and can have JavaScript executor functions.
1476
+ */
1477
+ clientTools?: LlmapiChatCompletionTool[];
1478
+ /**
1479
+ * Server-side tools to include from /api/v1/tools.
1480
+ * - undefined: Include all server-side tools (default)
1481
+ * - string[]: Include only tools with these names
1482
+ * - []: Include no server-side tools
1483
+ * - function: Dynamic filter that receives prompt embedding(s) and all tools,
1484
+ * returns tool names to include. Useful for semantic tool matching.
1485
+ *
1486
+ * @example
1487
+ * // Include only specific server tools
1488
+ * serverTools: ["generate_cloud_image", "perplexity_search"]
1489
+ *
1490
+ * // Disable server tools for this request
1491
+ * serverTools: []
1492
+ *
1493
+ * // Semantic tool matching based on prompt
1494
+ * serverTools: (embeddings, tools) => {
1495
+ * const matches = findMatchingTools(embeddings, tools, { limit: 5 });
1496
+ * return matches.map(m => m.tool.name);
1497
+ * }
1498
+ */
1499
+ serverTools?: ServerToolsFilter;
1500
+ /**
1501
+ * Dynamic filter for client-side tools based on prompt embeddings.
1502
+ * Receives the prompt embedding(s) (or null for short messages) and all client tools,
1503
+ * returns tool names to include. Tools not in the returned list are excluded from the request.
1504
+ *
1505
+ * @example
1506
+ * clientToolsFilter: (embeddings, tools) => {
1507
+ * if (!embeddings) return []; // Short message — no client tools
1508
+ * const matches = findMatchingTools(embeddings, pseudoServerTools);
1509
+ * return matches.map(m => m.tool.name);
1510
+ * }
1511
+ */
1512
+ clientToolsFilter?: ClientToolsFilterFn;
1513
+ /**
1514
+ * Controls which tool the model should use:
1515
+ * - "auto": Model decides whether to use a tool (default)
1516
+ * - "any": Model must use one of the provided tools
1517
+ * - "none": Model cannot use any tools
1518
+ * - "required": Model must use a tool
1519
+ * - Specific tool name: Model must use that specific tool
1520
+ */
1521
+ toolChoice?: string;
1522
+ /**
1523
+ * Maximum number of tool execution rounds before forcing the model to respond with text.
1524
+ * After this many rounds, `toolChoice` is set to `"none"` on the next continuation,
1525
+ * so the model produces a text answer using whatever tool results it has gathered.
1526
+ * @default 3
1527
+ */
1528
+ maxToolRounds?: number;
1529
+ /**
1530
+ * Reasoning configuration for o-series and other reasoning models.
1531
+ * Controls reasoning effort level and whether to include reasoning summary.
1532
+ */
1533
+ reasoning?: LlmapiResponseReasoning;
1534
+ /**
1535
+ * Extended thinking configuration for Anthropic models (Claude).
1536
+ * Enables the model to think through complex problems step by step
1537
+ * before generating the final response.
1538
+ */
1539
+ thinking?: LlmapiThinkingOptions;
1540
+ /** User-selected image generation model for server-side enforcement. */
1541
+ imageModel?: string;
1542
+ /**
1543
+ * Per-request callback for thinking/reasoning chunks.
1544
+ * Called with delta chunks as the model "thinks" through a problem.
1545
+ * Use this to display thinking progress in the UI.
1546
+ */
1547
+ onThinking?: (chunk: string) => void;
1548
+ /** Parent message ID for branching (edit/regenerate). Sets on the user message. */
1549
+ parentMessageId?: string;
1550
+ }
1551
+ interface BaseSendMessageSuccessResult {
1552
+ data: LlmapiResponseResponse;
1553
+ error: null;
1554
+ userMessage: StoredMessage;
1555
+ assistantMessage: StoredMessage;
1556
+ }
1557
+ interface BaseSendMessageSkippedResult {
1558
+ data: LlmapiResponseResponse;
1559
+ error: null;
1560
+ userMessage?: undefined;
1561
+ assistantMessage?: undefined;
1562
+ /** Indicates this was a skipStorage request - no messages were persisted */
1563
+ skipped: true;
1564
+ }
1565
+ interface BaseSendMessageErrorResult {
1566
+ data: null;
1567
+ error: string;
1568
+ userMessage?: StoredMessage;
1569
+ assistantMessage?: undefined;
1570
+ }
1571
+ type BaseSendMessageWithStorageResult = BaseSendMessageSuccessResult | BaseSendMessageSkippedResult | BaseSendMessageErrorResult;
1572
+ interface BaseUseChatStorageResult {
1573
+ isLoading: boolean;
1574
+ stop: () => void;
1575
+ conversationId: string | null;
1576
+ setConversationId: (id: string | null) => void;
1577
+ createConversation: (options?: CreateConversationOptions) => Promise<StoredConversation>;
1578
+ getConversation: (id: string) => Promise<StoredConversation | null>;
1579
+ getConversations: () => Promise<StoredConversation[]>;
1580
+ updateConversationTitle: (id: string, title: string) => Promise<boolean>;
1581
+ deleteConversation: (id: string) => Promise<boolean>;
1582
+ getMessages: (conversationId: string) => Promise<StoredMessage[]>;
1583
+ }
1584
+ declare function generateConversationId(): string;
1585
+
1586
+ declare class Message extends Model {
1587
+ static table: string;
1588
+ static associations: Associations;
1589
+ messageId: number;
1590
+ conversationId: string;
1591
+ role: ChatRole;
1592
+ content: string;
1593
+ model?: string;
1594
+ /** @deprecated Use fileIds with media table instead */
1595
+ files?: FileMetadata[];
1596
+ /** Array of media_id references for direct lookup */
1597
+ fileIds?: string[];
1598
+ createdAt: Date;
1599
+ updatedAt: Date;
1600
+ vector?: number[];
1601
+ embeddingModel?: string;
1602
+ chunks?: MessageChunk[];
1603
+ usage?: ChatCompletionUsage;
1604
+ sources?: SearchSource[];
1605
+ responseDuration?: number;
1606
+ wasStopped?: boolean;
1607
+ error?: string;
1608
+ thoughtProcess?: ActivityPhase[];
1609
+ thinking?: string;
1610
+ parentMessageId?: string;
1611
+ feedback?: MessageFeedback;
1612
+ }
1613
+ declare class Conversation extends Model {
1614
+ static table: string;
1615
+ static associations: Associations;
1616
+ conversationId: string;
1617
+ title: string;
1618
+ projectId?: string;
1619
+ createdAt: Date;
1620
+ updatedAt: Date;
1621
+ isDeleted: boolean;
1622
+ }
1623
+
1624
+ /**
1625
+ * Register a callback that fires when an encryption key becomes available for an address.
1626
+ * If the key is already available, the callback fires immediately.
1627
+ * @returns Unsubscribe function
1628
+ */
1629
+ declare function onKeyAvailable(address: string, callback: () => void): () => void;
1630
+ /**
1631
+ * Clears the encryption key for a wallet address from memory
1632
+ * @param address - The wallet address
1633
+ */
1634
+ declare function clearEncryptionKey(address: string): void;
1635
+ /**
1636
+ * Clears all encryption keys from memory
1637
+ */
1638
+ declare function clearAllEncryptionKeys(): void;
1639
+ /**
1640
+ * Checks if an encryption key exists in memory for the given wallet address
1641
+ */
1642
+ declare function hasEncryptionKey(address: string): boolean;
1643
+ /**
1644
+ * Options for signing messages.
1645
+ */
1646
+ interface SignMessageOptions {
1647
+ /** Whether to show wallet UI during signing. Default: true */
1648
+ showWalletUIs?: boolean;
1649
+ }
1650
+ /**
1651
+ * Type for the signMessage function that client must provide.
1652
+ * This is typically from Privy's useSignMessage hook.
1653
+ */
1654
+ type SignMessageFn = (message: string, options?: SignMessageOptions) => Promise<string>;
1655
+ /**
1656
+ * Type for embedded wallet signer function that enables silent signing.
1657
+ * For Privy embedded wallets, this can sign programmatically without user interaction
1658
+ * when configured correctly in the Privy dashboard.
1659
+ */
1660
+ type EmbeddedWalletSignerFn = (message: string, options?: SignMessageOptions) => Promise<string>;
1661
+ /**
1662
+ * Requests the user to sign a message to generate an encryption key.
1663
+ * If a key already exists in memory for the given wallet, resolves immediately.
1664
+ *
1665
+ * Note: Keys are stored in memory only and do not persist across page reloads.
1666
+ * This is a security feature - users must sign once per session to derive their key.
1667
+ *
1668
+ * @param walletAddress - The wallet address to generate the key for
1669
+ * @param signMessage - Function to sign a message (returns signature hex string)
1670
+ * @param embeddedWalletSigner - Optional function for silent signing with embedded wallets
1671
+ * @returns Promise that resolves when the key is available
1672
+ */
1673
+ declare function requestEncryptionKey(walletAddress: string, signMessage: SignMessageFn, embeddedWalletSigner?: EmbeddedWalletSignerFn): Promise<void>;
1674
+ /**
1675
+ * Result returned by the useEncryption hook.
1676
+ * @category Hooks
1677
+ */
1678
+ interface UseEncryptionResult {
1679
+ /** Request and generate an encryption key for a wallet address */
1680
+ requestEncryptionKey: (walletAddress: string) => Promise<void>;
1681
+ /** Request and generate an ECDH key pair for a wallet address */
1682
+ requestKeyPair: (walletAddress: string) => Promise<void>;
1683
+ /** Export the public key for a wallet address as base64-encoded SPKI */
1684
+ exportPublicKey: (walletAddress: string) => Promise<string>;
1685
+ /** Check if a key pair exists in memory for a wallet address */
1686
+ hasKeyPair: (walletAddress: string) => boolean;
1687
+ /** Clear the key pair for a wallet address from memory */
1688
+ clearKeyPair: (walletAddress: string) => void;
1689
+ }
1690
+ /**
1691
+ * Hook that provides encryption key management for securing local data.
1692
+ *
1693
+ * This hook helps you encrypt and decrypt data using a key derived from a wallet
1694
+ * signature. It requires `@privy-io/react-auth` for wallet authentication. Keys are
1695
+ * stored in memory only and do not persist across page reloads for security.
1696
+ *
1697
+ * ## How it works
1698
+ *
1699
+ * 1. User signs a message with their wallet
1700
+ * 2. The signature is used to deterministically derive an encryption key
1701
+ * 3. The key is stored in memory (not localStorage) for the session
1702
+ * 4. Data can be encrypted/decrypted using this key
1703
+ * 5. On page reload, user must sign again to derive the key
1704
+ *
1705
+ * ## Security Features
1706
+ *
1707
+ * - **In-memory only**: Keys never touch disk or localStorage
1708
+ * - **Deterministic**: Same wallet + signature always generates same key
1709
+ * - **Session-scoped**: Keys cleared on page reload
1710
+ * - **XSS-resistant**: Keys not accessible after page reload
1711
+ *
1712
+ * ## Embedded Wallet Support
1713
+ *
1714
+ * For Privy embedded wallets, you can provide an `embeddedWalletSigner` function
1715
+ * to enable silent signing without user confirmation modals. This is useful for
1716
+ * deterministic key generation that should happen automatically.
1717
+ *
1718
+ * @param signMessage - Function to sign a message (from Privy's useSignMessage hook)
1719
+ * @param embeddedWalletSigner - Optional function for silent signing with embedded wallets
1720
+ * @returns Functions to request encryption keys and manage key pairs
1721
+ *
1722
+ * @example
1723
+ * ```tsx
1724
+ * import { usePrivy, useWallets } from "@privy-io/react-auth";
1725
+ * import { useEncryption, encryptData, decryptData } from "@anuma/sdk/react";
1726
+ *
1727
+ * function SecureComponent() {
1728
+ * const { user, signMessage } = usePrivy();
1729
+ * const { wallets } = useWallets();
1730
+ * const embeddedWallet = wallets.find(w => w.walletClientType === 'privy');
1731
+ *
1732
+ * // Create silent signer for embedded wallets
1733
+ * const embeddedSigner = useCallback(async (message: string) => {
1734
+ * if (embeddedWallet) {
1735
+ * const { signature } = await embeddedWallet.signMessage({ message });
1736
+ * return signature;
1737
+ * }
1738
+ * throw new Error('No embedded wallet');
1739
+ * }, [embeddedWallet]);
1740
+ *
1741
+ * const { requestEncryptionKey } = useEncryption(signMessage, embeddedSigner);
1742
+ *
1743
+ * // Request encryption key when user is authenticated
1744
+ * useEffect(() => {
1745
+ * if (user?.wallet?.address) {
1746
+ * // This will use silent signing for embedded wallets
1747
+ * await requestEncryptionKey(user.wallet.address);
1748
+ * }
1749
+ * }, [user]);
1750
+ *
1751
+ * // Encrypt data
1752
+ * const saveSecret = async (text: string) => {
1753
+ * const encrypted = await encryptData(text, user.wallet.address);
1754
+ * localStorage.setItem("mySecret", encrypted);
1755
+ * };
1756
+ *
1757
+ * // Decrypt data
1758
+ * const loadSecret = async () => {
1759
+ * const encrypted = localStorage.getItem("mySecret");
1760
+ * if (encrypted) {
1761
+ * const decrypted = await decryptData(encrypted, user.wallet.address);
1762
+ * console.log(decrypted);
1763
+ * }
1764
+ * };
1765
+ *
1766
+ * return (
1767
+ * <div>
1768
+ * <button onClick={() => saveSecret("my secret data")}>Encrypt & Save</button>
1769
+ * <button onClick={loadSecret}>Load & Decrypt</button>
1770
+ * </div>
1771
+ * );
1772
+ * }
1773
+ * ```
1774
+ *
1775
+ * @example
1776
+ * ```tsx
1777
+ * // Standard usage with external wallets (shows confirmation modal)
1778
+ * import { usePrivy } from "@privy-io/react-auth";
1779
+ * import { useEncryption, encryptData, decryptData } from "@anuma/sdk/react";
1780
+ *
1781
+ * function SecureComponent() {
1782
+ * const { user, signMessage } = usePrivy();
1783
+ * const { requestEncryptionKey } = useEncryption(signMessage);
1784
+ *
1785
+ * // Request encryption key when user is authenticated
1786
+ * useEffect(() => {
1787
+ * if (user?.wallet?.address) {
1788
+ * // This will prompt user to sign if key doesn't exist
1789
+ * await requestEncryptionKey(user.wallet.address);
1790
+ * }
1791
+ * }, [user]);
1792
+ * }
1793
+ * ```
1794
+ *
1795
+ * @example
1796
+ * ```tsx
1797
+ * // ECDH key pair generation for end-to-end encryption
1798
+ * import { usePrivy } from "@privy-io/react-auth";
1799
+ * import { useEncryption } from "@anuma/sdk/react";
1800
+ *
1801
+ * function E2EEComponent() {
1802
+ * const { signMessage } = usePrivy();
1803
+ * const { requestKeyPair, exportPublicKey } = useEncryption(signMessage);
1804
+ *
1805
+ * const setupEncryption = async (walletAddress: string) => {
1806
+ * // Generate deterministic ECDH key pair from wallet signature
1807
+ * await requestKeyPair(walletAddress);
1808
+ *
1809
+ * // Export public key to share with others
1810
+ * const publicKey = await exportPublicKey(walletAddress);
1811
+ * console.log("Share this public key:", publicKey);
1812
+ * };
1813
+ * }
1814
+ * ```
1815
+ *
1816
+ * @category Hooks
1817
+ */
1818
+ declare function useEncryption(signMessage: SignMessageFn, embeddedWalletSigner?: EmbeddedWalletSignerFn): UseEncryptionResult;
1819
+
1820
+ interface StorageOperationsContext {
1821
+ database: Database;
1822
+ messagesCollection: Collection<Message>;
1823
+ conversationsCollection: Collection<Conversation>;
1824
+ /** Wallet address for encryption (optional - when present, enables field-level encryption) */
1825
+ walletAddress?: string;
1826
+ /** Function to sign a message for encryption key derivation */
1827
+ signMessage?: SignMessageFn;
1828
+ /** Function for silent signing with embedded wallets */
1829
+ embeddedWalletSigner?: EmbeddedWalletSignerFn;
1830
+ }
1831
+
1832
+ declare const chatStorageSchema: Readonly<{
1833
+ version: _nozbe_watermelondb_Schema.SchemaVersion;
1834
+ tables: _nozbe_watermelondb_Schema.TableMap;
1835
+ unsafeSql?: (_: string, __: _nozbe_watermelondb_Schema.AppSchemaUnsafeSqlKind) => string;
1836
+ }>;
1837
+ declare const chatStorageMigrations: Readonly<{
1838
+ validated: true;
1839
+ minVersion: _nozbe_watermelondb_Schema.SchemaVersion;
1840
+ maxVersion: _nozbe_watermelondb_Schema.SchemaVersion;
1841
+ sortedMigrations: _nozbe_watermelondb_Schema_migrations.Migration[];
1842
+ }>;
1843
+
1844
+ declare class VaultMemory extends Model {
1845
+ static table: string;
1846
+ content: string;
1847
+ scope: string;
1848
+ createdAt: Date;
1849
+ updatedAt: Date;
1850
+ isDeleted: boolean;
1851
+ }
1852
+
1853
+ interface StoredVaultMemory {
1854
+ /** WatermelonDB internal ID */
1855
+ uniqueId: string;
1856
+ /** Plain text memory content */
1857
+ content: string;
1858
+ /** Scope for partitioning memories (e.g., "private", "shared") */
1859
+ scope: string;
1860
+ createdAt: Date;
1861
+ updatedAt: Date;
1862
+ isDeleted: boolean;
1863
+ }
1864
+ interface CreateVaultMemoryOptions {
1865
+ content: string;
1866
+ /** Scope for the memory. Defaults to "private" if omitted. */
1867
+ scope?: string;
1868
+ }
1869
+ interface UpdateVaultMemoryOptions {
1870
+ content: string;
1871
+ /** If provided, updates the memory's scope. */
1872
+ scope?: string;
1873
+ }
1874
+
1875
+ interface VaultMemoryOperationsContext {
1876
+ database: Database;
1877
+ vaultMemoryCollection: Collection<VaultMemory>;
1878
+ walletAddress?: string;
1879
+ signMessage?: SignMessageFn;
1880
+ embeddedWalletSigner?: EmbeddedWalletSignerFn;
1881
+ }
1882
+ declare function createVaultMemoryOp(ctx: VaultMemoryOperationsContext, opts: CreateVaultMemoryOptions): Promise<StoredVaultMemory>;
1883
+ declare function getVaultMemoryOp(ctx: VaultMemoryOperationsContext, id: string): Promise<StoredVaultMemory | null>;
1884
+ declare function getAllVaultMemoriesOp(ctx: VaultMemoryOperationsContext, options?: {
1885
+ scopes?: string[];
1886
+ }): Promise<StoredVaultMemory[]>;
1887
+ declare function updateVaultMemoryOp(ctx: VaultMemoryOperationsContext, id: string, opts: UpdateVaultMemoryOptions): Promise<StoredVaultMemory | null>;
1888
+ declare function deleteVaultMemoryOp(ctx: VaultMemoryOperationsContext, id: string): Promise<boolean>;
1889
+
1890
+ /**
1891
+ * Queue Types
1892
+ *
1893
+ * Types for the in-memory write queue that holds operations
1894
+ * when encryption keys aren't yet available.
1895
+ */
1896
+
1897
+ /**
1898
+ * Types of database operations that can be queued.
1899
+ */
1900
+ type QueuedOperationType = "createConversation" | "updateConversationTitle" | "createMessage" | "updateMessage" | "createMedia" | "createMediaBatch" | "updateMediaMessageId";
1901
+ /**
1902
+ * A single queued database operation.
1903
+ */
1904
+ interface QueuedOperation {
1905
+ /** Unique ID for this operation */
1906
+ id: string;
1907
+ /** Type of operation */
1908
+ type: QueuedOperationType;
1909
+ /** Wallet address this operation belongs to */
1910
+ walletAddress: string;
1911
+ /** When the operation was queued */
1912
+ timestamp: number;
1913
+ /** Priority for ordering (lower = higher priority). Conversations=0, Messages=1, Media=2 */
1914
+ priority: number;
1915
+ /** IDs of operations that must complete before this one */
1916
+ dependencies: string[];
1917
+ /** Operation-specific payload */
1918
+ payload: Record<string, any>;
1919
+ /** Number of times this operation has been retried */
1920
+ retryCount: number;
1921
+ /** Maximum number of retries allowed */
1922
+ maxRetries: number;
1923
+ }
1924
+ /**
1925
+ * Status of a wallet's queue.
1926
+ */
1927
+ interface QueueStatus {
1928
+ /** Number of pending operations */
1929
+ pending: number;
1930
+ /** Number of operations that failed all retries */
1931
+ failed: number;
1932
+ /** Whether the queue is currently being flushed */
1933
+ isFlushing: boolean;
1934
+ /** Whether the queue is paused (e.g., wallet disconnected) */
1935
+ isPaused: boolean;
1936
+ }
1937
+ /**
1938
+ * Result of a flush operation.
1939
+ */
1940
+ interface FlushResult {
1941
+ /** IDs of operations that succeeded */
1942
+ succeeded: string[];
1943
+ /** Operations that failed with their errors */
1944
+ failed: Array<{
1945
+ id: string;
1946
+ error: string;
1947
+ }>;
1948
+ /** Total number of operations attempted */
1949
+ total: number;
1950
+ }
1951
+ /**
1952
+ * Encryption context needed to execute queued operations.
1953
+ */
1954
+ interface QueueEncryptionContext {
1955
+ walletAddress: string;
1956
+ signMessage: SignMessageFn;
1957
+ embeddedWalletSigner?: EmbeddedWalletSignerFn;
1958
+ }
1959
+ /**
1960
+ * Executor function that runs a single queued operation.
1961
+ * Provided by the consumer (e.g., useChatStorage) during flush.
1962
+ */
1963
+ type OperationExecutor = (operation: QueuedOperation, encryptionContext: QueueEncryptionContext) => Promise<void>;
1964
+
1965
+ /**
1966
+ * Queue Manager
1967
+ *
1968
+ * In-memory queue for database operations when encryption keys aren't yet available.
1969
+ * Operations are held in memory and flushed to the database once the key becomes available.
1970
+ *
1971
+ * Key design decisions:
1972
+ * - In-memory only: queue is lost on page refresh (acceptable since user must re-auth anyway)
1973
+ * - Per-wallet isolation: each wallet has its own queue
1974
+ * - Dependency tracking: operations are flushed in correct order (conversation before messages)
1975
+ * - Max 1000 operations per wallet to prevent memory leaks
1976
+ */
1977
+
1978
+ declare class QueueManager {
1979
+ /** Per-wallet operation queues: wallet address -> operation id -> operation */
1980
+ private queues;
1981
+ /** Per-wallet flushing state */
1982
+ private flushing;
1983
+ /** Per-wallet paused state */
1984
+ private paused;
1985
+ /** Per-wallet failed operations (exceeded max retries) */
1986
+ private failedOps;
1987
+ /** Change listeners: wallet address -> callbacks */
1988
+ private listeners;
1989
+ /**
1990
+ * Queue a new operation for a wallet.
1991
+ * @returns The operation ID, or null if queue is full.
1992
+ */
1993
+ queueOperation(walletAddress: string, type: QueuedOperationType, payload: Record<string, any>, dependencies?: string[], maxRetries?: number): string | null;
1994
+ /**
1995
+ * Get all pending operations for a wallet, sorted by dependency order.
1996
+ */
1997
+ getOperations(walletAddress: string): QueuedOperation[];
1998
+ /**
1999
+ * Remove a specific operation from the queue.
2000
+ */
2001
+ removeOperation(walletAddress: string, operationId: string): void;
2002
+ /**
2003
+ * Get the status of a wallet's queue.
2004
+ */
2005
+ getStatus(walletAddress: string): QueueStatus;
2006
+ /**
2007
+ * Flush all queued operations for a wallet by executing them with encryption.
2008
+ *
2009
+ * @param encryptionContext - Wallet address and signing functions for encryption
2010
+ * @param executor - Function that executes each operation against the database
2011
+ * @returns Result with succeeded/failed operation IDs
2012
+ */
2013
+ flush(encryptionContext: QueueEncryptionContext, executor: OperationExecutor): Promise<FlushResult>;
2014
+ /**
2015
+ * Clear all queued operations for a wallet.
2016
+ */
2017
+ clear(walletAddress: string): void;
2018
+ /**
2019
+ * Pause the queue for a wallet (stops flush mid-way).
2020
+ */
2021
+ pause(walletAddress: string): void;
2022
+ /**
2023
+ * Resume the queue for a wallet.
2024
+ */
2025
+ resume(walletAddress: string): void;
2026
+ /**
2027
+ * Register a listener for queue changes on a wallet.
2028
+ * @returns Unsubscribe function
2029
+ */
2030
+ onQueueChange(walletAddress: string, callback: () => void): () => void;
2031
+ /**
2032
+ * Check if a wallet has any pending operations.
2033
+ */
2034
+ hasPending(walletAddress: string): boolean;
2035
+ /** Move a failed operation to the failed set. */
2036
+ private moveToFailed;
2037
+ /** Notify all listeners for a wallet. */
2038
+ private notifyListeners;
2039
+ }
2040
+ /** Singleton queue manager instance */
2041
+ declare const queueManager: QueueManager;
2042
+
2043
+ /**
2044
+ * Wallet Poller
2045
+ *
2046
+ * Polls for embedded wallet availability during Privy initialization.
2047
+ * When a wallet becomes available, triggers a callback so the queue can flush.
2048
+ */
2049
+ declare class WalletPoller {
2050
+ private timerId;
2051
+ private attempts;
2052
+ /**
2053
+ * Start polling for wallet availability.
2054
+ *
2055
+ * @param checkWallet - Returns wallet address when ready, null if not yet available
2056
+ * @param onWalletReady - Called with the wallet address when it becomes available
2057
+ * @param intervalMs - Polling interval in milliseconds (default: 1000ms)
2058
+ * @param maxAttempts - Maximum polling attempts before giving up (default: 60)
2059
+ * @returns Stop function to cancel polling
2060
+ */
2061
+ startPolling(checkWallet: () => Promise<string | null>, onWalletReady: (address: string) => void, intervalMs?: number, maxAttempts?: number): () => void;
2062
+ /**
2063
+ * Stop polling.
2064
+ */
2065
+ stop(): void;
2066
+ }
2067
+
2068
+ /**
2069
+ * Memory Retrieval Types
2070
+ *
2071
+ * Types for the memory retrieval feature that allows semantic search
2072
+ * across past conversation messages.
2073
+ */
2074
+ /**
2075
+ * Options for memory retrieval search
2076
+ */
2077
+ interface MemoryRetrievalSearchOptions {
2078
+ /** Maximum number of results to return (default: 8) */
2079
+ limit?: number;
2080
+ /** Alias for limit - number of chunks to return (default: 8) */
2081
+ topK?: number;
2082
+ /** Minimum similarity threshold 0-1 (default: 0.3) */
2083
+ minSimilarity?: number;
2084
+ /** Include assistant messages in results (default: false) */
2085
+ includeAssistant?: boolean;
2086
+ /** Filter to a specific conversation */
2087
+ conversationId?: string;
2088
+ /** Exclude messages from this conversation (e.g., the current conversation) */
2089
+ excludeConversationId?: string;
2090
+ /** Inclusive start date filter (currently disabled) */
2091
+ startDate?: string;
2092
+ /** Inclusive end date filter (currently disabled) */
2093
+ endDate?: string;
2094
+ /** Sort order for results: "similarity" (most relevant first) or "chronological" (oldest first). Default: "similarity" */
2095
+ sortBy?: "similarity" | "chronological";
2096
+ }
2097
+ /**
2098
+ * A retrieved message with similarity score
2099
+ */
2100
+ interface MemoryRetrievalResult {
2101
+ /** Message content */
2102
+ content: string;
2103
+ /** Role of the message sender */
2104
+ role: "user" | "assistant";
2105
+ /** Conversation this message belongs to */
2106
+ conversationId: string;
2107
+ /** Cosine similarity score (0-1) */
2108
+ similarity: number;
2109
+ /** When the message was created */
2110
+ createdAt: Date;
2111
+ /** Unique message ID */
2112
+ uniqueId: string;
2113
+ }
2114
+ /**
2115
+ * Options for embedding generation
2116
+ *
2117
+ * Supports two auth methods:
2118
+ * - `getToken`: For Privy identity tokens (uses Authorization: Bearer header)
2119
+ * - `apiKey`: For direct API keys (uses X-API-Key header)
2120
+ *
2121
+ * At least one of `getToken` or `apiKey` must be provided.
2122
+ */
2123
+ interface EmbeddingOptions {
2124
+ /** Function to get auth token (e.g., Privy's getIdentityToken). Uses Authorization: Bearer header. */
2125
+ getToken?: () => Promise<string | null>;
2126
+ /** Direct API key for server-side usage. Uses X-API-Key header. */
2127
+ apiKey?: string;
2128
+ /** Base URL for the API */
2129
+ baseUrl?: string;
2130
+ /** Embedding model to use */
2131
+ model?: string;
2132
+ }
2133
+
2134
+ /**
2135
+ * Memory Retrieval Embeddings
2136
+ *
2137
+ * Functions for generating and storing embeddings for conversation messages.
2138
+ */
2139
+
2140
+ /**
2141
+ * Generate an embedding for text using the API
2142
+ *
2143
+ * Supports two auth methods:
2144
+ * - `apiKey`: Uses X-API-Key header (for server-side/CLI usage)
2145
+ * - `getToken`: Uses Authorization: Bearer header (for Privy identity tokens)
2146
+ */
2147
+ declare function generateEmbedding(text: string, options: EmbeddingOptions): Promise<number[]>;
2148
+ /**
2149
+ * Generate embeddings for multiple texts in a single API call
2150
+ *
2151
+ * More efficient than calling generateEmbedding multiple times.
2152
+ * Supports the same auth methods as generateEmbedding.
2153
+ *
2154
+ * @param texts - Array of texts to embed
2155
+ * @param options - Embedding options
2156
+ * @returns Array of embeddings in the same order as input texts
2157
+ */
2158
+ declare function generateEmbeddings(texts: string[], options: EmbeddingOptions): Promise<number[][]>;
2159
+ /**
2160
+ * Embed a single message and store the embedding in the database
2161
+ *
2162
+ * @param ctx - Storage operations context
2163
+ * @param messageId - Unique ID of the message to embed
2164
+ * @param options - Embedding options
2165
+ * @returns The updated message with embedding, or null if message not found
2166
+ */
2167
+ declare function embedMessage(ctx: StorageOperationsContext, messageId: string, options: EmbeddingOptions): Promise<StoredMessage | null>;
2168
+ /**
2169
+ * Embed all messages without embeddings in the database
2170
+ *
2171
+ * @param ctx - Storage operations context
2172
+ * @param options - Embedding options
2173
+ * @param filter - Optional filter for which messages to embed
2174
+ * @returns Number of messages embedded
2175
+ */
2176
+ declare function embedAllMessages(ctx: StorageOperationsContext, options: EmbeddingOptions, filter?: {
2177
+ /** Only embed messages from this conversation */
2178
+ conversationId?: string;
2179
+ /** Only embed messages with these roles */
2180
+ roles?: ("user" | "assistant")[];
2181
+ /** Minimum content length to embed (default: 30). Shorter messages are skipped. */
2182
+ minContentLength?: number;
2183
+ }): Promise<number>;
2184
+
2185
+ /**
2186
+ * Memory Retrieval Tool
2187
+ *
2188
+ * Provides a tool for LLMs to search through past conversation messages
2189
+ * using semantic similarity.
2190
+ */
2191
+
2192
+ /**
2193
+ * Creates a memory retrieval tool for use with chat completions.
2194
+ *
2195
+ * The tool allows the LLM to search through past conversation messages
2196
+ * using semantic similarity. Messages must have embeddings stored to be searchable.
2197
+ *
2198
+ * @param storageCtx - Storage operations context for database access
2199
+ * @param embeddingOptions - Options for embedding generation
2200
+ * @param searchOptions - Default search options (can be overridden per-call)
2201
+ * @returns A ToolConfig that can be passed to chat completion tools
2202
+ *
2203
+ * @example
2204
+ * ```ts
2205
+ * const tool = createMemoryRetrievalTool(
2206
+ * storageCtx,
2207
+ * { getToken: () => getIdentityToken() },
2208
+ * { limit: 5, minSimilarity: 0.4 }
2209
+ * );
2210
+ *
2211
+ * // Use with chat completion
2212
+ * const result = await sendMessage({
2213
+ * messages: [...],
2214
+ * tools: [tool],
2215
+ * });
2216
+ * ```
2217
+ */
2218
+ declare function createMemoryRetrievalTool(storageCtx: StorageOperationsContext, embeddingOptions: EmbeddingOptions, searchOptions?: Partial<MemoryRetrievalSearchOptions>): ToolConfig;
2219
+
2220
+ /**
2221
+ * Memory Vault Search Tool
2222
+ *
2223
+ * Provides a tool for LLMs to search the user's memory vault
2224
+ * using semantic similarity over pre-computed embeddings.
2225
+ */
2226
+
2227
+ /**
2228
+ * Embedding cache keyed by content string. Stores pre-computed embeddings
2229
+ * so that search only needs to embed the query, not the vault entries.
2230
+ */
2231
+ type VaultEmbeddingCache = Map<string, number[]>;
2232
+
2233
+ /**
2234
+ * Memory Vault Tool
2235
+ *
2236
+ * Provides a tool for LLMs to save and update persistent memories.
2237
+ * Each operation can be intercepted by the host app for confirmation/cancellation.
2238
+ */
2239
+
2240
+ /**
2241
+ * Describes a pending vault save operation for UI confirmation.
2242
+ */
2243
+ interface VaultSaveOperation {
2244
+ /** Whether this is a new memory or an update to an existing one */
2245
+ action: "add" | "update";
2246
+ /** The memory content to save */
2247
+ content: string;
2248
+ /** The scope of the memory (only present for add operations) */
2249
+ scope?: string;
2250
+ /** The ID of the memory being updated (only present for updates) */
2251
+ id?: string;
2252
+ /** The previous content of the memory (only present for updates, for diff display) */
2253
+ previousContent?: string;
2254
+ }
2255
+ /**
2256
+ * Options for creating a memory vault tool.
2257
+ */
2258
+ interface MemoryVaultToolOptions {
2259
+ /**
2260
+ * Callback invoked before each save operation.
2261
+ * Return `true` to confirm the save, `false` to cancel it.
2262
+ *
2263
+ * When provided, the tool uses autoExecute with the confirmation
2264
+ * built into the executor. When not provided, the tool uses
2265
+ * autoExecute: false so the host app can handle it via onToolCall.
2266
+ */
2267
+ onSave?: (operation: VaultSaveOperation) => Promise<boolean>;
2268
+ /**
2269
+ * Scope to assign to new memories. Defaults to "private".
2270
+ * This is injected by the client, not controlled by the LLM.
2271
+ */
2272
+ scope?: string;
2273
+ }
2274
+ /**
2275
+ * Creates a memory vault tool for use with chat completions.
2276
+ *
2277
+ * The tool allows the LLM to save and update persistent memories.
2278
+ * Each operation can be intercepted for user confirmation before committing.
2279
+ *
2280
+ * @param vaultCtx - Vault operations context for database access
2281
+ * @param options - Optional configuration (onSave callback for confirmation)
2282
+ * @returns A ToolConfig that can be passed to chat completion tools
2283
+ *
2284
+ * @example
2285
+ * ```ts
2286
+ * const tool = createMemoryVaultTool(vaultCtx, {
2287
+ * onSave: async (op) => {
2288
+ * // Show confirmation toast, return true/false
2289
+ * return await showConfirmationToast(op);
2290
+ * },
2291
+ * });
2292
+ *
2293
+ * await sendMessage({
2294
+ * messages: [...],
2295
+ * clientTools: [tool],
2296
+ * });
2297
+ * ```
2298
+ */
2299
+ declare function createMemoryVaultTool(vaultCtx: VaultMemoryOperationsContext, options?: MemoryVaultToolOptions, embeddingOptions?: EmbeddingOptions, cache?: VaultEmbeddingCache): ToolConfig;
2300
+
2301
+ /**
2302
+ * Options for useChatStorage hook (Expo version)
2303
+ *
2304
+ * Uses the base options without React-specific features (no local chat, no tools).
2305
+ * @inline
2306
+ */
2307
+ interface UseChatStorageOptions extends BaseUseChatStorageOptions {
2308
+ /**
2309
+ * Which API endpoint to use. Default: "responses"
2310
+ * - "responses": OpenAI Responses API (supports thinking, reasoning, conversations)
2311
+ * - "completions": OpenAI Chat Completions API (wider model compatibility)
2312
+ */
2313
+ apiType?: ApiType;
2314
+ /**
2315
+ * Wallet address for field-level encryption.
2316
+ * When provided with signMessage, all sensitive content is encrypted at rest.
2317
+ */
2318
+ walletAddress?: string;
2319
+ /**
2320
+ * Function to sign a message for encryption key derivation.
2321
+ */
2322
+ signMessage?: SignMessageFn;
2323
+ /**
2324
+ * Function for silent signing with Privy embedded wallets.
2325
+ */
2326
+ embeddedWalletSigner?: EmbeddedWalletSignerFn;
2327
+ /**
2328
+ * Async function to poll for wallet address during Privy initialization.
2329
+ */
2330
+ getWalletAddress?: () => Promise<string | null>;
2331
+ /**
2332
+ * Enable the in-memory write queue. @default true
2333
+ */
2334
+ enableQueue?: boolean;
2335
+ /**
2336
+ * Auto-flush queued operations when key becomes available. @default true
2337
+ */
2338
+ autoFlushOnKeyAvailable?: boolean;
2339
+ }
2340
+ /**
2341
+ * Arguments for sendMessage with storage (Expo version)
2342
+ *
2343
+ * Uses the base arguments without React-specific features (no runTools, no headers).
2344
+
2345
+ */
2346
+ type SendMessageWithStorageArgs = BaseSendMessageWithStorageArgs & {
2347
+ /**
2348
+ * Override the API type for this request only.
2349
+ * Useful when different models need different APIs.
2350
+ * @default Uses the hook-level apiType or "responses"
2351
+ */
2352
+ apiType?: ApiType;
2353
+ };
2354
+ /**
2355
+ * Result from sendMessage with storage (Expo version)
2356
+ *
2357
+ * Uses the base result without tool execution information.
2358
+ */
2359
+ type SendMessageWithStorageResult = BaseSendMessageWithStorageResult;
2360
+ /**
2361
+ * Result returned by useChatStorage hook (Expo version)
2362
+ *
2363
+ * Extends base result with Expo-specific sendMessage signature.
2364
+ */
2365
+ interface UseChatStorageResult extends BaseUseChatStorageResult {
2366
+ /** Send a message and automatically store it (Expo version) */
2367
+ sendMessage: (args: SendMessageWithStorageArgs) => Promise<SendMessageWithStorageResult>;
2368
+ /**
2369
+ * Create a memory retrieval tool for LLM to search past conversations.
2370
+ * The tool is pre-configured with the hook's storage context and auth.
2371
+ *
2372
+ * @param searchOptions - Optional search configuration (limit, minSimilarity, etc.)
2373
+ * @returns A ToolConfig that can be passed to sendMessage's clientTools
2374
+ *
2375
+ * @example
2376
+ * ```ts
2377
+ * const memoryTool = createMemoryRetrievalTool({ limit: 5 });
2378
+ * await sendMessage({
2379
+ * messages: [...],
2380
+ * clientTools: [memoryTool],
2381
+ * });
2382
+ * ```
2383
+ */
2384
+ createMemoryRetrievalTool: (searchOptions?: Partial<MemoryRetrievalSearchOptions>) => ToolConfig;
2385
+ /** Create a memory vault tool pre-configured with hook's vault context and encryption. */
2386
+ createMemoryVaultTool: (options?: MemoryVaultToolOptions) => ToolConfig;
2387
+ /** Get all vault memories for context injection. */
2388
+ getVaultMemories: (options?: {
2389
+ scopes?: string[];
2390
+ }) => Promise<StoredVaultMemory[]>;
2391
+ /** Delete a vault memory by its ID (soft delete). */
2392
+ deleteVaultMemory: (id: string) => Promise<boolean>;
2393
+ /** Manually flush all queued operations for the current wallet. */
2394
+ flushQueue: () => Promise<FlushResult>;
2395
+ /** Clear all queued operations without writing them. */
2396
+ clearQueue: () => void;
2397
+ /** Current status of the write queue. */
2398
+ queueStatus: QueueStatus;
2399
+ }
2400
+ /**
2401
+ * A React hook that wraps useChat with automatic message persistence using WatermelonDB.
2402
+ *
2403
+ * **Expo/React Native version** - This is a lightweight version that only supports
2404
+ * API-based chat completions. Local chat and client-side tools are not available.
2405
+ *
2406
+ * @param options - Configuration options
2407
+ * @returns An object containing chat state, methods, and storage operations
2408
+ *
2409
+ * @example
2410
+ * ```tsx
2411
+ * import { Database } from '@nozbe/watermelondb';
2412
+ * import { useChatStorage } from '@anuma/sdk/expo';
2413
+ *
2414
+ * function ChatScreen({ database }: { database: Database }) {
2415
+ * const {
2416
+ * isLoading,
2417
+ * sendMessage,
2418
+ * conversationId,
2419
+ * getMessages,
2420
+ * } = useChatStorage({
2421
+ * database,
2422
+ * getToken: async () => getAuthToken(),
2423
+ * onData: (chunk) => setResponse((prev) => prev + chunk),
2424
+ * });
2425
+ *
2426
+ * const handleSend = async () => {
2427
+ * const result = await sendMessage({
2428
+ * content: 'Hello!',
2429
+ * model: 'gpt-4o-mini',
2430
+ * includeHistory: true,
2431
+ * });
2432
+ * };
2433
+ *
2434
+ * return (
2435
+ * <View>
2436
+ * <Button onPress={handleSend} disabled={isLoading} title="Send" />
2437
+ * </View>
2438
+ * );
2439
+ * }
2440
+ * ```
2441
+ *
2442
+ * @category Hooks
2443
+ */
2444
+ declare function useChatStorage(options: UseChatStorageOptions): UseChatStorageResult;
2445
+
2446
+ /**
2447
+ * Current combined schema version for all SDK storage modules.
2448
+ *
2449
+ * Version history:
2450
+ * - v2: Baseline (chat + memory tables) - minimum supported version for migrations
2451
+ * - v3: Added was_stopped column to history table
2452
+ * - v4: Added modelPreferences table for settings storage
2453
+ * - v5: Added error column to history table for error persistence
2454
+ * - v6: Added thought_process column to history table for activity tracking
2455
+ * - v7: Added userPreferences table for unified user settings storage
2456
+ * - v8: BREAKING - Clear all data (switching embedding model from OpenAI to Fireworks)
2457
+ * - v9: Added thinking column to history table for reasoning/thinking content
2458
+ * - v10: Added projects table and project_id column to conversations table
2459
+ * - v11: Added media table for library feature, added file_ids column to history table
2460
+ * - v12: Added chunks column to history table for sub-message semantic search
2461
+ * - v13: Added parent_message_id column to history table for message branching (edit/regenerate)
2462
+ * - v14: Added feedback column to history table for like/dislike on responses
2463
+ * - v15: Replaced memories table with memory_vault table for persistent memory vault
2464
+ * - v16: Added scope column to memory_vault table for memory partitioning
2465
+ */
2466
+ declare const SDK_SCHEMA_VERSION = 16;
2467
+ /**
2468
+ * Combined WatermelonDB schema for all SDK storage modules.
2469
+ *
2470
+ * This unified schema includes all tables needed by the SDK:
2471
+ * - `history`: Chat message storage with embeddings and metadata
2472
+ * - `conversations`: Conversation metadata and organization
2473
+ * - `memory_vault`: Persistent memory vault for curated facts
2474
+ * - `modelPreferences`: User model preferences (deprecated, use userPreferences)
2475
+ * - `userPreferences`: Unified user preferences (profile, personality, models)
2476
+ *
2477
+ * @example
2478
+ * ```typescript
2479
+ * import { Database } from '@nozbe/watermelondb';
2480
+ * import LokiJSAdapter from '@nozbe/watermelondb/adapters/lokijs';
2481
+ * import { sdkSchema, sdkMigrations, sdkModelClasses } from '@anuma/sdk/react';
2482
+ *
2483
+ * const adapter = new LokiJSAdapter({
2484
+ * schema: sdkSchema,
2485
+ * migrations: sdkMigrations,
2486
+ * dbName: 'my-app-db',
2487
+ * useWebWorker: false,
2488
+ * useIncrementalIndexedDB: true,
2489
+ * });
2490
+ *
2491
+ * const database = new Database({
2492
+ * adapter,
2493
+ * modelClasses: sdkModelClasses,
2494
+ * });
2495
+ * ```
2496
+ */
2497
+ declare const sdkSchema: Readonly<{
2498
+ version: _nozbe_watermelondb_Schema.SchemaVersion;
2499
+ tables: _nozbe_watermelondb_Schema.TableMap;
2500
+ unsafeSql?: (_: string, __: _nozbe_watermelondb_Schema.AppSchemaUnsafeSqlKind) => string;
2501
+ }>;
2502
+ /**
2503
+ * Combined migrations for all SDK storage modules.
2504
+ *
2505
+ * These migrations handle database schema upgrades from any previous version
2506
+ * to the current version. The SDK manages all migration logic internally,
2507
+ * so consumer apps don't need to handle version arithmetic or migration merging.
2508
+ *
2509
+ * **Minimum supported version: v2**
2510
+ * Migrations from v1 are not supported. Databases at v1 require a fresh install.
2511
+ *
2512
+ * Migration history:
2513
+ * - v2 → v3: Added `was_stopped` column to history table
2514
+ * - v3 → v4: Added `modelPreferences` table for settings storage
2515
+ * - v4 → v5: Added `error` column to history table for error persistence
2516
+ * - v5 → v6: Added `thought_process` column to history table for activity tracking
2517
+ * - v6 → v7: Added `userPreferences` table for unified user settings storage
2518
+ * - v7 → v8: BREAKING - Clear all data (embedding model change)
2519
+ * - v8 → v9: Added `thinking` column to history table for reasoning/thinking content
2520
+ * - v9 → v10: Added `projects` table and `project_id` column to conversations
2521
+ * - v10 → v11: Added `media` table for library feature, added `file_ids` column to history
2522
+ * - v11 → v12: Added `chunks` column to history table for sub-message semantic search
2523
+ * - v12 → v13: Added `parent_message_id` column to history table for message branching
2524
+ * - v13 → v14: Added `feedback` column to history table for like/dislike on responses
2525
+ * - v14 → v15: Replaced `memories` table with `memory_vault` table for persistent memory vault
2526
+ * - v15 → v16: Added `scope` column to memory_vault table for memory partitioning
2527
+ */
2528
+ declare const sdkMigrations: Readonly<{
2529
+ validated: true;
2530
+ minVersion: _nozbe_watermelondb_Schema.SchemaVersion;
2531
+ maxVersion: _nozbe_watermelondb_Schema.SchemaVersion;
2532
+ sortedMigrations: _nozbe_watermelondb_Schema_migrations.Migration[];
2533
+ }>;
2534
+ /**
2535
+ * Model classes to register with the WatermelonDB database.
2536
+ *
2537
+ * Pass this array directly to the `modelClasses` option when creating
2538
+ * your Database instance.
2539
+ *
2540
+ * @example
2541
+ * ```typescript
2542
+ * import { Database } from '@nozbe/watermelondb';
2543
+ * import { sdkSchema, sdkMigrations, sdkModelClasses } from '@anuma/sdk/react';
2544
+ *
2545
+ * const database = new Database({
2546
+ * adapter,
2547
+ * modelClasses: sdkModelClasses,
2548
+ * });
2549
+ * ```
2550
+ */
2551
+ declare const sdkModelClasses: Class<Model$1>[];
2552
+
2553
+ /**
2554
+ * Platform abstraction for persistent and session storage.
2555
+ *
2556
+ * Web implementations use localStorage/sessionStorage/indexedDB.
2557
+ * Mobile implementations can use AsyncStorage/in-memory maps/SQLite cleanup.
2558
+ */
2559
+ interface PlatformStorage {
2560
+ /** Read a value from persistent storage (e.g. localStorage) */
2561
+ getItem(key: string): string | null;
2562
+ /** Write a value to persistent storage */
2563
+ setItem(key: string, value: string): void;
2564
+ /** Remove a value from persistent storage */
2565
+ removeItem(key: string): void;
2566
+ /** Read a value from session-scoped storage (e.g. sessionStorage). Used to prevent reload loops. */
2567
+ getSessionItem(key: string): string | null;
2568
+ /** Write a value to session-scoped storage */
2569
+ setSessionItem(key: string, value: string): void;
2570
+ /** Delete an IndexedDB database by name */
2571
+ deleteDatabase(name: string): Promise<void>;
2572
+ }
2573
+ /**
2574
+ * Optional logger interface for DatabaseManager.
2575
+ */
2576
+ interface DatabaseManagerLogger {
2577
+ debug?: (msg: string, ctx?: Record<string, unknown>) => void;
2578
+ warn?: (msg: string, ctx?: Record<string, unknown>) => void;
2579
+ info?: (msg: string, ctx?: Record<string, unknown>) => void;
2580
+ }
2581
+ /**
2582
+ * Configuration options for DatabaseManager.
2583
+ */
2584
+ interface DatabaseManagerOptions {
2585
+ /** Prefix for database names, e.g. "anuma-watermelon". Each wallet gets `{prefix}-{address}`. */
2586
+ dbNamePrefix: string;
2587
+ /**
2588
+ * Factory that creates a WatermelonDB adapter for a given database name.
2589
+ * The schema and migrations are provided for convenience.
2590
+ *
2591
+ * @example
2592
+ * ```typescript
2593
+ * createAdapter: (dbName, schema, migrations) => new LokiJSAdapter({
2594
+ * schema,
2595
+ * migrations,
2596
+ * dbName,
2597
+ * useWebWorker: false,
2598
+ * useIncrementalIndexedDB: true,
2599
+ * })
2600
+ * ```
2601
+ */
2602
+ createAdapter: (dbName: string, schema: typeof sdkSchema, migrations: typeof sdkMigrations) => DatabaseAdapter;
2603
+ /** Platform storage implementation. Defaults to webPlatformStorage. */
2604
+ storage?: PlatformStorage;
2605
+ /**
2606
+ * Called when a destructive migration is needed (schema too old).
2607
+ * On web, this typically triggers `window.location.reload()`.
2608
+ * If not provided, the manager will throw an error instead.
2609
+ */
2610
+ onDestructiveMigration?: () => void;
2611
+ /** Optional logger for debug/warn/info messages */
2612
+ logger?: DatabaseManagerLogger;
2613
+ }
2614
+ /**
2615
+ * Manages per-wallet WatermelonDB database instances.
2616
+ *
2617
+ * Each wallet address gets its own isolated database. The manager handles:
2618
+ * - Singleton caching per wallet
2619
+ * - Automatic database switching when the wallet changes
2620
+ * - Destructive schema migration detection and handling
2621
+ * - Per-wallet storage key namespacing
2622
+ *
2623
+ * @example
2624
+ * ```typescript
2625
+ * import { DatabaseManager, webPlatformStorage, sdkSchema, sdkMigrations } from '@anuma/sdk/react';
2626
+ * import LokiJSAdapter from '@nozbe/watermelondb/adapters/lokijs';
2627
+ *
2628
+ * const dbManager = new DatabaseManager({
2629
+ * dbNamePrefix: 'my-app',
2630
+ * createAdapter: (dbName, schema, migrations) => new LokiJSAdapter({
2631
+ * schema,
2632
+ * migrations,
2633
+ * dbName,
2634
+ * useWebWorker: false,
2635
+ * useIncrementalIndexedDB: true,
2636
+ * }),
2637
+ * storage: webPlatformStorage,
2638
+ * onDestructiveMigration: () => window.location.reload(),
2639
+ * });
2640
+ *
2641
+ * // Get the database for the current wallet
2642
+ * const database = dbManager.getDatabase(walletAddress);
2643
+ * ```
2644
+ */
2645
+ declare class DatabaseManager {
2646
+ private database;
2647
+ private currentWalletAddress;
2648
+ private migrationInProgress;
2649
+ private readonly dbNamePrefix;
2650
+ private readonly createAdapter;
2651
+ private readonly storage;
2652
+ private readonly onDestructiveMigration?;
2653
+ private readonly logger;
2654
+ constructor(options: DatabaseManagerOptions);
2655
+ /**
2656
+ * Get the database name for a given wallet address.
2657
+ */
2658
+ getDbName(walletAddress?: string): string;
2659
+ /**
2660
+ * Get or create a WatermelonDB Database instance for the given wallet.
2661
+ *
2662
+ * If the wallet address has changed since the last call, the previous
2663
+ * database instance is discarded and a new one is created.
2664
+ *
2665
+ * @param walletAddress - The wallet address to scope the database to.
2666
+ * If undefined, uses a "guest" database.
2667
+ * @returns The WatermelonDB Database instance
2668
+ * @throws If a destructive migration is in progress
2669
+ */
2670
+ getDatabase(walletAddress?: string): Database;
2671
+ /**
2672
+ * Reset the current database (useful for logout or testing).
2673
+ */
2674
+ resetDatabase(): Promise<void>;
2675
+ /**
2676
+ * Check and handle schema migrations for a specific wallet.
2677
+ * Returns true if a destructive migration is in progress.
2678
+ */
2679
+ private handleSchemaMigration;
2680
+ }
2681
+
2682
+ export { type CachedServerTools, Conversation as ChatConversation, Message as ChatMessage, type ChatRole, type CreateConversationOptions, type CreateMessageOptions, type CreateVaultMemoryOptions, DEFAULT_CACHE_EXPIRATION_MS, DatabaseManager, type DatabaseManagerLogger, type DatabaseManagerOptions, type EmbeddedWalletSignerFn, type FileMetadata, type FlushResult, type EmbeddingOptions as MemoryRetrievalEmbeddingOptions, type MemoryRetrievalResult, type MemoryRetrievalSearchOptions, type MemoryVaultToolOptions, type PlatformStorage, QueueManager, type QueueStatus, SDK_SCHEMA_VERSION, type SearchSource, type SendMessageWithStorageArgs, type SendMessageWithStorageResult, type ServerToolsOptions, type ServerToolsResponse, type SignMessageFn, type ChatCompletionUsage as StoredChatCompletionUsage, type StoredConversation, type StoredMessage, type StoredMessageWithSimilarity, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, type UpdateVaultMemoryOptions, type UseChatStorageOptions, type UseChatStorageResult, type UseCreditsOptions, type UseCreditsResult, type UseModelsOptions, type UseModelsResult, type VaultMemoryOperationsContext, type VaultSaveOperation, WalletPoller, chatStorageMigrations, chatStorageSchema, clearAllEncryptionKeys, clearEncryptionKey, clearServerToolsCache, createMemoryRetrievalTool, createMemoryVaultTool, createVaultMemoryOp, deleteVaultMemoryOp, embedAllMessages, embedMessage, generateConversationId, generateEmbedding, generateEmbeddings, getAllVaultMemoriesOp, getCachedServerTools, getServerTools, getVaultMemoryOp, hasEncryptionKey, onKeyAvailable, queueManager, requestEncryptionKey, sdkMigrations, sdkModelClasses, sdkSchema, updateVaultMemoryOp, useChat, useChatStorage, useCredits, useEncryption, useModels };