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71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/**

 * Bootstrap β€” the engine's single front door (`engine.configure` / `start` / `stop`).

 *

 * The host hands engine auth + config + analytics in one call; engine owns the

 * runtime construction behind `start()`. Internal services read this holder

 * directly instead of exposing host-facing adapter bags.

 */

import {isTrustedSystemMiniappRelease} from "../services/systemMiniappTrust"

export type SubjectTokenType = "supabase" | "authing" | (string & {})

export interface IslandAuth {
  /** Public profile of the selected Entra account, never bearer credentials. */
  getMeetingAccount?: () => Promise<{displayName?: string; email?: string} | undefined>
  /** Host-owned Teams subject token from the selected deployment account. */
  getTeamsToken?: () => Promise<string>
  /** Returns the host's current (auto-refreshed) subject token for the backend. */
  getSubjectToken?: () => Promise<{token: string; type: SubjectTokenType}>
  /** Supplies a token issued directly for Runtime in a Core-free deployment. */
  getRuntimeToken?: (opts?: {forceRefresh?: boolean}) => Promise<string>
  /** Stable, deployment-scoped local identity for bundled miniapp storage. */
  getUserId?: () => Promise<string> | string
  /**

   * Optional auth-session listener. Hosts that can emit auth changes should

   * wire this so engine can reconnect backend sessions after restored login

   * state lands post-boot.

   */
  onStateChange?: (callback: (event: string, session: {token?: string | null} | null) => void) => unknown
}

export interface IslandConfigValues {
  /** Workspace calls use Runtime credentials and cannot access the public Call backend. */
  privateMeetings?: boolean
  /** cloud-v2 core service base URL (defaults resolved by the cloud client). */
  coreUrl?: string | null
  /** cloud-v2 runtime service base URL. */
  runtimeUrl?: string | null
  /** Host's live manifest/override resolver, also used on automatic reconnects. */
  resolveCloudEndpoints?: () => {core: string; runtime: string}
  /** Scope for debug settings written through engine.dev. */
  cloudDebugScope?: string
  /** Open Runtime's live WebSocket/audio session. Defaults to true. */
  runtimeRealtimeSession?: boolean
  /** Complete allowlist for bundled/local miniapps; null or omitted allows all. */
  localMiniappAllowlist?: readonly string[] | null
  /** Live host access gate, composed with deployment policy at listing and launch. */
  isLocalMiniappAllowed?: (packageName: string) => boolean
  /** Provenance-aware policy for workspace SYSTEM and managed miniapps. */
  localMiniappPolicy?: LocalMiniappPolicy
  /**

   * Host availability per mode: `interactive` for user-facing discovery and

   * launches, `background` for invisible, invocation-scoped action wakes.

   * Omitted allows both.

   */
  isMiniappAvailable?: (packageName: string, mode: MiniappAvailabilityMode) => boolean
  /** User-facing Mentra App version, compared with a release's `minHostVersion`. */
  hostVersion?: string
  /** Semver range of Mentra Miniapp SDK versions (`sdkVersion`) this host runs. */
  supportedMiniappSdkRange?: string
  /** Package identities backed by miniapp ZIPs shipped in this host build. */
  bundledSystemMiniappPackages?: readonly string[]
  /**

   * Where Mentra hosts its own miniapps for this deployment, for example

   * `https://miniapps.mentraglass.com/`. Each bundled miniapp updates from

   * `<firstPartyMiniappsUrl><packageName>/`. Null or omitted keeps bundled

   * miniapps on the versions the build or deployment ships.

   */
  firstPartyMiniappsUrl?: string | null
  /**

   * Register every miniapp URL the engine installs in Core's registry, and stop an install the registry has

   * archived. On by default, as on iOS and Android. Off, the engine installs any miniapp URL without registering

   * it; the domain rule still applies. A host app that turns it off answers to the app stores' rules itself.

   */
  requireRegistry?: boolean
  /**

   * Whether a URL opens this host app itself: its own URL schemes, and the addresses it claims as app links. A

   * miniapp never opens one through `session.system.openUrl`: it would reach the host's own link handling, such as

   * its install sheet or its sign-in callbacks, which no miniapp may drive. Omitted, nothing more is refused.

   */
  isHostLink?: (url: string) => boolean
  /**

   * The host app's own App Store age rating, for example `"12+"`. A miniapp whose `ageRating` is above it installs or

   * opens only for a person whose declared age is old enough: the engine asks once through the `askDeclaredAge` seam

   * and keeps the answer on the person's Core account. A miniapp without a rating is never gated. Omitted, nothing is

   * gated; a host app that leaves it out answers to the app stores' rules itself.

   */
  hostAgeRating?: string | null
  /** Optional per-package configuration supplied by the host deployment. */
  miniappConfiguration?: Readonly<Record<string, Readonly<Record<string, string>>>>
  /** Deployment-scoped key for the persisted Core refresh token. */
  cloudAuthStorageKey?: string
  /** Deployment-pinned Mentra Live OTA manifest; explicit null disables remote OTA. */
  otaManifestUrl?: string | null
  /** Official deployments retain the legacy-device and embedded release fallback. */
  allowLegacyOtaFallback?: boolean
  /** Deployment capability policy. Omitted entries preserve consumer behavior. */
  features?: Partial<Record<IslandFeatureName, boolean>>
  /** OEM identifier (Mentra is OEM #0); reserved for OEM auth/telemetry. */
  oemId?: string
  /**

   * LC3 frame size (bytes) the phone's mic encoder emits β€” announced to the

   * cloud on connect (20 for G1, 40 for G2, …). Defaults to 20 if unset.

   */
  audioFrameSizeBytes?: number
  /**

   * Dev-only live Metro/LAN host used to repair persisted local-miniapp dev URLs

   * after the laptop changes networks. Omitted in production/OEM builds.

   */
  devServerHost?: () => string | undefined
}

