@onairosofficial/onairos-capacitor 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/CAPACITOR_QUICK_START.md +379 -0
  2. package/CONNECTORS.md +122 -0
  3. package/LICENSE +194 -10
  4. package/OnairosofficialOnairosCapacitor.podspec +13 -0
  5. package/Package.swift +26 -0
  6. package/README.md +176 -25
  7. package/dist/onairos.capacitor.esm.js +1 -0
  8. package/dist/onairos.capacitor.esm.turbopack.js +1 -0
  9. package/docs/CAPACITOR_INTEGRATION_GUIDE.md +159 -0
  10. package/docs/CAPACITOR_MOCK_APP_TESTING.md +213 -0
  11. package/docs/CAPACITOR_SDK_FIXES_SUMMARY.md +65 -0
  12. package/docs/CROSS_SDK_PARITY.md +239 -0
  13. package/docs/DATA_FREQUENCY.md +57 -0
  14. package/docs/DEVELOPER_SDK_CHANGES.md +532 -0
  15. package/docs/INCIDENT_ENABLETRAINING_PIN_WEB_8.1.9.md +82 -0
  16. package/docs/ONAIROS_BUTTON_PROPS.md +152 -0
  17. package/docs/PLATFORM_APIS.md +559 -0
  18. package/docs/RAW_MEMORIES_API.md +305 -0
  19. package/docs/RAW_MEMORIES_SDK_UPDATE.md +54 -0
  20. package/docs/SDK_PARITY_ROLLUP_2026_04_24_to_05_02.md +96 -0
  21. package/docs/oldFixes.md +216 -0
  22. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosChatGPTNativePlugin.swift +993 -0
  23. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosNetflixNativePlugin.swift +33 -0
  24. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosSpotifyNativePlugin.swift +1082 -0
  25. package/onairos.d.ts +656 -0
  26. package/package.json +188 -37
  27. package/src/OnairosReconnectButton.jsx +272 -0
  28. package/src/RSA.jsx +57 -0
  29. package/src/assets/NewLogo.png +0 -0
  30. package/src/assets/OnairosNewLogo.png +0 -0
  31. package/src/assets/chatgpt-icon.png +0 -0
  32. package/src/assets/fire-horse.png +0 -0
  33. package/src/assets/fire-horse.transparent.png +0 -0
  34. package/src/assets/latest-firehorse.png +0 -0
  35. package/src/assets/perplexity.png +0 -0
  36. package/src/assets/persona.png +0 -0
  37. package/src/assets/persona1.png +0 -0
  38. package/src/assets/persona2.png +0 -0
  39. package/src/assets/persona3.png +0 -0
  40. package/src/assets/persona4.png +0 -0
  41. package/src/assets/persona5.png +0 -0
  42. package/src/capacitorConnectorCatalog.js +38 -0
  43. package/src/capacitorOAuthConfig.js +52 -0
  44. package/src/chatgptHostedImport/index.js +303 -0
  45. package/src/components/AuthButtons.jsx +48 -0
  46. package/src/components/ConnectChatGPTModal.jsx +666 -0
  47. package/src/components/ConnectClaudeModal.jsx +610 -0
  48. package/src/components/ConnectGeminiModal.jsx +639 -0
  49. package/src/components/ConnectGrokModal.jsx +701 -0
  50. package/src/components/ConnectPerplexityModal.jsx +726 -0
  51. package/src/components/DataExplainerScreen.jsx +349 -0
  52. package/src/components/DataRequest.js +885 -0
  53. package/src/components/DataRequest.jsx +1055 -0
  54. package/src/components/EmailAuth.js +1871 -0
  55. package/src/components/EmailAuth.jsx +2062 -0
  56. package/src/components/ExtensionInstallPrompt.jsx +142 -0
  57. package/src/components/GoogleButton.js +133 -0
  58. package/src/components/LLMConnectorManager.jsx +201 -0
  59. package/src/components/LoadingPage.jsx +19 -0
  60. package/src/components/LoadingScreen.jsx +81 -0
  61. package/src/components/LunarBirthdate.jsx +96 -0
  62. package/src/components/LunarLoadingPage.jsx +251 -0
  63. package/src/components/Notification.jsx +21 -0
  64. package/src/components/OnairosAppButton.jsx +85 -0
  65. package/src/components/OnairosSSO.jsx +645 -0
  66. package/src/components/OnairosTrigger.jsx +61 -0
  67. package/src/components/PerplexityLogo.jsx +43 -0
  68. package/src/components/PinSetup.js +200 -0
  69. package/src/components/PinSetup.jsx +228 -0
  70. package/src/components/SDK_PIN_INTEGRATION_REQUIRED_CHANGES.md +526 -0
  71. package/src/components/SdkErrorBoundary.jsx +36 -0
  72. package/src/components/SecuritySetup.js +81 -0
  73. package/src/components/SessionUserBar.jsx +83 -0
  74. package/src/components/SignUp.js +123 -0
  75. package/src/components/TestTelegramButton.js +53 -0
  76. package/src/components/TrainingComponent.jsx +200 -0
  77. package/src/components/TrainingScreen.jsx +897 -0
  78. package/src/components/UniversalOnboarding.js +306 -0
  79. package/src/components/UniversalOnboarding.jsx +4837 -0
  80. package/src/components/ValentineLoadingPage.jsx +502 -0
  81. package/src/components/ValentineModeSelector.jsx +162 -0
  82. package/src/components/WelcomeScreen.jsx +435 -0
  83. package/src/components/WrappedLoadingPage.jsx +205 -0
  84. package/src/components/connectors/ChatGPTConnector.js +348 -0
  85. package/src/components/connectors/ChatGPTConnector.jsx +348 -0
  86. package/src/components/connectors/ClaudeConnector.js +44 -0
  87. package/src/components/connectors/ClaudeConnector.jsx +44 -0
  88. package/src/components/connectors/GeminiConnector.js +170 -0
  89. package/src/components/connectors/GeminiConnector.jsx +170 -0
  90. package/src/components/connectors/GmailConnector.js +148 -0
  91. package/src/components/connectors/GmailConnector.jsx +148 -0
  92. package/src/components/connectors/GrokConnector.js +16 -0
  93. package/src/components/connectors/GrokConnector.jsx +16 -0
  94. package/src/components/connectors/HingeConnector.js +419 -0
  95. package/src/components/connectors/HingeConnector.jsx +419 -0
  96. package/src/components/connectors/InstagramDataConnector.js +726 -0
  97. package/src/components/connectors/InstagramDataConnector.jsx +726 -0
  98. package/src/components/connectors/LinkedInConnector.js +4 -0
  99. package/src/components/connectors/LinkedInConnector.jsx +296 -0
  100. package/src/components/connectors/PerplexityConnector.jsx +16 -0
  101. package/src/components/connectors/PinterestConnector.js +208 -0
  102. package/src/components/connectors/PinterestConnector.jsx +208 -0
  103. package/src/components/connectors/README.md +292 -0
  104. package/src/components/connectors/RedditConnector.js +229 -0
  105. package/src/components/connectors/RedditConnector.jsx +229 -0
  106. package/src/components/connectors/SephoraConnector.js +482 -0
  107. package/src/components/connectors/SephoraConnector.jsx +482 -0
  108. package/src/components/connectors/TikTokConnector.jsx +430 -0
  109. package/src/components/connectors/YoutubeConnector.js +361 -0
  110. package/src/components/connectors/YoutubeConnector.jsx +361 -0
  111. package/src/components/connectors/index.js +50 -0
  112. package/src/components/icons.jsx +46 -0
  113. package/src/components/icons.tsx +21 -0
  114. package/src/components/ui/PageLayout.jsx +1255 -0
  115. package/src/components/ui/PrimaryButton.jsx +162 -0
  116. package/src/components/ui/button.jsx +49 -0
  117. package/src/components/ui/card.jsx +61 -0
  118. package/src/components/ui/checkbox.jsx +33 -0
  119. package/src/components/ui/label.jsx +29 -0
  120. package/src/components/utils/UpdateConnections.js +45 -0
  121. package/src/components/utils/oauthHelper.js +97 -0
  122. package/src/config/api-config.js +138 -0
  123. package/src/deepLink.jsx +38 -0
  124. package/src/getPin.js +26 -0
  125. package/src/icons/Avatar.png +0 -0
  126. package/src/icons/Sentiment.png +0 -0
  127. package/src/icons/Trait.png +0 -0
  128. package/src/iframe/DataRequestPage.jsx +285 -0
  129. package/src/iframe/OnairosButtonIntegration.md +148 -0
  130. package/src/iframe/components/Box.jsx +56 -0
  131. package/src/iframe/components/IndividualConnection.jsx +88 -0
  132. package/src/iframe/dataRequestHandler.js +714 -0
  133. package/src/iframe/data_request_iframe.html +27 -0
  134. package/src/iframe/data_request_page.js +47 -0
  135. package/src/iframe/icons/Avatar.png +1 -0
  136. package/src/iframe/icons/Avatar2.png +1 -0
  137. package/src/iframe/icons/Sentiment.png +1 -0
  138. package/src/iframe/icons/Trait.png +1 -0
  139. package/src/iframe/icons/onairos_logo.png +0 -0
  140. package/src/iframe/utils/api.js +57 -0
  141. package/src/index.js +274 -0
  142. package/src/laravel/OnairosVue.vue +410 -0
  143. package/src/laravel/blade-helpers.js +320 -0
  144. package/src/laravel/vite-plugin.js +179 -0
  145. package/src/mobile/MobileDataRequestPage.jsx +233 -0
  146. package/src/mobile/components/MobileBox.jsx +71 -0
  147. package/src/mobile/components/MobileIndividualConnection.jsx +51 -0
  148. package/src/mobile/shims/browser-apis.js +78 -0
  149. package/src/mobile/shims/lucide-shim.js +85 -0
  150. package/src/nativeConnectors.js +5 -0
  151. package/src/newUI/EMAIL_VERIFICATION_API_SCHEMA.md +268 -0
  152. package/src/newUI/PlatformConnectorsStep.tsx +435 -0
  153. package/src/newUI/PrimaryButton.tsx +213 -0
  154. package/src/newUI/SignInStep.tsx +194 -0
  155. package/src/newUI/VerificationStep.tsx +133 -0
  156. package/src/newUI/WelcomeScreen.tsx +311 -0
  157. package/src/newUI/services/connectedAccountsService.js +129 -0
  158. package/src/onairos.capacitor.jsx +15 -0
  159. package/src/onairos.core.jsx +133 -0
  160. package/src/onairos.jsx +14 -0
  161. package/src/onairos.native.jsx +15 -0
  162. package/src/onairosButton.jsx +9000 -0
  163. package/src/overlay/CheckBox.jsx +114 -0
  164. package/src/overlay/IndividualConnection copy.js +86 -0
  165. package/src/overlay/IndividualConnection.js +191 -0
  166. package/src/overlay/IndividualConnectionNew.jsx +157 -0
  167. package/src/overlay/box.js +84 -0
  168. package/src/overlay/overlay.js +437 -0
  169. package/src/styles/onairos-scoped-preflight.css +97 -0
  170. package/src/styles/sdkCssRegistry.js +20 -0
  171. package/src/styles/styleLoaderInsertShadow.js +69 -0
  172. package/src/styles/tailwind.capacitor.css +395 -0
  173. package/src/styles/tailwind.css +395 -0
  174. package/src/theme/colors.js +40 -0
  175. package/src/utils/apiKeyValidation.js +341 -0
  176. package/src/utils/apiResponseLogger.js +316 -0
  177. package/src/utils/authHeaders.js +275 -0
  178. package/src/utils/biometrics.js +26 -0
  179. package/src/utils/bookmarkletUtils.js +28 -0
  180. package/src/utils/capacitorDetection.js +278 -0
  181. package/src/utils/capacitorLLMHelper.js +352 -0
  182. package/src/utils/capacitorPlugins.js +366 -0
  183. package/src/utils/crossDomainSSO.js +587 -0
  184. package/src/utils/deepLinking.js +27 -0
  185. package/src/utils/devLogger.js +46 -0
  186. package/src/utils/extensionDetection.js +418 -0
  187. package/src/utils/extractMemory.js +277 -0
  188. package/src/utils/framerBrandingOverrides.js +40 -0
  189. package/src/utils/googleWebClientId.js +55 -0
  190. package/src/utils/overlayHandler.js +224 -0
  191. package/src/utils/platformDisconnect.js +309 -0
  192. package/src/utils/pollTrainingStatus.js +200 -0
  193. package/src/utils/rawMemoriesAccess.js +211 -0
  194. package/src/utils/resolveBackendAppId.js +47 -0
  195. package/src/utils/responseFormatter.js +140 -0
  196. package/src/utils/sdkDebugStorage.js +113 -0
  197. package/src/utils/sdkInitialization.js +645 -0
  198. package/src/utils/sessionManager.js +1258 -0
  199. package/src/utils/startBackgroundTraining.js +100 -0
  200. package/src/utils/userDataFormatter.js +222 -0
  201. package/index.d.ts +0 -1
  202. package/index.js +0 -1
