@ateam-ai-mobile/expo 0.1.18 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/bootstrap.d.mts +11 -0
  2. package/dist/bootstrap.d.ts +11 -0
  3. package/dist/bootstrap.js +12 -2
  4. package/dist/bootstrap.js.map +1 -1
  5. package/dist/bootstrap.mjs +12 -5
  6. package/dist/bootstrap.mjs.map +1 -1
  7. package/dist/capabilities/index.d.mts +112 -0
  8. package/dist/capabilities/index.d.ts +112 -0
  9. package/dist/capabilities/index.js +2574 -0
  10. package/dist/capabilities/index.js.map +1 -0
  11. package/dist/capabilities/index.mjs +608 -0
  12. package/dist/capabilities/index.mjs.map +1 -0
  13. package/dist/chunk-DE6Y4VRI.mjs +14 -0
  14. package/dist/chunk-DE6Y4VRI.mjs.map +1 -0
  15. package/dist/chunk-IJPR5ITF.mjs +19 -0
  16. package/dist/chunk-IJPR5ITF.mjs.map +1 -0
  17. package/dist/{chunk-DLDG77DX.mjs → chunk-Z3P7RUCC.mjs} +5 -5
  18. package/dist/device/createDeviceProvider.mjs +2 -2
  19. package/dist/device-bridge/collectors/health.d.mts +1 -1
  20. package/dist/device-bridge/collectors/health.d.ts +1 -1
  21. package/dist/device-bridge/deviceId.d.mts +23 -0
  22. package/dist/device-bridge/deviceId.d.ts +23 -0
  23. package/dist/device-bridge/deviceId.js +45 -0
  24. package/dist/device-bridge/deviceId.js.map +1 -0
  25. package/dist/device-bridge/deviceId.mjs +12 -0
  26. package/dist/device-bridge/deviceId.mjs.map +1 -0
  27. package/dist/device-bridge/index.d.mts +2 -2
  28. package/dist/device-bridge/index.d.ts +2 -2
  29. package/dist/{types-BRanJYTn.d.mts → types-DFsbxj1m.d.mts} +1 -1
  30. package/dist/{types-BRanJYTn.d.ts → types-DFsbxj1m.d.ts} +1 -1
  31. package/package.json +11 -4
  32. package/src/bootstrap.ts +19 -0
  33. package/src/capabilities/CapabilitiesSetup.tsx +239 -0
  34. package/src/capabilities/CapabilityCard.tsx +188 -0
  35. package/src/capabilities/config.ts +31 -0
  36. package/src/capabilities/index.ts +22 -0
  37. package/src/capabilities/store.ts +387 -0
  38. package/src/device-bridge/deviceId.ts +33 -0
  39. package/src/device-bridge/plugin.ts +1 -1
  40. /package/dist/{chunk-DLDG77DX.mjs.map → chunk-Z3P7RUCC.mjs.map} +0 -0