export interface ManagedMiniappPolicyEntry {
  packageName: string
  version: string
  sha256: string
  deploymentId: string
  deploymentOrigin: string
}

export interface LocalMiniappPolicy {
  systemPackageNames: readonly string[] | null
  managed: readonly ManagedMiniappPolicyEntry[]
}

export type MiniappAvailabilityMode = "interactive" | "background"

export type IslandFeatureName = "managedStreams" | "nativeMeetings" | "cloudSpeech" | "onDeviceSpeech" | "navigation"

export type IslandAnalytics = (event: string, props?: Record<string, unknown>) => void

/**

 * Named host-UI seams: engine dispatches the runtime request, the host owns the

 * screen/navigation/branding. Keep each entry a single narrow purpose β€” this is

 * a contract of specific UI capabilities, not a generic runtime-hook bag.

 */
export interface IslandUiSeams {
  /**

   * `session.glasses.requestWifiSetup` β€” open the host's glasses Wi-Fi setup

   * flow. Absent β‡’ miniapps get NOT_IMPLEMENTED for the request.

   */
  requestWifiSetup?: (reason?: string, packageName?: string) => Promise<void> | void
  /** Phone Wi-Fi availability; null when the platform cannot read the radio state. */
  isPhoneWifiEnabled?: () => Promise<boolean | null>
  /** Host prompt + system settings round trip. Keep the requesting miniapp mounted. */
  requestPhoneWifiEnable?: (reason?: string) => Promise<{enabled: boolean | null; cancelled: boolean}>
  /**

   * `session.system.scanQr` β€” open a phone-camera QR scanner overlay. Must NOT

   * clear miniapp foreground: UI_CLOSE on a live call hangs it up. Absent β‡’

   * miniapps get NOT_IMPLEMENTED.

   */
  scanQr?: (options?: ScanQrOptions) => Promise<ScanQrResult>
  /**

   * Ask the person how old they are, once: a miniapp rated above `hostAgeRating` is installing or opening and their

   * Core account has no declared age yet. Resolve the whole number of years they give, or null when they cancel. The

   * engine keeps the answer, with the date, on their account and never sends it to a miniapp. Absent β‡’ such

   * miniapps don't install or open until the account has a declared age.

   */
  askDeclaredAge?: () => Promise<number | null>
  /** A miniapp the person was installing or opening was stopped by its age rating. The host says why. */
  showAgeRestricted?: (notice: AgeRestrictionNotice) => void
}

/** Why the age gate stopped a miniapp the person was installing or opening. */
export interface AgeRestrictionNotice {
  packageName: string
  /** The miniapp's name. */
  name: string
  /** The rating it declares, for example `"18+"`. */
  ageRating: string
  /** `too_young`: their declared age is below its rating. `unavailable`: their age could not be checked (offline). */
  reason: "too_young" | "unavailable"
}

export interface ScanQrOptions {
  title?: string
  hint?: string
}

export type ScanQrResult = {data: string} | {cancelled: true}

export interface IslandConfigureOptions {
  /** REQUIRED β€” the only must-have seam. The host owns login; engine owns the rest. */
  auth: IslandAuth
  config?: IslandConfigValues
  analytics?: IslandAnalytics
  ui?: IslandUiSeams
}

/** Whether the host currently offers this miniapp for user launches or invisible maintenance. */
export function isMiniappAvailable(packageName: string, mode: MiniappAvailabilityMode = "interactive"): boolean {
  return options?.config?.isMiniappAvailable?.(packageName, mode) ?? true
}

