@reverbia/sdk 1.0.0-next.20251212012743 → 1.0.0-next.20251215143604

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,7 @@
1
+ import { Database, Model } from '@nozbe/watermelondb';
2
+ import * as _nozbe_watermelondb_Schema from '@nozbe/watermelondb/Schema';
3
+ import { Associations } from '@nozbe/watermelondb/Model';
4
+
1
5
  /**
2
6
  * ExtraFields contains additional metadata
3
7
  */
@@ -460,6 +464,11 @@ type SendMessageArgs = BaseSendMessageArgs & {
460
464
  * Optional custom headers to include with the request.
461
465
  */
462
466
  headers?: Record<string, string>;
467
+ /**
468
+ * Memory context to inject as a system message.
469
+ * This is typically formatted memories from useMemoryStorage.
470
+ */
471
+ memoryContext?: string;
463
472
  };
464
473
  type SendMessageResult = {
465
474
  data: LlmapiChatCompletionResponse;
@@ -524,6 +533,8 @@ type UseChatResult = BaseUseChatResult & {
524
533
  * @param options.toolSelectorModel - The model to use for tool selection.
525
534
  * @param options.onToolExecution - Callback function to be called when a tool is executed.
526
535
  *
536
+ * @category Hooks
537
+ *
527
538
  * @returns An object containing:
528
539
  * - `isLoading`: A boolean indicating whether a request is currently in progress
529
540
  * - `isSelectingTool`: A boolean indicating whether tool selection is in progress
@@ -612,12 +623,421 @@ declare function requestEncryptionKey(walletAddress: string, signMessage: SignMe
612
623
  * Hook that provides on-demand encryption key management.
613
624
  * @param signMessage - Function to sign a message (from Privy's useSignMessage)
614
625
  * @returns Functions to request encryption keys
626
+ * @category Hooks
615
627
  */
616
628
  declare function useEncryption(signMessage: SignMessageFn): {
617
629
  requestEncryptionKey: (walletAddress: string) => Promise<void>;
618
630
  };
619
631
 
620
- interface MemoryItem {
632
+ /**
633
+ * Message role type
634
+ */
635
+ type ChatRole = "user" | "assistant" | "system";
636
+ /**
637
+ * File metadata for attached files
638
+ */
639
+ interface FileMetadata {
640
+ /** Unique file identifier */
641
+ id: string;
642
+ /** Original file name */
643
+ name: string;
644
+ /** MIME type */
645
+ type: string;
646
+ /** File size in bytes */
647
+ size: number;
648
+ /** Optional URL or data URI */
649
+ url?: string;
650
+ }
651
+ /**
652
+ * Token usage and cost information
653
+ */
654
+ interface ChatCompletionUsage {
655
+ /** Number of tokens in the prompt */
656
+ promptTokens?: number;
657
+ /** Number of tokens in the completion */
658
+ completionTokens?: number;
659
+ /** Total tokens used */
660
+ totalTokens?: number;
661
+ /** Cost in micro-dollars (USD × 1,000,000) */
662
+ costMicroUsd?: number;
663
+ }
664
+ /**
665
+ * Web search source information
666
+ */
667
+ interface SearchSource {
668
+ /** Source title */
669
+ title?: string;
670
+ /** Source URL */
671
+ url?: string;
672
+ /** Text snippet from the source */
673
+ snippet?: string;
674
+ /** Publication or last updated date */
675
+ date?: string;
676
+ }
677
+ /**
678
+ * Stored message record (what gets persisted to the database)
679
+ */
680
+ interface StoredMessage {
681
+ /** Primary key, unique message identifier (WatermelonDB auto-generated) */
682
+ uniqueId: string;
683
+ /** Sequential message ID within conversation */
684
+ messageId: number;
685
+ /** Links message to its conversation */
686
+ conversationId: string;
687
+ /** Who sent the message */
688
+ role: ChatRole;
689
+ /** The message text */
690
+ content: string;
691
+ /** LLM model used */
692
+ model?: string;
693
+ /** Optional attached files */
694
+ files?: FileMetadata[];
695
+ /** When the message was created */
696
+ createdAt: Date;
697
+ /** When the message was last updated */
698
+ updatedAt: Date;
699
+ /** Embedding vector for semantic search */
700
+ vector?: number[];
701
+ /** Model used to generate embedding */
702
+ embeddingModel?: string;
703
+ /** Token counts and cost */
704
+ usage?: ChatCompletionUsage;
705
+ /** Web search sources */
706
+ sources?: SearchSource[];
707
+ /** Response time in seconds */
708
+ responseDuration?: number;
709
+ }
710
+ /**
711
+ * Stored conversation record
712
+ */
713
+ interface StoredConversation {
714
+ /** Primary key (WatermelonDB auto-generated) */
715
+ uniqueId: string;
716
+ /** Unique conversation identifier */
717
+ conversationId: string;
718
+ /** Conversation title */
719
+ title: string;
720
+ /** When the conversation was created */
721
+ createdAt: Date;
722
+ /** When the conversation was last updated */
723
+ updatedAt: Date;
724
+ /** Soft delete flag */
725
+ isDeleted: boolean;
726
+ }
727
+ /**
728
+ * Stored message with similarity score (for search results)
729
+ */
730
+ interface StoredMessageWithSimilarity extends StoredMessage {
731
+ /** Cosine similarity score (0 to 1) */
732
+ similarity: number;
733
+ }
734
+ /**
735
+ * Options for creating a new message
736
+ */
737
+ interface CreateMessageOptions {
738
+ /** Conversation ID to add the message to */
739
+ conversationId: string;
740
+ /** Message role */
741
+ role: ChatRole;
742
+ /** Message content */
743
+ content: string;
744
+ /** LLM model used (for assistant messages) */
745
+ model?: string;
746
+ /** Attached files */
747
+ files?: FileMetadata[];
748
+ /** Token usage information */
749
+ usage?: ChatCompletionUsage;
750
+ /** Web search sources */
751
+ sources?: SearchSource[];
752
+ /** Response duration in seconds */
753
+ responseDuration?: number;
754
+ /** Embedding vector for semantic search */
755
+ vector?: number[];
756
+ /** Model used to generate the embedding */
757
+ embeddingModel?: string;
758
+ }
759
+ /**
760
+ * Options for creating a new conversation
761
+ */
762
+ interface CreateConversationOptions {
763
+ /** Custom conversation ID (auto-generated if not provided) */
764
+ conversationId?: string;
765
+ /** Conversation title */
766
+ title?: string;
767
+ }
768
+ /**
769
+ * Base options for useChatStorage hook (shared between React and Expo)
770
+ */
771
+ interface BaseUseChatStorageOptions {
772
+ /** WatermelonDB database instance */
773
+ database: Database;
774
+ /** Current conversation ID (will create new if not provided) */
775
+ conversationId?: string;
776
+ /** Auto-create conversation if it doesn't exist (default: true) */
777
+ autoCreateConversation?: boolean;
778
+ /** Default title for auto-created conversations */
779
+ defaultConversationTitle?: string;
780
+ /** Authentication token getter */
781
+ getToken?: () => Promise<string | null>;
782
+ /** Base URL for API requests */
783
+ baseUrl?: string;
784
+ /** Callback when data chunk is received */
785
+ onData?: (chunk: string) => void;
786
+ /** Callback when chat completion finishes */
787
+ onFinish?: (response: LlmapiChatCompletionResponse) => void;
788
+ /** Callback when an error occurs */
789
+ onError?: (error: Error) => void;
790
+ }
791
+ /**
792
+ * Base arguments for sendMessage with storage (shared between React and Expo)
793
+ */
794
+ interface BaseSendMessageWithStorageArgs {
795
+ /** Message content to send */
796
+ content: string;
797
+ /** Model to use for the completion */
798
+ model?: string;
799
+ /** Previous messages to include (if not using stored messages) */
800
+ messages?: LlmapiMessage[];
801
+ /** Whether to include stored messages from conversation */
802
+ includeHistory?: boolean;
803
+ /** Maximum number of history messages to include (default: 50) */
804
+ maxHistoryMessages?: number;
805
+ /** Attached files */
806
+ files?: FileMetadata[];
807
+ /** Per-request data callback */
808
+ onData?: (chunk: string) => void;
809
+ /** Memory context to inject as system message (formatted memories from useMemoryStorage) */
810
+ memoryContext?: string;
811
+ }
812
+ /**
813
+ * Base result returned by useChatStorage hook (shared between React and Expo)
814
+ */
815
+ interface BaseUseChatStorageResult {
816
+ /** Whether a chat request is in progress */
817
+ isLoading: boolean;
818
+ /** Stop the current request */
819
+ stop: () => void;
820
+ /** Current conversation ID */
821
+ conversationId: string | null;
822
+ /** Set the current conversation ID */
823
+ setConversationId: (id: string | null) => void;
824
+ /** Create a new conversation */
825
+ createConversation: (options?: CreateConversationOptions) => Promise<StoredConversation>;
826
+ /** Get a conversation by ID */
827
+ getConversation: (id: string) => Promise<StoredConversation | null>;
828
+ /** Get all conversations (excluding soft-deleted) */
829
+ getConversations: () => Promise<StoredConversation[]>;
830
+ /** Update conversation title. Returns true if updated, false if not found. */
831
+ updateConversationTitle: (id: string, title: string) => Promise<boolean>;
832
+ /** Soft delete a conversation. Returns true if deleted, false if not found. */
833
+ deleteConversation: (id: string) => Promise<boolean>;
834
+ /** Get messages for a conversation */
835
+ getMessages: (conversationId: string) => Promise<StoredMessage[]>;
836
+ /** Get message count for a conversation */
837
+ getMessageCount: (conversationId: string) => Promise<number>;
838
+ /** Clear all messages in a conversation */
839
+ clearMessages: (conversationId: string) => Promise<void>;
840
+ }
841
+ /**
842
+ * Generate a unique ID for conversations
843
+ */
844
+ declare function generateConversationId(): string;
845
+
846
+ /**
847
+ * Options for useChatStorage hook (React version)
848
+ *
849
+ * Extends base options with React-specific features like local chat and tools.
850
+ */
851
+ interface UseChatStorageOptions extends BaseUseChatStorageOptions {
852
+ /** Chat provider: "api" or "local" */
853
+ chatProvider?: "api" | "local";
854
+ /** Model for local chat */
855
+ localModel?: string;
856
+ /** Client-side tools */
857
+ tools?: ClientTool[];
858
+ /** Tool selector model */
859
+ toolSelectorModel?: string;
860
+ /** Callback when tool is executed */
861
+ onToolExecution?: (result: ToolExecutionResult) => void;
862
+ }
863
+ /**
864
+ * Arguments for sendMessage with storage (React version)
865
+ *
866
+ * Extends base arguments with React-specific features like tools and headers.
867
+ */
868
+ interface SendMessageWithStorageArgs extends BaseSendMessageWithStorageArgs {
869
+ /** Whether to run tool selection */
870
+ runTools?: boolean;
871
+ /** Custom headers */
872
+ headers?: Record<string, string>;
873
+ }
874
+ /**
875
+ * Result from sendMessage with storage (React version)
876
+ *
877
+ * Extends base result with tool execution information.
878
+ */
879
+ type SendMessageWithStorageResult = {
880
+ data: LlmapiChatCompletionResponse;
881
+ error: null;
882
+ toolExecution?: ToolExecutionResult;
883
+ userMessage: StoredMessage;
884
+ assistantMessage: StoredMessage;
885
+ } | {
886
+ data: null;
887
+ error: string;
888
+ toolExecution?: ToolExecutionResult;
889
+ userMessage?: StoredMessage;
890
+ assistantMessage?: undefined;
891
+ };
892
+ /**
893
+ * Options for searching messages
894
+ */
895
+ interface SearchMessagesOptions {
896
+ /** Limit the number of results (default: 10) */
897
+ limit?: number;
898
+ /** Minimum similarity threshold (default: 0.5) */
899
+ minSimilarity?: number;
900
+ /** Filter by conversation ID */
901
+ conversationId?: string;
902
+ }
903
+ /**
904
+ * Result returned by useChatStorage hook (React version)
905
+ *
906
+ * Extends base result with tool selection state and React-specific sendMessage signature.
907
+ */
908
+ interface UseChatStorageResult extends BaseUseChatStorageResult {
909
+ /** Whether tool selection is in progress */
910
+ isSelectingTool: boolean;
911
+ /** Send a message and automatically store it (React version with tool support) */
912
+ sendMessage: (args: SendMessageWithStorageArgs) => Promise<SendMessageWithStorageResult>;
913
+ /** Search messages by vector similarity */
914
+ searchMessages: (queryVector: number[], options?: SearchMessagesOptions) => Promise<StoredMessageWithSimilarity[]>;
915
+ /** Update a message's embedding vector. Returns updated message or null if not found. */
916
+ updateMessageEmbedding: (uniqueId: string, vector: number[], embeddingModel: string) => Promise<StoredMessage | null>;
917
+ }
918
+ /**
919
+ * A React hook that wraps useChat with automatic message persistence using WatermelonDB.
920
+ *
921
+ * This hook provides all the functionality of useChat plus automatic storage of
922
+ * messages and conversations to a WatermelonDB database. Messages are automatically
923
+ * saved when sent and when responses are received.
924
+ *
925
+ * @param options - Configuration options
926
+ * @returns An object containing chat state, methods, and storage operations
927
+ *
928
+ * @example
929
+ * ```tsx
930
+ * import { Database } from '@nozbe/watermelondb';
931
+ * import { useChatStorage } from '@reverbia/sdk/react';
932
+ *
933
+ * function ChatComponent({ database }: { database: Database }) {
934
+ * const {
935
+ * isLoading,
936
+ * sendMessage,
937
+ * conversationId,
938
+ * getMessages,
939
+ * createConversation,
940
+ * } = useChatStorage({
941
+ * database,
942
+ * getToken: async () => getAuthToken(),
943
+ * onData: (chunk) => setResponse((prev) => prev + chunk),
944
+ * });
945
+ *
946
+ * const handleSend = async () => {
947
+ * const result = await sendMessage({
948
+ * content: 'Hello, how are you?',
949
+ * model: 'gpt-4o-mini',
950
+ * includeHistory: true, // Include previous messages from this conversation
951
+ * });
952
+ *
953
+ * if (result.error) {
954
+ * console.error('Error:', result.error);
955
+ * } else {
956
+ * console.log('User message stored:', result.userMessage);
957
+ * console.log('Assistant message stored:', result.assistantMessage);
958
+ * }
959
+ * };
960
+ *
961
+ * return (
962
+ * <div>
963
+ * <button onClick={handleSend} disabled={isLoading}>Send</button>
964
+ * </div>
965
+ * );
966
+ * }
967
+ * ```
968
+ *
969
+ * @category Hooks
970
+ */
971
+ declare function useChatStorage(options: UseChatStorageOptions): UseChatStorageResult;
972
+
973
+ /**
974
+ * WatermelonDB schema for chat storage
975
+ *
976
+ * Defines two tables:
977
+ * - history: Chat messages with metadata
978
+ * - conversations: Conversation metadata
979
+ */
980
+ declare const chatStorageSchema: Readonly<{
981
+ version: _nozbe_watermelondb_Schema.SchemaVersion;
982
+ tables: _nozbe_watermelondb_Schema.TableMap;
983
+ unsafeSql?: (_: string, __: _nozbe_watermelondb_Schema.AppSchemaUnsafeSqlKind) => string;
984
+ }>;
985
+
986
+ /**
987
+ * Message model representing a single chat message
988
+ *
989
+ * Note: This model uses raw column accessors instead of decorators
990
+ * for better TypeScript compatibility without requiring legacy decorators.
991
+ */
992
+ declare class Message extends Model {
993
+ static table: string;
994
+ static associations: Associations;
995
+ /** Sequential message ID within conversation */
996
+ get messageId(): number;
997
+ /** Links message to its conversation */
998
+ get conversationId(): string;
999
+ /** Who sent the message: 'user' | 'assistant' | 'system' */
1000
+ get role(): ChatRole;
1001
+ /** The message text content */
1002
+ get content(): string;
1003
+ /** LLM model used (e.g., GPT-4, Claude) */
1004
+ get model(): string | undefined;
1005
+ /** Optional attached files */
1006
+ get files(): FileMetadata[] | undefined;
1007
+ /** Created timestamp */
1008
+ get createdAt(): Date;
1009
+ /** Updated timestamp */
1010
+ get updatedAt(): Date;
1011
+ /** Embedding vector for semantic search */
1012
+ get vector(): number[] | undefined;
1013
+ /** Model used to generate embedding */
1014
+ get embeddingModel(): string | undefined;
1015
+ /** Token counts and cost */
1016
+ get usage(): ChatCompletionUsage | undefined;
1017
+ /** Web search sources */
1018
+ get sources(): SearchSource[] | undefined;
1019
+ /** Response time in seconds */
1020
+ get responseDuration(): number | undefined;
1021
+ }
1022
+ /**
1023
+ * Conversation model representing conversation metadata
1024
+ */
1025
+ declare class Conversation extends Model {
1026
+ static table: string;
1027
+ static associations: Associations;
1028
+ /** Unique conversation identifier */
1029
+ get conversationId(): string;
1030
+ /** Conversation title */
1031
+ get title(): string;
1032
+ /** Created timestamp */
1033
+ get createdAt(): Date;
1034
+ /** Updated timestamp */
1035
+ get updatedAt(): Date;
1036
+ /** Soft delete flag */
1037
+ get isDeleted(): boolean;
1038
+ }
1039
+
1040
+ interface MemoryItem$1 {
621
1041
  type: "identity" | "preference" | "project" | "skill" | "constraint";
622
1042
  namespace: string;
623
1043
  key: string;
@@ -627,26 +1047,120 @@ interface MemoryItem {
627
1047
  pii: boolean;
628
1048
  }
629
1049
  interface MemoryExtractionResult {
630
- items: MemoryItem[];
1050
+ items: MemoryItem$1[];
631
1051
  }
632
1052
 
633
1053
  /**
634
- * Extended MemoryItem with database fields
1054
+ * Memory type classification
635
1055
  */
636
- interface StoredMemoryItem extends MemoryItem {
637
- id?: number;
638
- createdAt: number;
639
- updatedAt: number;
1056
+ type MemoryType = "identity" | "preference" | "project" | "skill" | "constraint";
1057
+ /**
1058
+ * Base memory item (matches existing MemoryItem from memory/service.ts)
1059
+ */
1060
+ interface MemoryItem {
1061
+ type: MemoryType;
1062
+ namespace: string;
1063
+ key: string;
1064
+ value: string;
1065
+ rawEvidence: string;
1066
+ confidence: number;
1067
+ pii: boolean;
1068
+ }
1069
+ /**
1070
+ * Stored memory record (what gets persisted to the database)
1071
+ */
1072
+ interface StoredMemory {
1073
+ /** Primary key, unique memory identifier (WatermelonDB auto-generated) */
1074
+ uniqueId: string;
1075
+ /** Memory type classification */
1076
+ type: MemoryType;
1077
+ /** Namespace for grouping related memories */
1078
+ namespace: string;
1079
+ /** Key within the namespace */
1080
+ key: string;
1081
+ /** The memory value/content */
1082
+ value: string;
1083
+ /** Raw evidence from which this memory was extracted */
1084
+ rawEvidence: string;
1085
+ /** Confidence score (0-1) */
1086
+ confidence: number;
1087
+ /** Whether this memory contains PII */
1088
+ pii: boolean;
1089
+ /** Composite key (namespace:key) for efficient lookups */
640
1090
  compositeKey: string;
1091
+ /** Unique key (namespace:key:value) for deduplication */
641
1092
  uniqueKey: string;
1093
+ /** ISO timestamp */
1094
+ createdAt: Date;
1095
+ /** ISO timestamp */
1096
+ updatedAt: Date;
1097
+ /** Embedding vector for semantic search */
642
1098
  embedding?: number[];
1099
+ /** Model used to generate embedding */
643
1100
  embeddingModel?: string;
1101
+ /** Soft delete flag */
1102
+ isDeleted: boolean;
644
1103
  }
645
-
646
- type UseMemoryOptions = {
647
- /**
648
- * The model to use for fact extraction (default: "openai/gpt-4o")
649
- */
1104
+ /**
1105
+ * Memory with similarity score (returned from semantic search)
1106
+ */
1107
+ interface StoredMemoryWithSimilarity extends StoredMemory {
1108
+ /** Cosine similarity score (0-1) */
1109
+ similarity: number;
1110
+ }
1111
+ /**
1112
+ * Options for creating a new memory
1113
+ */
1114
+ interface CreateMemoryOptions {
1115
+ /** Memory type */
1116
+ type: MemoryType;
1117
+ /** Namespace for grouping */
1118
+ namespace: string;
1119
+ /** Key within namespace */
1120
+ key: string;
1121
+ /** Memory value/content */
1122
+ value: string;
1123
+ /** Raw evidence text */
1124
+ rawEvidence: string;
1125
+ /** Confidence score (0-1) */
1126
+ confidence: number;
1127
+ /** Whether this contains PII */
1128
+ pii: boolean;
1129
+ /** Optional embedding vector */
1130
+ embedding?: number[];
1131
+ /** Optional embedding model name */
1132
+ embeddingModel?: string;
1133
+ }
1134
+ /**
1135
+ * Options for updating a memory
1136
+ */
1137
+ interface UpdateMemoryOptions {
1138
+ /** Memory type */
1139
+ type?: MemoryType;
1140
+ /** Namespace for grouping */
1141
+ namespace?: string;
1142
+ /** Key within namespace */
1143
+ key?: string;
1144
+ /** Memory value/content */
1145
+ value?: string;
1146
+ /** Raw evidence text */
1147
+ rawEvidence?: string;
1148
+ /** Confidence score (0-1) */
1149
+ confidence?: number;
1150
+ /** Whether this contains PII */
1151
+ pii?: boolean;
1152
+ /** Optional embedding vector */
1153
+ embedding?: number[];
1154
+ /** Optional embedding model name */
1155
+ embeddingModel?: string;
1156
+ }
1157
+ /**
1158
+ * Base options for useMemoryStorage hook (shared between React and Expo)
1159
+ */
1160
+ interface BaseUseMemoryStorageOptions {
1161
+ /** WatermelonDB database instance */
1162
+ database: Database;
1163
+ /** The model to use for fact extraction (default: "openai/gpt-4o") */
650
1164
  completionsModel?: string;
651
1165
  /**
652
1166
  * The model to use for generating embeddings
@@ -661,68 +1175,86 @@ type UseMemoryOptions = {
661
1175
  * "api": Uses the backend API
662
1176
  */
663
1177
  embeddingProvider?: "local" | "api";
664
- /**
665
- * Whether to automatically generate embeddings for extracted memories (default: true)
666
- */
1178
+ /** Whether to automatically generate embeddings for extracted memories (default: true) */
667
1179
  generateEmbeddings?: boolean;
668
- /**
669
- * Callback when facts are extracted
670
- */
1180
+ /** Callback when facts are extracted */
671
1181
  onFactsExtracted?: (facts: MemoryExtractionResult) => void;
672
- /**
673
- * Custom function to get auth token for API calls
674
- */
1182
+ /** Custom function to get auth token for API calls */
675
1183
  getToken?: () => Promise<string | null>;
1184
+ /** Optional base URL for the API requests */
1185
+ baseUrl?: string;
1186
+ }
1187
+ /**
1188
+ * Base result returned by useMemoryStorage hook (shared between React and Expo)
1189
+ */
1190
+ interface BaseUseMemoryStorageResult {
1191
+ /** Current memories in state (reactive) */
1192
+ memories: StoredMemory[];
1193
+ /** Refresh memories from storage */
1194
+ refreshMemories: () => Promise<void>;
676
1195
  /**
677
- * Optional base URL for the API requests.
1196
+ * Extract memories from messages and store them
1197
+ * @param options Messages and model to use for extraction
1198
+ * @returns Extraction result or null if failed
678
1199
  */
679
- baseUrl?: string;
680
- };
681
- type UseMemoryResult = {
682
1200
  extractMemoriesFromMessage: (options: {
683
1201
  messages: Array<{
684
1202
  role: string;
685
1203
  content: string;
686
1204
  }>;
687
- model: string;
1205
+ model?: string;
688
1206
  }) => Promise<MemoryExtractionResult | null>;
689
1207
  /**
690
1208
  * Search for similar memories using semantic search
691
1209
  * @param query The text query to search for
692
1210
  * @param limit Maximum number of results (default: 10)
693
1211
  * @param minSimilarity Minimum similarity threshold 0-1 (default: 0.6)
694
- * Note: Embedding similarity scores are typically lower than expected.
695
- * A score of 0.6-0.7 is usually a good match, 0.5-0.6 is moderate.
696
1212
  * @returns Array of memories with similarity scores, sorted by relevance
697
1213
  */
698
- searchMemories: (query: string, limit?: number, minSimilarity?: number) => Promise<Array<StoredMemoryItem & {
699
- similarity: number;
700
- }>>;
1214
+ searchMemories: (query: string, limit?: number, minSimilarity?: number) => Promise<StoredMemoryWithSimilarity[]>;
701
1215
  /**
702
- * Get all memories stored in IndexedDB
1216
+ * Get all memories stored in the database
703
1217
  * @returns Array of all stored memories
704
1218
  */
705
- fetchAllMemories: () => Promise<StoredMemoryItem[]>;
1219
+ fetchAllMemories: () => Promise<StoredMemory[]>;
706
1220
  /**
707
1221
  * Get memories filtered by namespace
708
1222
  * @param namespace The namespace to filter by
709
1223
  * @returns Array of memories in the specified namespace
710
1224
  */
711
- fetchMemoriesByNamespace: (namespace: string) => Promise<StoredMemoryItem[]>;
1225
+ fetchMemoriesByNamespace: (namespace: string) => Promise<StoredMemory[]>;
712
1226
  /**
713
1227
  * Get memories by namespace and key
714
1228
  * @param namespace The namespace
715
1229
  * @param key The key within the namespace
716
1230
  * @returns Array of memories matching the namespace and key
717
1231
  */
718
- fetchMemoriesByKey: (namespace: string, key: string) => Promise<StoredMemoryItem[]>;
1232
+ fetchMemoriesByKey: (namespace: string, key: string) => Promise<StoredMemory[]>;
1233
+ /**
1234
+ * Get a memory by its unique ID
1235
+ * @param id The memory unique ID
1236
+ * @returns The memory or null if not found
1237
+ */
1238
+ getMemoryById: (id: string) => Promise<StoredMemory | null>;
1239
+ /**
1240
+ * Save a single memory to storage
1241
+ * @param memory The memory to save
1242
+ * @returns The stored memory
1243
+ */
1244
+ saveMemory: (memory: CreateMemoryOptions) => Promise<StoredMemory>;
1245
+ /**
1246
+ * Save multiple memories to storage
1247
+ * @param memories Array of memories to save
1248
+ * @returns Array of stored memories
1249
+ */
1250
+ saveMemories: (memories: CreateMemoryOptions[]) => Promise<StoredMemory[]>;
719
1251
  /**
720
1252
  * Update a memory by its ID
721
1253
  * @param id The memory ID
722
1254
  * @param updates Partial memory fields to update
723
- * @returns The updated memory or undefined if not found
1255
+ * @returns The updated memory or null if not found
724
1256
  */
725
- updateMemory: (id: number, updates: Partial<StoredMemoryItem & MemoryItem>) => Promise<StoredMemoryItem | undefined>;
1257
+ updateMemory: (id: string, updates: UpdateMemoryOptions) => Promise<StoredMemory | null>;
726
1258
  /**
727
1259
  * Delete a specific memory by namespace, key, and value
728
1260
  * @param namespace The namespace
@@ -731,10 +1263,10 @@ type UseMemoryResult = {
731
1263
  */
732
1264
  removeMemory: (namespace: string, key: string, value: string) => Promise<void>;
733
1265
  /**
734
- * Delete a memory by its ID
1266
+ * Delete a memory by its ID (soft delete)
735
1267
  * @param id The memory ID
736
1268
  */
737
- removeMemoryById: (id: number) => Promise<void>;
1269
+ removeMemoryById: (id: string) => Promise<void>;
738
1270
  /**
739
1271
  * Delete all memories by namespace and key
740
1272
  * @param namespace The namespace
@@ -742,21 +1274,137 @@ type UseMemoryResult = {
742
1274
  */
743
1275
  removeMemories: (namespace: string, key: string) => Promise<void>;
744
1276
  /**
745
- * Clear all memories from IndexedDB
1277
+ * Clear all memories from storage
746
1278
  */
747
1279
  clearMemories: () => Promise<void>;
748
- };
1280
+ }
1281
+ /**
1282
+ * Generate composite key from namespace and key
1283
+ */
1284
+ declare function generateCompositeKey(namespace: string, key: string): string;
749
1285
  /**
750
- * Standalone hook for extracting memories from user messages.
751
- * Can be composed with other hooks like useChat, useFiles, etc.
1286
+ * Generate unique key from namespace, key, and value
752
1287
  */
753
- declare function useMemory(options?: UseMemoryOptions): UseMemoryResult;
1288
+ declare function generateUniqueKey(namespace: string, key: string, value: string): string;
1289
+
1290
+ /**
1291
+ * Options for useMemoryStorage hook (React version)
1292
+ *
1293
+ * Uses the base options. React-specific features can be added here if needed.
1294
+ */
1295
+ type UseMemoryStorageOptions = BaseUseMemoryStorageOptions;
1296
+ /**
1297
+ * Result returned by useMemoryStorage hook (React version)
1298
+ *
1299
+ * Uses the base result. React-specific features can be added here if needed.
1300
+ */
1301
+ type UseMemoryStorageResult = BaseUseMemoryStorageResult;
1302
+ /**
1303
+ * A React hook that wraps useMemory with automatic memory persistence using WatermelonDB.
1304
+ *
1305
+ * This hook provides all the functionality of useMemory plus automatic storage of
1306
+ * memories to a WatermelonDB database. Memories are automatically saved when extracted
1307
+ * and can be searched using semantic similarity.
1308
+ *
1309
+ * @param options - Configuration options
1310
+ * @returns An object containing memory state, methods, and storage operations
1311
+ *
1312
+ * @example
1313
+ * ```tsx
1314
+ * import { Database } from '@nozbe/watermelondb';
1315
+ * import { useMemoryStorage } from '@reverbia/sdk/react';
1316
+ *
1317
+ * function MemoryComponent({ database }: { database: Database }) {
1318
+ * const {
1319
+ * memories,
1320
+ * extractMemoriesFromMessage,
1321
+ * searchMemories,
1322
+ * fetchAllMemories,
1323
+ * } = useMemoryStorage({
1324
+ * database,
1325
+ * getToken: async () => getAuthToken(),
1326
+ * onFactsExtracted: (facts) => console.log('Extracted:', facts),
1327
+ * });
1328
+ *
1329
+ * const handleExtract = async () => {
1330
+ * const result = await extractMemoriesFromMessage({
1331
+ * messages: [{ role: 'user', content: 'My name is John and I live in NYC' }],
1332
+ * model: 'gpt-4o-mini',
1333
+ * });
1334
+ * };
1335
+ *
1336
+ * return (
1337
+ * <div>
1338
+ * <button onClick={handleExtract}>Extract Memories</button>
1339
+ * <p>Total memories: {memories.length}</p>
1340
+ * </div>
1341
+ * );
1342
+ * }
1343
+ * ```
1344
+ *
1345
+ * @category Hooks
1346
+ */
1347
+ declare function useMemoryStorage(options: UseMemoryStorageOptions): UseMemoryStorageResult;
1348
+
1349
+ /**
1350
+ * WatermelonDB schema for memory storage
1351
+ *
1352
+ * Defines the memories table for storing extracted user memories
1353
+ * with support for vector embeddings for semantic search.
1354
+ */
1355
+ declare const memoryStorageSchema: Readonly<{
1356
+ version: _nozbe_watermelondb_Schema.SchemaVersion;
1357
+ tables: _nozbe_watermelondb_Schema.TableMap;
1358
+ unsafeSql?: (_: string, __: _nozbe_watermelondb_Schema.AppSchemaUnsafeSqlKind) => string;
1359
+ }>;
1360
+
1361
+ /**
1362
+ * Memory model representing a single extracted memory
1363
+ *
1364
+ * Note: This model uses raw column accessors instead of decorators
1365
+ * for better TypeScript compatibility without requiring legacy decorators.
1366
+ */
1367
+ declare class Memory extends Model {
1368
+ static table: string;
1369
+ /** Memory type classification */
1370
+ get type(): MemoryType;
1371
+ /** Namespace for grouping related memories */
1372
+ get namespace(): string;
1373
+ /** Key within the namespace */
1374
+ get key(): string;
1375
+ /** The memory value/content */
1376
+ get value(): string;
1377
+ /** Raw evidence from which this memory was extracted */
1378
+ get rawEvidence(): string;
1379
+ /** Confidence score (0-1) */
1380
+ get confidence(): number;
1381
+ /** Whether this memory contains PII */
1382
+ get pii(): boolean;
1383
+ /** Composite key (namespace:key) for efficient lookups */
1384
+ get compositeKey(): string;
1385
+ /** Unique key (namespace:key:value) for deduplication */
1386
+ get uniqueKey(): string;
1387
+ /** Created timestamp */
1388
+ get createdAt(): Date;
1389
+ /** Updated timestamp */
1390
+ get updatedAt(): Date;
1391
+ /** Embedding vector for semantic search */
1392
+ get embedding(): number[] | undefined;
1393
+ /** Model used to generate embedding */
1394
+ get embeddingModel(): string | undefined;
1395
+ /** Soft delete flag */
1396
+ get isDeleted(): boolean;
1397
+ }
754
1398
 
755
1399
  interface PdfFile {
756
1400
  url: string;
757
1401
  mediaType?: string;
758
1402
  filename?: string;
759
1403
  }
1404
+ /**
1405
+ * React hook for extracting text from PDF files.
1406
+ * @category Hooks
1407
+ */
760
1408
  declare function usePdf(): {
761
1409
  extractPdfContext: (files: PdfFile[]) => Promise<string | null>;
762
1410
  isProcessing: boolean;
@@ -768,6 +1416,10 @@ interface OCRFile {
768
1416
  filename?: string;
769
1417
  language?: string;
770
1418
  }
1419
+ /**
1420
+ * React hook for extracting text from images using OCR.
1421
+ * @category Hooks
1422
+ */
771
1423
  declare function useOCR(): {
772
1424
  extractOCRContext: (files: OCRFile[]) => Promise<string | null>;
773
1425
  isProcessing: boolean;
@@ -801,6 +1453,7 @@ type UseModelsResult = {
801
1453
  /**
802
1454
  * React hook for fetching available LLM models.
803
1455
  * Automatically fetches all available models.
1456
+ * @category Hooks
804
1457
  */
805
1458
  declare function useModels(options?: UseModelsOptions): UseModelsResult;
806
1459
 
@@ -852,6 +1505,7 @@ type UseSearchResult = {
852
1505
  *
853
1506
  * @param options - Configuration options for the search hook
854
1507
  * @returns Object containing search function, results, loading state, and error
1508
+ * @category Hooks
855
1509
  *
856
1510
  * @example
857
1511
  * ```tsx
@@ -899,6 +1553,7 @@ type UseImageGenerationResult = {
899
1553
  };
900
1554
  /**
901
1555
  * React hook for generating images using the LLM API.
1556
+ * @category Hooks
902
1557
  */
903
1558
  declare function useImageGeneration(options?: UseImageGenerationOptions): UseImageGenerationResult;
904
1559
 
@@ -908,7 +1563,7 @@ declare function useImageGeneration(options?: UseImageGenerationOptions): UseIma
908
1563
  * @param format Format style: "compact" (key-value pairs) or "detailed" (includes evidence)
909
1564
  * @returns Formatted string ready to include in system/user message
910
1565
  */
911
- declare const formatMemoriesForChat: (memories: Array<StoredMemoryItem & {
1566
+ declare const formatMemoriesForChat: (memories: Array<StoredMemory & {
912
1567
  similarity?: number;
913
1568
  }>, format?: "compact" | "detailed") => string;
914
1569
  /**
@@ -917,7 +1572,7 @@ declare const formatMemoriesForChat: (memories: Array<StoredMemoryItem & {
917
1572
  * @param baseSystemPrompt Optional base system prompt (memories will be prepended)
918
1573
  * @returns System message content with memories
919
1574
  */
920
- declare const createMemoryContextSystemMessage: (memories: Array<StoredMemoryItem & {
1575
+ declare const createMemoryContextSystemMessage: (memories: Array<StoredMemory & {
921
1576
  similarity?: number;
922
1577
  }>, baseSystemPrompt?: string) => string;
923
1578
  /**
@@ -953,4 +1608,4 @@ declare function executeTool(tool: ClientTool, params: Record<string, unknown>):
953
1608
  error?: string;
954
1609
  }>;
955
1610
 
956
- export { type ClientTool, DEFAULT_TOOL_SELECTOR_MODEL, type OCRFile, type PdfFile, type SignMessageFn, type ToolExecutionResult, type ToolParameter, type ToolSelectionResult, createMemoryContextSystemMessage, decryptData, decryptDataBytes, encryptData, executeTool, extractConversationContext, formatMemoriesForChat, hasEncryptionKey, requestEncryptionKey, selectTool, useChat, useEncryption, useImageGeneration, useMemory, useModels, useOCR, usePdf, useSearch };
1611
+ export { Conversation as ChatConversation, Message as ChatMessage, type ChatRole, type ClientTool, type CreateConversationOptions, type CreateMemoryOptions, type CreateMessageOptions, DEFAULT_TOOL_SELECTOR_MODEL, type FileMetadata, type MemoryItem, type MemoryType, type OCRFile, type PdfFile, type SearchMessagesOptions, type SearchSource, type SendMessageWithStorageArgs, type SendMessageWithStorageResult, type SignMessageFn, type ChatCompletionUsage as StoredChatCompletionUsage, type StoredConversation, type StoredMemory, Memory as StoredMemoryModel, type StoredMemoryWithSimilarity, type StoredMessage, type StoredMessageWithSimilarity, type ToolExecutionResult, type ToolParameter, type ToolSelectionResult, type UpdateMemoryOptions, type UseChatStorageOptions, type UseChatStorageResult, type UseMemoryStorageOptions, type UseMemoryStorageResult, chatStorageSchema, createMemoryContextSystemMessage, decryptData, decryptDataBytes, encryptData, executeTool, extractConversationContext, formatMemoriesForChat, generateCompositeKey, generateConversationId, generateUniqueKey, hasEncryptionKey, memoryStorageSchema, requestEncryptionKey, selectTool, useChat, useChatStorage, useEncryption, useImageGeneration, useMemoryStorage, useModels, useOCR, usePdf, useSearch };