Download mobile/modules/engine/src/runtime/bootstrap.ts from Anirudh1950/MentraOS: direct link, hf CLI and curl.
- Browser
- Download file 19.6 kB
-
https://huggingface.co/Anirudh1950/MentraOS/resolve/main/mobile/modules/engine/src/runtime/bootstrap.ts
- Command line
-
hf download hf://Anirudh1950/MentraOS/mobile/modules/engine/src/runtime/bootstrap.ts
-
curl -L -o bootstrap.ts https://huggingface.co/Anirudh1950/MentraOS/resolve/main/mobile/modules/engine/src/runtime/bootstrap.ts
19.6 kB
| /** | |
| * 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 ?? {} | |
| } | |