/** What, besides a release's provenance, decides whether a package or release may run. */
export interface InstalledMiniappContext {
  /**

   * The account's current workspace assigned the package through Fleet, or the install is that assignment's. It

   * admits the package under a workspace policy, and a release of it installed from a URL.

   */
  assigned?: boolean
}

/**

 * The deployment lets this package run at all: launches check it before its release. Under a workspace policy, a

 * package its system list or its manifest names, or one the account's current workspace assigned through Fleet that

 * this build doesn't bundle (a bundled package follows the system list).

 */
export function isLocalMiniappPackageAllowed(packageName: string, context: InstalledMiniappContext = {}): boolean {
  if (options?.config?.isLocalMiniappAllowed?.(packageName) === false) return false
  const policy = options?.config?.localMiniappPolicy
  if (policy) {
    return (
      policy.systemPackageNames === null ||
      policy.systemPackageNames.includes(packageName) ||
      policy.managed.some((entry) => entry.packageName === packageName) ||
      (context.assigned === true && !options?.config?.bundledSystemMiniappPackages?.includes(packageName))
    )
  }
  const allowlist = options?.config?.localMiniappAllowlist
  return allowlist == null || allowlist.includes(packageName)
}

export function isOfflineSystemMiniappAllowed(packageName: string): boolean {
  if (options?.config?.isLocalMiniappAllowed?.(packageName) === false) return false
  const policy = options?.config?.localMiniappPolicy
  if (!policy) return isLocalMiniappPackageAllowed(packageName)
  return policy.systemPackageNames === null || policy.systemPackageNames.includes(packageName)
}

/** The built-in system miniapp that holds the Miniapp Developer tools. */
const MINIAPP_DEVELOPER_PACKAGE_NAME = "com.mentra.miniappdev"

/**

 * Whether this deployment allows miniapp development: developer servers,

 * scanned release QRs and authoring snapshots, of any package. It follows the

 * deployment's approval of the Miniapp Developer tools; Super Mode never

 * overrides it.

 */
export function isMiniappDevelopmentAllowed(): boolean {
  return isOfflineSystemMiniappAllowed(MINIAPP_DEVELOPER_PACKAGE_NAME)
}

/** Refuse to register or install a developer build where development is off. */
export function assertMiniappDevelopmentAllowed(): void {
  if (!isMiniappDevelopmentAllowed()) throw new Error("This deployment does not allow miniapp development")
}

export function isInstalledMiniappAllowed(

  packageName: string,

  version: string | undefined,

  releaseIdentity: {

    source: string

    storePackageName?: string

    sourceUrl?: string

    bundleSha256?: string

    deploymentId?: string

    deploymentOrigin?: string

  } | null,

  context: InstalledMiniappContext = {},

): boolean {
  if (options?.config?.isLocalMiniappAllowed?.(packageName) === false) return false
  const policy = options?.config?.localMiniappPolicy
  if (!policy) return isLocalMiniappPackageAllowed(packageName)

  const systemApproved = policy.systemPackageNames === null || policy.systemPackageNames.includes(packageName)
  if (systemApproved && releaseIdentity?.source === "bundled_asset") return true
  // A compatible update of an approved bundled package, from Mentra's own host
  // (or, for an older install, the retired Mentra Store), keeps the visibility
  // of the bundled release it replaced.
  if (isTrustedSystemMiniappRelease(options?.config ?? {}, packageName, releaseIdentity)) return true
  // An explicit install: from the scanner's release QR, or from a miniapp URL. A package this build bundles follows
  // the system policy above whatever URL it came from: a deployment that leaves it out doesn't get it from a URL.
  if (releaseIdentity?.source === "direct_download") return isMiniappDevelopmentAllowed()
  if (releaseIdentity?.source === "url") {
    if (options?.config?.bundledSystemMiniappPackages?.includes(packageName)) return false
    // A workspace's Fleet assignment is its admins' deployment, not development: it runs where the developer tools
    // are off. It rewrites no deployment trust, so a package the deployment's manifest pins stays the manifest's.
    if (context.assigned && !policy.managed.some((entry) => entry.packageName === packageName)) return true
    return isMiniappDevelopmentAllowed()
  }
  if (!version || releaseIdentity?.source !== "deployment_manifest") return false

  return policy.managed.some(
    (entry) =>
      entry.packageName === packageName &&
      entry.version === version &&
      entry.sha256 === releaseIdentity.bundleSha256?.toLowerCase() &&
      entry.deploymentId === releaseIdentity.deploymentId &&
      entry.deploymentOrigin === releaseIdentity.deploymentOrigin,
  )
}

/**

 * A developer build (live server or `dev-*` snapshot) under `packageName`.

 * Where development is allowed it may add a package or stand in for an

 * installed one, managed or not.

 */
