@ateam-ai-mobile/expo 0.1.21 → 0.1.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aiLive/provider.d.mts +10 -4
- package/dist/aiLive/provider.d.ts +10 -4
- package/dist/aiLive/provider.js +119 -43
- package/dist/aiLive/provider.js.map +1 -1
- package/dist/aiLive/provider.mjs +5 -3
- package/dist/bootstrap.js +120 -46
- package/dist/bootstrap.js.map +1 -1
- package/dist/bootstrap.mjs +4 -4
- package/dist/capabilities/index.js +19 -1
- package/dist/capabilities/index.js.map +1 -1
- package/dist/capabilities/index.mjs +21 -3
- package/dist/capabilities/index.mjs.map +1 -1
- package/dist/{chunk-BAZFMTCC.mjs → chunk-4HJ5FO3S.mjs} +2 -2
- package/dist/{chunk-C62NQA4F.mjs → chunk-GGEFDRQQ.mjs} +2 -2
- package/dist/chunk-GGEFDRQQ.mjs.map +1 -0
- package/dist/{chunk-OEX4OKYQ.mjs → chunk-NH3CHSLR.mjs} +2 -2
- package/dist/{chunk-JUBLG3PN.mjs → chunk-PV2EHH2P.mjs} +119 -44
- package/dist/chunk-PV2EHH2P.mjs.map +1 -0
- package/dist/device/createDeviceProvider.mjs +3 -3
- package/dist/device-bridge/index.js +1 -1
- package/dist/device-bridge/index.js.map +1 -1
- package/dist/device-bridge/index.mjs +2 -2
- package/dist/push/silentSync.js.map +1 -1
- package/dist/push/silentSync.mjs +1 -1
- package/package.json +4 -4
- package/src/aiLive/provider.ts +138 -49
- package/src/aiLive/streamProtocol.ts +2 -2
- package/src/capabilities/store.ts +21 -1
- package/src/device-bridge/capabilities.ts +2 -1
- package/dist/chunk-C62NQA4F.mjs.map +0 -1
- package/dist/chunk-JUBLG3PN.mjs.map +0 -1
- /package/dist/{chunk-BAZFMTCC.mjs.map → chunk-4HJ5FO3S.mjs.map} +0 -0
- /package/dist/{chunk-OEX4OKYQ.mjs.map → chunk-NH3CHSLR.mjs.map} +0 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ateam-ai-mobile/expo",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.23",
|
|
4
4
|
"description": "Expo-backed providers for the ADAS SDK \u2014 haptics, bundle disk cache, attachment cache, device bridge.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -9,9 +9,9 @@
|
|
|
9
9
|
"build": "tsup"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@ateam-ai-mobile/core": "0.1.
|
|
13
|
-
"@ateam-ai-mobile/plugin-runtime": "0.1.
|
|
14
|
-
"@ateam-ai-mobile/ui": "0.1.
|
|
12
|
+
"@ateam-ai-mobile/core": "0.1.23",
|
|
13
|
+
"@ateam-ai-mobile/plugin-runtime": "0.1.23",
|
|
14
|
+
"@ateam-ai-mobile/ui": "0.1.23",
|
|
15
15
|
"zustand": "^5.0.0"
|
|
16
16
|
},
|
|
17
17
|
"peerDependencies": {
|
package/src/aiLive/provider.ts
CHANGED
|
@@ -4,29 +4,32 @@
|
|
|
4
4
|
* import { createAiLiveProvider } from '@ateam-ai-mobile/expo/ai-live';
|
|
5
5
|
* setAiLiveProvider(createAiLiveProvider());
|
|
6
6
|
* A plugin reaches it only through props.aiLive,
|
|
7
|
-
* whose gate (plugin-runtime aiLiveHost) has already checked the two-sided consent.
|
|
7
|
+
* whose gate (plugin-runtime aiLiveHost) has already checked the two-sided consent. The gate
|
|
8
|
+
* passes that check as ctx.allowed, and it is asked again right before every picture: once the
|
|
9
|
+
* person takes the yes back, nothing more is sent and the session stops (GPT review 2026-10-30).
|
|
8
10
|
*
|
|
9
11
|
* One camera, one sender: while one screen sends, another's start() is refused by name.
|
|
10
12
|
*
|
|
11
|
-
* start():
|
|
12
|
-
* 1.
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
* fresh frame, or while the socket is still busy,
|
|
20
|
-
* number, so Core reports it as a gap;
|
|
21
|
-
*
|
|
13
|
+
* ONE CONNECTION IS THE SESSION (owner direction 2026-10-30). start():
|
|
14
|
+
* 1. opens Core's stream endpoint (/ws/stream, kind "ai-models.live", the login in the
|
|
15
|
+
* subprotocol) asking for a session of its own (params.session "own"). That one round trip
|
|
16
|
+
* IS starting the person's live session: Core starts it with its own $0.50 cap, refuses in
|
|
17
|
+
* plain words when the person already has one running (never joins), and says how to send
|
|
18
|
+
* ({"event":"session"}: the rate and size the setup was tested at) before "opened";
|
|
19
|
+
* 2. turns on the screen's held camera on the requested side;
|
|
20
|
+
* 3. sends one picture per slot at that rate and size, from the newest fresh frame, as a JPEG
|
|
21
|
+
* made by native (jpegById). A slot with no fresh frame, or while the socket is still busy,
|
|
22
|
+
* sends nothing and still takes its sequence number, so Core reports it as a gap;
|
|
23
|
+
* 4. {"event":"episode"} from Core → the screen's onEpisode callbacks.
|
|
24
|
+
* stop() closes the connection and the camera; Core ends the session when the connection ends,
|
|
25
|
+
* whatever ended it (a stop, the screen closing, the app killed, the network lost).
|
|
22
26
|
*/
|
|
23
|
-
import { getCoreWsUrl, getTenant, getToken
|
|
27
|
+
import { getCoreWsUrl, getTenant, getToken } from '@ateam-ai-mobile/core';
|
|
28
|
+
import { CONSENT_TAKEN_BACK } from '@ateam-ai-mobile/plugin-runtime';
|
|
24
29
|
import type { AiLiveEpisode, AiLiveProvider, AiLiveSnapshot, AiLiveStartOptions, DeviceState, Subscription } from '@ateam-ai-mobile/plugin-runtime';
|
|
25
30
|
import { jpegById as nativeJpegById } from '../vision';
|
|
26
31
|
import { CLOSE_MESSAGE, STREAM_PATH, SUBPROTOCOL, base64ToBytes, describeClose, encodeFrame, openMessage, parseServerEvent } from './streamProtocol';
|
|
27
32
|
|
|
28
|
-
/** The most one phone session may spend (owner decision 2026-10-29), held from the AI Models budget. */
|
|
29
|
-
export const PHONE_SLICE_USD = 0.5;
|
|
30
33
|
export const LIVE_KIND = 'ai-models.live';
|
|
31
34
|
/** A frame older than this is not "what the camera sees now" and is not sent. */
|
|
32
35
|
const FRESH_MS = 3000;
|
|
@@ -37,7 +40,6 @@ const DEFAULT_CAMERA = { fps: 1, maxPx: 768 };
|
|
|
37
40
|
type Visual = DeviceState['visual'];
|
|
38
41
|
|
|
39
42
|
export interface AiLiveDeps {
|
|
40
|
-
callCp(method: string, params?: Record<string, unknown>): Promise<any>;
|
|
41
43
|
WebSocketImpl: any;
|
|
42
44
|
wsBase(): string;
|
|
43
45
|
token(): string | null;
|
|
@@ -46,21 +48,23 @@ export interface AiLiveDeps {
|
|
|
46
48
|
now(): number;
|
|
47
49
|
setInterval(fn: () => void, ms: number): any;
|
|
48
50
|
clearInterval(handle: any): void;
|
|
51
|
+
setTimeout(fn: () => void, ms: number): any;
|
|
52
|
+
clearTimeout(handle: any): void;
|
|
49
53
|
}
|
|
50
54
|
|
|
51
|
-
|
|
55
|
+
/** Core answers "opened" in one round trip (it starts the session first). Past this, the start gives up
|
|
56
|
+
* and closes the connection, so a start can never hang a screen's queue. */
|
|
57
|
+
export const OPEN_TIMEOUT_MS = 20_000;
|
|
58
|
+
/** A stop waits this long, at most, for its connection to finish closing: Core ends the session when it
|
|
59
|
+
* sees the close, so a restart right after a stop must not open the next one before (Codex on #53).
|
|
60
|
+
* Past this the transport is taken as broken, and Core's own 60 s rule ends that session. */
|
|
61
|
+
export const CLOSE_WAIT_MS = 3_000;
|
|
52
62
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
const out = unwrapMcpResult(res?.result);
|
|
57
|
-
if (res?.result?.isError) throw new Error(typeof out === 'string' ? out : out?.message || out?.error || 'AI Models refused the request');
|
|
58
|
-
if (out && typeof out === 'object' && out.ok === false) throw new Error(out.message || out.error || 'AI Models refused the request');
|
|
59
|
-
return out;
|
|
60
|
-
}
|
|
63
|
+
const isEpisode = (d: any): d is AiLiveEpisode =>
|
|
64
|
+
!!d && typeof d === 'object' && typeof d.type === 'string' && typeof d.class === 'string' &&
|
|
65
|
+
typeof d.episodeId === 'string' && typeof d.actorId === 'string' && d.actorId.length > 0 && Number.isFinite(d.at);
|
|
61
66
|
|
|
62
67
|
export const defaultAiLiveDeps = (): AiLiveDeps => ({
|
|
63
|
-
callCp: defaultCallCp,
|
|
64
68
|
WebSocketImpl: (globalThis as any).WebSocket,
|
|
65
69
|
wsBase: getCoreWsUrl,
|
|
66
70
|
token: getToken,
|
|
@@ -69,6 +73,8 @@ export const defaultAiLiveDeps = (): AiLiveDeps => ({
|
|
|
69
73
|
now: Date.now,
|
|
70
74
|
setInterval: (fn, ms) => setInterval(fn, ms),
|
|
71
75
|
clearInterval: (h) => clearInterval(h),
|
|
76
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
77
|
+
clearTimeout: (h) => clearTimeout(h),
|
|
72
78
|
});
|
|
73
79
|
|
|
74
80
|
const idle = (): AiLiveSnapshot => ({ state: 'idle', camera: null, sent: 0, skipped: 0, lastEpisode: null, lastError: null });
|
|
@@ -80,7 +86,17 @@ export function createAiLiveProvider(overrides: Partial<AiLiveDeps> = {}): AiLiv
|
|
|
80
86
|
let ws: any = null;
|
|
81
87
|
let loop: any = null;
|
|
82
88
|
let visual: Visual | null = null;
|
|
83
|
-
let
|
|
89
|
+
let allowed: () => boolean = () => false; // the two-sided consent, asked before every picture
|
|
90
|
+
let stopReason: string | null = null; // why the last teardown happened, known before it finishes
|
|
91
|
+
// A teardown still finishing (the camera, the connection): a start waits for it, so a quick restart neither
|
|
92
|
+
// reads the old session as its own nor is cleared by it afterwards (Codex on #53). Every teardown is
|
|
93
|
+
// tracked, the ones the provider starts itself (consent gone, the connection dropped) included.
|
|
94
|
+
let tearingDown: Promise<void> | null = null;
|
|
95
|
+
// Screens whose start is waiting for that teardown, before they own anything: a stop meanwhile cancels
|
|
96
|
+
// the start (it would otherwise go ahead after the screen had stopped or closed; Codex on #53).
|
|
97
|
+
const waitingToStart = new Map<string, { cancelled: boolean }>();
|
|
98
|
+
/** Each connection's "it has closed": a stop waits for it (CLOSE_WAIT_MS at most). */
|
|
99
|
+
const closedOf = new WeakMap<object, Promise<void>>();
|
|
84
100
|
let closingOnPurpose = false;
|
|
85
101
|
let seq = 0;
|
|
86
102
|
let busy = false;
|
|
@@ -118,6 +134,8 @@ export function createAiLiveProvider(overrides: Partial<AiLiveDeps> = {}): AiLiv
|
|
|
118
134
|
const g = gen;
|
|
119
135
|
const sock = ws;
|
|
120
136
|
const current = () => g === gen && ws === sock && sock?.readyState === 1;
|
|
137
|
+
const consentGone = () => { if (allowed()) return false; if (g === gen) void teardown('stopped', CONSENT_TAKEN_BACK); return true; };
|
|
138
|
+
if (consentGone()) return;
|
|
121
139
|
if (busy || !current()) { set({ skipped: snap.skipped + 1 }); return; }
|
|
122
140
|
if ((sock.bufferedAmount || 0) > MAX_BUFFERED) { set({ skipped: snap.skipped + 1 }); return; }
|
|
123
141
|
busy = true;
|
|
@@ -129,7 +147,7 @@ export function createAiLiveProvider(overrides: Partial<AiLiveDeps> = {}): AiLiv
|
|
|
129
147
|
const t = Number(f?.timestamp);
|
|
130
148
|
if (!id || id === lastFrameId || !(deps.now() - t < FRESH_MS)) { set({ skipped: snap.skipped + 1 }); return; }
|
|
131
149
|
const b64 = await deps.jpegById(id, camera.maxPx, 0.7);
|
|
132
|
-
if (!current()) return;
|
|
150
|
+
if (!current() || consentGone()) return;
|
|
133
151
|
const frame = encodeFrame({ seq: mySeq, tCapture: t, payload: base64ToBytes(b64) });
|
|
134
152
|
sock.send(frame.buffer);
|
|
135
153
|
lastFrameId = id;
|
|
@@ -151,30 +169,62 @@ export function createAiLiveProvider(overrides: Partial<AiLiveDeps> = {}): AiLiv
|
|
|
151
169
|
const sock = new deps.WebSocketImpl(url, [SUBPROTOCOL, `adas.bearer.${token}`]);
|
|
152
170
|
ws = sock;
|
|
153
171
|
sock.binaryType = 'arraybuffer';
|
|
154
|
-
|
|
172
|
+
let markClosed: () => void = () => {};
|
|
173
|
+
closedOf.set(sock, new Promise<void>((r) => { markClosed = r; }));
|
|
174
|
+
const gaveUp = deps.setTimeout(() => {
|
|
175
|
+
if (opened) return;
|
|
176
|
+
reject(new Error('Core did not answer in time. Try again.'));
|
|
177
|
+
try { sock.close(); } catch { /* closing anyway */ }
|
|
178
|
+
}, OPEN_TIMEOUT_MS);
|
|
179
|
+
// Its own session: opening IS starting it, and Core ends it when this connection ends.
|
|
180
|
+
sock.onopen = () => { try { sock.send(openMessage(LIVE_KIND, { session: 'own', source: 'phone' })); } catch (e) { reject(e); } };
|
|
155
181
|
sock.onmessage = (m: any) => {
|
|
182
|
+
// Only the current connection speaks for the current session. A message from a connection
|
|
183
|
+
// already stopped or replaced (it can still be queued after a stop, a restart or a switch to
|
|
184
|
+
// another screen) is dropped whole: its episode never reaches a newer screen, and its "session"
|
|
185
|
+
// or "opened" never touches a newer connection (GPT code review v5).
|
|
186
|
+
if (ws !== sock) return;
|
|
156
187
|
const ev = parseServerEvent(m?.data);
|
|
157
188
|
if (!ev) return;
|
|
158
|
-
if (ev.event === '
|
|
159
|
-
|
|
160
|
-
|
|
189
|
+
if (ev.event === 'session' && !opened) {
|
|
190
|
+
const c = ev.data?.camera;
|
|
191
|
+
camera = c && Number(c.fps) > 0 && Number(c.maxPx) > 0 ? { fps: Number(c.fps), maxPx: Number(c.maxPx) } : DEFAULT_CAMERA;
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (ev.event === 'opened' && !opened) { opened = true; deps.clearTimeout(gaveUp); resolve(); return; }
|
|
195
|
+
// Only a whole episode reaches the screen: what happened, of which class, and whose camera saw it
|
|
196
|
+
// (actorId: live sessions are per person). Anything less is dropped, never passed on half-made.
|
|
197
|
+
if (ev.event === 'episode' && isEpisode(ev.data)) {
|
|
198
|
+
const episode = ev.data;
|
|
161
199
|
set({ lastEpisode: episode });
|
|
162
200
|
for (const cb of (owner && episodeCbs.get(owner)) || []) { try { cb(episode); } catch { /* a listener's error is its own */ } }
|
|
163
201
|
}
|
|
164
202
|
};
|
|
165
203
|
sock.onerror = () => { /* the close that follows says why */ };
|
|
166
204
|
sock.onclose = (c: any) => {
|
|
205
|
+
markClosed();
|
|
167
206
|
const why = describeClose(Number(c?.code), c?.reason);
|
|
168
|
-
if (!opened) { reject(new Error(why)); return; }
|
|
207
|
+
if (!opened) { deps.clearTimeout(gaveUp); reject(new Error(why)); return; }
|
|
169
208
|
if (closingOnPurpose || ws !== sock) return;
|
|
170
209
|
void teardown('error', why);
|
|
171
210
|
};
|
|
172
211
|
});
|
|
173
212
|
}
|
|
174
213
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
214
|
+
function teardown(state: 'stopped' | 'error', lastError: string | null): Promise<void> {
|
|
215
|
+
// One at a time: a second stop while one is finishing joins it (Codex on #53). Two at once could
|
|
216
|
+
// finish out of order and the first, resuming late, would stop a session started in between.
|
|
217
|
+
if (tearingDown) return tearingDown;
|
|
218
|
+
const p = teardownNow(state, lastError);
|
|
219
|
+
tearingDown = p;
|
|
220
|
+
void p.then(() => {}, () => {}).then(() => { if (tearingDown === p) tearingDown = null; });
|
|
221
|
+
return p;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Closing the connection ends the session (Core); the camera is this phone's to stop.
|
|
225
|
+
async function teardownNow(state: 'stopped' | 'error', lastError: string | null) {
|
|
226
|
+
stopReason = lastError;
|
|
227
|
+
allowed = () => false;
|
|
178
228
|
gen++;
|
|
179
229
|
stopTimers();
|
|
180
230
|
const sock = ws;
|
|
@@ -185,14 +235,31 @@ export function createAiLiveProvider(overrides: Partial<AiLiveDeps> = {}): AiLiv
|
|
|
185
235
|
closingOnPurpose = false;
|
|
186
236
|
const v = visual;
|
|
187
237
|
visual = null;
|
|
188
|
-
|
|
189
|
-
|
|
238
|
+
// The camera off, and the connection really closed (so Core has ended its session) before this stop
|
|
239
|
+
// is done: a start right after it then never meets the old session (Codex on #53).
|
|
240
|
+
let gaveUp: any = null;
|
|
241
|
+
const closed = sock && closedOf.get(sock);
|
|
242
|
+
await Promise.all([
|
|
243
|
+
(async () => { try { await v?.stop?.(); } catch { /* the camera hold is released by the gate too */ } })(),
|
|
244
|
+
closed ? Promise.race([closed, new Promise<void>((r) => { gaveUp = deps.setTimeout(r, CLOSE_WAIT_MS); })]) : Promise.resolve(),
|
|
245
|
+
]);
|
|
246
|
+
if (gaveUp != null) deps.clearTimeout(gaveUp);
|
|
190
247
|
owner = null;
|
|
191
248
|
set({ state, lastError });
|
|
192
249
|
}
|
|
193
250
|
|
|
194
251
|
return {
|
|
195
|
-
async start(opts: AiLiveStartOptions, who: string, ctx: { visual: Visual }) {
|
|
252
|
+
async start(opts: AiLiveStartOptions, who: string, ctx: { visual: Visual; allowed: () => boolean }) {
|
|
253
|
+
if (tearingDown) {
|
|
254
|
+
const wait = { cancelled: false };
|
|
255
|
+
waitingToStart.set(who, wait);
|
|
256
|
+
try {
|
|
257
|
+
while (tearingDown) { try { await tearingDown; } catch { /* it stopped either way */ } }
|
|
258
|
+
} finally {
|
|
259
|
+
if (waitingToStart.get(who) === wait) waitingToStart.delete(who);
|
|
260
|
+
}
|
|
261
|
+
if (wait.cancelled) throw Object.assign(new Error('aiLive: stopped before it started.'), { code: 'STOPPED' });
|
|
262
|
+
}
|
|
196
263
|
if (owner && owner !== who) throw Object.assign(new Error('aiLive: another screen is sending to AI right now. Close it first.'), { code: 'CONFLICT' });
|
|
197
264
|
if (owner === who) return snap;
|
|
198
265
|
const cam = opts?.camera === 'front' ? 'front' : 'back';
|
|
@@ -200,30 +267,52 @@ export function createAiLiveProvider(overrides: Partial<AiLiveDeps> = {}): AiLiv
|
|
|
200
267
|
owner = who;
|
|
201
268
|
lastOwner = who;
|
|
202
269
|
visual = ctx.visual;
|
|
270
|
+
allowed = typeof ctx.allowed === 'function' ? ctx.allowed : () => false;
|
|
203
271
|
gen++; seq = 0; lastFrameId = null; busy = false;
|
|
272
|
+
const g = gen;
|
|
273
|
+
const cameraOfScreen = ctx.visual;
|
|
204
274
|
snap = { ...idle(), camera: cam };
|
|
205
275
|
set({ state: 'starting' });
|
|
276
|
+
// Starting takes several awaits, and the screen may be stopped, or the yes taken back,
|
|
277
|
+
// during any of them (Codex P1 on #53). After each: a stop already tore it down, so say why
|
|
278
|
+
// and go no further; a yes taken back unannounced tears it down here.
|
|
279
|
+
const stillStarting = async () => {
|
|
280
|
+
if (g === gen && !allowed()) await teardown('stopped', CONSENT_TAKEN_BACK);
|
|
281
|
+
if (g !== gen) throw Object.assign(new Error(stopReason || 'aiLive: stopped before it started sending.'), { code: 'STOPPED' });
|
|
282
|
+
};
|
|
206
283
|
try {
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
await visual.start({ intent: 'stream', facing: cam } as any);
|
|
284
|
+
await stillStarting();
|
|
285
|
+
// One round trip: the connection starts the session (or Core refuses, in its own words), and
|
|
286
|
+
// says how to send. Before the camera, so a refusal never turns the camera on.
|
|
287
|
+
camera = DEFAULT_CAMERA;
|
|
288
|
+
// Checked again with nothing in between: a stop that landed while the check above resolved has
|
|
289
|
+
// already torn this start down, and opening now would start a session nobody closes (Codex on #53).
|
|
290
|
+
if (g !== gen) throw Object.assign(new Error(stopReason || 'aiLive: stopped before it started sending.'), { code: 'STOPPED' });
|
|
215
291
|
await openSocket();
|
|
292
|
+
await stillStarting();
|
|
293
|
+
await cameraOfScreen.start({ intent: 'stream', facing: cam } as any);
|
|
294
|
+
if (g !== gen) { try { await cameraOfScreen.stop?.(); } catch { /* released by the gate too */ } }
|
|
295
|
+
await stillStarting();
|
|
296
|
+
// Again with nothing in between: a stop that landed while the last check resolved must not see
|
|
297
|
+
// pictures start or the state flip back to "sending" (Codex on #53).
|
|
298
|
+
if (g !== gen) throw Object.assign(new Error(stopReason || 'aiLive: stopped before it started sending.'), { code: 'STOPPED' });
|
|
216
299
|
loop = deps.setInterval(() => { void slot(); }, Math.max(200, Math.round(1000 / camera.fps)));
|
|
217
300
|
set({ state: 'sending' });
|
|
218
301
|
return snap;
|
|
219
302
|
} catch (e: any) {
|
|
303
|
+
if (g !== gen) {
|
|
304
|
+
// Already torn down by a stop: report why it stopped, not the closed socket.
|
|
305
|
+
throw e?.code === 'STOPPED' ? e : Object.assign(new Error(stopReason || 'aiLive: stopped before it started sending.'), { code: 'STOPPED' });
|
|
306
|
+
}
|
|
220
307
|
await teardown('error', String(e?.message || e));
|
|
221
308
|
throw e;
|
|
222
309
|
}
|
|
223
310
|
},
|
|
224
|
-
async stop(who: string) {
|
|
311
|
+
async stop(who: string, why?: string) {
|
|
312
|
+
const waiting = waitingToStart.get(who);
|
|
313
|
+
if (waiting) waiting.cancelled = true;
|
|
225
314
|
if (owner !== who) return;
|
|
226
|
-
await teardown('stopped', null);
|
|
315
|
+
await teardown('stopped', why ?? null);
|
|
227
316
|
},
|
|
228
317
|
getSnapshot: (who: string) => (lastOwner === who ? snap : idle()),
|
|
229
318
|
onEpisode: (cb, who) => add(episodeCbs, who, cb),
|
|
@@ -39,8 +39,8 @@ export function encodeFrame({ seq, tCapture, payload }: { seq: number; tCapture:
|
|
|
39
39
|
return out;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
export function openMessage(kind: string): string {
|
|
43
|
-
return JSON.stringify({ type: 'open', kind });
|
|
42
|
+
export function openMessage(kind: string, params?: Record<string, unknown>): string {
|
|
43
|
+
return JSON.stringify(params ? { type: 'open', kind, params } : { type: 'open', kind });
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
export const CLOSE_MESSAGE = JSON.stringify({ type: 'close' });
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { create } from 'zustand';
|
|
2
2
|
import AsyncStorage from '@react-native-async-storage/async-storage';
|
|
3
3
|
import { getTenant, getUser, onAppForeground } from '@ateam-ai-mobile/core';
|
|
4
|
-
import { setPicturesToAiConsentProvider } from '@ateam-ai-mobile/plugin-runtime';
|
|
4
|
+
import { setPicturesToAiConsentProvider, notifyPicturesToAiConsentChanged } from '@ateam-ai-mobile/plugin-runtime';
|
|
5
5
|
import { DeviceBridge, capabilities as capFactories } from '../device-bridge';
|
|
6
6
|
import type { Capability, PermissionState } from '../device-bridge/types';
|
|
7
7
|
import { getOrCreateDeviceId } from '../device-bridge/deviceId';
|
|
@@ -386,3 +386,23 @@ export const useCapabilitiesStore = create<CapabilitiesState>((set, get) => {
|
|
|
386
386
|
// read from this store at CALL time (derive, never store). A host that never loads this store
|
|
387
387
|
// has no consent provider, and the answer is no.
|
|
388
388
|
setPicturesToAiConsentProvider(() => picturesToAiAllowed(useCapabilitiesStore.getState()));
|
|
389
|
+
// Any change the answer reads (the switch, the camera's own switch, the OS permission the
|
|
390
|
+
// foreground refresh re-reads) is announced, so a session that is sending re-asks at once and
|
|
391
|
+
// stops on a no (GPT review 2026-10-30). Announced on every change: the listener re-asks the
|
|
392
|
+
// derived answer, so nothing is compared or cached here.
|
|
393
|
+
useCapabilitiesStore.subscribe(() => notifyPicturesToAiConsentChanged());
|
|
394
|
+
// The camera permission is the OS's, and it can be taken away in iOS Settings while the app is in
|
|
395
|
+
// the background, where nothing in this store changes. So it is read again every time the app
|
|
396
|
+
// comes back (Codex P1 on adas-mobile-sdk#53): a change lands in the store, and the subscription
|
|
397
|
+
// above announces it.
|
|
398
|
+
export async function recheckCameraPermission(): Promise<void> {
|
|
399
|
+
const cam = builtInCapabilities.find((c) => c.id === 'camera');
|
|
400
|
+
if (!cam) return; // not initialised: no camera state to correct
|
|
401
|
+
let granted = false;
|
|
402
|
+
try { granted = (await cam.checkPermission()) === true; } catch { granted = false; }
|
|
403
|
+
const current = useCapabilitiesStore.getState().capabilities.find((c) => c.id === 'camera');
|
|
404
|
+
if (!current) return;
|
|
405
|
+
if (granted && current.osPermission !== 'granted') useCapabilitiesStore.getState().setOsPermission('camera', 'granted');
|
|
406
|
+
if (!granted && current.osPermission === 'granted') useCapabilitiesStore.getState().setOsPermission('camera', 'denied');
|
|
407
|
+
}
|
|
408
|
+
onAppForeground(() => { void recheckCameraPermission(); });
|
|
@@ -168,7 +168,8 @@ export function cameraCapability(): Capability {
|
|
|
168
168
|
name: 'Camera',
|
|
169
169
|
description:
|
|
170
170
|
"Lets ada see through your camera to guide you — reading text and describing what's in " +
|
|
171
|
-
'front of you. Frames are analysed on the phone
|
|
171
|
+
'front of you. Frames are analysed on the phone and nothing is stored; nothing is uploaded ' +
|
|
172
|
+
'unless you also turn on "Camera pictures to AI".',
|
|
172
173
|
reason: 'Powers visual guidance (Ada Guide): a live view with on-device text and scene understanding.',
|
|
173
174
|
icon: 'camera',
|
|
174
175
|
requiresPermission: true,
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/device-bridge/relay-client.ts","../src/device-bridge/collectors/location.ts","../src/device-bridge/collectors/connectivity.ts","../src/device-bridge/capabilities.ts","../src/device-bridge/collectors/calendar.ts","../src/device-bridge/collectors/contacts.ts","../src/device-bridge/collectors/battery.ts","../src/device-bridge/collectors/notifications.ts","../src/device-bridge/collectors/mood.ts","../src/device-bridge/collectors/camera.ts","../src/device-bridge/background.ts"],"sourcesContent":["/**\n * Relay Client — REST client for the cloud relay service.\n * Handles data push, action polling, and offline buffering.\n *\n * Endpoints:\n * POST /api/device/{deviceId}/sync ← push data bundle\n * GET /api/device/{deviceId}/data/{domain} ← read latest (used by connector, not phone)\n * POST /api/device/{deviceId}/actions ← queue action (used by connector)\n * GET /api/device/{deviceId}/actions ← poll pending actions\n * DELETE /api/device/{deviceId}/actions/{id} ← confirm action executed\n */\n\nimport type {\n DeviceDataBundle,\n PendingAction,\n ActionResult,\n RelayResponse,\n} from './types';\n\nexport interface RelayClientConfig {\n relayUrl: string;\n deviceId: string;\n tenant: string;\n actorId?: string;\n apiKey?: string;\n timeout?: number; // ms, default 10000\n}\n\nexport class RelayClient {\n private baseUrl: string;\n private deviceId: string;\n private tenant: string;\n private actorId: string;\n private apiKey: string;\n private timeout: number;\n private offlineQueue: DeviceDataBundle[] = [];\n\n constructor(config: RelayClientConfig) {\n // Strip trailing slash\n this.baseUrl = config.relayUrl.replace(/\\/$/, '');\n this.deviceId = config.deviceId;\n this.tenant = config.tenant;\n this.actorId = config.actorId ?? 'default';\n this.apiKey = config.apiKey ?? '';\n this.timeout = config.timeout ?? 10_000;\n }\n\n // ─── Data Sync ───\n\n /**\n * Push a full device data bundle to the relay.\n * If offline, buffers the bundle and retries on next sync.\n */\n async pushData(bundle: DeviceDataBundle): Promise<RelayResponse<void>> {\n try {\n const response = await this.fetch(\n `/api/device/${this.deviceId}/sync`,\n {\n method: 'POST',\n body: JSON.stringify(bundle),\n }\n );\n\n if (response.ok) {\n // Flush any offline queue on successful connection\n await this.flushOfflineQueue();\n return { ok: true };\n }\n\n return {\n ok: false,\n error: `Relay returned ${response.status}: ${await response.text()}`,\n };\n } catch (error) {\n // Network error — buffer for later\n this.offlineQueue.push(bundle);\n return {\n ok: false,\n error: `Offline — buffered (${this.offlineQueue.length} pending)`,\n };\n }\n }\n\n /**\n * Push a single domain update (partial sync).\n */\n async pushDomain(\n domain: string,\n data: unknown\n ): Promise<RelayResponse<void>> {\n try {\n const response = await this.fetch(\n `/api/device/${this.deviceId}/sync/${domain}`,\n {\n method: 'POST',\n body: JSON.stringify({ domain, data, timestamp: new Date().toISOString(), actorId: this.actorId }),\n }\n );\n\n if (response.ok) return { ok: true };\n return {\n ok: false,\n error: `Relay returned ${response.status}`,\n };\n } catch (error) {\n return { ok: false, error: 'Network error — domain sync failed' };\n }\n }\n\n // ─── Action Queue ───\n\n /**\n * Poll for pending actions the phone needs to execute.\n */\n async pollActions(): Promise<RelayResponse<PendingAction[]>> {\n try {\n const response = await this.fetch(\n `/api/device/${this.deviceId}/actions`,\n { method: 'GET' }\n );\n\n if (response.ok) {\n const data = await response.json();\n return { ok: true, data: data.actions ?? [] };\n }\n return { ok: false, error: `Relay returned ${response.status}` };\n } catch (error) {\n return { ok: false, error: 'Network error — action poll failed' };\n }\n }\n\n /**\n * Report action execution result and remove from queue.\n */\n async completeAction(result: ActionResult): Promise<RelayResponse<void>> {\n try {\n const response = await this.fetch(\n `/api/device/${this.deviceId}/actions/${result.id}`,\n {\n method: 'DELETE',\n body: JSON.stringify(result),\n }\n );\n\n if (response.ok) return { ok: true };\n return { ok: false, error: `Relay returned ${response.status}` };\n } catch (error) {\n return { ok: false, error: 'Network error — action complete failed' };\n }\n }\n\n // ─── Health ───\n\n /**\n * Ping the relay to check connectivity.\n */\n async ping(): Promise<boolean> {\n try {\n const response = await this.fetch(\n `/api/health`,\n { method: 'GET' },\n 3_000 // short timeout for health check\n );\n return response.ok;\n } catch {\n return false;\n }\n }\n\n /**\n * Get count of buffered offline bundles.\n */\n getOfflineQueueSize(): number {\n return this.offlineQueue.length;\n }\n\n // ─── Internal ───\n\n private async fetch(\n path: string,\n init: RequestInit,\n timeout?: number\n ): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(\n () => controller.abort(),\n timeout ?? this.timeout\n );\n\n try {\n return await fetch(`${this.baseUrl}${path}`, {\n ...init,\n signal: controller.signal,\n headers: {\n 'Content-Type': 'application/json',\n 'X-ADAS-TENANT': this.tenant,\n 'X-ADAS-ACTOR': this.actorId,\n 'X-Device-Id': this.deviceId,\n // The relay (post-2026-04-25) gates every /api/device/* call on\n // a shared secret. Send it as `Authorization: Bearer` so the\n // server's relayAuth middleware accepts the request. Empty/missing\n // secret = 401 from the relay (correct fail-closed behavior).\n ...(this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}),\n ...(init.headers || {}),\n },\n });\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async flushOfflineQueue(): Promise<void> {\n if (this.offlineQueue.length === 0) return;\n\n const queue = [...this.offlineQueue];\n this.offlineQueue = [];\n\n for (const bundle of queue) {\n try {\n const response = await this.fetch(\n `/api/device/${this.deviceId}/sync`,\n {\n method: 'POST',\n body: JSON.stringify(bundle),\n }\n );\n if (!response.ok) {\n // Put it back if still failing\n this.offlineQueue.push(bundle);\n }\n } catch {\n this.offlineQueue.push(bundle);\n break; // Stop trying if still offline\n }\n }\n }\n}\n","/**\n * Location Collector — reads device location via expo-location.\n * Output format matches device-mock-mcp's location.current schema.\n */\n\nimport * as ExpoLocation from 'expo-location';\nimport type { MapsAddress } from '@ateam-ai-mobile/plugin-runtime';\n// The SDK's one reverse geocode — the same call native.maps.reverseGeocode makes.\nimport { reverseGeocode } from '../../maps';\nimport type { LocationData } from '../types';\n\n/**\n * Request location permissions (foreground + background).\n */\nexport async function requestPermission(): Promise<boolean> {\n const { status: fg } = await ExpoLocation.requestForegroundPermissionsAsync();\n if (fg !== 'granted') return false;\n\n // Background is optional — skip in Expo Go (crashes without native module)\n try {\n await ExpoLocation.requestBackgroundPermissionsAsync();\n } catch {\n // Expected in Expo Go — foreground is enough for basic functionality\n }\n return fg === 'granted';\n}\n\n/**\n * Check if location permission is granted.\n */\nexport async function hasPermission(): Promise<boolean> {\n const { status } = await ExpoLocation.getForegroundPermissionsAsync();\n return status === 'granted';\n}\n\n/**\n * Collect current location.\n * Matches the device.location.current tool output schema.\n */\nexport async function collectCurrent(): Promise<LocationData> {\n const location = await ExpoLocation.getCurrentPositionAsync({\n accuracy: ExpoLocation.Accuracy.Balanced,\n });\n\n // Reverse geocode to get address\n let place = 'Current Location';\n let address = `${location.coords.latitude.toFixed(4)}, ${location.coords.longitude.toFixed(4)}`;\n let locationType = 'unknown';\n\n try {\n const geocoded = await reverseGeocode({\n latitude: location.coords.latitude,\n longitude: location.coords.longitude,\n });\n\n if (geocoded) {\n place = geocoded.name || geocoded.street || place;\n address = [\n geocoded.streetNumber,\n geocoded.street,\n geocoded.city,\n geocoded.region,\n ]\n .filter(Boolean)\n .join(', ') || address;\n\n // Attempt to classify location type\n locationType = classifyLocation(geocoded);\n }\n } catch {\n // Reverse geocoding can fail — use coordinates only\n }\n\n return {\n ok: true,\n timestamp: new Date().toISOString(),\n location: {\n place,\n address,\n lat: location.coords.latitude,\n lng: location.coords.longitude,\n type: locationType,\n },\n };\n}\n\n// ─── Plugin-facing position API ───\n// `collectCurrent` above answers the device-context question (\"where am I, in\n// words\") and reverse-geocodes. A plugin tool usually wants the raw fix and\n// nothing else, so these stay separate: no geocoding round trip, no address.\n\nexport interface Position {\n latitude: number;\n longitude: number;\n altitude?: number;\n accuracy?: number;\n timestamp: number;\n /**\n * Metres per second. `undefined` = the OS gave no estimate.\n *\n * iOS reports -1 rather than omitting it, and -1 m/s passed through as a\n * speed would read as \"moving backwards\"; it is normalised away here so no\n * caller has to know the platform's sentinel.\n */\n speed?: number;\n /**\n * COURSE OVER GROUND in degrees — the direction the user is TRAVELLING.\n *\n * Deliberately not called `heading`: this and the compass answer different\n * questions and disagree constantly. Walking backwards down a corridor gives\n * a course of south and a compass heading of north; a phone held sideways\n * while walking forward gives the same course and a heading 90° off.\n * \"Turn right\" needs the compass. \"You are heading north on Main Street\"\n * needs this. The old code assigned one to the other, which is only ever\n * right by accident.\n *\n * `undefined` when not moving or not estimated — iOS reports -1 for both.\n */\n course?: number;\n}\n\n/** Ensure foreground permission, asking once if we do not have it yet. */\nasync function ensurePermission(): Promise<void> {\n if (await hasPermission()) return;\n const granted = await requestPermission();\n if (!granted) {\n // Callers surface this verbatim to the user (a voice assistant reads it\n // out), so it has to say what the user can do about it.\n throw new Error(\n 'Location permission was not granted. Enable it for this app in iOS Settings > Privacy > Location Services.',\n );\n }\n}\n\n/** One position fix. `accuracy: \"high\"` costs battery and time — default low. */\nexport async function getPosition(\n opts: { accuracy?: 'low' | 'high' } = {},\n): Promise<Position> {\n await ensurePermission();\n const fix = await ExpoLocation.getCurrentPositionAsync({\n accuracy:\n opts.accuracy === 'high'\n ? ExpoLocation.Accuracy.High\n : ExpoLocation.Accuracy.Balanced,\n });\n return toPosition(fix);\n}\n\n/**\n * One place that turns an expo fix into a `Position`.\n *\n * It exists because the sentinel handling has to be identical on the one-shot\n * and the streamed path. It was not: `watchPosition` passed lat/lon only, so\n * the semantic Spatial domain could never report speed or course no matter\n * what the OS supplied, and reported `null` as if the phone had no GPS.\n */\nfunction toPosition(fix: any): Position {\n return {\n latitude: fix.coords.latitude,\n longitude: fix.coords.longitude,\n altitude: fix.coords.altitude ?? undefined,\n accuracy: nonNegative(fix.coords.accuracy),\n timestamp: fix.timestamp ?? Date.now(),\n speed: nonNegative(fix.coords.speed),\n course: nonNegative(fix.coords.heading),\n };\n}\n\n/**\n * iOS uses -1 for \"no estimate\" on accuracy, speed and course alike. Dropping\n * the field says \"not measured\"; passing -1 through says \"measured, and the\n * answer is minus one\", which a model will happily repeat.\n */\nfunction nonNegative(v: unknown): number | undefined {\n return typeof v === 'number' && v >= 0 ? v : undefined;\n}\n\nconst WATCH_TIER = {\n navigation: ExpoLocation.Accuracy.BestForNavigation,\n high: ExpoLocation.Accuracy.High,\n balanced: ExpoLocation.Accuracy.Balanced,\n low: ExpoLocation.Accuracy.Low,\n} as const;\n\n/**\n * Stream position updates. Returns an unsubscribe function — call it, or the\n * GPS keeps running and drains the battery.\n *\n * `accuracy` picks the GPS tier. The default stays Balanced (≈100 m on iOS),\n * which is right for \"which city block\" and wrong for \"turn at the next corner\":\n * a navigation session asks for BestForNavigation and pays the battery for it.\n */\nexport function watchPosition(\n cb: (pos: Position) => void,\n opts?: { accuracy?: keyof typeof WATCH_TIER },\n): () => void {\n let subscription: { remove(): void } | null = null;\n let cancelled = false;\n\n (async () => {\n try {\n await ensurePermission();\n if (cancelled) return;\n subscription = await ExpoLocation.watchPositionAsync(\n { accuracy: WATCH_TIER[opts?.accuracy ?? 'balanced'] },\n fix => cb(toPosition(fix)),\n );\n // Unsubscribed while we were still asking for permission.\n if (cancelled) { subscription?.remove(); subscription = null; }\n } catch (err: any) {\n console.warn('[location] watchPosition failed:', err?.message || String(err));\n }\n })();\n\n return () => {\n cancelled = true;\n subscription?.remove();\n subscription = null;\n };\n}\n\n// ─── Helpers ───\n\nfunction classifyLocation(geocoded: MapsAddress): string {\n // Simple heuristic — can be enhanced with user-labeled places from memory\n const name = (geocoded.name || '').toLowerCase();\n const street = (geocoded.street || '').toLowerCase();\n\n if (name.includes('home') || name.includes('residence')) return 'home';\n if (name.includes('office') || name.includes('workplace') || name.includes('tech park')) return 'work';\n if (name.includes('school') || name.includes('elementary') || name.includes('university')) return 'school';\n if (name.includes('gym') || name.includes('fitness')) return 'fitness';\n if (name.includes('hospital') || name.includes('clinic') || name.includes('dental')) return 'medical';\n\n return 'other';\n}\n","/**\n * Connectivity Collector — reads network state via expo-network.\n * Output format matches device-mock-mcp's device.connectivity schema.\n */\n\nimport * as ExpoNetwork from 'expo-network';\nimport type { ConnectivityData } from '../types';\n\n// No special permission needed for network state\n\n/**\n * Collect current connectivity status.\n * Matches the device.connectivity tool output schema.\n */\nexport async function collectConnectivity(): Promise<ConnectivityData> {\n const networkState = await ExpoNetwork.getNetworkStateAsync();\n\n let type: 'wifi' | 'cellular' | 'none' = 'none';\n let wifiName: string | undefined;\n let cellularType: string | undefined;\n\n if (networkState.type === ExpoNetwork.NetworkStateType.WIFI) {\n type = 'wifi';\n // Wi-Fi SSID requires additional permissions on newer OS versions\n // and may not always be available\n try {\n wifiName = await getWifiName();\n } catch {\n wifiName = undefined;\n }\n } else if (networkState.type === ExpoNetwork.NetworkStateType.CELLULAR) {\n type = 'cellular';\n cellularType = getCellularGeneration();\n }\n\n return {\n ok: true,\n timestamp: new Date().toISOString(),\n connectivity: {\n type,\n is_connected: networkState.isConnected ?? false,\n ...(wifiName && { wifi_name: wifiName }),\n ...(cellularType && { cellular_type: cellularType }),\n },\n };\n}\n\n// ─── Helpers ───\n\nasync function getWifiName(): Promise<string | undefined> {\n // expo-network doesn't expose SSID directly on all platforms\n // This would need a native module or expo-wifi in production\n return undefined;\n}\n\nfunction getCellularGeneration(): string {\n // expo-network doesn't expose cellular generation\n // In production, use a native module for this\n return 'LTE';\n}\n","/**\n * Built-in Capabilities — wraps each collector as a registerable Capability.\n *\n * Each capability defines:\n * - id, name, description, reason (for UI)\n * - permission check/request\n * - collect function\n *\n * The host app can register these selectively, or add custom ones.\n */\n\nimport * as calendar from './collectors/calendar';\nimport * as contacts from './collectors/contacts';\nimport * as location from './collectors/location';\nimport * as battery from './collectors/battery';\nimport * as connectivity from './collectors/connectivity';\nimport * as notifications from './collectors/notifications';\nimport * as health from './collectors/health';\nimport * as mood from './collectors/mood';\nimport * as camera from './collectors/camera';\nimport type { Capability } from './types';\n\n// ─── Factory functions — call these to get a Capability instance ───\n\nexport function calendarCapability(): Capability {\n return {\n id: 'calendar',\n name: 'Calendar',\n description: 'Syncs your calendar events so your assistant knows your schedule.',\n reason: 'Needed for scheduling, meeting prep, commute alerts, and daily briefings.',\n icon: 'calendar',\n requiresPermission: true,\n permissionState: 'not_requested',\n requestPermission: calendar.requestPermission,\n checkPermission: calendar.hasPermission,\n collect: async () => {\n const [today, upcoming] = await Promise.all([\n calendar.collectToday(),\n calendar.collectUpcoming(7),\n ]);\n return { today, upcoming };\n },\n defaultInterval: 60_000, // 1 min\n };\n}\n\nexport function contactsCapability(): Capability {\n return {\n id: 'contacts',\n name: 'Contacts',\n description: 'Syncs your contacts so your assistant can find people and relationships.',\n reason: 'Needed for messaging, birthday reminders, and relationship insights.',\n icon: 'people',\n requiresPermission: true,\n permissionState: 'not_requested',\n requestPermission: contacts.requestPermission,\n checkPermission: contacts.hasPermission,\n collect: async () => {\n const list = await contacts.collectAll();\n // null = no changes since last successful sync → bridge skips push.\n // Critical for users with 6000+ contacts: full payload is ~1MB and\n // would otherwise re-upload every 5 min with no actual change.\n if (list === null) return null as any;\n return { contacts: list };\n },\n defaultInterval: 300_000, // 5 min\n };\n}\n\nexport function locationCapability(): Capability {\n return {\n id: 'location',\n name: 'Location',\n description: 'Syncs your location for weather, commute, and context-aware assistance.',\n reason: 'Needed for commute estimates, weather at your location, and situation detection.',\n icon: 'location',\n requiresPermission: true,\n permissionState: 'not_requested',\n requestPermission: location.requestPermission,\n checkPermission: location.hasPermission,\n collect: location.collectCurrent,\n defaultInterval: 30_000, // 30 sec\n };\n}\n\nexport function batteryCapability(): Capability {\n return {\n id: 'battery',\n name: 'Battery',\n description: 'Syncs battery level and charging status.',\n reason: 'Helps your assistant adjust behavior when battery is low.',\n icon: 'battery',\n requiresPermission: false,\n permissionState: 'not_needed',\n requestPermission: async () => true,\n checkPermission: async () => true,\n collect: battery.collectBattery,\n defaultInterval: 60_000, // 1 min\n subscribe: battery.subscribeToBattery,\n };\n}\n\nexport function connectivityCapability(): Capability {\n return {\n id: 'connectivity',\n name: 'Connectivity',\n description: 'Syncs WiFi/cellular status.',\n reason: 'Helps your assistant know if you have internet access.',\n icon: 'wifi',\n requiresPermission: false,\n permissionState: 'not_needed',\n requestPermission: async () => true,\n checkPermission: async () => true,\n collect: connectivity.collectConnectivity,\n defaultInterval: 30_000, // 30 sec\n };\n}\n\nexport function healthCapability(): Capability {\n return {\n id: 'health',\n name: 'Health',\n description: 'Reads daily steps, floors, calories, and distance from Apple Health.',\n reason: 'Powers the personal health coach and pairs activity data with nutrition tracking.',\n icon: 'heart',\n requiresPermission: true,\n permissionState: 'not_requested',\n requestPermission: health.requestPermission,\n checkPermission: health.hasPermission,\n collect: async () => {\n // Push today AND the last 30 days every sync. The connector slices\n // `days` to whatever range the caller asked for. ~30 sequential\n // HealthKit reads on iOS take <300ms total — cheap.\n const days = await health.collectHistory(30);\n const today = days[0] || (await health.collectToday());\n return { today, days };\n },\n defaultInterval: 300_000, // 5 min\n };\n}\n\nexport function moodCapability(): Capability {\n return {\n id: 'mood',\n name: 'Mood',\n description: 'Sends a daily behavioral-signal summary (activity, routine) to infer mood — not a medical diagnosis.',\n reason: 'Lets ada gently notice changes in energy, stress, and routine and check in.',\n icon: 'heart',\n // No OS permission of its own — it derives from collectors that gate\n // themselves (e.g. health). Treated as not_needed so the bridge syncs it\n // whenever the user has the Mood toggle on.\n requiresPermission: false,\n permissionState: 'not_needed',\n requestPermission: async () => true,\n checkPermission: async () => true,\n collect: async () => {\n // One compact daily summary (window/timezone/collected_at/today).\n // Pushed as the `mood` relay domain; backend runs /api/mood/analyze.\n return mood.collectToday();\n },\n defaultInterval: 3_600_000, // hourly — it's a daily summary, no need to spam\n };\n}\n\nexport function cameraCapability(): Capability {\n return {\n id: 'camera',\n name: 'Camera',\n description:\n \"Lets ada see through your camera to guide you — reading text and describing what's in \" +\n 'front of you. Frames are analysed on the phone; nothing is stored or uploaded.',\n reason: 'Powers visual guidance (Ada Guide): a live view with on-device text and scene understanding.',\n icon: 'camera',\n requiresPermission: true,\n permissionState: 'not_requested',\n requestPermission: camera.requestPermission,\n checkPermission: camera.hasPermission,\n // LIVE, not synced: the camera is used in the moment (deviceState.visual / a\n // widget's preview) and never collected to the relay. So collect never\n // pushes — this capability's value is the USER GRANT + OS permission, exposed\n // to the backend like every other, not a data payload. `null` = nothing to\n // push, which the bridge skips (same contract contacts uses when unchanged).\n collect: async () => null as any,\n defaultInterval: 3_600_000, // never really collects; keep the poll rare\n };\n}\n\nexport function notificationsCapability(): Capability {\n return {\n id: 'notifications',\n name: 'Notifications',\n description: 'Syncs your notifications for triage and smart grouping.',\n reason: 'Needed for notification triage, priority filtering, and Do Not Disturb.',\n icon: 'notifications',\n requiresPermission: true,\n permissionState: 'not_requested',\n requestPermission: notifications.requestPermission,\n checkPermission: notifications.hasPermission,\n collect: notifications.collectNotifications,\n defaultInterval: 15_000, // 15 sec\n };\n}\n\n// ─── Convenience: get all built-in capabilities ───\n\nexport function allBuiltIn(): Capability[] {\n return [\n calendarCapability(),\n contactsCapability(),\n locationCapability(),\n batteryCapability(),\n connectivityCapability(),\n notificationsCapability(),\n healthCapability(),\n moodCapability(),\n cameraCapability(),\n ];\n}\n","/**\n * Calendar Collector — reads device calendar via expo-calendar.\n * Output format matches device-mock-mcp's calendar.today / calendar.upcoming schemas.\n */\n\nimport * as ExpoCalendar from 'expo-calendar';\n// Type-only alias: the value namespace above cannot be used in type\n// position, so `ExpoCalendar.Calendar`-style annotations need this.\n// expo-calendar's types are not visible through the package entry under\n// bundler resolution, so derive them from the APIs that return them —\n// the shape then always matches the installed version.\ntype Calendar = Awaited<ReturnType<typeof ExpoCalendar.getCalendarsAsync>>[number];\ntype Event = Awaited<ReturnType<typeof ExpoCalendar.getEventsAsync>>[number];\nimport type { CalendarEvent, CalendarTodayData, CalendarUpcomingData } from '../types';\n\n/**\n * Request calendar permissions.\n * @returns true if granted\n */\nexport async function requestPermission(): Promise<boolean> {\n const { status } = await ExpoCalendar.requestCalendarPermissionsAsync();\n return status === 'granted';\n}\n\n/**\n * Check if calendar permission is granted.\n */\nexport async function hasPermission(): Promise<boolean> {\n const { status } = await ExpoCalendar.getCalendarPermissionsAsync();\n return status === 'granted';\n}\n\n/**\n * Get all calendar events for today.\n * Matches the device.calendar.today tool output schema.\n */\nexport async function collectToday(): Promise<CalendarTodayData> {\n const now = new Date();\n const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);\n\n const calendars = await ExpoCalendar.getCalendarsAsync(ExpoCalendar.EntityTypes.EVENT);\n const userCalendarIds = getUserCalendarIds(calendars);\n\n const events = await ExpoCalendar.getEventsAsync(userCalendarIds, startOfDay, endOfDay);\n const filtered = filterHolidays(events);\n\n const mapped: CalendarEvent[] = filtered.map(e => ({\n id: e.id,\n title: e.title || 'Untitled',\n date: startOfDay.toISOString().slice(0, 10),\n start: formatTime(new Date(e.startDate)),\n end: formatTime(new Date(e.endDate)),\n location: e.location || '',\n attendees: ((e as any).attendees || []).map((a: { name?: string; email?: string }) => a.name || a.email || 'Unknown'),\n notes: e.notes || '',\n }));\n\n // Sort by start time\n mapped.sort((a, b) => a.start.localeCompare(b.start));\n\n return {\n ok: true,\n date: startOfDay.toISOString().slice(0, 10),\n day_of_week: now.toLocaleDateString('en-US', { weekday: 'long' }),\n event_count: mapped.length,\n events: mapped,\n };\n}\n\n/**\n * Get upcoming calendar events for the next N days (tomorrow and beyond).\n * Matches the device.calendar.upcoming tool output schema.\n */\nexport async function collectUpcoming(daysAhead: number = 3): Promise<CalendarUpcomingData> {\n const now = new Date();\n const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);\n const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + daysAhead + 1);\n\n const calendars = await ExpoCalendar.getCalendarsAsync(ExpoCalendar.EntityTypes.EVENT);\n const userCalendarIds = getUserCalendarIds(calendars);\n\n const events = await ExpoCalendar.getEventsAsync(userCalendarIds, tomorrow, endDate);\n const filtered = filterHolidays(events);\n\n const mapped: CalendarEvent[] = filtered.map(e => {\n const startDt = new Date(e.startDate);\n return {\n id: e.id,\n title: e.title || 'Untitled',\n date: startDt.toISOString().slice(0, 10),\n start: formatTime(startDt),\n end: formatTime(new Date(e.endDate)),\n location: e.location || '',\n attendees: ((e as any).attendees || []).map((a: { name?: string; email?: string }) => a.name || a.email || 'Unknown'),\n notes: e.notes || '',\n };\n });\n\n // Sort by date then start time\n mapped.sort((a, b) =>\n a.date === b.date ? a.start.localeCompare(b.start) : a.date.localeCompare(b.date)\n );\n\n return {\n ok: true,\n from: tomorrow.toISOString().slice(0, 10),\n days_ahead: daysAhead,\n event_count: mapped.length,\n events: mapped,\n };\n}\n\n// ─── Helpers ───\n\n/**\n * Filter out holiday/subscription calendars — only keep user-owned calendars\n * (local, CalDAV, Exchange, Google). Subscription calendars are read-only\n * holiday feeds that clutter the real schedule.\n */\nfunction getUserCalendarIds(calendars: Calendar[]): string[] {\n const SKIP_SOURCES = ['birthdays', 'other']; // 'other' = subscribed holiday feeds on iOS\n const SKIP_TYPES = ['birthdays', 'other'];\n\n return calendars\n .filter(c => {\n const sourceType = ((c.source as any)?.type || '').toLowerCase();\n const calType = (c.type || '').toLowerCase();\n // Skip subscription/holiday calendars\n if (SKIP_SOURCES.includes(sourceType)) return false;\n if (SKIP_TYPES.includes(calType)) return false;\n return true;\n })\n .map(c => c.id);\n}\n\n/**\n * Extra safety: filter out all-day events with holiday-like patterns\n * in case they slip through from non-subscription calendars.\n */\nfunction filterHolidays(events: Event[]): Event[] {\n const HOLIDAY_PATTERNS = [\n /holiday/i, /observance/i, /eve\\b.*\\btentative\\b/i, /\\btentative\\b/i,\n ];\n\n return events.filter(e => {\n // All-day events spanning exactly one day with \"tentative\" or \"observance\" in notes → holiday\n const isAllDay = (e as any).allDay === true;\n const notes = (e.notes || '').toLowerCase();\n if (isAllDay && HOLIDAY_PATTERNS.some(p => p.test(notes))) return false;\n if (isAllDay && HOLIDAY_PATTERNS.some(p => p.test(e.title || ''))) return false;\n return true;\n });\n}\n\nfunction formatTime(date: Date): string {\n return date.toLocaleTimeString('en-US', {\n hour: '2-digit',\n minute: '2-digit',\n hour12: false,\n });\n}\n","/**\n * Contacts Collector — reads device contacts via expo-contacts.\n *\n * Two important properties for users with large address books (6000+ contacts):\n *\n * 1. Hash-based change detection. We persist a map of `contactId → contentHash`\n * across launches and on each collect cycle compare the freshly-read hashes\n * to the stored ones. If nothing changed, `collectAll()` returns null and\n * `syncCapability` skips the relay push entirely — no per-tick 1MB upload.\n *\n * 2. Reduced field set. iOS 16+ restricts which contact fields are accessible\n * without explicit user grants. Requesting `Note`/`Relationships` causes\n * `getContactsAsync` to throw \"Failed to serialize contact data:\n * Unauthorized Keys\", failing the entire collect. We stick to the four\n * fields actually used downstream (Name, PhoneNumbers, Emails, Birthday).\n *\n * Output format on push (when there ARE changes) is unchanged from before —\n * a full `Contact[]` — so the relay/MCP layer doesn't have to know about the\n * incremental scheme. The relay simply gets pushed less often.\n */\nimport * as ExpoContacts from 'expo-contacts';\n// Type-only alias: the value namespace above cannot be used in type\n// position, so `ExpoContacts.Calendar`-style annotations need this.\n// expo-contacts exports no `Date` type; take the shape from Contact itself.\ntype ExpoContact = Awaited<ReturnType<typeof ExpoContacts.getContactsAsync>>['data'][number];\ntype ContactDate = NonNullable<ExpoContact['birthday']>;\nimport AsyncStorage from '@react-native-async-storage/async-storage';\nimport type { Contact } from '../types';\n\nconst HASH_STORE_KEY = 'device-bridge.contacts.hashes.v1';\n\n/** Request contacts permissions. */\nexport async function requestPermission(): Promise<boolean> {\n const { status } = await ExpoContacts.requestPermissionsAsync();\n return status === 'granted';\n}\n\n/** Check if contacts permission is granted. */\nexport async function hasPermission(): Promise<boolean> {\n const { status } = await ExpoContacts.getPermissionsAsync();\n return status === 'granted';\n}\n\n/**\n * Diagnostic counters from the most recent collect — exposed so the Profile\n * debug view can surface \"what changed since last sync\".\n */\nexport interface ContactsCollectStats {\n total: number;\n added: number;\n updated: number;\n removed: number;\n unchanged: number;\n full_sync: boolean;\n}\nexport let lastContactsStats: ContactsCollectStats | null = null;\n\n/**\n * Read all contacts and detect changes vs the previously-stored hash map.\n *\n * Returns:\n * - the full Contact[] when anything changed (or this is the first sync),\n * - null when every contact's hash matches what we pushed last time, signalling\n * the bridge that no relay push is needed this cycle.\n */\nexport async function collectAll(): Promise<Contact[] | null> {\n // Only the four fields we actually surface downstream. Adding more reawakens\n // the iOS \"Unauthorized Keys\" failure unless the user has granted them via\n // a separate flow.\n const result = await ExpoContacts.getContactsAsync({\n fields: [\n ExpoContacts.Fields.Name,\n ExpoContacts.Fields.PhoneNumbers,\n ExpoContacts.Fields.Emails,\n ExpoContacts.Fields.Birthday,\n ],\n sort: ExpoContacts.SortTypes.LastName,\n });\n\n const raw = Array.isArray(result?.data) ? result.data : [];\n\n // Map raw contacts to our schema, computing a stable per-contact hash that's\n // independent of array ordering and resilient to spurious whitespace/case\n // changes in fields we don't actually compare on.\n const contacts: Contact[] = [];\n const currentHashes: Record<string, string> = {};\n for (let i = 0; i < raw.length; i++) {\n const c = raw[i];\n const id = c.id || `c${i}`;\n const mapped: Contact = {\n id,\n name: c.name || `${c.firstName || ''} ${c.lastName || ''}`.trim() || 'Unknown',\n relationship: '', // dropped — was the iOS Unauthorized-Keys trigger\n phone: c.phoneNumbers?.[0]?.number || null,\n email: c.emails?.[0]?.email || null,\n birthday: formatBirthday(c.birthday),\n notes: '', // dropped — Notes is restricted on iOS 16+\n };\n contacts.push(mapped);\n currentHashes[id] = hashContact(mapped);\n }\n\n // Compare against last-pushed hashes.\n let stored: Record<string, string> = {};\n try {\n const blob = await AsyncStorage.getItem(HASH_STORE_KEY);\n if (blob) stored = JSON.parse(blob) as Record<string, string>;\n } catch {\n /* corrupted store — treat as empty, will full-sync */\n }\n const fullSync = Object.keys(stored).length === 0;\n\n let added = 0;\n let updated = 0;\n let unchanged = 0;\n for (const id of Object.keys(currentHashes)) {\n const prev = stored[id];\n if (prev === undefined) added++;\n else if (prev !== currentHashes[id]) updated++;\n else unchanged++;\n }\n let removed = 0;\n for (const id of Object.keys(stored)) {\n if (currentHashes[id] === undefined) removed++;\n }\n\n lastContactsStats = {\n total: contacts.length,\n added,\n updated,\n removed,\n unchanged,\n full_sync: fullSync,\n };\n\n // No changes → tell the bridge to skip the relay push this cycle. Saves\n // a 6000-row payload going up the wire every 5 minutes when nothing moved.\n if (!fullSync && added === 0 && updated === 0 && removed === 0) {\n return null;\n }\n\n // Persist the new hash map AFTER deciding to push. If the push fails we'll\n // re-detect the same changes on the next cycle (push is idempotent enough).\n try {\n await AsyncStorage.setItem(HASH_STORE_KEY, JSON.stringify(currentHashes));\n } catch {\n /* a failed persist just means we'll redo the diff next time — non-fatal */\n }\n\n return contacts;\n}\n\n// ─── Helpers ────────────────────────────────────────────────\n\n/**\n * Stable string hash (FNV-1a 32-bit, hex). Pure JS, no native dep, fine for\n * change detection. NOT cryptographic — a determined collision attacker could\n * mask a contact change, but that's not in our threat model.\n */\nfunction fnv1a(str: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < str.length; i++) {\n h ^= str.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\nfunction hashContact(c: Contact): string {\n // Concatenate the canonical-cased, trimmed values of every field we surface.\n // Order matters and is fixed; null becomes a single sentinel character so\n // empty-vs-missing differs from \"actual whitespace\" in the hash space.\n const parts = [\n c.id,\n (c.name || '').trim(),\n c.phone || '\\0',\n (c.email || '\\0').toLowerCase(),\n c.birthday || '\\0',\n ];\n return fnv1a(parts.join('\u001f')); // unit separator — won't appear in any field\n}\n\nfunction formatBirthday(birthday: ContactDate | undefined): string | null {\n if (!birthday) return null;\n const { year, month, day } = birthday;\n if (month === undefined || day === undefined) return null;\n const m = String(month + 1).padStart(2, '0');\n const d = String(day).padStart(2, '0');\n\n // No year is the COMMON case on iOS — the contact editor lets you omit it,\n // and most people do. Substituting 1900 made that indistinguishable from a\n // real birth year, and the server dutifully computed an age from it: \"Dana\n // is turning 126 next Tuesday.\"\n //\n // `--MM-DD` is the ISO 8601 form for a recurring month-day with no year, so\n // the absence is stated rather than filled in.\n if (!year) return `--${m}-${d}`;\n\n return `${year}-${m}-${d}`;\n}\n","/**\n * Battery Collector — reads battery status via expo-battery.\n * Output format matches device-mock-mcp's device.battery schema.\n */\n\nimport * as ExpoBattery from 'expo-battery';\n// Type-only alias: the value namespace above cannot be used in type\n// position, so `ExpoBattery.Calendar`-style annotations need this.\n// BatteryState is not re-exported from the package entry — derive it from\n// the API that returns it so we never hand-maintain a copy of the enum.\ntype BatteryState = Awaited<ReturnType<typeof ExpoBattery.getBatteryStateAsync>>;\nimport type { BatteryData } from '../types';\n\n// No permission needed for battery\n\n/**\n * Collect current battery status.\n * Matches the device.battery tool output schema.\n */\nexport async function collectBattery(): Promise<BatteryData> {\n const level = await ExpoBattery.getBatteryLevelAsync();\n const state = await ExpoBattery.getBatteryStateAsync();\n const lowPower = await ExpoBattery.isLowPowerModeEnabledAsync();\n\n return {\n ok: true,\n timestamp: new Date().toISOString(),\n battery: {\n level: Math.round(level * 100), // expo-battery returns 0-1\n state: mapBatteryState(state),\n low_power_mode: lowPower,\n },\n };\n}\n\n/**\n * Subscribe to OS-level battery changes (level + charging state).\n *\n * iOS suspends JS timers when the app is backgrounded, so a pure setInterval\n * sync drifts: the relay ends up stuck on whatever level we last sampled\n * before the app went to sleep (commonly 100% from an overnight charge).\n * expo-battery's listeners fire from the native side and survive that gap,\n * so we get a fresh push as soon as the OS notices a change.\n *\n * Level changes are throttled to >=5pp deltas — without that, iOS emits a\n * level event for every 1% tick which would spam the relay.\n */\nexport function subscribeToBattery(callback: () => void): () => void {\n let lastLevel: number | null = null;\n\n const levelSub = ExpoBattery.addBatteryLevelListener(({ batteryLevel }) => {\n const pct = Math.round(batteryLevel * 100);\n if (lastLevel === null || Math.abs(pct - lastLevel) >= 5) {\n lastLevel = pct;\n callback();\n }\n });\n\n const stateSub = ExpoBattery.addBatteryStateListener(() => {\n callback();\n });\n\n return () => {\n levelSub?.remove?.();\n stateSub?.remove?.();\n };\n}\n\n// ─── Helpers ───\n\nfunction mapBatteryState(\n state: BatteryState\n): 'charging' | 'unplugged' | 'full' {\n switch (state) {\n case ExpoBattery.BatteryState.CHARGING:\n return 'charging';\n case ExpoBattery.BatteryState.FULL:\n return 'full';\n case ExpoBattery.BatteryState.UNPLUGGED:\n default:\n return 'unplugged';\n }\n}\n","/**\n * Notifications Collector — reads notification state via expo-notifications.\n * Output format matches device-mock-mcp's notifications.list schema.\n *\n * Note: On iOS/Android, expo-notifications only gives access to notifications\n * that YOUR app has posted or received. System-wide notification access\n * requires platform-specific APIs (NotificationListenerService on Android,\n * UNUserNotificationCenter on iOS with app extensions).\n *\n * For the PA, the relay approach means we capture notifications delivered\n * TO our app (from the PA system), not FROM other apps.\n * Other-app notifications would need a native module or accessibility service.\n */\n\nimport * as ExpoNotifications from 'expo-notifications';\nimport type { Notification, NotificationsData } from '../types';\n\n/**\n * Request notification permissions.\n */\nexport async function requestPermission(): Promise<boolean> {\n const { status } = await ExpoNotifications.requestPermissionsAsync();\n return status === 'granted';\n}\n\n/**\n * Check if notification permission is granted.\n */\nexport async function hasPermission(): Promise<boolean> {\n const { status } = await ExpoNotifications.getPermissionsAsync();\n return status === 'granted';\n}\n\n/**\n * Collect delivered notifications from the notification tray.\n * Only captures notifications delivered to THIS app.\n * Matches the device.notifications.list tool output schema.\n */\nexport async function collectNotifications(): Promise<NotificationsData> {\n const presented = await ExpoNotifications.getPresentedNotificationsAsync();\n\n const notifications: Notification[] = presented.map((n, i) => ({\n id: n.request.identifier || `n${i}`,\n app: (n.request.content.data?.app as string) || 'A-Team',\n title: n.request.content.title || '',\n body: n.request.content.body || '',\n timestamp: n.date ? new Date(n.date).toISOString() : new Date().toISOString(),\n sender: (n.request.content.data?.sender as string) || null,\n priority: mapPriority(n.request.content.data?.priority as string),\n read: false, // Presented notifications are unread by definition\n }));\n\n const unread = notifications.filter(n => !n.read).length;\n\n return {\n ok: true,\n timestamp: new Date().toISOString(),\n total: notifications.length,\n unread,\n notifications,\n };\n}\n\n// ─── Helpers ───\n\nfunction mapPriority(p: string | undefined): 'high' | 'medium' | 'low' {\n if (p === 'high' || p === 'max') return 'high';\n if (p === 'low' || p === 'min') return 'low';\n return 'medium';\n}\n","/**\n * Mood Signals Collector — assembles the daily behavioral-signal summary the\n * Mood Intelligence Kit's backend expects (MoodSignalToday), and emits it as\n * a compact daily object. It does NOT call the kit's HTTP client; transport is\n * the existing device-bridge relay path (pushed as the `mood` domain), same as\n * health/location/etc. The backend reads the relay domain and runs analysis.\n *\n * Philosophy (from the kit's DESIGN): send a concise daily SUMMARY, never raw\n * event logs. We fill the fields we can source today from existing collectors\n * and leave the rest null — the backend's baseline/fallback tolerates nulls.\n *\n * EXACT per-field contract + where each value comes from on THIS platform\n * (iOS). \"blocked\" = Apple does not expose it to third-party apps, so it is\n * permanently null on iOS; \"addable\" = we have a source but haven't wired it.\n *\n * steps ← health (HealthKit) ✅ sourced now\n * distance_km ← health (HealthKit) ✅ sourced now\n * sleep_min ← health (HealthKit sleep) ✅ sourced now\n * app_sessions ← our own app analytics ✅ sourced now\n * app_active_min ← our own app analytics ✅ sourced now\n * resting_hr (extra) ← health (HealthKit) ✅ sourced now\n * active_energy_kcal(x) ← health (HealthKit) ✅ sourced now\n * exercise_min (extra) ← health (HealthKit) ✅ sourced now\n * places_count ← location collector (distinct) ⏳ addable (not wired)\n * checkin_mood ← user self-report UI ⏳ addable (no UI yet)\n * screen_min ← iOS Screen Time ❌ blocked by iOS\n * night_screen_min ← iOS Screen Time ❌ blocked by iOS\n * social_app_min ← other apps' usage ❌ blocked by iOS\n * video_app_min ← other apps' usage ❌ blocked by iOS\n * productivity_app_min ← other apps' usage ❌ blocked by iOS\n * messages_sent ← Messages content/metadata ❌ blocked by iOS\n * calls_count ← call log ❌ blocked by iOS\n *\n * (extra) = not in the kit's MoodSignalToday but sent alongside; the backend\n * tolerates extra fields and these are strong mood proxies.\n *\n * The kit's spec listed many sources because several exist on Android\n * (UsageStatsManager etc.); on iOS most are sandbox-blocked. We send what we\n * truly have and leave the rest null — the backend baseline/fallback tolerates\n * nulls and weights only present fields.\n */\nimport * as health from './health';\nimport * as appEngagement from './appEngagement';\n\n// Mirrors the kit's MoodSignalToday (packages/mood-client-rn/src/types.ts).\nexport interface MoodSignalToday {\n steps: number | null;\n sleep_min: number | null;\n screen_min: number | null;\n night_screen_min: number | null;\n places_count: number | null;\n distance_km: number | null;\n social_app_min: number | null;\n video_app_min: number | null;\n productivity_app_min: number | null;\n messages_sent: number | null;\n calls_count: number | null;\n app_sessions: number | null;\n app_active_min: number | null;\n checkin_mood?: 'great' | 'ok' | 'low' | 'bad' | null;\n}\n\nfunction emptySignals(): MoodSignalToday {\n return {\n steps: null,\n sleep_min: null,\n screen_min: null,\n night_screen_min: null,\n places_count: null,\n distance_km: null,\n social_app_min: null,\n video_app_min: null,\n productivity_app_min: null,\n messages_sent: null,\n calls_count: null,\n app_sessions: null,\n app_active_min: null,\n checkin_mood: null,\n };\n}\n\n/**\n * Build today's mood signal summary from available collectors. Returns the\n * full MoodSignalToday plus collection metadata the backend wants\n * (window, timezone, collected_at) so it can run analyze without guessing.\n */\nexport async function collectToday(): Promise<{\n window: 'today';\n timezone: string;\n collected_at: string;\n today: MoodSignalToday;\n}> {\n const today = emptySignals();\n\n // Health-sourced fields (best-effort; collector returns zeros if HK denied).\n try {\n const h = await health.collectToday();\n if (h) {\n today.steps = typeof h.steps === 'number' ? h.steps : null;\n today.distance_km = typeof h.distance_km === 'number' ? h.distance_km : null;\n }\n } catch {\n // leave nulls — backend baseline handles missing fields\n }\n\n // HealthKit mood extras: sleep, resting HR, active energy, exercise minutes.\n try {\n const x = await health.collectMoodExtras();\n today.sleep_min = x.sleep_min;\n // resting_hr / active_energy_kcal / exercise_min aren't in the kit's\n // MoodSignalToday contract, but the backend tolerates extra fields and\n // they're strong mood proxies — include them alongside.\n (today as any).resting_hr = x.resting_hr;\n (today as any).active_energy_kcal = x.active_energy_kcal;\n (today as any).exercise_min = x.exercise_min;\n } catch {\n // leave nulls\n }\n\n // Our own app-engagement analytics (no OS permission; the only on-iOS source\n // for app_sessions / app_active_min).\n try {\n const e = await appEngagement.getToday();\n today.app_sessions = e.app_sessions;\n today.app_active_min = e.app_active_min;\n } catch {\n // leave nulls\n }\n\n let timezone = 'UTC';\n try {\n timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';\n } catch { /* RN without full ICU — fall back to UTC */ }\n\n return {\n window: 'today',\n timezone,\n collected_at: new Date().toISOString(),\n today,\n };\n}\n","/**\n * Camera capability — permission only, NO collector.\n *\n * Unlike calendar/contacts/health, the camera is a LIVE capability: frames are\n * used in the moment (deviceState.visual, a widget's camera preview) and are\n * analysed on-device — never collected to the relay. So this module carries only\n * the OS-permission check/request that the capability toggle drives; there is no\n * `collect`. The user's grant (this toggle) is what gates access, on the same\n * path as location/contacts.\n */\nimport { Camera } from 'expo-camera';\n\nexport async function hasPermission(): Promise<boolean> {\n try {\n return (await Camera.getCameraPermissionsAsync()).granted;\n } catch {\n return false;\n }\n}\n\nexport async function requestPermission(): Promise<boolean> {\n try {\n return (await Camera.requestCameraPermissionsAsync()).granted;\n } catch {\n return false;\n }\n}\n","/**\n * Background Sync — registers an expo-task-manager task for periodic\n * data sync when the app is in the background, and exposes a one-shot\n * `syncDomains()` for silent-push triggered syncs.\n *\n * iOS minimum background fetch interval is ~15 minutes.\n * Android allows more frequent background execution via WorkManager.\n *\n * Usage:\n * import { registerBackgroundSync, syncDomains } from '@mobile-pa/device-bridge';\n *\n * // Periodic background fetch — call once at app startup, outside any component\n * registerBackgroundSync({\n * relayUrl: 'https://relay.example.com',\n * deviceId: 'device-123',\n * tenant: 'mobile-pa',\n * actorId: 'user-abc',\n * apiKey: 'key-xxx',\n * });\n *\n * // Silent-push triggered sync — from FCM background message handler\n * await syncDomains(config, ['location', 'calendar']);\n */\n\nimport * as TaskManager from 'expo-task-manager';\nimport * as BackgroundFetch from 'expo-background-fetch';\nimport { RelayClient } from './relay-client';\nimport * as caps from './capabilities';\nimport type { Capability } from './types';\n\nexport const BACKGROUND_TASK_NAME = 'DEVICE_BRIDGE_BACKGROUND_SYNC';\n\nexport interface BackgroundSyncConfig {\n relayUrl: string;\n deviceId: string;\n tenant: string;\n actorId?: string;\n apiKey: string;\n}\n\nconst CAPABILITY_FACTORIES: Record<string, () => Capability> = {\n calendar: caps.calendarCapability,\n contacts: caps.contactsCapability,\n location: caps.locationCapability,\n battery: caps.batteryCapability,\n connectivity: caps.connectivityCapability,\n notifications: caps.notificationsCapability,\n health: caps.healthCapability,\n};\n\n/**\n * Register the periodic background-fetch task.\n * Call once at app startup, outside any React component.\n */\nexport async function registerBackgroundSync(\n config: BackgroundSyncConfig\n): Promise<void> {\n TaskManager.defineTask(BACKGROUND_TASK_NAME, async () => {\n try {\n const hasNew = await syncDomains(config, ['location', 'battery', 'calendar']);\n return hasNew\n ? BackgroundFetch.BackgroundFetchResult.NewData\n : BackgroundFetch.BackgroundFetchResult.NoData;\n } catch (error) {\n console.error('[DeviceBridge] Background sync failed:', error);\n return BackgroundFetch.BackgroundFetchResult.Failed;\n }\n });\n\n await BackgroundFetch.registerTaskAsync(BACKGROUND_TASK_NAME, {\n minimumInterval: 300, // 5 minutes (iOS will clamp to ~15 min)\n stopOnTerminate: false,\n startOnBoot: true,\n });\n}\n\n/**\n * Unregister the background sync task.\n */\nexport async function unregisterBackgroundSync(): Promise<void> {\n const isRegistered = await TaskManager.isTaskRegisteredAsync(\n BACKGROUND_TASK_NAME\n );\n if (isRegistered) {\n await BackgroundFetch.unregisterTaskAsync(BACKGROUND_TASK_NAME);\n }\n}\n\n/**\n * Collect and push the listed domains once. Used by both the periodic\n * background-fetch task and the silent-push handler.\n *\n * Returns true if at least one domain pushed new data.\n */\nexport async function syncDomains(\n config: BackgroundSyncConfig,\n domains: string[]\n): Promise<boolean> {\n const relay = new RelayClient({\n relayUrl: config.relayUrl,\n deviceId: config.deviceId,\n tenant: config.tenant,\n actorId: config.actorId,\n apiKey: config.apiKey,\n timeout: 15_000, // longer than foreground — background tasks are budget-limited but not latency-sensitive\n });\n\n const results = await Promise.allSettled(\n domains.map(d => collectAndPush(relay, d))\n );\n\n return results.some(r => r.status === 'fulfilled' && r.value);\n}\n\n// ─── Internal ───\n\nasync function collectAndPush(\n relay: RelayClient,\n domain: string\n): Promise<boolean> {\n const factory = CAPABILITY_FACTORIES[domain];\n if (!factory) {\n console.warn(`[DeviceBridge] Unknown sync domain: ${domain}`);\n return false;\n }\n\n const cap = factory();\n\n if (cap.requiresPermission) {\n const granted = await cap.checkPermission();\n if (!granted) return false;\n }\n\n const data = await cap.collect();\n const result = await relay.pushDomain(domain, data);\n return result.ok;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BO,IAAM,cAAN,MAAkB;AAAA,EASvB,YAAY,QAA2B;AAFvC,SAAQ,eAAmC,CAAC;AAI1C,SAAK,UAAU,OAAO,SAAS,QAAQ,OAAO,EAAE;AAChD,SAAK,WAAW,OAAO;AACvB,SAAK,SAAS,OAAO;AACrB,SAAK,UAAU,OAAO,WAAW;AACjC,SAAK,SAAS,OAAO,UAAU;AAC/B,SAAK,UAAU,OAAO,WAAW;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,SAAS,QAAwD;AACrE,QAAI;AACF,YAAM,WAAW,MAA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AAO;AAAA,IACjB,QAAQ,OAAO;AAAA,IACf,SAAS,OAAO;AAAA,IAChB,QAAQ,OAAO;AAAA,IACf,SAAS;AAAA;AAAA,EACX,CAAC;AAED,QAAM,UAAU,MAAM,QAAQ;AAAA,IAC5B,QAAQ,IAAI,OAAK,eAAe,OAAO,CAAC,CAAC;AAAA,EAC3C;AAEA,SAAO,QAAQ,KAAK,OAAK,EAAE,WAAW,eAAe,EAAE,KAAK;AAC9D;AAIA,eAAe,eACb,OACA,QACkB;AAClB,QAAM,UAAU,qBAAqB,MAAM;AAC3C,MAAI,CAAC,SAAS;AACZ,YAAQ,KAAK,uCAAuC,MAAM,EAAE;AAC5D,WAAO;AAAA,EACT;AAEA,QAAM,MAAM,QAAQ;AAEpB,MAAI,IAAI,oBAAoB;AAC1B,UAAM,UAAU,MAAM,IAAI,gBAAgB;AAC1C,QAAI,CAAC,QAAS,QAAO;AAAA,EACvB;AAEA,QAAM,OAAO,MAAM,IAAI,QAAQ;AAC/B,QAAM,SAAS,MAAM,MAAM,WAAW,QAAQ,IAAI;AAClD,SAAO,OAAO;AAChB;","names":["hasPermission","requestPermission","requestPermission","hasPermission","requestPermission","hasPermission","collectToday","requestPermission","hasPermission","requestPermission","hasPermission","collectToday","hasPermission","requestPermission","requestPermission","hasPermission","collectToday"]}
|