@ateam-ai-mobile/plugin-runtime 0.1.8 → 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/{chunk-RXR6M623.mjs → chunk-SICFDA5K.mjs} +121 -15
- package/dist/chunk-SICFDA5K.mjs.map +1 -0
- package/dist/index.d.mts +114 -18
- package/dist/index.d.ts +114 -18
- package/dist/index.js +142 -70
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +10 -59
- package/dist/index.mjs.map +1 -1
- package/dist/{loader-UUOPZQSI.mjs → loader-MSZ4PVTO.mjs} +2 -2
- package/package.json +2 -2
- package/src/api/plugins.ts +15 -9
- package/src/bundles/bundleManager.ts +28 -9
- package/src/bundles/bundleModuleNames.ts +52 -0
- package/src/bundles/bundleUrl.ts +41 -0
- package/src/bundles/storage.ts +52 -0
- package/src/hooks/usePlugin.ts +2 -1
- package/src/index.ts +10 -36
- package/src/sdk/CameraPreview.tsx +7 -0
- package/src/sdk/device-state.ts +20 -7
- package/src/sdk/index.ts +34 -0
- package/src/sdk/types.ts +13 -0
- package/src/sdk/voice.ts +48 -4
- package/src/tools/loader.ts +4 -2
- package/src/tools/registry.ts +2 -2
- package/dist/chunk-RXR6M623.mjs.map +0 -1
- /package/dist/{loader-UUOPZQSI.mjs.map → loader-MSZ4PVTO.mjs.map} +0 -0
package/dist/index.mjs
CHANGED
|
@@ -33,12 +33,13 @@ 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,
|
|
44
45
|
gateVoice,
|
|
@@ -52,11 +53,14 @@ import {
|
|
|
52
53
|
hasDeviceTool,
|
|
53
54
|
implementedStateDomains,
|
|
54
55
|
implementedVoice,
|
|
56
|
+
isActionable,
|
|
55
57
|
isInlineSurface,
|
|
56
58
|
isMountSurface,
|
|
57
59
|
listDeviceTools,
|
|
58
60
|
listPlugins,
|
|
59
61
|
nativePluginRegistry,
|
|
62
|
+
neverObserved,
|
|
63
|
+
pluginBundleUrl,
|
|
60
64
|
register,
|
|
61
65
|
registerBundleModules,
|
|
62
66
|
registerDeviceTools,
|
|
@@ -83,61 +87,7 @@ import {
|
|
|
83
87
|
useNativeBridge,
|
|
84
88
|
usePluginTheme,
|
|
85
89
|
useSurfaceStore
|
|
86
|
-
} from "./chunk-
|
|
87
|
-
|
|
88
|
-
// src/sdk/device-state.ts
|
|
89
|
-
var device_state_exports = {};
|
|
90
|
-
__export(device_state_exports, {
|
|
91
|
-
DeviceBridgeError: () => DeviceBridgeError,
|
|
92
|
-
explainCapability: () => explainCapability,
|
|
93
|
-
isActionable: () => isActionable,
|
|
94
|
-
neverObserved: () => neverObserved
|
|
95
|
-
});
|
|
96
|
-
var DeviceBridgeError = class extends Error {
|
|
97
|
-
constructor(code, message, opts) {
|
|
98
|
-
super(message);
|
|
99
|
-
this.name = "DeviceBridgeError";
|
|
100
|
-
this.code = code;
|
|
101
|
-
this.domain = opts?.domain;
|
|
102
|
-
this.recoverable = opts?.recoverable;
|
|
103
|
-
}
|
|
104
|
-
};
|
|
105
|
-
var CONFIDENCE_ORDER = {
|
|
106
|
-
unknown: 0,
|
|
107
|
-
low: 1,
|
|
108
|
-
medium: 2,
|
|
109
|
-
high: 3
|
|
110
|
-
};
|
|
111
|
-
function isActionable(quality, budget) {
|
|
112
|
-
const { freshness, confidence } = quality;
|
|
113
|
-
if (freshness.state === "unknown" || freshness.state === "stale") return false;
|
|
114
|
-
if (freshness.ageMs === null || freshness.ageMs > budget.maxAgeMs) return false;
|
|
115
|
-
if (budget.minConfidence) {
|
|
116
|
-
const have = CONFIDENCE_ORDER[confidence?.level ?? "unknown"];
|
|
117
|
-
if (have < CONFIDENCE_ORDER[budget.minConfidence]) return false;
|
|
118
|
-
}
|
|
119
|
-
return true;
|
|
120
|
-
}
|
|
121
|
-
function neverObserved() {
|
|
122
|
-
return { state: "unknown", observedAt: null, ageMs: null };
|
|
123
|
-
}
|
|
124
|
-
function explainCapability(status) {
|
|
125
|
-
if (status.support === "unsupported") return "this device does not have it";
|
|
126
|
-
if (status.permission === "denied") return "permission was denied";
|
|
127
|
-
if (status.permission === "restricted") return "permission is restricted";
|
|
128
|
-
if (status.permission === "notDetermined") return "permission has not been asked for yet";
|
|
129
|
-
if (status.permission === "limited") return "only limited access was granted";
|
|
130
|
-
if (status.restriction === "policyRestricted") return "this plugin did not declare it";
|
|
131
|
-
if (status.restriction === "backgroundRestricted") return "the app is in the background";
|
|
132
|
-
if (status.restriction === "lowPowerRestricted") return "the device is in low-power mode";
|
|
133
|
-
if (status.availability === "busy") return "it is in use by something else";
|
|
134
|
-
if (status.availability === "temporarilyUnavailable") return "it is temporarily unavailable";
|
|
135
|
-
if (status.availability === "unavailable") return "it is unavailable";
|
|
136
|
-
if (status.support === "unknown" || status.availability === "unknown") {
|
|
137
|
-
return "its state could not be determined";
|
|
138
|
-
}
|
|
139
|
-
return null;
|
|
140
|
-
}
|
|
90
|
+
} from "./chunk-SICFDA5K.mjs";
|
|
141
91
|
|
|
142
92
|
// src/tools/platformTools.ts
|
|
143
93
|
var PLATFORM_PLUGIN_ID = "platform:device-tools";
|
|
@@ -180,10 +130,10 @@ var REAL_DEPS = {
|
|
|
180
130
|
// `./loader` reaches react-native via the bundle manager; import it only when
|
|
181
131
|
// an effect actually fires (real app), never at module load (tests).
|
|
182
132
|
resetLoader: () => {
|
|
183
|
-
void import("./loader-
|
|
133
|
+
void import("./loader-MSZ4PVTO.mjs").then((m) => m.resetDeviceToolLoader());
|
|
184
134
|
},
|
|
185
135
|
load: () => {
|
|
186
|
-
void import("./loader-
|
|
136
|
+
void import("./loader-MSZ4PVTO.mjs").then((m) => {
|
|
187
137
|
m.resetDeviceToolLoader();
|
|
188
138
|
return m.ensureDeviceToolsLoaded({ force: true });
|
|
189
139
|
});
|
|
@@ -249,7 +199,7 @@ function extractBundleUrl(pluginId, manifest) {
|
|
|
249
199
|
const hasNativeComponent = !!(render.reactNative?.component || render.component);
|
|
250
200
|
if (hasNativeComponent) {
|
|
251
201
|
return {
|
|
252
|
-
url:
|
|
202
|
+
url: pluginBundleUrl(pluginId),
|
|
253
203
|
source: injected ? "ignored-explicit" : "derived-default",
|
|
254
204
|
...injected && { ignored: injected }
|
|
255
205
|
};
|
|
@@ -479,6 +429,7 @@ export {
|
|
|
479
429
|
listPlugins,
|
|
480
430
|
nativePluginRegistry,
|
|
481
431
|
neverObserved,
|
|
432
|
+
pluginBundleUrl,
|
|
482
433
|
register,
|
|
483
434
|
registerBundleModules,
|
|
484
435
|
registerDeviceTools,
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sdk/device-state.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 `capabilities: { camera: true }`\n * (the legacy `native: {}` field is still honoured).\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, TPayload = unknown> {\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. Defaults to `unknown` rather than `any` so a consumer is forced\n * to narrow it rather than read a field that may not exist. A domain that\n * decides its schemas (spatial — see `SpatialStateEvent`) passes `TPayload`,\n * which is the freeze's own second parameter, dropped here until one did.\n */\n payload?: TPayload;\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 — except where a DECISION closes\n * it (spatial, see `SpatialEvent`), and that list is checked against the rule\n * through `AssertConforming`.\n */\nexport type ConformingEventName =\n | `${string}Changed`\n | `${string}Started`\n | `${string}Stopped`\n | `${string}Available`\n | `${string}Unavailable`\n | `${string}StateStale`;\n\n/**\n * A closed list of names, checked against the naming rule at compile time.\n * Wrap a decided vocabulary in this and a name like `turnCompleted` stops\n * compiling instead of reaching a plugin.\n */\nexport type AssertConforming<T extends ConformingEventName> = T;\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\n/**\n * DECISION (not frozen) — the spatial event vocabulary. Six names, all ending\n * in a suffix the naming rule allows, which `AssertConforming` enforces.\n *\n * Drawn from the architecture doc's spatial candidates (meaningful movement,\n * meaningful turn, location quality degraded/recovered, state became stale)\n * and named after the SNAPSHOT fields they report, so an event and a read use\n * one vocabulary: `lastMeaningfulTurnChanged` is `changes.lastMeaningfulTurnDeg`\n * changing. The names an earlier note floated (`turnCompleted`, `arrived`,\n * `headingLost`) are rejected — the first two fail the rule, and \"arrived\" is a\n * destination, which the vocabulary's Governance puts above Device Bridge.\n */\nexport type SpatialEvent = AssertConforming<\n | 'movementStarted'\n | 'movementStopped'\n | 'lastMeaningfulTurnChanged'\n | 'positionConfidenceChanged'\n | 'positionChanged'\n | 'spatialStateStale'\n>;\n\n/** A spatial event: the frozen envelope, with its payload always present. */\ntype SpatialEventOf<TName extends SpatialEvent, TPayload> =\n StateEvent<TName, TPayload> & { domain: 'spatial'; payload: TPayload };\n\n/**\n * DECISION — what each spatial event carries. Only the facts of the\n * transition, in the snapshot's own field names; everything else is one\n * `getSnapshot()` away, which keeps two shapes of the same fact from drifting.\n *\n * `timestamp` on the envelope is when the transition was RECOGNISED. Where a\n * hold delays that on purpose, `since` carries the true onset.\n */\nexport type SpatialStateEvent =\n /** `movement.state` became `moving` and held (navigation: 3 s). */\n | SpatialEventOf<'movementStarted', {\n previous: 'stationary' | 'unknown';\n speedMps: number | null;\n bearingDeg: number | null;\n since: number;\n }>\n /** `moving` → `stationary`, held (navigation: 5 s). Never fired on moving →\n * `unknown`: losing the speed is not evidence of stopping. */\n | SpatialEventOf<'movementStopped', { previous: 'moving'; since: number }>\n /** A new completed turn. Signed: positive = clockwise = right. */\n | SpatialEventOf<'lastMeaningfulTurnChanged', { lastMeaningfulTurnDeg: number; timestamp: number }>\n /** The GPS fix band (high ≤10 m, medium ≤50 m, else low) changed and held.\n * The fix alone — a compass calibration change is not a position event. */\n | SpatialEventOf<'positionConfidenceChanged', {\n level: ConfidenceLevel;\n previous: ConfidenceLevel;\n accuracyM: number | null;\n direction: 'dropped' | 'recovered';\n }>\n /** Moved at least max(profile floor, 2 × accuracyM) from the last reported\n * position, so GPS jitter never fires it. The session's first fix fires\n * with `previous: null`. */\n | SpatialEventOf<'positionChanged', {\n position: SpatialPoint;\n previous: SpatialPoint | null;\n distanceM: number | null;\n }>\n /** `quality.freshness.state` became `stale`. Once; re-armed by a fresh read. */\n | SpatialEventOf<'spatialStateStale', { observedAt: number | null; ageMs: number | null }>;\n\nexport interface SpatialDomain {\n getSnapshot(): Promise<SpatialSnapshot>;\n start(options: StartOptions<SpatialIntent>): Promise<StateSession>;\n stop(sessionId?: string): Promise<void>;\n /**\n * DECISION: the six `SpatialEvent`s, typed per name — narrow on `e.name` and\n * `e.payload` is that event's shape.\n *\n * Events flow only while a spatial session is open; subscribing opens no\n * sensor. They are derived from the same snapshot `getSnapshot()` returns: a\n * listener that re-reads inside the callback sees the snapshot its event came\n * from. A state change must hold, on at least two fixes, before it fires.\n *\n * From a device tool's `ctx.deviceState` this refuses (RESTRICTED): a call\n * has no lifetime to own the listener.\n */\n subscribe(listener: (event: SpatialStateEvent) => void): 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, deviceContext. (Spatial's is a\n * DECISION, recorded at `SpatialEvent`, not a reading of the docs.)\n * - Per-event payload schemas for every domain but spatial\n * (`SpatialStateEvent`, likewise a DECISION).\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 * 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';\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: `/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 // 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmPO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAM3C,YACE,MACA,SACA,MACA;AACA,UAAM,OAAO;AAC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AC3B,QAAQ;AAAA,QACR,UAAU;AAAA,UACR,IAAI,OAAO;AAAA,UACX,MAAM,OAAO;AAAA,UACb,SAAS,OAAO,WAAW;AAAA,UAC3B,MAAM;AAAA,UACN,aAAa,OAAO,eAAe;AAAA,UACnC,cAAc,OAAO,gBAAgB,CAAC;AAAA,UACtC,UAAU,OAAO,YAAY,CAAC,SAAS;AAAA,UACvC,QAAS,OAAO,UAAU,OAAO,OAAO,WAAW,WAAY,OAAO,SAAS,EAAE,MAAM,gBAAyB,WAAW,OAAO,QAAQ,OAAO,GAAG;AAAA,UACpJ,aAAa,OAAO,eAAe,OAAO;AAAA,UAC1C,SAAS,OAAO,YAAY;AAAA,UAC5B,eAAe,OAAO,kBAAkB;AAAA,QAC1C;AAAA,MACF,EAAE;AAEF,iBAAW,SAAS;AAAA,IACtB,SAAS,KAAK;AACZ,YAAM,UAAU,eAAe,QAAQ,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,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YAAY,CAAC,SAAS;AAAA,UACvC,QAAS,OAAO,UAAU,OAAO,OAAO,WAAW,WAAY,OAAO,SAAS,EAAE,MAAM,gBAAyB,WAAW,OAAO,QAAQ,OAAO,GAAG;AAAA,UACpJ,aAAa,OAAO,eAAe,OAAO;AAAA,UAC1C,SAAS,OAAO,YAAY;AAAA,UAC5B,eAAe,OAAO,kBAAkB;AAAA,QAC1C;AAAA,MACF,EAAE;AAEF,iBAAW,SAAS;AAAA,IACtB,SAAS,KAAK;AACZ,YAAM,UAAU,eAAe,QAAQ,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,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ensureDeviceToolsLoaded,
|
|
3
3
|
resetDeviceToolLoader
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-SICFDA5K.mjs";
|
|
5
5
|
export {
|
|
6
6
|
ensureDeviceToolsLoaded,
|
|
7
7
|
resetDeviceToolLoader
|
|
8
8
|
};
|
|
9
|
-
//# sourceMappingURL=loader-
|
|
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.
|
|
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.
|
|
12
|
+
"@ateam-ai-mobile/core": "0.1.9",
|
|
13
13
|
"zustand": "^5.0.0"
|
|
14
14
|
},
|
|
15
15
|
"peerDependencies": {
|
package/src/api/plugins.ts
CHANGED
|
@@ -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
|
-
*
|
|
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
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
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
|
/**
|
|
@@ -23,9 +23,19 @@ import SurfaceFullscreen from '../surfaces/SurfaceFullscreen';
|
|
|
23
23
|
import { useSurfaceStore } from '../registry/store';
|
|
24
24
|
import SurfaceDispatcher from '../registry/SurfaceDispatcher';
|
|
25
25
|
import { resolveBundleModule } from '../host';
|
|
26
|
+
import { PLUGIN_SDK_MODULE, sdkModuleRefusal } from './bundleModuleNames';
|
|
26
27
|
import { sha256Hex } from '../utils/sha256';
|
|
27
28
|
import { assertBundleIntegrity } from './integrity';
|
|
28
|
-
import { getBundleStorage, type BundleCacheEntry, type TrustedToolDeclaration } from './storage';
|
|
29
|
+
import { getBundleStorage, loadCacheIndex, type BundleCacheEntry, type TrustedToolDeclaration } from './storage';
|
|
30
|
+
import { pluginBundleUrl, isPluginBundleUrl } from './bundleUrl';
|
|
31
|
+
|
|
32
|
+
/** The key a plugin's bundle is held under: its ONE canonical URL whenever the
|
|
33
|
+
* URL given is that plugin's route in any spelling (MGAP-C8). Any other URL is
|
|
34
|
+
* used as given. Every public load enters through this, so no caller, whichever
|
|
35
|
+
* spelling it holds, can make one plugin load twice. */
|
|
36
|
+
function bundleKey(pluginId: string, bundleUrl: string): string {
|
|
37
|
+
return isPluginBundleUrl(bundleUrl, pluginId) ? pluginBundleUrl(pluginId) : bundleUrl;
|
|
38
|
+
}
|
|
29
39
|
import { registerDeviceTools, unregisterDeviceTools, listDeviceTools } from '../tools/registry';
|
|
30
40
|
import type { PluginGrants } from '../pluginRuntime';
|
|
31
41
|
import type { RegisteredUIPlugin } from '../sdk/types';
|
|
@@ -35,7 +45,9 @@ import type { RegisteredUIPlugin } from '../sdk/types';
|
|
|
35
45
|
// so they emit require() calls that this shim resolves at runtime. Anything
|
|
36
46
|
// beyond the built-ins (react-native-webview, expo-linking, …) must be
|
|
37
47
|
// registered by the host via registerBundleModules() — the host is the one
|
|
38
|
-
// that actually has those modules installed.
|
|
48
|
+
// that actually has those modules installed. Any other name in the SDK's own
|
|
49
|
+
// namespaces ('@ateam-ai-mobile/*', '@adas/*') fails the evaluation BY NAME —
|
|
50
|
+
// see bundleModuleNames.ts for why that, and only that, is not warn-and-{}.
|
|
39
51
|
|
|
40
52
|
const ReactShim: any = {
|
|
41
53
|
__esModule: true,
|
|
@@ -80,7 +92,9 @@ const PluginSDKShim = Object.freeze({
|
|
|
80
92
|
const requireShim = (name: string) => {
|
|
81
93
|
if (name === 'react') return ReactShim;
|
|
82
94
|
if (name === 'react-native') return ReactNative;
|
|
83
|
-
if (name ===
|
|
95
|
+
if (name === PLUGIN_SDK_MODULE) return PluginSDKShim;
|
|
96
|
+
const refusal = sdkModuleRefusal(name);
|
|
97
|
+
if (refusal) throw new Error(`[BundleManager] ${refusal}`);
|
|
84
98
|
const hostModule = resolveBundleModule(name);
|
|
85
99
|
if (hostModule !== undefined) return hostModule;
|
|
86
100
|
console.warn(`[BundleManager] Unknown module: ${name} — register it via registerBundleModules()`);
|
|
@@ -257,6 +271,7 @@ class BundleManager {
|
|
|
257
271
|
expectedHash?: string,
|
|
258
272
|
grants?: PluginGrants,
|
|
259
273
|
): Promise<RegisteredUIPlugin> {
|
|
274
|
+
bundleUrl = bundleKey(pluginId, bundleUrl);
|
|
260
275
|
// Tenant boundary FIRST — fail closed without a tenant, drop the previous
|
|
261
276
|
// tenant's modules on a switch, and CAPTURE the tenant + generation at entry
|
|
262
277
|
// so a switch during the async load is caught before any result is used.
|
|
@@ -336,6 +351,7 @@ class BundleManager {
|
|
|
336
351
|
if (!grants) {
|
|
337
352
|
throw new Error(`[BundleManager] loadTools(${pluginId}) needs the manifest's grants (resolvePluginGrants) — refusing to register tools on the bundle's own claim`);
|
|
338
353
|
}
|
|
354
|
+
bundleUrl = bundleKey(pluginId, bundleUrl);
|
|
339
355
|
// Tenant boundary FIRST — same fail-closed / drop-on-switch as load(), and
|
|
340
356
|
// capture the tenant + generation for the stale check after the async load.
|
|
341
357
|
const tenant = this.requireTenant();
|
|
@@ -430,11 +446,14 @@ class BundleManager {
|
|
|
430
446
|
*/
|
|
431
447
|
async clearPlugin(pluginId: string): Promise<void> {
|
|
432
448
|
const storage = getBundleStorage();
|
|
433
|
-
const index = await storage
|
|
434
|
-
|
|
449
|
+
const index = await loadCacheIndex(storage);
|
|
450
|
+
// The index is keyed by bundle URL (0ea266d4), so the plugin's entry is
|
|
451
|
+
// under its canonical URL, never under its id.
|
|
452
|
+
const bundleUrl = pluginBundleUrl(pluginId);
|
|
453
|
+
const entry = index[bundleUrl];
|
|
435
454
|
if (entry) {
|
|
436
|
-
this.modules.delete(
|
|
437
|
-
delete index[
|
|
455
|
+
this.modules.delete(bundleUrl);
|
|
456
|
+
delete index[bundleUrl];
|
|
438
457
|
await storage.saveIndex(index);
|
|
439
458
|
try {
|
|
440
459
|
await storage.deleteBundle(entry.localPath);
|
|
@@ -480,7 +499,7 @@ class BundleManager {
|
|
|
480
499
|
}
|
|
481
500
|
|
|
482
501
|
const storage = getBundleStorage();
|
|
483
|
-
const index = await storage
|
|
502
|
+
const index = await loadCacheIndex(storage);
|
|
484
503
|
const expectedLc = expectedHash ? expectedHash.toLowerCase() : null;
|
|
485
504
|
|
|
486
505
|
// Check disk cache. A cache hit is only valid when the cached SHA-256
|
|
@@ -681,7 +700,7 @@ class BundleManager {
|
|
|
681
700
|
if (this.recordedDeclarations.get(bundleUrl) === key) return;
|
|
682
701
|
try {
|
|
683
702
|
const storage = getBundleStorage();
|
|
684
|
-
const index = await storage
|
|
703
|
+
const index = await loadCacheIndex(storage);
|
|
685
704
|
const entry = index[bundleUrl];
|
|
686
705
|
const running = this.provenance.get(bundleUrl)?.hash;
|
|
687
706
|
if (!entry || entry.tenant !== tenant || !running || entry.bundleHash?.toLowerCase() !== running) return;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SDK's module names, as a remote bundle sees them.
|
|
3
|
+
*
|
|
4
|
+
* A bundle keeps its SDK external, and the require shim (bundleManager) answers
|
|
5
|
+
* exactly ONE SDK name: '@adas/plugin-sdk'. The same code is published to npm as
|
|
6
|
+
* '@ateam-ai-mobile/plugin-runtime' — but that is the HOST app's dependency, and
|
|
7
|
+
* inside a bundle it resolves to nothing.
|
|
8
|
+
*
|
|
9
|
+
* Until MGAP-C2 (2026-09-27) the shim answered that name the way it answers any
|
|
10
|
+
* unknown module: a console warning and `{}`. So a bundle doing
|
|
11
|
+
* `import { CameraPreview } from '@ateam-ai-mobile/plugin-runtime'` evaluated
|
|
12
|
+
* cleanly, got `undefined`, and crashed on first render as "undefined is not a
|
|
13
|
+
* component" — nowhere near the import that caused it. The app's in-app
|
|
14
|
+
* reference HUD imports it that way (it is host code, compiled with the app, so
|
|
15
|
+
* the name resolves there), and that is where an agent copied it from.
|
|
16
|
+
*
|
|
17
|
+
* So the SDK's own namespaces fail BY NAME at evaluation:
|
|
18
|
+
* - '@ateam-ai-mobile/*' — the host's packages, never a bundle's.
|
|
19
|
+
* - '@adas/*' other than '@adas/plugin-sdk' — the SDK's own docs once told
|
|
20
|
+
* plugin authors to import '@adas/device-state' (sdk/device-state.ts header,
|
|
21
|
+
* 4110943), a name the shim never resolved. There is one SDK module name.
|
|
22
|
+
* Neither is aliased to '@adas/plugin-sdk': two names for one SDK is a second
|
|
23
|
+
* source of truth, and that is what this closes (CORE's call). The shim checks
|
|
24
|
+
* them BEFORE the host's module registry, so no host registration can alias one
|
|
25
|
+
* either.
|
|
26
|
+
*
|
|
27
|
+
* Every OTHER unknown module keeps the warning and `{}`. What exists there is
|
|
28
|
+
* the host's decision, not the SDK's — each host registers its own set
|
|
29
|
+
* (@ateam-ai-mobile/expo adds expo-web-browser and expo-linking, the reference
|
|
30
|
+
* app adds react-native-webview) — and a bundle built for one host may keep
|
|
31
|
+
* such a module external and only use it on a path another host never takes.
|
|
32
|
+
* Failing those at evaluation would break already-deployed bundles we have no
|
|
33
|
+
* inventory of, and there is no single right name to point the author at.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/** The one SDK module name a bundle can require (values and types alike). */
|
|
37
|
+
export const PLUGIN_SDK_MODULE = '@adas/plugin-sdk';
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The by-name refusal for a require of an SDK-namespace name the shim will
|
|
41
|
+
* never satisfy, or null when the name is the SDK itself or not the SDK's.
|
|
42
|
+
*/
|
|
43
|
+
export function sdkModuleRefusal(name: string): string | null {
|
|
44
|
+
if (name === PLUGIN_SDK_MODULE) return null;
|
|
45
|
+
if (!name.startsWith('@ateam-ai-mobile/') && !name.startsWith('@adas/')) return null;
|
|
46
|
+
return (
|
|
47
|
+
`a plugin bundle required '${name}', which does not exist inside a bundle. ` +
|
|
48
|
+
`Import from '${PLUGIN_SDK_MODULE}' instead — it is the only SDK module a bundle can require ` +
|
|
49
|
+
`(values and types alike), and the one to keep external when building. ` +
|
|
50
|
+
`'@ateam-ai-mobile/*' are the host app's packages, not the plugin's.`
|
|
51
|
+
);
|
|
52
|
+
}
|