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