@ateam-ai-mobile/expo 0.1.19 → 0.1.21
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/dist/aiLive/provider.d.mts +20 -0
- package/dist/aiLive/provider.d.ts +20 -0
- package/dist/aiLive/provider.js +400 -0
- package/dist/aiLive/provider.js.map +1 -0
- package/dist/aiLive/provider.mjs +15 -0
- package/dist/aiLive/provider.mjs.map +1 -0
- package/dist/bootstrap.js +350 -3
- package/dist/bootstrap.js.map +1 -1
- package/dist/bootstrap.mjs +17 -12
- package/dist/bootstrap.mjs.map +1 -1
- package/dist/capabilities/index.d.mts +40 -1
- package/dist/capabilities/index.d.ts +40 -1
- package/dist/capabilities/index.js +50 -14
- package/dist/capabilities/index.js.map +1 -1
- package/dist/capabilities/index.mjs +49 -32
- package/dist/capabilities/index.mjs.map +1 -1
- package/dist/{chunk-42FP5DTO.mjs → chunk-2ZQEQJQ6.mjs} +1 -1
- package/dist/chunk-2ZQEQJQ6.mjs.map +1 -0
- package/dist/chunk-AE55BKYV.mjs +24 -0
- package/dist/chunk-AE55BKYV.mjs.map +1 -0
- package/dist/chunk-BAZFMTCC.mjs +815 -0
- package/dist/chunk-BAZFMTCC.mjs.map +1 -0
- package/dist/{chunk-Z5AI2SXX.mjs → chunk-C62NQA4F.mjs} +203 -1004
- package/dist/chunk-C62NQA4F.mjs.map +1 -0
- package/dist/{chunk-DE6Y4VRI.mjs → chunk-GA7DS3PA.mjs} +1 -1
- package/dist/{chunk-DE6Y4VRI.mjs.map → chunk-GA7DS3PA.mjs.map} +1 -1
- package/dist/chunk-GW7YGXOW.mjs +47 -0
- package/dist/chunk-GW7YGXOW.mjs.map +1 -0
- package/dist/chunk-JUBLG3PN.mjs +351 -0
- package/dist/chunk-JUBLG3PN.mjs.map +1 -0
- package/dist/{chunk-Z3P7RUCC.mjs → chunk-OEX4OKYQ.mjs} +13 -13
- package/dist/{chunk-6JX222YX.mjs → chunk-WQK6PUBN.mjs} +9 -2
- package/dist/chunk-WQK6PUBN.mjs.map +1 -0
- package/dist/device/createDeviceProvider.js.map +1 -1
- package/dist/device/createDeviceProvider.mjs +7 -6
- package/dist/device-bridge/index.mjs +8 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/push/index.d.mts +24 -0
- package/dist/push/index.d.ts +24 -0
- package/dist/push/index.js +224 -0
- package/dist/push/index.js.map +1 -0
- package/dist/push/index.mjs +174 -0
- package/dist/push/index.mjs.map +1 -0
- package/dist/push/silentSync.d.mts +8 -0
- package/dist/push/silentSync.d.ts +8 -0
- package/dist/push/silentSync.js +1075 -0
- package/dist/push/silentSync.js.map +1 -0
- package/dist/push/silentSync.mjs +67 -0
- package/dist/push/silentSync.mjs.map +1 -0
- package/dist/vision/index.d.mts +7 -1
- package/dist/vision/index.d.ts +7 -1
- package/dist/vision/index.js +8 -0
- package/dist/vision/index.js.map +1 -1
- package/dist/vision/index.mjs +3 -1
- package/ios/AdaVisionModule.swift +44 -1
- package/package.json +28 -6
- package/src/aiLive/provider.ts +242 -0
- package/src/aiLive/streamProtocol.ts +90 -0
- package/src/bootstrap.ts +7 -1
- package/src/capabilities/choices.ts +65 -0
- package/src/capabilities/config.ts +5 -4
- package/src/capabilities/index.ts +2 -0
- package/src/capabilities/picturesToAi.ts +40 -0
- package/src/capabilities/store.ts +38 -37
- package/src/index.ts +3 -0
- package/src/push/index.ts +18 -0
- package/src/push/messaging.ts +49 -0
- package/src/push/registration.ts +31 -0
- package/src/push/silentSync.ts +83 -0
- package/src/push/usePushNotifications.ts +224 -0
- package/src/vision/index.ts +14 -0
- package/dist/chunk-42FP5DTO.mjs.map +0 -1
- package/dist/chunk-6JX222YX.mjs.map +0 -1
- package/dist/chunk-Z5AI2SXX.mjs.map +0 -1
- /package/dist/{chunk-Z3P7RUCC.mjs.map → chunk-OEX4OKYQ.mjs.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/device-bridge/relay-client.ts","../src/device-bridge/collectors/location.ts","../src/device-bridge/collectors/connectivity.ts","../src/device-bridge/capabilities.ts","../src/device-bridge/collectors/calendar.ts","../src/device-bridge/collectors/contacts.ts","../src/device-bridge/collectors/battery.ts","../src/device-bridge/collectors/notifications.ts","../src/device-bridge/collectors/mood.ts","../src/device-bridge/collectors/camera.ts","../src/device-bridge/background.ts"],"sourcesContent":["/**\n * Relay Client — REST client for the cloud relay service.\n * Handles data push, action polling, and offline buffering.\n *\n * Endpoints:\n * POST /api/device/{deviceId}/sync ← push data bundle\n * GET /api/device/{deviceId}/data/{domain} ← read latest (used by connector, not phone)\n * POST /api/device/{deviceId}/actions ← queue action (used by connector)\n * GET /api/device/{deviceId}/actions ← poll pending actions\n * DELETE /api/device/{deviceId}/actions/{id} ← confirm action executed\n */\n\nimport type {\n DeviceDataBundle,\n PendingAction,\n ActionResult,\n RelayResponse,\n} from './types';\n\nexport interface RelayClientConfig {\n relayUrl: string;\n deviceId: string;\n tenant: string;\n actorId?: string;\n apiKey?: string;\n timeout?: number; // ms, default 10000\n}\n\nexport class RelayClient {\n private baseUrl: string;\n private deviceId: string;\n private tenant: string;\n private actorId: string;\n private apiKey: string;\n private timeout: number;\n private offlineQueue: DeviceDataBundle[] = [];\n\n constructor(config: RelayClientConfig) {\n // Strip trailing slash\n this.baseUrl = config.relayUrl.replace(/\\/$/, '');\n this.deviceId = config.deviceId;\n this.tenant = config.tenant;\n this.actorId = config.actorId ?? 'default';\n this.apiKey = config.apiKey ?? '';\n this.timeout = config.timeout ?? 10_000;\n }\n\n // ─── Data Sync ───\n\n /**\n * Push a full device data bundle to the relay.\n * If offline, buffers the bundle and retries on next sync.\n */\n async pushData(bundle: DeviceDataBundle): Promise<RelayResponse<void>> {\n try {\n const response = await this.fetch(\n `/api/device/${this.deviceId}/sync`,\n {\n method: 'POST',\n body: JSON.stringify(bundle),\n }\n );\n\n if (response.ok) {\n // Flush any offline queue on successful connection\n await this.flushOfflineQueue();\n return { ok: true };\n }\n\n return {\n ok: false,\n error: `Relay returned ${response.status}: ${await response.text()}`,\n };\n } catch (error) {\n // Network error — buffer for later\n this.offlineQueue.push(bundle);\n return {\n ok: false,\n error: `Offline — buffered (${this.offlineQueue.length} pending)`,\n };\n }\n }\n\n /**\n * Push a single domain update (partial sync).\n */\n async pushDomain(\n domain: string,\n data: unknown\n ): Promise<RelayResponse<void>> {\n try {\n const response = await this.fetch(\n `/api/device/${this.deviceId}/sync/${domain}`,\n {\n method: 'POST',\n body: JSON.stringify({ domain, data, timestamp: new Date().toISOString(), actorId: this.actorId }),\n }\n );\n\n if (response.ok) return { ok: true };\n return {\n ok: false,\n error: `Relay returned ${response.status}`,\n };\n } catch (error) {\n return { ok: false, error: 'Network error — domain sync failed' };\n }\n }\n\n // ─── Action Queue ───\n\n /**\n * Poll for pending actions the phone needs to execute.\n */\n async pollActions(): Promise<RelayResponse<PendingAction[]>> {\n try {\n const response = await this.fetch(\n `/api/device/${this.deviceId}/actions`,\n { method: 'GET' }\n );\n\n if (response.ok) {\n const data = await response.json();\n return { ok: true, data: data.actions ?? [] };\n }\n return { ok: false, error: `Relay returned ${response.status}` };\n } catch (error) {\n return { ok: false, error: 'Network error — action poll failed' };\n }\n }\n\n /**\n * Report action execution result and remove from queue.\n */\n async completeAction(result: ActionResult): Promise<RelayResponse<void>> {\n try {\n const response = await this.fetch(\n `/api/device/${this.deviceId}/actions/${result.id}`,\n {\n method: 'DELETE',\n body: JSON.stringify(result),\n }\n );\n\n if (response.ok) return { ok: true };\n return { ok: false, error: `Relay returned ${response.status}` };\n } catch (error) {\n return { ok: false, error: 'Network error — action complete failed' };\n }\n }\n\n // ─── Health ───\n\n /**\n * Ping the relay to check connectivity.\n */\n async ping(): Promise<boolean> {\n try {\n const response = await this.fetch(\n `/api/health`,\n { method: 'GET' },\n 3_000 // short timeout for health check\n );\n return response.ok;\n } catch {\n return false;\n }\n }\n\n /**\n * Get count of buffered offline bundles.\n */\n getOfflineQueueSize(): number {\n return this.offlineQueue.length;\n }\n\n // ─── Internal ───\n\n private async fetch(\n path: string,\n init: RequestInit,\n timeout?: number\n ): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(\n () => controller.abort(),\n timeout ?? this.timeout\n );\n\n try {\n return await fetch(`${this.baseUrl}${path}`, {\n ...init,\n signal: controller.signal,\n headers: {\n 'Content-Type': 'application/json',\n 'X-ADAS-TENANT': this.tenant,\n 'X-ADAS-ACTOR': this.actorId,\n 'X-Device-Id': this.deviceId,\n // The relay (post-2026-04-25) gates every /api/device/* call on\n // a shared secret. Send it as `Authorization: Bearer` so the\n // server's relayAuth middleware accepts the request. Empty/missing\n // secret = 401 from the relay (correct fail-closed behavior).\n ...(this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}),\n ...(init.headers || {}),\n },\n });\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async flushOfflineQueue(): Promise<void> {\n if (this.offlineQueue.length === 0) return;\n\n const queue = [...this.offlineQueue];\n this.offlineQueue = [];\n\n for (const bundle of queue) {\n try {\n const response = await this.fetch(\n `/api/device/${this.deviceId}/sync`,\n {\n method: 'POST',\n body: JSON.stringify(bundle),\n }\n );\n if (!response.ok) {\n // Put it back if still failing\n this.offlineQueue.push(bundle);\n }\n } catch {\n this.offlineQueue.push(bundle);\n break; // Stop trying if still offline\n }\n }\n }\n}\n","/**\n * Location Collector — reads device location via expo-location.\n * Output format matches device-mock-mcp's location.current schema.\n */\n\nimport * as ExpoLocation from 'expo-location';\nimport type { MapsAddress } from '@ateam-ai-mobile/plugin-runtime';\n// The SDK's one reverse geocode — the same call native.maps.reverseGeocode makes.\nimport { reverseGeocode } from '../../maps';\nimport type { LocationData } from '../types';\n\n/**\n * Request location permissions (foreground + background).\n */\nexport async function requestPermission(): Promise<boolean> {\n const { status: fg } = await ExpoLocation.requestForegroundPermissionsAsync();\n if (fg !== 'granted') return false;\n\n // Background is optional — skip in Expo Go (crashes without native module)\n try {\n await ExpoLocation.requestBackgroundPermissionsAsync();\n } catch {\n // Expected in Expo Go — foreground is enough for basic functionality\n }\n return fg === 'granted';\n}\n\n/**\n * Check if location permission is granted.\n */\nexport async function hasPermission(): Promise<boolean> {\n const { status } = await ExpoLocation.getForegroundPermissionsAsync();\n return status === 'granted';\n}\n\n/**\n * Collect current location.\n * Matches the device.location.current tool output schema.\n */\nexport async function collectCurrent(): Promise<LocationData> {\n const location = await ExpoLocation.getCurrentPositionAsync({\n accuracy: ExpoLocation.Accuracy.Balanced,\n });\n\n // Reverse geocode to get address\n let place = 'Current Location';\n let address = `${location.coords.latitude.toFixed(4)}, ${location.coords.longitude.toFixed(4)}`;\n let locationType = 'unknown';\n\n try {\n const geocoded = await reverseGeocode({\n latitude: location.coords.latitude,\n longitude: location.coords.longitude,\n });\n\n if (geocoded) {\n place = geocoded.name || geocoded.street || place;\n address = [\n geocoded.streetNumber,\n geocoded.street,\n geocoded.city,\n geocoded.region,\n ]\n .filter(Boolean)\n .join(', ') || address;\n\n // Attempt to classify location type\n locationType = classifyLocation(geocoded);\n }\n } catch {\n // Reverse geocoding can fail — use coordinates only\n }\n\n return {\n ok: true,\n timestamp: new Date().toISOString(),\n location: {\n place,\n address,\n lat: location.coords.latitude,\n lng: location.coords.longitude,\n type: locationType,\n },\n };\n}\n\n// ─── Plugin-facing position API ───\n// `collectCurrent` above answers the device-context question (\"where am I, in\n// words\") and reverse-geocodes. A plugin tool usually wants the raw fix and\n// nothing else, so these stay separate: no geocoding round trip, no address.\n\nexport interface Position {\n latitude: number;\n longitude: number;\n altitude?: number;\n accuracy?: number;\n timestamp: number;\n /**\n * Metres per second. `undefined` = the OS gave no estimate.\n *\n * iOS reports -1 rather than omitting it, and -1 m/s passed through as a\n * speed would read as \"moving backwards\"; it is normalised away here so no\n * caller has to know the platform's sentinel.\n */\n speed?: number;\n /**\n * COURSE OVER GROUND in degrees — the direction the user is TRAVELLING.\n *\n * Deliberately not called `heading`: this and the compass answer different\n * questions and disagree constantly. Walking backwards down a corridor gives\n * a course of south and a compass heading of north; a phone held sideways\n * while walking forward gives the same course and a heading 90° off.\n * \"Turn right\" needs the compass. \"You are heading north on Main Street\"\n * needs this. The old code assigned one to the other, which is only ever\n * right by accident.\n *\n * `undefined` when not moving or not estimated — iOS reports -1 for both.\n */\n course?: number;\n}\n\n/** Ensure foreground permission, asking once if we do not have it yet. */\nasync function ensurePermission(): Promise<void> {\n if (await hasPermission()) return;\n const granted = await requestPermission();\n if (!granted) {\n // Callers surface this verbatim to the user (a voice assistant reads it\n // out), so it has to say what the user can do about it.\n throw new Error(\n 'Location permission was not granted. Enable it for this app in iOS Settings > Privacy > Location Services.',\n );\n }\n}\n\n/** One position fix. `accuracy: \"high\"` costs battery and time — default low. */\nexport async function getPosition(\n opts: { accuracy?: 'low' | 'high' } = {},\n): Promise<Position> {\n await ensurePermission();\n const fix = await ExpoLocation.getCurrentPositionAsync({\n accuracy:\n opts.accuracy === 'high'\n ? ExpoLocation.Accuracy.High\n : ExpoLocation.Accuracy.Balanced,\n });\n return toPosition(fix);\n}\n\n/**\n * One place that turns an expo fix into a `Position`.\n *\n * It exists because the sentinel handling has to be identical on the one-shot\n * and the streamed path. It was not: `watchPosition` passed lat/lon only, so\n * the semantic Spatial domain could never report speed or course no matter\n * what the OS supplied, and reported `null` as if the phone had no GPS.\n */\nfunction toPosition(fix: any): Position {\n return {\n latitude: fix.coords.latitude,\n longitude: fix.coords.longitude,\n altitude: fix.coords.altitude ?? undefined,\n accuracy: nonNegative(fix.coords.accuracy),\n timestamp: fix.timestamp ?? Date.now(),\n speed: nonNegative(fix.coords.speed),\n course: nonNegative(fix.coords.heading),\n };\n}\n\n/**\n * iOS uses -1 for \"no estimate\" on accuracy, speed and course alike. Dropping\n * the field says \"not measured\"; passing -1 through says \"measured, and the\n * answer is minus one\", which a model will happily repeat.\n */\nfunction nonNegative(v: unknown): number | undefined {\n return typeof v === 'number' && v >= 0 ? v : undefined;\n}\n\nconst WATCH_TIER = {\n navigation: ExpoLocation.Accuracy.BestForNavigation,\n high: ExpoLocation.Accuracy.High,\n balanced: ExpoLocation.Accuracy.Balanced,\n low: ExpoLocation.Accuracy.Low,\n} as const;\n\n/**\n * Stream position updates. Returns an unsubscribe function — call it, or the\n * GPS keeps running and drains the battery.\n *\n * `accuracy` picks the GPS tier. The default stays Balanced (≈100 m on iOS),\n * which is right for \"which city block\" and wrong for \"turn at the next corner\":\n * a navigation session asks for BestForNavigation and pays the battery for it.\n */\nexport function watchPosition(\n cb: (pos: Position) => void,\n opts?: { accuracy?: keyof typeof WATCH_TIER },\n): () => void {\n let subscription: { remove(): void } | null = null;\n let cancelled = false;\n\n (async () => {\n try {\n await ensurePermission();\n if (cancelled) return;\n subscription = await ExpoLocation.watchPositionAsync(\n { accuracy: WATCH_TIER[opts?.accuracy ?? 'balanced'] },\n fix => cb(toPosition(fix)),\n );\n // Unsubscribed while we were still asking for permission.\n if (cancelled) { subscription?.remove(); subscription = null; }\n } catch (err: any) {\n console.warn('[location] watchPosition failed:', err?.message || String(err));\n }\n })();\n\n return () => {\n cancelled = true;\n subscription?.remove();\n subscription = null;\n };\n}\n\n// ─── Helpers ───\n\nfunction classifyLocation(geocoded: MapsAddress): string {\n // Simple heuristic — can be enhanced with user-labeled places from memory\n const name = (geocoded.name || '').toLowerCase();\n const street = (geocoded.street || '').toLowerCase();\n\n if (name.includes('home') || name.includes('residence')) return 'home';\n if (name.includes('office') || name.includes('workplace') || name.includes('tech park')) return 'work';\n if (name.includes('school') || name.includes('elementary') || name.includes('university')) return 'school';\n if (name.includes('gym') || name.includes('fitness')) return 'fitness';\n if (name.includes('hospital') || name.includes('clinic') || name.includes('dental')) return 'medical';\n\n return 'other';\n}\n","/**\n * Connectivity Collector — reads network state via expo-network.\n * Output format matches device-mock-mcp's device.connectivity schema.\n */\n\nimport * as ExpoNetwork from 'expo-network';\nimport type { ConnectivityData } from '../types';\n\n// No special permission needed for network state\n\n/**\n * Collect current connectivity status.\n * Matches the device.connectivity tool output schema.\n */\nexport async function collectConnectivity(): Promise<ConnectivityData> {\n const networkState = await ExpoNetwork.getNetworkStateAsync();\n\n let type: 'wifi' | 'cellular' | 'none' = 'none';\n let wifiName: string | undefined;\n let cellularType: string | undefined;\n\n if (networkState.type === ExpoNetwork.NetworkStateType.WIFI) {\n type = 'wifi';\n // Wi-Fi SSID requires additional permissions on newer OS versions\n // and may not always be available\n try {\n wifiName = await getWifiName();\n } catch {\n wifiName = undefined;\n }\n } else if (networkState.type === ExpoNetwork.NetworkStateType.CELLULAR) {\n type = 'cellular';\n cellularType = getCellularGeneration();\n }\n\n return {\n ok: true,\n timestamp: new Date().toISOString(),\n connectivity: {\n type,\n is_connected: networkState.isConnected ?? false,\n ...(wifiName && { wifi_name: wifiName }),\n ...(cellularType && { cellular_type: cellularType }),\n },\n };\n}\n\n// ─── Helpers ───\n\nasync function getWifiName(): Promise<string | undefined> {\n // expo-network doesn't expose SSID directly on all platforms\n // This would need a native module or expo-wifi in production\n return undefined;\n}\n\nfunction getCellularGeneration(): string {\n // expo-network doesn't expose cellular generation\n // In production, use a native module for this\n return 'LTE';\n}\n","/**\n * Built-in Capabilities — wraps each collector as a registerable Capability.\n *\n * Each capability defines:\n * - id, name, description, reason (for UI)\n * - permission check/request\n * - collect function\n *\n * The host app can register these selectively, or add custom ones.\n */\n\nimport * as calendar from './collectors/calendar';\nimport * as contacts from './collectors/contacts';\nimport * as location from './collectors/location';\nimport * as battery from './collectors/battery';\nimport * as connectivity from './collectors/connectivity';\nimport * as notifications from './collectors/notifications';\nimport * as health from './collectors/health';\nimport * as mood from './collectors/mood';\nimport * as camera from './collectors/camera';\nimport type { Capability } from './types';\n\n// ─── Factory functions — call these to get a Capability instance ───\n\nexport function calendarCapability(): Capability {\n return {\n id: 'calendar',\n name: 'Calendar',\n description: 'Syncs your calendar events so your assistant knows your schedule.',\n reason: 'Needed for scheduling, meeting prep, commute alerts, and daily briefings.',\n icon: 'calendar',\n requiresPermission: true,\n permissionState: 'not_requested',\n requestPermission: calendar.requestPermission,\n checkPermission: calendar.hasPermission,\n collect: async () => {\n const [today, upcoming] = await Promise.all([\n calendar.collectToday(),\n calendar.collectUpcoming(7),\n ]);\n return { today, upcoming };\n },\n defaultInterval: 60_000, // 1 min\n };\n}\n\nexport function contactsCapability(): Capability {\n return {\n id: 'contacts',\n name: 'Contacts',\n description: 'Syncs your contacts so your assistant can find people and relationships.',\n reason: 'Needed for messaging, birthday reminders, and relationship insights.',\n icon: 'people',\n requiresPermission: true,\n permissionState: 'not_requested',\n requestPermission: contacts.requestPermission,\n checkPermission: contacts.hasPermission,\n collect: async () => {\n const list = await contacts.collectAll();\n // null = no changes since last successful sync → bridge skips push.\n // Critical for users with 6000+ contacts: full payload is ~1MB and\n // would otherwise re-upload every 5 min with no actual change.\n if (list === null) return null as any;\n return { contacts: list };\n },\n defaultInterval: 300_000, // 5 min\n };\n}\n\nexport function locationCapability(): Capability {\n return {\n id: 'location',\n name: 'Location',\n description: 'Syncs your location for weather, commute, and context-aware assistance.',\n reason: 'Needed for commute estimates, weather at your location, and situation detection.',\n icon: 'location',\n requiresPermission: true,\n permissionState: 'not_requested',\n requestPermission: location.requestPermission,\n checkPermission: location.hasPermission,\n collect: location.collectCurrent,\n defaultInterval: 30_000, // 30 sec\n };\n}\n\nexport function batteryCapability(): Capability {\n return {\n id: 'battery',\n name: 'Battery',\n description: 'Syncs battery level and charging status.',\n reason: 'Helps your assistant adjust behavior when battery is low.',\n icon: 'battery',\n requiresPermission: false,\n permissionState: 'not_needed',\n requestPermission: async () => true,\n checkPermission: async () => true,\n collect: battery.collectBattery,\n defaultInterval: 60_000, // 1 min\n subscribe: battery.subscribeToBattery,\n };\n}\n\nexport function connectivityCapability(): Capability {\n return {\n id: 'connectivity',\n name: 'Connectivity',\n description: 'Syncs WiFi/cellular status.',\n reason: 'Helps your assistant know if you have internet access.',\n icon: 'wifi',\n requiresPermission: false,\n permissionState: 'not_needed',\n requestPermission: async () => true,\n checkPermission: async () => true,\n collect: connectivity.collectConnectivity,\n defaultInterval: 30_000, // 30 sec\n };\n}\n\nexport function healthCapability(): Capability {\n return {\n id: 'health',\n name: 'Health',\n description: 'Reads daily steps, floors, calories, and distance from Apple Health.',\n reason: 'Powers the personal health coach and pairs activity data with nutrition tracking.',\n icon: 'heart',\n requiresPermission: true,\n permissionState: 'not_requested',\n requestPermission: health.requestPermission,\n checkPermission: health.hasPermission,\n collect: async () => {\n // Push today AND the last 30 days every sync. The connector slices\n // `days` to whatever range the caller asked for. ~30 sequential\n // HealthKit reads on iOS take <300ms total — cheap.\n const days = await health.collectHistory(30);\n const today = days[0] || (await health.collectToday());\n return { today, days };\n },\n defaultInterval: 300_000, // 5 min\n };\n}\n\nexport function moodCapability(): Capability {\n return {\n id: 'mood',\n name: 'Mood',\n description: 'Sends a daily behavioral-signal summary (activity, routine) to infer mood — not a medical diagnosis.',\n reason: 'Lets ada gently notice changes in energy, stress, and routine and check in.',\n icon: 'heart',\n // No OS permission of its own — it derives from collectors that gate\n // themselves (e.g. health). Treated as not_needed so the bridge syncs it\n // whenever the user has the Mood toggle on.\n requiresPermission: false,\n permissionState: 'not_needed',\n requestPermission: async () => true,\n checkPermission: async () => true,\n collect: async () => {\n // One compact daily summary (window/timezone/collected_at/today).\n // Pushed as the `mood` relay domain; backend runs /api/mood/analyze.\n return mood.collectToday();\n },\n defaultInterval: 3_600_000, // hourly — it's a daily summary, no need to spam\n };\n}\n\nexport function cameraCapability(): Capability {\n return {\n id: 'camera',\n name: 'Camera',\n description:\n \"Lets ada see through your camera to guide you — reading text and describing what's in \" +\n 'front of you. Frames are analysed on the phone; nothing is stored or uploaded.',\n reason: 'Powers visual guidance (Ada Guide): a live view with on-device text and scene understanding.',\n icon: 'camera',\n requiresPermission: true,\n permissionState: 'not_requested',\n requestPermission: camera.requestPermission,\n checkPermission: camera.hasPermission,\n // LIVE, not synced: the camera is used in the moment (deviceState.visual / a\n // widget's preview) and never collected to the relay. So collect never\n // pushes — this capability's value is the USER GRANT + OS permission, exposed\n // to the backend like every other, not a data payload. `null` = nothing to\n // push, which the bridge skips (same contract contacts uses when unchanged).\n collect: async () => null as any,\n defaultInterval: 3_600_000, // never really collects; keep the poll rare\n };\n}\n\nexport function notificationsCapability(): Capability {\n return {\n id: 'notifications',\n name: 'Notifications',\n description: 'Syncs your notifications for triage and smart grouping.',\n reason: 'Needed for notification triage, priority filtering, and Do Not Disturb.',\n icon: 'notifications',\n requiresPermission: true,\n permissionState: 'not_requested',\n requestPermission: notifications.requestPermission,\n checkPermission: notifications.hasPermission,\n collect: notifications.collectNotifications,\n defaultInterval: 15_000, // 15 sec\n };\n}\n\n// ─── Convenience: get all built-in capabilities ───\n\nexport function allBuiltIn(): Capability[] {\n return [\n calendarCapability(),\n contactsCapability(),\n locationCapability(),\n batteryCapability(),\n connectivityCapability(),\n notificationsCapability(),\n healthCapability(),\n moodCapability(),\n cameraCapability(),\n ];\n}\n","/**\n * Calendar Collector — reads device calendar via expo-calendar.\n * Output format matches device-mock-mcp's calendar.today / calendar.upcoming schemas.\n */\n\nimport * as ExpoCalendar from 'expo-calendar';\n// Type-only alias: the value namespace above cannot be used in type\n// position, so `ExpoCalendar.Calendar`-style annotations need this.\n// expo-calendar's types are not visible through the package entry under\n// bundler resolution, so derive them from the APIs that return them —\n// the shape then always matches the installed version.\ntype Calendar = Awaited<ReturnType<typeof ExpoCalendar.getCalendarsAsync>>[number];\ntype Event = Awaited<ReturnType<typeof ExpoCalendar.getEventsAsync>>[number];\nimport type { CalendarEvent, CalendarTodayData, CalendarUpcomingData } from '../types';\n\n/**\n * Request calendar permissions.\n * @returns true if granted\n */\nexport async function requestPermission(): Promise<boolean> {\n const { status } = await ExpoCalendar.requestCalendarPermissionsAsync();\n return status === 'granted';\n}\n\n/**\n * Check if calendar permission is granted.\n */\nexport async function hasPermission(): Promise<boolean> {\n const { status } = await ExpoCalendar.getCalendarPermissionsAsync();\n return status === 'granted';\n}\n\n/**\n * Get all calendar events for today.\n * Matches the device.calendar.today tool output schema.\n */\nexport async function collectToday(): Promise<CalendarTodayData> {\n const now = new Date();\n const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);\n\n const calendars = await ExpoCalendar.getCalendarsAsync(ExpoCalendar.EntityTypes.EVENT);\n const userCalendarIds = getUserCalendarIds(calendars);\n\n const events = await ExpoCalendar.getEventsAsync(userCalendarIds, startOfDay, endOfDay);\n const filtered = filterHolidays(events);\n\n const mapped: CalendarEvent[] = filtered.map(e => ({\n id: e.id,\n title: e.title || 'Untitled',\n date: startOfDay.toISOString().slice(0, 10),\n start: formatTime(new Date(e.startDate)),\n end: formatTime(new Date(e.endDate)),\n location: e.location || '',\n attendees: ((e as any).attendees || []).map((a: { name?: string; email?: string }) => a.name || a.email || 'Unknown'),\n notes: e.notes || '',\n }));\n\n // Sort by start time\n mapped.sort((a, b) => a.start.localeCompare(b.start));\n\n return {\n ok: true,\n date: startOfDay.toISOString().slice(0, 10),\n day_of_week: now.toLocaleDateString('en-US', { weekday: 'long' }),\n event_count: mapped.length,\n events: mapped,\n };\n}\n\n/**\n * Get upcoming calendar events for the next N days (tomorrow and beyond).\n * Matches the device.calendar.upcoming tool output schema.\n */\nexport async function collectUpcoming(daysAhead: number = 3): Promise<CalendarUpcomingData> {\n const now = new Date();\n const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);\n const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + daysAhead + 1);\n\n const calendars = await ExpoCalendar.getCalendarsAsync(ExpoCalendar.EntityTypes.EVENT);\n const userCalendarIds = getUserCalendarIds(calendars);\n\n const events = await ExpoCalendar.getEventsAsync(userCalendarIds, tomorrow, endDate);\n const filtered = filterHolidays(events);\n\n const mapped: CalendarEvent[] = filtered.map(e => {\n const startDt = new Date(e.startDate);\n return {\n id: e.id,\n title: e.title || 'Untitled',\n date: startDt.toISOString().slice(0, 10),\n start: formatTime(startDt),\n end: formatTime(new Date(e.endDate)),\n location: e.location || '',\n attendees: ((e as any).attendees || []).map((a: { name?: string; email?: string }) => a.name || a.email || 'Unknown'),\n notes: e.notes || '',\n };\n });\n\n // Sort by date then start time\n mapped.sort((a, b) =>\n a.date === b.date ? a.start.localeCompare(b.start) : a.date.localeCompare(b.date)\n );\n\n return {\n ok: true,\n from: tomorrow.toISOString().slice(0, 10),\n days_ahead: daysAhead,\n event_count: mapped.length,\n events: mapped,\n };\n}\n\n// ─── Helpers ───\n\n/**\n * Filter out holiday/subscription calendars — only keep user-owned calendars\n * (local, CalDAV, Exchange, Google). Subscription calendars are read-only\n * holiday feeds that clutter the real schedule.\n */\nfunction getUserCalendarIds(calendars: Calendar[]): string[] {\n const SKIP_SOURCES = ['birthdays', 'other']; // 'other' = subscribed holiday feeds on iOS\n const SKIP_TYPES = ['birthdays', 'other'];\n\n return calendars\n .filter(c => {\n const sourceType = ((c.source as any)?.type || '').toLowerCase();\n const calType = (c.type || '').toLowerCase();\n // Skip subscription/holiday calendars\n if (SKIP_SOURCES.includes(sourceType)) return false;\n if (SKIP_TYPES.includes(calType)) return false;\n return true;\n })\n .map(c => c.id);\n}\n\n/**\n * Extra safety: filter out all-day events with holiday-like patterns\n * in case they slip through from non-subscription calendars.\n */\nfunction filterHolidays(events: Event[]): Event[] {\n const HOLIDAY_PATTERNS = [\n /holiday/i, /observance/i, /eve\\b.*\\btentative\\b/i, /\\btentative\\b/i,\n ];\n\n return events.filter(e => {\n // All-day events spanning exactly one day with \"tentative\" or \"observance\" in notes → holiday\n const isAllDay = (e as any).allDay === true;\n const notes = (e.notes || '').toLowerCase();\n if (isAllDay && HOLIDAY_PATTERNS.some(p => p.test(notes))) return false;\n if (isAllDay && HOLIDAY_PATTERNS.some(p => p.test(e.title || ''))) return false;\n return true;\n });\n}\n\nfunction formatTime(date: Date): string {\n return date.toLocaleTimeString('en-US', {\n hour: '2-digit',\n minute: '2-digit',\n hour12: false,\n });\n}\n","/**\n * Contacts Collector — reads device contacts via expo-contacts.\n *\n * Two important properties for users with large address books (6000+ contacts):\n *\n * 1. Hash-based change detection. We persist a map of `contactId → contentHash`\n * across launches and on each collect cycle compare the freshly-read hashes\n * to the stored ones. If nothing changed, `collectAll()` returns null and\n * `syncCapability` skips the relay push entirely — no per-tick 1MB upload.\n *\n * 2. Reduced field set. iOS 16+ restricts which contact fields are accessible\n * without explicit user grants. Requesting `Note`/`Relationships` causes\n * `getContactsAsync` to throw \"Failed to serialize contact data:\n * Unauthorized Keys\", failing the entire collect. We stick to the four\n * fields actually used downstream (Name, PhoneNumbers, Emails, Birthday).\n *\n * Output format on push (when there ARE changes) is unchanged from before —\n * a full `Contact[]` — so the relay/MCP layer doesn't have to know about the\n * incremental scheme. The relay simply gets pushed less often.\n */\nimport * as ExpoContacts from 'expo-contacts';\n// Type-only alias: the value namespace above cannot be used in type\n// position, so `ExpoContacts.Calendar`-style annotations need this.\n// expo-contacts exports no `Date` type; take the shape from Contact itself.\ntype ExpoContact = Awaited<ReturnType<typeof ExpoContacts.getContactsAsync>>['data'][number];\ntype ContactDate = NonNullable<ExpoContact['birthday']>;\nimport AsyncStorage from '@react-native-async-storage/async-storage';\nimport type { Contact } from '../types';\n\nconst HASH_STORE_KEY = 'device-bridge.contacts.hashes.v1';\n\n/** Request contacts permissions. */\nexport async function requestPermission(): Promise<boolean> {\n const { status } = await ExpoContacts.requestPermissionsAsync();\n return status === 'granted';\n}\n\n/** Check if contacts permission is granted. */\nexport async function hasPermission(): Promise<boolean> {\n const { status } = await ExpoContacts.getPermissionsAsync();\n return status === 'granted';\n}\n\n/**\n * Diagnostic counters from the most recent collect — exposed so the Profile\n * debug view can surface \"what changed since last sync\".\n */\nexport interface ContactsCollectStats {\n total: number;\n added: number;\n updated: number;\n removed: number;\n unchanged: number;\n full_sync: boolean;\n}\nexport let lastContactsStats: ContactsCollectStats | null = null;\n\n/**\n * Read all contacts and detect changes vs the previously-stored hash map.\n *\n * Returns:\n * - the full Contact[] when anything changed (or this is the first sync),\n * - null when every contact's hash matches what we pushed last time, signalling\n * the bridge that no relay push is needed this cycle.\n */\nexport async function collectAll(): Promise<Contact[] | null> {\n // Only the four fields we actually surface downstream. Adding more reawakens\n // the iOS \"Unauthorized Keys\" failure unless the user has granted them via\n // a separate flow.\n const result = await ExpoContacts.getContactsAsync({\n fields: [\n ExpoContacts.Fields.Name,\n ExpoContacts.Fields.PhoneNumbers,\n ExpoContacts.Fields.Emails,\n ExpoContacts.Fields.Birthday,\n ],\n sort: ExpoContacts.SortTypes.LastName,\n });\n\n const raw = Array.isArray(result?.data) ? result.data : [];\n\n // Map raw contacts to our schema, computing a stable per-contact hash that's\n // independent of array ordering and resilient to spurious whitespace/case\n // changes in fields we don't actually compare on.\n const contacts: Contact[] = [];\n const currentHashes: Record<string, string> = {};\n for (let i = 0; i < raw.length; i++) {\n const c = raw[i];\n const id = c.id || `c${i}`;\n const mapped: Contact = {\n id,\n name: c.name || `${c.firstName || ''} ${c.lastName || ''}`.trim() || 'Unknown',\n relationship: '', // dropped — was the iOS Unauthorized-Keys trigger\n phone: c.phoneNumbers?.[0]?.number || null,\n email: c.emails?.[0]?.email || null,\n birthday: formatBirthday(c.birthday),\n notes: '', // dropped — Notes is restricted on iOS 16+\n };\n contacts.push(mapped);\n currentHashes[id] = hashContact(mapped);\n }\n\n // Compare against last-pushed hashes.\n let stored: Record<string, string> = {};\n try {\n const blob = await AsyncStorage.getItem(HASH_STORE_KEY);\n if (blob) stored = JSON.parse(blob) as Record<string, string>;\n } catch {\n /* corrupted store — treat as empty, will full-sync */\n }\n const fullSync = Object.keys(stored).length === 0;\n\n let added = 0;\n let updated = 0;\n let unchanged = 0;\n for (const id of Object.keys(currentHashes)) {\n const prev = stored[id];\n if (prev === undefined) added++;\n else if (prev !== currentHashes[id]) updated++;\n else unchanged++;\n }\n let removed = 0;\n for (const id of Object.keys(stored)) {\n if (currentHashes[id] === undefined) removed++;\n }\n\n lastContactsStats = {\n total: contacts.length,\n added,\n updated,\n removed,\n unchanged,\n full_sync: fullSync,\n };\n\n // No changes → tell the bridge to skip the relay push this cycle. Saves\n // a 6000-row payload going up the wire every 5 minutes when nothing moved.\n if (!fullSync && added === 0 && updated === 0 && removed === 0) {\n return null;\n }\n\n // Persist the new hash map AFTER deciding to push. If the push fails we'll\n // re-detect the same changes on the next cycle (push is idempotent enough).\n try {\n await AsyncStorage.setItem(HASH_STORE_KEY, JSON.stringify(currentHashes));\n } catch {\n /* a failed persist just means we'll redo the diff next time — non-fatal */\n }\n\n return contacts;\n}\n\n// ─── Helpers ────────────────────────────────────────────────\n\n/**\n * Stable string hash (FNV-1a 32-bit, hex). Pure JS, no native dep, fine for\n * change detection. NOT cryptographic — a determined collision attacker could\n * mask a contact change, but that's not in our threat model.\n */\nfunction fnv1a(str: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < str.length; i++) {\n h ^= str.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\nfunction hashContact(c: Contact): string {\n // Concatenate the canonical-cased, trimmed values of every field we surface.\n // Order matters and is fixed; null becomes a single sentinel character so\n // empty-vs-missing differs from \"actual whitespace\" in the hash space.\n const parts = [\n c.id,\n (c.name || '').trim(),\n c.phone || '\\0',\n (c.email || '\\0').toLowerCase(),\n c.birthday || '\\0',\n ];\n return fnv1a(parts.join('\u001f')); // unit separator — won't appear in any field\n}\n\nfunction formatBirthday(birthday: ContactDate | undefined): string | null {\n if (!birthday) return null;\n const { year, month, day } = birthday;\n if (month === undefined || day === undefined) return null;\n const m = String(month + 1).padStart(2, '0');\n const d = String(day).padStart(2, '0');\n\n // No year is the COMMON case on iOS — the contact editor lets you omit it,\n // and most people do. Substituting 1900 made that indistinguishable from a\n // real birth year, and the server dutifully computed an age from it: \"Dana\n // is turning 126 next Tuesday.\"\n //\n // `--MM-DD` is the ISO 8601 form for a recurring month-day with no year, so\n // the absence is stated rather than filled in.\n if (!year) return `--${m}-${d}`;\n\n return `${year}-${m}-${d}`;\n}\n","/**\n * Battery Collector — reads battery status via expo-battery.\n * Output format matches device-mock-mcp's device.battery schema.\n */\n\nimport * as ExpoBattery from 'expo-battery';\n// Type-only alias: the value namespace above cannot be used in type\n// position, so `ExpoBattery.Calendar`-style annotations need this.\n// BatteryState is not re-exported from the package entry — derive it from\n// the API that returns it so we never hand-maintain a copy of the enum.\ntype BatteryState = Awaited<ReturnType<typeof ExpoBattery.getBatteryStateAsync>>;\nimport type { BatteryData } from '../types';\n\n// No permission needed for battery\n\n/**\n * Collect current battery status.\n * Matches the device.battery tool output schema.\n */\nexport async function collectBattery(): Promise<BatteryData> {\n const level = await ExpoBattery.getBatteryLevelAsync();\n const state = await ExpoBattery.getBatteryStateAsync();\n const lowPower = await ExpoBattery.isLowPowerModeEnabledAsync();\n\n return {\n ok: true,\n timestamp: new Date().toISOString(),\n battery: {\n level: Math.round(level * 100), // expo-battery returns 0-1\n state: mapBatteryState(state),\n low_power_mode: lowPower,\n },\n };\n}\n\n/**\n * Subscribe to OS-level battery changes (level + charging state).\n *\n * iOS suspends JS timers when the app is backgrounded, so a pure setInterval\n * sync drifts: the relay ends up stuck on whatever level we last sampled\n * before the app went to sleep (commonly 100% from an overnight charge).\n * expo-battery's listeners fire from the native side and survive that gap,\n * so we get a fresh push as soon as the OS notices a change.\n *\n * Level changes are throttled to >=5pp deltas — without that, iOS emits a\n * level event for every 1% tick which would spam the relay.\n */\nexport function subscribeToBattery(callback: () => void): () => void {\n let lastLevel: number | null = null;\n\n const levelSub = ExpoBattery.addBatteryLevelListener(({ batteryLevel }) => {\n const pct = Math.round(batteryLevel * 100);\n if (lastLevel === null || Math.abs(pct - lastLevel) >= 5) {\n lastLevel = pct;\n callback();\n }\n });\n\n const stateSub = ExpoBattery.addBatteryStateListener(() => {\n callback();\n });\n\n return () => {\n levelSub?.remove?.();\n stateSub?.remove?.();\n };\n}\n\n// ─── Helpers ───\n\nfunction mapBatteryState(\n state: BatteryState\n): 'charging' | 'unplugged' | 'full' {\n switch (state) {\n case ExpoBattery.BatteryState.CHARGING:\n return 'charging';\n case ExpoBattery.BatteryState.FULL:\n return 'full';\n case ExpoBattery.BatteryState.UNPLUGGED:\n default:\n return 'unplugged';\n }\n}\n","/**\n * Notifications Collector — reads notification state via expo-notifications.\n * Output format matches device-mock-mcp's notifications.list schema.\n *\n * Note: On iOS/Android, expo-notifications only gives access to notifications\n * that YOUR app has posted or received. System-wide notification access\n * requires platform-specific APIs (NotificationListenerService on Android,\n * UNUserNotificationCenter on iOS with app extensions).\n *\n * For the PA, the relay approach means we capture notifications delivered\n * TO our app (from the PA system), not FROM other apps.\n * Other-app notifications would need a native module or accessibility service.\n */\n\nimport * as ExpoNotifications from 'expo-notifications';\nimport type { Notification, NotificationsData } from '../types';\n\n/**\n * Request notification permissions.\n */\nexport async function requestPermission(): Promise<boolean> {\n const { status } = await ExpoNotifications.requestPermissionsAsync();\n return status === 'granted';\n}\n\n/**\n * Check if notification permission is granted.\n */\nexport async function hasPermission(): Promise<boolean> {\n const { status } = await ExpoNotifications.getPermissionsAsync();\n return status === 'granted';\n}\n\n/**\n * Collect delivered notifications from the notification tray.\n * Only captures notifications delivered to THIS app.\n * Matches the device.notifications.list tool output schema.\n */\nexport async function collectNotifications(): Promise<NotificationsData> {\n const presented = await ExpoNotifications.getPresentedNotificationsAsync();\n\n const notifications: Notification[] = presented.map((n, i) => ({\n id: n.request.identifier || `n${i}`,\n app: (n.request.content.data?.app as string) || 'A-Team',\n title: n.request.content.title || '',\n body: n.request.content.body || '',\n timestamp: n.date ? new Date(n.date).toISOString() : new Date().toISOString(),\n sender: (n.request.content.data?.sender as string) || null,\n priority: mapPriority(n.request.content.data?.priority as string),\n read: false, // Presented notifications are unread by definition\n }));\n\n const unread = notifications.filter(n => !n.read).length;\n\n return {\n ok: true,\n timestamp: new Date().toISOString(),\n total: notifications.length,\n unread,\n notifications,\n };\n}\n\n// ─── Helpers ───\n\nfunction mapPriority(p: string | undefined): 'high' | 'medium' | 'low' {\n if (p === 'high' || p === 'max') return 'high';\n if (p === 'low' || p === 'min') return 'low';\n return 'medium';\n}\n","/**\n * Mood Signals Collector — assembles the daily behavioral-signal summary the\n * Mood Intelligence Kit's backend expects (MoodSignalToday), and emits it as\n * a compact daily object. It does NOT call the kit's HTTP client; transport is\n * the existing device-bridge relay path (pushed as the `mood` domain), same as\n * health/location/etc. The backend reads the relay domain and runs analysis.\n *\n * Philosophy (from the kit's DESIGN): send a concise daily SUMMARY, never raw\n * event logs. We fill the fields we can source today from existing collectors\n * and leave the rest null — the backend's baseline/fallback tolerates nulls.\n *\n * EXACT per-field contract + where each value comes from on THIS platform\n * (iOS). \"blocked\" = Apple does not expose it to third-party apps, so it is\n * permanently null on iOS; \"addable\" = we have a source but haven't wired it.\n *\n * steps ← health (HealthKit) ✅ sourced now\n * distance_km ← health (HealthKit) ✅ sourced now\n * sleep_min ← health (HealthKit sleep) ✅ sourced now\n * app_sessions ← our own app analytics ✅ sourced now\n * app_active_min ← our own app analytics ✅ sourced now\n * resting_hr (extra) ← health (HealthKit) ✅ sourced now\n * active_energy_kcal(x) ← health (HealthKit) ✅ sourced now\n * exercise_min (extra) ← health (HealthKit) ✅ sourced now\n * places_count ← location collector (distinct) ⏳ addable (not wired)\n * checkin_mood ← user self-report UI ⏳ addable (no UI yet)\n * screen_min ← iOS Screen Time ❌ blocked by iOS\n * night_screen_min ← iOS Screen Time ❌ blocked by iOS\n * social_app_min ← other apps' usage ❌ blocked by iOS\n * video_app_min ← other apps' usage ❌ blocked by iOS\n * productivity_app_min ← other apps' usage ❌ blocked by iOS\n * messages_sent ← Messages content/metadata ❌ blocked by iOS\n * calls_count ← call log ❌ blocked by iOS\n *\n * (extra) = not in the kit's MoodSignalToday but sent alongside; the backend\n * tolerates extra fields and these are strong mood proxies.\n *\n * The kit's spec listed many sources because several exist on Android\n * (UsageStatsManager etc.); on iOS most are sandbox-blocked. We send what we\n * truly have and leave the rest null — the backend baseline/fallback tolerates\n * nulls and weights only present fields.\n */\nimport * as health from './health';\nimport * as appEngagement from './appEngagement';\n\n// Mirrors the kit's MoodSignalToday (packages/mood-client-rn/src/types.ts).\nexport interface MoodSignalToday {\n steps: number | null;\n sleep_min: number | null;\n screen_min: number | null;\n night_screen_min: number | null;\n places_count: number | null;\n distance_km: number | null;\n social_app_min: number | null;\n video_app_min: number | null;\n productivity_app_min: number | null;\n messages_sent: number | null;\n calls_count: number | null;\n app_sessions: number | null;\n app_active_min: number | null;\n checkin_mood?: 'great' | 'ok' | 'low' | 'bad' | null;\n}\n\nfunction emptySignals(): MoodSignalToday {\n return {\n steps: null,\n sleep_min: null,\n screen_min: null,\n night_screen_min: null,\n places_count: null,\n distance_km: null,\n social_app_min: null,\n video_app_min: null,\n productivity_app_min: null,\n messages_sent: null,\n calls_count: null,\n app_sessions: null,\n app_active_min: null,\n checkin_mood: null,\n };\n}\n\n/**\n * Build today's mood signal summary from available collectors. Returns the\n * full MoodSignalToday plus collection metadata the backend wants\n * (window, timezone, collected_at) so it can run analyze without guessing.\n */\nexport async function collectToday(): Promise<{\n window: 'today';\n timezone: string;\n collected_at: string;\n today: MoodSignalToday;\n}> {\n const today = emptySignals();\n\n // Health-sourced fields (best-effort; collector returns zeros if HK denied).\n try {\n const h = await health.collectToday();\n if (h) {\n today.steps = typeof h.steps === 'number' ? h.steps : null;\n today.distance_km = typeof h.distance_km === 'number' ? h.distance_km : null;\n }\n } catch {\n // leave nulls — backend baseline handles missing fields\n }\n\n // HealthKit mood extras: sleep, resting HR, active energy, exercise minutes.\n try {\n const x = await health.collectMoodExtras();\n today.sleep_min = x.sleep_min;\n // resting_hr / active_energy_kcal / exercise_min aren't in the kit's\n // MoodSignalToday contract, but the backend tolerates extra fields and\n // they're strong mood proxies — include them alongside.\n (today as any).resting_hr = x.resting_hr;\n (today as any).active_energy_kcal = x.active_energy_kcal;\n (today as any).exercise_min = x.exercise_min;\n } catch {\n // leave nulls\n }\n\n // Our own app-engagement analytics (no OS permission; the only on-iOS source\n // for app_sessions / app_active_min).\n try {\n const e = await appEngagement.getToday();\n today.app_sessions = e.app_sessions;\n today.app_active_min = e.app_active_min;\n } catch {\n // leave nulls\n }\n\n let timezone = 'UTC';\n try {\n timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';\n } catch { /* RN without full ICU — fall back to UTC */ }\n\n return {\n window: 'today',\n timezone,\n collected_at: new Date().toISOString(),\n today,\n };\n}\n","/**\n * Camera capability — permission only, NO collector.\n *\n * Unlike calendar/contacts/health, the camera is a LIVE capability: frames are\n * used in the moment (deviceState.visual, a widget's camera preview) and are\n * analysed on-device — never collected to the relay. So this module carries only\n * the OS-permission check/request that the capability toggle drives; there is no\n * `collect`. The user's grant (this toggle) is what gates access, on the same\n * path as location/contacts.\n */\nimport { Camera } from 'expo-camera';\n\nexport async function hasPermission(): Promise<boolean> {\n try {\n return (await Camera.getCameraPermissionsAsync()).granted;\n } catch {\n return false;\n }\n}\n\nexport async function requestPermission(): Promise<boolean> {\n try {\n return (await Camera.requestCameraPermissionsAsync()).granted;\n } catch {\n return false;\n }\n}\n","/**\n * Background Sync — registers an expo-task-manager task for periodic\n * data sync when the app is in the background, and exposes a one-shot\n * `syncDomains()` for silent-push triggered syncs.\n *\n * iOS minimum background fetch interval is ~15 minutes.\n * Android allows more frequent background execution via WorkManager.\n *\n * Usage:\n * import { registerBackgroundSync, syncDomains } from '@mobile-pa/device-bridge';\n *\n * // Periodic background fetch — call once at app startup, outside any component\n * registerBackgroundSync({\n * relayUrl: 'https://relay.example.com',\n * deviceId: 'device-123',\n * tenant: 'mobile-pa',\n * actorId: 'user-abc',\n * apiKey: 'key-xxx',\n * });\n *\n * // Silent-push triggered sync — from FCM background message handler\n * await syncDomains(config, ['location', 'calendar']);\n */\n\nimport * as TaskManager from 'expo-task-manager';\nimport * as BackgroundFetch from 'expo-background-fetch';\nimport { RelayClient } from './relay-client';\nimport * as caps from './capabilities';\nimport type { Capability } from './types';\n\nexport const BACKGROUND_TASK_NAME = 'DEVICE_BRIDGE_BACKGROUND_SYNC';\n\nexport interface BackgroundSyncConfig {\n relayUrl: string;\n deviceId: string;\n tenant: string;\n actorId?: string;\n apiKey: string;\n}\n\nconst CAPABILITY_FACTORIES: Record<string, () => Capability> = {\n calendar: caps.calendarCapability,\n contacts: caps.contactsCapability,\n location: caps.locationCapability,\n battery: caps.batteryCapability,\n connectivity: caps.connectivityCapability,\n notifications: caps.notificationsCapability,\n health: caps.healthCapability,\n};\n\n/**\n * Register the periodic background-fetch task.\n * Call once at app startup, outside any React component.\n */\nexport async function registerBackgroundSync(\n config: BackgroundSyncConfig\n): Promise<void> {\n TaskManager.defineTask(BACKGROUND_TASK_NAME, async () => {\n try {\n const hasNew = await syncDomains(config, ['location', 'battery', 'calendar']);\n return hasNew\n ? BackgroundFetch.BackgroundFetchResult.NewData\n : BackgroundFetch.BackgroundFetchResult.NoData;\n } catch (error) {\n console.error('[DeviceBridge] Background sync failed:', error);\n return BackgroundFetch.BackgroundFetchResult.Failed;\n }\n });\n\n await BackgroundFetch.registerTaskAsync(BACKGROUND_TASK_NAME, {\n minimumInterval: 300, // 5 minutes (iOS will clamp to ~15 min)\n stopOnTerminate: false,\n startOnBoot: true,\n });\n}\n\n/**\n * Unregister the background sync task.\n */\nexport async function unregisterBackgroundSync(): Promise<void> {\n const isRegistered = await TaskManager.isTaskRegisteredAsync(\n BACKGROUND_TASK_NAME\n );\n if (isRegistered) {\n await BackgroundFetch.unregisterTaskAsync(BACKGROUND_TASK_NAME);\n }\n}\n\n/**\n * Collect and push the listed domains once. Used by both the periodic\n * background-fetch task and the silent-push handler.\n *\n * Returns true if at least one domain pushed new data.\n */\nexport async function syncDomains(\n config: BackgroundSyncConfig,\n domains: string[]\n): Promise<boolean> {\n const relay = new RelayClient({\n relayUrl: config.relayUrl,\n deviceId: config.deviceId,\n tenant: config.tenant,\n actorId: config.actorId,\n apiKey: config.apiKey,\n timeout: 15_000, // longer than foreground — background tasks are budget-limited but not latency-sensitive\n });\n\n const results = await Promise.allSettled(\n domains.map(d => collectAndPush(relay, d))\n );\n\n return results.some(r => r.status === 'fulfilled' && r.value);\n}\n\n// ─── Internal ───\n\nasync function collectAndPush(\n relay: RelayClient,\n domain: string\n): Promise<boolean> {\n const factory = CAPABILITY_FACTORIES[domain];\n if (!factory) {\n console.warn(`[DeviceBridge] Unknown sync domain: ${domain}`);\n return false;\n }\n\n const cap = factory();\n\n if (cap.requiresPermission) {\n const granted = await cap.checkPermission();\n if (!granted) return false;\n }\n\n const data = await cap.collect();\n const result = await relay.pushDomain(domain, data);\n return result.ok;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BO,IAAM,cAAN,MAAkB;AAAA,EASvB,YAAY,QAA2B;AAFvC,SAAQ,eAAmC,CAAC;AAI1C,SAAK,UAAU,OAAO,SAAS,QAAQ,OAAO,EAAE;AAChD,SAAK,WAAW,OAAO;AACvB,SAAK,SAAS,OAAO;AACrB,SAAK,UAAU,OAAO,WAAW;AACjC,SAAK,SAAS,OAAO,UAAU;AAC/B,SAAK,UAAU,OAAO,WAAW;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,SAAS,QAAwD;AACrE,QAAI;AACF,YAAM,WAAW,MAAM,KAAK;AAAA,QAC1B,eAAe,KAAK,QAAQ;AAAA,QAC5B;AAAA,UACE,QAAQ;AAAA,UACR,MAAM,KAAK,UAAU,MAAM;AAAA,QAC7B;AAAA,MACF;AAEA,UAAI,SAAS,IAAI;AAEf,cAAM,KAAK,kBAAkB;AAC7B,eAAO,EAAE,IAAI,KAAK;AAAA,MACpB;AAEA,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,OAAO,kBAAkB,SAAS,MAAM,KAAK,MAAM,SAAS,KAAK,CAAC;AAAA,MACpE;AAAA,IACF,SAAS,OAAO;AAEd,WAAK,aAAa,KAAK,MAAM;AAC7B,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,OAAO,4BAAuB,KAAK,aAAa,MAAM;AAAA,MACxD;AAAA,IACF;AAA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AAC1B,UAAM,UAAU,MAAM,IAAI,gBAAgB;AAC1C,QAAI,CAAC,QAAS,QAAO;AAAA,EACvB;AAEA,QAAM,OAAO,MAAM,IAAI,QAAQ;AAC/B,QAAM,SAAS,MAAM,MAAM,WAAW,QAAQ,IAAI;AAClD,SAAO,OAAO;AAChB;","names":["hasPermission","requestPermission","requestPermission","hasPermission","requestPermission","hasPermission","collectToday","requestPermission","hasPermission","requestPermission","hasPermission","collectToday","hasPermission","requestPermission","requestPermission","hasPermission","collectToday"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/capabilities/config.ts"],"sourcesContent":["/**\n * Device-sync settings the host provides once (bootstrapExpoAdas `deviceSync`,\n * or configureDeviceSync directly). Kept apart from the store so the bootstrap\n * can set them without loading the device bridge at module load.\n */\nimport type { SecureKv } from '../device-bridge/deviceId';\n\nexport interface DeviceSyncConfig {\n /** Relay base URL getter — read on every start, so an env switch flows through. */\n relayUrl: () => string;\n /** The relay's shared key, sent as `Authorization: Bearer`. Empty = the relay answers 401. */\n relayKey: string;\n /** Secure storage for the install's device id. */\n secureStorage: SecureKv;\n}\n\n// Module-private on purpose: plugin bundles run in the same JS context, so the\n// relay key and the secure-storage reader must not sit anywhere they can reach.\n// (The CJS build gives the bootstrap and
|
|
1
|
+
{"version":3,"sources":["../src/capabilities/config.ts"],"sourcesContent":["/**\n * Device-sync settings the host provides once (bootstrapExpoAdas `deviceSync`,\n * or configureDeviceSync directly). Kept apart from the store so the bootstrap\n * can set them without loading the device bridge at module load.\n */\nimport type { SecureKv } from '../device-bridge/deviceId';\n\nexport interface DeviceSyncConfig {\n /** Relay base URL getter — read on every start, so an env switch flows through. */\n relayUrl: () => string;\n /** The relay's shared key, sent as `Authorization: Bearer`. Empty = the relay answers 401. */\n relayKey: string;\n /** Secure storage for the install's device id. */\n secureStorage: SecureKv;\n}\n\n// Module-private on purpose: plugin bundles run in the same JS context, so the\n// relay key and the secure-storage reader must not sit anywhere they can reach.\n// (The CJS build gives the bootstrap, capabilities and silent-push entries each\n// their own copy of this file; a require() host calls configureDeviceSync from\n// '@ateam-ai-mobile/expo/capabilities' instead of the bootstrap option, and its\n// silent-push sync finds no config and skips. Metro uses the source and the ESM\n// build shares one copy.)\nlet config: DeviceSyncConfig | null = null;\n\nexport function configureDeviceSync(next: DeviceSyncConfig): void {\n config = next;\n}\n\nexport function getDeviceSyncConfig(): DeviceSyncConfig | null {\n return config;\n}\n"],"mappings":";AAuBA,IAAI,SAAkC;AAE/B,SAAS,oBAAoB,MAA8B;AAChE,WAAS;AACX;AAEO,SAAS,sBAA+C;AAC7D,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// src/capabilities/choices.ts
|
|
2
|
+
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
3
|
+
var STORAGE_KEY = "ateam.capabilities";
|
|
4
|
+
var SETUP_KEY = "ateam.capabilities.setup";
|
|
5
|
+
var DEFAULT_ENABLED = {
|
|
6
|
+
calendar: true,
|
|
7
|
+
contacts: true,
|
|
8
|
+
location: true,
|
|
9
|
+
battery: true,
|
|
10
|
+
connectivity: true,
|
|
11
|
+
health: true,
|
|
12
|
+
mood: true,
|
|
13
|
+
// Opt-IN: the camera is more invasive than the sync collectors and should not
|
|
14
|
+
// prompt every user for camera access on first launch. It lights up only when
|
|
15
|
+
// the user turns it on (which then requests the OS permission), so a solution
|
|
16
|
+
// that wants a camera preview asks the user to enable it.
|
|
17
|
+
camera: false
|
|
18
|
+
};
|
|
19
|
+
var HIDDEN_FROM_UI = /* @__PURE__ */ new Set(["notifications"]);
|
|
20
|
+
async function loadChoices() {
|
|
21
|
+
const setupDone = await AsyncStorage.getItem(SETUP_KEY);
|
|
22
|
+
const saved = await AsyncStorage.getItem(STORAGE_KEY);
|
|
23
|
+
return { setupDone: setupDone === "true", prefs: saved ? JSON.parse(saved) : {} };
|
|
24
|
+
}
|
|
25
|
+
function isEnabled(id, prefs) {
|
|
26
|
+
return prefs[id] ?? DEFAULT_ENABLED[id] ?? true;
|
|
27
|
+
}
|
|
28
|
+
async function sharedDomains(domains) {
|
|
29
|
+
let choices;
|
|
30
|
+
try {
|
|
31
|
+
choices = await loadChoices();
|
|
32
|
+
} catch {
|
|
33
|
+
return [];
|
|
34
|
+
}
|
|
35
|
+
if (!choices.setupDone) return [];
|
|
36
|
+
return domains.filter((d) => !HIDDEN_FROM_UI.has(d) && isEnabled(d, choices.prefs));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export {
|
|
40
|
+
STORAGE_KEY,
|
|
41
|
+
SETUP_KEY,
|
|
42
|
+
HIDDEN_FROM_UI,
|
|
43
|
+
loadChoices,
|
|
44
|
+
isEnabled,
|
|
45
|
+
sharedDomains
|
|
46
|
+
};
|
|
47
|
+
//# sourceMappingURL=chunk-GW7YGXOW.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/capabilities/choices.ts"],"sourcesContent":["/**\n * The user's device-sharing choices as saved — the one reader, used by the\n * capabilities store and by a silent-push background sync, which must share\n * only what the user turned on (it loads this file, not the store).\n */\nimport AsyncStorage from '@react-native-async-storage/async-storage';\n\n// The keys the app used before the SDK owned them — existing installs keep their choices.\nexport const STORAGE_KEY = 'ateam.capabilities';\nexport const SETUP_KEY = 'ateam.capabilities.setup';\n\n// Default enabled state per capability (first-time only)\nconst DEFAULT_ENABLED: Record<string, boolean> = {\n calendar: true,\n contacts: true,\n location: true,\n battery: true,\n connectivity: true,\n health: true,\n mood: true,\n // Opt-IN: the camera is more invasive than the sync collectors and should not\n // prompt every user for camera access on first launch. It lights up only when\n // the user turns it on (which then requests the OS permission), so a solution\n // that wants a camera preview asks the user to enable it.\n camera: false,\n};\n\n// Capabilities hidden from the user-facing list — the bridge never registers\n// them. The host's push-notifications toggle is the single user control; the\n// notifications collector is internal plumbing and shouldn't surface as a\n// separate switch.\nexport const HIDDEN_FROM_UI = new Set(['notifications']);\n\nexport interface SavedChoices {\n setupDone: boolean;\n /** The user's saved toggles; a capability missing here has its default. */\n prefs: Record<string, boolean>;\n}\n\n/** Read the saved choices. Throws on a corrupt save — callers decide what that means. */\nexport async function loadChoices(): Promise<SavedChoices> {\n const setupDone = await AsyncStorage.getItem(SETUP_KEY);\n const saved = await AsyncStorage.getItem(STORAGE_KEY);\n return { setupDone: setupDone === 'true', prefs: saved ? JSON.parse(saved) : {} };\n}\n\n/** Whether the user's choices turn this capability on. */\nexport function isEnabled(id: string, prefs: Record<string, boolean>): boolean {\n return prefs[id] ?? DEFAULT_ENABLED[id] ?? true;\n}\n\n/**\n * The domains among `domains` this device may sync now: setup done, shown to\n * the user, and turned on. Anything unreadable → none.\n */\nexport async function sharedDomains(domains: string[]): Promise<string[]> {\n let choices: SavedChoices;\n try {\n choices = await loadChoices();\n } catch {\n return [];\n }\n if (!choices.setupDone) return [];\n return domains.filter((d) => !HIDDEN_FROM_UI.has(d) && isEnabled(d, choices.prefs));\n}\n"],"mappings":";AAKA,OAAO,kBAAkB;AAGlB,IAAM,cAAc;AACpB,IAAM,YAAY;AAGzB,IAAM,kBAA2C;AAAA,EAC/C,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AAAA,EACV,SAAS;AAAA,EACT,cAAc;AAAA,EACd,QAAQ;AAAA,EACR,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,EAKN,QAAQ;AACV;AAMO,IAAM,iBAAiB,oBAAI,IAAI,CAAC,eAAe,CAAC;AASvD,eAAsB,cAAqC;AACzD,QAAM,YAAY,MAAM,aAAa,QAAQ,SAAS;AACtD,QAAM,QAAQ,MAAM,aAAa,QAAQ,WAAW;AACpD,SAAO,EAAE,WAAW,cAAc,QAAQ,OAAO,QAAQ,KAAK,MAAM,KAAK,IAAI,CAAC,EAAE;AAClF;AAGO,SAAS,UAAU,IAAY,OAAyC;AAC7E,SAAO,MAAM,EAAE,KAAK,gBAAgB,EAAE,KAAK;AAC7C;AAMA,eAAsB,cAAc,SAAsC;AACxE,MAAI;AACJ,MAAI;AACF,cAAU,MAAM,YAAY;AAAA,EAC9B,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACA,MAAI,CAAC,QAAQ,UAAW,QAAO,CAAC;AAChC,SAAO,QAAQ,OAAO,CAAC,MAAM,CAAC,eAAe,IAAI,CAAC,KAAK,UAAU,GAAG,QAAQ,KAAK,CAAC;AACpF;","names":[]}
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
import {
|
|
2
|
+
jpegById
|
|
3
|
+
} from "./chunk-WQK6PUBN.mjs";
|
|
4
|
+
|
|
5
|
+
// src/aiLive/provider.ts
|
|
6
|
+
import { getCoreWsUrl, getTenant, getToken, mcpToolCall, unwrapMcpResult } from "@ateam-ai-mobile/core";
|
|
7
|
+
|
|
8
|
+
// src/aiLive/streamProtocol.ts
|
|
9
|
+
var STREAM_PATH = "/ws/stream";
|
|
10
|
+
var SUBPROTOCOL = "adas.v1";
|
|
11
|
+
var HEADER_BYTES = 14;
|
|
12
|
+
var ENVELOPE_VERSION = 1;
|
|
13
|
+
var CLOSE = Object.freeze({
|
|
14
|
+
AUTH_MISSING: 4001,
|
|
15
|
+
AUTH_FAILED: 4002,
|
|
16
|
+
NO_SUCH_WORKSPACE: 4003,
|
|
17
|
+
NOT_ENTITLED: 4004,
|
|
18
|
+
BAD_REQUEST: 4400,
|
|
19
|
+
UNKNOWN_KIND: 4404,
|
|
20
|
+
TIMEOUT: 4408,
|
|
21
|
+
OVER_LIMIT: 4429,
|
|
22
|
+
TOO_BIG: 1009,
|
|
23
|
+
CONSUMER_FAILING: 1011
|
|
24
|
+
});
|
|
25
|
+
function encodeFrame({ seq, tCapture, payload }) {
|
|
26
|
+
const out = new Uint8Array(HEADER_BYTES + payload.length);
|
|
27
|
+
const v = new DataView(out.buffer);
|
|
28
|
+
v.setUint8(0, ENVELOPE_VERSION);
|
|
29
|
+
v.setUint8(1, 0);
|
|
30
|
+
v.setUint32(2, seq >>> 0, false);
|
|
31
|
+
v.setFloat64(6, tCapture, false);
|
|
32
|
+
out.set(payload, HEADER_BYTES);
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
function openMessage(kind) {
|
|
36
|
+
return JSON.stringify({ type: "open", kind });
|
|
37
|
+
}
|
|
38
|
+
var CLOSE_MESSAGE = JSON.stringify({ type: "close" });
|
|
39
|
+
function parseServerEvent(text) {
|
|
40
|
+
if (typeof text !== "string") return null;
|
|
41
|
+
try {
|
|
42
|
+
const m = JSON.parse(text);
|
|
43
|
+
return m && typeof m.event === "string" ? { event: m.event, data: m.data } : null;
|
|
44
|
+
} catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
var WHY = {
|
|
49
|
+
[CLOSE.AUTH_MISSING]: "The login or the workspace was missing. Sign in again and try once more.",
|
|
50
|
+
[CLOSE.AUTH_FAILED]: "The login was refused. Sign in again and try once more.",
|
|
51
|
+
[CLOSE.NO_SUCH_WORKSPACE]: "This workspace was not found.",
|
|
52
|
+
[CLOSE.NOT_ENTITLED]: "This workspace may not stream right now.",
|
|
53
|
+
[CLOSE.TIMEOUT]: "The connection to the AI timed out.",
|
|
54
|
+
[CLOSE.OVER_LIMIT]: "Too many cameras are sending to this workspace. Stop another one first.",
|
|
55
|
+
[CLOSE.TOO_BIG]: "A picture was too big to send.",
|
|
56
|
+
[CLOSE.CONSUMER_FAILING]: "The AI stopped taking pictures. Check the live session in AI Models."
|
|
57
|
+
};
|
|
58
|
+
function describeClose(code, reason) {
|
|
59
|
+
if (code === CLOSE.BAD_REQUEST && reason) return reason;
|
|
60
|
+
return WHY[code] || (reason ? reason : `The connection to the AI closed (${code}).`);
|
|
61
|
+
}
|
|
62
|
+
var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
63
|
+
var B64_INDEX = (() => {
|
|
64
|
+
const t = new Int16Array(256).fill(-1);
|
|
65
|
+
for (let i = 0; i < 64; i++) t[B64.charCodeAt(i)] = i;
|
|
66
|
+
return t;
|
|
67
|
+
})();
|
|
68
|
+
function base64ToBytes(b64) {
|
|
69
|
+
const clean = b64.replace(/[^A-Za-z0-9+/]/g, "");
|
|
70
|
+
const out = new Uint8Array(Math.floor(clean.length * 3 / 4));
|
|
71
|
+
let o = 0, acc = 0, bits = 0;
|
|
72
|
+
for (let i = 0; i < clean.length; i++) {
|
|
73
|
+
acc = acc << 6 | B64_INDEX[clean.charCodeAt(i)];
|
|
74
|
+
bits += 6;
|
|
75
|
+
if (bits >= 8) {
|
|
76
|
+
bits -= 8;
|
|
77
|
+
out[o++] = acc >> bits & 255;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return o === out.length ? out : out.subarray(0, o);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// src/aiLive/provider.ts
|
|
84
|
+
var PHONE_SLICE_USD = 0.5;
|
|
85
|
+
var LIVE_KIND = "ai-models.live";
|
|
86
|
+
var FRESH_MS = 3e3;
|
|
87
|
+
var MAX_BUFFERED = 512 * 1024;
|
|
88
|
+
var DEFAULT_CAMERA = { fps: 1, maxPx: 768 };
|
|
89
|
+
var SESSION_UP = /* @__PURE__ */ new Set(["starting", "running", "degraded"]);
|
|
90
|
+
async function defaultCallCp(method, params = {}) {
|
|
91
|
+
const res = await mcpToolCall("cp.ai_models_api", { method, params });
|
|
92
|
+
if (res?.error) throw new Error(res.error.message || "AI Models refused the request");
|
|
93
|
+
const out = unwrapMcpResult(res?.result);
|
|
94
|
+
if (res?.result?.isError) throw new Error(typeof out === "string" ? out : out?.message || out?.error || "AI Models refused the request");
|
|
95
|
+
if (out && typeof out === "object" && out.ok === false) throw new Error(out.message || out.error || "AI Models refused the request");
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
var defaultAiLiveDeps = () => ({
|
|
99
|
+
callCp: defaultCallCp,
|
|
100
|
+
WebSocketImpl: globalThis.WebSocket,
|
|
101
|
+
wsBase: getCoreWsUrl,
|
|
102
|
+
token: getToken,
|
|
103
|
+
tenant: getTenant,
|
|
104
|
+
jpegById,
|
|
105
|
+
now: Date.now,
|
|
106
|
+
setInterval: (fn, ms) => setInterval(fn, ms),
|
|
107
|
+
clearInterval: (h) => clearInterval(h)
|
|
108
|
+
});
|
|
109
|
+
var idle = () => ({ state: "idle", camera: null, sent: 0, skipped: 0, lastEpisode: null, lastError: null });
|
|
110
|
+
function createAiLiveProvider(overrides = {}) {
|
|
111
|
+
const deps = { ...defaultAiLiveDeps(), ...overrides };
|
|
112
|
+
let owner = null;
|
|
113
|
+
let snap = idle();
|
|
114
|
+
let ws = null;
|
|
115
|
+
let loop = null;
|
|
116
|
+
let visual = null;
|
|
117
|
+
let startedSession = false;
|
|
118
|
+
let closingOnPurpose = false;
|
|
119
|
+
let seq = 0;
|
|
120
|
+
let busy = false;
|
|
121
|
+
let gen = 0;
|
|
122
|
+
let lastFrameId = null;
|
|
123
|
+
let camera = DEFAULT_CAMERA;
|
|
124
|
+
let lastOwner = null;
|
|
125
|
+
const episodeCbs = /* @__PURE__ */ new Map();
|
|
126
|
+
const snapCbs = /* @__PURE__ */ new Map();
|
|
127
|
+
const sendingCbs = /* @__PURE__ */ new Set();
|
|
128
|
+
let wasSending = false;
|
|
129
|
+
const add = (m, who, cb) => {
|
|
130
|
+
let set2 = m.get(who);
|
|
131
|
+
if (!set2) {
|
|
132
|
+
set2 = /* @__PURE__ */ new Set();
|
|
133
|
+
m.set(who, set2);
|
|
134
|
+
}
|
|
135
|
+
set2.add(cb);
|
|
136
|
+
return { unsubscribe: () => {
|
|
137
|
+
set2.delete(cb);
|
|
138
|
+
} };
|
|
139
|
+
};
|
|
140
|
+
const set = (patch) => {
|
|
141
|
+
snap = { ...snap, ...patch };
|
|
142
|
+
for (const cb of lastOwner && snapCbs.get(lastOwner) || []) {
|
|
143
|
+
try {
|
|
144
|
+
cb(snap);
|
|
145
|
+
} catch {
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const sending = snap.state === "starting" || snap.state === "sending";
|
|
149
|
+
if (sending !== wasSending) {
|
|
150
|
+
wasSending = sending;
|
|
151
|
+
for (const cb of sendingCbs) {
|
|
152
|
+
try {
|
|
153
|
+
cb();
|
|
154
|
+
} catch {
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
function stopTimers() {
|
|
160
|
+
if (loop != null) {
|
|
161
|
+
deps.clearInterval(loop);
|
|
162
|
+
loop = null;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
async function slot() {
|
|
166
|
+
const mySeq = seq++;
|
|
167
|
+
const g = gen;
|
|
168
|
+
const sock = ws;
|
|
169
|
+
const current = () => g === gen && ws === sock && sock?.readyState === 1;
|
|
170
|
+
if (busy || !current()) {
|
|
171
|
+
set({ skipped: snap.skipped + 1 });
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if ((sock.bufferedAmount || 0) > MAX_BUFFERED) {
|
|
175
|
+
set({ skipped: snap.skipped + 1 });
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
busy = true;
|
|
179
|
+
try {
|
|
180
|
+
const v = await visual.getSnapshot();
|
|
181
|
+
if (!current()) return;
|
|
182
|
+
const f = v?.latest;
|
|
183
|
+
const id = f?.handle?.id;
|
|
184
|
+
const t = Number(f?.timestamp);
|
|
185
|
+
if (!id || id === lastFrameId || !(deps.now() - t < FRESH_MS)) {
|
|
186
|
+
set({ skipped: snap.skipped + 1 });
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const b64 = await deps.jpegById(id, camera.maxPx, 0.7);
|
|
190
|
+
if (!current()) return;
|
|
191
|
+
const frame = encodeFrame({ seq: mySeq, tCapture: t, payload: base64ToBytes(b64) });
|
|
192
|
+
sock.send(frame.buffer);
|
|
193
|
+
lastFrameId = id;
|
|
194
|
+
set({ sent: snap.sent + 1 });
|
|
195
|
+
} catch (e) {
|
|
196
|
+
if (g === gen) set({ skipped: snap.skipped + 1, lastError: String(e?.message || e) });
|
|
197
|
+
} finally {
|
|
198
|
+
if (g === gen) busy = false;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function openSocket() {
|
|
202
|
+
return new Promise((resolve, reject) => {
|
|
203
|
+
const token = deps.token();
|
|
204
|
+
const tenant = deps.tenant();
|
|
205
|
+
if (!token || !tenant) {
|
|
206
|
+
reject(new Error("not signed in to a workspace"));
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
const url = `${deps.wsBase()}${STREAM_PATH}?tenant=${encodeURIComponent(tenant)}`;
|
|
210
|
+
let opened = false;
|
|
211
|
+
const sock = new deps.WebSocketImpl(url, [SUBPROTOCOL, `adas.bearer.${token}`]);
|
|
212
|
+
ws = sock;
|
|
213
|
+
sock.binaryType = "arraybuffer";
|
|
214
|
+
sock.onopen = () => {
|
|
215
|
+
try {
|
|
216
|
+
sock.send(openMessage(LIVE_KIND));
|
|
217
|
+
} catch (e) {
|
|
218
|
+
reject(e);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
sock.onmessage = (m) => {
|
|
222
|
+
const ev = parseServerEvent(m?.data);
|
|
223
|
+
if (!ev) return;
|
|
224
|
+
if (ev.event === "opened" && !opened) {
|
|
225
|
+
opened = true;
|
|
226
|
+
resolve();
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (ev.event === "episode" && ev.data && typeof ev.data === "object") {
|
|
230
|
+
const episode = ev.data;
|
|
231
|
+
set({ lastEpisode: episode });
|
|
232
|
+
for (const cb of owner && episodeCbs.get(owner) || []) {
|
|
233
|
+
try {
|
|
234
|
+
cb(episode);
|
|
235
|
+
} catch {
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
sock.onerror = () => {
|
|
241
|
+
};
|
|
242
|
+
sock.onclose = (c) => {
|
|
243
|
+
const why = describeClose(Number(c?.code), c?.reason);
|
|
244
|
+
if (!opened) {
|
|
245
|
+
reject(new Error(why));
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (closingOnPurpose || ws !== sock) return;
|
|
249
|
+
void teardown("error", why);
|
|
250
|
+
};
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
async function teardown(state, lastError) {
|
|
254
|
+
const hadSession = startedSession;
|
|
255
|
+
startedSession = false;
|
|
256
|
+
gen++;
|
|
257
|
+
stopTimers();
|
|
258
|
+
const sock = ws;
|
|
259
|
+
ws = null;
|
|
260
|
+
closingOnPurpose = true;
|
|
261
|
+
try {
|
|
262
|
+
if (sock && sock.readyState === 1) sock.send(CLOSE_MESSAGE);
|
|
263
|
+
} catch {
|
|
264
|
+
}
|
|
265
|
+
try {
|
|
266
|
+
sock?.close?.();
|
|
267
|
+
} catch {
|
|
268
|
+
}
|
|
269
|
+
closingOnPurpose = false;
|
|
270
|
+
const v = visual;
|
|
271
|
+
visual = null;
|
|
272
|
+
try {
|
|
273
|
+
await v?.stop?.();
|
|
274
|
+
} catch {
|
|
275
|
+
}
|
|
276
|
+
if (hadSession) {
|
|
277
|
+
try {
|
|
278
|
+
await deps.callCp("liveStop");
|
|
279
|
+
} catch {
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
owner = null;
|
|
283
|
+
set({ state, lastError });
|
|
284
|
+
}
|
|
285
|
+
return {
|
|
286
|
+
async start(opts, who, ctx) {
|
|
287
|
+
if (owner && owner !== who) throw Object.assign(new Error("aiLive: another screen is sending to AI right now. Close it first."), { code: "CONFLICT" });
|
|
288
|
+
if (owner === who) return snap;
|
|
289
|
+
const cam = opts?.camera === "front" ? "front" : "back";
|
|
290
|
+
if (opts?.camera && opts.camera !== "front" && opts.camera !== "back") throw new Error(`aiLive: unknown camera "${String(opts.camera)}" \u2014 use "front" or "back"`);
|
|
291
|
+
owner = who;
|
|
292
|
+
lastOwner = who;
|
|
293
|
+
visual = ctx.visual;
|
|
294
|
+
gen++;
|
|
295
|
+
seq = 0;
|
|
296
|
+
lastFrameId = null;
|
|
297
|
+
busy = false;
|
|
298
|
+
snap = { ...idle(), camera: cam };
|
|
299
|
+
set({ state: "starting" });
|
|
300
|
+
try {
|
|
301
|
+
let session = (await deps.callCp("liveStatus"))?.session;
|
|
302
|
+
if (!SESSION_UP.has(session?.state)) {
|
|
303
|
+
session = (await deps.callCp("liveStart", { source: "phone", budgetSliceUsd: PHONE_SLICE_USD }))?.session;
|
|
304
|
+
startedSession = true;
|
|
305
|
+
}
|
|
306
|
+
const c = session?.camera;
|
|
307
|
+
camera = c && Number(c.fps) > 0 && Number(c.maxPx) > 0 ? { fps: Number(c.fps), maxPx: Number(c.maxPx) } : DEFAULT_CAMERA;
|
|
308
|
+
await visual.start({ intent: "stream", facing: cam });
|
|
309
|
+
await openSocket();
|
|
310
|
+
loop = deps.setInterval(() => {
|
|
311
|
+
void slot();
|
|
312
|
+
}, Math.max(200, Math.round(1e3 / camera.fps)));
|
|
313
|
+
set({ state: "sending" });
|
|
314
|
+
return snap;
|
|
315
|
+
} catch (e) {
|
|
316
|
+
await teardown("error", String(e?.message || e));
|
|
317
|
+
throw e;
|
|
318
|
+
}
|
|
319
|
+
},
|
|
320
|
+
async stop(who) {
|
|
321
|
+
if (owner !== who) return;
|
|
322
|
+
await teardown("stopped", null);
|
|
323
|
+
},
|
|
324
|
+
getSnapshot: (who) => lastOwner === who ? snap : idle(),
|
|
325
|
+
onEpisode: (cb, who) => add(episodeCbs, who, cb),
|
|
326
|
+
subscribe: (cb, who) => add(snapCbs, who, cb),
|
|
327
|
+
forget(who) {
|
|
328
|
+
episodeCbs.delete(who);
|
|
329
|
+
snapCbs.delete(who);
|
|
330
|
+
if (lastOwner === who && owner === null) {
|
|
331
|
+
lastOwner = null;
|
|
332
|
+
snap = idle();
|
|
333
|
+
}
|
|
334
|
+
},
|
|
335
|
+
isSending: () => snap.state === "starting" || snap.state === "sending",
|
|
336
|
+
subscribeSending(cb) {
|
|
337
|
+
sendingCbs.add(cb);
|
|
338
|
+
return { unsubscribe: () => {
|
|
339
|
+
sendingCbs.delete(cb);
|
|
340
|
+
} };
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export {
|
|
346
|
+
PHONE_SLICE_USD,
|
|
347
|
+
LIVE_KIND,
|
|
348
|
+
defaultAiLiveDeps,
|
|
349
|
+
createAiLiveProvider
|
|
350
|
+
};
|
|
351
|
+
//# sourceMappingURL=chunk-JUBLG3PN.mjs.map
|