@ateam-ai-mobile/plugin-runtime 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -33,14 +33,16 @@ import {
33
33
  TextInput,
34
34
  TouchableOpacity,
35
35
  View,
36
- __export,
37
36
  bundleManager,
38
37
  callDeviceTool,
39
38
  clearDeviceTools,
40
39
  createNativeBridge,
40
+ device_state_exports,
41
41
  ensureDeviceToolsLoaded,
42
+ explainCapability,
42
43
  gateDeviceState,
43
44
  gatePluginNative,
45
+ gateVoice,
44
46
  getCameraPreviewProvider,
45
47
  getHaptics,
46
48
  getNativeBundleHash,
@@ -50,11 +52,15 @@ import {
50
52
  getPluginNative,
51
53
  hasDeviceTool,
52
54
  implementedStateDomains,
55
+ implementedVoice,
56
+ isActionable,
53
57
  isInlineSurface,
54
58
  isMountSurface,
55
59
  listDeviceTools,
56
60
  listPlugins,
57
61
  nativePluginRegistry,
62
+ neverObserved,
63
+ pluginBundleUrl,
58
64
  register,
59
65
  registerBundleModules,
60
66
  registerDeviceTools,
@@ -62,6 +68,8 @@ import {
62
68
  registerService,
63
69
  registerTools,
64
70
  resetDeviceToolLoader,
71
+ resolvePluginGrants,
72
+ resolvePluginRuntimeProps,
65
73
  resolvePluginUrl,
66
74
  setBundleStorage,
67
75
  setCameraPreviewProvider,
@@ -70,6 +78,7 @@ import {
70
78
  setHapticsProvider,
71
79
  setPluginNativeProvider,
72
80
  setPluginThemeColors,
81
+ setVoiceProvider,
73
82
  supportsNative,
74
83
  supportsWebView,
75
84
  unregisterDeviceTools,
@@ -78,157 +87,7 @@ import {
78
87
  useNativeBridge,
79
88
  usePluginTheme,
80
89
  useSurfaceStore
81
- } from "./chunk-PKDQLNBL.mjs";
82
-
83
- // src/sdk/device-state.ts
84
- var device_state_exports = {};
85
- __export(device_state_exports, {
86
- DeviceBridgeError: () => DeviceBridgeError,
87
- explainCapability: () => explainCapability,
88
- isActionable: () => isActionable,
89
- neverObserved: () => neverObserved
90
- });
91
- var DeviceBridgeError = class extends Error {
92
- constructor(code, message, opts) {
93
- super(message);
94
- this.name = "DeviceBridgeError";
95
- this.code = code;
96
- this.domain = opts?.domain;
97
- this.recoverable = opts?.recoverable;
98
- }
99
- };
100
- var CONFIDENCE_ORDER = {
101
- unknown: 0,
102
- low: 1,
103
- medium: 2,
104
- high: 3
105
- };
106
- function isActionable(quality, budget) {
107
- const { freshness, confidence } = quality;
108
- if (freshness.state === "unknown" || freshness.state === "stale") return false;
109
- if (freshness.ageMs === null || freshness.ageMs > budget.maxAgeMs) return false;
110
- if (budget.minConfidence) {
111
- const have = CONFIDENCE_ORDER[confidence?.level ?? "unknown"];
112
- if (have < CONFIDENCE_ORDER[budget.minConfidence]) return false;
113
- }
114
- return true;
115
- }
116
- function neverObserved() {
117
- return { state: "unknown", observedAt: null, ageMs: null };
118
- }
119
- function explainCapability(status) {
120
- if (status.support === "unsupported") return "this device does not have it";
121
- if (status.permission === "denied") return "permission was denied";
122
- if (status.permission === "restricted") return "permission is restricted";
123
- if (status.permission === "notDetermined") return "permission has not been asked for yet";
124
- if (status.permission === "limited") return "only limited access was granted";
125
- if (status.restriction === "policyRestricted") return "this plugin did not declare it";
126
- if (status.restriction === "backgroundRestricted") return "the app is in the background";
127
- if (status.restriction === "lowPowerRestricted") return "the device is in low-power mode";
128
- if (status.availability === "busy") return "it is in use by something else";
129
- if (status.availability === "temporarilyUnavailable") return "it is temporarily unavailable";
130
- if (status.availability === "unavailable") return "it is unavailable";
131
- if (status.support === "unknown" || status.availability === "unknown") {
132
- return "its state could not be determined";
133
- }
134
- return null;
135
- }
136
-
137
- // src/voiceHost.ts
138
- var _provider = null;
139
- function setVoiceProvider(provider) {
140
- _provider = provider || null;
141
- }
142
- function implementedVoice() {
143
- return !!_provider;
144
- }
145
- function voiceDenial(why) {
146
- const err = new Error(`voice: ${why}`);
147
- err.code = "RESTRICTED";
148
- return err;
149
- }
150
- function deniedVoice(why) {
151
- const fail = () => {
152
- throw voiceDenial(why);
153
- };
154
- return {
155
- async start() {
156
- return fail();
157
- },
158
- stop() {
159
- fail();
160
- },
161
- setMuted() {
162
- fail();
163
- },
164
- prompt() {
165
- fail();
166
- },
167
- observe() {
168
- fail();
169
- },
170
- getSnapshot() {
171
- return {
172
- state: "error",
173
- sessionId: null,
174
- muted: false,
175
- speaking: false,
176
- listening: false,
177
- userSpeaking: false,
178
- lastUserSpeechEndedAt: null,
179
- lastError: why
180
- };
181
- },
182
- subscribe() {
183
- return fail();
184
- },
185
- transcript() {
186
- return [];
187
- }
188
- };
189
- }
190
- function scopedVoice(provider, pluginId) {
191
- return {
192
- start: (opts) => provider.start(opts, pluginId),
193
- stop: () => provider.stop(pluginId),
194
- setMuted: (muted) => provider.setMuted(muted, pluginId),
195
- prompt: (input) => provider.prompt(input, pluginId),
196
- observe: (text) => provider.observe(text, pluginId),
197
- getSnapshot: () => provider.getSnapshot(pluginId),
198
- subscribe: (cb) => provider.subscribe(cb, pluginId),
199
- transcript: () => provider.transcript(pluginId)
200
- };
201
- }
202
- function gateVoice(declared, pluginId) {
203
- if (!declared) {
204
- return deniedVoice(
205
- "not declared in this plugin's capabilities. Add `capabilities: { voice: true }` to use it."
206
- );
207
- }
208
- if (!pluginId) {
209
- return deniedVoice(
210
- "no plugin identity \u2014 voice fails closed without a caller to scope the session to."
211
- );
212
- }
213
- return _provider ? scopedVoice(_provider, pluginId) : deniedVoice(
214
- "no voice session in this build \u2014 the app has not mounted a VoiceSessionHost / called setVoiceProvider."
215
- );
216
- }
217
-
218
- // src/pluginRuntime.ts
219
- function mergeCaps(decl) {
220
- if (!decl) return void 0;
221
- return { ...decl.native, ...decl.capabilities };
222
- }
223
- function resolvePluginRuntimeProps(src) {
224
- const trusted = src.manifest ?? src.plugin ?? null;
225
- const capabilities = mergeCaps(trusted);
226
- const stateDomains = trusted?.stateDomains;
227
- const native = gatePluginNative(getPluginNative(), capabilities, src.pluginId);
228
- const deviceState = gateDeviceState(stateDomains);
229
- const voice = gateVoice(!!capabilities?.voice, src.pluginId);
230
- return { device: native, native, deviceState, voice };
231
- }
90
+ } from "./chunk-SICFDA5K.mjs";
232
91
 
233
92
  // src/tools/platformTools.ts
234
93
  var PLATFORM_PLUGIN_ID = "platform:device-tools";
@@ -271,10 +130,10 @@ var REAL_DEPS = {
271
130
  // `./loader` reaches react-native via the bundle manager; import it only when
272
131
  // an effect actually fires (real app), never at module load (tests).
273
132
  resetLoader: () => {
274
- void import("./loader-5LUVXUY2.mjs").then((m) => m.resetDeviceToolLoader());
133
+ void import("./loader-MSZ4PVTO.mjs").then((m) => m.resetDeviceToolLoader());
275
134
  },
276
135
  load: () => {
277
- void import("./loader-5LUVXUY2.mjs").then((m) => {
136
+ void import("./loader-MSZ4PVTO.mjs").then((m) => {
278
137
  m.resetDeviceToolLoader();
279
138
  return m.ensureDeviceToolsLoaded({ force: true });
280
139
  });
@@ -340,7 +199,7 @@ function extractBundleUrl(pluginId, manifest) {
340
199
  const hasNativeComponent = !!(render.reactNative?.component || render.component);
341
200
  if (hasNativeComponent) {
342
201
  return {
343
- url: `/api/ui-plugins/${encodeURIComponent(pluginId)}/bundle.js`,
202
+ url: pluginBundleUrl(pluginId),
344
203
  source: injected ? "ignored-explicit" : "derived-default",
345
204
  ...injected && { ignored: injected }
346
205
  };
@@ -370,6 +229,8 @@ function usePlugin(pluginId, manifest) {
370
229
  const bundleHash = extractBundleHash(manifest);
371
230
  const componentId = extractComponentId(manifest);
372
231
  const lookupId = componentId || pluginId;
232
+ const grants = resolvePluginGrants({ pluginId, manifest });
233
+ const grantsKey = JSON.stringify(grants);
373
234
  if (ignoredUrl) {
374
235
  console.warn(`[usePlugin] ${pluginId}: IGNORED connector-injected bundleUrl="${ignoredUrl}". The host derives bundle URLs from pluginId via the canonical route.`);
375
236
  }
@@ -392,7 +253,7 @@ function usePlugin(pluginId, manifest) {
392
253
  }
393
254
  if (bundleUrl) {
394
255
  try {
395
- const component = await bundleManager.load(pluginId, bundleUrl, version, bundleHash);
256
+ const component = await bundleManager.load(pluginId, bundleUrl, version, bundleHash, grants);
396
257
  if (cancelled) return;
397
258
  setPlugin(component);
398
259
  setLoading(false);
@@ -429,7 +290,7 @@ function usePlugin(pluginId, manifest) {
429
290
  return () => {
430
291
  cancelled = true;
431
292
  };
432
- }, [pluginId, lookupId, bundleUrl, bundleHash, version]);
293
+ }, [pluginId, lookupId, bundleUrl, bundleHash, version, grantsKey]);
433
294
  return { plugin, loading, error, bundleMissing };
434
295
  }
435
296
 
@@ -568,6 +429,7 @@ export {
568
429
  listPlugins,
569
430
  nativePluginRegistry,
570
431
  neverObserved,
432
+ pluginBundleUrl,
571
433
  register,
572
434
  registerBundleModules,
573
435
  registerDeviceTools,
@@ -576,6 +438,7 @@ export {
576
438
  registerService,
577
439
  registerTools,
578
440
  resetDeviceToolLoader,
441
+ resolvePluginGrants,
579
442
  resolvePluginRuntimeProps,
580
443
  resolvePluginUrl,
581
444
  setBundleStorage,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sdk/device-state.ts","../src/voiceHost.ts","../src/pluginRuntime.ts","../src/tools/platformTools.ts","../src/tools/sessionSync.ts","../src/tools/serverCalls.ts","../src/hooks/usePlugin.ts","../src/hooks/useRemotePlugins.ts"],"sourcesContent":["/**\n * @adas/device-state — Device Bridge v2, the SEMANTIC layer.\n *\n * Intended repo path:\n * packages/plugin-runtime/src/sdk/device-state.ts\n * Intended module specifier for plugin bundles:\n * '@adas/device-state' (NOT '@adas/plugin-sdk')\n *\n * ─────────────────────────────────────────────────────────────────────────\n * WHICH LAYER AM I IN?\n *\n * props.device.* MECHANICAL. \"Do this to the hardware, now.\"\n * VERB names: takePhoto, getCurrent, scanBarcode,\n * readOnce, authenticate, pickImage.\n * Returns a BARE value. THROWS when it cannot.\n * Declared in the manifest as `native: { camera: true }`.\n * Lives in '@adas/plugin-sdk'.\n *\n * props.deviceState.* SEMANTIC. \"What is true right now, and how well do\n * we know it?\"\n * STATE names: getSnapshot, subscribe, start, stop.\n * Returns a SNAPSHOT carrying freshness + confidence,\n * and able to say `unknown` in every field.\n * A read NEVER throws for absence.\n * Declared in the manifest as `stateDomains: ['visual']`.\n * Lives in '@adas/device-state' (this file).\n *\n * The two containers are the discriminator. Every semantic call in a plugin\n * begins with the eight characters `deviceState.`; every mechanical call\n * begins with `native.`. There is no line of code where the layer is\n * ambiguous, and no object on which both appear.\n *\n * This is a deliberate departure from\n * Docs/device-bridge-v2/DEVICE_BRIDGE_V2_IMPLEMENTATION_GROUNDING_2026-08-07.md\n * §\"Migration strategy\", which proposed adding `visual`, `spatial`,\n * `connectivityState`… as fields ON `PluginNative`. See the design note at the\n * bottom of this file for why that layout is rejected and what it costs.\n * ─────────────────────────────────────────────────────────────────────────\n *\n * PROVENANCE MARKERS used throughout. They are not decoration — the freeze\n * really does fix some of this and really does leave the rest open, and an\n * implementor needs to know which is which before changing a line:\n *\n * FROZEN — API_FREEZE 2026-08-07 §15 lists it as a frozen candidate.\n * V0.1 — \"v0.1 freeze candidate; may change only when implementation\n * grounding proves a field impossible/non-portable.\"\n * OPEN — the docs explicitly leave it undecided. Do not quietly close it.\n * DECISION — not in the docs at all; decided here, and reversible.\n */\n\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\n// ═════════════════════════════════════════════════════════════════════════\n// 1. Common metadata model\n// FROZEN (API_FREEZE §1, §15 \"Common metadata model: frozen candidate\").\n// Shared verbatim by all eight domains. Do not fork a per-domain variant.\n// ═════════════════════════════════════════════════════════════════════════\n\n/** FROZEN (API_FREEZE §1). The eight domain keys. */\nexport type DeviceBridgeDomain =\n | 'spatial'\n | 'visual'\n | 'activity'\n | 'deviceContext'\n | 'connectivity'\n | 'capability'\n | 'environment'\n | 'interaction';\n\nexport type FreshnessState = 'fresh' | 'aging' | 'stale' | 'unknown';\n\n/**\n * FROZEN. Both fields are nullable on purpose: \"we have no observation at all\"\n * has to be expressible without inventing a timestamp.\n *\n * `aging` is a real third state, not a rounding of fresh/stale — a consumer\n * that only branches on fresh-vs-stale is misreading the contract.\n *\n * API_FREEZE §1 \"Why observedAt + ageMs\": the host may compute `ageMs` at read\n * time, so it can be more accurate than `Date.now() - observedAt` measured on\n * the JS side after a bridge hop. Read `ageMs` when you have it.\n */\nexport interface Freshness {\n state: FreshnessState;\n /** Epoch ms of the observation itself. `null` = never observed. */\n observedAt: number | null;\n /** Age at read time. `null` = never observed. */\n ageMs: number | null;\n}\n\nexport type ConfidenceLevel = 'high' | 'medium' | 'low' | 'unknown';\n\n/**\n * FROZEN. `level` is mandatory and ordinal; `score` is optional and exists\n * only \"when a stable numeric estimate exists\" (API_FREEZE §1).\n *\n * The asymmetry is the point: native must not manufacture 0.5 to fill a field.\n * A missing `score` is information — it says the estimator has no calibrated\n * number, only a bucket.\n */\nexport interface Confidence {\n level: ConfidenceLevel;\n /** 0..1. Omitted when no stable numeric estimate exists. */\n score?: number;\n}\n\n/**\n * FROZEN. Every snapshot in v2 carries exactly one of these.\n *\n * `freshness` required, `confidence` optional — because some domains report\n * exact OS facts (battery level, audio route) where a confidence is\n * meaningless, and others report inference (activity, indoor/outdoor) where it\n * is mandatory. Cross-domain review: \"Freshness is mandatory for dynamic\n * state. Confidence is mandatory for inferred/estimated state; optional for\n * exact OS facts.\"\n *\n * NOTE (OPEN): freshness is per-SNAPSHOT, never per-field. So a snapshot\n * cannot today say \"lighting is fresh but acoustics is stale\". The\n * architecture doc raised this for Spatial and Environment and never resolved\n * it. Do not work around it by inventing a second freshness field.\n */\nexport interface StateQuality {\n freshness: Freshness;\n confidence?: Confidence;\n}\n\n// ── Support / permission / availability / restriction ──────────────────────\n// FROZEN (API_FREEZE §1). Four INDEPENDENT axes. The capability doc is blunt:\n// \"Do not collapse all failure modes into a single boolean.\" A camera can be\n// supported + granted + busy, and each of those three answers leads the caller\n// somewhere different.\n\nexport type SupportState = 'supported' | 'unsupported' | 'unknown';\n\nexport type PermissionState =\n | 'granted'\n | 'denied'\n | 'restricted'\n | 'notDetermined'\n | 'limited'\n | 'unavailable'\n | 'unknown';\n\nexport type AvailabilityState =\n | 'available'\n | 'busy'\n | 'temporarilyUnavailable'\n | 'unavailable'\n | 'unknown';\n\nexport type RestrictionState =\n | 'none'\n | 'backgroundRestricted'\n | 'systemRestricted'\n | 'policyRestricted'\n | 'lowPowerRestricted'\n | 'unknown';\n\n// ── Events ────────────────────────────────────────────────────────────────\n\n/**\n * FROZEN (API_FREEZE core rule 4): \"Events are meaningful semantic changes,\n * never raw sensor streams.\" If you find yourself wanting an event per frame\n * or per GPS fix, you are in the wrong layer.\n */\nexport interface StateEvent<TName extends string = string> {\n domain: DeviceBridgeDomain;\n name: TName;\n /** Epoch ms. */\n timestamp: number;\n /**\n * OPEN: per-event payload schemas are not specified anywhere in the three\n * design docs. Typed `unknown` rather than `any` so a consumer is forced to\n * narrow it rather than read a field that may not exist.\n */\n payload?: unknown;\n}\n\nexport interface Subscription {\n unsubscribe(): void;\n}\n\nexport type StateListener<TName extends string = string> = (\n event: StateEvent<TName>,\n) => void;\n\n/**\n * VOCABULARY §\"Event Naming Rule\", expressed as a type.\n *\n * Four domains (visual, activity, spatial, deviceContext) have NO frozen event\n * vocabulary — the vocabulary doc publishes \"Initial … Events\" lists for\n * connectivity, capability, interaction and environment only. Rather than mint\n * names those docs deliberately did not mint, their events are typed against\n * the naming RULE. A wrong-shaped name is a compile error; the specific\n * vocabulary stays open, as the docs left it.\n */\nexport type ConformingEventName =\n | `${string}Changed`\n | `${string}Started`\n | `${string}Stopped`\n | `${string}Available`\n | `${string}Unavailable`\n | `${string}StateStale`;\n\n// ── Errors ────────────────────────────────────────────────────────────────\n\n/** FROZEN (API_FREEZE §12). */\nexport type DeviceBridgeErrorCode =\n | 'UNSUPPORTED'\n | 'PERMISSION_DENIED'\n | 'RESTRICTED'\n | 'BUSY'\n | 'TEMPORARILY_UNAVAILABLE'\n | 'STALE'\n | 'TIMEOUT'\n | 'CANCELLED'\n | 'INTERNAL';\n\n/**\n * FROZEN shape (API_FREEZE §12).\n *\n * READ THE SCOPE LINE CAREFULLY. This is for FAILED OPERATIONS —\n * `visual.capture()`, `visual.start()`. It is NOT how the surface reports that\n * a camera is denied or a sensor is missing: \"Expected state should still be\n * exposed in snapshots.\"\n *\n * So: `getSnapshot()` does not throw this. `capture()` and `start()` do.\n * That split is the whole no-fabrication contract in one sentence — a read\n * always returns something honest, an action either happens or explains\n * itself in a typed code.\n */\nexport class DeviceBridgeError extends Error {\n readonly code: DeviceBridgeErrorCode;\n readonly domain?: DeviceBridgeDomain;\n /** Whether retrying could plausibly succeed (BUSY yes, UNSUPPORTED no). */\n readonly recoverable?: boolean;\n\n constructor(\n code: DeviceBridgeErrorCode,\n message: string,\n opts?: { domain?: DeviceBridgeDomain; recoverable?: boolean },\n ) {\n super(message);\n this.name = 'DeviceBridgeError';\n this.code = code;\n this.domain = opts?.domain;\n this.recoverable = opts?.recoverable;\n }\n}\n\n// ── Sessions and the lifecycle pattern ────────────────────────────────────\n\nexport interface StateSession {\n id: string;\n /** The intent this session was started with. */\n intent: string;\n startedAt: number;\n}\n\nexport interface StartOptions<TIntent extends string> {\n /**\n * MANDATORY, and that is the single most important line in this file.\n *\n * You cannot open a v2 session without naming what it is FOR. Native then\n * owns sampling rate, resolution, buffering, fusion and power — API_FREEZE\n * core rule 6. `start()` means \"maintain state according to this intent\",\n * not \"open a particular native API\" (§2).\n *\n * Contrast the mechanical layer, where `camera.takePhoto()` is a legal,\n * complete, intent-free call. That difference is visible at every call site.\n */\n intent: TIntent;\n /**\n * DECISION (not frozen). §13 requires bounded timeout/cancellation for\n * session starts and says chain STOP must propagate to native, but leaves\n * the plumbing \"implementation-specific\". `AbortSignal` is what\n * `DeviceToolContext.signal` already carries in this SDK, so reuse it rather\n * than invent a second cancellation idiom.\n */\n signal?: AbortSignal;\n}\n\n/**\n * FROZEN pattern (API_FREEZE §2), reproduced as documentation. The eight\n * concrete domains below do NOT extend this — each spells out exactly the\n * methods it has, because §11 warns \"domains should not be forced to implement\n * meaningless lifecycle methods\" and three domains genuinely have no intent\n * vocabulary at all.\n *\n * Two invariants apply to every domain:\n * - `getSnapshot()` reads CACHED state. It must not trigger expensive raw\n * sensing (no camera open, no network probe, no GPS cold start).\n * - \"Multiple plugins may eventually share one native engine; session\n * ownership must not imply duplicate sensor pipelines.\" (OPEN: the\n * arbitration mechanism is undefined. See DESIGN NOTE 3.)\n */\nexport interface StatefulDomain<\n TSnapshot,\n TIntent extends string = never,\n TEvent extends string = string,\n> {\n getSnapshot(): Promise<TSnapshot>;\n start?(options: StartOptions<TIntent>): Promise<StateSession>;\n stop?(sessionId?: string): Promise<void>;\n subscribe?(listener: StateListener<TEvent>): Subscription;\n}\n\n/**\n * Why every read is `Promise<T>` even though it is a cached read.\n *\n * Not because it samples — it must not. Because it crosses the RN bridge, and\n * this SDK has no synchronous JSI module today (verified: everything in\n * PluginNative except haptics/connectivity.isOnline is Promise-based). The\n * grounding doc's own target for a warm cached snapshot is p50 < 10 ms /\n * p95 < 30 ms, which is an async-bridge budget, not a sampling budget.\n */\n\n// ═════════════════════════════════════════════════════════════════════════\n// 2. Domain 1 — Spatial State\n// ═════════════════════════════════════════════════════════════════════════\n\n/**\n * FROZEN (API_FREEZE §3). Copied verbatim, not designed here.\n *\n * This landed as a placeholder first, on the belief that §3's field schema had\n * never been written. It had — the placeholder was a gap in what got read, not\n * a gap in the freeze. Worth recording, because \"the docs leave this open\" and\n * \"I did not find it\" produce identical-looking comments and only one of them\n * is a reason to invent a shape.\n */\nexport type SpatialIntent =\n | 'navigation'\n | 'fitness'\n | 'geofence'\n | 'lowPowerTracking'\n | 'preciseLocate';\n\n/** FROZEN (API_FREEZE §3). */\nexport interface SpatialPoint {\n latitude: number;\n longitude: number;\n altitude?: number | null;\n /** Metres. `null` when the platform gives no estimate — never 0, which\n * would read as a perfect fix. */\n accuracyM?: number | null;\n timestamp: number;\n}\n\n/** FROZEN (API_FREEZE §3). */\nexport interface SpatialSnapshot {\n /** `null` when there is no usable fix. Not a zero coordinate — (0,0) is a\n * real place in the Gulf of Guinea. */\n position: SpatialPoint | null;\n movement: {\n speedMps: number | null;\n bearingDeg: number | null;\n distanceRecentM: number | null;\n state?: 'stationary' | 'moving' | 'unknown';\n };\n orientation: {\n headingDeg: number | null;\n headingAccuracyDeg?: number | null;\n pitchDeg?: number | null;\n rollDeg?: number | null;\n };\n /** Newest last. Empty when nothing has been recorded — the ring is a native\n * concern, and its window is chosen by intent. */\n recentPath: SpatialPoint[];\n changes?: {\n lastMeaningfulTurnDeg?: number | null;\n timestamp?: number | null;\n };\n quality: StateQuality;\n}\n\nexport interface SpatialDomain {\n getSnapshot(): Promise<SpatialSnapshot>;\n start(options: StartOptions<SpatialIntent>): Promise<StateSession>;\n stop(sessionId?: string): Promise<void>;\n /** OPEN: no frozen spatial event vocabulary; rule-conforming names only. */\n subscribe(listener: StateListener<ConformingEventName>): Subscription;\n}\n\n// ═════════════════════════════════════════════════════════════════════════\n// 3. Domain 2 — Visual State\n//\n// Visual is NOT \"the camera API\". It is a native-maintained visual timeline\n// plus camera/capture state. Everything interpretive — what is in the scene,\n// what the sign says, which corridor to take — sits ABOVE Device Bridge and is\n// not modelled here.\n// ═════════════════════════════════════════════════════════════════════════\n\n/** FROZEN (API_FREEZE §4) + VOCABULARY §\"Visual Intents\". Nine values. */\nexport type VisualIntent =\n | 'navigation'\n | 'document'\n | 'ocr'\n | 'shopping'\n | 'inspection'\n | 'accessibility'\n | 'stream'\n | 'highQuality'\n | 'lowPower';\n\n/**\n * Media crosses by REFERENCE, never as inline bytes (core rule 3).\n *\n * AN ID AND NOTHING ELSE. The `uri` field is gone (2026-08-16), and its\n * removal answers the question this comment used to record as OPEN — \"how does\n * a plugin turn a handle into pixels?\" It doesn't. Ever.\n *\n * Frames now live in a native ring keyed by id and are never written to disk.\n * `native.vision.readText/describe/assessQuality` take this id and resolve it\n * INSIDE the trusted layer; the pixels do not cross into plugin code, so a\n * solution's bundle cannot copy, upload or retain them. That is what makes\n * \"frames never leave the phone\" enforceable rather than a promise.\n *\n * Do not add `uri` or `bytes` back. A plugin that believes it needs the pixels\n * needs a new method on `native.vision` instead — one whose implementation\n * stays on this side of the boundary.\n */\nexport interface MediaHandle {\n id: string;\n mimeType?: string;\n /**\n * Epoch ms after which this id no longer resolves — the frame's real\n * eviction time from the native ring, not a guess.\n *\n * Past it, `native.vision` throws rather than returning an empty result:\n * \"I cannot look at that frame\" and \"I looked and found nothing\" are\n * different answers and must never be confused by a caller about to speak.\n * In practice a caller rarely hits this, because the timeline is clamped to\n * native retention — see `visualEngine.effectiveWindowMs()`.\n */\n expiresAt?: number | null;\n}\n\n/**\n * V0.1. Per-frame usability is CATEGORICAL, not numeric — 'degraded' rather\n * than a blur score. Coarse honest classes beat false precision; the same\n * principle the connectivity doc states outright for connection quality.\n *\n * Every member carries `'unknown'` so a platform that cannot assess blur says\n * so instead of defaulting to 'good'.\n */\nexport interface VisualFrameQuality {\n blur?: 'good' | 'degraded' | 'unknown';\n exposure?: 'good' | 'dark' | 'bright' | 'unknown';\n /** `null` = cannot tell. Distinct from `false` = checked, not obstructed. */\n obstructed?: boolean | null;\n}\n\nexport interface VisualFrameRef {\n handle: MediaHandle;\n timestamp: number;\n orientation?: { headingDeg?: number; pitchDeg?: number; rollDeg?: number };\n quality?: VisualFrameQuality;\n}\n\nexport interface VisualSnapshot {\n camera: {\n available: boolean;\n /**\n * Independent of `available` on purpose. A camera can be present and\n * permitted (`available: true`) while no session is running\n * (`active: false`) — that is a different situation from a camera the app\n * cannot use at all, and Guide has to say different things about them.\n *\n * DRIFT (flagged, not resolved): the architecture doc's conceptual block\n * also carried `camera.orientation`; the frozen §4 block does not. Not\n * added here.\n */\n active: boolean;\n facing?: 'front' | 'back' | 'unknown';\n };\n /**\n * `null` when there is no usable current frame.\n *\n * This is the anti-fabrication field. The alternative implementation —\n * returning the last frame you happen to still hold — is precisely how a\n * guidance loop ends up describing a corridor the user left thirty seconds\n * ago. If it is not current, it is `null`, and the timeline below is where\n * you go looking for history, knowingly.\n */\n latest: VisualFrameRef | null;\n /**\n * TIME-based, not frame-count-based. Default window ~5s; documented bounded\n * range roughly 1–15s, selected by profile/intent. Native decides how\n * densely to retain frames inside the window and evicts everything outside\n * it automatically.\n *\n * `windowMs` is exposed; FPS knobs are NOT, and must never be added\n * (API_FREEZE §4). If a plugin wants \"more frames\", it declares a different\n * intent — it does not turn a dial.\n */\n recentTimeline: { windowMs: number; frames: VisualFrameRef[] };\n quality: StateQuality;\n}\n\nexport interface VisualCaptureResult {\n frame: VisualFrameRef;\n}\n\n/**\n * OPEN, worth knowing before you use it: whether `capture({intent})` may pass\n * an intent DIFFERENT from the running session's intent is not addressed\n * anywhere in the three docs.\n */\nexport interface VisualCaptureOptions {\n intent: VisualIntent;\n /** §13: capture must support bounded timeout/cancellation. */\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\nexport interface VisualDomain {\n /**\n * Cached read. Does NOT open the camera and does NOT take a picture.\n *\n * This is the call a guidance loop makes on every turn. The hot path is:\n * native camera pipeline → rolling native timeline → cached visual state →\n * one snapshot read from RN. \"Avoid repeatedly starting the camera or\n * capturing a new image for every plugin-tool call during an interactive\n * session.\"\n */\n getSnapshot(): Promise<VisualSnapshot>;\n\n /** Maintain visual state according to this intent. Not \"open the camera\". */\n start(options: StartOptions<VisualIntent>): Promise<StateSession>;\n\n /**\n * An intentional, one-shot, high-quality-ish acquisition. THROWS\n * DeviceBridgeError on failure — it is an operation, not a read.\n *\n * If you are about to call this once per conversational turn, stop: that is\n * `getSnapshot()`'s job, and doing it here is the frame-timer pattern this\n * whole layer exists to replace.\n */\n capture(options: VisualCaptureOptions): Promise<VisualCaptureResult>;\n\n /**\n * OPEN (doc conflict): the architecture doc shows `visual.subscribe(events)`\n * — a filter — while API_FREEZE shows `visual.subscribe(listener)`. The\n * freeze is followed here. Unresolved.\n *\n * OPEN: there is no \"Initial Visual Events\" list anywhere. The candidate set\n * in prose (camera became available/unavailable, frame quality degraded/\n * recovered, camera appears obstructed, significant scene change, visual\n * session suspended/resumed, visual state became stale) is NOT a minted\n * vocabulary. Typed against the naming rule only.\n */\n subscribe(listener: StateListener<ConformingEventName>): Subscription;\n\n stop(sessionId?: string): Promise<void>;\n}\n\n// ═════════════════════════════════════════════════════════════════════════\n// 4. Domain 3 — Human Activity State\n// ═════════════════════════════════════════════════════════════════════════\n\n/** FROZEN (API_FREEZE §5, VOCABULARY §\"Human Activity Values\"). */\nexport type HumanActivity =\n | 'stationary'\n | 'walking'\n | 'running'\n | 'cycling'\n | 'driving'\n | 'unknown';\n\n/** FROZEN. Independent of HumanActivity — walking+pocket, driving+mounted. */\nexport type DevicePlacement =\n | 'handheld'\n | 'pocket'\n | 'table'\n | 'mounted'\n | 'unknown';\n\n/**\n * FROZEN. Note `driving` is BOTH an intent here and a HumanActivity value\n * above. The docs define no relationship between the two and do not flag the\n * collision: declaring intent `driving` does not assert the user is driving.\n */\nexport type ActivityIntent =\n | 'navigation'\n | 'fitness'\n | 'driving'\n | 'safety'\n | 'accessibility'\n | 'lowPower';\n\nexport interface ActivitySnapshot {\n human: {\n state: HumanActivity;\n /** `null` when the start of the current activity is not known. */\n since: number | null;\n /** REQUIRED, unlike StateQuality.confidence — an inferred activity may\n * never be handed over without saying how sure the inference is. */\n confidence: Confidence;\n };\n devicePose: {\n placement: DevicePlacement;\n /** V0.1. These four values appear only in the freeze TS, not in the\n * vocabulary doc — unlike the placement values. Mild drift, flagged. */\n orientation?: 'portrait' | 'landscape' | 'flat' | 'unknown';\n confidence: Confidence;\n };\n /**\n * Advisory only. `likelyNext` is a hint and never a fact.\n * OPEN: transition names are bare `string` — no controlled vocabulary exists\n * anywhere, which sits awkwardly beside \"Intents are not arbitrary strings\".\n */\n transition?: {\n current?: string | null;\n likelyNext?: string | null;\n confidence?: Confidence;\n };\n /** OPEN: no window length or cap is specified for Activity (Spatial gets\n * ~10–20s, Visual ~5s). Required array — an empty one is a real answer. */\n recentTransitions: Array<{ name: string; timestamp: number }>;\n quality: StateQuality;\n}\n\nexport interface ActivityDomain {\n getSnapshot(): Promise<ActivitySnapshot>;\n /**\n * OPEN: §11's naming list shows only `activity.getSnapshot()`, and §2 makes\n * start/stop optional. Whether Activity is session-based or a passive\n * always-on domain is genuinely unstated. Included here because the six\n * frozen ActivityIntent values would otherwise have no seam to arrive\n * through — but this is a DECISION, not a reading of the freeze.\n */\n start(options: StartOptions<ActivityIntent>): Promise<StateSession>;\n stop(sessionId?: string): Promise<void>;\n /** OPEN: no \"Initial Activity Events\" list exists. */\n subscribe(listener: StateListener<ConformingEventName>): Subscription;\n}\n\n// ═════════════════════════════════════════════════════════════════════════\n// 5. Domain 4 — Device Context\n//\n// SCOPE WARNING. The early architecture draft put lifecycle, audio route and\n// hardware availability here. The freeze REMOVED all three: app foreground/\n// background and active channels are canonicalized under Interaction; hardware\n// support/permission moved to Capability. Frozen Device Context is power +\n// thermal + resources, and nothing else.\n// ═════════════════════════════════════════════════════════════════════════\n\nexport interface DeviceContextSnapshot {\n power: {\n /** 0..1 FRACTION, not a percentage. `null` = not known. */\n batteryLevel: number | null;\n charging: boolean | null;\n lowPowerMode: boolean | null;\n };\n thermal: {\n state: 'nominal' | 'fair' | 'serious' | 'critical' | 'unknown';\n };\n resources: {\n memoryPressure?: 'normal' | 'warning' | 'critical' | 'unknown';\n storagePressure?: 'normal' | 'warning' | 'critical' | 'unknown';\n };\n /** Confidence is legitimately omitted here — these are exact OS facts, not\n * estimates. Freshness still matters: a populated batteryLevel says nothing\n * about whether it was sampled a second or a minute ago. */\n quality: StateQuality;\n}\n\n/**\n * NO INTENT TYPE, and that is deliberate — not an oversight, and not a gap to\n * fill in later. There is no `DeviceContextIntent` in the freeze and no\n * \"Device Context Intents\" section in the vocabulary, because\n * (cross-domain review) \"A domain may expose an intent only if it changes\n * native implementation strategy in a meaningful way.\" Reading battery and\n * thermal does not.\n *\n * The direction of flow is the other way round: Device Context is an INPUT to\n * how OTHER domains satisfy their intents. Visual intent `navigation` +\n * device context `battery 5% + low-power mode` → native picks a lower-power\n * camera strategy while still honouring the Visual contract. The plugin does\n * not retune anything, and must not be asked to.\n *\n * Do not add `deviceContext.start({intent:'lowPower'})` because five other\n * domains have a lowPower intent.\n */\nexport interface DeviceContextDomain {\n getSnapshot(): Promise<DeviceContextSnapshot>;\n /**\n * OPEN: `DeviceContextDomain`'s interface body is never written in the\n * freeze, and no Device Context event names are frozen (the vocabulary has\n * \"Initial … Events\" for connectivity/capability/interaction/environment\n * only). DECISION: expose subscribe, because the candidate events —\n * low-power mode changed, charging changed, thermal pressure changed — are\n * exactly what an adaptive session needs and polling for them is wasteful.\n *\n * OPEN: \"battery crossed significant threshold\" and \"changed materially\"\n * have no numbers anywhere, and Device Context has no profiles to\n * parameterize them.\n */\n subscribe(listener: StateListener<ConformingEventName>): Subscription;\n}\n\n// ═════════════════════════════════════════════════════════════════════════\n// 6. Domain 5 — Connectivity State\n// ═════════════════════════════════════════════════════════════════════════\n\n/** FROZEN (API_FREEZE §7, VOCABULARY §\"Connectivity Intents\"). */\nexport type ConnectivityIntent =\n | 'lowLatencyConversation'\n | 'interactive'\n | 'bulkTransfer'\n | 'backgroundSync'\n | 'offlineResilient'\n | 'lowPower';\n\n/**\n * V0.1, and note it is FLAT — the connectivity design doc sketched a nested\n * shape (internet{…}, quality{…}, recent_history{…}) and the freeze flattened\n * it. Two unreconciled deltas, carried here as-is rather than merged:\n * - `bandwidthClass` appears in the freeze but in neither the design doc nor\n * the vocabulary's Connectivity Values.\n * - there is NO recent-history field, although the design doc requires native\n * to maintain recent transitions and leaves the default window OPEN.\n */\nexport interface ConnectivitySnapshot {\n /** NOTE: the design doc says \"online / offline / uncertain\"; the frozen\n * third value is `unknown`. The two words are never reconciled. */\n reachability: 'online' | 'offline' | 'unknown';\n transport: 'wifi' | 'cellular' | 'ethernet' | 'other' | 'none' | 'unknown';\n qualityClass:\n | 'excellent'\n | 'good'\n | 'degraded'\n | 'poor'\n | 'unusable'\n | 'unknown';\n stability: 'stable' | 'changing' | 'flapping' | 'unknown';\n /** `null` when no recent measurement exists. Explicitly preferred over\n * reporting a stale number: \"return unknown rather than stale precision.\" */\n latencyMs?: number | null;\n bandwidthClass?: 'high' | 'medium' | 'low' | 'unknown';\n metered?: boolean | null;\n constrained?: boolean | null;\n quality: StateQuality;\n}\n\n/** FROZEN v0.1 (VOCABULARY §\"Initial Connectivity Events\"). All ten. */\nexport type ConnectivityEvent =\n | 'connectivityOnline'\n | 'connectivityOffline'\n | 'transportChanged'\n | 'connectivityDegraded'\n | 'connectivityRecovered'\n | 'connectivityUnstable'\n | 'connectivityStable'\n | 'meteredStateChanged'\n | 'constrainedStateChanged'\n | 'connectivityStateStale';\n\nexport interface ConnectivityDomain {\n /**\n * A fast local cached read. It must NOT ping, and must NOT run a bandwidth\n * or speed test. Latency is sampled on native's own schedule, chosen by\n * intent, and cached with a timestamp.\n */\n getSnapshot(): Promise<ConnectivitySnapshot>;\n /**\n * OPEN: `ConnectivityDomain` is named in §11 but never defined, so whether\n * connectivity is session-based is unstated. DECISION: yes — six frozen\n * intents with documented behavioural differences (lowLatencyConversation\n * \"prioritize fresh latency knowledge\"; lowPower \"rely primarily on passive\n * OS signals and minimize active probes\") only mean something if there is a\n * way to declare one.\n */\n start(options: StartOptions<ConnectivityIntent>): Promise<StateSession>;\n stop(sessionId?: string): Promise<void>;\n subscribe(listener: StateListener<ConnectivityEvent>): Subscription;\n}\n\n// ═════════════════════════════════════════════════════════════════════════\n// 7. Domain 6 — Capability / Permission State\n//\n// The \"why\" domain. When another snapshot says `unknown`, this is where the\n// reason lives. Descriptive only — it never triggers a permission dialog.\n// ═════════════════════════════════════════════════════════════════════════\n\n/**\n * FROZEN. Four independent axes, deliberately not collapsed. The canonical\n * worked example from the capability doc: supported + granted + busy + none —\n * a camera you own, are allowed to use, and cannot have right now.\n */\nexport interface CapabilityStatus {\n support: SupportState;\n permission?: PermissionState;\n availability: AvailabilityState;\n restriction?: RestrictionState;\n}\n\nexport interface CapabilitySnapshot {\n camera: CapabilityStatus;\n microphone: CapabilityStatus;\n /** The only capability the freeze gives scoped detail to. Health and\n * photos/media do NOT get one — see the gap note below. */\n location: CapabilityStatus & {\n precision?: 'precise' | 'approximate' | 'unknown';\n backgroundPermission?: PermissionState;\n };\n motion: CapabilityStatus;\n bluetooth: CapabilityStatus;\n uwb: CapabilityStatus;\n nfc: CapabilityStatus;\n notifications: CapabilityStatus;\n /**\n * GAP (flagged): the capability doc notes health \"authorization is often\n * record-type specific rather than a single global permission\" and its\n * candidate shape had a `permission_summary`. The frozen §9 gives health a\n * plain CapabilityStatus, so scoped health authorization is NOT\n * representable in v0.1. Its own exit criterion (\"scoped permissions are\n * representable\") is therefore only partly met.\n */\n health: CapabilityStatus;\n backgroundExecution: CapabilityStatus;\n /** GAP (flagged): photos/media appears in the design doc's native inputs and\n * its full-vs-limited scope discussion, but there is NO photos key in the\n * frozen CapabilitySnapshot. Not added here. */\n quality: StateQuality;\n}\n\n/** FROZEN v0.1 (VOCABULARY §\"Initial Capability Events\"). All ten. */\nexport type CapabilityEvent =\n | 'capabilityChanged'\n | 'permissionChanged'\n | 'capabilityAvailable'\n | 'capabilityUnavailable'\n /** NOTE: this pair does not match the documented naming patterns. The docs\n * neither flag nor reconcile it; carried verbatim rather than \"fixed\". */\n | 'capabilityBusy'\n | 'capabilityFree'\n | 'restrictionChanged'\n | 'locationPrecisionChanged'\n | 'backgroundPermissionChanged'\n | 'capabilityStateStale';\n\n/**\n * NO INTENT TYPE — the one domain that is intent-less by explicit reasoning\n * rather than by omission: \"Capability State itself should generally be cheap\n * and mostly event-driven, so it does not need many sensing profiles.\"\n * A candidate `interactive/background/minimal` vocabulary is floated in the\n * design doc and explicitly conditional (\"only be kept if implementation\n * proves they add value\"). Nothing frozen. Not added.\n *\n * Also NOT here: any `requestPermission()`. Permission-request UX is outside\n * this state engine by design, and a floated generic primitive is future work.\n */\nexport interface CapabilityDomain {\n getSnapshot(): Promise<CapabilitySnapshot>;\n subscribe(listener: StateListener<CapabilityEvent>): Subscription;\n}\n\n// ═════════════════════════════════════════════════════════════════════════\n// 8. Domain 7 — Environment State\n// ═════════════════════════════════════════════════════════════════════════\n\n/** FROZEN (VOCABULARY §\"Environment Intents\"). */\nexport type EnvironmentIntent =\n | 'ambient'\n | 'navigation'\n | 'accessibility'\n | 'proximity'\n | 'safety'\n | 'lowPower';\n\nexport interface EnvironmentSnapshot {\n /** Privacy is part of the SHAPE, not advice: this says `dim`, never a camera\n * frame; `loud`, never microphone audio; a beacon count, never a BLE\n * payload. Raw audio/images/BLE payloads are not part of this domain. */\n lighting: {\n level: 'dark' | 'dim' | 'normal' | 'bright' | 'veryBright' | 'unknown';\n lux?: number | null;\n confidence?: Confidence;\n };\n acoustics: {\n level: 'quiet' | 'moderate' | 'loud' | 'veryLoud' | 'unknown';\n approximateDb?: number | null;\n confidence?: Confidence;\n };\n /** `uncertain` and `unknown` are different: uncertain = we looked and cannot\n * decide; unknown = we have no basis to decide. */\n enclosure: {\n state: 'indoor' | 'outdoor' | 'uncertain' | 'unknown';\n confidence?: Confidence;\n };\n proximity?: {\n distanceClass?: 'immediate' | 'near' | 'far' | 'unknown';\n confidence?: Confidence;\n };\n /** The only sub-block with no confidence — these are presence booleans, not\n * estimates. Note they cannot distinguish unsupported / denied / switched\n * off; that distinction lives in `capability`. */\n nearbySignals?: {\n bleAvailable?: boolean;\n beaconCount?: number | null;\n uwbAvailable?: boolean;\n nfcAvailable?: boolean;\n };\n quality: StateQuality;\n}\n\n/** FROZEN v0.1 (VOCABULARY §\"Initial Environment Events\"). All ten. */\nexport type EnvironmentEvent =\n | 'lightingChanged'\n | 'environmentBecameDark'\n | 'environmentBecameBright'\n | 'noiseLevelChanged'\n | 'environmentBecameLoud'\n | 'indoorOutdoorChanged'\n | 'proximityChanged'\n | 'nearbySignalAppeared'\n | 'nearbySignalDisappeared'\n | 'environmentStateStale';\n\nexport interface EnvironmentDomain {\n getSnapshot(): Promise<EnvironmentSnapshot>;\n start(options: StartOptions<EnvironmentIntent>): Promise<StateSession>;\n stop(sessionId?: string): Promise<void>;\n subscribe(listener: StateListener<EnvironmentEvent>): Subscription;\n}\n\n// ═════════════════════════════════════════════════════════════════════════\n// 9. Domain 8 — Interaction State\n//\n// Reports interaction FACTS. It never decides \"pause the guide\" or \"speak now\"\n// — that is orchestration and belongs to the Plugin Tool / Skill / AI.\n// ═════════════════════════════════════════════════════════════════════════\n\nexport interface InteractionSnapshot {\n lifecycle: {\n appState: 'foreground' | 'background' | 'inactive' | 'unknown';\n screenOn: boolean | null;\n userActive?: boolean | null;\n idleDurationMs?: number | null;\n };\n audio: {\n captureActive: boolean | null;\n playbackActive: boolean | null;\n route:\n | 'speaker'\n | 'earpiece'\n | 'wiredHeadset'\n | 'bluetooth'\n | 'carAudio'\n | 'other'\n | 'unknown';\n /** `none` (checked, nothing interrupting) and `unknown` (no knowledge) are\n * deliberately different values. */\n interruption: 'none' | 'temporary' | 'system' | 'unknown';\n };\n /** Optional GROUP: a platform that cannot report voice session state omits\n * the whole block rather than guessing `false` for each field. */\n voice?: {\n sessionActive: boolean | null;\n userSpeaking?: boolean | null;\n assistantSpeaking?: boolean | null;\n };\n /** May report that a camera session is running; must NOT duplicate frame\n * state. Frames belong to `visual`. */\n visual?: {\n cameraSessionActive: boolean | null;\n };\n quality: StateQuality;\n}\n\n/** FROZEN v0.1 (VOCABULARY §\"Initial Interaction Events\"). All twelve. */\nexport type InteractionEvent =\n | 'appStateChanged'\n | 'screenStateChanged'\n | 'audioRouteChanged'\n | 'audioInterruptionStarted'\n | 'audioInterruptionEnded'\n | 'voiceSessionStarted'\n | 'voiceSessionStopped'\n | 'cameraSessionStarted'\n | 'cameraSessionStopped'\n | 'userBecameActive'\n | 'userBecameIdle'\n | 'interactionStateStale';\n\n/**\n * NO INTENT TYPE. §10 declares only `InteractionSnapshot`, and the vocabulary\n * — which does publish intents for spatial, visual, activity, connectivity and\n * environment — has no \"Interaction Intents\" section. Five profiles are\n * floated in the design doc, hedged twice (\"Likely profiles, if needed\") with\n * no obligation attached to any of them. Not added.\n */\nexport interface InteractionDomain {\n getSnapshot(): Promise<InteractionSnapshot>;\n subscribe(listener: StateListener<InteractionEvent>): Subscription;\n}\n\n// ═════════════════════════════════════════════════════════════════════════\n// 10. Root surface\n// ═════════════════════════════════════════════════════════════════════════\n\n/**\n * FROZEN name (API_FREEZE §11) and FROZEN member names.\n *\n * §11's \"Recommended naming rule\" says to call it `visual.getSnapshot()`, not\n * `device.visual.*`. Read here as a rule about the WIRE/tool-name convention\n * (`device.*` stays a human/backend routing convention for callable plugin\n * tools) rather than a ban on a plugin-prop container. That reading is a\n * judgement call and is flagged as such — if it is wrong, the fix is to rename\n * the PROP, never to merge these eight members into `PluginNative`.\n */\nexport interface DeviceBridgeV2 {\n readonly spatial: SpatialDomain;\n readonly visual: VisualDomain;\n readonly activity: ActivityDomain;\n readonly deviceContext: DeviceContextDomain;\n readonly connectivity: ConnectivityDomain;\n readonly capability: CapabilityDomain;\n readonly environment: EnvironmentDomain;\n readonly interaction: InteractionDomain;\n}\n\n/** The name plugin authors see. See DESIGN NOTE 1 for why not `deviceBridge`. */\nexport type DeviceState = DeviceBridgeV2;\n\n// ═════════════════════════════════════════════════════════════════════════\n// 11. Manifest gate — a SEPARATE declaration from `native`\n// ═════════════════════════════════════════════════════════════════════════\n\n/**\n * DECISION (not in the docs). A second, differently-named manifest field, so a\n * plugin cannot half-declare its way across the boundary:\n *\n * native: { camera: true } → props.device.camera.takePhoto()\n * stateDomains: ['visual', 'spatial'] → props.deviceState.visual.getSnapshot()\n *\n * Declaring `native.camera` grants NOTHING in the semantic layer, and vice\n * versa. There is no field whose meaning spans both.\n *\n * How an UNDECLARED domain must behave — and this is the load-bearing part:\n * it returns a normal snapshot in which every enum is `unknown`, every\n * nullable is `null`, and `quality.freshness` is\n * `{ state:'unknown', observedAt:null, ageMs:null }`. It does NOT throw and it\n * does NOT return undefined.\n *\n * Why that matters here specifically: today's `gatePluginNative` gives an\n * undeclared capability a proxy whose methods `console.warn` and return\n * `undefined` (packages/plugin-runtime/src/host.ts:67-76). So\n * `await native.location.getCurrent()` on an undeclared plugin resolves to\n * `undefined`, and `pos?.latitude` is `undefined` — which then flows into an\n * LLM answer as a confident nothing. A silent undefined is a fabrication\n * vector; a snapshot of explicit unknowns is not.\n *\n * The \"why\" is readable from `capability.getSnapshot()` using an existing\n * frozen enum member: a manifest-gate denial maps to\n * `restriction: 'policyRestricted'` — the plugin manifest IS a policy. No new\n * vocabulary needed. (The docs never consider a manifest gate, so this\n * mapping is a DECISION, but it uses only frozen values.)\n */\nexport type StateDomainDeclaration = readonly DeviceBridgeDomain[];\n\n// ═════════════════════════════════════════════════════════════════════════\n// 12. Small helpers — the \"present does not mean fresh\" guard\n// DECISION. Not frozen, not in any doc. Included because the single most\n// likely misuse of this API is reading a value and ignoring `quality`, and a\n// one-line guard is easier to reach for than a correct hand-rolled check.\n// ═════════════════════════════════════════════════════════════════════════\n\nconst CONFIDENCE_ORDER: Record<ConfidenceLevel, number> = {\n unknown: 0,\n low: 1,\n medium: 2,\n high: 3,\n};\n\n/**\n * Is this snapshot good enough to act on?\n *\n * Deliberately requires the caller to state a budget: there is no universal\n * \"fresh enough\", and the docs give no numeric thresholds for any domain\n * (native chooses sampling behaviour). A guidance loop wants ~1500 ms; a\n * battery-aware background job is happy with 60 s.\n *\n * `unknown` freshness fails: it means nothing was ever observed, which is not\n * the same as an old-but-real reading and must not be treated as one.\n */\nexport function isActionable(\n quality: StateQuality,\n budget: { maxAgeMs: number; minConfidence?: ConfidenceLevel },\n): boolean {\n const { freshness, confidence } = quality;\n if (freshness.state === 'unknown' || freshness.state === 'stale') return false;\n if (freshness.ageMs === null || freshness.ageMs > budget.maxAgeMs) return false;\n if (budget.minConfidence) {\n const have = CONFIDENCE_ORDER[confidence?.level ?? 'unknown'];\n if (have < CONFIDENCE_ORDER[budget.minConfidence]) return false;\n }\n return true;\n}\n\n/** The honest \"we have never observed this\" value. Use it instead of\n * inventing a timestamp when constructing a degraded snapshot. This is the\n * canonical source of the `unknown` freshness shape — the engine's\n * `qualityUnknown()` derives from it so the two never drift. */\nexport function neverObserved(): Freshness {\n return { state: 'unknown', observedAt: null, ageMs: null };\n}\n\n/**\n * One human-readable sentence for why a capability cannot answer, built ONLY\n * from what the four axes actually say. Returns null when the capability is\n * fine — so a caller cannot accidentally print a reason that does not exist.\n */\nexport function explainCapability(status: CapabilityStatus): string | null {\n if (status.support === 'unsupported') return 'this device does not have it';\n if (status.permission === 'denied') return 'permission was denied';\n if (status.permission === 'restricted') return 'permission is restricted';\n if (status.permission === 'notDetermined') return 'permission has not been asked for yet';\n if (status.permission === 'limited') return 'only limited access was granted';\n if (status.restriction === 'policyRestricted') return 'this plugin did not declare it';\n if (status.restriction === 'backgroundRestricted') return 'the app is in the background';\n if (status.restriction === 'lowPowerRestricted') return 'the device is in low-power mode';\n if (status.availability === 'busy') return 'it is in use by something else';\n if (status.availability === 'temporarilyUnavailable') return 'it is temporarily unavailable';\n if (status.availability === 'unavailable') return 'it is unavailable';\n if (status.support === 'unknown' || status.availability === 'unknown') {\n return 'its state could not be determined';\n }\n return null;\n}\n\n// ═════════════════════════════════════════════════════════════════════════\n// 13. Integration seams into the existing SDK\n// ═════════════════════════════════════════════════════════════════════════\n\n/**\n * Additive extension of `PluginProps` (sdk/types.ts:259).\n *\n * `deviceState` is OPTIONAL because a host that has not installed a v2\n * provider must not pretend to have one. `undefined` means \"this host has no\n * semantic layer\", which a plugin can check once; it does NOT mean \"the\n * sensors said nothing\". Those are different, and collapsing them would\n * reintroduce exactly the ambiguity this file exists to remove.\n */\nexport interface PluginPropsV2Extension {\n readonly deviceState?: DeviceState;\n}\n\n/**\n * Additive extension of `DeviceToolContext` (sdk/types.ts:320-327).\n *\n * This is the seam that matters most: device tools are what the AI calls, and\n * device tools are where a fabricated value reaches a user. The lint rule\n * proposed alongside this file (`no-mechanical-sensing-in-device-tools`) bans\n * `ctx.native.camera`, `ctx.native.location` and `ctx.native.connectivity`\n * inside a `DeviceToolDefinition.run` body — a device tool must reach sensing\n * through `ctx.deviceState`. UI code is unaffected.\n */\nexport interface DeviceToolContextV2Extension {\n readonly deviceState?: DeviceState;\n}\n\n// ═════════════════════════════════════════════════════════════════════════\n// DESIGN NOTES\n// ═════════════════════════════════════════════════════════════════════════\n\n/**\n * DESIGN NOTE 1 — why the prop is `deviceState`, not `deviceBridge`.\n *\n * \"Device Bridge\" already names three different things in this codebase:\n * - `DeviceBridge`, the telemetry sync class that polls collectors and\n * pushes to the relay (packages/expo/src/device-bridge/index.ts:60);\n * - `PluginNative`, which sdk/types.ts:323 documents verbatim as\n * \"Device Bridge — camera, location, sensors, storage\";\n * - the v2 semantic layer in this file.\n * A fourth use of the word would be the opposite of unmistakable. `deviceState`\n * says what the object is (state, not actions) and collides with nothing.\n *\n *\n * DESIGN NOTE 2 — why NOT `PluginNative.visual` / `PluginNative.connectivityState`.\n *\n * The implementation-grounding doc proposes adding the eight domains as fields\n * on `PluginNative`, with `connectivityState` to dodge the collision with the\n * existing `connectivity`. Rejected, for three reasons:\n *\n * (a) It puts `native.camera.takePhoto()` and `native.visual.getSnapshot()`\n * on one object, one keystroke apart in autocomplete. The layer becomes\n * invisible at the call site, which is the failure being designed out.\n * (b) `native.connectivity` vs `native.connectivityState` is a confusable\n * pair by construction — two fields, one object, near-identical names,\n * different layers, different return shapes. `deviceState.connectivity`\n * vs `native.connectivity` is disambiguated by the first token instead.\n * (c) The gate model would have to span both meanings of one manifest field.\n *\n * The grounding doc's actual constraint is §14's \"Do not create a second\n * plugin runtime\" — and this design does not. Same runtime, same registration,\n * same bundle pipeline, same props object; one additional namespace on it.\n * Everything else in that doc's file-by-file plan (resident engines, warm\n * sessions, reference counting, no pipeline per tool call, the p50<10ms /\n * p95<30ms snapshot budget) stands unchanged.\n *\n *\n * DESIGN NOTE 3 — what this file does NOT decide, because the docs did not.\n *\n * - Per-intent behavioural contracts. The architecture doc MANDATES that each\n * intent document latency goal, quality target, continuous-vs-one-shot,\n * rolling-history behaviour, power posture, background behaviour, required\n * permissions and output shape. No document supplies these for ANY of the\n * nine visual intents, and there is no equivalent table for activity. The\n * vocabulary is minted; the semantics behind each name are not. This is the\n * largest hole in the whole design and no amount of TypeScript closes it.\n * - Multi-consumer session ownership / reference counting.\n * - MediaHandle → bytes resolution, and expiry behaviour.\n * - Whether `visual.capture()` may use a different intent from the session.\n * - Event vocabularies for visual, activity, spatial, deviceContext.\n * - Per-event payload schemas for every domain.\n * - Background/foreground semantics for activity and connectivity (specified\n * only for visual).\n * - Numeric thresholds for fresh/aging/stale, and for \"materially changed\".\n * - Cross-domain conflict resolution (activity says walking, spatial speed\n * says vehicle) — explicitly deferred as future State Engine Fusion and\n * out of v2 scope. A v2 snapshot must be internally coherent; it is NOT\n * obliged to reconcile itself with another domain.\n */\n","/**\n * Host DI + gate for `props.voice` — the session counterpart of\n * setDeviceStateProvider / setPluginNativeProvider.\n *\n * The app mounts one live voice session (VoiceSessionHost in @ateam-ai-mobile/ui)\n * and hands it here once at startup via setVoiceProvider. gateVoice then decides,\n * per plugin, whether that session is exposed:\n *\n * - declared (`capabilities: { voice: true }`) + a provider present → the real\n * session.\n * - declared but no provider (no session host in this build) → a refusal that\n * names the reason.\n * - NOT declared → a refusal that names the reason.\n *\n * ABSENCE IS AN ANSWER (spec invariant 6). A denied surface never fakes an\n * `idle` snapshot and never silently no-ops: reads report `state: 'error'` with\n * an explicit `lastError`, and actions throw. A silent `idle` would read to a\n * reasoning loop as \"a working session that simply isn't connected yet\" — a\n * fabrication, the same class of bug as an undefined that flows into an answer.\n */\nimport type { VoiceAPI, VoiceSnapshot, VoiceSessionProvider } from './sdk/voice';\n\nlet _provider: VoiceSessionProvider | null = null;\n\n/** Host DI: the app supplies its live (owner-aware) voice session. Called once\n * at startup; pass null to detach (e.g. in a build with no voice). */\nexport function setVoiceProvider(provider: VoiceSessionProvider | null): void {\n _provider = provider || null;\n}\n\n/** Whether this build has a voice session to expose — for diagnostics. */\nexport function implementedVoice(): boolean {\n return !!_provider;\n}\n\nfunction voiceDenial(why: string): Error {\n const err: any = new Error(`voice: ${why}`);\n // Frozen vocabulary (matches gateDeviceState): a capability/manifest gate IS a\n // policy, so a denial is RESTRICTED — no new error vocabulary.\n err.code = 'RESTRICTED';\n return err;\n}\n\n/**\n * The refused surface. Reads answer honestly (\"I am not available, here is\n * why\"); actions throw. Deliberately NOT a fake `idle` and NOT a silent no-op.\n */\nfunction deniedVoice(why: string): VoiceAPI {\n const fail = () => { throw voiceDenial(why); };\n return {\n async start() { return fail(); },\n stop() { fail(); },\n setMuted() { fail(); },\n prompt() { fail(); },\n observe() { fail(); },\n getSnapshot(): VoiceSnapshot {\n return {\n state: 'error',\n sessionId: null,\n muted: false,\n speaking: false,\n listening: false,\n userSpeaking: false,\n lastUserSpeechEndedAt: null,\n lastError: why,\n };\n },\n subscribe() { return fail(); },\n transcript() { return []; },\n };\n}\n\n/**\n * A per-plugin VoiceAPI that stamps `pluginId` as the caller on every call, so\n * the owner-aware provider can isolate it. TWO plugins get TWO facades bound to\n * TWO identities; neither can read, control, or attach to the other's live\n * session — even though both declared voice and both share the one physical\n * session. A plugin never supplies its own identity: it is captured here.\n */\nfunction scopedVoice(provider: VoiceSessionProvider, pluginId: string): VoiceAPI {\n return {\n start: (opts) => provider.start(opts, pluginId),\n stop: () => provider.stop(pluginId),\n setMuted: (muted) => provider.setMuted(muted, pluginId),\n prompt: (input) => provider.prompt(input, pluginId),\n observe: (text) => provider.observe(text, pluginId),\n getSnapshot: () => provider.getSnapshot(pluginId),\n subscribe: (cb) => provider.subscribe(cb, pluginId),\n transcript: () => provider.transcript(pluginId),\n };\n}\n\n/**\n * The `voice` a plugin receives, gated by whether it declared the capability AND\n * scoped to its identity.\n *\n * `declared` is `!!capabilities.voice` from the plugin's TRUSTED declaration\n * (resolved in pluginRuntime.ts — the server manifest for a remote plugin, the\n * registry entry for a host-owned one). A downloaded bundle cannot grant itself\n * voice. `pluginId` is the trusted identity the returned facade is bound to.\n *\n * Reading the transcript of a live session is a privacy surface, not just an\n * API: this gate is the only thing between a plugin and everything the user\n * says. Two protections stack: (1) it is coupled to evidence — a live session\n * shows the platform-owned, unsuppressable mic indicator, so there is no path to\n * a transcript without visible proof the mic is/was live; and (2) it is scoped\n * to the owner, so declaring `voice` lets a plugin run ITS OWN conversation, not\n * eavesdrop on another solution's. A missing identity FAILS CLOSED.\n */\nexport function gateVoice(declared: boolean, pluginId: string): VoiceAPI {\n if (!declared) {\n return deniedVoice(\n \"not declared in this plugin's capabilities. Add `capabilities: { voice: true }` to use it.\",\n );\n }\n if (!pluginId) {\n return deniedVoice(\n 'no plugin identity — voice fails closed without a caller to scope the session to.',\n );\n }\n return _provider\n ? scopedVoice(_provider, pluginId)\n : deniedVoice(\n 'no voice session in this build — the app has not mounted a VoiceSessionHost / called setVoiceProvider.',\n );\n}\n","/**\n * The ONE runtime contract that turns a plugin's declarations into its gated\n * device surface — `props.device` / `props.native` (L2) and `props.deviceState`\n * (L3) — for EVERY renderer, on EVERY surface.\n *\n * WHY THIS EXISTS. Each renderer used to resolve this itself: the embedded route\n * gated both `native` and `deviceState`; the drawer/fullscreen renderer gated\n * only `native` and read `manifest.native` instead of `manifest.capabilities`;\n * the host-built-in surfaces gated `native` off the registry entry and passed no\n * `deviceState` at all. The SAME plugin therefore got full device access on one\n * surface and `undefined` on another — invisible to the author, whose manifest\n * was correct. A seam owned by three renderers is tested by none. This makes it\n * owned by one: every renderer calls resolvePluginRuntimeProps, so they cannot\n * disagree, and a parity test on this function covers all of them at once.\n */\nimport { getPluginNative, gatePluginNative } from './host';\nimport { gateDeviceState } from './deviceStateHost';\nimport { gateVoice } from './voiceHost';\nimport type { PluginNative, NativeCapabilities } from './sdk/types';\nimport type { DeviceState, DeviceBridgeDomain } from './sdk/device-state';\nimport type { VoiceAPI } from './sdk/voice';\n\n/** The gated surface a plugin Component receives. `device` and `native` are the\n * SAME object (native is the deprecated alias). */\nexport interface PluginRuntimeProps {\n device: PluginNative;\n native: PluginNative;\n deviceState: DeviceState;\n voice: VoiceAPI;\n}\n\n/**\n * Where a plugin's declarations come from. TRUSTED source resolution lives here,\n * not in each caller: the server `manifest` wins, the loaded bundle's own default\n * export is the fallback.\n */\n/** One declaration source — either the server manifest or the registry entry. */\ninterface PluginDeclaration {\n capabilities?: NativeCapabilities | Record<string, unknown>;\n native?: NativeCapabilities;\n stateDomains?: readonly DeviceBridgeDomain[];\n}\n\nexport interface PluginRuntimeSource {\n pluginId: string;\n /**\n * The server manifest (Core-passed) — the TRUSTED authority for a REMOTE\n * plugin. `capabilities` is the current field Core emits; `native` is the\n * legacy one. A grant absent here is NOT GRANTED (fail closed).\n */\n manifest?: PluginDeclaration | null;\n /**\n * The registry entry — the trusted authority for a HOST-OWNED plugin\n * (registered locally, no server manifest). For a REMOTE plugin this is the\n * downloaded bundle's own claim and is UNTRUSTED for gating; it is used ONLY\n * when there is no manifest.\n */\n plugin?: PluginDeclaration | null;\n}\n\n/** Union the recognized native-capability flags from a source's `native`\n * (legacy) and `capabilities` (current) fields. A grant in EITHER is honored;\n * neither shadows the other. `capabilities` may also carry non-capability\n * metadata (e.g. `device_tools`) — gatePluginNative reads only the flags it\n * knows and ignores the rest. */\nfunction mergeCaps(decl: PluginDeclaration | null | undefined): NativeCapabilities | undefined {\n if (!decl) return undefined;\n return { ...(decl.native as any), ...(decl.capabilities as any) } as NativeCapabilities;\n}\n\n/**\n * Turn a plugin's declarations into the gated { device, native, deviceState } it\n * receives — the SINGLE place this happens, so every surface is identical.\n *\n * TRUST BOUNDARY. Exactly ONE source is authoritative: the server `manifest` for\n * a remote plugin, the registry `plugin` for a host-owned one. They are NEVER\n * mixed, and a remote plugin's own downloaded bundle claim NEVER expands its\n * capabilities or L3 domains past what the trusted source granted. If the\n * trusted source omits a grant, it is not granted — fail closed. (If Core does\n * not carry `stateDomains` for a remote plugin, the fix is Core passing it, not\n * trusting the bundle: Core already holds the solution's declaration.)\n */\nexport function resolvePluginRuntimeProps(src: PluginRuntimeSource): PluginRuntimeProps {\n const trusted = src.manifest ?? src.plugin ?? null;\n const capabilities = mergeCaps(trusted);\n const stateDomains = trusted?.stateDomains;\n const native = gatePluginNative(getPluginNative(), capabilities, src.pluginId);\n const deviceState = gateDeviceState(stateDomains);\n // Voice is a capability flag, gated the same way — the TRUSTED declaration\n // decides, a downloaded bundle cannot grant itself the session (or the\n // transcript it can read). The facade is bound to the TRUSTED pluginId, so the\n // session is isolated per solution: declaring voice runs YOUR conversation, it\n // does not attach to another plugin's live one.\n const voice = gateVoice(!!(capabilities as any)?.voice, src.pluginId);\n // device and native are intentionally the SAME gated object (R4 rename).\n return { device: native, native, deviceState, voice };\n}\n","/**\n * Platform device tools.\n *\n * These are not a solution's plugin tools — they ship with the SDK and every\n * host has them, which is what makes a device tool testable without deploying\n * anything to a tenant. Their names and contracts are declared once on the\n * server (connectors/platform/device-tools-mcp.json); this is the device half.\n *\n * Registered at import, so a client answers them even before any plugin bundle\n * has loaded — that is the point: proving the device path works should not\n * depend on the thing being proved.\n */\nimport { registerDeviceTools } from './registry';\n\nconst PLATFORM_PLUGIN_ID = 'platform:device-tools';\n\nexport function registerPlatformDeviceTools(): void {\n registerDeviceTools(PLATFORM_PLUGIN_ID, [\n {\n name: 'device.echo',\n description: \"Echo a string back from the user's own device.\",\n input_schema: {\n type: 'object',\n properties: { text: { type: 'string' } },\n required: ['text'],\n },\n run: (args: any) => ({\n ok: true,\n echoed: (args && args.text) || '',\n // The proof: a server-side implementation could not say this truthfully.\n ran_on: 'device',\n }),\n },\n {\n name: 'device.ping',\n description: 'Check that the device is reachable.',\n input_schema: { type: 'object', properties: {} },\n run: () => ({ ok: true, ran_on: 'device', at: new Date().toISOString() }),\n },\n ]);\n}\n","/**\n * Ambient device-tool registration, driven by the auth session (R14).\n *\n * The LOCAL reasoning path must be live BEFORE voice opens — otherwise the only\n * proof of a loadable external skill is a voice-triggered one. So the host wires\n * this to its EXISTING auth-session subscription (no new transport, no plugin\n * special-case): a tenant becoming authenticated loads that tenant's external\n * device-tool bundles (and re-ensures the static platform tools); a tenant\n * SWITCH is a change of tenant while still authenticated, so it clears the old\n * tenant's tools and reloads; sign-out resets the loader latch (the registry\n * itself is cleared by the host's logout teardown, which already calls\n * clearDeviceTools()).\n *\n * The decision is a PURE function so the lifecycle is testable without a network\n * or a device; the effects are injected (same DI shape as the host's logout\n * teardown) so a test drives them with fakes.\n */\nimport { registerPlatformDeviceTools } from './platformTools';\nimport { clearDeviceTools } from './registry';\n// NOTE: `./loader` pulls in the bundle manager (react-native, core), so it is\n// imported LAZILY inside the real effects below — keeping this module itself\n// node-testable (a test injects fake effects and never touches that graph).\n\nexport interface SessionSnapshot {\n authenticated: boolean;\n /** The tenant the session is scoped to (derive it; never a stored copy). */\n tenant: string | null;\n}\n\nexport type DeviceToolsAction = 'load' | 'reset' | 'none';\n\n/**\n * PURE: what should the device-tool registry do for this session transition?\n * - a new authenticated tenant (initial sign-in OR a switch) → 'load'\n * - the same authenticated tenant again (e.g. a silent token refresh) → 'none'\n * - leaving authenticated (sign-out) → 'reset'\n */\nexport function deviceToolsActionForSession(\n next: SessionSnapshot,\n prevTenant: string | null,\n): { action: DeviceToolsAction; tenant: string | null } {\n const tenant = next.authenticated ? (next.tenant ?? null) : null;\n if (tenant && tenant !== prevTenant) return { action: 'load', tenant };\n if (!tenant && prevTenant) return { action: 'reset', tenant: null };\n return { action: 'none', tenant: prevTenant };\n}\n\n/** The effects a session transition drives — injected so a test can fake them. */\nexport interface DeviceToolsSessionDeps {\n /** Drop the previous tenant's device tools (a switch does not run logout teardown). */\n clear: () => void;\n /** Ensure the static, host-owned platform device tools are present. */\n registerPlatform: () => void;\n /** Forget the \"already loaded\" latch so a later (non-forced) load runs — sign-out. */\n resetLoader: () => void;\n /** Fire-and-forget reload of the current tenant's external device-tool bundles. */\n load: () => void;\n}\n\nconst REAL_DEPS: DeviceToolsSessionDeps = {\n clear: clearDeviceTools,\n registerPlatform: registerPlatformDeviceTools,\n // `./loader` reaches react-native via the bundle manager; import it only when\n // an effect actually fires (real app), never at module load (tests).\n resetLoader: () => {\n void import('./loader').then((m) => m.resetDeviceToolLoader());\n },\n load: () => {\n void import('./loader').then((m) => {\n m.resetDeviceToolLoader();\n return m.ensureDeviceToolsLoaded({ force: true });\n });\n },\n};\n\nlet prevTenant: string | null = null;\n\n/**\n * Apply a session transition to the device-tool registry. Call from the host's\n * existing auth-session subscription with a derived snapshot. Idempotent per\n * tenant: repeated snapshots for the same authenticated tenant do nothing, so a\n * silent token refresh does not churn the registry. Returns the action taken.\n */\nexport function syncDeviceToolsForSession(\n next: SessionSnapshot,\n deps: DeviceToolsSessionDeps = REAL_DEPS,\n): DeviceToolsAction {\n const { action, tenant } = deviceToolsActionForSession(next, prevTenant);\n prevTenant = tenant;\n if (action === 'load') {\n // A new authenticated tenant: drop the prior tenant's tools, re-seat the\n // static platform tools, then reload this tenant's external bundles (forced).\n deps.clear();\n deps.registerPlatform();\n deps.load();\n } else if (action === 'reset') {\n // Sign-out: the host's logout teardown clears the registry; we only forget\n // the loader latch so a later sign-in reloads.\n deps.resetLoader();\n }\n return action;\n}\n\n/** Test seam: forget the last-seen tenant so a test starts from signed-out. */\nexport function __resetSessionSyncForTest(): void {\n prevTenant = null;\n}\n","/**\n * Device tools called BY THE SERVER.\n *\n * Two callers reach the same registered function on this phone:\n *\n * - the voice loop, which already runs here (no server hop at all), and\n * - the server reasoning loop, which cannot execute a device tool itself and\n * sends it down the client's stream instead.\n *\n * This is the second one. It rides the transport the `ui.*` plugin commands\n * already use — a command arrives on the job/actor stream, we run it, and post\n * the outcome back keyed by `correlationId`. Nothing new was invented; the\n * payload just carries a tool call instead of a UI command.\n *\n * The host wires this once at startup:\n *\n * pluginCommandEmitter.on('plugin-command', handleServerDeviceToolCall);\n */\nimport { callDeviceTool } from './registry';\nimport { ensureDeviceToolsLoaded } from './loader';\n\ntype PostResult = (correlationId: string, result: any, error?: string) => Promise<void>;\n\nlet postResult: PostResult | null = null;\n\n/**\n * Host DI: how to answer the server. `@ateam-ai-mobile/core` supplies\n * postCommandResult; kept injectable so this package stays free of the REST\n * client and so tests can observe the answer.\n */\nexport function setDeviceToolResultPoster(fn: PostResult): void {\n postResult = fn;\n}\n\n/** Is this stream command a device tool call? */\nexport function isDeviceToolCommand(cmd: any): boolean {\n return !!cmd && cmd.kind === 'device_tool' && typeof cmd.tool === 'string' && !!cmd.correlationId;\n}\n\n/**\n * Run a server-dispatched device tool and answer.\n *\n * Never throws — the server is blocked on the correlationId, so the one thing\n * we must not do is stay silent. Every path posts something back.\n */\nexport async function handleServerDeviceToolCall(cmd: any): Promise<void> {\n if (!isDeviceToolCommand(cmd)) return;\n\n const { tool, args, correlationId } = cmd;\n\n if (!postResult) {\n console.warn('[deviceTools] server called a tool but no result poster is installed');\n return;\n }\n\n try {\n // The server may reach us before anything opened a voice call, so the\n // plugins may not be loaded yet. Cheap and idempotent once warm.\n await ensureDeviceToolsLoaded();\n\n const outcome = await callDeviceTool(tool, args || {});\n console.log(`[deviceTools] server-called ${tool} → ${outcome.ok ? 'ok' : outcome.reason}`);\n\n await postResult(\n correlationId,\n outcome.ok ? { ok: true, ...unwrap(outcome.result) } : undefined,\n outcome.ok ? undefined : outcome.error,\n );\n } catch (err: any) {\n await postResult(correlationId, undefined, err?.message || String(err)).catch(() => {});\n }\n}\n\n/** Keep an object result flat for the reasoning loop; wrap anything else. */\nfunction unwrap(result: any): Record<string, any> {\n if (result && typeof result === 'object' && !Array.isArray(result)) return result;\n return { result };\n}\n","/**\n * usePlugin — single hook for loading any plugin.\n *\n * Simple async load → done pattern over the global BundleManager singleton\n * (deduplication + caching) and the host's native plugin registry.\n *\n * Usage:\n * const { plugin, loading, error } = usePlugin(pluginId, manifest);\n * if (loading) return <Spinner />;\n * if (error) return <Error message={error} />;\n * return <plugin.Component bridge={bridge} device={device} theme={theme} context={context} />;\n */\nimport { useState, useEffect } from 'react';\nimport { bundleManager } from '../bundles/bundleManager';\nimport { nativePluginRegistry } from '../host';\nimport type { RegisteredUIPlugin } from '../sdk/types';\n\ninterface PluginManifestLike {\n version?: string;\n name?: string;\n render?: any;\n _connectorId?: string;\n}\n\ninterface UsePluginResult {\n plugin: RegisteredUIPlugin | null;\n loading: boolean;\n error: string | null;\n bundleMissing: boolean;\n}\n\n/**\n * Compute the bundle URL.\n *\n * **Policy:** bundle URLs are ALWAYS derived from the pluginId via the\n * canonical platform route /api/ui-plugins/{pluginId}/bundle.js.\n * Connector-supplied bundleUrl fields are IGNORED — the Builder strips them\n * at introspection time, but we treat any survivors as bugs and ignore them\n * here too (defense in depth vs \"hand-coded URL with bad encoding causes\n * silent iframe fallback\" bugs).\n */\ntype BundleUrlSource = 'derived-default' | 'ignored-explicit' | 'none';\nfunction extractBundleUrl(pluginId: string, manifest: PluginManifestLike): { url: string | null; source: BundleUrlSource; ignored?: string } {\n const render = manifest.render;\n if (!render || typeof render !== 'object') return { url: null, source: 'none' };\n\n // Detect (and refuse) any explicit bundle URL the connector tried to inject.\n const injected =\n (manifest as any).bundleUrl ||\n (render as any).bundleUrl ||\n render.reactNative?.bundleUrl ||\n null;\n\n // Mobile decides native vs web INDEPENDENT of render.mode. The server's\n // cp.getContextPlugin flattens mode to \"iframe\" whenever an iframeUrl is\n // available (for web-frontend compatibility) — even when a reactNative\n // component is also declared. So we derive the bundle URL whenever a\n // reactNative component is present, regardless of what `mode` says.\n const hasNativeComponent = !!(render.reactNative?.component || render.component);\n if (hasNativeComponent) {\n return {\n url: `/api/ui-plugins/${encodeURIComponent(pluginId)}/bundle.js`,\n source: injected ? 'ignored-explicit' : 'derived-default',\n ...(injected && { ignored: injected }),\n };\n }\n\n return { url: null, source: 'none' };\n}\n\n/**\n * Extract the SHA-256 integrity hash from the manifest (server-provided).\n * BundleManager refuses to evaluate a downloaded bundle whose bytes don't\n * hash to this value — defense vs MITM/CDN tampering.\n */\nfunction extractBundleHash(manifest: PluginManifestLike): string | undefined {\n if ((manifest as any).bundleHash) return (manifest as any).bundleHash;\n const render = manifest.render;\n if (!render || typeof render !== 'object') return undefined;\n if (render.bundleHash) return render.bundleHash;\n if (render.reactNative?.bundleHash) return render.reactNative.bundleHash;\n return undefined;\n}\n\n/**\n * Extract component name from manifest render field.\n */\nfunction extractComponentId(manifest: PluginManifestLike): string | null {\n const render = manifest.render;\n if (!render || typeof render !== 'object') return null;\n return render.component || render.reactNative?.component || null;\n}\n\nexport function usePlugin(pluginId: string, manifest: PluginManifestLike): UsePluginResult {\n const [plugin, setPlugin] = useState<RegisteredUIPlugin | null>(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n const [bundleMissing, setBundleMissing] = useState(false);\n\n const version = manifest.version || '1.0.0';\n const { url: bundleUrl, ignored: ignoredUrl } = extractBundleUrl(pluginId, manifest);\n const bundleHash = extractBundleHash(manifest);\n const componentId = extractComponentId(manifest);\n const lookupId = componentId || pluginId;\n\n if (ignoredUrl) {\n console.warn(`[usePlugin] ${pluginId}: IGNORED connector-injected bundleUrl=\"${ignoredUrl}\". The host derives bundle URLs from pluginId via the canonical route.`);\n }\n\n useEffect(() => {\n let cancelled = false;\n\n (async () => {\n try {\n // Path 1: Local registry (host-bundled / dev plugins)\n if (nativePluginRegistry.has(lookupId)) {\n const registered = await nativePluginRegistry.get(lookupId);\n if (cancelled) return;\n\n if (!registered) {\n throw new Error(`Local plugin not found: ${lookupId}`);\n }\n if (registered.type === 'service') {\n throw new Error(`Plugin ${lookupId} is a service plugin and cannot be rendered`);\n }\n\n setPlugin(registered as RegisteredUIPlugin);\n setLoading(false);\n return;\n }\n\n // Path 2: Remote bundle (via global BundleManager)\n if (bundleUrl) {\n try {\n const component = await bundleManager.load(pluginId, bundleUrl, version, bundleHash);\n if (cancelled) return;\n setPlugin(component);\n setLoading(false);\n return;\n } catch (bundleErr) {\n const msg = bundleErr instanceof Error ? bundleErr.message : String(bundleErr);\n // warn (not error) — this is a handled path: we fall back to WebView.\n console.warn(`[usePlugin] ${pluginId}: Bundle load failed, falling back to WebView:`, msg);\n // RN bundle failed — connector declared a component but didn't\n // ship a usable bundle (404, eval error, integrity fail, etc).\n // Mark \"bundle missing\" so the parent renderer can fall back to\n // the WebView/iframe when the manifest also has an iframeUrl.\n if (!cancelled) {\n setBundleMissing(true);\n setLoading(false);\n }\n return;\n }\n }\n\n // No native source available. If the manifest also has an iframeUrl,\n // mark \"bundle missing\" so the parent falls back to the WebView.\n // Only throw when there's truly nothing renderable.\n const iframeUrl = manifest?.render?.iframeUrl\n || (manifest?.render?.mode === 'adaptive' && manifest?.render?.iframe?.iframeUrl);\n if (iframeUrl) {\n if (!cancelled) {\n setBundleMissing(true);\n setLoading(false);\n }\n return;\n }\n throw new Error(\n `Plugin \"${manifest.name || pluginId}\" has no bundle URL and is not in the local registry. ` +\n `Check that the solution definition includes a valid render.reactNative.bundleUrl.`\n );\n } catch (err) {\n if (cancelled) return;\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`[usePlugin] Failed to load ${pluginId}:`, msg);\n setError(msg);\n setLoading(false);\n }\n })();\n\n return () => { cancelled = true; };\n }, [pluginId, lookupId, bundleUrl, bundleHash, version]);\n\n return { plugin, loading, error, bundleMissing };\n}\n","import { useEffect, useState, useCallback } from 'react';\nimport { apiFetch } from '@ateam-ai-mobile/core';\nimport type { PluginManifest } from '../sdk/types';\n\nexport interface RemotePlugin {\n id: string;\n name: string;\n version: string;\n manifest: PluginManifest;\n source: 'remote' | 'local'; // Where this plugin came from\n}\n\ninterface UseRemotePluginsResult {\n plugins: RemotePlugin[];\n loading: boolean;\n error: string | null;\n refreshing: boolean;\n refresh: () => Promise<void>;\n}\n\n/**\n * Fetches available UI plugins from A-Team Core for the current solution.\n * Uses apiFetch which auto-injects JWT + tenant headers.\n */\nexport function useRemotePlugins(solutionId?: string): UseRemotePluginsResult {\n const [plugins, setPlugins] = useState<RemotePlugin[]>([]);\n const [loading, setLoading] = useState(true);\n const [refreshing, setRefreshing] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const fetchRemotePlugins = useCallback(async () => {\n try {\n setError(null);\n\n const targetSolutionId = solutionId || 'current';\n\n let data: any;\n try {\n data = await apiFetch<any>(`/api/solutions/${targetSolutionId}/ui-plugins`);\n } catch (err: any) {\n if (err?.message?.includes('404')) {\n console.warn(`[useRemotePlugins] Solution ${targetSolutionId} not found or has no plugins`);\n setPlugins([]);\n return;\n }\n throw err;\n }\n const uiPlugins: RemotePlugin[] = (data.plugins || []).map((plugin: any) => ({\n id: plugin.id,\n name: plugin.name,\n version: plugin.version || '1.0.0',\n source: 'remote' as const,\n manifest: {\n id: plugin.id,\n name: plugin.name,\n version: plugin.version || '1.0.0',\n type: 'ui',\n description: plugin.description || '',\n capabilities: plugin.capabilities || {},\n channels: plugin.channels || ['default'],\n render: (plugin.render && typeof plugin.render === 'object') ? plugin.render : { mode: 'react-native' as const, component: plugin.name || plugin.id },\n entry_point: plugin.entry_point || plugin.name,\n sandbox: plugin.sandbox !== false,\n requires_auth: plugin.requires_auth !== false,\n } as PluginManifest,\n }));\n\n setPlugins(uiPlugins);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.error('[useRemotePlugins] Failed to fetch plugins:', message);\n setError(message);\n setPlugins([]); // Clear plugins on error\n } finally {\n setLoading(false);\n setRefreshing(false);\n }\n }, [solutionId]);\n\n const refresh = useCallback(async () => {\n setRefreshing(true);\n await fetchRemotePlugins();\n }, [fetchRemotePlugins]);\n\n useEffect(() => {\n setLoading(true);\n fetchRemotePlugins();\n }, [fetchRemotePlugins]);\n\n return {\n plugins,\n loading,\n error,\n refreshing,\n refresh,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuOO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAM3C,YACE,MACA,SACA,MACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OA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AQ,IAAI,UAAU,OAAO,GAAG;AAC/D,cAAQ,MAAM,+CAA+C,OAAO;AACpE,eAAS,OAAO;AAChB,iBAAW,CAAC,CAAC;AAAA,IACf,UAAE;AACA,iBAAW,KAAK;AAChB,oBAAc,KAAK;AAAA,IACrB;AAAA,EACF,GAAG,CAAC,UAAU,CAAC;AAEf,QAAM,UAAU,YAAY,YAAY;AACtC,kBAAc,IAAI;AAClB,UAAM,mBAAmB;AAAA,EAC3B,GAAG,CAAC,kBAAkB,CAAC;AAEvB,EAAAD,WAAU,MAAM;AACd,eAAW,IAAI;AACf,uBAAmB;AAAA,EACrB,GAAG,CAAC,kBAAkB,CAAC;AAEvB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["prevTenant","useEffect","useState"]}
1
+ {"version":3,"sources":["../src/tools/platformTools.ts","../src/tools/sessionSync.ts","../src/tools/serverCalls.ts","../src/hooks/usePlugin.ts","../src/hooks/useRemotePlugins.ts"],"sourcesContent":["/**\n * Platform device tools.\n *\n * These are not a solution's plugin tools — they ship with the SDK and every\n * host has them, which is what makes a device tool testable without deploying\n * anything to a tenant. Their names and contracts are declared once on the\n * server (connectors/platform/device-tools-mcp.json); this is the device half.\n *\n * Registered at import, so a client answers them even before any plugin bundle\n * has loaded — that is the point: proving the device path works should not\n * depend on the thing being proved.\n */\nimport { registerDeviceTools } from './registry';\n\nconst PLATFORM_PLUGIN_ID = 'platform:device-tools';\n\nexport function registerPlatformDeviceTools(): void {\n registerDeviceTools(PLATFORM_PLUGIN_ID, [\n {\n name: 'device.echo',\n description: \"Echo a string back from the user's own device.\",\n input_schema: {\n type: 'object',\n properties: { text: { type: 'string' } },\n required: ['text'],\n },\n run: (args: any) => ({\n ok: true,\n echoed: (args && args.text) || '',\n // The proof: a server-side implementation could not say this truthfully.\n ran_on: 'device',\n }),\n },\n {\n name: 'device.ping',\n description: 'Check that the device is reachable.',\n input_schema: { type: 'object', properties: {} },\n run: () => ({ ok: true, ran_on: 'device', at: new Date().toISOString() }),\n },\n ]);\n}\n","/**\n * Ambient device-tool registration, driven by the auth session (R14).\n *\n * The LOCAL reasoning path must be live BEFORE voice opens — otherwise the only\n * proof of a loadable external skill is a voice-triggered one. So the host wires\n * this to its EXISTING auth-session subscription (no new transport, no plugin\n * special-case): a tenant becoming authenticated loads that tenant's external\n * device-tool bundles (and re-ensures the static platform tools); a tenant\n * SWITCH is a change of tenant while still authenticated, so it clears the old\n * tenant's tools and reloads; sign-out resets the loader latch (the registry\n * itself is cleared by the host's logout teardown, which already calls\n * clearDeviceTools()).\n *\n * The decision is a PURE function so the lifecycle is testable without a network\n * or a device; the effects are injected (same DI shape as the host's logout\n * teardown) so a test drives them with fakes.\n */\nimport { registerPlatformDeviceTools } from './platformTools';\nimport { clearDeviceTools } from './registry';\n// NOTE: `./loader` pulls in the bundle manager (react-native, core), so it is\n// imported LAZILY inside the real effects below — keeping this module itself\n// node-testable (a test injects fake effects and never touches that graph).\n\nexport interface SessionSnapshot {\n authenticated: boolean;\n /** The tenant the session is scoped to (derive it; never a stored copy). */\n tenant: string | null;\n}\n\nexport type DeviceToolsAction = 'load' | 'reset' | 'none';\n\n/**\n * PURE: what should the device-tool registry do for this session transition?\n * - a new authenticated tenant (initial sign-in OR a switch) → 'load'\n * - the same authenticated tenant again (e.g. a silent token refresh) → 'none'\n * - leaving authenticated (sign-out) → 'reset'\n */\nexport function deviceToolsActionForSession(\n next: SessionSnapshot,\n prevTenant: string | null,\n): { action: DeviceToolsAction; tenant: string | null } {\n const tenant = next.authenticated ? (next.tenant ?? null) : null;\n if (tenant && tenant !== prevTenant) return { action: 'load', tenant };\n if (!tenant && prevTenant) return { action: 'reset', tenant: null };\n return { action: 'none', tenant: prevTenant };\n}\n\n/** The effects a session transition drives — injected so a test can fake them. */\nexport interface DeviceToolsSessionDeps {\n /** Drop the previous tenant's device tools (a switch does not run logout teardown). */\n clear: () => void;\n /** Ensure the static, host-owned platform device tools are present. */\n registerPlatform: () => void;\n /** Forget the \"already loaded\" latch so a later (non-forced) load runs — sign-out. */\n resetLoader: () => void;\n /** Fire-and-forget reload of the current tenant's external device-tool bundles. */\n load: () => void;\n}\n\nconst REAL_DEPS: DeviceToolsSessionDeps = {\n clear: clearDeviceTools,\n registerPlatform: registerPlatformDeviceTools,\n // `./loader` reaches react-native via the bundle manager; import it only when\n // an effect actually fires (real app), never at module load (tests).\n resetLoader: () => {\n void import('./loader').then((m) => m.resetDeviceToolLoader());\n },\n load: () => {\n void import('./loader').then((m) => {\n m.resetDeviceToolLoader();\n return m.ensureDeviceToolsLoaded({ force: true });\n });\n },\n};\n\nlet prevTenant: string | null = null;\n\n/**\n * Apply a session transition to the device-tool registry. Call from the host's\n * existing auth-session subscription with a derived snapshot. Idempotent per\n * tenant: repeated snapshots for the same authenticated tenant do nothing, so a\n * silent token refresh does not churn the registry. Returns the action taken.\n */\nexport function syncDeviceToolsForSession(\n next: SessionSnapshot,\n deps: DeviceToolsSessionDeps = REAL_DEPS,\n): DeviceToolsAction {\n const { action, tenant } = deviceToolsActionForSession(next, prevTenant);\n prevTenant = tenant;\n if (action === 'load') {\n // A new authenticated tenant: drop the prior tenant's tools, re-seat the\n // static platform tools, then reload this tenant's external bundles (forced).\n deps.clear();\n deps.registerPlatform();\n deps.load();\n } else if (action === 'reset') {\n // Sign-out: the host's logout teardown clears the registry; we only forget\n // the loader latch so a later sign-in reloads.\n deps.resetLoader();\n }\n return action;\n}\n\n/** Test seam: forget the last-seen tenant so a test starts from signed-out. */\nexport function __resetSessionSyncForTest(): void {\n prevTenant = null;\n}\n","/**\n * Device tools called BY THE SERVER.\n *\n * Two callers reach the same registered function on this phone:\n *\n * - the voice loop, which already runs here (no server hop at all), and\n * - the server reasoning loop, which cannot execute a device tool itself and\n * sends it down the client's stream instead.\n *\n * This is the second one. It rides the transport the `ui.*` plugin commands\n * already use — a command arrives on the job/actor stream, we run it, and post\n * the outcome back keyed by `correlationId`. Nothing new was invented; the\n * payload just carries a tool call instead of a UI command.\n *\n * The host wires this once at startup:\n *\n * pluginCommandEmitter.on('plugin-command', handleServerDeviceToolCall);\n */\nimport { callDeviceTool } from './registry';\nimport { ensureDeviceToolsLoaded } from './loader';\n\ntype PostResult = (correlationId: string, result: any, error?: string) => Promise<void>;\n\nlet postResult: PostResult | null = null;\n\n/**\n * Host DI: how to answer the server. `@ateam-ai-mobile/core` supplies\n * postCommandResult; kept injectable so this package stays free of the REST\n * client and so tests can observe the answer.\n */\nexport function setDeviceToolResultPoster(fn: PostResult): void {\n postResult = fn;\n}\n\n/** Is this stream command a device tool call? */\nexport function isDeviceToolCommand(cmd: any): boolean {\n return !!cmd && cmd.kind === 'device_tool' && typeof cmd.tool === 'string' && !!cmd.correlationId;\n}\n\n/**\n * Run a server-dispatched device tool and answer.\n *\n * Never throws — the server is blocked on the correlationId, so the one thing\n * we must not do is stay silent. Every path posts something back.\n */\nexport async function handleServerDeviceToolCall(cmd: any): Promise<void> {\n if (!isDeviceToolCommand(cmd)) return;\n\n const { tool, args, correlationId } = cmd;\n\n if (!postResult) {\n console.warn('[deviceTools] server called a tool but no result poster is installed');\n return;\n }\n\n try {\n // The server may reach us before anything opened a voice call, so the\n // plugins may not be loaded yet. Cheap and idempotent once warm.\n await ensureDeviceToolsLoaded();\n\n const outcome = await callDeviceTool(tool, args || {});\n console.log(`[deviceTools] server-called ${tool} → ${outcome.ok ? 'ok' : outcome.reason}`);\n\n await postResult(\n correlationId,\n outcome.ok ? { ok: true, ...unwrap(outcome.result) } : undefined,\n outcome.ok ? undefined : outcome.error,\n );\n } catch (err: any) {\n await postResult(correlationId, undefined, err?.message || String(err)).catch(() => {});\n }\n}\n\n/** Keep an object result flat for the reasoning loop; wrap anything else. */\nfunction unwrap(result: any): Record<string, any> {\n if (result && typeof result === 'object' && !Array.isArray(result)) return result;\n return { result };\n}\n","/**\n * usePlugin — single hook for loading any plugin.\n *\n * Simple async load → done pattern over the global BundleManager singleton\n * (deduplication + caching) and the host's native plugin registry.\n *\n * Usage:\n * const { plugin, loading, error } = usePlugin(pluginId, manifest);\n * if (loading) return <Spinner />;\n * if (error) return <Error message={error} />;\n * return <plugin.Component bridge={bridge} device={device} theme={theme} context={context} />;\n */\nimport { useState, useEffect } from 'react';\nimport { bundleManager } from '../bundles/bundleManager';\nimport { nativePluginRegistry } from '../host';\nimport { resolvePluginGrants } from '../pluginRuntime';\nimport type { NativeCapabilities, RegisteredUIPlugin } from '../sdk/types';\nimport type { DeviceBridgeDomain } from '../sdk/device-state';\nimport { pluginBundleUrl } from '../bundles/bundleUrl';\n\ninterface PluginManifestLike {\n version?: string;\n name?: string;\n render?: any;\n _connectorId?: string;\n capabilities?: Record<string, unknown>;\n native?: NativeCapabilities;\n stateDomains?: DeviceBridgeDomain[];\n}\n\ninterface UsePluginResult {\n plugin: RegisteredUIPlugin | null;\n loading: boolean;\n error: string | null;\n bundleMissing: boolean;\n}\n\n/**\n * Compute the bundle URL.\n *\n * **Policy:** bundle URLs are ALWAYS derived from the pluginId via the\n * canonical platform route /api/ui-plugins/{pluginId}/bundle.js.\n * Connector-supplied bundleUrl fields are IGNORED — the Builder strips them\n * at introspection time, but we treat any survivors as bugs and ignore them\n * here too (defense in depth vs \"hand-coded URL with bad encoding causes\n * silent iframe fallback\" bugs).\n */\ntype BundleUrlSource = 'derived-default' | 'ignored-explicit' | 'none';\nfunction extractBundleUrl(pluginId: string, manifest: PluginManifestLike): { url: string | null; source: BundleUrlSource; ignored?: string } {\n const render = manifest.render;\n if (!render || typeof render !== 'object') return { url: null, source: 'none' };\n\n // Detect (and refuse) any explicit bundle URL the connector tried to inject.\n const injected =\n (manifest as any).bundleUrl ||\n (render as any).bundleUrl ||\n render.reactNative?.bundleUrl ||\n null;\n\n // Mobile decides native vs web INDEPENDENT of render.mode. The server's\n // cp.getContextPlugin flattens mode to \"iframe\" whenever an iframeUrl is\n // available (for web-frontend compatibility) — even when a reactNative\n // component is also declared. So we derive the bundle URL whenever a\n // reactNative component is present, regardless of what `mode` says.\n const hasNativeComponent = !!(render.reactNative?.component || render.component);\n if (hasNativeComponent) {\n return {\n url: pluginBundleUrl(pluginId),\n source: injected ? 'ignored-explicit' : 'derived-default',\n ...(injected && { ignored: injected }),\n };\n }\n\n return { url: null, source: 'none' };\n}\n\n/**\n * Extract the SHA-256 integrity hash from the manifest (server-provided).\n * BundleManager refuses to evaluate a downloaded bundle whose bytes don't\n * hash to this value — defense vs MITM/CDN tampering.\n */\nfunction extractBundleHash(manifest: PluginManifestLike): string | undefined {\n if ((manifest as any).bundleHash) return (manifest as any).bundleHash;\n const render = manifest.render;\n if (!render || typeof render !== 'object') return undefined;\n if (render.bundleHash) return render.bundleHash;\n if (render.reactNative?.bundleHash) return render.reactNative.bundleHash;\n return undefined;\n}\n\n/**\n * Extract component name from manifest render field.\n */\nfunction extractComponentId(manifest: PluginManifestLike): string | null {\n const render = manifest.render;\n if (!render || typeof render !== 'object') return null;\n return render.component || render.reactNative?.component || null;\n}\n\nexport function usePlugin(pluginId: string, manifest: PluginManifestLike): UsePluginResult {\n const [plugin, setPlugin] = useState<RegisteredUIPlugin | null>(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n const [bundleMissing, setBundleMissing] = useState(false);\n\n const version = manifest.version || '1.0.0';\n const { url: bundleUrl, ignored: ignoredUrl } = extractBundleUrl(pluginId, manifest);\n const bundleHash = extractBundleHash(manifest);\n const componentId = extractComponentId(manifest);\n const lookupId = componentId || pluginId;\n // The manifest's grants — the authority for the bundle's device tools, the\n // same one the renderer gates the component with. Keyed by value so a fresh\n // manifest object with the same grants does not reload the plugin.\n const grants = resolvePluginGrants({ pluginId, manifest });\n const grantsKey = JSON.stringify(grants);\n\n if (ignoredUrl) {\n console.warn(`[usePlugin] ${pluginId}: IGNORED connector-injected bundleUrl=\"${ignoredUrl}\". The host derives bundle URLs from pluginId via the canonical route.`);\n }\n\n useEffect(() => {\n let cancelled = false;\n\n (async () => {\n try {\n // Path 1: Local registry (host-bundled / dev plugins)\n if (nativePluginRegistry.has(lookupId)) {\n const registered = await nativePluginRegistry.get(lookupId);\n if (cancelled) return;\n\n if (!registered) {\n throw new Error(`Local plugin not found: ${lookupId}`);\n }\n if (registered.type === 'service') {\n throw new Error(`Plugin ${lookupId} is a service plugin and cannot be rendered`);\n }\n\n setPlugin(registered as RegisteredUIPlugin);\n setLoading(false);\n return;\n }\n\n // Path 2: Remote bundle (via global BundleManager)\n if (bundleUrl) {\n try {\n const component = await bundleManager.load(pluginId, bundleUrl, version, bundleHash, grants);\n if (cancelled) return;\n setPlugin(component);\n setLoading(false);\n return;\n } catch (bundleErr) {\n const msg = bundleErr instanceof Error ? bundleErr.message : String(bundleErr);\n // warn (not error) — this is a handled path: we fall back to WebView.\n console.warn(`[usePlugin] ${pluginId}: Bundle load failed, falling back to WebView:`, msg);\n // RN bundle failed — connector declared a component but didn't\n // ship a usable bundle (404, eval error, integrity fail, etc).\n // Mark \"bundle missing\" so the parent renderer can fall back to\n // the WebView/iframe when the manifest also has an iframeUrl.\n if (!cancelled) {\n setBundleMissing(true);\n setLoading(false);\n }\n return;\n }\n }\n\n // No native source available. If the manifest also has an iframeUrl,\n // mark \"bundle missing\" so the parent falls back to the WebView.\n // Only throw when there's truly nothing renderable.\n const iframeUrl = manifest?.render?.iframeUrl\n || (manifest?.render?.mode === 'adaptive' && manifest?.render?.iframe?.iframeUrl);\n if (iframeUrl) {\n if (!cancelled) {\n setBundleMissing(true);\n setLoading(false);\n }\n return;\n }\n throw new Error(\n `Plugin \"${manifest.name || pluginId}\" has no bundle URL and is not in the local registry. ` +\n `Check that the solution definition includes a valid render.reactNative.bundleUrl.`\n );\n } catch (err) {\n if (cancelled) return;\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`[usePlugin] Failed to load ${pluginId}:`, msg);\n setError(msg);\n setLoading(false);\n }\n })();\n\n return () => { cancelled = true; };\n }, [pluginId, lookupId, bundleUrl, bundleHash, version, grantsKey]);\n\n return { plugin, loading, error, bundleMissing };\n}\n","import { useEffect, useState, useCallback } from 'react';\nimport { apiFetch } from '@ateam-ai-mobile/core';\nimport type { PluginManifest } from '../sdk/types';\n\nexport interface RemotePlugin {\n id: string;\n name: string;\n version: string;\n manifest: PluginManifest;\n source: 'remote' | 'local'; // Where this plugin came from\n}\n\ninterface UseRemotePluginsResult {\n plugins: RemotePlugin[];\n loading: boolean;\n error: string | null;\n refreshing: boolean;\n refresh: () => Promise<void>;\n}\n\n/**\n * Fetches available UI plugins from A-Team Core for the current solution.\n * Uses apiFetch which auto-injects JWT + tenant headers.\n */\nexport function useRemotePlugins(solutionId?: string): UseRemotePluginsResult {\n const [plugins, setPlugins] = useState<RemotePlugin[]>([]);\n const [loading, setLoading] = useState(true);\n const [refreshing, setRefreshing] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const fetchRemotePlugins = useCallback(async () => {\n try {\n setError(null);\n\n const targetSolutionId = solutionId || 'current';\n\n let data: any;\n try {\n data = await apiFetch<any>(`/api/solutions/${targetSolutionId}/ui-plugins`);\n } catch (err: any) {\n if (err?.message?.includes('404')) {\n console.warn(`[useRemotePlugins] Solution ${targetSolutionId} not found or has no plugins`);\n setPlugins([]);\n return;\n }\n throw err;\n }\n const uiPlugins: RemotePlugin[] = (data.plugins || []).map((plugin: any) => ({\n id: plugin.id,\n name: plugin.name,\n version: plugin.version || '1.0.0',\n source: 'remote' as const,\n manifest: {\n id: plugin.id,\n name: plugin.name,\n version: plugin.version || '1.0.0',\n type: 'ui',\n description: plugin.description || '',\n capabilities: plugin.capabilities || {},\n channels: plugin.channels || ['default'],\n render: (plugin.render && typeof plugin.render === 'object') ? plugin.render : { mode: 'react-native' as const, component: plugin.name || plugin.id },\n entry_point: plugin.entry_point || plugin.name,\n sandbox: plugin.sandbox !== false,\n requires_auth: plugin.requires_auth !== false,\n } as PluginManifest,\n }));\n\n setPlugins(uiPlugins);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.error('[useRemotePlugins] Failed to fetch plugins:', message);\n setError(message);\n setPlugins([]); // Clear plugins on error\n } finally {\n setLoading(false);\n setRefreshing(false);\n }\n }, [solutionId]);\n\n const refresh = useCallback(async () => {\n setRefreshing(true);\n await fetchRemotePlugins();\n }, [fetchRemotePlugins]);\n\n useEffect(() => {\n setLoading(true);\n fetchRemotePlugins();\n }, [fetchRemotePlugins]);\n\n return {\n plugins,\n loading,\n error,\n refreshing,\n refresh,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,IAAM,qBAAqB;AAEpB,SAAS,8BAAoC;AAClD,sBAAoB,oBAAoB;AAAA,IACtC;AAAA,MACE,MAAM;AAAA,MACN,aAAa;AAAA,MACb,cAAc;AAAA,QACZ,MAAM;AAAA,QACN,YAAY,EAAE,MAAM,EAAE,MAAM,SAAS,EAAE;AAAA,QACvC,UAAU,CAAC,MAAM;AAAA,MACnB;AAAA,MACA,KAAK,CAAC,UAAe;AAAA,QACnB,IAAI;AAAA,QACJ,QAAS,QAAQ,KAAK,QAAS;AAAA;AAAA,QAE/B,QAAQ;AAAA,MACV;AAAA,IACF;AAAA,IACA;AAAA,MACE,MAAM;AAAA,MACN,aAAa;AAAA,MACb,cAAc,EAAE,MAAM,UAAU,YAAY,CAAC,EAAE;AAAA,MAC/C,KAAK,OAAO,EAAE,IAAI,MAAM,QAAQ,UAAU,KAAI,oBAAI,KAAK,GAAE,YAAY,EAAE;AAAA,IACzE;AAAA,EACF,CAAC;AACH;;;ACHO,SAAS,4BACd,MACAA,aACsD;AACtD,QAAM,SAAS,KAAK,gBAAiB,KAAK,UAAU,OAAQ;AAC5D,MAAI,UAAU,WAAWA,YAAY,QAAO,EAAE,QAAQ,QAAQ,OAAO;AACrE,MAAI,CAAC,UAAUA,YAAY,QAAO,EAAE,QAAQ,SAAS,QAAQ,KAAK;AAClE,SAAO,EAAE,Q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AU,YAAY,YAAY;AACtC,kBAAc,IAAI;AAClB,UAAM,mBAAmB;AAAA,EAC3B,GAAG,CAAC,kBAAkB,CAAC;AAEvB,EAAAD,WAAU,MAAM;AACd,eAAW,IAAI;AACf,uBAAmB;AAAA,EACrB,GAAG,CAAC,kBAAkB,CAAC;AAEvB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["prevTenant","useEffect","useState"]}
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  ensureDeviceToolsLoaded,
3
3
  resetDeviceToolLoader
4
- } from "./chunk-PKDQLNBL.mjs";
4
+ } from "./chunk-SICFDA5K.mjs";
5
5
  export {
6
6
  ensureDeviceToolsLoaded,
7
7
  resetDeviceToolLoader
8
8
  };
9
- //# sourceMappingURL=loader-5LUVXUY2.mjs.map
9
+ //# sourceMappingURL=loader-MSZ4PVTO.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ateam-ai-mobile/plugin-runtime",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "ADAS plugin runtime for React Native hosts — plugin SDK, bundle pipeline with integrity verification, host bridge, surfaces. No Expo dependencies.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -9,7 +9,7 @@
9
9
  "build": "tsup"
10
10
  },
11
11
  "dependencies": {
12
- "@ateam-ai-mobile/core": "0.1.7",
12
+ "@ateam-ai-mobile/core": "0.1.9",
13
13
  "zustand": "^5.0.0"
14
14
  },
15
15
  "peerDependencies": {
@@ -1,5 +1,6 @@
1
1
  import { apiFetch } from '@ateam-ai-mobile/core';
2
2
  import { getCoreApiUrl } from '@ateam-ai-mobile/core';
3
+ import { pluginBundleUrl } from '../bundles/bundleUrl';
3
4
 
4
5
  /**
5
6
  * Summary returned by cp.listContextPlugins — no `render` field.
@@ -103,18 +104,23 @@ export function getNativeComponentId(manifest: PluginManifest): string | null {
103
104
  }
104
105
 
105
106
  /**
106
- * Get the native bundle URL from a manifest (if it has native support).
107
+ * The native bundle URL for a manifest that has a bundle on the server, or null.
108
+ *
109
+ * Core writes `bundleUrl` into the manifest only when the connector's bundle
110
+ * exists, so its PRESENCE says "there is a bundle". Its SPELLING is not used:
111
+ * Core writes the id unencoded, and a connector could inject any URL. The URL
112
+ * returned is always the one derivation, pluginBundleUrl(manifest.id), the same
113
+ * one the rendered surface uses. Returning the manifest's own string (6294cc3)
114
+ * gave the device-tool loader a second spelling, so one plugin downloaded and
115
+ * evaluated twice, as two module instances (MGAP-C8).
107
116
  */
108
117
  export function getNativeBundleUrl(manifest: PluginManifest): string | null {
109
- // Check direct bundleUrl on manifest or within render structure
110
- const direct = (manifest as any).bundleUrl;
111
- if (direct) return direct;
112
-
113
118
  const render = manifest.render;
114
- if (render.mode === 'react-native') return render.bundleUrl || null;
115
- if (render.mode === 'adaptive') return render.reactNative?.bundleUrl || null;
116
-
117
- return null;
119
+ const declared =
120
+ (manifest as any).bundleUrl ||
121
+ (render?.mode === 'react-native' ? render.bundleUrl : null) ||
122
+ (render?.mode === 'adaptive' ? render.reactNative?.bundleUrl : null);
123
+ return declared && manifest.id ? pluginBundleUrl(manifest.id) : null;
118
124
  }
119
125
 
120
126
  /**