@ateam-ai-mobile/plugin-runtime 0.1.5 → 0.1.8

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.
@@ -0,0 +1,3085 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/api/plugins.ts
8
+ import { apiFetch } from "@ateam-ai-mobile/core";
9
+ import { getCoreApiUrl } from "@ateam-ai-mobile/core";
10
+ function supportsNative(manifest) {
11
+ const mode = manifest.render?.mode;
12
+ return mode === "react-native" || mode === "adaptive";
13
+ }
14
+ function getNativeComponentId(manifest) {
15
+ if (manifest.render?.mode === "react-native") return manifest.render.component;
16
+ if (manifest.render?.mode === "adaptive") return manifest.render.reactNative?.component;
17
+ return null;
18
+ }
19
+ function getNativeBundleUrl(manifest) {
20
+ const direct = manifest.bundleUrl;
21
+ if (direct) return direct;
22
+ const render = manifest.render;
23
+ if (render.mode === "react-native") return render.bundleUrl || null;
24
+ if (render.mode === "adaptive") return render.reactNative?.bundleUrl || null;
25
+ return null;
26
+ }
27
+ function getNativeBundleHash(manifest) {
28
+ const direct = manifest.bundleHash;
29
+ if (direct) return direct;
30
+ const render = manifest.render;
31
+ if (render.mode === "react-native") return render.bundleHash || null;
32
+ if (render.mode === "adaptive") return render.reactNative?.bundleHash || null;
33
+ return null;
34
+ }
35
+ function supportsWebView(manifest) {
36
+ return manifest.render?.mode === "iframe" || manifest.render?.mode === "adaptive";
37
+ }
38
+ async function listPlugins() {
39
+ const res = await apiFetch("/mcp", {
40
+ method: "POST",
41
+ body: JSON.stringify({
42
+ jsonrpc: "2.0",
43
+ id: Date.now(),
44
+ method: "tools/call",
45
+ params: {
46
+ name: "cp.listContextPlugins",
47
+ arguments: {}
48
+ }
49
+ })
50
+ });
51
+ const structured = res.result?.structuredContent?.plugins;
52
+ if (structured) return structured;
53
+ const text = res.result?.content?.[0]?.text;
54
+ if (!text) return [];
55
+ try {
56
+ const parsed = JSON.parse(text);
57
+ return parsed.plugins || parsed || [];
58
+ } catch {
59
+ return [];
60
+ }
61
+ }
62
+ async function getPlugin(pluginId) {
63
+ const res = await apiFetch("/mcp", {
64
+ method: "POST",
65
+ body: JSON.stringify({
66
+ jsonrpc: "2.0",
67
+ id: Date.now(),
68
+ method: "tools/call",
69
+ params: {
70
+ name: "cp.getContextPlugin",
71
+ arguments: { id: pluginId }
72
+ // Backend expects { id }, NOT { pluginId }
73
+ }
74
+ })
75
+ });
76
+ if (res.result?.structuredContent) return res.result.structuredContent;
77
+ const text = res.result?.content?.[0]?.text;
78
+ if (!text) return null;
79
+ try {
80
+ const parsed = JSON.parse(text);
81
+ if (parsed.error) {
82
+ console.warn("[getPlugin] Backend error:", parsed.error);
83
+ return null;
84
+ }
85
+ return parsed;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ function resolvePluginUrl(manifest, tenant) {
91
+ const render = manifest.render;
92
+ let url;
93
+ if (render?.mode === "iframe") {
94
+ url = render.iframeUrl;
95
+ } else if (render?.mode === "adaptive") {
96
+ url = render.iframeUrl || render.iframe?.iframeUrl;
97
+ }
98
+ if (!url) return "";
99
+ if (url.startsWith("http")) {
100
+ const sep = url.includes("?") ? "&" : "?";
101
+ return tenant ? `${url}${sep}tenant=${encodeURIComponent(tenant)}` : url;
102
+ }
103
+ if (tenant && url.startsWith("/mcp-ui/")) {
104
+ const tenantUrl = url.replace("/mcp-ui/", `/mcp-ui/${encodeURIComponent(tenant)}/`);
105
+ return `${getCoreApiUrl()}${tenantUrl}`;
106
+ }
107
+ return `${getCoreApiUrl()}${url}`;
108
+ }
109
+
110
+ // src/bundles/bundleManager.ts
111
+ import React2 from "react";
112
+ import {
113
+ useState,
114
+ useEffect as useEffect6,
115
+ useCallback as useCallback2,
116
+ useMemo as useMemo4,
117
+ useRef as useRef4,
118
+ useContext,
119
+ useReducer,
120
+ useLayoutEffect,
121
+ useImperativeHandle,
122
+ useDebugValue
123
+ } from "react";
124
+ import * as ReactNative from "react-native";
125
+ import { apiFetchRaw, getTenant as getTenant2 } from "@ateam-ai-mobile/core";
126
+
127
+ // src/sdk/index.ts
128
+ var sdk_exports = {};
129
+ __export(sdk_exports, {
130
+ ActionButton: () => ActionButton,
131
+ ActivityIndicator: () => ActivityIndicator,
132
+ Animated: () => Animated,
133
+ Badge: () => Badge,
134
+ CameraPreview: () => CameraPreview,
135
+ Card: () => Card,
136
+ EmptyState: () => EmptyState,
137
+ ErrorState: () => ErrorState,
138
+ FlatList: () => FlatList,
139
+ Image: () => Image,
140
+ ListItem: () => ListItem,
141
+ LoadingState: () => LoadingState,
142
+ Modal: () => Modal,
143
+ PLATFORM_VOICE_CALLER: () => PLATFORM_VOICE_CALLER,
144
+ Platform: () => Platform,
145
+ PluginSDK: () => PluginSDK,
146
+ Pressable: () => Pressable,
147
+ RefreshControl: () => RefreshControl,
148
+ ScrollView: () => ScrollView,
149
+ SearchBar: () => SearchBar,
150
+ SectionList: () => SectionList,
151
+ StyleSheet: () => StyleSheet,
152
+ Switch: () => Switch,
153
+ TabBar: () => TabBar,
154
+ Text: () => Text,
155
+ TextInput: () => TextInput,
156
+ TouchableOpacity: () => TouchableOpacity,
157
+ View: () => View,
158
+ register: () => register,
159
+ registerService: () => registerService,
160
+ registerTools: () => registerTools,
161
+ setPluginThemeColors: () => setPluginThemeColors,
162
+ useApi: () => useApi,
163
+ usePluginTheme: () => usePluginTheme
164
+ });
165
+
166
+ // src/sdk/registration.ts
167
+ function register(id, config) {
168
+ return {
169
+ id,
170
+ type: config.type || "ui",
171
+ capabilities: config.capabilities,
172
+ stateDomains: config.stateDomains,
173
+ Component: config.Component,
174
+ tools: config.tools
175
+ };
176
+ }
177
+ function registerTools(id, config) {
178
+ return {
179
+ id,
180
+ type: "tools",
181
+ capabilities: config.capabilities,
182
+ stateDomains: config.stateDomains,
183
+ tools: config.tools
184
+ };
185
+ }
186
+ function registerService(id, config) {
187
+ return {
188
+ id,
189
+ type: "service",
190
+ capabilities: config.capabilities,
191
+ hooks: config.hooks,
192
+ onStart: config.onStart,
193
+ onStop: config.onStop
194
+ };
195
+ }
196
+
197
+ // src/sdk/voice.ts
198
+ var PLATFORM_VOICE_CALLER = /* @__PURE__ */ Symbol("adas.voice.platform");
199
+
200
+ // src/sdk/primitives.ts
201
+ import {
202
+ View,
203
+ Text,
204
+ ScrollView,
205
+ FlatList,
206
+ SectionList,
207
+ Pressable,
208
+ TouchableOpacity,
209
+ TextInput,
210
+ Image,
211
+ ActivityIndicator,
212
+ Modal,
213
+ Switch,
214
+ StyleSheet,
215
+ Animated,
216
+ Platform,
217
+ RefreshControl
218
+ } from "react-native";
219
+
220
+ // src/sdk/components.ts
221
+ import React from "react";
222
+ import {
223
+ View as View2,
224
+ Text as Text2,
225
+ Pressable as Pressable2,
226
+ TextInput as TextInput2,
227
+ ActivityIndicator as ActivityIndicator2,
228
+ StyleSheet as StyleSheet2
229
+ } from "react-native";
230
+ function Card({ theme, children, style, onPress }) {
231
+ const cardStyle = [
232
+ styles.card,
233
+ {
234
+ backgroundColor: theme.colors.surface,
235
+ borderColor: theme.colors.border
236
+ },
237
+ style
238
+ ];
239
+ if (onPress) {
240
+ return React.createElement(Pressable2, { style: cardStyle, onPress }, children);
241
+ }
242
+ return React.createElement(View2, { style: cardStyle }, children);
243
+ }
244
+ var BADGE_COLORS = {
245
+ accent: { bg: "accentSoft", text: "accent" },
246
+ success: { bg: "successSoft", text: "success" },
247
+ warning: { bg: "warningSoft", text: "warning" },
248
+ error: { bg: "errorSoft", text: "error" },
249
+ purple: { bg: "purpleSoft", text: "purple" }
250
+ };
251
+ function Badge({ theme, label, color = "accent", style }) {
252
+ const mapping = BADGE_COLORS[color];
253
+ return React.createElement(
254
+ View2,
255
+ {
256
+ style: [
257
+ styles.badge,
258
+ {
259
+ backgroundColor: theme.colors[mapping.bg],
260
+ borderRadius: theme.borderRadius.sm
261
+ },
262
+ style
263
+ ]
264
+ },
265
+ React.createElement(Text2, {
266
+ style: [styles.badgeText, { color: theme.colors[mapping.text] }]
267
+ }, label)
268
+ );
269
+ }
270
+ function TabBar({ theme, tabs, activeTab, onTabChange, style }) {
271
+ return React.createElement(
272
+ View2,
273
+ {
274
+ style: [
275
+ styles.tabBar,
276
+ { borderBottomColor: theme.colors.border },
277
+ style
278
+ ]
279
+ },
280
+ tabs.map(
281
+ (tab) => React.createElement(
282
+ Pressable2,
283
+ {
284
+ key: tab,
285
+ style: [
286
+ styles.tab,
287
+ {
288
+ borderBottomColor: tab === activeTab ? theme.colors.accent : "transparent"
289
+ }
290
+ ],
291
+ onPress: () => onTabChange(tab)
292
+ },
293
+ React.createElement(Text2, {
294
+ style: {
295
+ color: tab === activeTab ? theme.colors.accent : theme.colors.textSecondary,
296
+ fontSize: theme.fontSize.sm,
297
+ fontWeight: tab === activeTab ? "600" : "400"
298
+ }
299
+ }, tab)
300
+ )
301
+ )
302
+ );
303
+ }
304
+ function ListItem({ theme, title, subtitle, right, onPress, style }) {
305
+ const content = [
306
+ React.createElement(
307
+ View2,
308
+ { key: "content", style: styles.listItemContent },
309
+ React.createElement(Text2, {
310
+ style: { color: theme.colors.text, fontSize: theme.fontSize.md },
311
+ numberOfLines: 1
312
+ }, title),
313
+ subtitle ? React.createElement(Text2, {
314
+ style: { color: theme.colors.textSecondary, fontSize: theme.fontSize.xs, marginTop: 2 },
315
+ numberOfLines: 1
316
+ }, subtitle) : null
317
+ ),
318
+ right ? React.createElement(View2, { key: "right" }, right) : null
319
+ ];
320
+ if (onPress) {
321
+ return React.createElement(
322
+ Pressable2,
323
+ { style: [styles.listItem, { borderBottomColor: theme.colors.border }, style], onPress },
324
+ ...content
325
+ );
326
+ }
327
+ return React.createElement(
328
+ View2,
329
+ { style: [styles.listItem, { borderBottomColor: theme.colors.border }, style] },
330
+ ...content
331
+ );
332
+ }
333
+ function SearchBar({ theme, value, onChangeText, placeholder = "Search...", style }) {
334
+ return React.createElement(TextInput2, {
335
+ style: [
336
+ styles.searchBar,
337
+ {
338
+ backgroundColor: theme.colors.input,
339
+ color: theme.colors.text,
340
+ borderColor: theme.colors.border,
341
+ borderRadius: theme.borderRadius.sm,
342
+ fontSize: theme.fontSize.sm
343
+ },
344
+ style
345
+ ],
346
+ value,
347
+ onChangeText,
348
+ placeholder,
349
+ placeholderTextColor: theme.colors.textMuted,
350
+ autoCapitalize: "none",
351
+ autoCorrect: false
352
+ });
353
+ }
354
+ function EmptyState({ theme, title, subtitle, style }) {
355
+ return React.createElement(
356
+ View2,
357
+ { style: [styles.emptyState, style] },
358
+ React.createElement(Text2, {
359
+ style: { color: theme.colors.textSecondary, fontSize: theme.fontSize.md, textAlign: "center" }
360
+ }, title),
361
+ subtitle ? React.createElement(Text2, {
362
+ style: { color: theme.colors.textMuted, fontSize: theme.fontSize.sm, textAlign: "center", marginTop: 4 }
363
+ }, subtitle) : null
364
+ );
365
+ }
366
+ function ErrorState({ theme, message, onRetry, style }) {
367
+ return React.createElement(
368
+ View2,
369
+ { style: [styles.emptyState, style] },
370
+ React.createElement(Text2, {
371
+ style: { color: theme.colors.error, fontSize: theme.fontSize.md, textAlign: "center" }
372
+ }, message),
373
+ onRetry ? React.createElement(
374
+ Pressable2,
375
+ {
376
+ style: [styles.retryButton, { backgroundColor: theme.colors.accentSoft, borderRadius: theme.borderRadius.sm }],
377
+ onPress: onRetry
378
+ },
379
+ React.createElement(Text2, {
380
+ style: { color: theme.colors.accent, fontSize: theme.fontSize.sm, fontWeight: "600" }
381
+ }, "Retry")
382
+ ) : null
383
+ );
384
+ }
385
+ function LoadingState({ theme, message = "Loading...", style }) {
386
+ return React.createElement(
387
+ View2,
388
+ { style: [styles.emptyState, style] },
389
+ React.createElement(ActivityIndicator2, { size: "small", color: theme.colors.accent }),
390
+ React.createElement(Text2, {
391
+ style: { color: theme.colors.textSecondary, fontSize: theme.fontSize.sm, marginTop: 8 }
392
+ }, message)
393
+ );
394
+ }
395
+ function ActionButton({ theme, label, icon, onPress, style }) {
396
+ return React.createElement(
397
+ Pressable2,
398
+ {
399
+ style: [
400
+ styles.fab,
401
+ { backgroundColor: theme.colors.accent, borderRadius: theme.borderRadius.full },
402
+ style
403
+ ],
404
+ onPress
405
+ },
406
+ icon || React.createElement(Text2, { style: styles.fabText }, label || "+")
407
+ );
408
+ }
409
+ var styles = StyleSheet2.create({
410
+ card: {
411
+ padding: 12,
412
+ borderRadius: 12,
413
+ borderWidth: 1,
414
+ marginBottom: 8
415
+ },
416
+ badge: {
417
+ paddingHorizontal: 8,
418
+ paddingVertical: 3
419
+ },
420
+ badgeText: {
421
+ fontSize: 11,
422
+ fontWeight: "600"
423
+ },
424
+ tabBar: {
425
+ flexDirection: "row",
426
+ borderBottomWidth: 1
427
+ },
428
+ tab: {
429
+ flex: 1,
430
+ padding: 12,
431
+ alignItems: "center",
432
+ borderBottomWidth: 2
433
+ },
434
+ listItem: {
435
+ flexDirection: "row",
436
+ alignItems: "center",
437
+ paddingVertical: 12,
438
+ paddingHorizontal: 16,
439
+ borderBottomWidth: StyleSheet2.hairlineWidth
440
+ },
441
+ listItemContent: {
442
+ flex: 1
443
+ },
444
+ searchBar: {
445
+ height: 40,
446
+ paddingHorizontal: 12,
447
+ borderWidth: 1
448
+ },
449
+ emptyState: {
450
+ flex: 1,
451
+ justifyContent: "center",
452
+ alignItems: "center",
453
+ padding: 32
454
+ },
455
+ retryButton: {
456
+ marginTop: 12,
457
+ paddingHorizontal: 16,
458
+ paddingVertical: 8
459
+ },
460
+ fab: {
461
+ position: "absolute",
462
+ bottom: 24,
463
+ right: 24,
464
+ width: 56,
465
+ height: 56,
466
+ justifyContent: "center",
467
+ alignItems: "center",
468
+ shadowColor: "#000",
469
+ shadowOffset: { width: 0, height: 2 },
470
+ shadowOpacity: 0.25,
471
+ shadowRadius: 4,
472
+ elevation: 5
473
+ },
474
+ fabText: {
475
+ color: "#fff",
476
+ fontSize: 24,
477
+ fontWeight: "600"
478
+ }
479
+ });
480
+
481
+ // src/host.ts
482
+ var _haptics = null;
483
+ function setHapticsProvider(haptics) {
484
+ _haptics = haptics;
485
+ }
486
+ function getHaptics() {
487
+ return _haptics;
488
+ }
489
+ function unavailable(api) {
490
+ return new Proxy({}, {
491
+ get: (_t, method) => () => Promise.reject(new Error(`[adas] native.${api}.${String(method)} unavailable \u2014 host did not call setPluginNativeProvider()`))
492
+ });
493
+ }
494
+ var noopNative = {
495
+ camera: unavailable("camera"),
496
+ location: unavailable("location"),
497
+ storage: unavailable("storage"),
498
+ biometrics: unavailable("biometrics"),
499
+ biometricsV2: unavailable("biometricsV2"),
500
+ notifications: unavailable("notifications"),
501
+ haptics: { impact: () => {
502
+ }, notification: () => {
503
+ }, selection: () => {
504
+ }, error: () => {
505
+ } },
506
+ connectivity: { isOnline: () => true, onChange: () => () => {
507
+ } },
508
+ fileSystem: unavailable("fileSystem"),
509
+ cookies: unavailable("cookies"),
510
+ sharing: unavailable("sharing"),
511
+ scanner: unavailable("scanner"),
512
+ nfc: unavailable("nfc"),
513
+ bluetooth: unavailable("bluetooth"),
514
+ vision: unavailable("vision"),
515
+ maps: unavailable("maps")
516
+ };
517
+ var _pluginNative = noopNative;
518
+ function setPluginNativeProvider(native) {
519
+ _pluginNative = native;
520
+ }
521
+ function getPluginNative() {
522
+ return _pluginNative;
523
+ }
524
+ function blocked(api, reason) {
525
+ return new Proxy({}, {
526
+ get: (_t, method) => {
527
+ if (typeof method !== "string") return void 0;
528
+ return () => {
529
+ console.warn(`[adas] native.${api}.${method} blocked \u2014 ${reason ?? `capability '${api}' not declared in the plugin manifest`}`);
530
+ };
531
+ }
532
+ });
533
+ }
534
+ function gatePluginNative(native, declared, pluginId) {
535
+ const caps = declared || {};
536
+ const scopedFileSystem = native.fileSystemFor && pluginId ? native.fileSystemFor(pluginId) : null;
537
+ const scopedStorage = native.storageFor && pluginId ? native.storageFor(pluginId) : null;
538
+ const gated = {
539
+ camera: caps.camera ? native.camera : blocked("camera"),
540
+ location: caps.location ? native.location : blocked("location"),
541
+ storage: caps.offline ? scopedStorage ?? blocked("storage", "no trusted pluginId to scope storage \u2014 refusing shared access (fail closed)") : blocked("storage"),
542
+ biometrics: caps.biometrics ? native.biometrics : blocked("biometrics"),
543
+ biometricsV2: caps.biometricsV2 ? native.biometricsV2 : blocked("biometricsV2"),
544
+ notifications: caps.notifications ? native.notifications : blocked("notifications"),
545
+ haptics: caps.haptics ? native.haptics : blocked("haptics"),
546
+ connectivity: native.connectivity,
547
+ fileSystem: caps.fileSystem ? scopedFileSystem ?? blocked("fileSystem", "no trusted pluginId to scope the filesystem \u2014 refusing shared access (fail closed)") : blocked("fileSystem"),
548
+ cookies: caps.cookies ? native.cookies : blocked("cookies"),
549
+ sharing: caps.sharing ? native.sharing : blocked("sharing"),
550
+ scanner: caps.scanner ? native.scanner : blocked("scanner"),
551
+ nfc: caps.nfc ? native.nfc : blocked("nfc"),
552
+ // Gated like the rest even though nothing implements it yet. An undeclared
553
+ // plugin gets the usual blocked proxy; a DECLARED one reaches an API whose
554
+ // every method refuses by name. Both are better than the `undefined` this
555
+ // used to be, which crashed with "cannot read properties of undefined".
556
+ bluetooth: caps.bluetooth ? native.bluetooth : blocked("bluetooth"),
557
+ vision: caps.vision ? native.vision : blocked("vision"),
558
+ maps: caps.maps ? native.maps : blocked("maps")
559
+ // What this plugin DECLARED, carried on the object it already receives.
560
+ //
561
+ // It is how a COMPONENT can be capability-gated: <CameraPreview> is handed
562
+ // `native` and reads this, so showing the camera obeys the same flag as
563
+ // calling it. Without this the preview would be a second door to the camera
564
+ // with only one lock. Non-enumerable so it cannot be mistaken for an API.
565
+ };
566
+ Object.defineProperty(gated, "__declaredCapabilities", {
567
+ value: Object.freeze({ ...caps }),
568
+ enumerable: false,
569
+ writable: false
570
+ });
571
+ return gated;
572
+ }
573
+ var _cameraPreview = null;
574
+ function setCameraPreviewProvider(Component) {
575
+ _cameraPreview = Component;
576
+ }
577
+ function getCameraPreviewProvider() {
578
+ return _cameraPreview;
579
+ }
580
+ var _nativeRegistry = /* @__PURE__ */ new Map();
581
+ function registerNativePlugin(id, plugin) {
582
+ _nativeRegistry.set(id, plugin);
583
+ }
584
+ function unregisterNativePlugin(id) {
585
+ _nativeRegistry.delete(id);
586
+ }
587
+ var nativePluginRegistry = {
588
+ has(id) {
589
+ return _nativeRegistry.has(id);
590
+ },
591
+ async get(id) {
592
+ const entry = _nativeRegistry.get(id);
593
+ if (!entry) return null;
594
+ if (typeof entry === "function") {
595
+ try {
596
+ return await entry();
597
+ } catch (err) {
598
+ console.warn(`[adas-plugins] lazy native plugin '${id}' failed to load:`, err);
599
+ return null;
600
+ }
601
+ }
602
+ return entry;
603
+ }
604
+ };
605
+ var _bundleModules = /* @__PURE__ */ new Map();
606
+ function registerBundleModules(modules) {
607
+ for (const [name, mod] of Object.entries(modules)) {
608
+ _bundleModules.set(name, mod);
609
+ }
610
+ }
611
+ function resolveBundleModule(name) {
612
+ return _bundleModules.get(name);
613
+ }
614
+
615
+ // src/sdk/CameraPreview.tsx
616
+ import { jsx } from "react/jsx-runtime";
617
+ function declaredCapabilities(native) {
618
+ return native && native.__declaredCapabilities || null;
619
+ }
620
+ function CameraPreview({ native, facing = "back", style, renderUnavailable }) {
621
+ const caps = declaredCapabilities(native);
622
+ if (caps && !caps.camera) {
623
+ return unavailable2(
624
+ "this plugin did not declare `capabilities: { camera: true }`, so it may not show the camera",
625
+ renderUnavailable,
626
+ style
627
+ );
628
+ }
629
+ const Provider = getCameraPreviewProvider();
630
+ if (!Provider) {
631
+ return unavailable2(
632
+ "this app does not provide a camera preview (the host has not called setCameraPreviewProvider)",
633
+ renderUnavailable,
634
+ style
635
+ );
636
+ }
637
+ return /* @__PURE__ */ jsx(Provider, { facing, style, renderUnavailable });
638
+ }
639
+ function unavailable2(reason, render, style) {
640
+ if (render) return render(reason);
641
+ return /* @__PURE__ */ jsx(View, { style: [{ flex: 1, backgroundColor: "#000", alignItems: "center", justifyContent: "center", padding: 20 }, style], children: /* @__PURE__ */ jsx(Text, { style: { color: "#39FF66", fontSize: 12, textAlign: "center" }, children: `NO CAMERA PREVIEW
642
+ ${reason}` }) });
643
+ }
644
+
645
+ // src/sdk/usePluginTheme.ts
646
+ import { useMemo, useSyncExternalStore } from "react";
647
+ import { useColorScheme } from "react-native";
648
+ import { ada, spacing, fontSize, borderRadius } from "@ateam-ai-mobile/core";
649
+ var adaColors = {
650
+ bg: ada.paper,
651
+ surface: ada.paperSoft,
652
+ surfaceAlt: ada.paperDeep,
653
+ input: ada.paper,
654
+ border: ada.border,
655
+ text: ada.ink,
656
+ textSecondary: ada.inkSoft,
657
+ textMuted: ada.inkMuted,
658
+ accent: ada.orange,
659
+ accentSoft: ada.orangeSoft,
660
+ success: "#5A8A5C",
661
+ successSoft: "rgba(90,138,92,0.14)",
662
+ warning: "#D49A4E",
663
+ warningSoft: "rgba(212,154,78,0.16)",
664
+ error: "#C15545",
665
+ errorSoft: "rgba(193,85,69,0.14)",
666
+ purple: ada.orangeDeep,
667
+ purpleSoft: ada.orangeSoft
668
+ };
669
+ var _colors = adaColors;
670
+ var _isDark = null;
671
+ var _subscribers = /* @__PURE__ */ new Set();
672
+ function setPluginThemeColors(colors, opts) {
673
+ _colors = { ...adaColors, ...colors };
674
+ if (opts?.isDark !== void 0) _isDark = opts.isDark;
675
+ _subscribers.forEach((fn) => fn());
676
+ }
677
+ function subscribe(fn) {
678
+ _subscribers.add(fn);
679
+ return () => {
680
+ _subscribers.delete(fn);
681
+ };
682
+ }
683
+ function usePluginTheme() {
684
+ const colors = useSyncExternalStore(subscribe, () => _colors);
685
+ const hostIsDark = useSyncExternalStore(subscribe, () => _isDark);
686
+ const scheme = useColorScheme();
687
+ const isDark = hostIsDark ?? scheme === "dark";
688
+ return useMemo(() => ({
689
+ colors,
690
+ spacing: {
691
+ xs: spacing.xs,
692
+ sm: spacing.sm,
693
+ md: spacing.md,
694
+ lg: spacing.lg,
695
+ xl: spacing.xl,
696
+ xxl: spacing.xxl
697
+ },
698
+ fontSize: {
699
+ xs: fontSize.xs,
700
+ sm: fontSize.sm,
701
+ md: fontSize.md,
702
+ lg: fontSize.lg,
703
+ xl: fontSize.xl
704
+ },
705
+ borderRadius: {
706
+ sm: borderRadius.sm,
707
+ md: borderRadius.md,
708
+ lg: borderRadius.lg,
709
+ full: borderRadius.full
710
+ },
711
+ isDark
712
+ }), [colors, isDark]);
713
+ }
714
+
715
+ // src/sdk/useApi.ts
716
+ import { useMemo as useMemo2 } from "react";
717
+ function useApi(bridge) {
718
+ return useMemo2(() => {
719
+ const apiFn = async (connectorId, tool, args = {}) => {
720
+ if (!bridge) {
721
+ throw new Error("useApi: bridge is required. Pass it from plugin props.");
722
+ }
723
+ return bridge.mcpCall(tool, args, connectorId);
724
+ };
725
+ const callMethod = async (first, second, third) => {
726
+ if (!bridge) {
727
+ throw new Error("useApi: bridge is required. Pass it from plugin props.");
728
+ }
729
+ if (typeof second === "string") {
730
+ return bridge.mcpCall(second, third || {}, first);
731
+ }
732
+ if (typeof third === "string") {
733
+ return bridge.mcpCall(first, second || {}, third);
734
+ }
735
+ return bridge.mcpCall(first, second || {});
736
+ };
737
+ Object.defineProperty(apiFn, "call", {
738
+ value: callMethod,
739
+ writable: false,
740
+ configurable: false
741
+ });
742
+ return apiFn;
743
+ }, [bridge]);
744
+ }
745
+
746
+ // src/sdk/index.ts
747
+ var PluginSDK = { register, registerService, registerTools };
748
+
749
+ // src/surfaces/SurfaceDrawer.tsx
750
+ import { useEffect as useEffect2, useRef } from "react";
751
+ import {
752
+ View as View4,
753
+ Text as Text3,
754
+ Pressable as Pressable3,
755
+ StyleSheet as StyleSheet4,
756
+ Animated as Animated3,
757
+ Dimensions,
758
+ Platform as Platform2
759
+ } from "react-native";
760
+ import Svg2, { Path } from "react-native-svg";
761
+ import { ada as ada2 } from "@ateam-ai-mobile/core";
762
+
763
+ // src/surfaces/AdaOrb.tsx
764
+ import { useEffect } from "react";
765
+ import { View as View3, StyleSheet as StyleSheet3 } from "react-native";
766
+ import Animated2, {
767
+ useSharedValue,
768
+ useAnimatedProps,
769
+ withRepeat,
770
+ withTiming,
771
+ withSequence,
772
+ Easing,
773
+ cancelAnimation
774
+ } from "react-native-reanimated";
775
+ import Svg, { Circle, Defs, RadialGradient, Stop, Text as SvgText } from "react-native-svg";
776
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
777
+ var AnimatedCircle = Animated2.createAnimatedComponent(Circle);
778
+ function AdaOrb({ size = 120, state = "idle", inscription = true }) {
779
+ const showInscription = inscription && size >= 60;
780
+ const center = size / 2;
781
+ const coreR = size * 0.32;
782
+ const innerHaloR = size * 0.42;
783
+ const outerHaloR = size * 0.5;
784
+ const coreScale = useSharedValue(1);
785
+ const innerScale = useSharedValue(1);
786
+ const outerScale = useSharedValue(1);
787
+ const outerOpacity = useSharedValue(0.55);
788
+ const rippleCycle = useSharedValue(0);
789
+ const orbit1 = useSharedValue(0);
790
+ const orbit2 = useSharedValue(0);
791
+ const orbit3 = useSharedValue(0);
792
+ const beat = useSharedValue(1);
793
+ useEffect(() => {
794
+ cancelAnimation(coreScale);
795
+ cancelAnimation(innerScale);
796
+ cancelAnimation(outerScale);
797
+ cancelAnimation(outerOpacity);
798
+ cancelAnimation(rippleCycle);
799
+ cancelAnimation(orbit1);
800
+ cancelAnimation(orbit2);
801
+ cancelAnimation(orbit3);
802
+ cancelAnimation(beat);
803
+ rippleCycle.value = 0;
804
+ orbit1.value = 0;
805
+ orbit2.value = 0;
806
+ orbit3.value = 0;
807
+ beat.value = 1;
808
+ let breathMs = 3600;
809
+ let breathAmount = 0.025;
810
+ if (state === "listening") {
811
+ breathMs = 2e3;
812
+ breathAmount = 0.05;
813
+ rippleCycle.value = withRepeat(
814
+ withTiming(1, { duration: 2e3, easing: Easing.out(Easing.quad) }),
815
+ -1,
816
+ false
817
+ );
818
+ } else if (state === "thinking") {
819
+ breathMs = 2400;
820
+ breathAmount = 0.04;
821
+ orbit1.value = withRepeat(
822
+ withTiming(1, { duration: 1100, easing: Easing.linear }),
823
+ -1,
824
+ false
825
+ );
826
+ orbit2.value = withRepeat(
827
+ withTiming(1, { duration: 1900, easing: Easing.linear }),
828
+ -1,
829
+ false
830
+ );
831
+ orbit3.value = withRepeat(
832
+ withTiming(-1, { duration: 2700, easing: Easing.linear }),
833
+ -1,
834
+ false
835
+ );
836
+ } else if (state === "speaking") {
837
+ breathMs = 700;
838
+ breathAmount = 0.13;
839
+ beat.value = withRepeat(
840
+ withSequence(
841
+ withTiming(1.08, { duration: 90, easing: Easing.out(Easing.quad) }),
842
+ withTiming(1, { duration: 130, easing: Easing.in(Easing.quad) }),
843
+ withTiming(1.05, { duration: 80, easing: Easing.out(Easing.quad) }),
844
+ withTiming(1, { duration: 200, easing: Easing.in(Easing.quad) }),
845
+ withTiming(1, { duration: 280 })
846
+ ),
847
+ -1,
848
+ false
849
+ );
850
+ }
851
+ const breathEasing = state === "speaking" ? Easing.out(Easing.cubic) : Easing.inOut(Easing.sin);
852
+ coreScale.value = withRepeat(
853
+ withSequence(
854
+ withTiming(1 + breathAmount, { duration: breathMs, easing: breathEasing }),
855
+ withTiming(1, { duration: breathMs, easing: breathEasing })
856
+ ),
857
+ -1,
858
+ false
859
+ );
860
+ innerScale.value = withRepeat(
861
+ withSequence(
862
+ withTiming(1 + breathAmount * 1.4, { duration: breathMs * 1.15, easing: breathEasing }),
863
+ withTiming(1, { duration: breathMs * 1.15, easing: breathEasing })
864
+ ),
865
+ -1,
866
+ false
867
+ );
868
+ outerScale.value = withRepeat(
869
+ withSequence(
870
+ withTiming(1 + breathAmount * 1.8, { duration: breathMs * 1.3, easing: breathEasing }),
871
+ withTiming(1, { duration: breathMs * 1.3, easing: breathEasing })
872
+ ),
873
+ -1,
874
+ false
875
+ );
876
+ outerOpacity.value = withRepeat(
877
+ withSequence(
878
+ withTiming(state === "idle" ? 0.55 : 0.8, { duration: breathMs * 1.3, easing: breathEasing }),
879
+ withTiming(0.35, { duration: breathMs * 1.3, easing: breathEasing })
880
+ ),
881
+ -1,
882
+ false
883
+ );
884
+ }, [state]);
885
+ const coreProps = useAnimatedProps(() => ({
886
+ r: coreR * coreScale.value * beat.value
887
+ }));
888
+ const innerProps = useAnimatedProps(() => ({
889
+ r: innerHaloR * innerScale.value * beat.value
890
+ }));
891
+ const outerProps = useAnimatedProps(() => ({
892
+ r: outerHaloR * outerScale.value,
893
+ opacity: outerOpacity.value
894
+ }));
895
+ const ripple1Props = useAnimatedProps(() => {
896
+ const t = rippleCycle.value;
897
+ return {
898
+ r: outerHaloR * (1 + t * 0.55),
899
+ opacity: state === "listening" ? 0.55 * (1 - t) : 0
900
+ };
901
+ });
902
+ const ripple2Props = useAnimatedProps(() => {
903
+ const t = (rippleCycle.value + 0.34) % 1;
904
+ return {
905
+ r: outerHaloR * (1 + t * 0.55),
906
+ opacity: state === "listening" ? 0.45 * (1 - t) : 0
907
+ };
908
+ });
909
+ const ripple3Props = useAnimatedProps(() => {
910
+ const t = (rippleCycle.value + 0.67) % 1;
911
+ return {
912
+ r: outerHaloR * (1 + t * 0.55),
913
+ opacity: state === "listening" ? 0.35 * (1 - t) : 0
914
+ };
915
+ });
916
+ const spark1Props = useAnimatedProps(() => {
917
+ const angle = orbit1.value * Math.PI * 2 - Math.PI / 2;
918
+ const r = coreR * 0.55;
919
+ return {
920
+ cx: center + Math.cos(angle) * r,
921
+ cy: center + Math.sin(angle) * r,
922
+ opacity: state === "thinking" ? 1 : 0
923
+ };
924
+ });
925
+ const spark2Props = useAnimatedProps(() => {
926
+ const angle = orbit2.value * Math.PI * 2 + Math.PI * 0.6;
927
+ const r = coreR * 0.85;
928
+ return {
929
+ cx: center + Math.cos(angle) * r,
930
+ cy: center + Math.sin(angle) * r,
931
+ opacity: state === "thinking" ? 0.9 : 0
932
+ };
933
+ });
934
+ const spark3Props = useAnimatedProps(() => {
935
+ const angle = orbit3.value * Math.PI * 2 + Math.PI * 1.3;
936
+ const r = coreR * 1.05;
937
+ return {
938
+ cx: center + Math.cos(angle) * r,
939
+ cy: center + Math.sin(angle) * r,
940
+ opacity: state === "thinking" ? 0.7 : 0
941
+ };
942
+ });
943
+ return /* @__PURE__ */ jsx2(View3, { style: [styles2.wrap, { width: size, height: size }], children: /* @__PURE__ */ jsxs(Svg, { width: size, height: size, children: [
944
+ /* @__PURE__ */ jsxs(Defs, { children: [
945
+ /* @__PURE__ */ jsxs(RadialGradient, { id: "adaCore", cx: "36%", cy: "30%", r: "70%", children: [
946
+ /* @__PURE__ */ jsx2(Stop, { offset: "0%", stopColor: "#FFE0B0", stopOpacity: "1" }),
947
+ /* @__PURE__ */ jsx2(Stop, { offset: "28%", stopColor: "#FFA85A", stopOpacity: "1" }),
948
+ /* @__PURE__ */ jsx2(Stop, { offset: "65%", stopColor: "#FF7A28", stopOpacity: "1" }),
949
+ /* @__PURE__ */ jsx2(Stop, { offset: "100%", stopColor: "#B8410A", stopOpacity: "1" })
950
+ ] }),
951
+ /* @__PURE__ */ jsxs(RadialGradient, { id: "adaInner", cx: "50%", cy: "50%", r: "50%", children: [
952
+ /* @__PURE__ */ jsx2(Stop, { offset: "0%", stopColor: "#FF8A3C", stopOpacity: "0.55" }),
953
+ /* @__PURE__ */ jsx2(Stop, { offset: "100%", stopColor: "#FF7028", stopOpacity: "0" })
954
+ ] }),
955
+ /* @__PURE__ */ jsxs(RadialGradient, { id: "adaOuter", cx: "50%", cy: "50%", r: "50%", children: [
956
+ /* @__PURE__ */ jsx2(Stop, { offset: "0%", stopColor: "#FF7A28", stopOpacity: "0.4" }),
957
+ /* @__PURE__ */ jsx2(Stop, { offset: "100%", stopColor: "#FF6018", stopOpacity: "0" })
958
+ ] }),
959
+ /* @__PURE__ */ jsxs(RadialGradient, { id: "adaSpark", cx: "50%", cy: "50%", r: "50%", children: [
960
+ /* @__PURE__ */ jsx2(Stop, { offset: "0%", stopColor: "#FFFAEB", stopOpacity: "1" }),
961
+ /* @__PURE__ */ jsx2(Stop, { offset: "60%", stopColor: "#FFD095", stopOpacity: "0.9" }),
962
+ /* @__PURE__ */ jsx2(Stop, { offset: "100%", stopColor: "#FFA85A", stopOpacity: "0" })
963
+ ] })
964
+ ] }),
965
+ /* @__PURE__ */ jsx2(
966
+ AnimatedCircle,
967
+ {
968
+ cx: center,
969
+ cy: center,
970
+ stroke: "#FF7A28",
971
+ strokeWidth: 1.5,
972
+ fill: "none",
973
+ animatedProps: ripple1Props
974
+ }
975
+ ),
976
+ /* @__PURE__ */ jsx2(
977
+ AnimatedCircle,
978
+ {
979
+ cx: center,
980
+ cy: center,
981
+ stroke: "#FF7A28",
982
+ strokeWidth: 1.5,
983
+ fill: "none",
984
+ animatedProps: ripple2Props
985
+ }
986
+ ),
987
+ /* @__PURE__ */ jsx2(
988
+ AnimatedCircle,
989
+ {
990
+ cx: center,
991
+ cy: center,
992
+ stroke: "#FF7A28",
993
+ strokeWidth: 1.5,
994
+ fill: "none",
995
+ animatedProps: ripple3Props
996
+ }
997
+ ),
998
+ /* @__PURE__ */ jsx2(AnimatedCircle, { cx: center, cy: center, fill: "url(#adaOuter)", animatedProps: outerProps }),
999
+ /* @__PURE__ */ jsx2(AnimatedCircle, { cx: center, cy: center, fill: "url(#adaInner)", animatedProps: innerProps }),
1000
+ /* @__PURE__ */ jsx2(AnimatedCircle, { cx: center, cy: center, fill: "url(#adaCore)", animatedProps: coreProps }),
1001
+ /* @__PURE__ */ jsx2(
1002
+ AnimatedCircle,
1003
+ {
1004
+ r: Math.max(3, size * 0.05),
1005
+ fill: "url(#adaSpark)",
1006
+ animatedProps: spark1Props
1007
+ }
1008
+ ),
1009
+ /* @__PURE__ */ jsx2(
1010
+ AnimatedCircle,
1011
+ {
1012
+ r: Math.max(2.5, size * 0.04),
1013
+ fill: "url(#adaSpark)",
1014
+ animatedProps: spark2Props
1015
+ }
1016
+ ),
1017
+ /* @__PURE__ */ jsx2(
1018
+ AnimatedCircle,
1019
+ {
1020
+ r: Math.max(2, size * 0.032),
1021
+ fill: "url(#adaSpark)",
1022
+ animatedProps: spark3Props
1023
+ }
1024
+ ),
1025
+ showInscription && /* @__PURE__ */ jsx2(
1026
+ SvgText,
1027
+ {
1028
+ x: center,
1029
+ y: center + size * 0.11,
1030
+ fontSize: size * 0.34,
1031
+ fontWeight: "600",
1032
+ fill: "#FFF5E0",
1033
+ textAnchor: "middle",
1034
+ letterSpacing: -size * 5e-3,
1035
+ children: "iA"
1036
+ }
1037
+ )
1038
+ ] }) });
1039
+ }
1040
+ var styles2 = StyleSheet3.create({
1041
+ wrap: {
1042
+ alignItems: "center",
1043
+ justifyContent: "center"
1044
+ }
1045
+ });
1046
+
1047
+ // src/surfaces/SurfaceDrawer.tsx
1048
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
1049
+ var SCREEN_H = Dimensions.get("window").height;
1050
+ var fontFam = Platform2.OS === "ios" ? "SF Pro Rounded" : void 0;
1051
+ function SurfaceDrawer({
1052
+ visible,
1053
+ onClose,
1054
+ title,
1055
+ subtitle,
1056
+ privacy,
1057
+ showOrb = true,
1058
+ heightRatio = 0.85,
1059
+ children
1060
+ }) {
1061
+ const sheetH = Math.round(SCREEN_H * heightRatio);
1062
+ const fadeAnim = useRef(new Animated3.Value(0)).current;
1063
+ const slideAnim = useRef(new Animated3.Value(sheetH)).current;
1064
+ useEffect2(() => {
1065
+ if (visible) {
1066
+ Animated3.parallel([
1067
+ Animated3.timing(fadeAnim, { toValue: 1, duration: 220, useNativeDriver: true }),
1068
+ Animated3.spring(slideAnim, { toValue: 0, useNativeDriver: true, tension: 80, friction: 12 })
1069
+ ]).start();
1070
+ } else {
1071
+ fadeAnim.setValue(0);
1072
+ slideAnim.setValue(sheetH);
1073
+ }
1074
+ }, [visible]);
1075
+ const close = () => {
1076
+ Animated3.parallel([
1077
+ Animated3.timing(fadeAnim, { toValue: 0, duration: 160, useNativeDriver: true }),
1078
+ Animated3.timing(slideAnim, { toValue: sheetH, duration: 200, useNativeDriver: true })
1079
+ ]).start(() => onClose());
1080
+ };
1081
+ if (!visible) return null;
1082
+ return /* @__PURE__ */ jsxs2(Animated3.View, { style: [styles3.overlay, { opacity: fadeAnim }], pointerEvents: "auto", children: [
1083
+ /* @__PURE__ */ jsx3(Pressable3, { style: StyleSheet4.absoluteFill, onPress: close }),
1084
+ /* @__PURE__ */ jsxs2(
1085
+ Animated3.View,
1086
+ {
1087
+ style: [
1088
+ styles3.sheet,
1089
+ { height: sheetH, transform: [{ translateY: slideAnim }] }
1090
+ ],
1091
+ children: [
1092
+ /* @__PURE__ */ jsx3(View4, { style: styles3.handle }),
1093
+ /* @__PURE__ */ jsxs2(View4, { style: styles3.header, children: [
1094
+ showOrb ? /* @__PURE__ */ jsx3(View4, { style: styles3.headerOrb, children: /* @__PURE__ */ jsx3(AdaOrb, { size: 36, state: "idle" }) }) : null,
1095
+ /* @__PURE__ */ jsxs2(View4, { style: { flex: 1 }, children: [
1096
+ /* @__PURE__ */ jsx3(Text3, { style: styles3.title, children: title }),
1097
+ subtitle ? /* @__PURE__ */ jsx3(Text3, { style: styles3.subtitle, children: subtitle }) : null,
1098
+ privacy ? /* @__PURE__ */ jsxs2(View4, { style: styles3.privacyPill, children: [
1099
+ /* @__PURE__ */ jsxs2(Svg2, { width: 11, height: 11, viewBox: "0 0 24 24", fill: "none", stroke: ada2.inkSoft, strokeWidth: 2.5, strokeLinecap: "round", strokeLinejoin: "round", children: [
1100
+ /* @__PURE__ */ jsx3(Path, { d: "M19 11H5a2 2 0 00-2 2v7a2 2 0 002 2h14a2 2 0 002-2v-7a2 2 0 00-2-2z" }),
1101
+ /* @__PURE__ */ jsx3(Path, { d: "M7 11V7a5 5 0 0110 0v4" })
1102
+ ] }),
1103
+ /* @__PURE__ */ jsx3(Text3, { style: styles3.privacyText, children: "Only you can see this" })
1104
+ ] }) : null
1105
+ ] }),
1106
+ /* @__PURE__ */ jsx3(
1107
+ Pressable3,
1108
+ {
1109
+ accessibilityRole: "button",
1110
+ accessibilityLabel: "Close",
1111
+ style: styles3.closeBtn,
1112
+ onPress: close,
1113
+ hitSlop: 12,
1114
+ children: /* @__PURE__ */ jsx3(Svg2, { width: 18, height: 18, viewBox: "0 0 24 24", fill: "none", stroke: ada2.inkSoft, strokeWidth: 2.2, strokeLinecap: "round", children: /* @__PURE__ */ jsx3(Path, { d: "M18 6L6 18M6 6l12 12" }) })
1115
+ }
1116
+ )
1117
+ ] }),
1118
+ /* @__PURE__ */ jsx3(View4, { style: styles3.body, children })
1119
+ ]
1120
+ }
1121
+ )
1122
+ ] });
1123
+ }
1124
+ var styles3 = StyleSheet4.create({
1125
+ overlay: {
1126
+ position: "absolute",
1127
+ top: 0,
1128
+ left: 0,
1129
+ right: 0,
1130
+ bottom: 0,
1131
+ backgroundColor: "rgba(26, 20, 16, 0.35)",
1132
+ justifyContent: "flex-end",
1133
+ zIndex: 999,
1134
+ elevation: 999
1135
+ },
1136
+ sheet: {
1137
+ backgroundColor: ada2.paper,
1138
+ borderTopLeftRadius: 28,
1139
+ borderTopRightRadius: 28,
1140
+ overflow: "hidden"
1141
+ },
1142
+ handle: {
1143
+ width: 40,
1144
+ height: 4,
1145
+ borderRadius: 2,
1146
+ backgroundColor: ada2.inkMuted,
1147
+ opacity: 0.3,
1148
+ alignSelf: "center",
1149
+ marginTop: 10,
1150
+ marginBottom: 6
1151
+ },
1152
+ header: {
1153
+ flexDirection: "row",
1154
+ alignItems: "center",
1155
+ paddingHorizontal: 22,
1156
+ paddingVertical: 16,
1157
+ gap: 12,
1158
+ borderBottomWidth: 1,
1159
+ borderBottomColor: ada2.border
1160
+ },
1161
+ headerOrb: {
1162
+ width: 36,
1163
+ height: 36,
1164
+ alignItems: "center",
1165
+ justifyContent: "center"
1166
+ },
1167
+ title: {
1168
+ fontSize: 17,
1169
+ fontWeight: "600",
1170
+ color: ada2.ink,
1171
+ letterSpacing: -0.2,
1172
+ fontFamily: fontFam
1173
+ },
1174
+ subtitle: {
1175
+ fontSize: 13,
1176
+ fontWeight: "400",
1177
+ color: ada2.inkSoft,
1178
+ marginTop: 2,
1179
+ letterSpacing: -0.1,
1180
+ fontFamily: fontFam
1181
+ },
1182
+ privacyPill: {
1183
+ flexDirection: "row",
1184
+ alignItems: "center",
1185
+ gap: 5,
1186
+ marginTop: 4
1187
+ },
1188
+ privacyText: {
1189
+ fontSize: 11,
1190
+ fontWeight: "500",
1191
+ color: ada2.inkSoft,
1192
+ letterSpacing: 0.2,
1193
+ fontFamily: fontFam
1194
+ },
1195
+ closeBtn: {
1196
+ width: 32,
1197
+ height: 32,
1198
+ borderRadius: 16,
1199
+ backgroundColor: ada2.paperSoft,
1200
+ justifyContent: "center",
1201
+ alignItems: "center"
1202
+ },
1203
+ body: {
1204
+ flex: 1
1205
+ }
1206
+ });
1207
+
1208
+ // src/surfaces/SurfaceCard.tsx
1209
+ import {
1210
+ View as View5,
1211
+ Text as Text4,
1212
+ Pressable as Pressable4,
1213
+ StyleSheet as StyleSheet5,
1214
+ Platform as Platform3
1215
+ } from "react-native";
1216
+ import { ada as ada3, borderRadius as borderRadius2 } from "@ateam-ai-mobile/core";
1217
+ import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
1218
+ var fontFam2 = Platform3.OS === "ios" ? "SF Pro Rounded" : void 0;
1219
+ function SurfaceCard({
1220
+ icon,
1221
+ title,
1222
+ subtitle,
1223
+ onPress,
1224
+ onLongPress,
1225
+ showArrow,
1226
+ children
1227
+ }) {
1228
+ const arrow = showArrow ?? !!onPress;
1229
+ const handlePress = () => {
1230
+ if (!onPress) return;
1231
+ getHaptics()?.impact("light");
1232
+ onPress();
1233
+ };
1234
+ const handleLongPress = () => {
1235
+ if (!onLongPress) return;
1236
+ getHaptics()?.impact("medium");
1237
+ onLongPress();
1238
+ };
1239
+ return /* @__PURE__ */ jsxs3(
1240
+ Pressable4,
1241
+ {
1242
+ accessibilityRole: "button",
1243
+ accessibilityLabel: [icon, title, subtitle].filter(Boolean).join(", "),
1244
+ accessibilityHint: onLongPress ? "Long-press for more options" : void 0,
1245
+ style: styles4.card,
1246
+ onPress: onPress ? handlePress : void 0,
1247
+ onLongPress: onLongPress ? handleLongPress : void 0,
1248
+ disabled: !onPress && !onLongPress,
1249
+ children: [
1250
+ /* @__PURE__ */ jsxs3(View5, { style: styles4.row, children: [
1251
+ icon ? /* @__PURE__ */ jsx4(Text4, { style: styles4.icon, children: icon }) : null,
1252
+ /* @__PURE__ */ jsxs3(View5, { style: { flex: 1 }, children: [
1253
+ /* @__PURE__ */ jsx4(Text4, { style: styles4.title, children: title }),
1254
+ subtitle ? /* @__PURE__ */ jsx4(Text4, { style: styles4.subtitle, children: subtitle }) : null
1255
+ ] }),
1256
+ arrow ? /* @__PURE__ */ jsx4(Text4, { style: styles4.arrow, children: "\u2192" }) : null
1257
+ ] }),
1258
+ children ? /* @__PURE__ */ jsx4(View5, { style: styles4.body, children }) : null
1259
+ ]
1260
+ }
1261
+ );
1262
+ }
1263
+ var styles4 = StyleSheet5.create({
1264
+ card: {
1265
+ backgroundColor: ada3.paperSoft,
1266
+ borderWidth: 1,
1267
+ borderColor: ada3.border,
1268
+ borderRadius: borderRadius2.xl,
1269
+ paddingHorizontal: 16,
1270
+ paddingVertical: 14
1271
+ },
1272
+ row: {
1273
+ flexDirection: "row",
1274
+ alignItems: "center",
1275
+ gap: 14
1276
+ },
1277
+ icon: {
1278
+ fontSize: 22
1279
+ },
1280
+ title: {
1281
+ fontSize: 15,
1282
+ fontWeight: "600",
1283
+ color: ada3.ink,
1284
+ letterSpacing: -0.2,
1285
+ fontFamily: fontFam2
1286
+ },
1287
+ subtitle: {
1288
+ fontSize: 13,
1289
+ fontWeight: "400",
1290
+ color: ada3.inkMuted,
1291
+ marginTop: 2,
1292
+ letterSpacing: -0.1,
1293
+ fontFamily: fontFam2
1294
+ },
1295
+ arrow: {
1296
+ fontSize: 18,
1297
+ color: ada3.inkMuted,
1298
+ fontWeight: "400"
1299
+ },
1300
+ body: {
1301
+ marginTop: 10,
1302
+ paddingTop: 10,
1303
+ borderTopWidth: 1,
1304
+ borderTopColor: ada3.border
1305
+ }
1306
+ });
1307
+
1308
+ // src/surfaces/SurfaceFullscreen.tsx
1309
+ import { useEffect as useEffect3, useRef as useRef2 } from "react";
1310
+ import {
1311
+ View as View6,
1312
+ Text as Text5,
1313
+ Pressable as Pressable5,
1314
+ StyleSheet as StyleSheet6,
1315
+ Animated as Animated4,
1316
+ Platform as Platform4
1317
+ } from "react-native";
1318
+ import Svg3, { Path as Path2 } from "react-native-svg";
1319
+ import { ada as ada4 } from "@ateam-ai-mobile/core";
1320
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
1321
+ var fontFam3 = Platform4.OS === "ios" ? "SF Pro Rounded" : void 0;
1322
+ function SurfaceFullscreen({
1323
+ visible,
1324
+ onClose,
1325
+ status,
1326
+ hero,
1327
+ children,
1328
+ showWordmark = true,
1329
+ closeIcon = "x",
1330
+ closeLabel = "Close"
1331
+ }) {
1332
+ const fadeAnim = useRef2(new Animated4.Value(0)).current;
1333
+ const heroScale = useRef2(new Animated4.Value(0.6)).current;
1334
+ useEffect3(() => {
1335
+ if (visible) {
1336
+ Animated4.parallel([
1337
+ Animated4.timing(fadeAnim, { toValue: 1, duration: 280, useNativeDriver: true }),
1338
+ Animated4.spring(heroScale, { toValue: 1, useNativeDriver: true, tension: 60, friction: 11 })
1339
+ ]).start();
1340
+ } else {
1341
+ fadeAnim.setValue(0);
1342
+ heroScale.setValue(0.6);
1343
+ }
1344
+ }, [visible]);
1345
+ const close = () => {
1346
+ Animated4.parallel([
1347
+ Animated4.timing(fadeAnim, { toValue: 0, duration: 180, useNativeDriver: true }),
1348
+ Animated4.timing(heroScale, { toValue: 0.6, duration: 180, useNativeDriver: true })
1349
+ ]).start(() => onClose());
1350
+ };
1351
+ if (!visible) return null;
1352
+ const renderCloseIcon = () => {
1353
+ if (closeIcon === "hangup") {
1354
+ return /* @__PURE__ */ jsx5(Svg3, { width: 22, height: 22, viewBox: "0 0 24 24", fill: ada4.paper, children: /* @__PURE__ */ jsx5(Path2, { d: "M3.68 16.07l3.92-3.11c.28-.23.68-.28 1.01-.14l2.77 1.15c.36.15.61.5.61.89v2.82c4.34-.76 7.93-4.35 8.69-8.69h-2.82c-.39 0-.74-.25-.89-.61L16.12 5.6c-.13-.33-.09-.73.14-1.01l3.11-3.92c.29-.37.81-.41 1.15-.08l3.24 3.24c.2.2.31.47.31.76C24 14.44 14.44 24 4.59 24c-.29 0-.56-.11-.76-.31L.59 20.45c-.33-.34-.29-.86.09-1.15z" }) });
1355
+ }
1356
+ if (closeIcon === "x") {
1357
+ return /* @__PURE__ */ jsx5(Svg3, { width: 20, height: 20, viewBox: "0 0 24 24", fill: "none", stroke: ada4.paper, strokeWidth: 2.5, strokeLinecap: "round", children: /* @__PURE__ */ jsx5(Path2, { d: "M18 6L6 18M6 6l12 12" }) });
1358
+ }
1359
+ return closeIcon;
1360
+ };
1361
+ return /* @__PURE__ */ jsxs4(Animated4.View, { style: [styles5.overlay, { opacity: fadeAnim }], pointerEvents: "auto", children: [
1362
+ /* @__PURE__ */ jsxs4(View6, { style: styles5.topBar, children: [
1363
+ showWordmark ? /* @__PURE__ */ jsx5(Text5, { style: styles5.wordmark, children: "ada" }) : null,
1364
+ status ? /* @__PURE__ */ jsx5(Text5, { style: styles5.status, children: status }) : null
1365
+ ] }),
1366
+ hero ? /* @__PURE__ */ jsx5(View6, { style: styles5.heroWrap, children: /* @__PURE__ */ jsx5(Animated4.View, { style: { transform: [{ scale: heroScale }] }, children: hero }) }) : null,
1367
+ /* @__PURE__ */ jsx5(View6, { style: styles5.body, children }),
1368
+ /* @__PURE__ */ jsxs4(View6, { style: styles5.bottomBar, children: [
1369
+ /* @__PURE__ */ jsx5(
1370
+ Pressable5,
1371
+ {
1372
+ accessibilityRole: "button",
1373
+ accessibilityLabel: closeLabel,
1374
+ style: styles5.closeBtn,
1375
+ onPress: close,
1376
+ hitSlop: 12,
1377
+ children: renderCloseIcon()
1378
+ }
1379
+ ),
1380
+ closeLabel ? /* @__PURE__ */ jsx5(Text5, { style: styles5.closeLabel, children: closeLabel }) : null
1381
+ ] })
1382
+ ] });
1383
+ }
1384
+ var styles5 = StyleSheet6.create({
1385
+ overlay: {
1386
+ position: "absolute",
1387
+ top: 0,
1388
+ left: 0,
1389
+ right: 0,
1390
+ bottom: 0,
1391
+ backgroundColor: ada4.paper,
1392
+ zIndex: 1e3,
1393
+ elevation: 1e3
1394
+ },
1395
+ topBar: {
1396
+ paddingTop: Platform4.OS === "ios" ? 64 : 36,
1397
+ paddingHorizontal: 24,
1398
+ alignItems: "center",
1399
+ gap: 6
1400
+ },
1401
+ wordmark: {
1402
+ fontSize: 14,
1403
+ fontFamily: fontFam3,
1404
+ fontWeight: "500",
1405
+ color: ada4.inkMuted,
1406
+ letterSpacing: 4
1407
+ },
1408
+ status: {
1409
+ fontSize: 17,
1410
+ fontFamily: fontFam3,
1411
+ fontWeight: "500",
1412
+ color: ada4.ink,
1413
+ letterSpacing: -0.2
1414
+ },
1415
+ heroWrap: {
1416
+ paddingTop: 24,
1417
+ paddingBottom: 12,
1418
+ alignItems: "center",
1419
+ justifyContent: "center"
1420
+ },
1421
+ body: {
1422
+ flex: 1
1423
+ },
1424
+ bottomBar: {
1425
+ paddingBottom: Platform4.OS === "ios" ? 48 : 32,
1426
+ paddingTop: 12,
1427
+ alignItems: "center",
1428
+ gap: 8
1429
+ },
1430
+ closeBtn: {
1431
+ width: 64,
1432
+ height: 64,
1433
+ borderRadius: 32,
1434
+ backgroundColor: ada4.ink,
1435
+ justifyContent: "center",
1436
+ alignItems: "center",
1437
+ shadowColor: ada4.ink,
1438
+ shadowOffset: { width: 0, height: 8 },
1439
+ shadowOpacity: 0.18,
1440
+ shadowRadius: 14,
1441
+ elevation: 8
1442
+ },
1443
+ closeLabel: {
1444
+ fontSize: 13,
1445
+ fontFamily: fontFam3,
1446
+ fontWeight: "500",
1447
+ color: ada4.inkMuted,
1448
+ letterSpacing: 0.3
1449
+ }
1450
+ });
1451
+
1452
+ // src/registry/store.ts
1453
+ import { create } from "zustand";
1454
+ var useSurfaceStore = create((set, get) => ({
1455
+ manifests: {},
1456
+ activeDrawer: null,
1457
+ activeFullscreen: null,
1458
+ activeProps: {},
1459
+ mountKey: 0,
1460
+ register: (manifest) => set((s) => ({ manifests: { ...s.manifests, [manifest.id]: manifest } })),
1461
+ unregister: (id) => set((s) => {
1462
+ const next = { ...s.manifests };
1463
+ delete next[id];
1464
+ const nextProps = { ...s.activeProps };
1465
+ delete nextProps[id];
1466
+ return { manifests: next, activeProps: nextProps };
1467
+ }),
1468
+ show: (id, props) => {
1469
+ const m = get().manifests[id];
1470
+ if (!m) {
1471
+ console.warn("[SurfaceStore] show: unknown surface id", id);
1472
+ return;
1473
+ }
1474
+ set((s) => {
1475
+ const nextProps = props !== void 0 ? { ...s.activeProps, [id]: props } : s.activeProps;
1476
+ const mountKey = s.mountKey + 1;
1477
+ if (m.type === "drawer") return { activeDrawer: id, activeProps: nextProps, mountKey };
1478
+ if (m.type === "fullscreen") return { activeFullscreen: id, activeProps: nextProps, mountKey };
1479
+ return { mountKey };
1480
+ });
1481
+ },
1482
+ hide: (id) => {
1483
+ const s = get();
1484
+ if (!id) {
1485
+ const cleanup2 = { ...s.activeProps };
1486
+ if (s.activeDrawer) delete cleanup2[s.activeDrawer];
1487
+ if (s.activeFullscreen) delete cleanup2[s.activeFullscreen];
1488
+ set({ activeDrawer: null, activeFullscreen: null, activeProps: cleanup2 });
1489
+ return;
1490
+ }
1491
+ const cleanup = { ...s.activeProps };
1492
+ delete cleanup[id];
1493
+ const patch = { activeProps: cleanup };
1494
+ if (s.activeDrawer === id) patch.activeDrawer = null;
1495
+ if (s.activeFullscreen === id) patch.activeFullscreen = null;
1496
+ set(patch);
1497
+ },
1498
+ list: (filter) => {
1499
+ const all = Object.values(get().manifests);
1500
+ return all.filter((m) => {
1501
+ if (filter?.type && m.type !== filter.type) return false;
1502
+ if (filter?.visibility && !filter.visibility.includes(m.visibility)) return false;
1503
+ if (filter?.placement) {
1504
+ if (filter.placement === "unset") {
1505
+ if (m.placement) return false;
1506
+ } else if (m.placement !== filter.placement) {
1507
+ return false;
1508
+ }
1509
+ }
1510
+ return true;
1511
+ });
1512
+ }
1513
+ }));
1514
+ function isMountSurface(m) {
1515
+ return m.type === "drawer" || m.type === "fullscreen";
1516
+ }
1517
+ function isInlineSurface(m) {
1518
+ return m.type === "card" || m.type === "header" || m.type === "ambient" || m.type === "nudge";
1519
+ }
1520
+
1521
+ // src/registry/SurfaceDispatcher.tsx
1522
+ import { useEffect as useEffect4 } from "react";
1523
+ import { pluginCommandEmitter } from "@ateam-ai-mobile/core";
1524
+ import { Fragment, jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
1525
+ function SurfaceDispatcher() {
1526
+ const manifests = useSurfaceStore((s) => s.manifests);
1527
+ const activeDrawer = useSurfaceStore((s) => s.activeDrawer);
1528
+ const activeFullscreen = useSurfaceStore((s) => s.activeFullscreen);
1529
+ const activeProps = useSurfaceStore((s) => s.activeProps);
1530
+ const mountKey = useSurfaceStore((s) => s.mountKey);
1531
+ const hide = useSurfaceStore((s) => s.hide);
1532
+ useEffect4(() => {
1533
+ const unsub = pluginCommandEmitter.on("plugin-close", ({ pluginId } = {}) => {
1534
+ if (!pluginId) return;
1535
+ const s = useSurfaceStore.getState();
1536
+ if (s.activeDrawer === pluginId || s.activeFullscreen === pluginId) {
1537
+ s.hide(pluginId);
1538
+ }
1539
+ });
1540
+ return unsub;
1541
+ }, []);
1542
+ const drawer = activeDrawer ? manifests[activeDrawer] : null;
1543
+ const fullscreen = activeFullscreen ? manifests[activeFullscreen] : null;
1544
+ const drawerProps = activeDrawer ? activeProps[activeDrawer] : void 0;
1545
+ const fullscreenProps = activeFullscreen ? activeProps[activeFullscreen] : void 0;
1546
+ return /* @__PURE__ */ jsxs5(Fragment, { children: [
1547
+ drawer && drawer.type === "drawer" && drawer.Component ? /* @__PURE__ */ jsx6(
1548
+ drawer.Component,
1549
+ {
1550
+ dismiss: () => hide(drawer.id),
1551
+ props: drawerProps
1552
+ },
1553
+ `drawer-${drawer.id}-${mountKey}`
1554
+ ) : null,
1555
+ fullscreen && fullscreen.type === "fullscreen" && fullscreen.Component ? /* @__PURE__ */ jsx6(
1556
+ fullscreen.Component,
1557
+ {
1558
+ dismiss: () => hide(fullscreen.id),
1559
+ props: fullscreenProps
1560
+ },
1561
+ `fullscreen-${fullscreen.id}-${mountKey}`
1562
+ ) : null
1563
+ ] });
1564
+ }
1565
+
1566
+ // src/utils/sha256.ts
1567
+ var K = new Uint32Array([
1568
+ 1116352408,
1569
+ 1899447441,
1570
+ 3049323471,
1571
+ 3921009573,
1572
+ 961987163,
1573
+ 1508970993,
1574
+ 2453635748,
1575
+ 2870763221,
1576
+ 3624381080,
1577
+ 310598401,
1578
+ 607225278,
1579
+ 1426881987,
1580
+ 1925078388,
1581
+ 2162078206,
1582
+ 2614888103,
1583
+ 3248222580,
1584
+ 3835390401,
1585
+ 4022224774,
1586
+ 264347078,
1587
+ 604807628,
1588
+ 770255983,
1589
+ 1249150122,
1590
+ 1555081692,
1591
+ 1996064986,
1592
+ 2554220882,
1593
+ 2821834349,
1594
+ 2952996808,
1595
+ 3210313671,
1596
+ 3336571891,
1597
+ 3584528711,
1598
+ 113926993,
1599
+ 338241895,
1600
+ 666307205,
1601
+ 773529912,
1602
+ 1294757372,
1603
+ 1396182291,
1604
+ 1695183700,
1605
+ 1986661051,
1606
+ 2177026350,
1607
+ 2456956037,
1608
+ 2730485921,
1609
+ 2820302411,
1610
+ 3259730800,
1611
+ 3345764771,
1612
+ 3516065817,
1613
+ 3600352804,
1614
+ 4094571909,
1615
+ 275423344,
1616
+ 430227734,
1617
+ 506948616,
1618
+ 659060556,
1619
+ 883997877,
1620
+ 958139571,
1621
+ 1322822218,
1622
+ 1537002063,
1623
+ 1747873779,
1624
+ 1955562222,
1625
+ 2024104815,
1626
+ 2227730452,
1627
+ 2361852424,
1628
+ 2428436474,
1629
+ 2756734187,
1630
+ 3204031479,
1631
+ 3329325298
1632
+ ]);
1633
+ var rotr = (n, x) => x >>> n | x << 32 - n;
1634
+ function sha256Hex(message) {
1635
+ const utf8 = unescape(encodeURIComponent(message));
1636
+ const bytes = new Uint8Array(utf8.length);
1637
+ for (let i = 0; i < utf8.length; i++) bytes[i] = utf8.charCodeAt(i);
1638
+ const bitLen = bytes.length * 8;
1639
+ const padLen = (56 - (bytes.length + 1) % 64 + 64) % 64;
1640
+ const buf = new Uint8Array(bytes.length + 1 + padLen + 8);
1641
+ buf.set(bytes);
1642
+ buf[bytes.length] = 128;
1643
+ const len = buf.length;
1644
+ buf[len - 4] = bitLen >>> 24 & 255;
1645
+ buf[len - 3] = bitLen >>> 16 & 255;
1646
+ buf[len - 2] = bitLen >>> 8 & 255;
1647
+ buf[len - 1] = bitLen & 255;
1648
+ const h = new Uint32Array([
1649
+ 1779033703,
1650
+ 3144134277,
1651
+ 1013904242,
1652
+ 2773480762,
1653
+ 1359893119,
1654
+ 2600822924,
1655
+ 528734635,
1656
+ 1541459225
1657
+ ]);
1658
+ const w = new Uint32Array(64);
1659
+ for (let i = 0; i < buf.length; i += 64) {
1660
+ for (let t = 0; t < 16; t++) {
1661
+ const j = i + t * 4;
1662
+ w[t] = buf[j] << 24 | buf[j + 1] << 16 | buf[j + 2] << 8 | buf[j + 3];
1663
+ }
1664
+ for (let t = 16; t < 64; t++) {
1665
+ const s0 = rotr(7, w[t - 15]) ^ rotr(18, w[t - 15]) ^ w[t - 15] >>> 3;
1666
+ const s1 = rotr(17, w[t - 2]) ^ rotr(19, w[t - 2]) ^ w[t - 2] >>> 10;
1667
+ w[t] = w[t - 16] + s0 + w[t - 7] + s1 | 0;
1668
+ }
1669
+ let a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
1670
+ for (let t = 0; t < 64; t++) {
1671
+ const S1 = rotr(6, e) ^ rotr(11, e) ^ rotr(25, e);
1672
+ const ch = e & f ^ ~e & g;
1673
+ const temp1 = hh + S1 + ch + K[t] + w[t] | 0;
1674
+ const S0 = rotr(2, a) ^ rotr(13, a) ^ rotr(22, a);
1675
+ const maj = a & b ^ a & c ^ b & c;
1676
+ const temp2 = S0 + maj | 0;
1677
+ hh = g;
1678
+ g = f;
1679
+ f = e;
1680
+ e = d + temp1 | 0;
1681
+ d = c;
1682
+ c = b;
1683
+ b = a;
1684
+ a = temp1 + temp2 | 0;
1685
+ }
1686
+ h[0] = h[0] + a | 0;
1687
+ h[1] = h[1] + b | 0;
1688
+ h[2] = h[2] + c | 0;
1689
+ h[3] = h[3] + d | 0;
1690
+ h[4] = h[4] + e | 0;
1691
+ h[5] = h[5] + f | 0;
1692
+ h[6] = h[6] + g | 0;
1693
+ h[7] = h[7] + hh | 0;
1694
+ }
1695
+ let out = "";
1696
+ for (let i = 0; i < 8; i++) {
1697
+ out += h[i].toString(16).padStart(8, "0");
1698
+ }
1699
+ return out;
1700
+ }
1701
+
1702
+ // src/bundles/integrity.ts
1703
+ function assertBundleIntegrity(content, verifiedHash, label) {
1704
+ const digest = sha256Hex(content);
1705
+ if (!verifiedHash) {
1706
+ throw new Error(`[bundle-integrity] refusing to evaluate ${label}: no verified SHA-256 (fail closed).`);
1707
+ }
1708
+ if (digest !== verifiedHash.toLowerCase()) {
1709
+ throw new Error(
1710
+ `[bundle-integrity] integrity FAIL at eval for ${label}: content sha256 ${digest.slice(0, 12)}\u2026 \u2260 verified ${verifiedHash.slice(0, 12)}\u2026. Refusing to evaluate.`
1711
+ );
1712
+ }
1713
+ }
1714
+
1715
+ // src/bundles/storage.ts
1716
+ function selectOwnedCacheEntries(entries, tenant) {
1717
+ if (!tenant) return [];
1718
+ return (entries || []).filter((e) => !!e && e.tenant === tenant);
1719
+ }
1720
+ var MemoryBundleStorage = class {
1721
+ constructor() {
1722
+ this.index = {};
1723
+ this.files = /* @__PURE__ */ new Map();
1724
+ }
1725
+ async loadIndex() {
1726
+ return this.index;
1727
+ }
1728
+ async saveIndex(index) {
1729
+ this.index = index;
1730
+ }
1731
+ async readBundle(localPath) {
1732
+ return this.files.get(localPath) ?? null;
1733
+ }
1734
+ async writeBundle(key, content) {
1735
+ const localPath = `memory://${key}`;
1736
+ this.files.set(localPath, content);
1737
+ return localPath;
1738
+ }
1739
+ async deleteBundle(localPath) {
1740
+ this.files.delete(localPath);
1741
+ }
1742
+ async clearAll() {
1743
+ this.index = {};
1744
+ this.files.clear();
1745
+ }
1746
+ };
1747
+ var _storage = new MemoryBundleStorage();
1748
+ function setBundleStorage(storage) {
1749
+ _storage = storage;
1750
+ }
1751
+ function getBundleStorage() {
1752
+ return _storage;
1753
+ }
1754
+
1755
+ // src/bridge/native.ts
1756
+ import { useCallback, useMemo as useMemo3, useRef as useRef3, useEffect as useEffect5 } from "react";
1757
+ import {
1758
+ connectorCall,
1759
+ mcpFetch as mcpFetchApi,
1760
+ unwrapMcpResult,
1761
+ postCommandResult,
1762
+ getTenant,
1763
+ getUser,
1764
+ pluginCommandEmitter as pluginCommandEmitter2,
1765
+ useChatStore
1766
+ } from "@ateam-ai-mobile/core";
1767
+ function buildContext(pluginId, connectorId) {
1768
+ const user = getUser();
1769
+ return {
1770
+ tenant: getTenant(),
1771
+ pluginId,
1772
+ connectorId,
1773
+ user: user ? { id: user.actorId || "", name: user.name || "", roles: user.roles || [] } : void 0
1774
+ };
1775
+ }
1776
+ function useNativeBridge(pluginId, connectorId, commandBufferRef) {
1777
+ const initCallbackRef = useRef3(null);
1778
+ const commandListenersRef = useRef3(/* @__PURE__ */ new Set());
1779
+ const initializedRef = useRef3(false);
1780
+ const fireInit = useCallback(() => {
1781
+ if (initializedRef.current || !initCallbackRef.current) return;
1782
+ initCallbackRef.current(buildContext(pluginId, connectorId));
1783
+ initializedRef.current = true;
1784
+ }, [pluginId, connectorId]);
1785
+ const onInit = useCallback((cb) => {
1786
+ initCallbackRef.current = cb;
1787
+ setTimeout(fireInit, 0);
1788
+ }, [fireInit]);
1789
+ const mcpCall = useCallback(async (toolOrConnector, argsOrTool, cIdOrArgs) => {
1790
+ let tool;
1791
+ let args;
1792
+ let cId;
1793
+ if (typeof argsOrTool === "string") {
1794
+ cId = toolOrConnector;
1795
+ tool = argsOrTool;
1796
+ args = cIdOrArgs || {};
1797
+ } else {
1798
+ tool = toolOrConnector;
1799
+ args = argsOrTool;
1800
+ cId = typeof cIdOrArgs === "string" ? cIdOrArgs : void 0;
1801
+ }
1802
+ const targetConnector = cId || connectorId;
1803
+ if (!targetConnector) {
1804
+ console.warn(`[NativeBridge:${pluginId}] mcpCall failed \u2014 no connectorId. tool=${tool}`);
1805
+ throw new Error(`[NativeBridge:${pluginId}] mcpCall requires a connectorId`);
1806
+ }
1807
+ try {
1808
+ const data = await connectorCall(targetConnector, tool, args);
1809
+ if (!data.ok && data.error) {
1810
+ throw new Error(data.error);
1811
+ }
1812
+ return unwrapMcpResult(data.result);
1813
+ } catch (err) {
1814
+ console.warn(`[NativeBridge:${pluginId}] mcpCall failed \u2192 connector=${targetConnector} tool=${tool}:`, err?.message || err);
1815
+ throw err;
1816
+ }
1817
+ }, [pluginId, connectorId]);
1818
+ const mcpFetch = useCallback(async (body) => {
1819
+ return mcpFetchApi(body);
1820
+ }, []);
1821
+ const sendCommand = useCallback((type, payload) => {
1822
+ if (type === "plugin.command.result" && payload?.correlationId) {
1823
+ postCommandResult(payload.correlationId, payload.result, payload.error);
1824
+ return;
1825
+ }
1826
+ }, [pluginId]);
1827
+ const onCommand = useCallback((cb) => {
1828
+ commandListenersRef.current.add(cb);
1829
+ if (commandBufferRef) {
1830
+ const buf = commandBufferRef.current;
1831
+ const remaining = [];
1832
+ for (const cmd of buf) {
1833
+ if (cmd.pluginId === pluginId && cmd.command !== "__focus") {
1834
+ try {
1835
+ cb(cmd.command, { ...cmd.args, correlationId: cmd.correlationId });
1836
+ } catch {
1837
+ }
1838
+ } else {
1839
+ remaining.push(cmd);
1840
+ }
1841
+ }
1842
+ commandBufferRef.current = remaining;
1843
+ }
1844
+ for (const cmd of pluginCommandEmitter2.drainPluginCommands(pluginId)) {
1845
+ try {
1846
+ cb(cmd.command, { ...cmd.args, correlationId: cmd.correlationId });
1847
+ } catch {
1848
+ }
1849
+ }
1850
+ return () => {
1851
+ commandListenersRef.current.delete(cb);
1852
+ };
1853
+ }, [pluginId, commandBufferRef]);
1854
+ useEffect5(() => {
1855
+ const unsub = pluginCommandEmitter2.on("plugin-command", (cmd) => {
1856
+ if (cmd.pluginId !== pluginId) return;
1857
+ if (cmd.command === "__focus") return;
1858
+ commandListenersRef.current.forEach((fn) => {
1859
+ try {
1860
+ fn(cmd.command, { ...cmd.args, correlationId: cmd.correlationId });
1861
+ } catch {
1862
+ }
1863
+ });
1864
+ });
1865
+ return unsub;
1866
+ }, [pluginId]);
1867
+ useEffect5(() => {
1868
+ const timer = setTimeout(() => {
1869
+ const dispatch = (cmd) => {
1870
+ commandListenersRef.current.forEach((fn) => {
1871
+ try {
1872
+ fn(cmd.command, { ...cmd.args, correlationId: cmd.correlationId });
1873
+ } catch {
1874
+ }
1875
+ });
1876
+ };
1877
+ if (commandBufferRef) {
1878
+ const remaining = [];
1879
+ for (const cmd of commandBufferRef.current) {
1880
+ if (cmd.pluginId === pluginId && cmd.command !== "__focus") dispatch(cmd);
1881
+ else remaining.push(cmd);
1882
+ }
1883
+ commandBufferRef.current = remaining;
1884
+ }
1885
+ for (const cmd of pluginCommandEmitter2.drainPluginCommands(pluginId)) {
1886
+ dispatch(cmd);
1887
+ }
1888
+ }, 500);
1889
+ return () => clearTimeout(timer);
1890
+ }, [pluginId, commandBufferRef]);
1891
+ useEffect5(() => {
1892
+ return () => {
1893
+ commandListenersRef.current.clear();
1894
+ initializedRef.current = false;
1895
+ };
1896
+ }, []);
1897
+ const close = useCallback(() => {
1898
+ pluginCommandEmitter2.emit("plugin-close", { pluginId });
1899
+ }, [pluginId]);
1900
+ const sendMessage = useCallback((text) => {
1901
+ const t = (text || "").trim();
1902
+ if (!t) return;
1903
+ try {
1904
+ useChatStore.getState().sendMessage(t);
1905
+ } catch (err) {
1906
+ console.warn("[bridge.sendMessage] failed:", err instanceof Error ? err.message : String(err));
1907
+ }
1908
+ }, []);
1909
+ const prepareMessage = useCallback((text) => {
1910
+ const t = (text || "").trim();
1911
+ if (!t) return;
1912
+ pluginCommandEmitter2.emit("prepare-chat-message", { text: t });
1913
+ }, []);
1914
+ return useMemo3(
1915
+ () => ({ onInit, mcpCall, mcpFetch, sendCommand, onCommand, close, sendMessage, prepareMessage }),
1916
+ [onInit, mcpCall, mcpFetch, sendCommand, onCommand, close, sendMessage, prepareMessage]
1917
+ );
1918
+ }
1919
+ function createNativeBridge(pluginId, connectorId) {
1920
+ const commandListeners = /* @__PURE__ */ new Set();
1921
+ return {
1922
+ onInit(cb) {
1923
+ setTimeout(() => {
1924
+ cb(buildContext(pluginId, connectorId));
1925
+ }, 0);
1926
+ },
1927
+ async mcpCall(tool, args, cId) {
1928
+ const targetConnector = cId || connectorId;
1929
+ if (!targetConnector) {
1930
+ throw new Error(`[NativeBridge:${pluginId}] mcpCall requires a connectorId`);
1931
+ }
1932
+ const data = await connectorCall(targetConnector, tool, args);
1933
+ if (!data.ok && data.error) throw new Error(data.error);
1934
+ return unwrapMcpResult(data.result);
1935
+ },
1936
+ async mcpFetch(body) {
1937
+ return mcpFetchApi(body);
1938
+ },
1939
+ sendCommand(_type, _payload) {
1940
+ },
1941
+ onCommand(cb) {
1942
+ commandListeners.add(cb);
1943
+ return () => {
1944
+ commandListeners.delete(cb);
1945
+ };
1946
+ },
1947
+ close() {
1948
+ pluginCommandEmitter2.emit("plugin-close", { pluginId });
1949
+ },
1950
+ sendMessage(text) {
1951
+ const t = (text || "").trim();
1952
+ if (!t) return;
1953
+ try {
1954
+ useChatStore.getState().sendMessage(t);
1955
+ } catch (err) {
1956
+ console.warn("[bridge.sendMessage] failed:", err instanceof Error ? err.message : String(err));
1957
+ }
1958
+ },
1959
+ prepareMessage(text) {
1960
+ const t = (text || "").trim();
1961
+ if (!t) return;
1962
+ pluginCommandEmitter2.emit("prepare-chat-message", { text: t });
1963
+ }
1964
+ };
1965
+ }
1966
+
1967
+ // src/deviceStateHost.ts
1968
+ var UNKNOWN_QUALITY = {
1969
+ freshness: { state: "unknown", observedAt: null, ageMs: null },
1970
+ confidence: { level: "unknown" }
1971
+ };
1972
+ function deniedSnapshot(domain) {
1973
+ const base = { quality: UNKNOWN_QUALITY };
1974
+ switch (domain) {
1975
+ case "spatial":
1976
+ return {
1977
+ ...base,
1978
+ position: null,
1979
+ movement: { speedMps: null, bearingDeg: null, distanceRecentM: null, state: "unknown" },
1980
+ orientation: { headingDeg: null },
1981
+ recentPath: []
1982
+ };
1983
+ case "visual":
1984
+ return {
1985
+ ...base,
1986
+ camera: { available: false, active: false, facing: "unknown" },
1987
+ latest: null,
1988
+ recentTimeline: { windowMs: 0, frames: [] }
1989
+ };
1990
+ case "deviceContext":
1991
+ return {
1992
+ ...base,
1993
+ power: { batteryLevel: null, charging: null, lowPowerMode: null },
1994
+ thermal: { state: "unknown" },
1995
+ resources: { memoryPressure: "unknown", storagePressure: "unknown" }
1996
+ };
1997
+ case "connectivity":
1998
+ return {
1999
+ ...base,
2000
+ reachability: "unknown",
2001
+ transport: "unknown",
2002
+ qualityClass: "unknown",
2003
+ stability: "unknown",
2004
+ latencyMs: null
2005
+ };
2006
+ case "interaction":
2007
+ return {
2008
+ ...base,
2009
+ lifecycle: { appState: "unknown", screenOn: null },
2010
+ audio: { captureActive: null, playbackActive: null, route: "unknown", interruption: "unknown" }
2011
+ };
2012
+ case "activity":
2013
+ return {
2014
+ ...base,
2015
+ // `confidence` is REQUIRED on both blocks in the freeze, precisely
2016
+ // because an inferred activity must never be handed over without
2017
+ // saying how sure the inference is. An empty snapshot is the least
2018
+ // sure of all.
2019
+ human: { state: "unknown", since: null, confidence: { level: "unknown" } },
2020
+ devicePose: { placement: "unknown", orientation: "unknown", confidence: { level: "unknown" } },
2021
+ recentTransitions: []
2022
+ };
2023
+ case "environment":
2024
+ return {
2025
+ ...base,
2026
+ lighting: { level: "unknown", lux: null },
2027
+ acoustics: { level: "unknown", approximateDb: null },
2028
+ // 'unknown' rather than 'uncertain': uncertain means we looked and
2029
+ // could not decide, and nothing looked at all here.
2030
+ enclosure: { state: "unknown" },
2031
+ proximity: { distanceClass: "unknown" },
2032
+ nearbySignals: { bleAvailable: false, beaconCount: null, uwbAvailable: false }
2033
+ };
2034
+ case "capability": {
2035
+ const unknownStatus = { support: "unknown", permission: "unknown", availability: "unknown" };
2036
+ return {
2037
+ ...base,
2038
+ camera: unknownStatus,
2039
+ microphone: unknownStatus,
2040
+ location: { ...unknownStatus, precision: "unknown", backgroundPermission: "unknown" },
2041
+ motion: unknownStatus,
2042
+ bluetooth: unknownStatus,
2043
+ uwb: unknownStatus,
2044
+ nfc: unknownStatus,
2045
+ notifications: unknownStatus,
2046
+ health: unknownStatus,
2047
+ backgroundExecution: unknownStatus
2048
+ };
2049
+ }
2050
+ default:
2051
+ return base;
2052
+ }
2053
+ }
2054
+ function deniedDomain(domain, why) {
2055
+ return {
2056
+ async getSnapshot() {
2057
+ return deniedSnapshot(domain);
2058
+ },
2059
+ async start() {
2060
+ throw denial(domain, why);
2061
+ },
2062
+ async stop() {
2063
+ throw denial(domain, why);
2064
+ },
2065
+ subscribe() {
2066
+ throw denial(domain, why);
2067
+ }
2068
+ };
2069
+ }
2070
+ function denial(domain, why) {
2071
+ const err = new Error(`deviceState.${domain}: ${why}`);
2072
+ err.code = "RESTRICTED";
2073
+ err.domain = domain;
2074
+ return err;
2075
+ }
2076
+ var ALL_DOMAINS = [
2077
+ "spatial",
2078
+ "visual",
2079
+ "activity",
2080
+ "deviceContext",
2081
+ "connectivity",
2082
+ "capability",
2083
+ "environment",
2084
+ "interaction"
2085
+ ];
2086
+ var _provider = {};
2087
+ function setDeviceStateProvider(state) {
2088
+ _provider = state || {};
2089
+ }
2090
+ function gateDeviceState(declared) {
2091
+ const allowed = new Set(declared || []);
2092
+ const out = {};
2093
+ for (const domain of ALL_DOMAINS) {
2094
+ if (!allowed.has(domain)) {
2095
+ out[domain] = deniedDomain(
2096
+ domain,
2097
+ `not declared in this plugin's stateDomains. Add '${domain}' to use it.`
2098
+ );
2099
+ continue;
2100
+ }
2101
+ const engine = _provider[domain];
2102
+ out[domain] = engine ?? deniedDomain(
2103
+ domain,
2104
+ "no engine in this build \u2014 the native side does not exist yet. See docs/DEVICE_API_STATUS.md."
2105
+ );
2106
+ }
2107
+ return out;
2108
+ }
2109
+ function withoutSubscribe(state) {
2110
+ if (!state) return state;
2111
+ const out = {};
2112
+ for (const domain of ALL_DOMAINS) {
2113
+ const d = state[domain];
2114
+ out[domain] = d && Object.assign(Object.create(d), {
2115
+ subscribe() {
2116
+ throw denial(domain, "a device tool call has no lifetime to own a subscription. Subscribe from the plugin UI, or read getSnapshot() within the call.");
2117
+ }
2118
+ });
2119
+ }
2120
+ return out;
2121
+ }
2122
+ function implementedStateDomains() {
2123
+ return ALL_DOMAINS.filter((d) => !!_provider[d]);
2124
+ }
2125
+
2126
+ // src/tools/registry.ts
2127
+ var registry = /* @__PURE__ */ new Map();
2128
+ var contextProvider = null;
2129
+ var DEFAULT_TIMEOUT_MS = 3e4;
2130
+ function setDeviceToolContextProvider(fn) {
2131
+ contextProvider = fn;
2132
+ }
2133
+ function defaultContext(pluginId, capabilities, stateDomains) {
2134
+ return {
2135
+ bridge: createNativeBridge(pluginId),
2136
+ native: gatePluginNative(getPluginNative(), capabilities, pluginId),
2137
+ deviceState: gateDeviceState(stateDomains)
2138
+ };
2139
+ }
2140
+ function registerDeviceTools(pluginId, tools, capabilities, stateDomains) {
2141
+ const accepted = [];
2142
+ for (const tool of tools || []) {
2143
+ if (!tool || typeof tool.name !== "string" || typeof tool.run !== "function") {
2144
+ console.warn(`[deviceTools] ${pluginId}: skipping malformed tool entry`);
2145
+ continue;
2146
+ }
2147
+ const existing = registry.get(tool.name);
2148
+ if (existing && existing.pluginId !== pluginId) {
2149
+ console.warn(
2150
+ `[deviceTools] ${pluginId}: "${tool.name}" already registered by ${existing.pluginId} \u2014 refusing to override`
2151
+ );
2152
+ continue;
2153
+ }
2154
+ registry.set(tool.name, { pluginId, tool, capabilities, stateDomains });
2155
+ accepted.push(tool.name);
2156
+ }
2157
+ if (accepted.length > 0) {
2158
+ console.log(`[deviceTools] ${pluginId} registered: ${accepted.join(", ")}`);
2159
+ }
2160
+ return accepted;
2161
+ }
2162
+ function unregisterDeviceTools(pluginId) {
2163
+ for (const [name, entry] of registry.entries()) {
2164
+ if (entry.pluginId === pluginId) registry.delete(name);
2165
+ }
2166
+ }
2167
+ function hasDeviceTool(name, pluginId) {
2168
+ const entry = registry.get(name);
2169
+ return !!entry && (pluginId === void 0 || entry.pluginId === pluginId);
2170
+ }
2171
+ function listDeviceTools() {
2172
+ return Array.from(registry.entries()).map(([name, { pluginId, tool }]) => ({
2173
+ name,
2174
+ pluginId,
2175
+ description: tool.description,
2176
+ input_schema: tool.input_schema
2177
+ }));
2178
+ }
2179
+ async function callDeviceTool(name, args = {}, opts = {}) {
2180
+ const entry = registry.get(name);
2181
+ if (!entry) {
2182
+ return { ok: false, reason: "not_found", error: `No device tool registered as "${name}"` };
2183
+ }
2184
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2185
+ let timer;
2186
+ try {
2187
+ const build = contextProvider || defaultContext;
2188
+ const built = build(entry.pluginId, entry.capabilities, entry.stateDomains);
2189
+ const ctx = {
2190
+ ...built,
2191
+ // Whoever built the context, a call cannot own a subscription.
2192
+ deviceState: withoutSubscribe(built.deviceState),
2193
+ signal: opts.signal
2194
+ };
2195
+ const result = await Promise.race([
2196
+ Promise.resolve(entry.tool.run(args, ctx)),
2197
+ new Promise((_, reject) => {
2198
+ timer = setTimeout(
2199
+ () => reject(new Error(`Device tool "${name}" timed out after ${timeoutMs}ms`)),
2200
+ timeoutMs
2201
+ );
2202
+ })
2203
+ ]);
2204
+ return { ok: true, result };
2205
+ } catch (err) {
2206
+ const message = err?.message || String(err);
2207
+ const timedOut = message.includes("timed out after");
2208
+ return { ok: false, reason: timedOut ? "timeout" : "failed", error: message };
2209
+ } finally {
2210
+ if (timer) clearTimeout(timer);
2211
+ }
2212
+ }
2213
+ function clearDeviceTools() {
2214
+ registry.clear();
2215
+ }
2216
+
2217
+ // src/bundles/bundleManager.ts
2218
+ var ReactShim = {
2219
+ __esModule: true,
2220
+ default: React2,
2221
+ ...React2,
2222
+ // Explicitly include hooks (React 19 may not have them as own enumerable props)
2223
+ useState,
2224
+ useEffect: useEffect6,
2225
+ useCallback: useCallback2,
2226
+ useMemo: useMemo4,
2227
+ useRef: useRef4,
2228
+ useContext,
2229
+ useReducer,
2230
+ useLayoutEffect,
2231
+ useImperativeHandle,
2232
+ useDebugValue,
2233
+ createElement: React2.createElement,
2234
+ Fragment: React2.Fragment,
2235
+ Component: React2.Component,
2236
+ PureComponent: React2.PureComponent,
2237
+ createContext: React2.createContext,
2238
+ forwardRef: React2.forwardRef,
2239
+ memo: React2.memo,
2240
+ Children: React2.Children,
2241
+ cloneElement: React2.cloneElement,
2242
+ isValidElement: React2.isValidElement,
2243
+ createRef: React2.createRef,
2244
+ lazy: React2.lazy,
2245
+ Suspense: React2.Suspense
2246
+ };
2247
+ var PluginSDKShim = Object.freeze({
2248
+ ...sdk_exports,
2249
+ SurfaceDrawer,
2250
+ SurfaceCard,
2251
+ SurfaceFullscreen,
2252
+ useSurfaceStore,
2253
+ SurfaceDispatcher,
2254
+ PluginSDK: Object.freeze({
2255
+ ...PluginSDK,
2256
+ register: PluginSDK.register
2257
+ }),
2258
+ register
2259
+ });
2260
+ var requireShim = (name) => {
2261
+ if (name === "react") return ReactShim;
2262
+ if (name === "react-native") return ReactNative;
2263
+ if (name === "@adas/plugin-sdk") return PluginSDKShim;
2264
+ const hostModule = resolveBundleModule(name);
2265
+ if (hostModule !== void 0) return hostModule;
2266
+ console.warn(`[BundleManager] Unknown module: ${name} \u2014 register it via registerBundleModules()`);
2267
+ return {};
2268
+ };
2269
+ var CACHE_TTL = 7 * 24 * 60 * 60 * 1e3;
2270
+ var hasComponent = (val) => !!val && typeof val === "object" && typeof val.Component === "function";
2271
+ var hasTools = (val) => !!val && typeof val === "object" && Array.isArray(val.tools) && val.tools.length > 0;
2272
+ var BundleManager = class {
2273
+ constructor() {
2274
+ /** In-memory module cache: bundleUrl → evaluated module.exports. Holds ONE
2275
+ * tenant's modules at a time — the tenant boundary is `cacheTenant` /
2276
+ * `requireTenant()`, NOT the key. */
2277
+ this.modules = /* @__PURE__ */ new Map();
2278
+ /** What is actually RUNNING, keyed by bundleUrl (for the current tenant). See
2279
+ * getLoadedBundles(). */
2280
+ this.provenance = /* @__PURE__ */ new Map();
2281
+ /** In-flight download deduplication: bundleUrl → Promise */
2282
+ this.inflight = /* @__PURE__ */ new Map();
2283
+ /**
2284
+ * The tenant the in-memory caches (modules / provenance / inflight) currently
2285
+ * belong to. This is the tenant BOUNDARY for evaluated code.
2286
+ *
2287
+ * A bundleUrl resolves PER-TENANT on the server — one url, different bytes for
2288
+ * different tenants — so a memory hit keyed on url alone would hand tenant B
2289
+ * the module tenant A already evaluated and ran. PR #9 scoped the DISK cache
2290
+ * (per-tenant index + hash gate); the in-memory map was left url-keyed. This
2291
+ * closes that: the caches only ever hold ONE tenant's modules, and a switch
2292
+ * drops them before anything is served.
2293
+ */
2294
+ this.cacheTenant = null;
2295
+ /**
2296
+ * pluginIds this manager registered device tools for. A tenant switch drops
2297
+ * the in-memory modules AND unregisters these, so the incoming tenant's bundle
2298
+ * re-registers into a clean registry instead of being refused as a duplicate
2299
+ * of the previous tenant's tools.
2300
+ */
2301
+ this.registeredToolPluginIds = /* @__PURE__ */ new Set();
2302
+ /** bundleUrl → the trusted declaration last recorded on its disk-cache entry
2303
+ * this session, so a memory hit with unchanged grants skips the index I/O. */
2304
+ this.recordedDeclarations = /* @__PURE__ */ new Map();
2305
+ /**
2306
+ * Enforce the in-memory tenant boundary. Call at the top of every public load
2307
+ * path, BEFORE any cache read.
2308
+ *
2309
+ * FAIL CLOSED: without a tenant identity we cannot prove a cached module is
2310
+ * this session's, so we drop everything and refuse rather than risk serving
2311
+ * one tenant's evaluated code to another. On a tenant change we drop the
2312
+ * previous tenant's modules (and their tool registrations) before proceeding.
2313
+ */
2314
+ /**
2315
+ * Monotonic load generation. Bumped on every in-memory wipe (a tenant change,
2316
+ * fail-closed, or clearAll). A load captures it at ENTRY; a completion whose
2317
+ * generation no longer matches is stale and is discarded before it can commit.
2318
+ * This closes the async race the sequential guard cannot: tenant A's in-flight
2319
+ * loadModule can resolve AFTER a switch to B — clearing `inflight` does not
2320
+ * cancel that Promise — and would otherwise write A's module / provenance /
2321
+ * device tools into the singleton now marked cacheTenant=B.
2322
+ */
2323
+ this.epoch = 0;
2324
+ }
2325
+ requireTenant() {
2326
+ const tenant = getTenant2();
2327
+ if (!tenant) {
2328
+ this.dropInMemory();
2329
+ this.cacheTenant = null;
2330
+ throw new Error(
2331
+ "[BundleManager] refusing to load a tenant-scoped bundle without a tenant identity (fail closed)"
2332
+ );
2333
+ }
2334
+ if (tenant !== this.cacheTenant) {
2335
+ this.dropInMemory();
2336
+ this.cacheTenant = tenant;
2337
+ }
2338
+ return tenant;
2339
+ }
2340
+ /** Drop every in-memory cache and unregister the device tools this manager
2341
+ * registered — used on a tenant change and by clearAll(). */
2342
+ dropInMemory() {
2343
+ for (const pluginId of this.registeredToolPluginIds) {
2344
+ try {
2345
+ unregisterDeviceTools(pluginId);
2346
+ } catch {
2347
+ }
2348
+ }
2349
+ this.registeredToolPluginIds.clear();
2350
+ this.recordedDeclarations.clear();
2351
+ this.modules.clear();
2352
+ this.provenance.clear();
2353
+ this.inflight.clear();
2354
+ this.epoch++;
2355
+ }
2356
+ /** True once the boundary has moved since a load captured `epoch` — i.e. a
2357
+ * tenant switch (or wipe) happened while this load was in flight. Its results
2358
+ * belong to a tenant that is no longer current and must be discarded. */
2359
+ isStale(epoch, tenant) {
2360
+ return this.epoch !== epoch || getTenant2() !== tenant;
2361
+ }
2362
+ /** Record a memory serve: the running bytes are the already-evaluated module,
2363
+ * and `expected` is refreshed from the manifest hash the caller JUST passed —
2364
+ * so after a redeploy the record reads hash !== expected (STALE) instead of
2365
+ * the old in-sync pair. The ONE place both memory paths (load()'s early return
2366
+ * and loadModule's) record reuse. No-op if nothing was recorded yet. */
2367
+ markMemoryHit(bundleUrl, expectedHash) {
2368
+ const prev = this.provenance.get(bundleUrl);
2369
+ if (prev) {
2370
+ this.provenance.set(bundleUrl, { ...prev, source: "memory", expected: expectedHash?.toLowerCase() ?? prev.expected });
2371
+ }
2372
+ }
2373
+ // ── Public API ──────────────────────────────────────────────
2374
+ /**
2375
+ * Load a plugin component. Returns the RegisteredUIPlugin object.
2376
+ * Handles: in-memory cache → disk cache → download → evaluate → extract.
2377
+ *
2378
+ * `expectedHash` (SHA-256 hex from cp.getContextPlugin manifest) MUST be
2379
+ * provided for any bundle the user has not previously verified — without
2380
+ * it, a tampered bundle is `eval`'d as JS with full RN runtime + every
2381
+ * native capability the manifest declares.
2382
+ *
2383
+ * `grants` is what the MANIFEST grants this plugin (resolvePluginGrants) — the
2384
+ * only authority its device tools are registered under. Omitted (e.g. a
2385
+ * prewarm from the slim plugin list) → the bundle is loaded but its tools are
2386
+ * NOT registered: without the manifest there is nothing trusted to gate them
2387
+ * on, and registering with nothing would downgrade a registration the
2388
+ * manifest-driven tool loader already made.
2389
+ */
2390
+ async load(pluginId, bundleUrl, version, expectedHash, grants) {
2391
+ const tenant = this.requireTenant();
2392
+ const epoch = this.epoch;
2393
+ const cached = this.getComponentFromMemory(pluginId, bundleUrl);
2394
+ if (cached) {
2395
+ this.markMemoryHit(bundleUrl, expectedHash);
2396
+ if (grants) await this.commitTools(pluginId, bundleUrl, grants, tenant, epoch);
2397
+ return cached;
2398
+ }
2399
+ let modulePromise = this.inflight.get(bundleUrl);
2400
+ if (!modulePromise) {
2401
+ const promise = this.loadModule(bundleUrl, version, expectedHash, tenant, epoch);
2402
+ modulePromise = promise;
2403
+ this.inflight.set(bundleUrl, promise);
2404
+ promise.catch(() => {
2405
+ }).finally(() => {
2406
+ if (this.inflight.get(bundleUrl) === promise) this.inflight.delete(bundleUrl);
2407
+ });
2408
+ }
2409
+ await modulePromise;
2410
+ if (this.isStale(epoch, tenant)) {
2411
+ throw new Error("[BundleManager] tenant changed while loading \u2014 discarding (fail closed)");
2412
+ }
2413
+ if (grants) await this.commitTools(pluginId, bundleUrl, grants, tenant, epoch);
2414
+ const component = this.getComponentFromMemory(pluginId, bundleUrl);
2415
+ if (!component) {
2416
+ throw new Error(
2417
+ `Bundle loaded from ${bundleUrl} but no component found for "${pluginId}". Available exports: ${this.describeModule(this.modules.get(bundleUrl))}`
2418
+ );
2419
+ }
2420
+ return component;
2421
+ }
2422
+ /**
2423
+ * Load a bundle for its `tools/` section only — no UI required.
2424
+ *
2425
+ * Same download, same integrity check, same evaluation as `load()`; the only
2426
+ * difference is that a bundle exporting tools and no `Component` is a success
2427
+ * here rather than "no component found". Returns the tool names registered.
2428
+ *
2429
+ * `grants` is REQUIRED: the tools are registered under `pluginId` with exactly
2430
+ * what the manifest grants (see load()), never what the bundle claims.
2431
+ */
2432
+ async loadTools(pluginId, bundleUrl, version, expectedHash, grants) {
2433
+ if (!grants) {
2434
+ throw new Error(`[BundleManager] loadTools(${pluginId}) needs the manifest's grants (resolvePluginGrants) \u2014 refusing to register tools on the bundle's own claim`);
2435
+ }
2436
+ const tenant = this.requireTenant();
2437
+ const epoch = this.epoch;
2438
+ let modulePromise = this.inflight.get(bundleUrl);
2439
+ if (!modulePromise) {
2440
+ const promise = this.loadModule(bundleUrl, version, expectedHash, tenant, epoch);
2441
+ modulePromise = promise;
2442
+ this.inflight.set(bundleUrl, promise);
2443
+ promise.catch(() => {
2444
+ }).finally(() => {
2445
+ if (this.inflight.get(bundleUrl) === promise) this.inflight.delete(bundleUrl);
2446
+ });
2447
+ }
2448
+ await modulePromise;
2449
+ if (this.isStale(epoch, tenant)) {
2450
+ throw new Error("[BundleManager] tenant changed while loading tools \u2014 discarding (fail closed)");
2451
+ }
2452
+ await this.commitTools(pluginId, bundleUrl, grants, tenant, epoch);
2453
+ const names = listDeviceTools().filter((t) => t.pluginId === pluginId).map((t) => t.name);
2454
+ if (names.length === 0) {
2455
+ console.warn(
2456
+ `[BundleManager] ${pluginId}: bundle loaded from ${bundleUrl} but registered no tools. Available exports: ${this.describeModule(this.modules.get(bundleUrl))}`
2457
+ );
2458
+ }
2459
+ return names;
2460
+ }
2461
+ /**
2462
+ * Prewarm: load every plugin bundle in the background after app boot, so a
2463
+ * later open is instant (in-memory hit) instead of round-tripping the
2464
+ * network. Errors are swallowed per-plugin — one bad bundle shouldn't
2465
+ * block others. Concurrency capped at 3.
2466
+ */
2467
+ async prewarmAll(items) {
2468
+ const queue = [...items];
2469
+ const concurrency = Math.min(3, queue.length);
2470
+ const start = Date.now();
2471
+ let okCount = 0;
2472
+ let failCount = 0;
2473
+ const worker = async () => {
2474
+ while (queue.length > 0) {
2475
+ const it = queue.shift();
2476
+ if (!it) return;
2477
+ try {
2478
+ await this.load(it.pluginId, it.bundleUrl, it.version, it.bundleHash, it.grants);
2479
+ okCount++;
2480
+ } catch (err) {
2481
+ failCount++;
2482
+ console.log(`[prewarm] ${it.pluginId}: ${err instanceof Error ? err.message : String(err)}`);
2483
+ }
2484
+ }
2485
+ };
2486
+ await Promise.all(Array.from({ length: concurrency }, worker));
2487
+ console.log(`[prewarm] ${okCount} loaded, ${failCount} failed in ${Date.now() - start}ms`);
2488
+ }
2489
+ /**
2490
+ * Clear all caches (in-memory + storage).
2491
+ */
2492
+ async clearAll() {
2493
+ this.dropInMemory();
2494
+ this.cacheTenant = null;
2495
+ try {
2496
+ await getBundleStorage().clearAll();
2497
+ } catch (err) {
2498
+ console.warn("[BundleManager] clearAll error:", err);
2499
+ }
2500
+ }
2501
+ /**
2502
+ * Clear cache for a specific plugin/bundle.
2503
+ */
2504
+ async clearPlugin(pluginId) {
2505
+ const storage = getBundleStorage();
2506
+ const index = await storage.loadIndex();
2507
+ const entry = index[pluginId];
2508
+ if (entry) {
2509
+ this.modules.delete(entry.bundleUrl);
2510
+ delete index[pluginId];
2511
+ await storage.saveIndex(index);
2512
+ try {
2513
+ await storage.deleteBundle(entry.localPath);
2514
+ } catch {
2515
+ }
2516
+ }
2517
+ }
2518
+ /**
2519
+ * What every loaded bundle IS, right now: the sha256 of the bytes running,
2520
+ * the hash the server advertised, and where they came from.
2521
+ *
2522
+ * Deliberately not filtered or prettified — this is the raw answer to "did my
2523
+ * redeploy reach the phone?", and it is comparable directly against the
2524
+ * manifest `bundleHash` and the server's X-Bundle-SHA256 header.
2525
+ */
2526
+ getLoadedBundles() {
2527
+ return [...this.provenance.values()];
2528
+ }
2529
+ // ── Private: module loading pipeline ────────────────────────
2530
+ async loadModule(bundleUrl, version, expectedHash, expectedTenant, expectedEpoch) {
2531
+ if (this.isStale(expectedEpoch, expectedTenant)) {
2532
+ throw new Error("[BundleManager] tenant changed before load started \u2014 discarding (fail closed)");
2533
+ }
2534
+ if (this.modules.has(bundleUrl)) {
2535
+ this.markMemoryHit(bundleUrl, expectedHash);
2536
+ return;
2537
+ }
2538
+ const storage = getBundleStorage();
2539
+ const index = await storage.loadIndex();
2540
+ const expectedLc = expectedHash ? expectedHash.toLowerCase() : null;
2541
+ let content = null;
2542
+ let verifiedHash = null;
2543
+ let servedFrom = "download";
2544
+ for (const entry of Object.values(index)) {
2545
+ if (entry.bundleUrl === bundleUrl && entry.version === version) {
2546
+ const age = Date.now() - entry.timestamp;
2547
+ const hashOk = expectedLc && entry.bundleHash && entry.bundleHash.toLowerCase() === expectedLc;
2548
+ if (age < CACHE_TTL && hashOk) {
2549
+ content = await storage.readBundle(entry.localPath);
2550
+ if (content) {
2551
+ verifiedHash = entry.bundleHash.toLowerCase();
2552
+ servedFrom = "disk-cache";
2553
+ break;
2554
+ }
2555
+ }
2556
+ }
2557
+ }
2558
+ if (!content) {
2559
+ const downloaded = await this.download(bundleUrl, expectedLc);
2560
+ content = downloaded.content;
2561
+ verifiedHash = downloaded.sha256.toLowerCase();
2562
+ if (this.isStale(expectedEpoch, expectedTenant)) {
2563
+ throw new Error("[BundleManager] tenant changed during download \u2014 discarding (fail closed)");
2564
+ }
2565
+ try {
2566
+ const localPath = await storage.writeBundle(`${verifiedHash}.js`, content);
2567
+ if (!this.isStale(expectedEpoch, expectedTenant)) {
2568
+ index[bundleUrl] = {
2569
+ localPath,
2570
+ version,
2571
+ timestamp: Date.now(),
2572
+ bundleUrl,
2573
+ bundleHash: downloaded.sha256,
2574
+ tenant: expectedTenant
2575
+ };
2576
+ await storage.saveIndex(index);
2577
+ }
2578
+ } catch (err) {
2579
+ console.warn("[BundleManager] Cache write error:", err);
2580
+ }
2581
+ }
2582
+ if (this.isStale(expectedEpoch, expectedTenant)) {
2583
+ throw new Error("[BundleManager] tenant changed while loading \u2014 discarding stale bundle before eval (fail closed)");
2584
+ }
2585
+ const mod = this.evaluate(content, bundleUrl, verifiedHash);
2586
+ this.modules.set(bundleUrl, mod);
2587
+ this.provenance.set(bundleUrl, {
2588
+ bundleUrl,
2589
+ version,
2590
+ hash: verifiedHash,
2591
+ expected: expectedLc,
2592
+ source: servedFrom,
2593
+ // The captured owner — same rule as the disk stamp. The final stale check
2594
+ // above guarantees getTenant() === expectedTenant here, but binding it to
2595
+ // the captured value keeps the ownership record impossible to mislabel.
2596
+ tenant: expectedTenant,
2597
+ loadedAt: Date.now()
2598
+ });
2599
+ console.log(
2600
+ `[BundleManager] RUNNING ${bundleUrl} v${version} sha=${(verifiedHash || "none").slice(0, 12)} (${servedFrom}${expectedLc && verifiedHash && expectedLc !== verifiedHash ? `, EXPECTED ${expectedLc.slice(0, 12)} \u2014 STALE` : ""})`
2601
+ );
2602
+ }
2603
+ /**
2604
+ * Register THIS plugin's device tools under the TRUSTED declaration, then
2605
+ * record that declaration on the disk-cache entry. Runs on every trusted load
2606
+ * — memory hit included — so the grants in force are always the latest the
2607
+ * manifest gave (a revoked grant stops applying on the next load, not the next
2608
+ * app start). Callers run it only after their stale check.
2609
+ */
2610
+ async commitTools(pluginId, bundleUrl, grants, tenant, epoch) {
2611
+ const declaration = {
2612
+ pluginId,
2613
+ capabilities: grants.capabilities,
2614
+ stateDomains: grants.stateDomains
2615
+ };
2616
+ this.registerToolsFromModule(this.modules.get(bundleUrl), declaration);
2617
+ await this.recordTrustedDeclaration(bundleUrl, declaration, tenant, epoch);
2618
+ }
2619
+ /**
2620
+ * Put the plugin's own `tools` section in the device tool registry — under the
2621
+ * pluginId and grants the MANIFEST resolved, never the bundle's own `id`,
2622
+ * `capabilities` or `stateDomains`. A bundle is code the manifest authorised
2623
+ * by hash; what it may touch is the manifest's to say, same as its rendered
2624
+ * surface (resolvePluginRuntimeProps). Its own `id` would also let it register
2625
+ * as another plugin — including the host's platform tools, which a same-id
2626
+ * re-registration replaces.
2627
+ *
2628
+ * Only this plugin's export (the same lookup the component uses) is
2629
+ * registered. Another export's tools in the same bundle belong to another
2630
+ * plugin and register when THAT plugin's manifest loads it.
2631
+ */
2632
+ registerToolsFromModule(mod, { pluginId, capabilities, stateDomains }) {
2633
+ if (!mod) return;
2634
+ const own = this.findPluginExport(mod, pluginId, hasTools);
2635
+ const others = Object.keys(mod).filter((k) => hasTools(mod[k]) && mod[k] !== own);
2636
+ if (others.length > 0) {
2637
+ console.warn(
2638
+ `[BundleManager] ${pluginId}: not registering tools from export(s) ${others.join(", ")} \u2014 they are not this plugin's, and only their own manifest can grant them`
2639
+ );
2640
+ }
2641
+ if (!own) return;
2642
+ const ungranted = [
2643
+ ...(Array.isArray(own.stateDomains) ? own.stateDomains : []).filter((d) => !stateDomains?.includes(d)),
2644
+ ...Object.keys(own.capabilities || {}).filter((k) => own.capabilities[k] === true && !capabilities?.[k])
2645
+ ];
2646
+ if (ungranted.length > 0) {
2647
+ console.warn(
2648
+ `[BundleManager] ${pluginId}: bundle declares ${ungranted.join(", ")} but the manifest does not grant it \u2014 denied`
2649
+ );
2650
+ }
2651
+ try {
2652
+ registerDeviceTools(pluginId, own.tools, capabilities, stateDomains);
2653
+ this.registeredToolPluginIds.add(pluginId);
2654
+ } catch (err) {
2655
+ console.warn(
2656
+ `[BundleManager] tool registration failed for ${pluginId}:`,
2657
+ err instanceof Error ? err.message : String(err)
2658
+ );
2659
+ }
2660
+ }
2661
+ /**
2662
+ * Record the trusted declaration on this tenant's disk-cache entry for the
2663
+ * bytes RUNNING — the recovery path (tools/loader loadFromDiskCache) has no
2664
+ * manifest and re-registers with exactly this. Only onto an entry this tenant
2665
+ * owns whose hash is the running hash: the grant was issued for these bytes,
2666
+ * and those are the bytes recovery will evaluate. Best-effort — a lost write
2667
+ * leaves no `trusted`, which recovery treats as fail closed.
2668
+ */
2669
+ async recordTrustedDeclaration(bundleUrl, declaration, tenant, epoch) {
2670
+ const key = JSON.stringify(declaration);
2671
+ if (this.recordedDeclarations.get(bundleUrl) === key) return;
2672
+ try {
2673
+ const storage = getBundleStorage();
2674
+ const index = await storage.loadIndex();
2675
+ const entry = index[bundleUrl];
2676
+ const running = this.provenance.get(bundleUrl)?.hash;
2677
+ if (!entry || entry.tenant !== tenant || !running || entry.bundleHash?.toLowerCase() !== running) return;
2678
+ if (this.isStale(epoch, tenant)) return;
2679
+ if (JSON.stringify(entry.trusted) !== key) {
2680
+ index[bundleUrl] = { ...entry, trusted: declaration };
2681
+ await storage.saveIndex(index);
2682
+ }
2683
+ this.recordedDeclarations.set(bundleUrl, key);
2684
+ } catch (err) {
2685
+ console.warn("[BundleManager] could not record trusted declaration:", err);
2686
+ }
2687
+ }
2688
+ /**
2689
+ * Download + integrity-verify a bundle. Refuses to return when:
2690
+ * - manifest hash and computed hash disagree
2691
+ * - server's `X-Bundle-SHA256` disagrees with manifest hash
2692
+ * - no expected hash AND no server hash header (cannot prove the bundle
2693
+ * wasn't tampered with — fail closed rather than trust the wire).
2694
+ */
2695
+ async download(bundleUrl, expectedHash) {
2696
+ const cacheBust = `${bundleUrl}${bundleUrl.includes("?") ? "&" : "?"}t=${Date.now()}`;
2697
+ const response = await apiFetchRaw(cacheBust);
2698
+ if (!response.ok) {
2699
+ const body = await response.text().catch(() => "");
2700
+ throw new Error(`Download failed: ${response.status} ${response.statusText} \u2014 ${body.substring(0, 200)}`);
2701
+ }
2702
+ const content = await response.text();
2703
+ if (content.length < 50 || content.trimStart().startsWith("<!")) {
2704
+ throw new Error("Bundle content is empty or HTML \u2014 server may have returned an error page");
2705
+ }
2706
+ const headerHash = (response.headers.get("x-bundle-sha256") || "").toLowerCase();
2707
+ const computed = sha256Hex(content);
2708
+ if (expectedHash) {
2709
+ if (computed !== expectedHash) {
2710
+ throw new Error(
2711
+ `Bundle integrity FAIL: expected sha256=${expectedHash.slice(0, 12)}... got ${computed.slice(0, 12)}.... Refusing to evaluate.`
2712
+ );
2713
+ }
2714
+ if (headerHash && headerHash !== expectedHash) {
2715
+ throw new Error(
2716
+ `Bundle hash mismatch: manifest=${expectedHash.slice(0, 12)}... server=${headerHash.slice(0, 12)}.... Refusing to evaluate.`
2717
+ );
2718
+ }
2719
+ } else if (headerHash) {
2720
+ if (computed !== headerHash) {
2721
+ throw new Error(
2722
+ `Bundle body sha256 (${computed.slice(0, 12)}...) does not match server's X-Bundle-SHA256 (${headerHash.slice(0, 12)}...).`
2723
+ );
2724
+ }
2725
+ console.warn(`[BundleManager] No manifest bundleHash \u2014 verified via X-Bundle-SHA256 header only`);
2726
+ } else {
2727
+ throw new Error(
2728
+ `No bundleHash in manifest and no X-Bundle-SHA256 header from server. Refusing to evaluate untrusted bundle.`
2729
+ );
2730
+ }
2731
+ return { content, sha256: computed };
2732
+ }
2733
+ evaluate(content, bundleUrl, verifiedHash) {
2734
+ assertBundleIntegrity(content, verifiedHash, bundleUrl);
2735
+ let cleaned = content.replace(
2736
+ /__toESM\(require\(("[^"]+")\)(?:,\s*\d+)?\)/g,
2737
+ "require($1)"
2738
+ );
2739
+ cleaned = cleaned.replace(
2740
+ /module\.exports\s*=\s*__toCommonJS\((\w+)\)/g,
2741
+ "module.exports = $1"
2742
+ );
2743
+ const mod = { exports: {} };
2744
+ try {
2745
+ const factory = new Function(
2746
+ "module",
2747
+ "exports",
2748
+ "require",
2749
+ "__filename",
2750
+ "__dirname",
2751
+ cleaned
2752
+ );
2753
+ factory(mod, mod.exports, requireShim, bundleUrl, "adas-plugin-bundles");
2754
+ } catch (err) {
2755
+ throw new Error(`Bundle evaluation failed: ${err instanceof Error ? err.message : String(err)}`);
2756
+ }
2757
+ const raw = mod.exports;
2758
+ const materialized = {};
2759
+ for (const key of Object.getOwnPropertyNames(raw)) {
2760
+ try {
2761
+ materialized[key] = raw[key];
2762
+ } catch {
2763
+ }
2764
+ }
2765
+ return materialized;
2766
+ }
2767
+ // ── Private: component extraction ───────────────────────────
2768
+ /** Find a plugin component in a loaded module. */
2769
+ getComponentFromMemory(pluginId, bundleUrl) {
2770
+ return this.findPluginExport(this.modules.get(bundleUrl), pluginId, hasComponent);
2771
+ }
2772
+ /**
2773
+ * Find THIS plugin's export in a loaded module — the one lookup both the
2774
+ * component and the device tools use, so a plugin's UI and its tools always
2775
+ * come from the same export. `accept` says what the caller needs from it.
2776
+ * Handles: direct key match, PascalCase key, default export, multi-plugin .id match.
2777
+ */
2778
+ findPluginExport(mod, pluginId, accept) {
2779
+ if (!mod) return null;
2780
+ const shortName = pluginId.includes(":") ? pluginId.split(":").pop() : pluginId;
2781
+ if (accept(mod[pluginId])) return mod[pluginId];
2782
+ const pascal = shortName.replace(/(^|-)([a-z])/g, (_, __, c) => c.toUpperCase());
2783
+ if (accept(mod[pascal])) return mod[pascal];
2784
+ if (accept(mod.default)) return mod.default;
2785
+ for (const key of Object.keys(mod)) {
2786
+ const val = mod[key];
2787
+ if (val && (val.id === pluginId || val.id === shortName) && accept(val)) return val;
2788
+ }
2789
+ return null;
2790
+ }
2791
+ describeModule(mod) {
2792
+ if (!mod) return "(empty)";
2793
+ return Object.keys(mod).map((k) => {
2794
+ const v = mod[k];
2795
+ if (v && typeof v === "object" && v.id) return `${k}(id="${v.id}")`;
2796
+ return k;
2797
+ }).join(", ");
2798
+ }
2799
+ };
2800
+ var bundleManager = new BundleManager();
2801
+
2802
+ // src/voiceHost.ts
2803
+ var _provider2 = null;
2804
+ function setVoiceProvider(provider) {
2805
+ _provider2 = provider || null;
2806
+ }
2807
+ function implementedVoice() {
2808
+ return !!_provider2;
2809
+ }
2810
+ function voiceDenial(why) {
2811
+ const err = new Error(`voice: ${why}`);
2812
+ err.code = "RESTRICTED";
2813
+ return err;
2814
+ }
2815
+ function deniedVoice(why) {
2816
+ const fail = () => {
2817
+ throw voiceDenial(why);
2818
+ };
2819
+ return {
2820
+ async start() {
2821
+ return fail();
2822
+ },
2823
+ stop() {
2824
+ fail();
2825
+ },
2826
+ setMuted() {
2827
+ fail();
2828
+ },
2829
+ prompt() {
2830
+ fail();
2831
+ },
2832
+ observe() {
2833
+ fail();
2834
+ },
2835
+ getSnapshot() {
2836
+ return {
2837
+ state: "error",
2838
+ sessionId: null,
2839
+ muted: false,
2840
+ speaking: false,
2841
+ listening: false,
2842
+ userSpeaking: false,
2843
+ lastUserSpeechEndedAt: null,
2844
+ lastDeviceTool: null,
2845
+ authorizedSessionId: null,
2846
+ lastError: why
2847
+ };
2848
+ },
2849
+ subscribe() {
2850
+ return fail();
2851
+ },
2852
+ transcript() {
2853
+ return [];
2854
+ }
2855
+ };
2856
+ }
2857
+ function scopedVoice(provider, pluginId) {
2858
+ return {
2859
+ start: (opts) => provider.start(opts, pluginId),
2860
+ stop: () => provider.stop(pluginId),
2861
+ setMuted: (muted) => provider.setMuted(muted, pluginId),
2862
+ prompt: (input) => provider.prompt(input, pluginId),
2863
+ observe: (text) => provider.observe(text, pluginId),
2864
+ getSnapshot: () => provider.getSnapshot(pluginId),
2865
+ subscribe: (cb) => provider.subscribe(cb, pluginId),
2866
+ transcript: () => provider.transcript(pluginId)
2867
+ };
2868
+ }
2869
+ function gateVoice(declared, pluginId) {
2870
+ if (!declared) {
2871
+ return deniedVoice(
2872
+ "not declared in this plugin's capabilities. Add `capabilities: { voice: true }` to use it."
2873
+ );
2874
+ }
2875
+ if (!pluginId) {
2876
+ return deniedVoice(
2877
+ "no plugin identity \u2014 voice fails closed without a caller to scope the session to."
2878
+ );
2879
+ }
2880
+ return _provider2 ? scopedVoice(_provider2, pluginId) : deniedVoice(
2881
+ "no voice session in this build \u2014 the app has not mounted a VoiceSessionHost / called setVoiceProvider."
2882
+ );
2883
+ }
2884
+
2885
+ // src/pluginRuntime.ts
2886
+ function mergeCaps(decl) {
2887
+ if (!decl) return void 0;
2888
+ return { ...decl.native, ...decl.capabilities };
2889
+ }
2890
+ function resolvePluginGrants(src) {
2891
+ const trusted = src.manifest ?? src.plugin ?? null;
2892
+ const stateDomains = trusted?.stateDomains ? [...trusted.stateDomains] : void 0;
2893
+ return { capabilities: mergeCaps(trusted), stateDomains };
2894
+ }
2895
+ function resolvePluginRuntimeProps(src) {
2896
+ const { capabilities, stateDomains } = resolvePluginGrants(src);
2897
+ const native = gatePluginNative(getPluginNative(), capabilities, src.pluginId);
2898
+ const deviceState = gateDeviceState(stateDomains);
2899
+ const voice = gateVoice(!!capabilities?.voice, src.pluginId);
2900
+ return { device: native, native, deviceState, voice };
2901
+ }
2902
+
2903
+ // src/tools/loader.ts
2904
+ import { getTenant as getTenant3 } from "@ateam-ai-mobile/core";
2905
+ var inflight = null;
2906
+ var loadedOnce = false;
2907
+ async function ensureDeviceToolsLoaded({ force = false } = {}) {
2908
+ if (loadedOnce && !force) return listDeviceTools().map((t) => t.name);
2909
+ if (inflight) return inflight;
2910
+ inflight = (async () => {
2911
+ try {
2912
+ const summaries = await listPlugins();
2913
+ const manifests = await Promise.all(
2914
+ (summaries || []).map(
2915
+ (s) => getPlugin(s.id).catch(() => null)
2916
+ )
2917
+ );
2918
+ const targets = manifests.filter((m) => {
2919
+ const declared = m?.capabilities?.device_tools;
2920
+ return Array.isArray(declared) && declared.length > 0;
2921
+ });
2922
+ if (targets.length === 0) {
2923
+ const recovered = await loadFromDiskCache();
2924
+ if (recovered.length > 0) {
2925
+ console.log(`[deviceTools] catalog listed none \u2014 recovered from cache: ${recovered.join(", ")}`);
2926
+ return recovered;
2927
+ }
2928
+ console.log("[deviceTools] no device tools available yet \u2014 will look again next call");
2929
+ return [];
2930
+ }
2931
+ await Promise.all(
2932
+ targets.map(async (m) => {
2933
+ const bundleUrl = getNativeBundleUrl(m);
2934
+ if (!bundleUrl) {
2935
+ console.warn(`[deviceTools] ${m.id} declares device_tools but has no native bundle`);
2936
+ return;
2937
+ }
2938
+ try {
2939
+ await bundleManager.loadTools(
2940
+ m.id,
2941
+ bundleUrl,
2942
+ m.version || "1.0.0",
2943
+ getNativeBundleHash(m) || void 0,
2944
+ resolvePluginGrants({ pluginId: m.id, manifest: m })
2945
+ );
2946
+ } catch (err) {
2947
+ console.warn(`[deviceTools] ${m.id} failed to load:`, err?.message || String(err));
2948
+ }
2949
+ })
2950
+ );
2951
+ const names = listDeviceTools().map((t) => t.name);
2952
+ loadedOnce = names.length > 0;
2953
+ console.log(`[deviceTools] ready: ${names.length > 0 ? names.join(", ") : "(none registered \u2014 will retry next call)"}`);
2954
+ return names;
2955
+ } finally {
2956
+ inflight = null;
2957
+ }
2958
+ })();
2959
+ return inflight;
2960
+ }
2961
+ async function loadFromDiskCache() {
2962
+ try {
2963
+ const index = await getBundleStorage().loadIndex();
2964
+ const entries = Object.values(index || {});
2965
+ if (entries.length === 0) return [];
2966
+ const tenant = getTenant3();
2967
+ if (!tenant) {
2968
+ console.warn("[deviceTools] disk-cache recovery skipped \u2014 no active tenant");
2969
+ return [];
2970
+ }
2971
+ const mine = selectOwnedCacheEntries(entries, tenant);
2972
+ const skipped = entries.length - mine.length;
2973
+ if (skipped > 0) {
2974
+ console.log(`[deviceTools] disk-cache recovery: ${mine.length} for "${tenant}", skipped ${skipped} not owned by it`);
2975
+ }
2976
+ const declared = mine.filter((e) => !!e.trusted?.pluginId);
2977
+ if (declared.length < mine.length) {
2978
+ console.log(
2979
+ `[deviceTools] disk-cache recovery: skipped ${mine.length - declared.length} with no recorded manifest grant (fail closed)`
2980
+ );
2981
+ }
2982
+ if (declared.length === 0) return [];
2983
+ await Promise.all(declared.map(async (e) => {
2984
+ try {
2985
+ await bundleManager.loadTools(e.trusted.pluginId, e.bundleUrl, e.version, e.bundleHash, e.trusted);
2986
+ } catch {
2987
+ }
2988
+ }));
2989
+ return listDeviceTools().map((t) => t.name);
2990
+ } catch (err) {
2991
+ console.warn("[deviceTools] disk-cache recovery failed:", err?.message || String(err));
2992
+ return [];
2993
+ }
2994
+ }
2995
+ function resetDeviceToolLoader() {
2996
+ loadedOnce = false;
2997
+ }
2998
+
2999
+ export {
3000
+ __export,
3001
+ register,
3002
+ registerTools,
3003
+ registerService,
3004
+ PLATFORM_VOICE_CALLER,
3005
+ View,
3006
+ Text,
3007
+ ScrollView,
3008
+ FlatList,
3009
+ SectionList,
3010
+ Pressable,
3011
+ TouchableOpacity,
3012
+ TextInput,
3013
+ Image,
3014
+ ActivityIndicator,
3015
+ Modal,
3016
+ Switch,
3017
+ StyleSheet,
3018
+ Animated,
3019
+ Platform,
3020
+ RefreshControl,
3021
+ Card,
3022
+ Badge,
3023
+ TabBar,
3024
+ ListItem,
3025
+ SearchBar,
3026
+ EmptyState,
3027
+ ErrorState,
3028
+ LoadingState,
3029
+ ActionButton,
3030
+ setHapticsProvider,
3031
+ getHaptics,
3032
+ setPluginNativeProvider,
3033
+ getPluginNative,
3034
+ gatePluginNative,
3035
+ setCameraPreviewProvider,
3036
+ getCameraPreviewProvider,
3037
+ registerNativePlugin,
3038
+ unregisterNativePlugin,
3039
+ nativePluginRegistry,
3040
+ registerBundleModules,
3041
+ CameraPreview,
3042
+ setPluginThemeColors,
3043
+ usePluginTheme,
3044
+ useApi,
3045
+ PluginSDK,
3046
+ setDeviceStateProvider,
3047
+ gateDeviceState,
3048
+ implementedStateDomains,
3049
+ setVoiceProvider,
3050
+ implementedVoice,
3051
+ gateVoice,
3052
+ resolvePluginGrants,
3053
+ resolvePluginRuntimeProps,
3054
+ useNativeBridge,
3055
+ createNativeBridge,
3056
+ setDeviceToolContextProvider,
3057
+ registerDeviceTools,
3058
+ unregisterDeviceTools,
3059
+ hasDeviceTool,
3060
+ listDeviceTools,
3061
+ callDeviceTool,
3062
+ clearDeviceTools,
3063
+ supportsNative,
3064
+ getNativeComponentId,
3065
+ getNativeBundleUrl,
3066
+ getNativeBundleHash,
3067
+ supportsWebView,
3068
+ listPlugins,
3069
+ getPlugin,
3070
+ resolvePluginUrl,
3071
+ AdaOrb,
3072
+ SurfaceDrawer,
3073
+ SurfaceCard,
3074
+ SurfaceFullscreen,
3075
+ useSurfaceStore,
3076
+ isMountSurface,
3077
+ isInlineSurface,
3078
+ SurfaceDispatcher,
3079
+ MemoryBundleStorage,
3080
+ setBundleStorage,
3081
+ bundleManager,
3082
+ ensureDeviceToolsLoaded,
3083
+ resetDeviceToolLoader
3084
+ };
3085
+ //# sourceMappingURL=chunk-RXR6M623.mjs.map