@@ -0,0 +1,418 @@
1
+ /**
2
+ * Browser Extension Detection Utility
3
+ *
4
+ * This utility detects if the browser extension is installed
5
+ * by checking for the global window.onairos object that the extension injects.
6
+ *
7
+ * Based on the extension's inject-script.js implementation:
8
+ * - window.onairos.isOnairos = true
9
+ * - window.onairos.version = '1.0.0'
10
+ * - 'onairosReady' event is dispatched when extension loads
11
+ */
12
+
13
+ import { getApiBaseUrl } from '../config/api-config.js';
14
+
15
+ /**
16
+ * Chrome Web Store URL for the browser extension
17
+ */
18
+ export const ONAIROS_EXTENSION_STORE_URL = 'https://chromewebstore.google.com/detail/onairos/apkfageplidiblifhnadehmplfccapkf?hl=en';
19
+
20
+ /**
21
+ * Timeout for extension detection (in milliseconds)
22
+ */
23
+ const DETECTION_TIMEOUT = 2000;
24
+
25
+ /**
26
+ * Detect if the browser extension is installed
27
+ * @returns {Promise<boolean>} True if extension is installed and active
28
+ */
29
+ export const detectOnairosExtension = () => {
30
+ return new Promise((resolve) => {
31
+ // Method 1: Direct detection - check if already loaded
32
+ if (window.onairos && window.onairos.isOnairos) {
33
+ resolve(true);
34
+ return;
35
+ }
36
+
37
+ // Method 2: Event-based detection - wait for extension to load
38
+ let resolved = false;
39
+
40
+ const handleOnairosReady = () => {
41
+ if (!resolved) {
42
+ resolved = true;
43
+ resolve(true);
44
+ }
45
+ };
46
+
47
+ // Listen for the onairosReady event
48
+ window.addEventListener('onairosReady', handleOnairosReady, { once: true });
49
+
50
+ // Set timeout to avoid waiting indefinitely
51
+ setTimeout(() => {
52
+ if (!resolved) {
53
+ resolved = true;
54
+ window.removeEventListener('onairosReady', handleOnairosReady);
55
+ resolve(false);
56
+ }
57
+ }, DETECTION_TIMEOUT);
58
+ });
59
+ };
60
+
61
+ /**
62
+ * Get extension information if available
63
+ * @returns {Object|null} Extension info or null if not available
64
+ */
65
+ export const getExtensionInfo = () => {
66
+ if (window.onairos && window.onairos.getInfo) {
67
+ return window.onairos.getInfo();
68
+ }
69
+ return null;
70
+ };
71
+
72
+ /**
73
+ * Check if extension is available synchronously (for already loaded extensions)
74
+ * @returns {boolean} True if extension is immediately available
75
+ */
76
+ export const isExtensionAvailableSync = () => {
77
+ return !!(window.onairos && window.onairos.isOnairos);
78
+ };
79
+
80
+ /**
81
+ * Open Chrome Web Store to install the extension
82
+ * @param {string} source - Source identifier for analytics (e.g., 'chatgpt', 'claude')
83
+ */
84
+ export const openExtensionInstallPage = (source = 'unknown') => {
85
+ const storeUrl = ONAIROS_EXTENSION_STORE_URL;
86
+
87
+ // Try to open in new tab
88
+ const installWindow = window.open(storeUrl, '_blank');
89
+
90
+ if (!installWindow) {
91
+ console.warn('Popup blocked, redirecting to store');
92
+ window.location.href = storeUrl;
93
+ }
94
+ };
95
+
96
+ /**
97
+ * LLM Platform URLs
98
+ */
99
+ export const LLM_URLS = {
100
+ chatgpt: 'https://chatgpt.com',
101
+ claude: 'https://claude.ai',
102
+ gemini: 'https://gemini.google.com',
103
+ grok: 'https://grok.com',
104
+ perplexity: 'https://www.perplexity.ai'
105
+ };
106
+
107
+ /**
108
+ * Open LLM platform if extension is installed, otherwise prompt for extension installation
109
+ * @param {string} platform - LLM platform name ('chatgpt', 'claude', 'gemini', 'grok')
110
+ * @param {Function} onExtensionMissing - Callback when extension is not installed
111
+ * @param {Object} userInfo - User information to pass to the LLM platform
112
+ * @param {string} userInfo.username - User's username/email
113
+ * @param {string} userInfo.userId - User's unique identifier
114
+ * @param {string} userInfo.sessionToken - Optional session token
115
+ * @returns {Promise<boolean>} True if LLM was opened, false if extension missing
116
+ */
117
+ export const openLLMWithExtensionCheck = async (platform, onExtensionMissing = null, userInfo = {}) => {
118
+ // Check if extension is installed
119
+ const hasExtension = await detectOnairosExtension();
120
+
121
+ if (hasExtension) {
122
+ // Extension is installed - open the LLM platform
123
+ const baseUrl = LLM_URLS[platform];
124
+ if (baseUrl) {
125
+ const finalUrl = baseUrl;
126
+
127
+ const llmWindow = window.open(finalUrl, '_blank');
128
+
129
+ if (!llmWindow) {
130
+ return false;
131
+ }
132
+ return true;
133
+ } else {
134
+ console.error('Unknown LLM platform:', platform);
135
+ return false;
136
+ }
137
+ } else {
138
+ // Extension is not installed - handle missing extension
139
+ if (onExtensionMissing) {
140
+ onExtensionMissing(platform);
141
+ } else {
142
+ // Default behavior: open extension store
143
+ openExtensionInstallPage(platform);
144
+ }
145
+
146
+ return false;
147
+ }
148
+ };
149
+
150
+ /**
151
+ * Enhanced extension detection with retry mechanism
152
+ * @param {number} maxRetries - Maximum number of detection attempts
153
+ * @param {number} retryDelay - Delay between retries in milliseconds
154
+ * @returns {Promise<boolean>} True if extension is detected
155
+ */
156
+ export const detectExtensionWithRetry = async (maxRetries = 3, retryDelay = 500) => {
157
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
158
+ const detected = await detectOnairosExtension();
159
+ if (detected) {
160
+ return true;
161
+ }
162
+
163
+ if (attempt < maxRetries) {
164
+ await new Promise(resolve => setTimeout(resolve, retryDelay));
165
+ }
166
+ }
167
+
168
+ return false;
169
+ };
170
+
171
+ /**
172
+ * Extract user information from URL parameters
173
+ * This function is intended to be used by the browser extension to read user info
174
+ * @param {string} url - URL to parse (defaults to current page URL)
175
+ * @returns {Object|null} User information object or null if no params found
176
+ */
177
+ export const extractUserInfoFromURL = (url = window.location.href) => {
178
+ try {
179
+ const urlObj = new URL(url);
180
+ const params = urlObj.searchParams;
181
+
182
+ // Check if this URL has Onairos parameters
183
+ if (!params.has('onairos_user') && !params.has('onairos_id')) {
184
+ return null;
185
+ }
186
+
187
+ const userInfo = {
188
+ username: params.get('onairos_user') ? decodeURIComponent(params.get('onairos_user')) : null,
189
+ userId: params.get('onairos_id') ? decodeURIComponent(params.get('onairos_id')) : null,
190
+ sessionToken: params.get('onairos_session') ? decodeURIComponent(params.get('onairos_session')) : null,
191
+ platform: params.get('onairos_platform') || null,
192
+ source: params.get('onairos_source') || null,
193
+ timestamp: params.get('onairos_timestamp') || null
194
+ };
195
+
196
+ // Only return if we have at least username or userId
197
+ if (userInfo.username || userInfo.userId) {
198
+ return userInfo;
199
+ }
200
+
201
+ return null;
202
+ } catch (error) {
203
+ console.error('Error extracting user info from URL:', error);
204
+ return null;
205
+ }
206
+ };
207
+
208
+ /**
209
+ * Send user information to the browser extension
210
+ * This function communicates with the extension to provide user context
211
+ * @param {Object} userInfo - User information to send
212
+ * @returns {Promise<boolean>} True if successfully sent to extension
213
+ */
214
+ export const sendUserInfoToExtension = async (userInfo) => {
215
+ try {
216
+ if (!window.onairos || !window.onairos.isOnairos) {
217
+ return false;
218
+ }
219
+
220
+ // Send user info via postMessage to the extension
221
+ window.postMessage({
222
+ source: 'onairos_npm_connector',
223
+ type: 'USER_INFO',
224
+ data: {
225
+ ...userInfo,
226
+ timestamp: new Date().toISOString(),
227
+ connectorVersion: '3.4.2'
228
+ }
229
+ }, window.location.origin);
230
+
231
+ return true;
232
+ } catch (error) {
233
+ console.error('Error sending user info to extension:', error);
234
+ return false;
235
+ }
236
+ };
237
+
238
+ /**
239
+ * Send LLM conversation data to backend (for browser extension)
240
+ * This function formats and sends encrypted conversation data to the /llm-data/store endpoint
241
+ * @param {Object} conversationData - Raw conversation data
242
+ * @param {Object} userInfo - User authentication info
243
+ * @param {string} platform - LLM platform (chatgpt, claude, gemini, grok)
244
+ * @returns {Promise<boolean>} True if successfully stored
245
+ */
246
+ export const storeLLMConversationData = async (conversationData, userInfo, platform) => {
247
+ try {
248
+ // Format data according to backend API schema
249
+ const payload = {
250
+ encryptedData: btoa(JSON.stringify(conversationData)), // Base64 encode for now
251
+ encryptionMetadata: {
252
+ algorithm: "AES-GCM",
253
+ keyDerivation: "PBKDF2",
254
+ iterations: 100000
255
+ },
256
+ authentication: {
257
+ username: userInfo.username || userInfo.email,
258
+ timestamp: Date.now()
259
+ },
260
+ integrity: {
261
+ hash: await generateDataHash(conversationData),
262
+ algorithm: "SHA-256"
263
+ },
264
+ platform: platform,
265
+ source: 'browser_extension'
266
+ };
267
+
268
+ const response = await fetch(`${getApiBaseUrl()}/llm-data/store`, {
269
+ method: 'POST',
270
+ headers: {
271
+ 'Content-Type': 'application/json',
272
+ 'Authorization': `Bearer ${userInfo.sessionToken || userInfo.jwtToken}`,
273
+ 'X-Onairos-User': userInfo.userId || userInfo.username
274
+ },
275
+ body: JSON.stringify(payload)
276
+ });
277
+
278
+ if (response.ok) {
279
+ return true;
280
+ } else {
281
+ console.error('Failed to store LLM data:', response.status);
282
+ return false;
283
+ }
284
+ } catch (error) {
285
+ console.error('Error storing LLM data:', error);
286
+ return false;
287
+ }
288
+ };
289
+
290
+ /**
291
+ * Generate SHA-256 hash of data for integrity verification
292
+ * @param {Object} data - Data to hash
293
+ * @returns {Promise<string>} SHA-256 hash
294
+ */
295
+ async function generateDataHash(data) {
296
+ try {
297
+ const encoder = new TextEncoder();
298
+ const dataString = JSON.stringify(data);
299
+ const dataBuffer = encoder.encode(dataString);
300
+ const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
301
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
302
+ const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
303
+ return `sha256-${hashHex}`;
304
+ } catch (error) {
305
+ console.error('Error generating hash:', error);
306
+ return `sha256-${Date.now()}`; // Fallback
307
+ }
308
+ }
309
+
310
+ /**
311
+ * Get user information from standard localStorage keys
312
+ * @returns {Object} User information from localStorage
313
+ */
314
+ export const getUserInfoFromStorage = () => {
315
+ try {
316
+ const userDataStr = localStorage.getItem('onairosUser');
317
+ const jwtToken = localStorage.getItem('onairos_jwt_token');
318
+ const legacyToken = localStorage.getItem('onairosToken');
319
+ const username = localStorage.getItem('username');
320
+ const userDataSDK = localStorage.getItem('onairos_user_data');
321
+
322
+ let userData = null;
323
+
324
+ // Try to parse main user data
325
+ if (userDataStr) {
326
+ try {
327
+ userData = JSON.parse(userDataStr);
328
+ } catch (error) {
329
+ // Skip unparseable data
330
+ }
331
+ }
332
+
333
+ // Try to parse SDK user data as fallback
334
+ if (!userData && userDataSDK) {
335
+ try {
336
+ userData = JSON.parse(userDataSDK);
337
+ } catch (error) {
338
+ // Skip unparseable data
339
+ }
340
+ }
341
+
342
+ // Build comprehensive user info object
343
+ const userInfo = {
344
+ // User identification
345
+ username: userData?.email || userData?.username || username || null,
346
+ userId: userData?.userId || userData?.email || username || null,
347
+ email: userData?.email || null,
348
+
349
+ // Authentication tokens
350
+ sessionToken: jwtToken || userData?.token || legacyToken || null,
351
+ jwtToken: jwtToken || userData?.token || null,
352
+
353
+ // User metadata
354
+ isNewUser: userData?.isNewUser || false,
355
+ verified: userData?.verified || false,
356
+ onboardingComplete: userData?.onboardingComplete || false,
357
+ pinCreated: userData?.pinCreated || false,
358
+
359
+ // Account details
360
+ accountInfo: userData?.accountInfo || null,
361
+ connectedAccounts: userData?.connectedAccounts || [],
362
+
363
+ // Timestamps
364
+ lastLogin: userData?.lastLogin || null,
365
+ createdAt: userData?.createdAt || null,
366
+
367
+ // Source tracking
368
+ source: 'localStorage_extraction',
369
+ extractedAt: new Date().toISOString()
370
+ };
371
+
372
+ return userInfo;
373
+ } catch (error) {
374
+ console.error('Error extracting user info:', error);
375
+ return {
376
+ username: null,
377
+ userId: null,
378
+ sessionToken: null,
379
+ source: 'extraction_failed',
380
+ error: error.message
381
+ };
382
+ }
383
+ };
384
+
385
+ /**
386
+ * Initialize user context for the current page
387
+ * This should be called when the page loads to set up user context for the extension
388
+ * @param {Object} userInfo - User information to initialize (optional, will auto-extract if not provided)
389
+ */
390
+ export const initializeUserContext = async (userInfo = null) => {
391
+ // If no user info provided, extract from localStorage
392
+ if (!userInfo) {
393
+ userInfo = getUserInfoFromStorage();
394
+ }
395
+
396
+ // First try to extract user info from URL (in case we're on an LLM platform)
397
+ const urlUserInfo = extractUserInfoFromURL();
398
+
399
+ // Merge URL info with provided/extracted info (URL takes precedence)
400
+ const finalUserInfo = {
401
+ ...userInfo,
402
+ ...urlUserInfo
403
+ };
404
+
405
+ if (finalUserInfo.username || finalUserInfo.userId) {
406
+ // Try to send to extension
407
+ const sent = await sendUserInfoToExtension(finalUserInfo);
408
+
409
+ if (!sent) {
410
+ // Store in localStorage as fallback
411
+ localStorage.setItem('onairos_user_context', JSON.stringify(finalUserInfo));
412
+ }
413
+
414
+ return finalUserInfo;
415
+ } else {
416
+ return null;
417
+ }
418
+ };
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Extract meaningful memory data from user interactions
3
+ * This function determines what information should be stored in the vector database
4
+ * for future RAG retrieval, focusing on preferences, insights, and key information
5
+ * rather than raw conversation data.
6
+ */
7
+
8
+ /**
9
+ * Extract memory data from a query-response interaction
10
+ * @param {Object} params - Extraction parameters
11
+ * @param {string} params.query - User query
12
+ * @param {string} params.response - Assistant response
13
+ * @returns {string|null} Extracted memory data or null if nothing meaningful
14
+ */
15
+ export function extractMemory({ query, response }) {
16
+ if (!query || !response) {
17
+ return null;
18
+ }
19
+
20
+ const queryLower = query.toLowerCase();
21
+ const responseLower = response.toLowerCase();
22
+
23
+ // Extract user preferences
24
+ const preferenceMemory = extractPreferences(queryLower, response);
25
+ if (preferenceMemory) {
26
+ return preferenceMemory;
27
+ }
28
+
29
+ // Extract personal information and interests
30
+ const personalMemory = extractPersonalInfo(queryLower, response);
31
+ if (personalMemory) {
32
+ return personalMemory;
33
+ }
34
+
35
+ // Extract goals and objectives
36
+ const goalMemory = extractGoals(queryLower, response);
37
+ if (goalMemory) {
38
+ return goalMemory;
39
+ }
40
+
41
+ // Extract skills and expertise
42
+ const skillMemory = extractSkills(queryLower, response);
43
+ if (skillMemory) {
44
+ return skillMemory;
45
+ }
46
+
47
+ // Extract context and background
48
+ const contextMemory = extractContext(queryLower, response);
49
+ if (contextMemory) {
50
+ return contextMemory;
51
+ }
52
+
53
+ // Extract decisions and choices
54
+ const decisionMemory = extractDecisions(queryLower, response);
55
+ if (decisionMemory) {
56
+ return decisionMemory;
57
+ }
58
+
59
+ return null; // No meaningful memory to extract
60
+ }
61
+
62
+ /**
63
+ * Extract user preferences from interactions
64
+ */
65
+ function extractPreferences(query, response) {
66
+ const preferenceKeywords = [
67
+ 'favorite', 'prefer', 'like', 'love', 'enjoy', 'hate', 'dislike',
68
+ 'best', 'worst', 'choose', 'pick', 'select', 'want', 'need'
69
+ ];
70
+
71
+ const hasPreferenceKeyword = preferenceKeywords.some(keyword =>
72
+ query.includes(keyword)
73
+ );
74
+
75
+ if (hasPreferenceKeyword) {
76
+ // Extract specific preferences mentioned in the response
77
+ if (query.includes('favorite') && response.length > 10) {
78
+ return `User's favorite: ${response.substring(0, 200)}`;
79
+ }
80
+
81
+ if (query.includes('prefer') && response.length > 10) {
82
+ return `User prefers: ${response.substring(0, 200)}`;
83
+ }
84
+
85
+ if ((query.includes('like') || query.includes('love')) && response.length > 10) {
86
+ return `User likes: ${response.substring(0, 200)}`;
87
+ }
88
+
89
+ if ((query.includes('dislike') || query.includes('hate')) && response.length > 10) {
90
+ return `User dislikes: ${response.substring(0, 200)}`;
91
+ }
92
+ }
93
+
94
+ return null;
95
+ }
96
+
97
+ /**
98
+ * Extract personal information and interests
99
+ */
100
+ function extractPersonalInfo(query, response) {
101
+ const personalKeywords = [
102
+ 'i am', 'i work', 'i study', 'my job', 'my role', 'my background',
103
+ 'i live', 'my experience', 'my hobby', 'my interest', 'i enjoy',
104
+ 'my name', 'my age', 'my family', 'my education'
105
+ ];
106
+
107
+ const hasPersonalKeyword = personalKeywords.some(keyword =>
108
+ query.includes(keyword)
109
+ );
110
+
111
+ if (hasPersonalKeyword && response.length > 20) {
112
+ if (query.includes('i am') || query.includes('i work') || query.includes('my job')) {
113
+ return `User's profession/role: ${response.substring(0, 150)}`;
114
+ }
115
+
116
+ if (query.includes('i live') || query.includes('my location')) {
117
+ return `User's location: ${response.substring(0, 100)}`;
118
+ }
119
+
120
+ if (query.includes('my hobby') || query.includes('my interest') || query.includes('i enjoy')) {
121
+ return `User's interests: ${response.substring(0, 150)}`;
122
+ }
123
+
124
+ if (query.includes('my background') || query.includes('my experience')) {
125
+ return `User's background: ${response.substring(0, 200)}`;
126
+ }
127
+ }
128
+
129
+ return null;
130
+ }
131
+
132
+ /**
133
+ * Extract goals and objectives
134
+ */
135
+ function extractGoals(query, response) {
136
+ const goalKeywords = [
137
+ 'my goal', 'i want to', 'i plan to', 'i hope to', 'i aim to',
138
+ 'my objective', 'my target', 'i intend to', 'looking to', 'trying to'
139
+ ];
140
+
141
+ const hasGoalKeyword = goalKeywords.some(keyword =>
142
+ query.includes(keyword)
143
+ );
144
+
145
+ if (hasGoalKeyword && response.length > 20) {
146
+ return `User's goal: ${response.substring(0, 200)}`;
147
+ }
148
+
149
+ return null;
150
+ }
151
+
152
+ /**
153
+ * Extract skills and expertise
154
+ */
155
+ function extractSkills(query, response) {
156
+ const skillKeywords = [
157
+ 'i know', 'i can', 'my skill', 'i am good at', 'i am expert',
158
+ 'my expertise', 'i specialize', 'my strength', 'i am proficient'
159
+ ];
160
+
161
+ const hasSkillKeyword = skillKeywords.some(keyword =>
162
+ query.includes(keyword)
163
+ );
164
+
165
+ if (hasSkillKeyword && response.length > 20) {
166
+ return `User's skills: ${response.substring(0, 150)}`;
167
+ }
168
+
169
+ return null;
170
+ }
171
+
172
+ /**
173
+ * Extract context and background information
174
+ */
175
+ function extractContext(query, response) {
176
+ const contextKeywords = [
177
+ 'currently', 'right now', 'at the moment', 'these days',
178
+ 'recently', 'lately', 'this week', 'this month', 'this year'
179
+ ];
180
+
181
+ const hasContextKeyword = contextKeywords.some(keyword =>
182
+ query.includes(keyword)
183
+ );
184
+
185
+ if (hasContextKeyword && response.length > 30) {
186
+ return `Current context: ${response.substring(0, 180)}`;
187
+ }
188
+
189
+ return null;
190
+ }
191
+
192
+ /**
193
+ * Extract important decisions and choices
194
+ */
195
+ function extractDecisions(query, response) {
196
+ const decisionKeywords = [
197
+ 'i decided', 'i chose', 'i selected', 'i picked', 'my decision',
198
+ 'i will', 'i am going to', 'i have decided', 'my choice'
199
+ ];
200
+
201
+ const hasDecisionKeyword = decisionKeywords.some(keyword =>
202
+ query.includes(keyword)
203
+ );
204
+
205
+ if (hasDecisionKeyword && response.length > 20) {
206
+ return `User's decision: ${response.substring(0, 180)}`;
207
+ }
208
+
209
+ return null;
210
+ }
211
+
212
+ /**
213
+ * Extract memory based on response patterns
214
+ * @param {string} query - User query
215
+ * @param {string} response - Assistant response
216
+ * @returns {string|null} Extracted memory or null
217
+ */
218
+ export function extractMemoryFromResponse(query, response) {
219
+ // Look for factual information in responses
220
+ if (response.includes('you mentioned') || response.includes('you said')) {
221
+ return `Context reference: ${response.substring(0, 200)}`;
222
+ }
223
+
224
+ // Extract recommendations given to the user
225
+ if (response.includes('I recommend') || response.includes('I suggest')) {
226
+ return `Recommendation given: ${response.substring(0, 200)}`;
227
+ }
228
+
229
+ // Extract explanations of user's situation
230
+ if (response.includes('based on your') || response.includes('given your')) {
231
+ return `User situation: ${response.substring(0, 200)}`;
232
+ }
233
+
234
+ return null;
235
+ }
236
+
237
+ /**
238
+ * Determine if an interaction contains meaningful memory
239
+ * @param {string} query - User query
240
+ * @param {string} response - Assistant response
241
+ * @returns {boolean} True if interaction contains meaningful memory
242
+ */
243
+ export function hasMeaningfulMemory(query, response) {
244
+ if (!query || !response || query.length < 10 || response.length < 20) {
245
+ return false;
246
+ }
247
+
248
+ // Skip generic greetings and simple questions
249
+ const genericPatterns = [
250
+ 'hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening',
251
+ 'how are you', 'what is', 'what are', 'how do', 'can you', 'please help'
252
+ ];
253
+
254
+ const queryLower = query.toLowerCase();
255
+ const isGeneric = genericPatterns.some(pattern =>
256
+ queryLower.includes(pattern) && queryLower.length < 50
257
+ );
258
+
259
+ return !isGeneric;
260
+ }
261
+
262
+ /**
263
+ * Clean and format memory data
264
+ * @param {string} memoryData - Raw memory data
265
+ * @returns {string} Cleaned memory data
266
+ */
267
+ export function cleanMemoryData(memoryData) {
268
+ if (!memoryData) {
269
+ return '';
270
+ }
271
+
272
+ return memoryData
273
+ .trim()
274
+ .replace(/\s+/g, ' ') // Replace multiple spaces with single space
275
+ .replace(/[^\w\s.,!?-]/g, '') // Remove special characters except basic punctuation
276
+ .substring(0, 500); // Limit length
277
+ }