@@ -0,0 +1,2574 @@
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/capabilities/index.ts
31
+ var capabilities_exports2 = {};
32
+ __export(capabilities_exports2, {
33
+ CapabilitiesSetup: () => CapabilitiesSetup,
34
+ CapabilityCard: () => CapabilityCard,
35
+ configureDeviceSync: () => configureDeviceSync,
36
+ useCapabilitiesStore: () => useCapabilitiesStore
37
+ });
38
+ module.exports = __toCommonJS(capabilities_exports2);
39
+
40
+ // src/capabilities/store.ts
41
+ var import_zustand = require("zustand");
42
+ var import_async_storage3 = __toESM(require("@react-native-async-storage/async-storage"));
43
+ var import_core = require("@ateam-ai-mobile/core");
44
+
45
+ // src/device-bridge/relay-client.ts
46
+ var RelayClient = class {
47
+ constructor(config2) {
48
+ this.offlineQueue = [];
49
+ this.baseUrl = config2.relayUrl.replace(/\/$/, "");
50
+ this.deviceId = config2.deviceId;
51
+ this.tenant = config2.tenant;
52
+ this.actorId = config2.actorId ?? "default";
53
+ this.apiKey = config2.apiKey ?? "";
54
+ this.timeout = config2.timeout ?? 1e4;
55
+ }
56
+ // ─── Data Sync ───
57
+ /**
58
+ * Push a full device data bundle to the relay.
59
+ * If offline, buffers the bundle and retries on next sync.
60
+ */
61
+ async pushData(bundle) {
62
+ try {
63
+ const response = await this.fetch(
64
+ `/api/device/${this.deviceId}/sync`,
65
+ {
66
+ method: "POST",
67
+ body: JSON.stringify(bundle)
68
+ }
69
+ );
70
+ if (response.ok) {
71
+ await this.flushOfflineQueue();
72
+ return { ok: true };
73
+ }
74
+ return {
75
+ ok: false,
76
+ error: `Relay returned ${response.status}: ${await response.text()}`
77
+ };
78
+ } catch (error) {
79
+ this.offlineQueue.push(bundle);
80
+ return {
81
+ ok: false,
82
+ error: `Offline \u2014 buffered (${this.offlineQueue.length} pending)`
83
+ };
84
+ }
85
+ }
86
+ /**
87
+ * Push a single domain update (partial sync).
88
+ */
89
+ async pushDomain(domain, data) {
90
+ try {
91
+ const response = await this.fetch(
92
+ `/api/device/${this.deviceId}/sync/${domain}`,
93
+ {
94
+ method: "POST",
95
+ body: JSON.stringify({ domain, data, timestamp: (/* @__PURE__ */ new Date()).toISOString(), actorId: this.actorId })
96
+ }
97
+ );
98
+ if (response.ok) return { ok: true };
99
+ return {
100
+ ok: false,
101
+ error: `Relay returned ${response.status}`
102
+ };
103
+ } catch (error) {
104
+ return { ok: false, error: "Network error \u2014 domain sync failed" };
105
+ }
106
+ }
107
+ // ─── Action Queue ───
108
+ /**
109
+ * Poll for pending actions the phone needs to execute.
110
+ */
111
+ async pollActions() {
112
+ try {
113
+ const response = await this.fetch(
114
+ `/api/device/${this.deviceId}/actions`,
115
+ { method: "GET" }
116
+ );
117
+ if (response.ok) {
118
+ const data = await response.json();
119
+ return { ok: true, data: data.actions ?? [] };
120
+ }
121
+ return { ok: false, error: `Relay returned ${response.status}` };
122
+ } catch (error) {
123
+ return { ok: false, error: "Network error \u2014 action poll failed" };
124
+ }
125
+ }
126
+ /**
127
+ * Report action execution result and remove from queue.
128
+ */
129
+ async completeAction(result) {
130
+ try {
131
+ const response = await this.fetch(
132
+ `/api/device/${this.deviceId}/actions/${result.id}`,
133
+ {
134
+ method: "DELETE",
135
+ body: JSON.stringify(result)
136
+ }
137
+ );
138
+ if (response.ok) return { ok: true };
139
+ return { ok: false, error: `Relay returned ${response.status}` };
140
+ } catch (error) {
141
+ return { ok: false, error: "Network error \u2014 action complete failed" };
142
+ }
143
+ }
144
+ // ─── Health ───
145
+ /**
146
+ * Ping the relay to check connectivity.
147
+ */
148
+ async ping() {
149
+ try {
150
+ const response = await this.fetch(
151
+ `/api/health`,
152
+ { method: "GET" },
153
+ 3e3
154
+ // short timeout for health check
155
+ );
156
+ return response.ok;
157
+ } catch {
158
+ return false;
159
+ }
160
+ }
161
+ /**
162
+ * Get count of buffered offline bundles.
163
+ */
164
+ getOfflineQueueSize() {
165
+ return this.offlineQueue.length;
166
+ }
167
+ // ─── Internal ───
168
+ async fetch(path, init, timeout) {
169
+ const controller = new AbortController();
170
+ const timer = setTimeout(
171
+ () => controller.abort(),
172
+ timeout ?? this.timeout
173
+ );
174
+ try {
175
+ return await fetch(`${this.baseUrl}${path}`, {
176
+ ...init,
177
+ signal: controller.signal,
178
+ headers: {
179
+ "Content-Type": "application/json",
180
+ "X-ADAS-TENANT": this.tenant,
181
+ "X-ADAS-ACTOR": this.actorId,
182
+ "X-Device-Id": this.deviceId,
183
+ // The relay (post-2026-04-25) gates every /api/device/* call on
184
+ // a shared secret. Send it as `Authorization: Bearer` so the
185
+ // server's relayAuth middleware accepts the request. Empty/missing
186
+ // secret = 401 from the relay (correct fail-closed behavior).
187
+ ...this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {},
188
+ ...init.headers || {}
189
+ }
190
+ });
191
+ } finally {
192
+ clearTimeout(timer);
193
+ }
194
+ }
195
+ async flushOfflineQueue() {
196
+ if (this.offlineQueue.length === 0) return;
197
+ const queue = [...this.offlineQueue];
198
+ this.offlineQueue = [];
199
+ for (const bundle of queue) {
200
+ try {
201
+ const response = await this.fetch(
202
+ `/api/device/${this.deviceId}/sync`,
203
+ {
204
+ method: "POST",
205
+ body: JSON.stringify(bundle)
206
+ }
207
+ );
208
+ if (!response.ok) {
209
+ this.offlineQueue.push(bundle);
210
+ }
211
+ } catch {
212
+ this.offlineQueue.push(bundle);
213
+ break;
214
+ }
215
+ }
216
+ }
217
+ };
218
+
219
+ // src/device-bridge/actions/messaging.ts
220
+ var SMS = __toESM(require("expo-sms"));
221
+ async function execute(actionId, params) {
222
+ const phone = params.phone;
223
+ const message = params.message;
224
+ if (!phone || !message) {
225
+ return {
226
+ id: actionId,
227
+ ok: false,
228
+ error: "Missing phone or message parameter",
229
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
230
+ };
231
+ }
232
+ try {
233
+ const available = await SMS.isAvailableAsync();
234
+ if (!available) {
235
+ return {
236
+ id: actionId,
237
+ ok: false,
238
+ error: "SMS not available on this device",
239
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
240
+ };
241
+ }
242
+ const { result } = await SMS.sendSMSAsync([phone], message);
243
+ return {
244
+ id: actionId,
245
+ ok: result === "sent" || result === "unknown",
246
+ // 'unknown' on Android means it was sent
247
+ result: {
248
+ to: params.contact_name || phone,
249
+ phone,
250
+ message,
251
+ status: result,
252
+ sent_at: (/* @__PURE__ */ new Date()).toISOString()
253
+ },
254
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
255
+ };
256
+ } catch (error) {
257
+ return {
258
+ id: actionId,
259
+ ok: false,
260
+ error: `SMS send failed: ${error instanceof Error ? error.message : String(error)}`,
261
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
262
+ };
263
+ }
264
+ }
265
+
266
+ // src/device-bridge/actions/calendar-actions.ts
267
+ var ExpoCalendar = __toESM(require("expo-calendar"));
268
+ async function getDefaultCalendarId() {
269
+ const calendars = await ExpoCalendar.getCalendarsAsync(ExpoCalendar.EntityTypes.EVENT);
270
+ const defaultCal = calendars.find((c) => c.isPrimary) || calendars[0];
271
+ return defaultCal?.id || null;
272
+ }
273
+ async function executeCreate(actionId, params) {
274
+ const title = params.title;
275
+ const date = params.date;
276
+ const startTime = params.start_time;
277
+ const endTime = params.end_time;
278
+ if (!title || !date || !startTime) {
279
+ return {
280
+ id: actionId,
281
+ ok: false,
282
+ error: "Missing title, date, or start_time",
283
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
284
+ };
285
+ }
286
+ try {
287
+ const calendarId = await getDefaultCalendarId();
288
+ if (!calendarId) {
289
+ return {
290
+ id: actionId,
291
+ ok: false,
292
+ error: "No calendar found on device",
293
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
294
+ };
295
+ }
296
+ const [year, month, day] = date.split("-").map(Number);
297
+ const [startH, startM] = startTime.split(":").map(Number);
298
+ const startDate = new Date(year, month - 1, day, startH, startM);
299
+ let endDate;
300
+ if (endTime) {
301
+ const [endH, endM] = endTime.split(":").map(Number);
302
+ endDate = new Date(year, month - 1, day, endH, endM);
303
+ } else {
304
+ endDate = new Date(startDate.getTime() + 60 * 60 * 1e3);
305
+ }
306
+ const eventId = await ExpoCalendar.createEventAsync(calendarId, {
307
+ title,
308
+ startDate,
309
+ endDate,
310
+ location: params.location || void 0,
311
+ notes: params.notes || void 0,
312
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
313
+ });
314
+ return {
315
+ id: actionId,
316
+ ok: true,
317
+ result: {
318
+ event_id: eventId,
319
+ title,
320
+ date,
321
+ start: startTime,
322
+ end: endTime || formatTime(endDate),
323
+ message: `Event "${title}" created successfully`
324
+ },
325
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
326
+ };
327
+ } catch (error) {
328
+ return {
329
+ id: actionId,
330
+ ok: false,
331
+ error: `Calendar create failed: ${error instanceof Error ? error.message : String(error)}`,
332
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
333
+ };
334
+ }
335
+ }
336
+ async function executeReschedule(actionId, params) {
337
+ const eventId = params.event_id;
338
+ if (!eventId) {
339
+ return {
340
+ id: actionId,
341
+ ok: false,
342
+ error: "Missing event_id",
343
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
344
+ };
345
+ }
346
+ try {
347
+ const updates = {};
348
+ if (params.new_date && params.new_start_time) {
349
+ const [year, month, day] = params.new_date.split("-").map(Number);
350
+ const [h, m] = params.new_start_time.split(":").map(Number);
351
+ updates.startDate = new Date(year, month - 1, day, h, m);
352
+ if (params.new_end_time) {
353
+ const [eh, em] = params.new_end_time.split(":").map(Number);
354
+ updates.endDate = new Date(year, month - 1, day, eh, em);
355
+ } else {
356
+ updates.endDate = new Date(updates.startDate.getTime() + 60 * 60 * 1e3);
357
+ }
358
+ }
359
+ await ExpoCalendar.updateEventAsync(eventId, updates);
360
+ return {
361
+ id: actionId,
362
+ ok: true,
363
+ result: { event_id: eventId, message: "Event rescheduled successfully" },
364
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
365
+ };
366
+ } catch (error) {
367
+ return {
368
+ id: actionId,
369
+ ok: false,
370
+ error: `Calendar reschedule failed: ${error instanceof Error ? error.message : String(error)}`,
371
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
372
+ };
373
+ }
374
+ }
375
+ async function executeCancel(actionId, params) {
376
+ const eventId = params.event_id;
377
+ if (!eventId) {
378
+ return {
379
+ id: actionId,
380
+ ok: false,
381
+ error: "Missing event_id",
382
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
383
+ };
384
+ }
385
+ try {
386
+ await ExpoCalendar.deleteEventAsync(eventId);
387
+ return {
388
+ id: actionId,
389
+ ok: true,
390
+ result: { event_id: eventId, message: "Event cancelled successfully" },
391
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
392
+ };
393
+ } catch (error) {
394
+ return {
395
+ id: actionId,
396
+ ok: false,
397
+ error: `Calendar cancel failed: ${error instanceof Error ? error.message : String(error)}`,
398
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
399
+ };
400
+ }
401
+ }
402
+ function formatTime(date) {
403
+ return date.toLocaleTimeString("en-US", {
404
+ hour: "2-digit",
405
+ minute: "2-digit",
406
+ hour12: false
407
+ });
408
+ }
409
+
410
+ // src/device-bridge/actions/dnd.ts
411
+ var currentDndState = {
412
+ enabled: false,
413
+ schedule: { start: "22:00", end: "07:00" },
414
+ allowlist: []
415
+ };
416
+ async function execute2(actionId, params) {
417
+ try {
418
+ if (params.enabled !== void 0) {
419
+ currentDndState.enabled = params.enabled;
420
+ }
421
+ if (params.schedule_start) {
422
+ currentDndState.schedule.start = params.schedule_start;
423
+ }
424
+ if (params.schedule_end) {
425
+ currentDndState.schedule.end = params.schedule_end;
426
+ }
427
+ if (params.allowlist) {
428
+ currentDndState.allowlist = params.allowlist;
429
+ }
430
+ return {
431
+ id: actionId,
432
+ ok: true,
433
+ result: {
434
+ message: `DND ${currentDndState.enabled ? "enabled" : "disabled"}`,
435
+ dnd: currentDndState
436
+ },
437
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
438
+ };
439
+ } catch (error) {
440
+ return {
441
+ id: actionId,
442
+ ok: false,
443
+ error: `DND set failed: ${error instanceof Error ? error.message : String(error)}`,
444
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
445
+ };
446
+ }
447
+ }
448
+
449
+ // src/device-bridge/actions/navigation.ts
450
+ var Linking = __toESM(require("expo-linking"));
451
+ var import_react_native = require("react-native");
452
+ async function execute3(actionId, params) {
453
+ const destination = params.destination;
454
+ const mode = params.mode || "driving";
455
+ if (!destination) {
456
+ return {
457
+ id: actionId,
458
+ ok: false,
459
+ error: "Missing destination parameter",
460
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
461
+ };
462
+ }
463
+ try {
464
+ const encodedDest = encodeURIComponent(destination);
465
+ let url;
466
+ if (import_react_native.Platform.OS === "ios") {
467
+ const modeMap = {
468
+ driving: "d",
469
+ transit: "r",
470
+ walking: "w"
471
+ };
472
+ url = `maps://maps.apple.com/?daddr=${encodedDest}&dirflg=${modeMap[mode] || "d"}`;
473
+ } else {
474
+ const modeMap = {
475
+ driving: "driving",
476
+ transit: "transit",
477
+ walking: "walking"
478
+ };
479
+ url = `google.navigation:q=${encodedDest}&mode=${modeMap[mode] || "driving"}`;
480
+ }
481
+ const canOpen = await Linking.canOpenURL(url);
482
+ if (!canOpen) {
483
+ const webModeMap = {
484
+ driving: "driving",
485
+ transit: "transit",
486
+ walking: "walking"
487
+ };
488
+ url = `https://www.google.com/maps/dir/?api=1&destination=${encodedDest}&travelmode=${webModeMap[mode] || "driving"}`;
489
+ }
490
+ await Linking.openURL(url);
491
+ return {
492
+ id: actionId,
493
+ ok: true,
494
+ result: {
495
+ message: `Navigation started to ${destination} via ${mode}`,
496
+ destination,
497
+ mode,
498
+ status: "navigating"
499
+ },
500
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
501
+ };
502
+ } catch (error) {
503
+ return {
504
+ id: actionId,
505
+ ok: false,
506
+ error: `Navigation failed: ${error instanceof Error ? error.message : String(error)}`,
507
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
508
+ };
509
+ }
510
+ }
511
+
512
+ // src/device-bridge/collectors/health.ts
513
+ var import_react_native2 = require("react-native");
514
+ var _HK = null;
515
+ var _hkProbed = false;
516
+ function getHK() {
517
+ if (import_react_native2.Platform.OS !== "ios") return null;
518
+ if (_hkProbed) return _HK;
519
+ _hkProbed = true;
520
+ try {
521
+ const mod = require("@kingstinct/react-native-healthkit");
522
+ if (mod && typeof mod.requestAuthorization === "function") {
523
+ _HK = mod;
524
+ } else {
525
+ console.warn("[health] @kingstinct/react-native-healthkit native bridge unavailable \u2014 HealthKit disabled (Expo Go?)");
526
+ }
527
+ } catch (e) {
528
+ console.warn("[health] @kingstinct/react-native-healthkit require failed:", e);
529
+ }
530
+ return _HK;
531
+ }
532
+ var lastHealthInitError = null;
533
+ var READ_TYPES = [
534
+ "HKQuantityTypeIdentifierStepCount",
535
+ "HKQuantityTypeIdentifierFlightsClimbed",
536
+ "HKQuantityTypeIdentifierActiveEnergyBurned",
537
+ "HKQuantityTypeIdentifierDistanceWalkingRunning",
538
+ // Added for mood signals — all read-only, covered by the same auth sheet.
539
+ "HKQuantityTypeIdentifierRestingHeartRate",
540
+ "HKQuantityTypeIdentifierAppleExerciseTime",
541
+ "HKCategoryTypeIdentifierSleepAnalysis"
542
+ ];
543
+ var _initPromise = null;
544
+ async function ensureInit() {
545
+ const HK = getHK();
546
+ if (!HK) {
547
+ lastHealthInitError = "@kingstinct/react-native-healthkit native module not loaded";
548
+ return false;
549
+ }
550
+ if (_initPromise) return _initPromise;
551
+ _initPromise = (async () => {
552
+ try {
553
+ await HK.requestAuthorization({ toRead: READ_TYPES, toWrite: [] });
554
+ lastHealthInitError = null;
555
+ return true;
556
+ } catch (e) {
557
+ lastHealthInitError = `requestAuthorization threw: ${e?.message || String(e)}`;
558
+ console.warn("[health]", lastHealthInitError);
559
+ _initPromise = null;
560
+ return false;
561
+ }
562
+ })();
563
+ return _initPromise;
564
+ }
565
+ async function hasPermission() {
566
+ return ensureInit();
567
+ }
568
+ async function requestPermission() {
569
+ return ensureInit();
570
+ }
571
+ function startOfDay(d) {
572
+ const out = new Date(d);
573
+ out.setHours(0, 0, 0, 0);
574
+ return out;
575
+ }
576
+ function dateKey(d) {
577
+ const y = d.getFullYear();
578
+ const m = String(d.getMonth() + 1).padStart(2, "0");
579
+ const day = String(d.getDate()).padStart(2, "0");
580
+ return `${y}-${m}-${day}`;
581
+ }
582
+ async function readDailySum(identifier, unit, start, end) {
583
+ const HK = getHK();
584
+ if (!HK?.queryStatisticsForQuantity) return 0;
585
+ try {
586
+ const result = await HK.queryStatisticsForQuantity(
587
+ identifier,
588
+ ["cumulativeSum"],
589
+ {
590
+ unit,
591
+ filter: { date: { startDate: start, endDate: end } }
592
+ }
593
+ );
594
+ const q = result?.sumQuantity?.quantity;
595
+ return typeof q === "number" ? q : 0;
596
+ } catch {
597
+ return 0;
598
+ }
599
+ }
600
+ async function readDailyAverage(identifier, unit, start, end) {
601
+ const HK = getHK();
602
+ if (!HK?.queryStatisticsForQuantity) return null;
603
+ try {
604
+ const result = await HK.queryStatisticsForQuantity(
605
+ identifier,
606
+ ["discreteAverage"],
607
+ { unit, filter: { date: { startDate: start, endDate: end } } }
608
+ );
609
+ const q = result?.averageQuantity?.quantity;
610
+ return typeof q === "number" ? q : null;
611
+ } catch {
612
+ return null;
613
+ }
614
+ }
615
+ async function readSleepMinutes(start, end) {
616
+ const HK = getHK();
617
+ const query = HK?.queryCategorySamples || HK?.queryCategorySamplesAsync || HK?.querySamples;
618
+ if (!query) return null;
619
+ try {
620
+ const samples = await query.call(
621
+ HK,
622
+ "HKCategoryTypeIdentifierSleepAnalysis",
623
+ { filter: { date: { startDate: start, endDate: end } } }
624
+ );
625
+ if (!Array.isArray(samples) || samples.length === 0) return null;
626
+ let ms = 0;
627
+ for (const s of samples) {
628
+ const v = s?.value;
629
+ const isAsleep = v !== 0 && v !== 2;
630
+ if (!isAsleep) continue;
631
+ const a = new Date(s?.startDate).getTime();
632
+ const b = new Date(s?.endDate).getTime();
633
+ if (Number.isFinite(a) && Number.isFinite(b) && b > a) ms += b - a;
634
+ }
635
+ return ms > 0 ? Math.round(ms / 6e4) : null;
636
+ } catch {
637
+ return null;
638
+ }
639
+ }
640
+ async function collectMoodExtras() {
641
+ const ok = await ensureInit();
642
+ if (!ok) return { sleep_min: null, resting_hr: null, active_energy_kcal: null, exercise_min: null };
643
+ const start = startOfDay(/* @__PURE__ */ new Date());
644
+ const end = new Date(start);
645
+ end.setDate(end.getDate() + 1);
646
+ const sleepStart = new Date(start);
647
+ sleepStart.setHours(sleepStart.getHours() - 6);
648
+ const [sleep_min, resting_hr, energy, exercise] = await Promise.all([
649
+ readSleepMinutes(sleepStart, end),
650
+ readDailyAverage("HKQuantityTypeIdentifierRestingHeartRate", "count/min", start, end),
651
+ readDailySum("HKQuantityTypeIdentifierActiveEnergyBurned", "kcal", start, end),
652
+ readDailySum("HKQuantityTypeIdentifierAppleExerciseTime", "min", start, end)
653
+ ]);
654
+ return {
655
+ sleep_min,
656
+ resting_hr: resting_hr != null ? Math.round(resting_hr) : null,
657
+ active_energy_kcal: energy ? Math.round(energy) : null,
658
+ exercise_min: exercise ? Math.round(exercise) : null
659
+ };
660
+ }
661
+ async function readDay(date) {
662
+ const start = startOfDay(date);
663
+ const end = new Date(start);
664
+ end.setDate(end.getDate() + 1);
665
+ const [steps, floors, energy, distance] = await Promise.all([
666
+ readDailySum("HKQuantityTypeIdentifierStepCount", "count", start, end),
667
+ readDailySum("HKQuantityTypeIdentifierFlightsClimbed", "count", start, end),
668
+ readDailySum("HKQuantityTypeIdentifierActiveEnergyBurned", "kcal", start, end),
669
+ // Ask for kilometers directly so we don't have to convert from meters.
670
+ readDailySum("HKQuantityTypeIdentifierDistanceWalkingRunning", "km", start, end)
671
+ ]);
672
+ return {
673
+ date: dateKey(start),
674
+ available: true,
675
+ steps: Math.round(steps),
676
+ floors: Math.round(floors),
677
+ active_energy_kcal: Math.round(energy),
678
+ distance_km: Math.round(distance * 100) / 100
679
+ };
680
+ }
681
+ function unavailableDay(date) {
682
+ return {
683
+ date: dateKey(date),
684
+ available: false,
685
+ steps: null,
686
+ floors: null,
687
+ active_energy_kcal: null,
688
+ distance_km: null
689
+ };
690
+ }
691
+ async function collectToday() {
692
+ const ok = await ensureInit();
693
+ if (!ok) {
694
+ return unavailableDay(/* @__PURE__ */ new Date());
695
+ }
696
+ return readDay(/* @__PURE__ */ new Date());
697
+ }
698
+ async function collectHistory(days) {
699
+ const n = Math.max(1, Math.min(30, Math.floor(days)));
700
+ const ok = await ensureInit();
701
+ if (!ok) return [];
702
+ const today = startOfDay(/* @__PURE__ */ new Date());
703
+ const out = [];
704
+ for (let i = 0; i < n; i++) {
705
+ const d = new Date(today);
706
+ d.setDate(d.getDate() - i);
707
+ out.push(await readDay(d));
708
+ }
709
+ return out;
710
+ }
711
+
712
+ // src/device-bridge/actions/health-actions.ts
713
+ async function executeToday(actionId) {
714
+ try {
715
+ const today = await collectToday();
716
+ return {
717
+ id: actionId,
718
+ ok: true,
719
+ result: { today },
720
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
721
+ };
722
+ } catch (e) {
723
+ return {
724
+ id: actionId,
725
+ ok: false,
726
+ error: String(e?.message || e),
727
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
728
+ };
729
+ }
730
+ }
731
+ async function executeHistory(actionId, params) {
732
+ try {
733
+ const days = Number(params?.days) || 30;
734
+ const list = await collectHistory(days);
735
+ return {
736
+ id: actionId,
737
+ ok: true,
738
+ result: { days: list },
739
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
740
+ };
741
+ } catch (e) {
742
+ return {
743
+ id: actionId,
744
+ ok: false,
745
+ error: String(e?.message || e),
746
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
747
+ };
748
+ }
749
+ }
750
+
751
+ // src/device-bridge/actions/queue-poller.ts
752
+ var QueuePoller = class {
753
+ constructor(config2) {
754
+ this.timer = null;
755
+ this.running = false;
756
+ this.relayClient = config2.relayClient;
757
+ this.pollInterval = config2.pollInterval ?? 5e3;
758
+ this.onActionExecuted = config2.onActionExecuted;
759
+ this.onError = config2.onError;
760
+ }
761
+ /**
762
+ * Start polling for actions.
763
+ */
764
+ start() {
765
+ if (this.running) return;
766
+ this.running = true;
767
+ this.poll();
768
+ this.timer = setInterval(() => this.poll(), this.pollInterval);
769
+ }
770
+ /**
771
+ * Stop polling.
772
+ */
773
+ stop() {
774
+ this.running = false;
775
+ if (this.timer) {
776
+ clearInterval(this.timer);
777
+ this.timer = null;
778
+ }
779
+ }
780
+ /**
781
+ * Check if poller is running.
782
+ */
783
+ isRunning() {
784
+ return this.running;
785
+ }
786
+ /**
787
+ * Execute a single poll cycle.
788
+ */
789
+ async poll() {
790
+ if (!this.running) return;
791
+ try {
792
+ const response = await this.relayClient.pollActions();
793
+ if (!response.ok || !response.data) return;
794
+ for (const action of response.data) {
795
+ if (action.status && action.status !== "pending") continue;
796
+ const result = await this.executeAction(action);
797
+ await this.relayClient.completeAction(result);
798
+ this.onActionExecuted?.(result);
799
+ }
800
+ } catch (error) {
801
+ this.onError?.(
802
+ error instanceof Error ? error : new Error(String(error))
803
+ );
804
+ }
805
+ }
806
+ /**
807
+ * Route an action to the appropriate executor.
808
+ */
809
+ async executeAction(action) {
810
+ const { id, type, params } = action;
811
+ try {
812
+ switch (type) {
813
+ case "messaging.send":
814
+ return await execute(id, params);
815
+ case "calendar.create":
816
+ return await executeCreate(id, params);
817
+ case "calendar.reschedule":
818
+ return await executeReschedule(id, params);
819
+ case "calendar.cancel":
820
+ return await executeCancel(id, params);
821
+ case "dnd.set":
822
+ return await execute2(id, params);
823
+ case "navigation.start":
824
+ return await execute3(id, params);
825
+ case "health.today":
826
+ return await executeToday(id);
827
+ case "health.history":
828
+ return await executeHistory(id, params);
829
+ default:
830
+ return {
831
+ id,
832
+ ok: false,
833
+ error: `Unknown action type: ${type}`,
834
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
835
+ };
836
+ }
837
+ } catch (error) {
838
+ return {
839
+ id,
840
+ ok: false,
841
+ error: `Action execution failed: ${error instanceof Error ? error.message : String(error)}`,
842
+ executed_at: (/* @__PURE__ */ new Date()).toISOString()
843
+ };
844
+ }
845
+ }
846
+ };
847
+
848
+ // src/device-bridge/background.ts
849
+ var TaskManager = __toESM(require("expo-task-manager"));
850
+ var BackgroundFetch = __toESM(require("expo-background-fetch"));
851
+
852
+ // src/device-bridge/capabilities.ts
853
+ var capabilities_exports = {};
854
+ __export(capabilities_exports, {
855
+ allBuiltIn: () => allBuiltIn,
856
+ batteryCapability: () => batteryCapability,
857
+ calendarCapability: () => calendarCapability,
858
+ cameraCapability: () => cameraCapability,
859
+ connectivityCapability: () => connectivityCapability,
860
+ contactsCapability: () => contactsCapability,
861
+ healthCapability: () => healthCapability,
862
+ locationCapability: () => locationCapability,
863
+ moodCapability: () => moodCapability,
864
+ notificationsCapability: () => notificationsCapability
865
+ });
866
+
867
+ // src/device-bridge/collectors/calendar.ts
868
+ var ExpoCalendar2 = __toESM(require("expo-calendar"));
869
+ async function requestPermission2() {
870
+ const { status } = await ExpoCalendar2.requestCalendarPermissionsAsync();
871
+ return status === "granted";
872
+ }
873
+ async function hasPermission2() {
874
+ const { status } = await ExpoCalendar2.getCalendarPermissionsAsync();
875
+ return status === "granted";
876
+ }
877
+ async function collectToday2() {
878
+ const now = /* @__PURE__ */ new Date();
879
+ const startOfDay2 = new Date(now.getFullYear(), now.getMonth(), now.getDate());
880
+ const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
881
+ const calendars = await ExpoCalendar2.getCalendarsAsync(ExpoCalendar2.EntityTypes.EVENT);
882
+ const userCalendarIds = getUserCalendarIds(calendars);
883
+ const events = await ExpoCalendar2.getEventsAsync(userCalendarIds, startOfDay2, endOfDay);
884
+ const filtered = filterHolidays(events);
885
+ const mapped = filtered.map((e) => ({
886
+ id: e.id,
887
+ title: e.title || "Untitled",
888
+ date: startOfDay2.toISOString().slice(0, 10),
889
+ start: formatTime2(new Date(e.startDate)),
890
+ end: formatTime2(new Date(e.endDate)),
891
+ location: e.location || "",
892
+ attendees: (e.attendees || []).map((a) => a.name || a.email || "Unknown"),
893
+ notes: e.notes || ""
894
+ }));
895
+ mapped.sort((a, b) => a.start.localeCompare(b.start));
896
+ return {
897
+ ok: true,
898
+ date: startOfDay2.toISOString().slice(0, 10),
899
+ day_of_week: now.toLocaleDateString("en-US", { weekday: "long" }),
900
+ event_count: mapped.length,
901
+ events: mapped
902
+ };
903
+ }
904
+ async function collectUpcoming(daysAhead = 3) {
905
+ const now = /* @__PURE__ */ new Date();
906
+ const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
907
+ const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + daysAhead + 1);
908
+ const calendars = await ExpoCalendar2.getCalendarsAsync(ExpoCalendar2.EntityTypes.EVENT);
909
+ const userCalendarIds = getUserCalendarIds(calendars);
910
+ const events = await ExpoCalendar2.getEventsAsync(userCalendarIds, tomorrow, endDate);
911
+ const filtered = filterHolidays(events);
912
+ const mapped = filtered.map((e) => {
913
+ const startDt = new Date(e.startDate);
914
+ return {
915
+ id: e.id,
916
+ title: e.title || "Untitled",
917
+ date: startDt.toISOString().slice(0, 10),
918
+ start: formatTime2(startDt),
919
+ end: formatTime2(new Date(e.endDate)),
920
+ location: e.location || "",
921
+ attendees: (e.attendees || []).map((a) => a.name || a.email || "Unknown"),
922
+ notes: e.notes || ""
923
+ };
924
+ });
925
+ mapped.sort(
926
+ (a, b) => a.date === b.date ? a.start.localeCompare(b.start) : a.date.localeCompare(b.date)
927
+ );
928
+ return {
929
+ ok: true,
930
+ from: tomorrow.toISOString().slice(0, 10),
931
+ days_ahead: daysAhead,
932
+ event_count: mapped.length,
933
+ events: mapped
934
+ };
935
+ }
936
+ function getUserCalendarIds(calendars) {
937
+ const SKIP_SOURCES = ["birthdays", "other"];
938
+ const SKIP_TYPES = ["birthdays", "other"];
939
+ return calendars.filter((c) => {
940
+ const sourceType = (c.source?.type || "").toLowerCase();
941
+ const calType = (c.type || "").toLowerCase();
942
+ if (SKIP_SOURCES.includes(sourceType)) return false;
943
+ if (SKIP_TYPES.includes(calType)) return false;
944
+ return true;
945
+ }).map((c) => c.id);
946
+ }
947
+ function filterHolidays(events) {
948
+ const HOLIDAY_PATTERNS = [
949
+ /holiday/i,
950
+ /observance/i,
951
+ /eve\b.*\btentative\b/i,
952
+ /\btentative\b/i
953
+ ];
954
+ return events.filter((e) => {
955
+ const isAllDay = e.allDay === true;
956
+ const notes = (e.notes || "").toLowerCase();
957
+ if (isAllDay && HOLIDAY_PATTERNS.some((p) => p.test(notes))) return false;
958
+ if (isAllDay && HOLIDAY_PATTERNS.some((p) => p.test(e.title || ""))) return false;
959
+ return true;
960
+ });
961
+ }
962
+ function formatTime2(date) {
963
+ return date.toLocaleTimeString("en-US", {
964
+ hour: "2-digit",
965
+ minute: "2-digit",
966
+ hour12: false
967
+ });
968
+ }
969
+
970
+ // src/device-bridge/collectors/contacts.ts
971
+ var ExpoContacts = __toESM(require("expo-contacts"));
972
+ var import_async_storage = __toESM(require("@react-native-async-storage/async-storage"));
973
+ var HASH_STORE_KEY = "device-bridge.contacts.hashes.v1";
974
+ async function requestPermission3() {
975
+ const { status } = await ExpoContacts.requestPermissionsAsync();
976
+ return status === "granted";
977
+ }
978
+ async function hasPermission3() {
979
+ const { status } = await ExpoContacts.getPermissionsAsync();
980
+ return status === "granted";
981
+ }
982
+ var lastContactsStats = null;
983
+ async function collectAll() {
984
+ const result = await ExpoContacts.getContactsAsync({
985
+ fields: [
986
+ ExpoContacts.Fields.Name,
987
+ ExpoContacts.Fields.PhoneNumbers,
988
+ ExpoContacts.Fields.Emails,
989
+ ExpoContacts.Fields.Birthday
990
+ ],
991
+ sort: ExpoContacts.SortTypes.LastName
992
+ });
993
+ const raw = Array.isArray(result?.data) ? result.data : [];
994
+ const contacts = [];
995
+ const currentHashes = {};
996
+ for (let i = 0; i < raw.length; i++) {
997
+ const c = raw[i];
998
+ const id = c.id || `c${i}`;
999
+ const mapped = {
1000
+ id,
1001
+ name: c.name || `${c.firstName || ""} ${c.lastName || ""}`.trim() || "Unknown",
1002
+ relationship: "",
1003
+ // dropped — was the iOS Unauthorized-Keys trigger
1004
+ phone: c.phoneNumbers?.[0]?.number || null,
1005
+ email: c.emails?.[0]?.email || null,
1006
+ birthday: formatBirthday(c.birthday),
1007
+ notes: ""
1008
+ // dropped — Notes is restricted on iOS 16+
1009
+ };
1010
+ contacts.push(mapped);
1011
+ currentHashes[id] = hashContact(mapped);
1012
+ }
1013
+ let stored = {};
1014
+ try {
1015
+ const blob = await import_async_storage.default.getItem(HASH_STORE_KEY);
1016
+ if (blob) stored = JSON.parse(blob);
1017
+ } catch {
1018
+ }
1019
+ const fullSync = Object.keys(stored).length === 0;
1020
+ let added = 0;
1021
+ let updated = 0;
1022
+ let unchanged = 0;
1023
+ for (const id of Object.keys(currentHashes)) {
1024
+ const prev = stored[id];
1025
+ if (prev === void 0) added++;
1026
+ else if (prev !== currentHashes[id]) updated++;
1027
+ else unchanged++;
1028
+ }
1029
+ let removed = 0;
1030
+ for (const id of Object.keys(stored)) {
1031
+ if (currentHashes[id] === void 0) removed++;
1032
+ }
1033
+ lastContactsStats = {
1034
+ total: contacts.length,
1035
+ added,
1036
+ updated,
1037
+ removed,
1038
+ unchanged,
1039
+ full_sync: fullSync
1040
+ };
1041
+ if (!fullSync && added === 0 && updated === 0 && removed === 0) {
1042
+ return null;
1043
+ }
1044
+ try {
1045
+ await import_async_storage.default.setItem(HASH_STORE_KEY, JSON.stringify(currentHashes));
1046
+ } catch {
1047
+ }
1048
+ return contacts;
1049
+ }
1050
+ function fnv1a(str) {
1051
+ let h = 2166136261;
1052
+ for (let i = 0; i < str.length; i++) {
1053
+ h ^= str.charCodeAt(i);
1054
+ h = Math.imul(h, 16777619);
1055
+ }
1056
+ return (h >>> 0).toString(16).padStart(8, "0");
1057
+ }
1058
+ function hashContact(c) {
1059
+ const parts = [
1060
+ c.id,
1061
+ (c.name || "").trim(),
1062
+ c.phone || "\0",
1063
+ (c.email || "\0").toLowerCase(),
1064
+ c.birthday || "\0"
1065
+ ];
1066
+ return fnv1a(parts.join(""));
1067
+ }
1068
+ function formatBirthday(birthday) {
1069
+ if (!birthday) return null;
1070
+ const { year, month, day } = birthday;
1071
+ if (month === void 0 || day === void 0) return null;
1072
+ const m = String(month + 1).padStart(2, "0");
1073
+ const d = String(day).padStart(2, "0");
1074
+ if (!year) return `--${m}-${d}`;
1075
+ return `${year}-${m}-${d}`;
1076
+ }
1077
+
1078
+ // src/device-bridge/collectors/location.ts
1079
+ var ExpoLocation2 = __toESM(require("expo-location"));
1080
+
1081
+ // src/maps/index.ts
1082
+ var import_react_native3 = require("react-native");
1083
+ var import_expo_modules_core = require("expo-modules-core");
1084
+ var ExpoLocation = __toESM(require("expo-location"));
1085
+
1086
+ // src/maps/normalize.ts
1087
+ var text = (v) => typeof v === "string" && v.trim() !== "" ? v : null;
1088
+ function toMapsAddress(raw) {
1089
+ const r = raw ?? {};
1090
+ return {
1091
+ name: text(r.name),
1092
+ street: text(r.street),
1093
+ streetNumber: text(r.streetNumber),
1094
+ district: text(r.district),
1095
+ city: text(r.city),
1096
+ region: text(r.region),
1097
+ postalCode: text(r.postalCode),
1098
+ country: text(r.country),
1099
+ isoCountryCode: text(r.isoCountryCode)
1100
+ };
1101
+ }
1102
+
1103
+ // src/maps/index.ts
1104
+ var native = (0, import_expo_modules_core.requireOptionalNativeModule)("AdaMaps");
1105
+ async function reverseGeocode(at) {
1106
+ const [first] = await ExpoLocation.reverseGeocodeAsync({ latitude: at.latitude, longitude: at.longitude });
1107
+ return first ? toMapsAddress(first) : null;
1108
+ }
1109
+
1110
+ // src/device-bridge/collectors/location.ts
1111
+ async function requestPermission4() {
1112
+ const { status: fg } = await ExpoLocation2.requestForegroundPermissionsAsync();
1113
+ if (fg !== "granted") return false;
1114
+ try {
1115
+ await ExpoLocation2.requestBackgroundPermissionsAsync();
1116
+ } catch {
1117
+ }
1118
+ return fg === "granted";
1119
+ }
1120
+ async function hasPermission4() {
1121
+ const { status } = await ExpoLocation2.getForegroundPermissionsAsync();
1122
+ return status === "granted";
1123
+ }
1124
+ async function collectCurrent() {
1125
+ const location = await ExpoLocation2.getCurrentPositionAsync({
1126
+ accuracy: ExpoLocation2.Accuracy.Balanced
1127
+ });
1128
+ let place = "Current Location";
1129
+ let address = `${location.coords.latitude.toFixed(4)}, ${location.coords.longitude.toFixed(4)}`;
1130
+ let locationType = "unknown";
1131
+ try {
1132
+ const geocoded = await reverseGeocode({
1133
+ latitude: location.coords.latitude,
1134
+ longitude: location.coords.longitude
1135
+ });
1136
+ if (geocoded) {
1137
+ place = geocoded.name || geocoded.street || place;
1138
+ address = [
1139
+ geocoded.streetNumber,
1140
+ geocoded.street,
1141
+ geocoded.city,
1142
+ geocoded.region
1143
+ ].filter(Boolean).join(", ") || address;
1144
+ locationType = classifyLocation(geocoded);
1145
+ }
1146
+ } catch {
1147
+ }
1148
+ return {
1149
+ ok: true,
1150
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1151
+ location: {
1152
+ place,
1153
+ address,
1154
+ lat: location.coords.latitude,
1155
+ lng: location.coords.longitude,
1156
+ type: locationType
1157
+ }
1158
+ };
1159
+ }
1160
+ var WATCH_TIER = {
1161
+ navigation: ExpoLocation2.Accuracy.BestForNavigation,
1162
+ high: ExpoLocation2.Accuracy.High,
1163
+ balanced: ExpoLocation2.Accuracy.Balanced,
1164
+ low: ExpoLocation2.Accuracy.Low
1165
+ };
1166
+ function classifyLocation(geocoded) {
1167
+ const name = (geocoded.name || "").toLowerCase();
1168
+ const street = (geocoded.street || "").toLowerCase();
1169
+ if (name.includes("home") || name.includes("residence")) return "home";
1170
+ if (name.includes("office") || name.includes("workplace") || name.includes("tech park")) return "work";
1171
+ if (name.includes("school") || name.includes("elementary") || name.includes("university")) return "school";
1172
+ if (name.includes("gym") || name.includes("fitness")) return "fitness";
1173
+ if (name.includes("hospital") || name.includes("clinic") || name.includes("dental")) return "medical";
1174
+ return "other";
1175
+ }
1176
+
1177
+ // src/device-bridge/collectors/battery.ts
1178
+ var ExpoBattery = __toESM(require("expo-battery"));
1179
+ async function collectBattery() {
1180
+ const level = await ExpoBattery.getBatteryLevelAsync();
1181
+ const state = await ExpoBattery.getBatteryStateAsync();
1182
+ const lowPower = await ExpoBattery.isLowPowerModeEnabledAsync();
1183
+ return {
1184
+ ok: true,
1185
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1186
+ battery: {
1187
+ level: Math.round(level * 100),
1188
+ // expo-battery returns 0-1
1189
+ state: mapBatteryState(state),
1190
+ low_power_mode: lowPower
1191
+ }
1192
+ };
1193
+ }
1194
+ function subscribeToBattery(callback) {
1195
+ let lastLevel = null;
1196
+ const levelSub = ExpoBattery.addBatteryLevelListener(({ batteryLevel }) => {
1197
+ const pct = Math.round(batteryLevel * 100);
1198
+ if (lastLevel === null || Math.abs(pct - lastLevel) >= 5) {
1199
+ lastLevel = pct;
1200
+ callback();
1201
+ }
1202
+ });
1203
+ const stateSub = ExpoBattery.addBatteryStateListener(() => {
1204
+ callback();
1205
+ });
1206
+ return () => {
1207
+ levelSub?.remove?.();
1208
+ stateSub?.remove?.();
1209
+ };
1210
+ }
1211
+ function mapBatteryState(state) {
1212
+ switch (state) {
1213
+ case ExpoBattery.BatteryState.CHARGING:
1214
+ return "charging";
1215
+ case ExpoBattery.BatteryState.FULL:
1216
+ return "full";
1217
+ case ExpoBattery.BatteryState.UNPLUGGED:
1218
+ default:
1219
+ return "unplugged";
1220
+ }
1221
+ }
1222
+
1223
+ // src/device-bridge/collectors/connectivity.ts
1224
+ var ExpoNetwork = __toESM(require("expo-network"));
1225
+ async function collectConnectivity() {
1226
+ const networkState = await ExpoNetwork.getNetworkStateAsync();
1227
+ let type = "none";
1228
+ let wifiName;
1229
+ let cellularType;
1230
+ if (networkState.type === ExpoNetwork.NetworkStateType.WIFI) {
1231
+ type = "wifi";
1232
+ try {
1233
+ wifiName = await getWifiName();
1234
+ } catch {
1235
+ wifiName = void 0;
1236
+ }
1237
+ } else if (networkState.type === ExpoNetwork.NetworkStateType.CELLULAR) {
1238
+ type = "cellular";
1239
+ cellularType = getCellularGeneration();
1240
+ }
1241
+ return {
1242
+ ok: true,
1243
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1244
+ connectivity: {
1245
+ type,
1246
+ is_connected: networkState.isConnected ?? false,
1247
+ ...wifiName && { wifi_name: wifiName },
1248
+ ...cellularType && { cellular_type: cellularType }
1249
+ }
1250
+ };
1251
+ }
1252
+ async function getWifiName() {
1253
+ return void 0;
1254
+ }
1255
+ function getCellularGeneration() {
1256
+ return "LTE";
1257
+ }
1258
+
1259
+ // src/device-bridge/collectors/notifications.ts
1260
+ var ExpoNotifications = __toESM(require("expo-notifications"));
1261
+ async function requestPermission5() {
1262
+ const { status } = await ExpoNotifications.requestPermissionsAsync();
1263
+ return status === "granted";
1264
+ }
1265
+ async function hasPermission5() {
1266
+ const { status } = await ExpoNotifications.getPermissionsAsync();
1267
+ return status === "granted";
1268
+ }
1269
+ async function collectNotifications() {
1270
+ const presented = await ExpoNotifications.getPresentedNotificationsAsync();
1271
+ const notifications = presented.map((n, i) => ({
1272
+ id: n.request.identifier || `n${i}`,
1273
+ app: n.request.content.data?.app || "A-Team",
1274
+ title: n.request.content.title || "",
1275
+ body: n.request.content.body || "",
1276
+ timestamp: n.date ? new Date(n.date).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
1277
+ sender: n.request.content.data?.sender || null,
1278
+ priority: mapPriority(n.request.content.data?.priority),
1279
+ read: false
1280
+ // Presented notifications are unread by definition
1281
+ }));
1282
+ const unread = notifications.filter((n) => !n.read).length;
1283
+ return {
1284
+ ok: true,
1285
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1286
+ total: notifications.length,
1287
+ unread,
1288
+ notifications
1289
+ };
1290
+ }
1291
+ function mapPriority(p) {
1292
+ if (p === "high" || p === "max") return "high";
1293
+ if (p === "low" || p === "min") return "low";
1294
+ return "medium";
1295
+ }
1296
+
1297
+ // src/device-bridge/collectors/appEngagement.ts
1298
+ var import_react_native4 = require("react-native");
1299
+ var import_async_storage2 = __toESM(require("@react-native-async-storage/async-storage"));
1300
+ var KEY = "ateam.appEngagement.v1";
1301
+ var _tally = null;
1302
+ var _foregroundSince = null;
1303
+ function todayKey() {
1304
+ const d = /* @__PURE__ */ new Date();
1305
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
1306
+ }
1307
+ function fresh() {
1308
+ return { date: todayKey(), sessions: 0, activeMs: 0 };
1309
+ }
1310
+ async function load() {
1311
+ try {
1312
+ const raw = await import_async_storage2.default.getItem(KEY);
1313
+ if (raw) {
1314
+ const parsed = JSON.parse(raw);
1315
+ _tally = parsed?.date === todayKey() ? parsed : fresh();
1316
+ } else {
1317
+ _tally = fresh();
1318
+ }
1319
+ } catch {
1320
+ _tally = fresh();
1321
+ }
1322
+ }
1323
+ function persist() {
1324
+ if (_tally) import_async_storage2.default.setItem(KEY, JSON.stringify(_tally)).catch(() => {
1325
+ });
1326
+ }
1327
+ function rollIfNewDay() {
1328
+ if (!_tally || _tally.date !== todayKey()) {
1329
+ _tally = fresh();
1330
+ persist();
1331
+ }
1332
+ }
1333
+ function flushForeground() {
1334
+ if (_foregroundSince == null || !_tally) return;
1335
+ const now = Date.now();
1336
+ const delta = now - _foregroundSince;
1337
+ if (delta > 0) _tally.activeMs += delta;
1338
+ _foregroundSince = now;
1339
+ }
1340
+ async function getToday() {
1341
+ if (!_tally) await load();
1342
+ rollIfNewDay();
1343
+ flushForeground();
1344
+ persist();
1345
+ if (!_tally) return { app_sessions: null, app_active_min: null };
1346
+ return {
1347
+ app_sessions: _tally.sessions,
1348
+ app_active_min: Math.round(_tally.activeMs / 6e4)
1349
+ };
1350
+ }
1351
+
1352
+ // src/device-bridge/collectors/mood.ts
1353
+ function emptySignals() {
1354
+ return {
1355
+ steps: null,
1356
+ sleep_min: null,
1357
+ screen_min: null,
1358
+ night_screen_min: null,
1359
+ places_count: null,
1360
+ distance_km: null,
1361
+ social_app_min: null,
1362
+ video_app_min: null,
1363
+ productivity_app_min: null,
1364
+ messages_sent: null,
1365
+ calls_count: null,
1366
+ app_sessions: null,
1367
+ app_active_min: null,
1368
+ checkin_mood: null
1369
+ };
1370
+ }
1371
+ async function collectToday3() {
1372
+ const today = emptySignals();
1373
+ try {
1374
+ const h = await collectToday();
1375
+ if (h) {
1376
+ today.steps = typeof h.steps === "number" ? h.steps : null;
1377
+ today.distance_km = typeof h.distance_km === "number" ? h.distance_km : null;
1378
+ }
1379
+ } catch {
1380
+ }
1381
+ try {
1382
+ const x = await collectMoodExtras();
1383
+ today.sleep_min = x.sleep_min;
1384
+ today.resting_hr = x.resting_hr;
1385
+ today.active_energy_kcal = x.active_energy_kcal;
1386
+ today.exercise_min = x.exercise_min;
1387
+ } catch {
1388
+ }
1389
+ try {
1390
+ const e = await getToday();
1391
+ today.app_sessions = e.app_sessions;
1392
+ today.app_active_min = e.app_active_min;
1393
+ } catch {
1394
+ }
1395
+ let timezone = "UTC";
1396
+ try {
1397
+ timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
1398
+ } catch {
1399
+ }
1400
+ return {
1401
+ window: "today",
1402
+ timezone,
1403
+ collected_at: (/* @__PURE__ */ new Date()).toISOString(),
1404
+ today
1405
+ };
1406
+ }
1407
+
1408
+ // src/device-bridge/collectors/camera.ts
1409
+ var import_expo_camera = require("expo-camera");
1410
+ async function hasPermission6() {
1411
+ try {
1412
+ return (await import_expo_camera.Camera.getCameraPermissionsAsync()).granted;
1413
+ } catch {
1414
+ return false;
1415
+ }
1416
+ }
1417
+ async function requestPermission6() {
1418
+ try {
1419
+ return (await import_expo_camera.Camera.requestCameraPermissionsAsync()).granted;
1420
+ } catch {
1421
+ return false;
1422
+ }
1423
+ }
1424
+
1425
+ // src/device-bridge/capabilities.ts
1426
+ function calendarCapability() {
1427
+ return {
1428
+ id: "calendar",
1429
+ name: "Calendar",
1430
+ description: "Syncs your calendar events so your assistant knows your schedule.",
1431
+ reason: "Needed for scheduling, meeting prep, commute alerts, and daily briefings.",
1432
+ icon: "calendar",
1433
+ requiresPermission: true,
1434
+ permissionState: "not_requested",
1435
+ requestPermission: requestPermission2,
1436
+ checkPermission: hasPermission2,
1437
+ collect: async () => {
1438
+ const [today, upcoming] = await Promise.all([
1439
+ collectToday2(),
1440
+ collectUpcoming(7)
1441
+ ]);
1442
+ return { today, upcoming };
1443
+ },
1444
+ defaultInterval: 6e4
1445
+ // 1 min
1446
+ };
1447
+ }
1448
+ function contactsCapability() {
1449
+ return {
1450
+ id: "contacts",
1451
+ name: "Contacts",
1452
+ description: "Syncs your contacts so your assistant can find people and relationships.",
1453
+ reason: "Needed for messaging, birthday reminders, and relationship insights.",
1454
+ icon: "people",
1455
+ requiresPermission: true,
1456
+ permissionState: "not_requested",
1457
+ requestPermission: requestPermission3,
1458
+ checkPermission: hasPermission3,
1459
+ collect: async () => {
1460
+ const list = await collectAll();
1461
+ if (list === null) return null;
1462
+ return { contacts: list };
1463
+ },
1464
+ defaultInterval: 3e5
1465
+ // 5 min
1466
+ };
1467
+ }
1468
+ function locationCapability() {
1469
+ return {
1470
+ id: "location",
1471
+ name: "Location",
1472
+ description: "Syncs your location for weather, commute, and context-aware assistance.",
1473
+ reason: "Needed for commute estimates, weather at your location, and situation detection.",
1474
+ icon: "location",
1475
+ requiresPermission: true,
1476
+ permissionState: "not_requested",
1477
+ requestPermission: requestPermission4,
1478
+ checkPermission: hasPermission4,
1479
+ collect: collectCurrent,
1480
+ defaultInterval: 3e4
1481
+ // 30 sec
1482
+ };
1483
+ }
1484
+ function batteryCapability() {
1485
+ return {
1486
+ id: "battery",
1487
+ name: "Battery",
1488
+ description: "Syncs battery level and charging status.",
1489
+ reason: "Helps your assistant adjust behavior when battery is low.",
1490
+ icon: "battery",
1491
+ requiresPermission: false,
1492
+ permissionState: "not_needed",
1493
+ requestPermission: async () => true,
1494
+ checkPermission: async () => true,
1495
+ collect: collectBattery,
1496
+ defaultInterval: 6e4,
1497
+ // 1 min
1498
+ subscribe: subscribeToBattery
1499
+ };
1500
+ }
1501
+ function connectivityCapability() {
1502
+ return {
1503
+ id: "connectivity",
1504
+ name: "Connectivity",
1505
+ description: "Syncs WiFi/cellular status.",
1506
+ reason: "Helps your assistant know if you have internet access.",
1507
+ icon: "wifi",
1508
+ requiresPermission: false,
1509
+ permissionState: "not_needed",
1510
+ requestPermission: async () => true,
1511
+ checkPermission: async () => true,
1512
+ collect: collectConnectivity,
1513
+ defaultInterval: 3e4
1514
+ // 30 sec
1515
+ };
1516
+ }
1517
+ function healthCapability() {
1518
+ return {
1519
+ id: "health",
1520
+ name: "Health",
1521
+ description: "Reads daily steps, floors, calories, and distance from Apple Health.",
1522
+ reason: "Powers the personal health coach and pairs activity data with nutrition tracking.",
1523
+ icon: "heart",
1524
+ requiresPermission: true,
1525
+ permissionState: "not_requested",
1526
+ requestPermission,
1527
+ checkPermission: hasPermission,
1528
+ collect: async () => {
1529
+ const days = await collectHistory(30);
1530
+ const today = days[0] || await collectToday();
1531
+ return { today, days };
1532
+ },
1533
+ defaultInterval: 3e5
1534
+ // 5 min
1535
+ };
1536
+ }
1537
+ function moodCapability() {
1538
+ return {
1539
+ id: "mood",
1540
+ name: "Mood",
1541
+ description: "Sends a daily behavioral-signal summary (activity, routine) to infer mood \u2014 not a medical diagnosis.",
1542
+ reason: "Lets ada gently notice changes in energy, stress, and routine and check in.",
1543
+ icon: "heart",
1544
+ // No OS permission of its own — it derives from collectors that gate
1545
+ // themselves (e.g. health). Treated as not_needed so the bridge syncs it
1546
+ // whenever the user has the Mood toggle on.
1547
+ requiresPermission: false,
1548
+ permissionState: "not_needed",
1549
+ requestPermission: async () => true,
1550
+ checkPermission: async () => true,
1551
+ collect: async () => {
1552
+ return collectToday3();
1553
+ },
1554
+ defaultInterval: 36e5
1555
+ // hourly — it's a daily summary, no need to spam
1556
+ };
1557
+ }
1558
+ function cameraCapability() {
1559
+ return {
1560
+ id: "camera",
1561
+ name: "Camera",
1562
+ description: "Lets ada see through your camera to guide you \u2014 reading text and describing what's in front of you. Frames are analysed on the phone; nothing is stored or uploaded.",
1563
+ reason: "Powers visual guidance (Ada Guide): a live view with on-device text and scene understanding.",
1564
+ icon: "camera",
1565
+ requiresPermission: true,
1566
+ permissionState: "not_requested",
1567
+ requestPermission: requestPermission6,
1568
+ checkPermission: hasPermission6,
1569
+ // LIVE, not synced: the camera is used in the moment (deviceState.visual / a
1570
+ // widget's preview) and never collected to the relay. So collect never
1571
+ // pushes — this capability's value is the USER GRANT + OS permission, exposed
1572
+ // to the backend like every other, not a data payload. `null` = nothing to
1573
+ // push, which the bridge skips (same contract contacts uses when unchanged).
1574
+ collect: async () => null,
1575
+ defaultInterval: 36e5
1576
+ // never really collects; keep the poll rare
1577
+ };
1578
+ }
1579
+ function notificationsCapability() {
1580
+ return {
1581
+ id: "notifications",
1582
+ name: "Notifications",
1583
+ description: "Syncs your notifications for triage and smart grouping.",
1584
+ reason: "Needed for notification triage, priority filtering, and Do Not Disturb.",
1585
+ icon: "notifications",
1586
+ requiresPermission: true,
1587
+ permissionState: "not_requested",
1588
+ requestPermission: requestPermission5,
1589
+ checkPermission: hasPermission5,
1590
+ collect: collectNotifications,
1591
+ defaultInterval: 15e3
1592
+ // 15 sec
1593
+ };
1594
+ }
1595
+ function allBuiltIn() {
1596
+ return [
1597
+ calendarCapability(),
1598
+ contactsCapability(),
1599
+ locationCapability(),
1600
+ batteryCapability(),
1601
+ connectivityCapability(),
1602
+ notificationsCapability(),
1603
+ healthCapability(),
1604
+ moodCapability(),
1605
+ cameraCapability()
1606
+ ];
1607
+ }
1608
+
1609
+ // src/device-bridge/background.ts
1610
+ var BACKGROUND_TASK_NAME = "DEVICE_BRIDGE_BACKGROUND_SYNC";
1611
+ var CAPABILITY_FACTORIES = {
1612
+ calendar: calendarCapability,
1613
+ contacts: contactsCapability,
1614
+ location: locationCapability,
1615
+ battery: batteryCapability,
1616
+ connectivity: connectivityCapability,
1617
+ notifications: notificationsCapability,
1618
+ health: healthCapability
1619
+ };
1620
+ async function registerBackgroundSync(config2) {
1621
+ TaskManager.defineTask(BACKGROUND_TASK_NAME, async () => {
1622
+ try {
1623
+ const hasNew = await syncDomains(config2, ["location", "battery", "calendar"]);
1624
+ return hasNew ? BackgroundFetch.BackgroundFetchResult.NewData : BackgroundFetch.BackgroundFetchResult.NoData;
1625
+ } catch (error) {
1626
+ console.error("[DeviceBridge] Background sync failed:", error);
1627
+ return BackgroundFetch.BackgroundFetchResult.Failed;
1628
+ }
1629
+ });
1630
+ await BackgroundFetch.registerTaskAsync(BACKGROUND_TASK_NAME, {
1631
+ minimumInterval: 300,
1632
+ // 5 minutes (iOS will clamp to ~15 min)
1633
+ stopOnTerminate: false,
1634
+ startOnBoot: true
1635
+ });
1636
+ }
1637
+ async function unregisterBackgroundSync() {
1638
+ const isRegistered = await TaskManager.isTaskRegisteredAsync(
1639
+ BACKGROUND_TASK_NAME
1640
+ );
1641
+ if (isRegistered) {
1642
+ await BackgroundFetch.unregisterTaskAsync(BACKGROUND_TASK_NAME);
1643
+ }
1644
+ }
1645
+ async function syncDomains(config2, domains) {
1646
+ const relay = new RelayClient({
1647
+ relayUrl: config2.relayUrl,
1648
+ deviceId: config2.deviceId,
1649
+ tenant: config2.tenant,
1650
+ actorId: config2.actorId,
1651
+ apiKey: config2.apiKey,
1652
+ timeout: 15e3
1653
+ // longer than foreground — background tasks are budget-limited but not latency-sensitive
1654
+ });
1655
+ const results = await Promise.allSettled(
1656
+ domains.map((d) => collectAndPush(relay, d))
1657
+ );
1658
+ return results.some((r) => r.status === "fulfilled" && r.value);
1659
+ }
1660
+ async function collectAndPush(relay, domain) {
1661
+ const factory = CAPABILITY_FACTORIES[domain];
1662
+ if (!factory) {
1663
+ console.warn(`[DeviceBridge] Unknown sync domain: ${domain}`);
1664
+ return false;
1665
+ }
1666
+ const cap = factory();
1667
+ if (cap.requiresPermission) {
1668
+ const granted = await cap.checkPermission();
1669
+ if (!granted) return false;
1670
+ }
1671
+ const data = await cap.collect();
1672
+ const result = await relay.pushDomain(domain, data);
1673
+ return result.ok;
1674
+ }
1675
+
1676
+ // src/device-bridge/biometrics.ts
1677
+ var LocalAuthentication = __toESM(require("expo-local-authentication"));
1678
+
1679
+ // src/device-bridge/sharing.ts
1680
+ var Sharing = __toESM(require("expo-sharing"));
1681
+
1682
+ // src/device-bridge/scanner.ts
1683
+ var import_expo_camera2 = require("expo-camera");
1684
+
1685
+ // src/device-bridge/index.ts
1686
+ var DeviceBridge = class {
1687
+ constructor(config2) {
1688
+ // Capability registry
1689
+ this.caps = /* @__PURE__ */ new Map();
1690
+ this.syncTimers = /* @__PURE__ */ new Map();
1691
+ this.subscriptions = /* @__PURE__ */ new Map();
1692
+ this.domainStatus = /* @__PURE__ */ new Map();
1693
+ this.running = false;
1694
+ this.config = config2;
1695
+ this.relay = new RelayClient({
1696
+ relayUrl: config2.relayUrl,
1697
+ deviceId: config2.deviceId,
1698
+ tenant: config2.tenant,
1699
+ actorId: config2.actorId,
1700
+ apiKey: config2.apiKey
1701
+ });
1702
+ this.queuePoller = new QueuePoller({
1703
+ relayClient: this.relay,
1704
+ pollInterval: 5e3,
1705
+ onActionExecuted: () => this.notifyStatusChange(),
1706
+ onError: (error) => this.config.onError?.({
1707
+ domain: "actions",
1708
+ message: error.message,
1709
+ code: "ACTION_ERROR",
1710
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1711
+ })
1712
+ });
1713
+ }
1714
+ // ─── Capability Registration ───
1715
+ /**
1716
+ * Register a capability. Does NOT request permission — just makes it known.
1717
+ * Can be called before or after startSync().
1718
+ */
1719
+ register(cap) {
1720
+ this.caps.set(cap.id, cap);
1721
+ this.domainStatus.set(cap.id, {
1722
+ domain: cap.id,
1723
+ lastSync: null,
1724
+ state: "idle"
1725
+ });
1726
+ }
1727
+ /**
1728
+ * Register multiple capabilities at once.
1729
+ */
1730
+ registerAll(caps) {
1731
+ for (const cap of caps) {
1732
+ this.register(cap);
1733
+ }
1734
+ }
1735
+ /**
1736
+ * Get a registered capability by ID.
1737
+ * Use this to read name/description/reason for your permission UI.
1738
+ */
1739
+ getCapability(id) {
1740
+ return this.caps.get(id);
1741
+ }
1742
+ /**
1743
+ * Get all registered capabilities with their current status.
1744
+ */
1745
+ listCapabilities() {
1746
+ return Array.from(this.caps.values()).map((cap) => ({
1747
+ id: cap.id,
1748
+ name: cap.name,
1749
+ permission: cap.permissionState,
1750
+ sync: this.domainStatus.get(cap.id) || {
1751
+ domain: cap.id,
1752
+ lastSync: null,
1753
+ state: "idle"
1754
+ }
1755
+ }));
1756
+ }
1757
+ // ─── Permissions (host app controls the flow) ───
1758
+ /**
1759
+ * Request permission for ONE capability.
1760
+ * Call after showing your own explanation screen.
1761
+ * If bridge is already running and granted, syncing starts automatically.
1762
+ */
1763
+ async requestPermission(capId) {
1764
+ const cap = this.caps.get(capId);
1765
+ if (!cap) throw new Error(`Capability "${capId}" not registered`);
1766
+ if (!cap.requiresPermission) {
1767
+ cap.permissionState = "not_needed";
1768
+ return true;
1769
+ }
1770
+ const granted = await cap.requestPermission();
1771
+ cap.permissionState = granted ? "granted" : "denied";
1772
+ if (granted && this.running) {
1773
+ this.startCapabilitySync(cap);
1774
+ }
1775
+ this.notifyStatusChange();
1776
+ return granted;
1777
+ }
1778
+ /**
1779
+ * Check permission WITHOUT prompting.
1780
+ */
1781
+ async checkPermission(capId) {
1782
+ const cap = this.caps.get(capId);
1783
+ if (!cap) throw new Error(`Capability "${capId}" not registered`);
1784
+ if (!cap.requiresPermission) return "not_needed";
1785
+ const granted = await cap.checkPermission();
1786
+ cap.permissionState = granted ? "granted" : cap.permissionState;
1787
+ return cap.permissionState;
1788
+ }
1789
+ /**
1790
+ * Request ALL permissions sequentially (one at a time, not bombarded).
1791
+ */
1792
+ async requestAllPermissions() {
1793
+ const results = /* @__PURE__ */ new Map();
1794
+ for (const [id, cap] of this.caps) {
1795
+ if (!cap.requiresPermission) {
1796
+ cap.permissionState = "not_needed";
1797
+ results.set(id, true);
1798
+ continue;
1799
+ }
1800
+ const granted = await cap.requestPermission();
1801
+ cap.permissionState = granted ? "granted" : "denied";
1802
+ results.set(id, granted);
1803
+ }
1804
+ this.notifyStatusChange();
1805
+ return results;
1806
+ }
1807
+ /**
1808
+ * Get capabilities that still need permission.
1809
+ * Use this to drive a "next permission" onboarding flow.
1810
+ */
1811
+ getPendingPermissions() {
1812
+ return Array.from(this.caps.values()).filter(
1813
+ (cap) => cap.requiresPermission && cap.permissionState === "not_requested"
1814
+ );
1815
+ }
1816
+ // ─── Sync Control ───
1817
+ /**
1818
+ * Start syncing all permitted capabilities + action queue poller.
1819
+ */
1820
+ async startSync() {
1821
+ if (this.running) return;
1822
+ this.running = true;
1823
+ for (const [, cap] of this.caps) {
1824
+ const permitted = !cap.requiresPermission || cap.permissionState === "granted" || cap.permissionState === "not_needed";
1825
+ if (permitted) {
1826
+ this.startCapabilitySync(cap);
1827
+ } else {
1828
+ this.updateDomainStatus(cap.id, "error", "Permission not granted");
1829
+ }
1830
+ }
1831
+ this.queuePoller.start();
1832
+ if (this.config.tenant && this.config.apiKey) {
1833
+ registerBackgroundSync({
1834
+ relayUrl: this.config.relayUrl,
1835
+ deviceId: this.config.deviceId,
1836
+ tenant: this.config.tenant,
1837
+ actorId: this.config.actorId,
1838
+ apiKey: this.config.apiKey
1839
+ }).catch((e) => console.warn("[adas/bridge] registerBackgroundSync failed:", e?.message || e));
1840
+ }
1841
+ this.notifyStatusChange();
1842
+ }
1843
+ /**
1844
+ * Stop all syncing.
1845
+ */
1846
+ stopSync() {
1847
+ this.running = false;
1848
+ for (const [id, timer] of this.syncTimers) {
1849
+ clearInterval(timer);
1850
+ this.updateDomainStatus(id, "stopped");
1851
+ }
1852
+ this.syncTimers.clear();
1853
+ for (const unsub of this.subscriptions.values()) {
1854
+ try {
1855
+ unsub();
1856
+ } catch {
1857
+ }
1858
+ }
1859
+ this.subscriptions.clear();
1860
+ this.queuePoller.stop();
1861
+ unregisterBackgroundSync().catch((e) => console.warn("[adas/bridge] unregisterBackgroundSync failed:", e?.message || e));
1862
+ this.notifyStatusChange();
1863
+ }
1864
+ /**
1865
+ * Force immediate sync of all permitted capabilities.
1866
+ */
1867
+ async syncNow() {
1868
+ const promises = Array.from(this.caps.values()).filter((c) => c.permissionState === "granted" || c.permissionState === "not_needed").map((c) => this.syncCapability(c));
1869
+ await Promise.allSettled(promises);
1870
+ }
1871
+ /**
1872
+ * Force immediate sync of a single capability by id. Used by the host to
1873
+ * refresh fast-moving sources (battery) on app-foreground so the relay
1874
+ * gets a fresh reading the moment the user opens the app.
1875
+ */
1876
+ async syncCapabilityNow(capId) {
1877
+ const cap = this.caps.get(capId);
1878
+ if (!cap) return;
1879
+ const permitted = !cap.requiresPermission || cap.permissionState === "granted" || cap.permissionState === "not_needed";
1880
+ if (!permitted) return;
1881
+ await this.syncCapability(cap);
1882
+ }
1883
+ /**
1884
+ * Get current bridge status.
1885
+ */
1886
+ getStatus() {
1887
+ return {
1888
+ running: this.running,
1889
+ capabilities: this.listCapabilities(),
1890
+ lastFullSync: this.getLastFullSync(),
1891
+ pendingActions: this.relay.getOfflineQueueSize()
1892
+ };
1893
+ }
1894
+ /**
1895
+ * Check if the relay is reachable.
1896
+ */
1897
+ async checkConnectivity() {
1898
+ return this.relay.ping();
1899
+ }
1900
+ // ─── Internal ───
1901
+ startCapabilitySync(cap) {
1902
+ if (this.syncTimers.has(cap.id)) return;
1903
+ const interval = this.config.syncIntervals?.[cap.id] ?? cap.defaultInterval;
1904
+ this.syncCapability(cap);
1905
+ const timer = setInterval(() => this.syncCapability(cap), interval);
1906
+ this.syncTimers.set(cap.id, timer);
1907
+ if (cap.subscribe && !this.subscriptions.has(cap.id)) {
1908
+ try {
1909
+ const unsub = cap.subscribe(() => {
1910
+ if (this.running) this.syncCapability(cap);
1911
+ });
1912
+ this.subscriptions.set(cap.id, unsub);
1913
+ } catch (err) {
1914
+ const message = err instanceof Error ? err.message : String(err);
1915
+ this.config.onError?.({
1916
+ domain: cap.id,
1917
+ message: `subscribe failed: ${message}`,
1918
+ code: "SUBSCRIBE_ERROR",
1919
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1920
+ });
1921
+ }
1922
+ }
1923
+ }
1924
+ async syncCapability(cap) {
1925
+ if (!this.running) return;
1926
+ this.updateDomainStatus(cap.id, "syncing");
1927
+ try {
1928
+ const data = await cap.collect();
1929
+ if (data === null) {
1930
+ this.updateDomainStatus(cap.id, "idle");
1931
+ return;
1932
+ }
1933
+ const result = await this.relay.pushDomain(cap.id, data);
1934
+ if (result.ok) {
1935
+ this.updateDomainStatus(cap.id, "idle");
1936
+ } else {
1937
+ this.updateDomainStatus(cap.id, "error", result.error);
1938
+ this.config.onError?.({
1939
+ domain: cap.id,
1940
+ message: result.error || "Push failed",
1941
+ code: "RELAY_ERROR",
1942
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1943
+ });
1944
+ }
1945
+ } catch (error) {
1946
+ const message = error instanceof Error ? error.message : String(error);
1947
+ this.updateDomainStatus(cap.id, "error", message);
1948
+ this.config.onError?.({
1949
+ domain: cap.id,
1950
+ message,
1951
+ code: "COLLECTOR_ERROR",
1952
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1953
+ });
1954
+ }
1955
+ }
1956
+ updateDomainStatus(id, state, error) {
1957
+ const current = this.domainStatus.get(id);
1958
+ this.domainStatus.set(id, {
1959
+ domain: id,
1960
+ lastSync: state === "idle" ? (/* @__PURE__ */ new Date()).toISOString() : current?.lastSync ?? null,
1961
+ state,
1962
+ error,
1963
+ itemCount: current?.itemCount
1964
+ });
1965
+ }
1966
+ getLastFullSync() {
1967
+ const syncs = Array.from(this.domainStatus.values()).map((d) => d.lastSync).filter((s) => s !== null);
1968
+ if (syncs.length === 0) return null;
1969
+ return syncs.sort()[0];
1970
+ }
1971
+ notifyStatusChange() {
1972
+ this.config.onStatusChange?.(this.getStatus());
1973
+ }
1974
+ };
1975
+
1976
+ // src/device-bridge/deviceId.ts
1977
+ var DEVICE_ID_KEY = "ateam.deviceId";
1978
+ async function getOrCreateDeviceId(storage) {
1979
+ const saved = await storage.getItem(DEVICE_ID_KEY);
1980
+ if (saved) return saved;
1981
+ const id = `device-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1982
+ await storage.setItem(DEVICE_ID_KEY, id);
1983
+ return id;
1984
+ }
1985
+
1986
+ // src/capabilities/config.ts
1987
+ var config = null;
1988
+ function configureDeviceSync(next) {
1989
+ config = next;
1990
+ }
1991
+ function getDeviceSyncConfig() {
1992
+ return config;
1993
+ }
1994
+
1995
+ // src/capabilities/store.ts
1996
+ var STORAGE_KEY = "ateam.capabilities";
1997
+ var SETUP_KEY = "ateam.capabilities.setup";
1998
+ var DEFAULT_ENABLED = {
1999
+ calendar: true,
2000
+ contacts: true,
2001
+ location: true,
2002
+ battery: true,
2003
+ connectivity: true,
2004
+ health: true,
2005
+ mood: true,
2006
+ // Opt-IN: the camera is more invasive than the sync collectors and should not
2007
+ // prompt every user for camera access on first launch. It lights up only when
2008
+ // the user turns it on (which then requests the OS permission), so a solution
2009
+ // that wants a camera preview asks the user to enable it.
2010
+ camera: false
2011
+ };
2012
+ var HIDDEN_FROM_UI = /* @__PURE__ */ new Set(["notifications"]);
2013
+ var bridge = null;
2014
+ var bridgeOwner = null;
2015
+ var startQueue = Promise.resolve();
2016
+ var startGeneration = 0;
2017
+ var builtInCapabilities = [];
2018
+ var foregroundUnsub = null;
2019
+ var useCapabilitiesStore = (0, import_zustand.create)((set, get) => {
2020
+ const runStart = async () => {
2021
+ const tenant = (0, import_core.getTenant)();
2022
+ const actorId = (0, import_core.getUser)()?.actorId;
2023
+ if (bridge) {
2024
+ if (bridgeOwner?.tenant === tenant && bridgeOwner?.actorId === actorId) {
2025
+ console.log("[Capabilities] Bridge already running");
2026
+ return;
2027
+ }
2028
+ console.log("[Capabilities] Team or user changed \u2014 restarting bridge");
2029
+ get().stopBridge();
2030
+ }
2031
+ const { capabilities: caps } = get();
2032
+ const enabledCaps = caps.filter((c) => c.enabled);
2033
+ if (enabledCaps.length === 0) {
2034
+ console.log("[Capabilities] No capabilities enabled \u2014 bridge not started");
2035
+ return;
2036
+ }
2037
+ const config2 = getDeviceSyncConfig();
2038
+ if (!config2) {
2039
+ console.error("[Capabilities] Bridge not started: device sync is not configured \u2014 pass deviceSync to bootstrapExpoAdas (or call configureDeviceSync)");
2040
+ return;
2041
+ }
2042
+ if (!tenant || !actorId) {
2043
+ console.error(`[Capabilities] Bridge not started: no signed-in ${!tenant ? "tenant" : "user"}`);
2044
+ return;
2045
+ }
2046
+ const generation = startGeneration;
2047
+ const deviceId = await getOrCreateDeviceId(config2.secureStorage);
2048
+ if (generation !== startGeneration) return;
2049
+ console.log(`[Capabilities] Starting bridge for tenant=${tenant} actor=${actorId} device=${deviceId} with ${enabledCaps.length} capabilities: ${enabledCaps.map((c) => c.id).join(", ")}`);
2050
+ const started = new DeviceBridge({
2051
+ relayUrl: config2.relayUrl(),
2052
+ deviceId,
2053
+ tenant,
2054
+ actorId,
2055
+ // RelayClient sends `Authorization: Bearer <apiKey>` so the relay's
2056
+ // auth gate accepts the call. Empty string = misconfig → relay returns
2057
+ // 401, surfaced as a sync error in the UI.
2058
+ apiKey: config2.relayKey,
2059
+ onStatusChange: (status) => {
2060
+ for (const capStatus of status.capabilities) {
2061
+ const current = get().capabilities.find((c) => c.id === capStatus.id);
2062
+ if (current && current.osPermission !== capStatus.permission) {
2063
+ get().setOsPermission(capStatus.id, capStatus.permission);
2064
+ }
2065
+ }
2066
+ },
2067
+ onError: (err) => {
2068
+ console.warn(`[device-bridge] ${err.domain}: ${err.message}`);
2069
+ }
2070
+ });
2071
+ bridge = started;
2072
+ bridgeOwner = { tenant, actorId };
2073
+ try {
2074
+ const enabledIds = new Set(enabledCaps.map((c) => c.id));
2075
+ const capsToRegister = builtInCapabilities.filter((c) => enabledIds.has(c.id));
2076
+ started.registerAll(capsToRegister);
2077
+ await started.requestAllPermissions();
2078
+ if (generation !== startGeneration) return;
2079
+ const statuses = started.listCapabilities();
2080
+ set((state) => ({
2081
+ bridgeRunning: true,
2082
+ capabilities: state.capabilities.map((c) => {
2083
+ const status = statuses.find((s) => s.id === c.id);
2084
+ return status ? { ...c, osPermission: status.permission } : c;
2085
+ })
2086
+ }));
2087
+ await started.startSync();
2088
+ if (generation !== startGeneration) {
2089
+ started.stopSync();
2090
+ return;
2091
+ }
2092
+ console.log("[Capabilities] Bridge started and syncing");
2093
+ } catch (err) {
2094
+ if (bridge === started) get().stopBridge();
2095
+ throw err;
2096
+ }
2097
+ if (!foregroundUnsub) {
2098
+ foregroundUnsub = (0, import_core.onAppForeground)(() => {
2099
+ bridge?.syncCapabilityNow("battery").catch((err) => {
2100
+ console.warn("[Capabilities] foreground battery sync failed:", err);
2101
+ });
2102
+ });
2103
+ }
2104
+ };
2105
+ return {
2106
+ capabilities: [],
2107
+ hasCompletedSetup: false,
2108
+ isLoading: true,
2109
+ bridgeRunning: false,
2110
+ initialize: async () => {
2111
+ try {
2112
+ builtInCapabilities = capabilities_exports.allBuiltIn().filter((c) => !HIDDEN_FROM_UI.has(c.id));
2113
+ const capStates = builtInCapabilities.map((cap) => ({
2114
+ id: cap.id,
2115
+ name: cap.name,
2116
+ description: cap.description,
2117
+ reason: cap.reason,
2118
+ icon: cap.icon || cap.id,
2119
+ requiresPermission: cap.requiresPermission,
2120
+ enabled: DEFAULT_ENABLED[cap.id] ?? true,
2121
+ osPermission: cap.permissionState
2122
+ }));
2123
+ const setupDone = await import_async_storage3.default.getItem(SETUP_KEY);
2124
+ const saved = await import_async_storage3.default.getItem(STORAGE_KEY);
2125
+ const prefs = saved ? JSON.parse(saved) : {};
2126
+ set({
2127
+ capabilities: capStates.map((cap) => ({
2128
+ ...cap,
2129
+ enabled: prefs[cap.id] ?? cap.enabled
2130
+ })),
2131
+ hasCompletedSetup: setupDone === "true",
2132
+ isLoading: false
2133
+ });
2134
+ console.log(`[Capabilities] Initialized ${capStates.length} capabilities from device-bridge (setup ${setupDone === "true" ? "done" : "pending"})`);
2135
+ } catch (err) {
2136
+ console.error("[Capabilities] Initialize failed:", err);
2137
+ set({ isLoading: false });
2138
+ }
2139
+ },
2140
+ toggleCapability: async (id, enabled) => {
2141
+ set((state) => ({
2142
+ capabilities: state.capabilities.map(
2143
+ (cap) => cap.id === id ? { ...cap, enabled } : cap
2144
+ )
2145
+ }));
2146
+ const prefs = {};
2147
+ for (const cap of get().capabilities) {
2148
+ prefs[cap.id] = cap.id === id ? enabled : cap.enabled;
2149
+ }
2150
+ await import_async_storage3.default.setItem(STORAGE_KEY, JSON.stringify(prefs));
2151
+ if (bridge && get().bridgeRunning) {
2152
+ if (enabled) {
2153
+ const builtIn = builtInCapabilities.find((c) => c.id === id);
2154
+ if (builtIn) {
2155
+ bridge.register(builtIn);
2156
+ const granted = await bridge.requestPermission(id);
2157
+ set((state) => ({
2158
+ capabilities: state.capabilities.map(
2159
+ (c) => c.id === id ? { ...c, osPermission: granted ? "granted" : "denied" } : c
2160
+ )
2161
+ }));
2162
+ }
2163
+ } else {
2164
+ console.log(`[Capabilities] ${id} disabled \u2014 restarting bridge`);
2165
+ get().stopBridge();
2166
+ await get().startBridge();
2167
+ }
2168
+ }
2169
+ },
2170
+ setOsPermission: (id, permState) => {
2171
+ set((s) => ({
2172
+ capabilities: s.capabilities.map(
2173
+ (cap) => cap.id === id ? { ...cap, osPermission: permState } : cap
2174
+ )
2175
+ }));
2176
+ },
2177
+ completeSetup: async () => {
2178
+ await import_async_storage3.default.setItem(SETUP_KEY, "true");
2179
+ set({ hasCompletedSetup: true });
2180
+ },
2181
+ startBridge: () => {
2182
+ const run = startQueue.then(runStart);
2183
+ startQueue = run.catch((err) => {
2184
+ console.error("[Capabilities] Bridge start failed:", err);
2185
+ });
2186
+ return run;
2187
+ },
2188
+ stopBridge: () => {
2189
+ startGeneration++;
2190
+ if (bridge) {
2191
+ bridge.stopSync();
2192
+ bridge = null;
2193
+ bridgeOwner = null;
2194
+ set({ bridgeRunning: false });
2195
+ console.log("[Capabilities] Bridge stopped");
2196
+ }
2197
+ if (foregroundUnsub) {
2198
+ foregroundUnsub();
2199
+ foregroundUnsub = null;
2200
+ }
2201
+ },
2202
+ syncNow: async () => {
2203
+ if (!bridge) return { ok: false, error: "bridge not running" };
2204
+ try {
2205
+ await bridge.syncNow();
2206
+ const statuses = bridge.listCapabilities();
2207
+ const failed = statuses.filter(
2208
+ (s) => s.sync?.state === "error" || s.sync?.state === "syncing"
2209
+ );
2210
+ if (failed.length > 0) {
2211
+ const summary = failed.map((s) => `${s.id}:${s.sync?.state}${s.sync?.error ? `(${s.sync.error})` : ""}`).join(", ");
2212
+ return { ok: false, error: summary };
2213
+ }
2214
+ return { ok: true };
2215
+ } catch (e) {
2216
+ return { ok: false, error: e?.message || String(e) };
2217
+ }
2218
+ }
2219
+ };
2220
+ });
2221
+
2222
+ // src/capabilities/CapabilitiesSetup.tsx
2223
+ var import_react = require("react");
2224
+ var import_react_native6 = require("react-native");
2225
+ var import_core3 = require("@ateam-ai-mobile/core");
2226
+
2227
+ // src/capabilities/CapabilityCard.tsx
2228
+ var import_react_native5 = require("react-native");
2229
+ var import_core2 = require("@ateam-ai-mobile/core");
2230
+ var import_jsx_runtime = require("react/jsx-runtime");
2231
+ var fontFam = import_react_native5.Platform.OS === "ios" ? "SF Pro Rounded" : void 0;
2232
+ var ICONS = {
2233
+ calendar: "\u{1F4C5}",
2234
+ contacts: "\u{1F465}",
2235
+ location: "\u{1F4CD}",
2236
+ battery: "\u{1F50B}",
2237
+ wifi: "\u{1F4F6}",
2238
+ notifications: "\u{1F514}"
2239
+ };
2240
+ function CapabilityCard({ capability, onToggle }) {
2241
+ const { id, name, description, reason, icon, enabled, osPermission, requiresPermission } = capability;
2242
+ const isDenied = osPermission === "denied";
2243
+ const isGranted = osPermission === "granted" || osPermission === "not_needed";
2244
+ const handleToggle = (value) => {
2245
+ if (isDenied && value) {
2246
+ import_react_native5.Linking.openSettings();
2247
+ return;
2248
+ }
2249
+ onToggle(id, value);
2250
+ };
2251
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react_native5.View, { style: [styles.card, enabled && styles.cardEnabled], children: [
2252
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react_native5.View, { style: styles.row, children: [
2253
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.View, { style: [styles.iconBox, enabled && styles.iconBoxEnabled], children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.Text, { style: styles.iconText, children: ICONS[icon] || "\u2699\uFE0F" }) }),
2254
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react_native5.View, { style: styles.info, children: [
2255
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.Text, { style: styles.name, children: name }),
2256
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.Text, { style: styles.description, children: description })
2257
+ ] }),
2258
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
2259
+ import_react_native5.Switch,
2260
+ {
2261
+ value: enabled,
2262
+ onValueChange: handleToggle,
2263
+ trackColor: { false: import_core2.ada.border, true: import_core2.ada.orange },
2264
+ thumbColor: "#fff",
2265
+ ios_backgroundColor: import_core2.ada.border
2266
+ }
2267
+ )
2268
+ ] }),
2269
+ enabled && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.Text, { style: styles.reason, children: reason }),
2270
+ enabled && requiresPermission && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.View, { style: styles.statusRow, children: isDenied ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.Pressable, { onPress: () => import_react_native5.Linking.openSettings(), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.View, { style: styles.deniedBadge, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.Text, { style: styles.deniedText, children: "Blocked \u2014 tap to open Settings" }) }) }) : isGranted ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.View, { style: styles.grantedBadge, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.Text, { style: styles.grantedText, children: "Active" }) }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.View, { style: styles.pendingBadge, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native5.Text, { style: styles.pendingText, children: "Will ask permission" }) }) })
2271
+ ] });
2272
+ }
2273
+ var styles = import_react_native5.StyleSheet.create({
2274
+ card: {
2275
+ backgroundColor: import_core2.ada.paperSoft,
2276
+ borderRadius: import_core2.borderRadius.lg,
2277
+ borderWidth: 1,
2278
+ borderColor: import_core2.ada.border,
2279
+ padding: import_core2.spacing.lg,
2280
+ marginBottom: import_core2.spacing.md
2281
+ },
2282
+ cardEnabled: {
2283
+ borderColor: import_core2.ada.orange,
2284
+ borderWidth: 1.5
2285
+ },
2286
+ row: {
2287
+ flexDirection: "row",
2288
+ alignItems: "center",
2289
+ gap: import_core2.spacing.md
2290
+ },
2291
+ iconBox: {
2292
+ width: 44,
2293
+ height: 44,
2294
+ borderRadius: 12,
2295
+ backgroundColor: import_core2.ada.paperDeep,
2296
+ justifyContent: "center",
2297
+ alignItems: "center"
2298
+ },
2299
+ iconBoxEnabled: {
2300
+ backgroundColor: import_core2.ada.orangeSoft
2301
+ },
2302
+ iconText: {
2303
+ fontSize: 20
2304
+ },
2305
+ info: {
2306
+ flex: 1
2307
+ },
2308
+ name: {
2309
+ color: import_core2.ada.ink,
2310
+ fontSize: import_core2.fontSize.lg,
2311
+ fontWeight: "600",
2312
+ fontFamily: fontFam,
2313
+ letterSpacing: -0.2
2314
+ },
2315
+ description: {
2316
+ color: import_core2.ada.inkSoft,
2317
+ fontSize: import_core2.fontSize.sm,
2318
+ marginTop: 2,
2319
+ lineHeight: 18,
2320
+ fontFamily: fontFam,
2321
+ letterSpacing: -0.05
2322
+ },
2323
+ reason: {
2324
+ color: import_core2.ada.inkMuted,
2325
+ fontSize: import_core2.fontSize.xs,
2326
+ marginTop: import_core2.spacing.sm,
2327
+ marginLeft: 44 + import_core2.spacing.md,
2328
+ lineHeight: 16,
2329
+ fontFamily: fontFam
2330
+ },
2331
+ statusRow: {
2332
+ marginTop: import_core2.spacing.sm,
2333
+ marginLeft: 44 + import_core2.spacing.md
2334
+ },
2335
+ grantedBadge: {
2336
+ backgroundColor: "rgba(90, 138, 92, 0.14)",
2337
+ borderRadius: import_core2.borderRadius.sm,
2338
+ paddingHorizontal: import_core2.spacing.sm,
2339
+ paddingVertical: 3,
2340
+ alignSelf: "flex-start"
2341
+ },
2342
+ grantedText: {
2343
+ color: "#5A8A5C",
2344
+ fontSize: import_core2.fontSize.xs,
2345
+ fontWeight: "700",
2346
+ fontFamily: fontFam,
2347
+ letterSpacing: 0.2
2348
+ },
2349
+ pendingBadge: {
2350
+ backgroundColor: import_core2.ada.orangeSoft,
2351
+ borderRadius: import_core2.borderRadius.sm,
2352
+ paddingHorizontal: import_core2.spacing.sm,
2353
+ paddingVertical: 3,
2354
+ alignSelf: "flex-start"
2355
+ },
2356
+ pendingText: {
2357
+ color: import_core2.ada.orangeDeep,
2358
+ fontSize: import_core2.fontSize.xs,
2359
+ fontWeight: "700",
2360
+ fontFamily: fontFam,
2361
+ letterSpacing: 0.2
2362
+ },
2363
+ deniedBadge: {
2364
+ backgroundColor: "rgba(193, 85, 69, 0.14)",
2365
+ borderRadius: import_core2.borderRadius.sm,
2366
+ paddingHorizontal: import_core2.spacing.sm,
2367
+ paddingVertical: 3,
2368
+ alignSelf: "flex-start"
2369
+ },
2370
+ deniedText: {
2371
+ color: "#C15545",
2372
+ fontSize: import_core2.fontSize.xs,
2373
+ fontWeight: "700",
2374
+ fontFamily: fontFam,
2375
+ letterSpacing: 0.2
2376
+ }
2377
+ });
2378
+
2379
+ // src/capabilities/CapabilitiesSetup.tsx
2380
+ var import_jsx_runtime2 = require("react/jsx-runtime");
2381
+ var fontFam2 = import_react_native6.Platform.OS === "ios" ? "SF Pro Rounded" : void 0;
2382
+ function CapabilitiesSetup({
2383
+ onComplete,
2384
+ header,
2385
+ title = "What can the assistant use?",
2386
+ subtitle = "Choose what it can see on this device. You're in charge \u2014 change it anytime in settings.",
2387
+ loading
2388
+ }) {
2389
+ const {
2390
+ capabilities,
2391
+ toggleCapability,
2392
+ completeSetup,
2393
+ isLoading
2394
+ } = useCapabilitiesStore();
2395
+ const [requesting, setRequesting] = (0, import_react.useState)(false);
2396
+ const enabledCount = capabilities.filter((c) => c.enabled).length;
2397
+ const permissionCount = capabilities.filter((c) => c.enabled && c.requiresPermission).length;
2398
+ const handleContinue = async () => {
2399
+ setRequesting(true);
2400
+ await completeSetup();
2401
+ setRequesting(false);
2402
+ onComplete();
2403
+ };
2404
+ const handleSkip = async () => {
2405
+ for (const cap of capabilities) {
2406
+ if (cap.enabled) {
2407
+ await toggleCapability(cap.id, false);
2408
+ }
2409
+ }
2410
+ await completeSetup();
2411
+ onComplete();
2412
+ };
2413
+ if (isLoading) {
2414
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native6.SafeAreaView, { style: styles2.center, children: loading ?? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native6.ActivityIndicator, { size: "large", color: import_core3.ada.inkMuted }) });
2415
+ }
2416
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_react_native6.SafeAreaView, { style: styles2.container, children: [
2417
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_react_native6.ScrollView, { contentContainerStyle: styles2.content, children: [
2418
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_react_native6.View, { style: styles2.header, children: [
2419
+ header ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native6.View, { style: styles2.heroRow, children: header }) : null,
2420
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native6.Text, { style: styles2.title, children: title }),
2421
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native6.Text, { style: styles2.subtitle, children: subtitle })
2422
+ ] }),
2423
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_react_native6.View, { style: styles2.section, children: [
2424
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native6.Text, { style: styles2.sectionTitle, children: "NEEDS YOUR PERMISSION" }),
2425
+ capabilities.filter((c) => c.requiresPermission).map((cap) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2426
+ CapabilityCard,
2427
+ {
2428
+ capability: cap,
2429
+ onToggle: toggleCapability
2430
+ },
2431
+ cap.id
2432
+ ))
2433
+ ] }),
2434
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_react_native6.View, { style: styles2.section, children: [
2435
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native6.Text, { style: styles2.sectionTitle, children: "ALWAYS AVAILABLE" }),
2436
+ capabilities.filter((c) => !c.requiresPermission).map((cap) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2437
+ CapabilityCard,
2438
+ {
2439
+ capability: cap,
2440
+ onToggle: toggleCapability
2441
+ },
2442
+ cap.id
2443
+ ))
2444
+ ] }),
2445
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native6.View, { style: styles2.summaryBox, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_react_native6.Text, { style: styles2.summaryText, children: [
2446
+ enabledCount,
2447
+ " of ",
2448
+ capabilities.length,
2449
+ " on",
2450
+ permissionCount > 0 && ` \xB7 ${permissionCount} will ask for permission`
2451
+ ] }) })
2452
+ ] }),
2453
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_react_native6.View, { style: styles2.footer, children: [
2454
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2455
+ import_react_native6.Pressable,
2456
+ {
2457
+ style: [styles2.continueBtn, requesting && styles2.continueBtnDisabled],
2458
+ onPress: handleContinue,
2459
+ disabled: requesting,
2460
+ children: requesting ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native6.ActivityIndicator, { size: "small", color: import_core3.ada.paper }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native6.Text, { style: styles2.continueBtnText, children: enabledCount > 0 ? "Continue" : "Continue without these" })
2461
+ }
2462
+ ),
2463
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native6.Pressable, { style: styles2.skipBtn, onPress: handleSkip, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native6.Text, { style: styles2.skipBtnText, children: "Skip for now" }) })
2464
+ ] })
2465
+ ] });
2466
+ }
2467
+ var styles2 = import_react_native6.StyleSheet.create({
2468
+ container: {
2469
+ flex: 1,
2470
+ backgroundColor: import_core3.ada.paper
2471
+ },
2472
+ center: {
2473
+ flex: 1,
2474
+ justifyContent: "center",
2475
+ alignItems: "center",
2476
+ backgroundColor: import_core3.ada.paper
2477
+ },
2478
+ content: {
2479
+ paddingBottom: 20
2480
+ },
2481
+ header: {
2482
+ paddingHorizontal: import_core3.spacing.xl,
2483
+ paddingTop: 20,
2484
+ paddingBottom: import_core3.spacing.lg
2485
+ },
2486
+ heroRow: {
2487
+ flexDirection: "row",
2488
+ alignItems: "center",
2489
+ gap: 10,
2490
+ marginBottom: import_core3.spacing.lg
2491
+ },
2492
+ title: {
2493
+ color: import_core3.ada.ink,
2494
+ fontSize: 28,
2495
+ fontWeight: "700",
2496
+ letterSpacing: -0.5,
2497
+ marginBottom: 8,
2498
+ fontFamily: fontFam2
2499
+ },
2500
+ subtitle: {
2501
+ color: import_core3.ada.inkSoft,
2502
+ fontSize: import_core3.fontSize.md,
2503
+ lineHeight: 22,
2504
+ letterSpacing: -0.1,
2505
+ fontFamily: fontFam2
2506
+ },
2507
+ section: {
2508
+ paddingHorizontal: import_core3.spacing.lg,
2509
+ marginBottom: import_core3.spacing.lg
2510
+ },
2511
+ sectionTitle: {
2512
+ color: import_core3.ada.inkMuted,
2513
+ fontSize: 11,
2514
+ fontWeight: "700",
2515
+ letterSpacing: 1.4,
2516
+ marginBottom: import_core3.spacing.sm,
2517
+ paddingHorizontal: 4,
2518
+ fontFamily: fontFam2
2519
+ },
2520
+ summaryBox: {
2521
+ marginHorizontal: import_core3.spacing.lg,
2522
+ backgroundColor: import_core3.ada.orangeSoft,
2523
+ borderRadius: import_core3.borderRadius.md,
2524
+ padding: import_core3.spacing.md,
2525
+ alignItems: "center"
2526
+ },
2527
+ summaryText: {
2528
+ color: import_core3.ada.orangeDeep,
2529
+ fontSize: import_core3.fontSize.sm,
2530
+ fontWeight: "600",
2531
+ fontFamily: fontFam2,
2532
+ letterSpacing: -0.1
2533
+ },
2534
+ footer: {
2535
+ paddingHorizontal: import_core3.spacing.lg,
2536
+ paddingVertical: import_core3.spacing.lg,
2537
+ borderTopWidth: 1,
2538
+ borderTopColor: import_core3.ada.border,
2539
+ gap: import_core3.spacing.sm
2540
+ },
2541
+ continueBtn: {
2542
+ backgroundColor: import_core3.ada.ink,
2543
+ borderRadius: 999,
2544
+ paddingVertical: 16,
2545
+ alignItems: "center"
2546
+ },
2547
+ continueBtnDisabled: {
2548
+ opacity: 0.6
2549
+ },
2550
+ continueBtnText: {
2551
+ color: import_core3.ada.paper,
2552
+ fontSize: import_core3.fontSize.lg,
2553
+ fontWeight: "600",
2554
+ fontFamily: fontFam2,
2555
+ letterSpacing: -0.2
2556
+ },
2557
+ skipBtn: {
2558
+ paddingVertical: 12,
2559
+ alignItems: "center"
2560
+ },
2561
+ skipBtnText: {
2562
+ color: import_core3.ada.inkMuted,
2563
+ fontSize: import_core3.fontSize.md,
2564
+ fontFamily: fontFam2
2565
+ }
2566
+ });
2567
+ // Annotate the CommonJS export names for ESM import in node:
2568
+ 0 && (module.exports = {
2569
+ CapabilitiesSetup,
2570
+ CapabilityCard,
2571
+ configureDeviceSync,
2572
+ useCapabilitiesStore
2573
+ });
2574
+ //# sourceMappingURL=index.js.map