export function isDevMiniappAllowed(packageName: string): boolean {
  if (options?.config?.isLocalMiniappAllowed?.(packageName) === false) return false
  return isMiniappDevelopmentAllowed()
}

/** Read a defensive package-scoped configuration snapshot. */
export function getMiniappConfiguration(packageName: string): Record<string, string> {
  const configuration = options?.config?.miniappConfiguration?.[packageName]
  return configuration ? {...configuration} : {}
}

export function isFeatureEnabled(feature: IslandFeatureName): boolean {
  return options?.config?.features?.[feature] !== false
}

let options: IslandConfigureOptions | null = null
let started = false

/**

 * Hand engine its auth + config + analytics. Call once, before `start()`.

 *

 * Reconfiguring a RUNNING runtime is not supported: services capture pieces of

 * this config as they build (e.g. the cloud client's endpoints), so swapping the

 * options mid-run would split-brain the runtime (`getAuth()`/`getConfigValues()`

 * report values the running services never consumed). Ignored with a warning

 * while started; after `stop()`, `configure()` + `start()` begin a fresh cycle.

 */
export function configure(opts: IslandConfigureOptions): void {
  if (started) {
    console.warn("engine.configure() called after engine.start(); ignored β€” stop() the runtime before reconfiguring")
    return
  }
  options = {
    ...opts,
    config: opts.config ? {...opts.config, ...frozenMiniappPolicy(opts.config)} : undefined,
  }
}

function frozenMiniappPolicy(

  config: Pick<IslandConfigValues, "localMiniappAllowlist" | "localMiniappPolicy">,

): Pick<IslandConfigValues, "localMiniappAllowlist" | "localMiniappPolicy"> {
  const {localMiniappAllowlist, localMiniappPolicy} = config
  return {
    localMiniappAllowlist: Array.isArray(localMiniappAllowlist)
      ? Object.freeze([...localMiniappAllowlist])
      : localMiniappAllowlist,
    localMiniappPolicy: localMiniappPolicy
      ? Object.freeze({
          systemPackageNames: Array.isArray(localMiniappPolicy.systemPackageNames)
            ? Object.freeze([...localMiniappPolicy.systemPackageNames])
            : null,
          managed: Object.freeze(
            localMiniappPolicy.managed.map((entry) => Object.freeze({...entry, sha256: entry.sha256.toLowerCase()})),
          ),
        })
      : undefined,
  }
}

/** A workspace's miniapp catalog: the releases it manages, its allowlist and miniapp configuration. */
export type MiniappPolicy = Pick<
  IslandConfigValues,
  "localMiniappAllowlist" | "localMiniappPolicy" | "miniappConfiguration"
>

/**

 * Replace the workspace's miniapp catalog on a running runtime, as

 * `updateUiSeams` does for UI seams. Installs, launches and miniapp

 * configuration read it when they run. Everything else stays as configured:

 * endpoints, auth and feature switches belong to the started session.

 */
export function updateMiniappPolicy(policy: MiniappPolicy): void {
  if (!options?.config) {
    console.warn("engine.updateMiniappPolicy() called before engine.configure(); ignored")
    return
  }
  options = {
    ...options,
    config: {...options.config, ...frozenMiniappPolicy(policy), miniappConfiguration: policy.miniappConfiguration},
  }
}

/**

 * Merge host-UI seams after configure/start. UI capabilities (scan overlay,

 * wifi setup) are looked up per request, so this is safe on a running runtime.

 * Used so Metro reloads can attach seams that missed the original configure().

 */
export function updateUiSeams(ui: IslandUiSeams): void {
  if (!options) {
    console.warn("engine.updateUiSeams() called before engine.configure(); ignored")
    return
  }
  options = {...options, ui: {...options.ui, ...ui}}
}

/** Mark the runtime started. Idempotent. */
export async function start(): Promise<void> {
  if (started) return
  if (!options) {
    throw new Error("engine.start() called before engine.configure()")
  }
  started = true
}

/** Tear down. Idempotent. */
export async function stop(): Promise<void> {
  started = false
}

export function isStarted(): boolean {
  return started
}

/** Test-only: wipe configure state so suites can start from a cold host. */
export function resetForTests(): void {
  options = null
  started = false
}

/** The host-supplied auth provider, or null if not configured yet. */
export function getAuth(): IslandAuth | null {
  return options?.auth ?? null
}

export function getConfigValues(): IslandConfigValues {
  return options?.config ?? {}
}

export function getAnalytics(): IslandAnalytics | null {
  return options?.analytics ?? null
}

/** The host-supplied UI seams ({} until configure() provides them). */
export function getUiSeams(): IslandUiSeams {
  return options?.ui ?? {}
}