@ateam-ai-mobile/expo 0.1.4 → 0.1.7
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/android/build.gradle +16 -0
- package/android/src/main/java/expo/modules/adavision/AdaVisionModule.kt +75 -0
- package/dist/attachmentCache-DhQTqi2E.d.mts +18 -0
- package/dist/attachmentCache-DhQTqi2E.d.ts +18 -0
- package/dist/bootstrap.d.mts +95 -0
- package/dist/bootstrap.d.ts +95 -0
- package/dist/bootstrap.js +2473 -0
- package/dist/bootstrap.js.map +1 -0
- package/dist/bootstrap.mjs +64 -0
- package/dist/bootstrap.mjs.map +1 -0
- package/dist/chunk-4BMWVN25.mjs +91 -0
- package/dist/chunk-4BMWVN25.mjs.map +1 -0
- package/dist/chunk-4XYXJYN5.mjs +1513 -0
- package/dist/chunk-4XYXJYN5.mjs.map +1 -0
- package/dist/chunk-5HM6UA2K.mjs +571 -0
- package/dist/chunk-5HM6UA2K.mjs.map +1 -0
- package/dist/chunk-6LXF3JVX.mjs +96 -0
- package/dist/chunk-6LXF3JVX.mjs.map +1 -0
- package/dist/chunk-FF6ZZZXH.mjs +71 -0
- package/dist/chunk-FF6ZZZXH.mjs.map +1 -0
- package/dist/chunk-KOXF2FZM.mjs +92 -0
- package/dist/chunk-KOXF2FZM.mjs.map +1 -0
- package/dist/chunk-L4V7OCJ3.mjs +71 -0
- package/dist/chunk-L4V7OCJ3.mjs.map +1 -0
- package/dist/chunk-TZXWVYYR.mjs +67 -0
- package/dist/chunk-TZXWVYYR.mjs.map +1 -0
- package/dist/chunk-VQJPSLHP.mjs +1801 -0
- package/dist/chunk-VQJPSLHP.mjs.map +1 -0
- package/dist/chunk-WMJKH4XE.mjs +34 -0
- package/dist/chunk-WMJKH4XE.mjs.map +1 -0
- package/dist/chunk-XQSY6MHP.mjs +213 -0
- package/dist/chunk-XQSY6MHP.mjs.map +1 -0
- package/dist/createBridge.mjs +2 -0
- package/dist/createBridge.mjs.map +1 -1
- package/dist/device/createDeviceProvider.d.mts +23 -0
- package/dist/device/createDeviceProvider.d.ts +23 -0
- package/dist/device/createDeviceProvider.js +967 -0
- package/dist/device/createDeviceProvider.js.map +1 -0
- package/dist/device/createDeviceProvider.mjs +17 -0
- package/dist/device/createDeviceProvider.mjs.map +1 -0
- package/dist/device-bridge/collectors/appEngagement.d.mts +10 -0
- package/dist/device-bridge/collectors/appEngagement.d.ts +10 -0
- package/dist/device-bridge/collectors/appEngagement.js +128 -0
- package/dist/device-bridge/collectors/appEngagement.js.map +1 -0
- package/dist/device-bridge/collectors/appEngagement.mjs +12 -0
- package/dist/device-bridge/collectors/appEngagement.mjs.map +1 -0
- package/dist/device-bridge/collectors/health.d.mts +24 -0
- package/dist/device-bridge/collectors/health.d.ts +24 -0
- package/dist/device-bridge/collectors/health.js +238 -0
- package/dist/device-bridge/collectors/health.js.map +1 -0
- package/dist/device-bridge/collectors/health.mjs +18 -0
- package/dist/device-bridge/collectors/health.mjs.map +1 -0
- package/dist/device-bridge/cookies.d.mts +49 -0
- package/dist/device-bridge/cookies.d.ts +49 -0
- package/dist/device-bridge/cookies.js +90 -0
- package/dist/device-bridge/cookies.js.map +1 -0
- package/dist/device-bridge/cookies.mjs +14 -0
- package/dist/device-bridge/cookies.mjs.map +1 -0
- package/dist/device-bridge/index.d.mts +483 -0
- package/dist/device-bridge/index.d.ts +483 -0
- package/dist/device-bridge/index.js +2084 -0
- package/dist/device-bridge/index.js.map +1 -0
- package/dist/device-bridge/index.mjs +32 -0
- package/dist/device-bridge/index.mjs.map +1 -0
- package/dist/device-bridge/nfc.d.mts +30 -0
- package/dist/device-bridge/nfc.d.ts +30 -0
- package/dist/device-bridge/nfc.js +109 -0
- package/dist/device-bridge/nfc.js.map +1 -0
- package/dist/device-bridge/nfc.mjs +14 -0
- package/dist/device-bridge/nfc.mjs.map +1 -0
- package/dist/index.d.mts +493 -18
- package/dist/index.d.ts +493 -18
- package/dist/index.js +1409 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +23 -194
- package/dist/index.mjs.map +1 -1
- package/dist/oauth/expoOAuth.d.mts +18 -0
- package/dist/oauth/expoOAuth.d.ts +18 -0
- package/dist/oauth/expoOAuth.js +102 -0
- package/dist/oauth/expoOAuth.js.map +1 -0
- package/dist/oauth/expoOAuth.mjs +8 -0
- package/dist/oauth/expoOAuth.mjs.map +1 -0
- package/dist/types-BRanJYTn.d.mts +138 -0
- package/dist/types-BRanJYTn.d.ts +138 -0
- package/dist/vision/index.d.mts +81 -0
- package/dist/vision/index.d.ts +81 -0
- package/dist/vision/index.js +101 -0
- package/dist/vision/index.js.map +1 -0
- package/dist/vision/index.mjs +28 -0
- package/dist/vision/index.mjs.map +1 -0
- package/expo-module.config.json +9 -0
- package/ios/AdaVision.podspec +28 -0
- package/ios/AdaVisionModule.swift +432 -0
- package/ios/Resources/yolov8n-oiv7.mlmodelc/analytics/coremldata.bin +0 -0
- package/ios/Resources/yolov8n-oiv7.mlmodelc/coremldata.bin +0 -0
- package/ios/Resources/yolov8n-oiv7.mlmodelc/metadata.json +773 -0
- package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/analytics/coremldata.bin +0 -0
- package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/coremldata.bin +0 -0
- package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/model.mil +720 -0
- package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/weights/weight.bin +0 -0
- package/ios/Resources/yolov8n-oiv7.mlmodelc/model1/coremldata.bin +0 -0
- package/package.json +107 -7
- package/src/bootstrap.ts +159 -0
- package/src/camera/CameraTaskHost.tsx +175 -0
- package/src/camera/cameraTasks.ts +129 -0
- package/src/device/createDeviceProvider.ts +832 -0
- package/src/device-bridge/actions/calendar-actions.ts +217 -0
- package/src/device-bridge/actions/dnd.ts +74 -0
- package/src/device-bridge/actions/health-actions.ts +58 -0
- package/src/device-bridge/actions/index.ts +12 -0
- package/src/device-bridge/actions/messaging.ts +74 -0
- package/src/device-bridge/actions/navigation.ts +88 -0
- package/src/device-bridge/actions/queue-poller.ts +151 -0
- package/src/device-bridge/background.ts +137 -0
- package/src/device-bridge/biometrics.ts +64 -0
- package/src/device-bridge/capabilities.ts +218 -0
- package/src/device-bridge/collectors/appEngagement.ts +120 -0
- package/src/device-bridge/collectors/battery.ts +83 -0
- package/src/device-bridge/collectors/calendar.ts +162 -0
- package/src/device-bridge/collectors/camera.ts +27 -0
- package/src/device-bridge/collectors/connectivity.ts +60 -0
- package/src/device-bridge/collectors/contacts.ts +200 -0
- package/src/device-bridge/collectors/health.ts +299 -0
- package/src/device-bridge/collectors/index.ts +12 -0
- package/src/device-bridge/collectors/location.ts +224 -0
- package/src/device-bridge/collectors/mood.ts +141 -0
- package/src/device-bridge/collectors/notifications.ts +70 -0
- package/src/device-bridge/cookies.ts +89 -0
- package/src/device-bridge/dynamic-connector.ts +422 -0
- package/src/device-bridge/index.ts +467 -0
- package/src/device-bridge/nfc.ts +85 -0
- package/src/device-bridge/plugin.ts +71 -0
- package/src/device-bridge/relay-client.ts +237 -0
- package/src/device-bridge/scanner.ts +42 -0
- package/src/device-bridge/sharing.ts +35 -0
- package/src/device-bridge/types.ts +326 -0
- package/src/device-state/activityClassifier.ts +151 -0
- package/src/device-state/activityEngine.ts +252 -0
- package/src/device-state/collectors.ts +31 -0
- package/src/device-state/domains/activity.ts +93 -0
- package/src/device-state/domains/capability.ts +60 -0
- package/src/device-state/domains/connectivity.ts +60 -0
- package/src/device-state/domains/deviceContext.ts +55 -0
- package/src/device-state/domains/interaction.ts +59 -0
- package/src/device-state/domains/spatial.ts +283 -0
- package/src/device-state/domains/visual.ts +100 -0
- package/src/device-state/headingSource.ts +84 -0
- package/src/device-state/index.ts +77 -0
- package/src/device-state/quality.ts +60 -0
- package/src/device-state/replay.ts +220 -0
- package/src/device-state/turnDetector.ts +121 -0
- package/src/device-state/visualEngine.ts +341 -0
- package/src/haptics.ts +4 -0
- package/src/index.ts +37 -0
- package/src/oauth/expoOAuth.tsx +113 -0
- package/src/vision/analysis.js +80 -0
- package/src/vision/index.ts +144 -0
- package/src/vision/ring.js +35 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/device-bridge/cookies.ts","../../src/device-bridge/nfc.ts","../../src/device/createDeviceProvider.ts","../../src/camera/cameraTasks.ts","../../src/vision/index.ts","../../src/device-bridge/actions/messaging.ts","../../src/device-bridge/actions/calendar-actions.ts","../../src/device-bridge/actions/navigation.ts","../../src/device-bridge/collectors/health.ts","../../src/device-bridge/background.ts","../../src/device-bridge/collectors/calendar.ts","../../src/device-bridge/collectors/contacts.ts","../../src/device-bridge/collectors/location.ts","../../src/device-bridge/collectors/battery.ts","../../src/device-bridge/collectors/connectivity.ts","../../src/device-bridge/collectors/notifications.ts","../../src/device-bridge/collectors/appEngagement.ts","../../src/device-bridge/collectors/camera.ts","../../src/device-bridge/biometrics.ts","../../src/device-bridge/sharing.ts","../../src/device-bridge/scanner.ts"],"sourcesContent":["/**\n * Device-bridge: Cookies API\n *\n * Reads the platform's shared cookie jar (NSHTTPCookieStorage on iOS,\n * CookieManager on Android) so upper layers (plugin-sdk → RN plugins) can\n * extract session cookies captured during a native WebView login flow.\n *\n * Wraps `@react-native-cookies/cookies` so upper layers never import the\n * native module directly. If we swap implementations, only this file changes.\n *\n * Why device-bridge owns this: cookies are a device-level capability (tied\n * to the platform's shared HTTP stack). Plugins should consume a clean\n * abstraction; the native wiring lives here.\n */\n\nimport CookieManager from '@react-native-cookies/cookies';\n\nexport interface DeviceCookie {\n name: string;\n value: string;\n domain?: string;\n path?: string;\n /** Unix seconds. Omitted for session cookies. */\n expires?: number;\n httpOnly?: boolean;\n secure?: boolean;\n sameSite?: 'Lax' | 'Strict' | 'None';\n}\n\n/**\n * Get every cookie attached to the URL's effective domain.\n * Set `includeHttpOnly` true to include HttpOnly cookies (required for\n * LinkedIn/Google session tokens).\n */\nexport async function get(url: string, includeHttpOnly: boolean = true): Promise<DeviceCookie[]> {\n const raw = (await CookieManager.get(url, includeHttpOnly)) as Record<string, any>;\n const out: DeviceCookie[] = [];\n for (const [name, c] of Object.entries(raw || {})) {\n if (!c || typeof c !== 'object') continue;\n const value = typeof c.value === 'string' ? c.value : String(c.value ?? '');\n const cookie: DeviceCookie = { name, value };\n if (c.domain) cookie.domain = String(c.domain);\n if (c.path) cookie.path = String(c.path);\n if (c.expires) {\n const t = Date.parse(c.expires);\n if (!Number.isNaN(t)) cookie.expires = Math.floor(t / 1000);\n }\n if (typeof c.httpOnly === 'boolean') cookie.httpOnly = c.httpOnly;\n if (typeof c.secure === 'boolean') cookie.secure = c.secure;\n if (c.sameSite === 'Lax' || c.sameSite === 'Strict' || c.sameSite === 'None') {\n cookie.sameSite = c.sameSite;\n }\n out.push(cookie);\n }\n return out;\n}\n\n/**\n * Wipe the shared cookie jar. Cross-platform scoped clear isn't supported\n * uniformly; `clearAll` is the safe operation on both iOS and Android.\n */\nexport async function clearAll(): Promise<{ ok: boolean; error?: string }> {\n try {\n await CookieManager.clearAll(true);\n return { ok: true };\n } catch (e: any) {\n return { ok: false, error: String(e?.message || e) };\n }\n}\n\n/**\n * Set a cookie programmatically. Useful when replaying a saved session on\n * the device's shared jar before opening a WebView.\n */\nexport async function set(url: string, cookie: DeviceCookie): Promise<{ ok: boolean; error?: string }> {\n try {\n await CookieManager.set(url, {\n name: cookie.name,\n value: cookie.value,\n domain: cookie.domain,\n path: cookie.path || '/',\n httpOnly: cookie.httpOnly,\n secure: cookie.secure,\n } as any, true);\n return { ok: true };\n } catch (e: any) {\n return { ok: false, error: String(e?.message || e) };\n }\n}\n","/**\n * Device-bridge: NFC\n *\n * Wraps react-native-nfc-manager for:\n * - Reading NFC tags (NDEF, Mifare)\n * - Writing to writable tags\n * - App-triggered tag discovery\n *\n * Use cases: physical-world triggers, inventory lookup, hardware keys,\n * loyalty cards, transit top-up, pairing.\n *\n * iOS: requires \"Near Field Communication Tag Reading\" entitlement in the\n * app's provisioning profile. Android: requires NFC permission in manifest.\n */\n\nimport NfcManager, { NfcTech, Ndef } from 'react-native-nfc-manager';\n\nlet _initialized = false;\n\nasync function ensureInit(): Promise<boolean> {\n if (_initialized) return true;\n try {\n const supported = await NfcManager.isSupported();\n if (!supported) return false;\n await NfcManager.start();\n _initialized = true;\n return true;\n } catch (e) {\n return false;\n }\n}\n\nexport async function isSupported(): Promise<boolean> {\n try { return await NfcManager.isSupported(); } catch { return false; }\n}\n\nexport async function isEnabled(): Promise<boolean> {\n try { return await NfcManager.isEnabled(); } catch { return false; }\n}\n\nexport interface NdefRecord {\n type: string;\n payload: string;\n}\n\nexport interface TagReadResult {\n ok: boolean;\n tagId?: string;\n records?: NdefRecord[];\n error?: string;\n}\n\n/** Wait for the next tag to be scanned, read NDEF records, release, and return. */\nexport async function readOnce(timeoutMs: number = 30_000): Promise<TagReadResult> {\n const ready = await ensureInit();\n if (!ready) return { ok: false, error: 'nfc_unsupported' };\n try {\n const tag = await Promise.race([\n NfcManager.requestTechnology(NfcTech.Ndef).then(() => NfcManager.getTag()),\n new Promise<null>((resolve) => setTimeout(() => resolve(null), timeoutMs)),\n ]);\n if (!tag) {\n try { await NfcManager.cancelTechnologyRequest(); } catch {}\n return { ok: false, error: 'timeout' };\n }\n const records: NdefRecord[] = [];\n if ((tag as any).ndefMessage) {\n for (const r of (tag as any).ndefMessage) {\n try {\n const type = String.fromCharCode(...(r.type || []));\n const payload = Ndef.text.decodePayload(r.payload || []);\n records.push({ type, payload: String(payload) });\n } catch {\n // skip records we can't decode\n }\n }\n }\n const tagId = (tag as any).id ? Array.from((tag as any).id).map((b: any) => b.toString(16).padStart(2, '0')).join('') : undefined;\n return { ok: true, tagId, records };\n } catch (e: any) {\n return { ok: false, error: String(e?.message || e) };\n } finally {\n try { await NfcManager.cancelTechnologyRequest(); } catch {}\n }\n}\n","/**\n * SDK device-primitive provider (Expo-backed).\n *\n * `createDeviceProvider()` builds the FULL, UNGATED `PluginNative` implementation\n * a host registers once via `setPluginNativeProvider`. Per-plugin capability\n * gating and per-plugin filesystem scoping are applied downstream by\n * plugin-runtime's `gatePluginNative` — this module does not gate.\n *\n * Not a React hook: it holds no React state and must be safe to build at module\n * scope, including on a headless background wake before any UI exists.\n */\nimport * as Haptics from 'expo-haptics';\n// Both are already app dependencies and already used by the device-bridge\n// collectors — safe for eager import (unlike cookies/nfc, which need native\n// modules absent from Expo Go).\nimport * as ExpoLocation from 'expo-location';\nimport * as ImagePicker from 'expo-image-picker';\nimport * as Notifications from 'expo-notifications';\nimport * as DocumentPicker from 'expo-document-picker';\nimport * as FS from 'expo-file-system';\nimport * as SQLite from 'expo-sqlite';\n// The broker behind scanner.scanOnce() and camera.recordVideo(): both need a\n// MOUNTED camera, which a function call cannot provide.\nimport { cameraTasks } from '../camera/cameraTasks';\nimport AsyncStorage from '@react-native-async-storage/async-storage';\n// native.vision: the on-device analyzer (ada-vision module) — resolve a frame id\n// to its local pixels, measure/read/classify on-device, never off the phone.\nimport * as adaVision from '../vision';\n// Device-bridge owns every native module. plugin-sdk delegates so RN\n// plugins never import native modules directly. When adding a new\n// capability: add it to device-bridge, import here, declare in types.ts,\n// wire in the factory below.\n//\n// IMPORTANT: cookies and nfc use native modules NOT available in Expo Go.\n// We lazy-import them so the app doesn't crash at load time.\n// Only biometrics (expo-local-authentication), sharing (expo-sharing),\n// and scanner (expo-camera) are safe for eager import.\nimport {\n biometrics as deviceBiometrics,\n sharing as deviceSharing,\n scanner as deviceScanner,\n} from '../device-bridge';\n\n// Lazy loaders for native modules not in Expo Go\nfunction getDeviceCookies() {\n try { return require('../device-bridge/cookies'); } catch { return null; }\n}\nfunction getDeviceNfc() {\n try { return require('../device-bridge/nfc'); } catch { return null; }\n}\nimport type {\n NativeCapabilities,\n PluginNative,\n CameraAPI,\n LocationAPI,\n StorageAPI,\n BiometricsAPI,\n BiometricsAPIv2,\n NotificationsAPI,\n HapticsAPI,\n ConnectivityAPI,\n FileSystemAPI,\n CookiesAPI,\n WebViewCookie,\n SharingAPI,\n ScannerAPI,\n NfcAPI,\n BluetoothAPI,\n VisionAPI,\n} from '@ateam-ai-mobile/plugin-runtime';\n\nclass CapabilityUnavailableError extends Error {\n code = 'UNAVAILABLE' as const;\n constructor(capability: string, reason?: string) {\n super(reason || `${capability} is not yet implemented. Coming in Phase 2.`);\n this.name = 'CapabilityUnavailableError';\n }\n}\n\nclass CapabilityNotDeclaredError extends Error {\n code = 'NOT_DECLARED' as const;\n constructor(capability: string) {\n super(`Capability '${capability}' not declared in plugin manifest. Add it to the native.${capability} field.`);\n this.name = 'CapabilityNotDeclaredError';\n }\n}\n\nfunction stubApi<T extends object>(capability: string): T {\n return new Proxy({} as T, {\n get(_target, prop) {\n if (typeof prop === 'string') {\n return () => {\n throw new CapabilityUnavailableError(capability);\n };\n }\n },\n });\n}\n\n// ── Location (expo-location — was stubbed, is real now) ───────────\n//\n// `location` was wired to stubApi, so a plugin that correctly DECLARED\n// `location: true` still got \"location is not yet implemented. Coming in\n// Phase 2.\" on every call. expo-location has been a dependency all along and\n// the device-bridge collectors use it; only the plugin-facing API was missing.\n\nfunction createLocationAPI(): LocationAPI {\n /** Ask once, and say what the user can do about a refusal. */\n const ensurePermission = async (): Promise<void> => {\n const existing = await ExpoLocation.getForegroundPermissionsAsync();\n if (existing.status === 'granted') return;\n const asked = await ExpoLocation.requestForegroundPermissionsAsync();\n if (asked.status !== 'granted') {\n // A voice assistant reads this out, so it has to be actionable rather\n // than a status code.\n throw new Error(\n 'Location permission was not granted. Enable it for this app in Settings > Privacy > Location Services.',\n );\n }\n };\n\n return {\n async getCurrent(opts) {\n await ensurePermission();\n // 'high' costs battery and a second or two of settling; default balanced,\n // which is plenty for \"which street am I on\".\n const fix = await ExpoLocation.getCurrentPositionAsync({\n accuracy:\n opts?.accuracy === 'high'\n ? ExpoLocation.Accuracy.High\n : ExpoLocation.Accuracy.Balanced,\n });\n return {\n latitude: fix.coords.latitude,\n longitude: fix.coords.longitude,\n altitude: fix.coords.altitude ?? undefined,\n };\n },\n\n watchPosition(cb) {\n let subscription: { remove(): void } | null = null;\n let cancelled = false;\n\n void (async () => {\n try {\n await ensurePermission();\n if (cancelled) return;\n subscription = await ExpoLocation.watchPositionAsync(\n { accuracy: ExpoLocation.Accuracy.Balanced },\n fix => cb({ latitude: fix.coords.latitude, longitude: fix.coords.longitude }),\n );\n // Unsubscribed while we were still asking for permission — otherwise\n // the GPS stays on with nobody listening.\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}\n\n// ── Camera (expo-image-picker — was stubbed, is real now) ─────────\n//\n// Every method here opens the SYSTEM camera or picker UI, which is why they\n// are honest one-shot actions rather than a frame source: expo-camera can\n// deliver a live feed, but only through a MOUNTED CameraView component, which\n// a headless tool call has no way to mount. A continuous visual feed is the\n// semantic Visual domain's job (Device Bridge v2), not this API's.\n\nfunction createCameraAPI(): CameraAPI {\n const ensurePermission = async (): Promise<void> => {\n const existing = await ImagePicker.getCameraPermissionsAsync();\n if (existing.granted) return;\n const asked = await ImagePicker.requestCameraPermissionsAsync();\n if (!asked.granted) {\n throw new Error(\n 'Camera permission was not granted. Enable it for this app in Settings > Privacy > Camera.',\n );\n }\n };\n\n return {\n async takePhoto(opts) {\n await ensurePermission();\n const res = await ImagePicker.launchCameraAsync({\n quality: opts?.quality ?? 0.7,\n cameraType:\n opts?.facing === 'front'\n ? ImagePicker.CameraType.front\n : ImagePicker.CameraType.back,\n });\n // The user backing out is not an error — but it is also not a photo, so\n // it must not come back as an empty-looking success.\n if (res.canceled || !res.assets?.[0]) {\n throw new Error('No photo taken — the camera was dismissed.');\n }\n const a = res.assets[0];\n return { uri: a.uri, width: a.width, height: a.height };\n },\n\n async scanBarcode(opts) {\n // Kept refusing, and now the refusal has somewhere to send you. Scanning\n // is a mounted camera lifecycle, which is why it lives on `scanner`.\n // Silently forwarding would leave a misleading name in every plugin.\n throw new CapabilityUnavailableError(\n 'camera.scanBarcode',\n 'Use native.scanner.scanOnce() instead — scanning needs a mounted camera, ' +\n 'which this call cannot provide. Same arguments, and it returns { data, format }.' +\n (opts?.formats?.length ? ' Pass your formats through to scanOnce.' : ''),\n );\n },\n\n async recordVideo(opts) {\n // A FILE the user deliberately makes — not the Visual domain's frame\n // ring, which is ephemeral and nobody keeps. Runs on the shared camera\n // surface, so it throws the same coded failures as scanOnce.\n return cameraTasks.run('record', {\n maxDurationMs: opts?.maxDurationMs,\n withAudio: opts?.withAudio ?? false,\n });\n },\n\n async pickImage(opts) {\n const existing = await ImagePicker.getMediaLibraryPermissionsAsync();\n if (!existing.granted) {\n const asked = await ImagePicker.requestMediaLibraryPermissionsAsync();\n if (!asked.granted) {\n throw new Error(\n 'Photo library permission was not granted. Enable it for this app in Settings > Privacy > Photos.',\n );\n }\n }\n const res = await ImagePicker.launchImageLibraryAsync({\n allowsMultipleSelection: !!opts?.multiple,\n });\n if (res.canceled) return [];\n return (res.assets || []).map(a => ({ uri: a.uri }));\n },\n };\n}\n\n// ── Storage (AsyncStorage — was stubbed) ──────────────────────────\n//\n// KV is real. `db.execute` is NOT: expo-sqlite is not installed, and a fake\n// SQL layer over AsyncStorage would be a worse lie than an error — it would\n// accept a query and return an empty rowset, which reads as \"no rows matched\".\n\n/**\n * One SQLite file for plugin storage, opened lazily and once.\n *\n * Lazy because opening a database at module load costs startup time for every\n * user who never touches a plugin that needs one; once because two handles to\n * the same file is how you get a locked database under concurrent writes.\n */\n// Typed `any` for the handle: expo-sqlite is an any-shim in this SDK repo's\n// typecheck (the host supplies the real types), so `SQLite.SQLiteDatabase` is\n// not a nameable type here. Runtime is unchanged — SQLite.openDatabaseAsync\n// still returns a real SQLiteDatabase on device.\n// One handle PER plugin database file, opened lazily and once each. A Map (not a\n// single promise) because storage is now per-plugin: each plugin gets its own\n// file, and two handles to the same file is how you get a locked database.\nconst _pluginDbs = new Map<string, Promise<any>>();\nfunction openPluginDb(file: string): Promise<any> {\n const existing = _pluginDbs.get(file);\n if (existing) return existing;\n const opened: Promise<any> = SQLite.openDatabaseAsync(file);\n _pluginDbs.set(file, opened);\n return opened;\n}\n\n// The leading SQL keyword, uppercased, after stripping leading whitespace and\n// leading `-- line` / `/* block */` comments — so a comment cannot smuggle the\n// verb past the cross-file check (e.g. `/* */ ATTACH …`).\nfunction sqlLeadingKeyword(sql: string): string {\n let s = String(sql);\n for (;;) {\n const before = s;\n s = s.replace(/^\\s+/, '');\n if (s.startsWith('--')) { const nl = s.indexOf('\\n'); s = nl === -1 ? '' : s.slice(nl + 1); }\n else if (s.startsWith('/*')) { const end = s.indexOf('*/'); s = end === -1 ? '' : s.slice(end + 2); }\n if (s === before) break;\n }\n const m = s.match(/^[A-Za-z]+/);\n return m ? m[0].toUpperCase() : '';\n}\n\n// R3 SECURITY — per-plugin storage isolation. Both the KV namespace and the\n// SQLite database are scoped to the plugin's OWN id, so Plugin A cannot read,\n// overwrite, or query Plugin B's entries/tables. The id is threaded in from the\n// TRUSTED gate (storageFor(pluginId)) — never a caller-supplied prefix.\n//\n// The id is encoded with encodeURIComponent (not used raw) precisely because KV\n// is a FLAT concatenated keyspace with no structural boundary: a raw id like\n// `mcp:conn:plug` shares the `:` delimiter, so `@plugin:mcp:conn:plug:<k>` from\n// one plugin could collide with another plugin's id+key split. Encoding escapes\n// `:` (→ %3A), making the id segment unambiguous and the mapping injective, so\n// distinct ids can never produce overlapping namespaces regardless of the key.\n// (The filesystem sandbox can use the raw id as a directory name because a\n// directory boundary is structural, not delimiter-based.) The same encoded\n// token names the plugin's database file, giving each plugin a distinct DB.\nfunction createStorageAPI(pluginId: string): StorageAPI {\n const ns = encodeURIComponent(pluginId);\n const key = (k: string) => `@plugin:${ns}:${k}`;\n const dbFile = `plugin-storage-${ns}.db`;\n\n return {\n get: (k) => AsyncStorage.getItem(key(k)),\n set: (k, v) => AsyncStorage.setItem(key(k), v),\n delete: (k) => AsyncStorage.removeItem(key(k)),\n db: {\n async execute(sql: string, params?: any[]) {\n const verb = sqlLeadingKeyword(sql);\n // Per-plugin storage isolation rests on each plugin owning its OWN\n // database FILE. SQLite can cross files — ATTACH mounts another db,\n // VACUUM INTO writes one — so the file boundary only holds if those are\n // refused. Otherwise a plugin could `ATTACH '.../plugin-storage-<other\n // id>.db'` (the id is public and the filename deterministic) and read or\n // overwrite another plugin's tables. Refuse cross-file statements at the\n // trusted gate; a plugin never needs them for its own single database.\n // (runAsync/getAllAsync compile only the FIRST statement, so a trailing\n // `; ATTACH …` never runs — the leading verb is the whole surface.)\n // ATTACH/DETACH/VACUUM are the only cross-FILE statements in the standard\n // expo-sqlite build: loadable extensions are disabled and the file-vtab\n // modules (fileio/csv/zipfile) are not compiled in, so there is no other\n // way for a plugin's own connection to reach another plugin's file. If a\n // future SQLite build enables those, revisit (an allowlist would be the\n // durable form).\n if (verb === 'ATTACH' || verb === 'DETACH' || verb === 'VACUUM') {\n throw new CapabilityUnavailableError(\n 'storage.db',\n `SQL '${verb}' is not permitted: a plugin's storage is confined to its own database and cannot reach another file.`,\n );\n }\n const db = await openPluginDb(dbFile);\n // A statement either RETURNS ROWS or CHANGES THEM, and the two need\n // different calls. Deciding by the leading keyword rather than by\n // trying one and falling back: a failed INSERT retried as a query\n // would run it twice.\n const returnsRows = verb === 'SELECT' || verb === 'PRAGMA' || verb === 'WITH';\n\n if (returnsRows) {\n const rows = await db.getAllAsync(sql, (params ?? []) as any);\n // changes: 0 is the truth for a SELECT, not a placeholder.\n return { rows, changes: 0 };\n }\n const res = await db.runAsync(sql, (params ?? []) as any);\n // rows: [] is likewise true for a write — it did not select anything.\n return { rows: [], changes: res.changes ?? 0 };\n },\n },\n };\n}\n\n/**\n * Wipe ALL plugin storage — KV, SQLite, and the file sandbox — across EVERY\n * plugin. Per-plugin isolation (R3) keeps plugins apart from each other; this is\n * the USER boundary: on sign-out it must run so the NEXT user/tenant cannot read\n * the previous one's plugin data. Best-effort per store — a hiccup clearing one\n * must never block sign-out — so each part is guarded independently.\n */\nexport async function clearAllPluginData(): Promise<void> {\n // 1. KV — every `@plugin:` namespace (all plugins, all keys).\n try {\n const keys = await AsyncStorage.getAllKeys();\n const mine = keys.filter((k: string) => k.startsWith('@plugin:'));\n if (mine.length) await AsyncStorage.multiRemove(mine);\n } catch (e: any) {\n console.warn('[adas] clearAllPluginData: KV clear failed:', e?.message || e);\n }\n\n // 2. SQLite — close any open per-plugin handles, then delete the db files.\n try {\n for (const [, p] of _pluginDbs) {\n try { const db = await p; await db.closeAsync?.(); } catch { /* already closed */ }\n }\n _pluginDbs.clear();\n const sqliteDir = new FS.Directory(FS.Paths.document, 'SQLite');\n if (sqliteDir.exists) {\n for (const entry of sqliteDir.list()) {\n if (/^plugin-storage-.*\\.db$/.test(String(entry.name ?? ''))) {\n try { entry.delete(); } catch { /* best effort */ }\n }\n }\n }\n } catch (e: any) {\n console.warn('[adas] clearAllPluginData: SQLite clear failed:', e?.message || e);\n }\n\n // 3. Files — the whole plugin-files/ sandbox tree (all plugins).\n try {\n const dir = new FS.Directory(FS.Paths.document, 'plugin-files');\n if (dir.exists) dir.delete();\n } catch (e: any) {\n console.warn('[adas] clearAllPluginData: file sandbox clear failed:', e?.message || e);\n }\n}\n\n// ── Notifications (expo-notifications — was stubbed) ──────────────\n\nfunction createNotificationsAPI(): NotificationsAPI {\n return {\n async schedule({ title, body, trigger }) {\n const perm = await Notifications.getPermissionsAsync();\n if (!perm.granted) {\n const asked = await Notifications.requestPermissionsAsync();\n if (!asked.granted) {\n throw new Error(\n 'Notification permission was not granted. Enable it for this app in Settings > Notifications.',\n );\n }\n }\n // `seconds` and `date` are the two the contract declares; anything else\n // would be this API inventing a scheduling model of its own.\n const when: any =\n typeof trigger?.seconds === 'number'\n ? { type: 'timeInterval', seconds: trigger.seconds, repeats: false }\n : trigger?.date\n ? { type: 'date', date: new Date(trigger.date) }\n : null;\n if (!when) {\n throw new Error('schedule() needs trigger.seconds or trigger.date.');\n }\n return Notifications.scheduleNotificationAsync({\n content: { title, body },\n trigger: when,\n });\n },\n\n cancel: (id) => Notifications.cancelScheduledNotificationAsync(id),\n\n onReceived(cb) {\n const sub = Notifications.addNotificationReceivedListener(n => {\n cb({\n id: n.request.identifier,\n title: n.request.content.title || '',\n body: n.request.content.body || '',\n data: n.request.content.data,\n });\n });\n return () => sub.remove();\n },\n };\n}\n\n// ── File system (expo-document-picker — partially real) ───────────\n//\n// pickDocument works. read/write do NOT: expo-file-system is not installed.\n// Named honestly rather than returning empty strings, which would read as an\n// empty file rather than a missing capability.\n\nfunction createFileSystemAPI(pluginId: string): FileSystemAPI {\n /**\n * Every path a plugin gives us is resolved INSIDE its own sandbox directory.\n *\n * A plugin is code a solution ships that runs on someone's phone, so\n * `readFile('/etc/passwd')` — or, more realistically, reading the app's own\n * auth store or another solution's data — must not be reachable. This is the\n * same reasoning that took the `sw.*` filesystem tools out of the kernel and\n * anchored them per tenant.\n *\n * The check is on the RESOLVED path, not the input string: `..` segments are\n * what a blocklist of prefixes misses, and `plugin-files/../../secrets` looks\n * innocent until it is normalised.\n */\n /**\n * Resolved on FIRST USE, never at construction.\n *\n * `new FS.Directory(FS.Paths.document, …)` is a SYNCHRONOUS NATIVE CALL, and\n * `createNativeCapabilities({ fileSystem: true, … })` runs at MODULE SCOPE in\n * src/adas.ts. Building it eagerly therefore did native work during startup\n * module evaluation — on every launch, including a headless background wake\n * from a push, before any UI exists. If the native module is missing or\n * `Paths.document` throws there, the whole app dies with no screen to show it\n * on. Nothing in this factory may touch native until a method is called.\n */\n let _root: InstanceType<typeof FS.Directory> | null = null;\n const rootDir = () => (_root ??= new FS.Directory(FS.Paths.document, 'plugin-files', pluginId));\n\n const resolve = (p: string): InstanceType<typeof FS.File> => {\n const root = rootDir();\n const file = new FS.File(root, p);\n if (!file.uri.startsWith(root.uri)) {\n throw new CapabilityUnavailableError(\n 'fileSystem',\n `Path escapes the plugin's storage area: ${p}. Plugin files live under plugin-files/ and paths cannot traverse out of it.`,\n );\n }\n return file;\n };\n\n return {\n async readFile(path) {\n const file = resolve(path);\n if (!file.exists) {\n // A missing file is not an empty file. Returning '' would read as a\n // document that exists and happens to have nothing in it.\n throw new CapabilityUnavailableError(\n 'fileSystem.readFile',\n `No such file: ${path}. Nothing was read.`,\n );\n }\n return file.text();\n },\n\n async writeFile(path, content) {\n const file = resolve(path);\n // Create parents as needed — a plugin writing 'cache/report.json' should\n // not have to know that directories are a separate concept.\n const parent = file.parentDirectory;\n if (!parent.exists) parent.create({ intermediates: true });\n if (!file.exists) file.create();\n file.write(content);\n },\n async pickDocument(opts) {\n const res = await DocumentPicker.getDocumentAsync({\n type: opts?.types?.length ? opts.types : '*/*',\n copyToCacheDirectory: true,\n });\n // Backing out is not a file. Returning zeros here would look like an\n // empty document the user actually chose.\n if (res.canceled || !res.assets?.[0]) {\n throw new Error('No document chosen — the picker was dismissed.');\n }\n const a = res.assets[0];\n return { uri: a.uri, name: a.name, size: a.size ?? 0 };\n },\n };\n}\n\n// ── Haptics (fully implemented — expo-haptics already installed) ───\n\nfunction createHapticsAPI(): HapticsAPI {\n return {\n impact(style: 'light' | 'medium' | 'heavy') {\n const map = {\n light: Haptics.ImpactFeedbackStyle.Light,\n medium: Haptics.ImpactFeedbackStyle.Medium,\n heavy: Haptics.ImpactFeedbackStyle.Heavy,\n };\n Haptics.impactAsync(map[style]);\n },\n notification(type: 'success' | 'warning' | 'error') {\n const map = {\n success: Haptics.NotificationFeedbackType.Success,\n warning: Haptics.NotificationFeedbackType.Warning,\n error: Haptics.NotificationFeedbackType.Error,\n };\n Haptics.notificationAsync(map[type]);\n },\n // Shorthand for notification('error'). Plugins call this; it was never\n // implemented, and optional chaining meant the failure the user was meant\n // to FEEL simply did not happen.\n error() {\n Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);\n },\n selection() {\n Haptics.selectionAsync();\n },\n };\n}\n\n// ── Connectivity (implemented using basic RN fetch check) ──────\n\nfunction createConnectivityAPI(reachabilityUrl?: string): ConnectivityAPI {\n let online = true;\n const listeners = new Set<(online: boolean) => void>();\n // Lazy + re-armable polling: the instance is now a singleton shared by ALL\n // plugins (injected once via setPluginNativeProvider), so the interval must\n // (a) not run at app boot when nobody is listening, and (b) restart when a\n // later plugin subscribes after an earlier one unsubscribed to zero.\n // Pre-singleton, each Plugin mount got its own instance and clearInterval\n // was harmless; with a shared instance it would kill polling app-wide.\n let interval: ReturnType<typeof setInterval> | null = null;\n\n // Simple connectivity check — upgrade to @react-native-community/netinfo in Phase 2.\n // NO hardcoded URL: the host injects its own health endpoint. With none given\n // we assume reachable (return true) rather than pin an A-Team-specific default.\n const checkOnline = async () => {\n if (!reachabilityUrl) return true;\n try {\n const res = await fetch(reachabilityUrl, {\n method: 'HEAD',\n signal: AbortSignal.timeout(5000),\n });\n return res.ok;\n } catch {\n return false;\n }\n };\n\n const startPolling = () => {\n // Nothing to poll without a reachability URL: `online` stays constant-true,\n // so an interval would only wake the app to learn the same answer.\n if (!reachabilityUrl) return;\n if (interval) return;\n interval = setInterval(async () => {\n const newState = await checkOnline();\n if (newState !== online) {\n online = newState;\n listeners.forEach(cb => cb(online));\n }\n }, 30000);\n };\n\n return {\n isOnline() {\n return online;\n },\n onChange(cb: (online: boolean) => void) {\n listeners.add(cb);\n startPolling();\n return () => {\n listeners.delete(cb);\n if (listeners.size === 0 && interval) {\n clearInterval(interval);\n interval = null;\n }\n };\n },\n };\n}\n\n// ── Cookies (delegates to device-bridge, lazy-loaded) ──\nfunction createCookiesAPI(): CookiesAPI {\n return {\n async get(url: string): Promise<WebViewCookie[]> {\n const mod = getDeviceCookies();\n if (!mod) throw new CapabilityUnavailableError('cookies (native module not available — use a dev build)');\n const list = await mod.get(url, true);\n return list as WebViewCookie[];\n },\n async clear(_url: string): Promise<{ ok: boolean }> {\n const mod = getDeviceCookies();\n if (!mod) throw new CapabilityUnavailableError('cookies (native module not available — use a dev build)');\n const r = await mod.clearAll();\n return { ok: r.ok };\n },\n };\n}\n\n// ── Biometrics v2 (Face ID / Touch ID / fingerprint) ──\nfunction createBiometricsAPIv2(): BiometricsAPIv2 {\n return {\n capabilities: () => deviceBiometrics.capabilities(),\n authenticate: (opts) => deviceBiometrics.authenticate(opts),\n };\n}\n\n// ── Sharing (native share sheet) ──\nfunction createSharingAPI(): SharingAPI {\n return {\n isAvailable: () => deviceSharing.isAvailable(),\n shareFile: (fileUri, opts) => deviceSharing.shareFile(fileUri, opts),\n };\n}\n\n// ── Scanner (QR / barcode permission helper) ──\nfunction createScannerAPI(): ScannerAPI {\n return {\n requestPermissions: () => deviceScanner.requestPermissions(),\n // Raises the shared camera surface and settles on the first code read.\n // The plugin mounts nothing — that lifecycle is owned once, by\n // CameraTaskHost, instead of by every plugin that wants to scan.\n scanOnce: (opts) => cameraTasks.run('scan', {\n formats: opts?.formats,\n timeoutMs: opts?.timeoutMs,\n }),\n };\n}\n\n// ── NFC (tag read, lazy-loaded) ──\nfunction createNfcAPI(): NfcAPI {\n return {\n async isSupported() {\n const mod = getDeviceNfc();\n if (!mod) return false;\n return mod.isSupported();\n },\n async isEnabled() {\n const mod = getDeviceNfc();\n if (!mod) return false;\n return mod.isEnabled();\n },\n readOnce(timeoutMs) {\n const mod = getDeviceNfc();\n if (!mod) return Promise.resolve({ ok: false, error: 'nfc_unavailable' } as any);\n return mod.readOnce(timeoutMs);\n },\n };\n}\n\n// ── Bluetooth / BLE (SHAPE ONLY — every method refuses) ──\n//\n// Nothing implements this yet, and it is wired up anyway. `bluetooth` has been\n// a manifest flag with no API behind it, so a plugin that correctly declared it\n// got `undefined` and crashed with \"cannot read properties of undefined\" — a\n// failure that names nothing and teaches nothing.\n//\n// Refusing BY NAME is the whole difference. The rule this layer runs on is that\n// absence is an answer, but only when it says what is absent.\n//\n// KEPT rather than dropped because BLE beacons are one of the few indoor\n// position signals that survive where GPS does not — which is precisely where\n// Ada Guide ends up the moment the user walks into a building.\nfunction createBluetoothAPI(): BluetoothAPI {\n const refuse = (method: string) =>\n new CapabilityUnavailableError(\n `bluetooth.${method}`,\n 'Bluetooth is not implemented in this build — no BLE native module is installed. ' +\n 'The capability is declared so it fails by name rather than silently; nothing was scanned.',\n );\n\n return {\n // These two answer `false` rather than throwing, because \"is BLE usable?\"\n // is exactly the question a plugin should be allowed to ask before\n // committing to a flow, and `false` is the true answer here.\n async isSupported() { return false; },\n async isEnabled() { return false; },\n // scan() THROWS, because there is no honest empty result: an empty device\n // list is a real finding (\"nothing is advertising nearby\") and returning\n // one would report a scan that never happened.\n async scan() { throw refuse('scan'); },\n };\n}\n\n\n// ── Vision — on-device image understanding (SHAPE ONLY) ──\n//\n// Nothing implements this yet; every method refuses BY NAME. Declared now\n// because it is the last missing piece of Ada Guide and a solution should be\n// able to design against it before the native side exists.\n//\n// WHY IT IS NOT IN THE VISUAL DOMAIN: the freeze reserves Visual for the frame\n// TIMELINE and puts everything interpretive — what is in the scene, what the\n// sign says — ABOVE Device Bridge. This is that layer.\n//\n// FRAMES MUST NEVER LEAVE THE PHONE (Arie, 2026-08-15). Whoever implements\n// this: iOS Vision (VNRecognizeTextRequest / VNClassifyImageRequest) or\n// Android MLKit, both on-device and free per call. An implementation that\n// POSTs the frame anywhere satisfies these types and violates the design.\nfunction createVisionAPI(): VisionAPI {\n // All three methods are implemented on-device via the ada-vision native module:\n // assessQuality (pixel statistics), readText (VNRecognizeText), describe\n // (VNClassifyImage). Frames never leave the phone.\n return {\n // \"Can I see?\" — true once the native module is present in the binary. On a\n // build without it, adaVision.isSupported() answers false, and assessQuality\n // below refuses cleanly (no crash), exactly the pre-module behaviour.\n async isSupported() { return adaVision.isSupported(); },\n // readText: on-device OCR on a published frame (native resolves the id →\n // pixels). [] = looked, found no text (a real finding); throws = could not\n // look (unknown/aged-out id). describe (VNClassifyImage) is the next pass.\n async readText(frameId: string, opts?: { languages?: string[] }) {\n return adaVision.readText(frameId, opts?.languages);\n },\n // describe: on-device labels (VNClassifyImage), not prose — the sentence is\n // the skill's job. [] = looked, recognised nothing.\n async describe(frameId: string, opts?: { maxLabels?: number }) {\n return adaVision.describe(frameId, opts?.maxLabels ?? 5);\n },\n // detectObjects: on-device located objects (bundled detector), each with a\n // box — what a guidance loop reads to say WHERE a thing is, not just that the\n // scene contains it. [] = looked, found nothing; throws = could not look.\n async detectObjects(frameId: string, opts?: { maxItems?: number; minConfidence?: number }) {\n return adaVision.detectObjects(frameId, opts?.maxItems ?? 10, opts?.minConfidence ?? 0.25);\n },\n // assessQuality: resolve the frame id to its LOCAL file, measure on-device,\n // and record the result back onto the frame so a later read of\n // VisualFrameRef.quality reflects it. Throwing here means \"could not look\"\n // (unknown/aged-out id, or no native module) — never a measured verdict.\n async assessQuality(frameId: string) {\n // Quality was measured at publish; the pixels live in the native ring,\n // resolved by id inside native. Null = the frame is unknown or has aged out\n // of the ring — \"could not look\", never \"looked and found nothing\".\n const q = adaVision.qualityById(frameId);\n if (!q) {\n throw new CapabilityUnavailableError(\n 'vision.assessQuality',\n `No frame for id \"${frameId}\" — unknown or aged out of the ring. ` +\n 'This is \"could not look\", not a measurement.',\n );\n }\n return q;\n },\n };\n}\n\n// ── Provider factory ───────────────────────────────────────────\n\nexport interface DeviceProviderConfig {\n /** Endpoint the connectivity check HEAD-fetches (host-injected, e.g. the app's\n * own health URL). Omitted → connectivity assumes reachable (no hardcoded URL). */\n reachabilityUrl?: string;\n}\n\n/**\n * The full device-primitive implementation a host registers once via\n * setPluginNativeProvider. It is UNGATED — per-plugin capability gating and\n * per-plugin filesystem scoping are applied by plugin-runtime's gatePluginNative.\n */\nexport function createDeviceProvider(config?: DeviceProviderConfig): PluginNative {\n const connectivity = createConnectivityAPI(config?.reachabilityUrl);\n return {\n camera: createCameraAPI(),\n location: createLocationAPI(),\n // Only the per-plugin storageFor/fileSystemFor are exposed — NO shared\n // `storage`/`fileSystem` bucket. The gate scopes by pluginId and fails\n // closed without one, so a shared instance would be an unreachable\n // (and dangerous) fallback. Each plugin gets its own namespace + db file /\n // sandbox directory, or nothing.\n storageFor: (pluginId: string) => createStorageAPI(pluginId),\n biometrics: stubApi<BiometricsAPI>('biometrics'),\n biometricsV2: createBiometricsAPIv2(),\n notifications: createNotificationsAPI(),\n haptics: createHapticsAPI(),\n connectivity,\n fileSystemFor: (pluginId: string) => createFileSystemAPI(pluginId),\n cookies: createCookiesAPI(),\n sharing: createSharingAPI(),\n scanner: createScannerAPI(),\n nfc: createNfcAPI(),\n bluetooth: createBluetoothAPI(),\n vision: createVisionAPI(),\n };\n}\n","/**\n * The broker between a plugin's `await` and a mounted camera.\n *\n * WHY THIS EXISTS. expo-camera has no headless capture: scanning a barcode and\n * recording a clip both require a MOUNTED `<CameraView>`. But a plugin calls\n * `native.scanner.scanOnce()` and expects a promise — it has no way to mount\n * anything, and it must not have to.\n *\n * So the API enqueues a TASK here and awaits it; `CameraTaskHost`, mounted once\n * by the app, notices, shows the camera, does the work, and settles the\n * promise. This is the same split as the Visual engine, for the same reason —\n * and it is why `native.camera.scanBarcode` refuses and points here rather than\n * pretending a function call can own a React lifecycle.\n *\n * ONE TASK AT A TIME, and it is the phone that says so: there is one camera. A\n * second request while one is running is REJECTED rather than queued, because a\n * queued scan would open the camera again minutes later, long after the user\n * moved on and with no idea why it appeared.\n */\nexport interface ScanTask {\n kind: 'scan';\n opts: { formats?: string[]; timeoutMs?: number };\n resolve: (v: { data: string; format: string }) => void;\n reject: (e: Error) => void;\n}\n\nexport interface RecordTask {\n kind: 'record';\n opts: { maxDurationMs?: number; withAudio?: boolean };\n resolve: (v: { uri: string; durationMs: number | null }) => void;\n reject: (e: Error) => void;\n}\n\nexport type CameraTask = ScanTask | RecordTask;\n\ntype Listener = () => void;\n\n/** Typed failure, so a caller can say something specific and true. */\nexport function cameraError(code: string, message: string): Error {\n const err: any = new Error(message);\n err.code = code;\n return err;\n}\n\nclass CameraTaskBroker {\n private task: CameraTask | null = null;\n private listeners = new Set<Listener>();\n /** Set by the host while a camera is mounted and ready. */\n private hostMounted = false;\n\n current(): CameraTask | null { return this.task; }\n\n subscribe(fn: Listener): () => void {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Declare that a `CameraTaskHost` exists.\n *\n * Without it nothing will ever settle the promise, so a request must fail\n * IMMEDIATELY and say why. The alternative is a plugin awaiting forever,\n * which is the worst failure of the set: no error, no timeout, no camera,\n * and a conversation that simply stops.\n */\n setHostMounted(mounted: boolean): void {\n this.hostMounted = mounted;\n if (!mounted) this.fail(cameraError('UNAVAILABLE', 'The camera surface was dismissed before the task completed.'));\n this.notify();\n }\n\n isHostMounted(): boolean { return this.hostMounted; }\n\n /** Enqueue and hand back the promise the plugin awaits. */\n run<T>(kind: CameraTask['kind'], opts: any): Promise<T> {\n if (!this.hostMounted) {\n return Promise.reject(cameraError(\n 'UNAVAILABLE',\n 'No camera surface is mounted in this app, so the camera cannot be shown. ' +\n 'The host must render <CameraTaskHost /> once, near the app root.',\n ));\n }\n if (this.task) {\n return Promise.reject(cameraError(\n 'BUSY',\n `The camera is already in use (${this.task.kind}). Only one camera task can run at a time.`,\n ));\n }\n return new Promise<T>((resolve, reject) => {\n this.task = { kind, opts, resolve, reject } as unknown as CameraTask;\n this.notify();\n });\n }\n\n /** Settle the running task successfully and clear it. */\n complete(value: any): void {\n const t = this.task;\n if (!t) return;\n this.task = null;\n this.notify();\n t.resolve(value);\n }\n\n /** Settle the running task with a failure and clear it. */\n fail(err: Error): void {\n const t = this.task;\n if (!t) return;\n this.task = null;\n this.notify();\n t.reject(err);\n }\n\n /**\n * The user backed out.\n *\n * A distinct code, because \"the user chose not to\" is not a malfunction and\n * a guide should say something different about it than about a broken lens.\n */\n cancel(): void {\n this.fail(cameraError('CANCELLED', 'Cancelled — the camera was dismissed before anything was captured.'));\n }\n\n private notify(): void {\n for (const fn of this.listeners) { try { fn(); } catch { /* a bad listener is not the broker's problem */ } }\n }\n}\n\n/** One broker per app: there is one camera. */\nexport const cameraTasks = new CameraTaskBroker();\n","// ada-vision — on-device image understanding, our own native code (no camera lib).\n//\n// On-device, frames never leave the phone:\n// assessQuality(uri) — one-shot quality of a LOCAL frame file.\n// startVision()/onVisionFrame — the headless camera session that publishes a\n// timeline frame (id + quality, never pixels) at a\n// cadence; readText/describe/detectObjects resolve\n// a published id ON-DEVICE.\n//\n// The luma math mirrors ./analysis.js (which has the exhaustive unit tests).\n//\n// requireOptionalNativeModule: on a binary WITHOUT the native module, the import\n// is null, isSupported() is false, and the session calls refuse cleanly (no crash).\n\nimport type { ComponentType } from 'react';\nimport { requireOptionalNativeModule } from 'expo-modules-core';\nimport { requireNativeView } from 'expo';\n\n/** TEST-ONLY live preview bound to the same headless session (so a tester can\n * aim). The real Guide runs headless and never mounts this. Null on a binary\n * without the native view, so importing this module never crashes. */\nexport const CameraPreview: ComponentType<any> | null = (() => {\n try { return requireNativeView('AdaVision'); } catch { return null; }\n})();\n\nexport interface RawFrameQuality {\n blur: 'sharp' | 'slight' | 'severe' | 'unknown';\n exposure: 'good' | 'dark' | 'bright' | 'unknown';\n /** true = lens covered; false = clearly not; null = not assessed. */\n obstructed: boolean | null;\n}\n\ninterface Subscription { remove(): void }\n\n/** A published timeline frame from the vision session (metadata only — never\n * pixels; the buffer stays in the native ring, resolved by id). */\nexport interface VisionFrame {\n id: string;\n ts: number;\n expiresAt: number;\n blur: RawFrameQuality['blur'];\n exposure: RawFrameQuality['exposure'];\n obstructed: RawFrameQuality['obstructed'];\n}\n\n/** One OCR result on a frame — matches the SDK's VisionText. */\nexport interface VisionText {\n text: string;\n /** 0..1 recogniser confidence (never a 1.0 filler). */\n confidence: number | null;\n /** Normalised 0..1 box, origin TOP-left. */\n box?: { x: number; y: number; width: number; height: number };\n}\n\n/** One classifier label — a vocabulary term, NOT prose. Matches VisionLabel. */\nexport interface VisionLabel {\n label: string;\n confidence: number | null;\n}\n\n/** One detected object — a located item with a box, from the bundled detector. */\nexport interface VisionObject {\n /** Open-Images class name (e.g. \"Car\", \"Traffic light\", \"Building\", \"Person\"). */\n label: string;\n /** 0..1 detector confidence. */\n confidence: number | null;\n /** Normalised 0..1 box, origin TOP-left. */\n box?: { x: number; y: number; width: number; height: number };\n}\n\ninterface AdaVisionNative {\n isSupported(): boolean;\n assessQuality(uri: string): Promise<RawFrameQuality>;\n startVision(intervalMs: number): Promise<void>;\n stopVision(): void;\n visionRetentionMs(): number;\n qualityById(id: string): RawFrameQuality | null;\n readText(id: string, languages: string[] | null): Promise<VisionText[]>;\n describe(id: string, maxLabels: number): Promise<VisionLabel[]>;\n detectObjects(id: string, maxItems: number, minConfidence: number): Promise<VisionObject[]>;\n addListener(event: 'visionFrame', cb: (f: VisionFrame) => void): Subscription;\n}\n\nconst native = requireOptionalNativeModule<AdaVisionNative>('AdaVision');\n\n/** Is the native vision module present in this binary? */\nexport function isSupported(): boolean {\n try { return native?.isSupported() ?? false; } catch { return false; }\n}\n\n/** One-shot: measure a frame's quality from its LOCAL file. Throws if it cannot look. */\nexport async function assessQuality(uri: string): Promise<RawFrameQuality> {\n if (!native) throw new Error('ada-vision native module not present in this build');\n return native.assessQuality(uri);\n}\n\n// ── Vision session (feeds the Visual Engine) ──\n\n/** Start the vision session — publishes a timeline frame every `intervalMs`. */\nexport async function startVision(intervalMs = 1000): Promise<void> {\n if (!native) throw new Error('ada-vision native module not present in this build');\n return native.startVision(intervalMs);\n}\n\n/** Stop the vision session and release the camera. */\nexport function stopVision(): void {\n native?.stopVision?.();\n}\n\n/** Subscribe to published timeline frames (id + quality + expiry; no pixels). */\nexport function onVisionFrame(cb: (f: VisionFrame) => void): Subscription {\n if (!native) return { remove() {} };\n return native.addListener('visionFrame', cb);\n}\n\n/** How far back the native ring can still resolve a frame id (ms). */\nexport function visionRetentionMs(): number {\n return native?.visionRetentionMs?.() ?? 0;\n}\n\n/** Resolve a published frame id → its measured quality (null if evicted). */\nexport function qualityById(id: string): RawFrameQuality | null {\n return native?.qualityById?.(id) ?? null;\n}\n\n/** On-device OCR on a published frame. [] = looked, no text; throws = couldn't look. */\nexport async function readText(id: string, languages?: string[]): Promise<VisionText[]> {\n if (!native) throw new Error('ada-vision native module not present in this build');\n return native.readText(id, languages ?? null);\n}\n\n/** On-device image classification → labels (not prose). [] = nothing recognised. */\nexport async function describe(id: string, maxLabels = 5): Promise<VisionLabel[]> {\n if (!native) throw new Error('ada-vision native module not present in this build');\n return native.describe(id, maxLabels);\n}\n\n/** On-device object detection (bundled YOLOv8n, Open-Images vocabulary) → located\n * items with boxes. [] = looked, found nothing above `minConfidence`; throws =\n * couldn't look (id aged out, or the model isn't in this build). */\nexport async function detectObjects(id: string, maxItems = 10, minConfidence = 0.25): Promise<VisionObject[]> {\n if (!native) throw new Error('ada-vision native module not present in this build');\n return native.detectObjects(id, maxItems, minConfidence);\n}\n","/**\n * Messaging Action Executor — sends SMS via expo-sms.\n * Executes 'messaging.send' actions from the action queue.\n */\n\nimport * as SMS from 'expo-sms';\nimport type { ActionResult } from '../types';\n\n/**\n * Check if SMS is available on this device.\n */\nexport async function isAvailable(): Promise<boolean> {\n return SMS.isAvailableAsync();\n}\n\n/**\n * Execute a messaging.send action.\n *\n * Params expected:\n * - contact_name: string (for display only)\n * - phone: string (phone number to send to)\n * - message: string (message text)\n */\nexport async function execute(\n actionId: string,\n params: Record<string, unknown>\n): Promise<ActionResult> {\n const phone = params.phone as string;\n const message = params.message as string;\n\n if (!phone || !message) {\n return {\n id: actionId,\n ok: false,\n error: 'Missing phone or message parameter',\n executed_at: new Date().toISOString(),\n };\n }\n\n try {\n const available = await SMS.isAvailableAsync();\n if (!available) {\n return {\n id: actionId,\n ok: false,\n error: 'SMS not available on this device',\n executed_at: new Date().toISOString(),\n };\n }\n\n // Opens the native SMS compose screen with pre-filled content\n const { result } = await SMS.sendSMSAsync([phone], message);\n\n return {\n id: actionId,\n ok: result === 'sent' || result === 'unknown', // 'unknown' on Android means it was sent\n result: {\n to: params.contact_name || phone,\n phone,\n message,\n status: result,\n sent_at: new Date().toISOString(),\n },\n executed_at: new Date().toISOString(),\n };\n } catch (error) {\n return {\n id: actionId,\n ok: false,\n error: `SMS send failed: ${error instanceof Error ? error.message : String(error)}`,\n executed_at: new Date().toISOString(),\n };\n }\n}\n","/**\n * Calendar Action Executor — creates/modifies events via expo-calendar.\n * Executes 'calendar.create', 'calendar.reschedule', 'calendar.cancel' actions.\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// Derived rather than imported — see collectors/calendar.ts.\ntype Event = Awaited<ReturnType<typeof ExpoCalendar.getEventsAsync>>[number];\nimport type { ActionResult } from '../types';\n\n/**\n * Get the default calendar ID for creating events.\n */\nasync function getDefaultCalendarId(): Promise<string | null> {\n const calendars = await ExpoCalendar.getCalendarsAsync(ExpoCalendar.EntityTypes.EVENT);\n\n // Prefer the default calendar\n const defaultCal = calendars.find(c => c.isPrimary) || calendars[0];\n return defaultCal?.id || null;\n}\n\n/**\n * Execute a calendar.create action.\n *\n * Params expected:\n * - title: string\n * - date: string (YYYY-MM-DD)\n * - start_time: string (HH:MM)\n * - end_time?: string (HH:MM)\n * - location?: string\n * - attendees?: string[] (names — no email lookup here)\n * - notes?: string\n */\nexport async function executeCreate(\n actionId: string,\n params: Record<string, unknown>\n): Promise<ActionResult> {\n const title = params.title as string;\n const date = params.date as string;\n const startTime = params.start_time as string;\n const endTime = params.end_time as string | undefined;\n\n if (!title || !date || !startTime) {\n return {\n id: actionId,\n ok: false,\n error: 'Missing title, date, or start_time',\n executed_at: new Date().toISOString(),\n };\n }\n\n try {\n const calendarId = await getDefaultCalendarId();\n if (!calendarId) {\n return {\n id: actionId,\n ok: false,\n error: 'No calendar found on device',\n executed_at: new Date().toISOString(),\n };\n }\n\n const [year, month, day] = date.split('-').map(Number);\n const [startH, startM] = startTime.split(':').map(Number);\n\n const startDate = new Date(year, month - 1, day, startH, startM);\n let endDate: Date;\n\n if (endTime) {\n const [endH, endM] = endTime.split(':').map(Number);\n endDate = new Date(year, month - 1, day, endH, endM);\n } else {\n // Default 1 hour duration\n endDate = new Date(startDate.getTime() + 60 * 60 * 1000);\n }\n\n const eventId = await ExpoCalendar.createEventAsync(calendarId, {\n title,\n startDate,\n endDate,\n location: (params.location as string) || undefined,\n notes: (params.notes as string) || undefined,\n timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n });\n\n return {\n id: actionId,\n ok: true,\n result: {\n event_id: eventId,\n title,\n date,\n start: startTime,\n end: endTime || formatTime(endDate),\n message: `Event \"${title}\" created successfully`,\n },\n executed_at: new Date().toISOString(),\n };\n } catch (error) {\n return {\n id: actionId,\n ok: false,\n error: `Calendar create failed: ${error instanceof Error ? error.message : String(error)}`,\n executed_at: new Date().toISOString(),\n };\n }\n}\n\n/**\n * Execute a calendar.reschedule action.\n *\n * Params expected:\n * - event_id: string\n * - new_date?: string (YYYY-MM-DD)\n * - new_start_time?: string (HH:MM)\n * - new_end_time?: string (HH:MM)\n */\nexport async function executeReschedule(\n actionId: string,\n params: Record<string, unknown>\n): Promise<ActionResult> {\n const eventId = params.event_id as string;\n\n if (!eventId) {\n return {\n id: actionId,\n ok: false,\n error: 'Missing event_id',\n executed_at: new Date().toISOString(),\n };\n }\n\n try {\n const updates: Partial<Event> = {};\n\n if (params.new_date && params.new_start_time) {\n const [year, month, day] = (params.new_date as string).split('-').map(Number);\n const [h, m] = (params.new_start_time as string).split(':').map(Number);\n updates.startDate = new Date(year, month - 1, day, h, m);\n\n if (params.new_end_time) {\n const [eh, em] = (params.new_end_time as string).split(':').map(Number);\n updates.endDate = new Date(year, month - 1, day, eh, em);\n } else {\n updates.endDate = new Date(updates.startDate.getTime() + 60 * 60 * 1000);\n }\n }\n\n await ExpoCalendar.updateEventAsync(eventId, updates);\n\n return {\n id: actionId,\n ok: true,\n result: { event_id: eventId, message: 'Event rescheduled successfully' },\n executed_at: new Date().toISOString(),\n };\n } catch (error) {\n return {\n id: actionId,\n ok: false,\n error: `Calendar reschedule failed: ${error instanceof Error ? error.message : String(error)}`,\n executed_at: new Date().toISOString(),\n };\n }\n}\n\n/**\n * Execute a calendar.cancel action.\n *\n * Params expected:\n * - event_id: string\n */\nexport async function executeCancel(\n actionId: string,\n params: Record<string, unknown>\n): Promise<ActionResult> {\n const eventId = params.event_id as string;\n\n if (!eventId) {\n return {\n id: actionId,\n ok: false,\n error: 'Missing event_id',\n executed_at: new Date().toISOString(),\n };\n }\n\n try {\n await ExpoCalendar.deleteEventAsync(eventId);\n\n return {\n id: actionId,\n ok: true,\n result: { event_id: eventId, message: 'Event cancelled successfully' },\n executed_at: new Date().toISOString(),\n };\n } catch (error) {\n return {\n id: actionId,\n ok: false,\n error: `Calendar cancel failed: ${error instanceof Error ? error.message : String(error)}`,\n executed_at: new Date().toISOString(),\n };\n }\n}\n\n// ─── Helpers ───\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 * Navigation Action Executor — opens maps app via expo-linking.\n * Executes 'navigation.start' actions from the action queue.\n */\n\nimport * as Linking from 'expo-linking';\nimport { Platform } from 'react-native';\nimport type { ActionResult } from '../types';\n\n/**\n * Execute a navigation.start action.\n * Opens the native maps app with turn-by-turn directions.\n *\n * Params expected:\n * - destination: string (address or place name)\n * - mode?: 'driving' | 'transit' | 'walking' (default: 'driving')\n */\nexport async function execute(\n actionId: string,\n params: Record<string, unknown>\n): Promise<ActionResult> {\n const destination = params.destination as string;\n const mode = (params.mode as string) || 'driving';\n\n if (!destination) {\n return {\n id: actionId,\n ok: false,\n error: 'Missing destination parameter',\n executed_at: new Date().toISOString(),\n };\n }\n\n try {\n const encodedDest = encodeURIComponent(destination);\n let url: string;\n\n if (Platform.OS === 'ios') {\n // Apple Maps with directions\n const modeMap: Record<string, string> = {\n driving: 'd',\n transit: 'r',\n walking: 'w',\n };\n url = `maps://maps.apple.com/?daddr=${encodedDest}&dirflg=${modeMap[mode] || 'd'}`;\n } else {\n // Google Maps on Android\n const modeMap: Record<string, string> = {\n driving: 'driving',\n transit: 'transit',\n walking: 'walking',\n };\n url = `google.navigation:q=${encodedDest}&mode=${modeMap[mode] || 'driving'}`;\n }\n\n const canOpen = await Linking.canOpenURL(url);\n if (!canOpen) {\n // Fallback to Google Maps web URL\n const webModeMap: Record<string, string> = {\n driving: 'driving',\n transit: 'transit',\n walking: 'walking',\n };\n url = `https://www.google.com/maps/dir/?api=1&destination=${encodedDest}&travelmode=${webModeMap[mode] || 'driving'}`;\n }\n\n await Linking.openURL(url);\n\n return {\n id: actionId,\n ok: true,\n result: {\n message: `Navigation started to ${destination} via ${mode}`,\n destination,\n mode,\n status: 'navigating',\n },\n executed_at: new Date().toISOString(),\n };\n } catch (error) {\n return {\n id: actionId,\n ok: false,\n error: `Navigation failed: ${error instanceof Error ? error.message : String(error)}`,\n executed_at: new Date().toISOString(),\n };\n }\n}\n","/**\n * Health Collector — reads HealthKit aggregates via @kingstinct/react-native-healthkit\n * (TurboModule / Nitro-Modules based; works in React Native's New Architecture).\n *\n * iOS only. On Android the functions resolve with zeros so the caller doesn't\n * need to platform-check.\n *\n * Public:\n * - hasPermission() — returns true once authorization has been requested.\n * - requestPermission() — triggers the iOS HealthKit permission sheet (red heart).\n * - collectToday() — one HealthDayMetrics for today.\n * - collectHistory(days) — array of HealthDayMetrics, newest-first.\n */\nimport { Platform } from 'react-native';\nimport type { HealthDayMetrics } from '../types';\n\n// Lazy-loaded so the module is harmless on Android / Expo Go / non-iOS.\n// In Expo Go the JS module resolves but the native bridge is missing —\n// resulting object exists yet methods like requestAuthorization are undefined.\nlet _HK: any = null;\nlet _hkProbed = false;\nfunction getHK(): any | null {\n if (Platform.OS !== 'ios') return null;\n if (_hkProbed) return _HK;\n _hkProbed = true;\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const mod = require('@kingstinct/react-native-healthkit');\n if (mod && typeof mod.requestAuthorization === 'function') {\n _HK = mod;\n } else {\n console.warn('[health] @kingstinct/react-native-healthkit native bridge unavailable — HealthKit disabled (Expo Go?)');\n }\n } catch (e) {\n console.warn('[health] @kingstinct/react-native-healthkit require failed:', e);\n }\n return _HK;\n}\n\n// Last error from requestAuthorization — surfaced to UI so we don't fail silently.\nexport let lastHealthInitError: string | null = null;\n\nconst READ_TYPES = [\n 'HKQuantityTypeIdentifierStepCount',\n 'HKQuantityTypeIdentifierFlightsClimbed',\n 'HKQuantityTypeIdentifierActiveEnergyBurned',\n 'HKQuantityTypeIdentifierDistanceWalkingRunning',\n // Added for mood signals — all read-only, covered by the same auth sheet.\n 'HKQuantityTypeIdentifierRestingHeartRate',\n 'HKQuantityTypeIdentifierAppleExerciseTime',\n 'HKCategoryTypeIdentifierSleepAnalysis',\n] as const;\n\nlet _initPromise: Promise<boolean> | null = null;\n\n/** Request HealthKit authorization once; subsequent calls reuse the result. */\nasync function ensureInit(): Promise<boolean> {\n const HK = getHK();\n if (!HK) {\n lastHealthInitError = '@kingstinct/react-native-healthkit native module not loaded';\n return false;\n }\n if (_initPromise) return _initPromise;\n _initPromise = (async () => {\n try {\n // requestAuthorization triggers the iOS HealthKit permission sheet.\n // Resolves once the user dismisses it (regardless of allow/deny).\n // Returns the authorization status — but iOS deliberately does not\n // disclose per-type read permission state for privacy, so we just\n // treat \"we asked\" as \"ready to read\" and let reads return 0 if denied.\n await HK.requestAuthorization({ toRead: READ_TYPES, toWrite: [] });\n lastHealthInitError = null;\n return true;\n } catch (e: any) {\n lastHealthInitError = `requestAuthorization threw: ${e?.message || String(e)}`;\n console.warn('[health]', lastHealthInitError);\n _initPromise = null;\n return false;\n }\n })();\n return _initPromise;\n}\n\nexport async function hasPermission(): Promise<boolean> {\n return ensureInit();\n}\n\nexport async function requestPermission(): Promise<boolean> {\n return ensureInit();\n}\n\n// ─── Helpers ────────────────────────────────────────────────\n\nfunction startOfDay(d: Date): Date {\n const out = new Date(d);\n out.setHours(0, 0, 0, 0);\n return out;\n}\n\nfunction dateKey(d: Date): string {\n // Local-date YYYY-MM-DD\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, '0');\n const day = String(d.getDate()).padStart(2, '0');\n return `${y}-${m}-${day}`;\n}\n\n/**\n * Read a single daily-aggregate sum for [start, end) in the given unit.\n * Returns 0 when no data, HealthKit unavailable, or the call throws.\n *\n * `queryStatisticsForQuantity` is the modern statistics API; we ask only for\n * the cumulative sum since that's what we need for these data types.\n */\nasync function readDailySum(identifier: string, unit: string, start: Date, end: Date): Promise<number> {\n const HK = getHK();\n if (!HK?.queryStatisticsForQuantity) return 0;\n try {\n // The kingstinct API takes the date range nested under filter.date — not\n // top-level from/to. Without filter.date the call returns the cumulative\n // sum across ALL historical data, which is what we hit before this fix\n // (millions of steps, thousands of km, hundreds of thousands of kcal).\n const result: any = await HK.queryStatisticsForQuantity(\n identifier,\n ['cumulativeSum'],\n {\n unit,\n filter: { date: { startDate: start, endDate: end } },\n },\n );\n const q = result?.sumQuantity?.quantity;\n return typeof q === 'number' ? q : 0;\n } catch {\n return 0;\n }\n}\n\n/**\n * Daily discrete-average for a quantity (e.g. resting heart rate). Returns\n * null when no sample exists for the day so the backend can tell \"no data\"\n * apart from a real zero.\n */\nasync function readDailyAverage(identifier: string, unit: string, start: Date, end: Date): Promise<number | null> {\n const HK = getHK();\n if (!HK?.queryStatisticsForQuantity) return null;\n try {\n const result: any = await HK.queryStatisticsForQuantity(\n identifier,\n ['discreteAverage'],\n { unit, filter: { date: { startDate: start, endDate: end } } },\n );\n const q = result?.averageQuantity?.quantity;\n return typeof q === 'number' ? q : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Total minutes asleep for [start, end) from HKCategoryTypeIdentifierSleepAnalysis.\n * Sums sample durations that represent actual sleep (any \"asleep*\" value),\n * excluding inBed/awake. Heavily guarded — sleep-stage enums differ across iOS\n * versions and the kingstinct API surface, so any failure returns null.\n */\nasync function readSleepMinutes(start: Date, end: Date): Promise<number | null> {\n const HK = getHK();\n const query = HK?.queryCategorySamples || HK?.queryCategorySamplesAsync || HK?.querySamples;\n if (!query) return null;\n try {\n const samples: any[] = await query.call(\n HK,\n 'HKCategoryTypeIdentifierSleepAnalysis',\n { filter: { date: { startDate: start, endDate: end } } },\n );\n if (!Array.isArray(samples) || samples.length === 0) return null;\n // value semantics: 0 = inBed, 2 = awake; everything else = a sleep stage.\n // Treat anything that isn't explicitly inBed/awake as asleep.\n let ms = 0;\n for (const s of samples) {\n const v = s?.value;\n const isAsleep = v !== 0 && v !== 2; // exclude inBed + awake\n if (!isAsleep) continue;\n const a = new Date(s?.startDate).getTime();\n const b = new Date(s?.endDate).getTime();\n if (Number.isFinite(a) && Number.isFinite(b) && b > a) ms += b - a;\n }\n return ms > 0 ? Math.round(ms / 60000) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Mood-relevant HealthKit extras for today: sleep minutes, resting heart rate,\n * active energy (kcal), exercise minutes. Each is null when unavailable so the\n * backend weights only present fields.\n */\nexport async function collectMoodExtras(): Promise<{\n sleep_min: number | null;\n resting_hr: number | null;\n active_energy_kcal: number | null;\n exercise_min: number | null;\n}> {\n const ok = await ensureInit();\n if (!ok) return { sleep_min: null, resting_hr: null, active_energy_kcal: null, exercise_min: null };\n const start = startOfDay(new Date());\n const end = new Date(start);\n end.setDate(end.getDate() + 1);\n // Sleep window: look back from this morning over the past night (~last 18h)\n // so an evening collection still captures the prior night.\n const sleepStart = new Date(start);\n sleepStart.setHours(sleepStart.getHours() - 6); // include after-midnight + prev evening within today's window\n const [sleep_min, resting_hr, energy, exercise] = await Promise.all([\n readSleepMinutes(sleepStart, end),\n readDailyAverage('HKQuantityTypeIdentifierRestingHeartRate', 'count/min', start, end),\n readDailySum('HKQuantityTypeIdentifierActiveEnergyBurned', 'kcal', start, end),\n readDailySum('HKQuantityTypeIdentifierAppleExerciseTime', 'min', start, end),\n ]);\n return {\n sleep_min,\n resting_hr: resting_hr != null ? Math.round(resting_hr) : null,\n active_energy_kcal: energy ? Math.round(energy) : null,\n exercise_min: exercise ? Math.round(exercise) : null,\n };\n}\n\nasync function readDay(date: Date): Promise<HealthDayMetrics> {\n const start = startOfDay(date);\n const end = new Date(start);\n end.setDate(end.getDate() + 1);\n\n const [steps, floors, energy, distance] = await Promise.all([\n readDailySum('HKQuantityTypeIdentifierStepCount', 'count', start, end),\n readDailySum('HKQuantityTypeIdentifierFlightsClimbed', 'count', start, end),\n readDailySum('HKQuantityTypeIdentifierActiveEnergyBurned', 'kcal', start, end),\n // Ask for kilometers directly so we don't have to convert from meters.\n readDailySum('HKQuantityTypeIdentifierDistanceWalkingRunning', 'km', start, end),\n ]);\n\n return {\n date: dateKey(start),\n available: true,\n steps: Math.round(steps),\n floors: Math.round(floors),\n active_energy_kcal: Math.round(energy),\n distance_km: Math.round(distance * 100) / 100,\n };\n}\n\n// ─── Public API ─────────────────────────────────────────────\n\n/**\n * A day we could not read: metrics null, availability stated.\n *\n * The distinction this preserves is the whole point — \"no data\" and \"a day\n * with no activity\" look identical once you write a zero, and only one of\n * them is something to tell the user about.\n */\nfunction unavailableDay(date: Date): HealthDayMetrics {\n return {\n date: dateKey(date),\n available: false,\n steps: null,\n floors: null,\n active_energy_kcal: null,\n distance_km: null,\n };\n}\n\nexport async function collectToday(): Promise<HealthDayMetrics> {\n const ok = await ensureInit();\n if (!ok) {\n // HealthKit unavailable or access denied. NOT a day with no activity —\n // reporting zeros here is how \"you have taken 0 steps today\" reached the\n // user as a fact, with a coaching skill ready to act on it.\n return unavailableDay(new Date());\n }\n return readDay(new Date());\n}\n\n/**\n * Last `days` days, newest-first. Index 0 is today.\n * Caller passes 1..30 — we clamp defensively.\n */\nexport async function collectHistory(days: number): Promise<HealthDayMetrics[]> {\n const n = Math.max(1, Math.min(30, Math.floor(days)));\n const ok = await ensureInit();\n if (!ok) return [];\n\n const today = startOfDay(new Date());\n const out: HealthDayMetrics[] = [];\n // Sequential to avoid hammering HealthKit with 30 parallel queries.\n for (let i = 0; i < n; i++) {\n const d = new Date(today);\n d.setDate(d.getDate() - i);\n out.push(await readDay(d));\n }\n return out;\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","/**\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 * 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';\n// Type-only alias: the value namespace above cannot be used in type\n// position, so `ExpoLocation.Calendar`-style annotations need this.\n// Not re-exported from the package entry — derive from the API that\n// returns it, so the shape follows the installed expo-location.\ntype LocationGeocodedAddress = Awaited<ReturnType<typeof ExpoLocation.reverseGeocodeAsync>>[number];\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 ExpoLocation.reverseGeocodeAsync({\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\n/**\n * Stream position updates. Returns an unsubscribe function — call it, or the\n * GPS keeps running and drains the battery.\n */\nexport function watchPosition(cb: (pos: Position) => void): () => 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: ExpoLocation.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: LocationGeocodedAddress): 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 * 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 * 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 * 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 * App Engagement Collector — our OWN usage analytics (no OS permission, fully\n * available on every platform). Feeds the mood summary's app_sessions +\n * app_active_min, which iOS otherwise blocks for third-party apps.\n *\n * app_sessions — count of foreground sessions today (a background→active\n * transition, or a cold start, starts a session).\n * app_active_min — total minutes the app was in the foreground today.\n *\n * Counters are kept per local day and persisted to AsyncStorage so they\n * survive relaunches. start() must be called once at app boot to attach the\n * AppState listener; getToday() returns the current day's tallies.\n */\nimport { AppState, type AppStateStatus } from 'react-native';\nimport AsyncStorage from '@react-native-async-storage/async-storage';\n\nconst KEY = 'ateam.appEngagement.v1';\n\ninterface DayTally {\n date: string; // local YYYY-MM-DD\n sessions: number;\n activeMs: number;\n}\n\nlet _tally: DayTally | null = null;\nlet _foregroundSince: number | null = null;\nlet _started = false;\nlet _sub: { remove: () => void } | null = null;\n\nfunction todayKey(): string {\n const d = new Date();\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;\n}\n\nfunction fresh(): DayTally {\n return { date: todayKey(), sessions: 0, activeMs: 0 };\n}\n\nasync function load(): Promise<void> {\n try {\n const raw = await AsyncStorage.getItem(KEY);\n if (raw) {\n const parsed = JSON.parse(raw) as DayTally;\n _tally = parsed?.date === todayKey() ? parsed : fresh();\n } else {\n _tally = fresh();\n }\n } catch {\n _tally = fresh();\n }\n}\n\nfunction persist(): void {\n if (_tally) AsyncStorage.setItem(KEY, JSON.stringify(_tally)).catch(() => {});\n}\n\nfunction rollIfNewDay(): void {\n if (!_tally || _tally.date !== todayKey()) {\n _tally = fresh();\n persist();\n }\n}\n\n/** Fold the time spent foregrounded since the last checkpoint into activeMs. */\nfunction flushForeground(): void {\n if (_foregroundSince == null || !_tally) return;\n const now = Date.now();\n const delta = now - _foregroundSince;\n if (delta > 0) _tally.activeMs += delta;\n _foregroundSince = now;\n}\n\nfunction onChange(state: AppStateStatus): void {\n rollIfNewDay();\n if (state === 'active') {\n // New foreground session.\n if (_tally) _tally.sessions += 1;\n _foregroundSince = Date.now();\n persist();\n } else {\n // Leaving foreground — bank the elapsed active time.\n flushForeground();\n _foregroundSince = null;\n persist();\n }\n}\n\n/** Attach the AppState listener. Idempotent; call once at app boot. */\nexport async function start(): Promise<void> {\n if (_started) return;\n _started = true;\n await load();\n // Count the launch itself as the first active session.\n rollIfNewDay();\n if (_tally) _tally.sessions += 1;\n _foregroundSince = Date.now();\n persist();\n _sub = AppState.addEventListener('change', onChange);\n}\n\nexport function stop(): void {\n flushForeground();\n persist();\n _sub?.remove();\n _sub = null;\n _started = false;\n}\n\n/** Current day's tallies for the mood summary. */\nexport async function getToday(): Promise<{ app_sessions: number | null; app_active_min: number | null }> {\n if (!_tally) await load();\n rollIfNewDay();\n flushForeground(); // include the in-progress foreground stretch\n persist();\n if (!_tally) return { app_sessions: null, app_active_min: null };\n return {\n app_sessions: _tally.sessions,\n app_active_min: Math.round(_tally.activeMs / 60000),\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 * Device-bridge: Biometrics (Face ID / Touch ID / fingerprint)\n *\n * Used by solutions that need a biometric gate before sensitive actions\n * (e.g. \"unlock payment\", \"confirm financial transfer\", \"reveal stored\n * credentials\"). Also useful for protecting session cookies at rest.\n *\n * Wraps expo-local-authentication.\n */\n\nimport * as LocalAuthentication from 'expo-local-authentication';\n\nexport type BiometricType = 'fingerprint' | 'face' | 'iris' | 'none';\n\nexport interface BiometricCapabilities {\n hasHardware: boolean;\n isEnrolled: boolean;\n /**\n * Never contains 'none' — the mapper filters it out, since 'none' means\n * \"the OS reported an auth type we do not recognise\" and is not a\n * biometric a caller can offer. Typed as the guarantee the code makes.\n */\n supportedTypes: Exclude<BiometricType, 'none'>[];\n}\n\n/** What can the device do right now? */\nexport async function capabilities(): Promise<BiometricCapabilities> {\n const [hasHardware, isEnrolled, types] = await Promise.all([\n LocalAuthentication.hasHardwareAsync(),\n LocalAuthentication.isEnrolledAsync(),\n LocalAuthentication.supportedAuthenticationTypesAsync(),\n ]);\n const supportedTypes = types.map((t) => {\n if (t === LocalAuthentication.AuthenticationType.FINGERPRINT) return 'fingerprint';\n if (t === LocalAuthentication.AuthenticationType.FACIAL_RECOGNITION) return 'face';\n if (t === LocalAuthentication.AuthenticationType.IRIS) return 'iris';\n return 'none';\n }).filter((t) => t !== 'none') as Exclude<BiometricType, 'none'>[];\n return { hasHardware, isEnrolled, supportedTypes };\n}\n\nexport interface AuthenticateOptions {\n /** User-visible reason shown in the system dialog. */\n reason: string;\n /** Label on the \"cancel\" button (iOS only; Android has system default). */\n cancelLabel?: string;\n /** If biometrics aren't enrolled, fall back to device passcode. Default true. */\n fallbackToPasscode?: boolean;\n}\n\n/** Prompt the user for biometric auth. Resolves { success } or { success:false, error }. */\nexport async function authenticate(opts: AuthenticateOptions): Promise<{ success: boolean; error?: string }> {\n try {\n const res = await LocalAuthentication.authenticateAsync({\n promptMessage: opts.reason,\n cancelLabel: opts.cancelLabel,\n disableDeviceFallback: opts.fallbackToPasscode === false,\n });\n if (res.success) return { success: true };\n return { success: false, error: (res as any).error || 'unknown' };\n } catch (e: any) {\n return { success: false, error: String(e?.message || e) };\n }\n}\n","/**\n * Device-bridge: Sharing (native share sheet)\n *\n * Wraps expo-sharing. Lets solutions hand content off to the OS share sheet\n * — any installed app can receive it (Messages, WhatsApp, Mail, Files, etc.).\n *\n * Typical use: \"Share this article / calendar invite / photo with a contact.\"\n */\n\nimport * as Sharing from 'expo-sharing';\n\nexport interface ShareOptions {\n /** MIME type, e.g. 'application/pdf'. Optional. */\n mimeType?: string;\n /** iOS UTI, e.g. 'public.image'. Optional. */\n UTI?: string;\n /** Dialog title (Android only). */\n dialogTitle?: string;\n}\n\n/** Share a local file URI. */\nexport async function shareFile(fileUri: string, opts: ShareOptions = {}): Promise<{ ok: boolean; error?: string }> {\n try {\n const available = await Sharing.isAvailableAsync();\n if (!available) return { ok: false, error: 'sharing_unavailable' };\n await Sharing.shareAsync(fileUri, opts);\n return { ok: true };\n } catch (e: any) {\n return { ok: false, error: String(e?.message || e) };\n }\n}\n\nexport async function isAvailable(): Promise<boolean> {\n return Sharing.isAvailableAsync();\n}\n","/**\n * Device-bridge: Scanner (QR / barcode)\n *\n * Wraps expo-camera (which replaced the deprecated expo-barcode-scanner\n * in Expo SDK 50+). The CameraView component has built-in barcode scanning.\n *\n * Use cases:\n * - Wi-Fi QR handoff\n * - OAuth / pairing codes\n * - Payment QR codes\n * - Product lookup\n *\n * Plugins mount <CameraView onBarcodeScanned={...} /> directly. This module\n * exposes the permission helper + a result normalizer so plugins don't need\n * to import expo-camera directly.\n */\n\nimport { CameraView, useCameraPermissions, type BarcodeScanningResult } from 'expo-camera';\n\nexport interface ScanResult {\n type: string; // e.g. 'qr', 'ean13', 'code128'\n data: string; // decoded content\n}\n\n/** Request camera permission if not already granted. */\nexport async function requestPermissions(): Promise<{ granted: boolean; status: string }> {\n // useCameraPermissions is a hook; for the non-hook flow plugins should use\n // Camera.requestCameraPermissionsAsync. But it's easier to expose the hook\n // helper — plugins typically use the hook form inside their Component.\n // For service-style callers, fall back to the imperative API:\n const { Camera } = await import('expo-camera');\n const { status } = await Camera.requestCameraPermissionsAsync();\n return { granted: status === 'granted', status };\n}\n\n/** Normalize a CameraView barcode result to a stable shape. */\nexport function normalizeResult(r: BarcodeScanningResult): ScanResult {\n return { type: r.type, data: r.data };\n}\n\n/** Re-export the component + hook so plugins consume them via device-bridge. */\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OAAO;AACvC,UAAI,CAAC,GAAG;AACN,cAAM,IAAI;AAAA,UACR;AAAA,UACA,oBAAoB,OAAO;AAAA,QAE7B;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAeO,SAAS,qBAAqB,QAA6C;AAChF,QAAM,eAAe,sBAAsB,QAAQ,eAAe;AAClE,SAAO;AAAA,IACL,QAAQ,gBAAgB;AAAA,IACxB,UAAU,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAM5B,YAAY,CAAC,aAAqB,iBAAiB,QAAQ;AAAA,IAC3D,YAAY,QAAuB,YAAY;AAAA,IAC/C,cAAc,sBAAsB;AAAA,IACpC,eAAe,uBAAuB;AAAA,IACtC,SAAS,iBAAiB;AAAA,IAC1B;AAAA,IACA,eAAe,CAAC,aAAqB,oBAAoB,QAAQ;AAAA,IACjE,SAAS,iBAAiB;AAAA,IAC1B,SAAS,iBAAiB;AAAA,IAC1B,SAAS,iBAAiB;AAAA,IAC1B,KAAK,aAAa;AAAA,IAClB,WAAW,mBAAmB;AAAA,IAC9B,QAAQ,gBAAgB;AAAA,EAC1B;AACF;","names":["CookieManager","isSupported","NfcManager","ExpoLocation","import_async_storage","import_react_native","ExpoCalendar","import_react_native","import_async_storage","import_expo_camera","Camera","AsyncStorage"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import {
|
|
2
|
+
clearAllPluginData,
|
|
3
|
+
createDeviceProvider
|
|
4
|
+
} from "../chunk-5HM6UA2K.mjs";
|
|
5
|
+
import "../chunk-TZXWVYYR.mjs";
|
|
6
|
+
import "../chunk-6LXF3JVX.mjs";
|
|
7
|
+
import "../chunk-FF6ZZZXH.mjs";
|
|
8
|
+
import "../chunk-VQJPSLHP.mjs";
|
|
9
|
+
import "../chunk-KOXF2FZM.mjs";
|
|
10
|
+
import "../chunk-XQSY6MHP.mjs";
|
|
11
|
+
import "../chunk-4BMWVN25.mjs";
|
|
12
|
+
import "../chunk-WMJKH4XE.mjs";
|
|
13
|
+
export {
|
|
14
|
+
clearAllPluginData,
|
|
15
|
+
createDeviceProvider
|
|
16
|
+
};
|
|
17
|
+
//# sourceMappingURL=createDeviceProvider.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Attach the AppState listener. Idempotent; call once at app boot. */
|
|
2
|
+
declare function start(): Promise<void>;
|
|
3
|
+
declare function stop(): void;
|
|
4
|
+
/** Current day's tallies for the mood summary. */
|
|
5
|
+
declare function getToday(): Promise<{
|
|
6
|
+
app_sessions: number | null;
|
|
7
|
+
app_active_min: number | null;
|
|
8
|
+
}>;
|
|
9
|
+
|
|
10
|
+
export { getToday, start, stop };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Attach the AppState listener. Idempotent; call once at app boot. */
|
|
2
|
+
declare function start(): Promise<void>;
|
|
3
|
+
declare function stop(): void;
|
|
4
|
+
/** Current day's tallies for the mood summary. */
|
|
5
|
+
declare function getToday(): Promise<{
|
|
6
|
+
app_sessions: number | null;
|
|
7
|
+
app_active_min: number | null;
|
|
8
|
+
}>;
|
|
9
|
+
|
|
10
|
+
export { getToday, start, stop };
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/device-bridge/collectors/appEngagement.ts
|
|
31
|
+
var appEngagement_exports = {};
|
|
32
|
+
__export(appEngagement_exports, {
|
|
33
|
+
getToday: () => getToday,
|
|
34
|
+
start: () => start,
|
|
35
|
+
stop: () => stop
|
|
36
|
+
});
|
|
37
|
+
module.exports = __toCommonJS(appEngagement_exports);
|
|
38
|
+
var import_react_native = require("react-native");
|
|
39
|
+
var import_async_storage = __toESM(require("@react-native-async-storage/async-storage"));
|
|
40
|
+
var KEY = "ateam.appEngagement.v1";
|
|
41
|
+
var _tally = null;
|
|
42
|
+
var _foregroundSince = null;
|
|
43
|
+
var _started = false;
|
|
44
|
+
var _sub = null;
|
|
45
|
+
function todayKey() {
|
|
46
|
+
const d = /* @__PURE__ */ new Date();
|
|
47
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
48
|
+
}
|
|
49
|
+
function fresh() {
|
|
50
|
+
return { date: todayKey(), sessions: 0, activeMs: 0 };
|
|
51
|
+
}
|
|
52
|
+
async function load() {
|
|
53
|
+
try {
|
|
54
|
+
const raw = await import_async_storage.default.getItem(KEY);
|
|
55
|
+
if (raw) {
|
|
56
|
+
const parsed = JSON.parse(raw);
|
|
57
|
+
_tally = parsed?.date === todayKey() ? parsed : fresh();
|
|
58
|
+
} else {
|
|
59
|
+
_tally = fresh();
|
|
60
|
+
}
|
|
61
|
+
} catch {
|
|
62
|
+
_tally = fresh();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function persist() {
|
|
66
|
+
if (_tally) import_async_storage.default.setItem(KEY, JSON.stringify(_tally)).catch(() => {
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
function rollIfNewDay() {
|
|
70
|
+
if (!_tally || _tally.date !== todayKey()) {
|
|
71
|
+
_tally = fresh();
|
|
72
|
+
persist();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function flushForeground() {
|
|
76
|
+
if (_foregroundSince == null || !_tally) return;
|
|
77
|
+
const now = Date.now();
|
|
78
|
+
const delta = now - _foregroundSince;
|
|
79
|
+
if (delta > 0) _tally.activeMs += delta;
|
|
80
|
+
_foregroundSince = now;
|
|
81
|
+
}
|
|
82
|
+
function onChange(state) {
|
|
83
|
+
rollIfNewDay();
|
|
84
|
+
if (state === "active") {
|
|
85
|
+
if (_tally) _tally.sessions += 1;
|
|
86
|
+
_foregroundSince = Date.now();
|
|
87
|
+
persist();
|
|
88
|
+
} else {
|
|
89
|
+
flushForeground();
|
|
90
|
+
_foregroundSince = null;
|
|
91
|
+
persist();
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async function start() {
|
|
95
|
+
if (_started) return;
|
|
96
|
+
_started = true;
|
|
97
|
+
await load();
|
|
98
|
+
rollIfNewDay();
|
|
99
|
+
if (_tally) _tally.sessions += 1;
|
|
100
|
+
_foregroundSince = Date.now();
|
|
101
|
+
persist();
|
|
102
|
+
_sub = import_react_native.AppState.addEventListener("change", onChange);
|
|
103
|
+
}
|
|
104
|
+
function stop() {
|
|
105
|
+
flushForeground();
|
|
106
|
+
persist();
|
|
107
|
+
_sub?.remove();
|
|
108
|
+
_sub = null;
|
|
109
|
+
_started = false;
|
|
110
|
+
}
|
|
111
|
+
async function getToday() {
|
|
112
|
+
if (!_tally) await load();
|
|
113
|
+
rollIfNewDay();
|
|
114
|
+
flushForeground();
|
|
115
|
+
persist();
|
|
116
|
+
if (!_tally) return { app_sessions: null, app_active_min: null };
|
|
117
|
+
return {
|
|
118
|
+
app_sessions: _tally.sessions,
|
|
119
|
+
app_active_min: Math.round(_tally.activeMs / 6e4)
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
123
|
+
0 && (module.exports = {
|
|
124
|
+
getToday,
|
|
125
|
+
start,
|
|
126
|
+
stop
|
|
127
|
+
});
|
|
128
|
+
//# sourceMappingURL=appEngagement.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/device-bridge/collectors/appEngagement.ts"],"sourcesContent":["/**\n * App Engagement Collector — our OWN usage analytics (no OS permission, fully\n * available on every platform). Feeds the mood summary's app_sessions +\n * app_active_min, which iOS otherwise blocks for third-party apps.\n *\n * app_sessions — count of foreground sessions today (a background→active\n * transition, or a cold start, starts a session).\n * app_active_min — total minutes the app was in the foreground today.\n *\n * Counters are kept per local day and persisted to AsyncStorage so they\n * survive relaunches. start() must be called once at app boot to attach the\n * AppState listener; getToday() returns the current day's tallies.\n */\nimport { AppState, type AppStateStatus } from 'react-native';\nimport AsyncStorage from '@react-native-async-storage/async-storage';\n\nconst KEY = 'ateam.appEngagement.v1';\n\ninterface DayTally {\n date: string; // local YYYY-MM-DD\n sessions: number;\n activeMs: number;\n}\n\nlet _tally: DayTally | null = null;\nlet _foregroundSince: number | null = null;\nlet _started = false;\nlet _sub: { remove: () => void } | null = null;\n\nfunction todayKey(): string {\n const d = new Date();\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;\n}\n\nfunction fresh(): DayTally {\n return { date: todayKey(), sessions: 0, activeMs: 0 };\n}\n\nasync function load(): Promise<void> {\n try {\n const raw = await AsyncStorage.getItem(KEY);\n if (raw) {\n const parsed = JSON.parse(raw) as DayTally;\n _tally = parsed?.date === todayKey() ? parsed : fresh();\n } else {\n _tally = fresh();\n }\n } catch {\n _tally = fresh();\n }\n}\n\nfunction persist(): void {\n if (_tally) AsyncStorage.setItem(KEY, JSON.stringify(_tally)).catch(() => {});\n}\n\nfunction rollIfNewDay(): void {\n if (!_tally || _tally.date !== todayKey()) {\n _tally = fresh();\n persist();\n }\n}\n\n/** Fold the time spent foregrounded since the last checkpoint into activeMs. */\nfunction flushForeground(): void {\n if (_foregroundSince == null || !_tally) return;\n const now = Date.now();\n const delta = now - _foregroundSince;\n if (delta > 0) _tally.activeMs += delta;\n _foregroundSince = now;\n}\n\nfunction onChange(state: AppStateStatus): void {\n rollIfNewDay();\n if (state === 'active') {\n // New foreground session.\n if (_tally) _tally.sessions += 1;\n _foregroundSince = Date.now();\n persist();\n } else {\n // Leaving foreground — bank the elapsed active time.\n flushForeground();\n _foregroundSince = null;\n persist();\n }\n}\n\n/** Attach the AppState listener. Idempotent; call once at app boot. */\nexport async function start(): Promise<void> {\n if (_started) return;\n _started = true;\n await load();\n // Count the launch itself as the first active session.\n rollIfNewDay();\n if (_tally) _tally.sessions += 1;\n _foregroundSince = Date.now();\n persist();\n _sub = AppState.addEventListener('change', onChange);\n}\n\nexport function stop(): void {\n flushForeground();\n persist();\n _sub?.remove();\n _sub = null;\n _started = false;\n}\n\n/** Current day's tallies for the mood summary. */\nexport async function getToday(): Promise<{ app_sessions: number | null; app_active_min: number | null }> {\n if (!_tally) await load();\n rollIfNewDay();\n flushForeground(); // include the in-progress foreground stretch\n persist();\n if (!_tally) return { app_sessions: null, app_active_min: null };\n return {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;AACpB,MAAI,QAAQ,EAAG,QAAO,YAAY;AAClC,qBAAmB;AACrB;AAEA,SAAS,SAAS,OAA6B;AAC7C,eAAa;AACb,MAAI,UAAU,UAAU;AAEtB,QAAI,OAAQ,QAAO,YAAY;AAC/B,uBAAmB,KAAK,IAAI;AAC5B,YAAQ;AAAA,EACV,OAAO;AAEL,oBAAgB;AAChB,uBAAmB;AACnB,YAAQ;AAAA,EACV;AACF;AAGA,eAAsB,QAAuB;AAC3C,MAAI,SAAU;AACd,aAAW;AACX,QAAM,KAAK;AAEX,eAAa;AACb,MAAI,OAAQ,QAAO,YAAY;AAC/B,qBAAmB,KAAK,IAAI;AAC5B,UAAQ;AACR,SAAO,6BAAS,iBAAiB,UAAU,QAAQ;AACrD;AAEO,SAAS,OAAa;AAC3B,kBAAgB;AAChB,UAAQ;AACR,QAAM,OAAO;AACb,SAAO;AACP,aAAW;AACb;AAGA,eAAsB,WAAoF;AACxG,MAAI,CAAC,OAAQ,OAAM,KAAK;AACxB,eAAa;AACb,kBAAgB;AAChB,UAAQ;AACR,MAAI,CAAC,OAAQ,QAAO,EAAE,cAAc,MAAM,gBAAgB,KAAK;AAC/D,SAAO;AAAA,IACL,cAAc,OAAO;AAAA,IACrB,gBAAgB,KAAK,MAAM,OAAO,WAAW,GAAK;AAAA,EACpD;AACF;","names":["AsyncStorage"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { H as HealthDayMetrics } from '../../types-BRanJYTn.mjs';
|
|
2
|
+
|
|
3
|
+
declare let lastHealthInitError: string | null;
|
|
4
|
+
declare function hasPermission(): Promise<boolean>;
|
|
5
|
+
declare function requestPermission(): Promise<boolean>;
|
|
6
|
+
/**
|
|
7
|
+
* Mood-relevant HealthKit extras for today: sleep minutes, resting heart rate,
|
|
8
|
+
* active energy (kcal), exercise minutes. Each is null when unavailable so the
|
|
9
|
+
* backend weights only present fields.
|
|
10
|
+
*/
|
|
11
|
+
declare function collectMoodExtras(): Promise<{
|
|
12
|
+
sleep_min: number | null;
|
|
13
|
+
resting_hr: number | null;
|
|
14
|
+
active_energy_kcal: number | null;
|
|
15
|
+
exercise_min: number | null;
|
|
16
|
+
}>;
|
|
17
|
+
declare function collectToday(): Promise<HealthDayMetrics>;
|
|
18
|
+
/**
|
|
19
|
+
* Last `days` days, newest-first. Index 0 is today.
|
|
20
|
+
* Caller passes 1..30 — we clamp defensively.
|
|
21
|
+
*/
|
|
22
|
+
declare function collectHistory(days: number): Promise<HealthDayMetrics[]>;
|
|
23
|
+
|
|
24
|
+
export { collectHistory, collectMoodExtras, collectToday, hasPermission, lastHealthInitError, requestPermission };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { H as HealthDayMetrics } from '../../types-BRanJYTn.js';
|
|
2
|
+
|
|
3
|
+
declare let lastHealthInitError: string | null;
|
|
4
|
+
declare function hasPermission(): Promise<boolean>;
|
|
5
|
+
declare function requestPermission(): Promise<boolean>;
|
|
6
|
+
/**
|
|
7
|
+
* Mood-relevant HealthKit extras for today: sleep minutes, resting heart rate,
|
|
8
|
+
* active energy (kcal), exercise minutes. Each is null when unavailable so the
|
|
9
|
+
* backend weights only present fields.
|
|
10
|
+
*/
|
|
11
|
+
declare function collectMoodExtras(): Promise<{
|
|
12
|
+
sleep_min: number | null;
|
|
13
|
+
resting_hr: number | null;
|
|
14
|
+
active_energy_kcal: number | null;
|
|
15
|
+
exercise_min: number | null;
|
|
16
|
+
}>;
|
|
17
|
+
declare function collectToday(): Promise<HealthDayMetrics>;
|
|
18
|
+
/**
|
|
19
|
+
* Last `days` days, newest-first. Index 0 is today.
|
|
20
|
+
* Caller passes 1..30 — we clamp defensively.
|
|
21
|
+
*/
|
|
22
|
+
declare function collectHistory(days: number): Promise<HealthDayMetrics[]>;
|
|
23
|
+
|
|
24
|
+
export { collectHistory, collectMoodExtras, collectToday, hasPermission, lastHealthInitError, requestPermission };
|