@mentra/miniapp 3.4.0-dev.998 → 3.5.0-dev.1238

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.
Files changed (95) hide show
  1. package/README.md +7 -7
  2. package/dist/background/index.d.ts +5 -2
  3. package/dist/background/index.d.ts.map +1 -1
  4. package/dist/background/index.js.map +1 -1
  5. package/dist/background/register.d.ts +3 -1
  6. package/dist/background/register.d.ts.map +1 -1
  7. package/dist/background/register.js +19 -2
  8. package/dist/background/register.js.map +1 -1
  9. package/dist/index.d.ts +5 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/modules/blob.d.ts +2 -1
  13. package/dist/modules/blob.d.ts.map +1 -1
  14. package/dist/modules/blob.js +2 -1
  15. package/dist/modules/blob.js.map +1 -1
  16. package/dist/modules/events.d.ts +16 -6
  17. package/dist/modules/events.d.ts.map +1 -1
  18. package/dist/modules/events.js +53 -47
  19. package/dist/modules/events.js.map +1 -1
  20. package/dist/modules/mic.d.ts +26 -4
  21. package/dist/modules/mic.d.ts.map +1 -1
  22. package/dist/modules/mic.js +13 -4
  23. package/dist/modules/mic.js.map +1 -1
  24. package/dist/modules/miniapps.d.ts +44 -57
  25. package/dist/modules/miniapps.d.ts.map +1 -1
  26. package/dist/modules/miniapps.js +21 -24
  27. package/dist/modules/miniapps.js.map +1 -1
  28. package/dist/modules/speaker.d.ts +41 -10
  29. package/dist/modules/speaker.d.ts.map +1 -1
  30. package/dist/modules/speaker.js +17 -6
  31. package/dist/modules/speaker.js.map +1 -1
  32. package/dist/modules/speechProcessing.d.ts +29 -0
  33. package/dist/modules/speechProcessing.d.ts.map +1 -0
  34. package/dist/modules/speechProcessing.js +22 -0
  35. package/dist/modules/speechProcessing.js.map +1 -0
  36. package/dist/modules/system.d.ts +8 -3
  37. package/dist/modules/system.d.ts.map +1 -1
  38. package/dist/modules/system.js +1 -1
  39. package/dist/modules/system.js.map +1 -1
  40. package/dist/modules/telemetry.d.ts +25 -0
  41. package/dist/modules/telemetry.d.ts.map +1 -0
  42. package/dist/modules/telemetry.js +61 -0
  43. package/dist/modules/telemetry.js.map +1 -0
  44. package/dist/modules/transcription.d.ts +70 -3
  45. package/dist/modules/transcription.d.ts.map +1 -1
  46. package/dist/modules/transcription.js +68 -2
  47. package/dist/modules/transcription.js.map +1 -1
  48. package/dist/protocol.d.ts +29 -15
  49. package/dist/protocol.d.ts.map +1 -1
  50. package/dist/protocol.js +30 -15
  51. package/dist/protocol.js.map +1 -1
  52. package/dist/react/MentraProvider.d.ts +13 -1
  53. package/dist/react/MentraProvider.d.ts.map +1 -1
  54. package/dist/react/MentraProvider.js +31 -1
  55. package/dist/react/MentraProvider.js.map +1 -1
  56. package/dist/session.d.ts +59 -6
  57. package/dist/session.d.ts.map +1 -1
  58. package/dist/session.js +203 -43
  59. package/dist/session.js.map +1 -1
  60. package/dist/transport/auto.js +6 -0
  61. package/dist/transport/auto.js.map +1 -1
  62. package/dist/transport/dispatch.d.ts +2 -0
  63. package/dist/transport/dispatch.d.ts.map +1 -1
  64. package/dist/transport/dispatch.js +7 -2
  65. package/dist/transport/dispatch.js.map +1 -1
  66. package/dist/transport/local-socket.d.ts +6 -0
  67. package/dist/transport/local-socket.d.ts.map +1 -1
  68. package/dist/transport/local-socket.js +34 -2
  69. package/dist/transport/local-socket.js.map +1 -1
  70. package/dist/transport/types.d.ts +4 -1
  71. package/dist/transport/types.d.ts.map +1 -1
  72. package/dist/ui/index.d.ts +7 -4
  73. package/dist/ui/index.d.ts.map +1 -1
  74. package/dist/ui/index.js.map +1 -1
  75. package/package.json +2 -2
  76. package/src/background/index.ts +6 -3
  77. package/src/background/register.ts +24 -2
  78. package/src/index.ts +11 -3
  79. package/src/modules/blob.ts +2 -1
  80. package/src/modules/events.ts +65 -51
  81. package/src/modules/mic.ts +30 -4
  82. package/src/modules/miniapps.ts +59 -71
  83. package/src/modules/speaker.ts +56 -12
  84. package/src/modules/speechProcessing.ts +42 -0
  85. package/src/modules/system.ts +8 -3
  86. package/src/modules/telemetry.ts +62 -0
  87. package/src/modules/transcription.ts +106 -9
  88. package/src/protocol.ts +32 -16
  89. package/src/react/MentraProvider.tsx +23 -2
  90. package/src/session.ts +206 -52
  91. package/src/transport/auto.ts +5 -0
  92. package/src/transport/dispatch.ts +7 -2
  93. package/src/transport/local-socket.ts +30 -1
  94. package/src/transport/types.ts +4 -1
  95. package/src/ui/index.ts +7 -4
@@ -7,10 +7,12 @@
7
7
  * layer (invoke / handle) lives on `session.actions`, not here — these are
8
8
  * operations on the app as a whole, not on a declared action.
9
9
  *
10
- * Installation (`install`, `checkInstallCompatibility`, `uninstall`) is
11
- * narrower still: the host accepts it only from a Store miniapp bundled with
12
- * the Mentra App build. The host downloads, verifies, and activates the
13
- * release through its own installer; the Store only selects the release.
10
+ * Installing (`install`, `checkInstallCompatibility`, `uninstall`) is
11
+ * narrower still: only a miniapp on the Mentra App's system list, running the
12
+ * release the Mentra App installed for it, may install miniapps. Development
13
+ * builds, which may use the calls above, may not. The host installs from a
14
+ * miniapp URL through the same installer as every other way in, with no install
15
+ * sheet: the caller asks the person first.
14
16
  */
15
17
 
16
18
  import {MiniappRequestType} from "../protocol"
@@ -55,10 +57,6 @@ export interface MiniappInfo {
55
57
  compatibility: MiniappCompatibility
56
58
  /** True when this package identity is backed by a ZIP in the Mentra App build. */
57
59
  system: boolean
58
- /** Store package that owns updates of this active release, when it is Store-managed. */
59
- storeOwnerPackageName?: string
60
- /** Store the host build assigns to update this bundled package's active release, if any. */
61
- systemStoreOwnerPackageName?: string
62
60
  /** Declared actions (empty if the miniapp declares none). */
63
61
  actions: MiniappActionInfo[]
64
62
  }
@@ -74,49 +72,54 @@ export interface MiniappHardwareRequirement {
74
72
  description?: string
75
73
  }
76
74
 
77
- /** Backend-neutral release request, accepted only from a bundled, host-trusted Store. */
75
+ /** A miniapp to install. */
78
76
  export interface InstallMiniappRequest {
79
- packageName: string
80
- version: string
81
- bundleUrl: string
82
- /** SHA-256 of the release ZIP; the host refuses any other bytes. */
83
- bundleSha256: string
84
- /**
85
- * Bearer for `bundleUrl`, when the Store's backend requires one. The host
86
- * forwards it untouched and keeps no Store address of its own: entitlement is
87
- * settled between this miniapp and its backend, integrity by the SHA-256 and
88
- * the bundle's publisher signature.
89
- */
90
- bundleAuthorization?: string
91
- /**
92
- * Automatic update: never stop a running miniapp. A running or starting
93
- * target defers the request with `APP_RUNNING`.
94
- */
95
- onlyIfStopped?: boolean
77
+ /** The miniapp's URL: the HTTPS address that serves its `miniapp.json`. */
78
+ url: string
96
79
  /**
97
- * With `onlyIfStopped`: when the target is running, the host stages the
98
- * release and asks the user whether to update now. Declining, or a prompt the
99
- * host does not show (the Mentra App is in the background, another prompt is
100
- * open, or this miniapp was asked within the last day), still answers
101
- * `APP_RUNNING`.
80
+ * The package the person agreed to install. When given, a URL that serves another package installs nothing and
81
+ * fails with `not_a_miniapp`.
102
82
  */
103
- askIfRunning?: boolean
104
- /** Minimum Mentra App version declared by the release manifest. */
105
- minHostVersion?: string
106
- /** Mentra Miniapp SDK version declared by the release manifest. */
107
- sdkVersion?: string
108
- /** Glasses hardware requirements declared by the release manifest. */
109
- hardwareRequirements?: MiniappHardwareRequirement[]
110
- releaseId?: string
111
- channel?: string
83
+ packageName?: string
112
84
  }
113
85
 
114
86
  export interface InstallMiniappResult {
87
+ /**
88
+ * `installed`: this release installed. `opened`: nothing installed, because the miniapp is installed from this URL
89
+ * already, or a newer release of it is; {@link MiniappsModule.open} it to show it. `deferred`: the miniapp is
90
+ * running, so its update waits until it stops, or until the person answers the Mentra App's update prompt.
91
+ */
92
+ status: "installed" | "opened" | "deferred"
115
93
  packageName: string
94
+ /** The installed version: the new release, or the one that stays. */
116
95
  version: string
117
- installedByStore: string
118
96
  }
119
97
 
98
+ /**
99
+ * Why an install failed: the `reason` of an `INSTALL_FAILED` rejection from {@link MiniappsModule.install}.
100
+ * - `not_a_miniapp`: the URL serves no valid `miniapp.json` or bundle.
101
+ * - `domain_mismatch`: the package name doesn't belong to the URL's domain.
102
+ * - `archived`: Mentra archived this URL; it doesn't install.
103
+ * - `needs_newer_app`: the miniapp needs a newer Mentra App, or hardware the glasses lack.
104
+ * - `access_denied`: its server refused this account, or this deployment doesn't allow installing from a URL.
105
+ * - `age_restricted`: the person's declared age is below the miniapp's age rating.
106
+ * - `network`: the URL couldn't be reached.
107
+ * - `cancelled`: the Mentra App signed out or switched deployments meanwhile.
108
+ * - `integrity`: the bundle doesn't match what `miniapp.json` names.
109
+ * - `signature_invalid`: the bundle's signature doesn't match the installed miniapp's publisher.
110
+ */
111
+ export type InstallMiniappFailureReason =
112
+ | "not_a_miniapp"
113
+ | "domain_mismatch"
114
+ | "archived"
115
+ | "needs_newer_app"
116
+ | "access_denied"
117
+ | "age_restricted"
118
+ | "network"
119
+ | "cancelled"
120
+ | "integrity"
121
+ | "signature_invalid"
122
+
120
123
  export interface InstallMiniappCompatibilityRequest {
121
124
  minHostVersion?: string | null
122
125
  sdkVersion?: string | null
@@ -127,17 +130,7 @@ export type InstallMiniappCompatibility =
127
130
  | {compatible: true}
128
131
  | {compatible: false; blocker: "host" | "sdk" | "hardware"; reason: string}
129
132
 
130
- export type InstallMiniappPhase = "downloading" | "verifying" | "extracting" | "activating" | "complete"
131
-
132
- export interface InstallMiniappProgress {
133
- packageName: string
134
- version: string
135
- phase: InstallMiniappPhase
136
- }
137
-
138
133
  export class MiniappsModule {
139
- private readonly progressHandlers = new Set<(progress: InstallMiniappProgress) => void>()
140
-
141
134
  constructor(private readonly session: MiniappSession) {}
142
135
 
143
136
  /**
@@ -185,24 +178,27 @@ export class MiniappsModule {
185
178
  }
186
179
 
187
180
  /**
188
- * Download, verify, and install a release through the phone host. Accepted
189
- * only from a Store bundled with the Mentra App build; other callers receive
190
- * NOT_PERMITTED.
181
+ * Install the miniapp at a miniapp URL, with no install sheet: ask the person first. The host fetches its
182
+ * `miniapp.json`, checks the package name against the URL's domain, registers the URL with Mentra, checks the
183
+ * phone can run it, and downloads, verifies and installs its bundle.
184
+ *
185
+ * Only a miniapp on the Mentra App's system list may install; any other caller gets NOT_PERMITTED. A failed
186
+ * install rejects with INSTALL_FAILED, whose `reason` is an {@link InstallMiniappFailureReason}.
191
187
  */
192
188
  async install(request: InstallMiniappRequest): Promise<InstallMiniappResult> {
193
189
  return this.session.sendRequest<InstallMiniappResult>(
194
190
  {
195
- ...request,
196
191
  type: MiniappRequestType.MINIAPPS_INSTALL,
192
+ url: request.url,
193
+ ...(request.packageName !== undefined ? {packageName: request.packageName} : {}),
197
194
  },
198
- // Downloading, validating, extracting, asking the user and relaunching
199
- // can legitimately outlast the SDK's default request timeout. The request
200
- // still settles on the host response or session disconnect.
195
+ // Fetching, registering, downloading and installing can legitimately outlast the SDK's default request
196
+ // timeout. The request still settles on the host response or session disconnect.
201
197
  {timeoutMs: 0},
202
198
  )
203
199
  }
204
200
 
205
- /** Check host, Mentra Miniapp SDK, and glasses compatibility before offering or applying an update. */
201
+ /** Check a release's Mentra App, SDK and glasses requirements against this phone. System-list miniapps only. */
206
202
  async checkInstallCompatibility(request: InstallMiniappCompatibilityRequest): Promise<InstallMiniappCompatibility> {
207
203
  return this.session.sendRequest<InstallMiniappCompatibility>({
208
204
  type: MiniappRequestType.MINIAPPS_INSTALL_CHECK,
@@ -212,18 +208,10 @@ export class MiniappsModule {
212
208
  })
213
209
  }
214
210
 
215
- /** Subscribe to host-owned install progress. Returns an unsubscribe function. */
216
- onInstallProgress(handler: (progress: InstallMiniappProgress) => void): () => void {
217
- this.progressHandlers.add(handler)
218
- return () => this.progressHandlers.delete(handler)
219
- }
220
-
221
- /** @internal */
222
- _deliverInstallProgress(progress: InstallMiniappProgress): void {
223
- for (const handler of this.progressHandlers) handler(progress)
224
- }
225
-
226
- /** Uninstall a package this Store installed. Bundled Stores only. */
211
+ /**
212
+ * Uninstall a miniapp installed from a miniapp URL. A miniapp the Mentra App bundles, one a workspace manages and a
213
+ * development build stay, with NOT_PERMITTED. System-list miniapps only.
214
+ */
227
215
  async uninstall(packageName: string): Promise<void> {
228
216
  await this.session.sendRequest<void>({
229
217
  type: MiniappRequestType.MINIAPPS_UNINSTALL,
@@ -5,13 +5,15 @@
5
5
  * audio chunks, VAD) lives on session.mic — the split is by I/O direction.
6
6
  *
7
7
  * Imperative surface:
8
- * speaker.play({audioUrl}) — play an arbitrary URL via the phone's
8
+ * speaker.play({audioUrl}) — play an http(s) or data: URL, or one of this
9
+ * miniapp's blobs, via the phone's
9
10
  * AudioPlaybackService.
10
- * speaker.speak(text) — send a SPEAK request. Phone streams cloud
11
- * TTS when connected and falls back to local
12
- * offline TTS when cloud is unavailable.
11
+ * speaker.speak(text) — send a SPEAK request. By default the phone
12
+ * streams cloud TTS when connected and falls
13
+ * back to its on-device voice; the
14
+ * `processing` option picks the order.
13
15
  * Resolves when playback completes; rejects
14
- * with a TTS_* error code on cloud failure.
16
+ * with a TTS_* error code on failure.
15
17
  * speaker.createStream(opts) — open a live PCM output stream (16-bit LE).
16
18
  * Returns a SpeakerStreamWriter: write() PCM
17
19
  * chunks as they arrive (e.g. from a WebSocket
@@ -38,8 +40,13 @@ import {MiniappErrorCode, MiniappRequestType} from "../protocol"
38
40
  import {MiniappSession} from "../session"
39
41
  import {bytesToBase64, toUint8Array} from "./base64"
40
42
  import type {UnsubscribeFn} from "./events"
43
+ import {resolveSpeechProcessing, type SpeechProcessing} from "./speechProcessing"
41
44
 
42
45
  export interface PlayAudioOptions {
46
+ /**
47
+ * An http(s) or `data:` URL, or the `file://` uri of one of this miniapp's
48
+ * blobs (`session.blob`). The host refuses any other file or scheme.
49
+ */
43
50
  audioUrl: string
44
51
  /** Start playback at this offset in milliseconds. Defaults to zero. */
45
52
  startPositionMs?: number
@@ -58,10 +65,17 @@ export interface SpeakOptions {
58
65
  */
59
66
  enableSanitization?: boolean
60
67
  /**
61
- * Force this call to use on-device offline TTS, skipping cloud TTS
62
- * entirely — even when cloud is connected. Rejects with `TTS_LOCAL_UNAVAILABLE`
63
- * if the offline model isn't ready instead of falling back to cloud.
68
+ * Where the speech is synthesized. Default `"preferCloud"`.
69
+ *
70
+ * - `"preferCloud"`: cloud TTS while the cloud is connected, otherwise the
71
+ * phone's on-device voice.
72
+ * - `"preferLocal"`: the on-device voice when its model is ready and can say
73
+ * it (an explicit cloud `voice_id` cannot), otherwise cloud TTS.
74
+ * - `"localOnly"`: the on-device voice only; never the cloud. Rejects with
75
+ * `TTS_LOCAL_UNAVAILABLE` when the on-device model isn't ready.
64
76
  */
77
+ processing?: SpeechProcessing
78
+ /** @deprecated Use `processing: "localOnly"`. Removed in 4.0; ignored when `processing` is set. */
65
79
  forceLocal?: boolean
66
80
  }
67
81
 
@@ -80,6 +94,22 @@ export type SpeakerStreamSampleRate = 16000 | 24000 | 48000
80
94
  export interface SpeakerStreamOptions {
81
95
  /** PCM sample rate in Hz. Default 16000. */
82
96
  sampleRate?: SpeakerStreamSampleRate
97
+ /**
98
+ * Open the native stream now and keep it idle until the first write, so a
99
+ * later sound only has to write samples. The speaker reports `idle` and other
100
+ * audio is left alone until then. If the audio route changes before the
101
+ * first write (Bluetooth or glasses connect/disconnect, a call, an audio
102
+ * interruption), the phone closes the stream and the next write fails with
103
+ * "not open"; open a fresh stream then.
104
+ */
105
+ prewarm?: boolean
106
+ /**
107
+ * How much audio (80–500 ms) the phone queues before playback starts, and
108
+ * the cushion against gaps after that. Default 500. A sound shorter than
109
+ * this still plays once you close the stream. Use a small value such as 80
110
+ * for short cues that should start immediately.
111
+ */
112
+ jitterMs?: number
83
113
  /** Channel count. v1 is mono only. Default 1. */
84
114
  channels?: 1
85
115
  /** Playback volume 0..1. Default 1. */
@@ -118,7 +148,10 @@ export class SpeakerStreamWriter {
118
148
  private settled = false
119
149
  private writeChain: Promise<void> = Promise.resolve()
120
150
 
121
- constructor(private readonly session: MiniappSession, readonly streamId: string) {}
151
+ constructor(
152
+ private readonly session: MiniappSession,
153
+ readonly streamId: string,
154
+ ) {}
122
155
 
123
156
  /**
124
157
  * Append raw PCM bytes (16-bit LE). Auto-chunked. Resolves with the host's
@@ -255,8 +288,9 @@ export class SpeakerModule {
255
288
  }
256
289
 
257
290
  /**
258
- * Speak text through the phone. The host streams cloud TTS when connected,
259
- * then falls back to local offline TTS.
291
+ * Speak text through the phone, in the cloud or on-device as
292
+ * `options.processing` says (default: cloud TTS when connected, then the
293
+ * on-device voice).
260
294
  *
261
295
  * Rejects with a MiniappRequestError containing a `code` field on cloud-side
262
296
  * TTS failures: `TTS_TEXT_TOO_LONG`, `TTS_INVALID_VOICE`, `TTS_UPSTREAM_ERROR`.
@@ -268,6 +302,7 @@ export class SpeakerModule {
268
302
  if ((Array.isArray(normalized) && normalized.length === 0) || normalized === "") {
269
303
  throw {code: MiniappErrorCode.INTERNAL, message: "speak requires at least one non-empty sentence"}
270
304
  }
305
+ const processing = resolveSpeechProcessing(options, "speaker.speak(options)")
271
306
  try {
272
307
  // Like play(): resolves only when TTS playback completes, so opt out of the
273
308
  // default request timeout (long text can outlast it). Settled by the host
@@ -281,7 +316,9 @@ export class SpeakerModule {
281
316
  volume: options.volume,
282
317
  stopOtherAudio: options.stopOtherAudio ?? false,
283
318
  enableSanitization: options.enableSanitization ?? true,
284
- forceLocal: options.forceLocal ?? false,
319
+ processing,
320
+ // Hosts before `processing` (Mentra App 3.4.0) read only this flag.
321
+ forceLocal: processing === "localOnly",
285
322
  },
286
323
  {timeoutMs: 0},
287
324
  )
@@ -312,9 +349,16 @@ export class SpeakerModule {
312
349
  ) {
313
350
  throw new RangeError("speaker stream volume must be between 0 and 1")
314
351
  }
352
+ if (
353
+ options.jitterMs !== undefined &&
354
+ (!Number.isFinite(options.jitterMs) || options.jitterMs < 80 || options.jitterMs > 500)
355
+ )
356
+ throw new RangeError("speaker stream jitterMs must be between 80 and 500")
315
357
  const res = await this.session.sendRequest<{streamId: string}>({
316
358
  type: MiniappRequestType.SPEAKER_STREAM_OPEN,
317
359
  sampleRate: options.sampleRate ?? 16000,
360
+ ...(options.jitterMs === undefined ? {} : {jitterMs: options.jitterMs}),
361
+ ...(options.prewarm === undefined ? {} : {prewarm: options.prewarm}),
318
362
  channels: options.channels ?? 1,
319
363
  volume: options.volume,
320
364
  stopOtherAudio: options.stopOtherAudio ?? true,
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @fileoverview Where speech is processed: on the phone or in the cloud.
3
+ *
4
+ * Transcription listeners (`session.transcription.on` / `forLanguage`) and
5
+ * speech requests (`session.speaker.speak`) take the same `processing` option.
6
+ */
7
+
8
+ import {MiniappValidationError} from "./languages"
9
+
10
+ /**
11
+ * Where speech is processed.
12
+ *
13
+ * - `"preferCloud"` (default): the cloud; the phone's on-device models only
14
+ * while the cloud is unreachable.
15
+ * - `"preferLocal"`: on-device when a model for the language is ready,
16
+ * otherwise the cloud.
17
+ * - `"localOnly"`: on-device only; never the cloud.
18
+ */
19
+ export type SpeechProcessing = "preferCloud" | "preferLocal" | "localOnly"
20
+
21
+ const SPEECH_PROCESSING: readonly SpeechProcessing[] = ["preferCloud", "preferLocal", "localOnly"]
22
+
23
+ /** The `processing` option, with the deprecated `forceLocal` it replaces. */
24
+ export interface SpeechProcessingOptions {
25
+ processing?: SpeechProcessing
26
+ /** @deprecated Use `processing: "localOnly"`. Removed in 4.0. */
27
+ forceLocal?: boolean
28
+ }
29
+
30
+ /**
31
+ * @internal The processing an options object asks for. `processing` wins;
32
+ * without it, the deprecated `forceLocal: true` means `"localOnly"`.
33
+ * Throws `MiniappValidationError` for an unknown `processing` value.
34
+ */
35
+ export function resolveSpeechProcessing(options: SpeechProcessingOptions, where: string): SpeechProcessing {
36
+ const {processing} = options
37
+ if (processing === undefined) return options.forceLocal === true ? "localOnly" : "preferCloud"
38
+ if (SPEECH_PROCESSING.includes(processing)) return processing
39
+ throw new MiniappValidationError(
40
+ `${where}: unknown processing ${JSON.stringify(processing)}. Use ${SPEECH_PROCESSING.map((value) => `"${value}"`).join(", ")}.`,
41
+ )
42
+ }
@@ -9,13 +9,17 @@ import { MiniappSession } from "../session"
9
9
 
10
10
  export interface ShareOptions {
11
11
  text?: string
12
+ /**
13
+ * An http(s) link, or the `file://` uri of one of this miniapp's blobs
14
+ * (`session.blob`). The host refuses any other file or scheme.
15
+ */
12
16
  url?: string
13
17
  title?: string
14
18
  /** Base64-encoded file data for file sharing. */
15
19
  base64?: string
16
20
  /** MIME type when sharing base64 data. */
17
21
  mimeType?: string
18
- /** Filename when sharing base64 data. */
22
+ /** File name when sharing base64 data: one name; path separators become `_`. */
19
23
  filename?: string
20
24
  }
21
25
 
@@ -25,9 +29,10 @@ export interface ShareResult {
25
29
  }
26
30
 
27
31
  export interface DownloadOptions {
28
- /** URL to download from, OR base64 data. */
32
+ /** An http: or https: URL to download from, OR base64 data. */
29
33
  url?: string
30
34
  base64?: string
35
+ /** One file name; path separators become `_`. */
31
36
  filename?: string
32
37
  mimeType?: string
33
38
  }
@@ -58,7 +63,7 @@ export class SystemModule {
58
63
  return result ?? { success: false }
59
64
  }
60
65
 
61
- /** Open a URL in the system browser. Blocks dangerous schemes (javascript:, file:). */
66
+ /** Open a URL in the system browser. Never opens local files or scripts (file:, content:, javascript:, data:). */
62
67
  openUrl(url: string): void {
63
68
  this.session.sendOneShot({
64
69
  type: MiniappRequestType.OPEN_URL,
@@ -0,0 +1,62 @@
1
+ /**
2
+ * @fileoverview TelemetryModule (`session.telemetry`): a miniapp's own analytics, shown in its organization's Fleet
3
+ * Management.
4
+ *
5
+ * `capture(event, properties?)` sends one fire-and-forget message to the Mentra App and returns nothing. It never throws
6
+ * and never waits. The SDK checks nothing: the Mentra App attributes the event to this miniapp and applies the limits
7
+ * (names, values, 25 properties, the rate), and on a Mentra App without the `telemetry` host feature it does nothing.
8
+ * Before the handshake says which, it holds the latest 100 captures and sends them once it knows.
9
+ */
10
+
11
+ import {MiniappRequestType} from "../protocol"
12
+ import type {MiniappSession} from "../session"
13
+
14
+ export type TelemetryValue = string | number | boolean
15
+ export type TelemetryProperties = Record<string, TelemetryValue>
16
+
17
+ /** Captures held until the handshake says whether the Mentra App takes them. */
18
+ const MAX_HELD = 100
19
+
20
+ export class TelemetryModule {
21
+ private held: object[] = []
22
+ private waiting = false
23
+
24
+ constructor(private readonly session: MiniappSession) {}
25
+
26
+ /**
27
+ * Captures one event, in the style of PostHog: `session.telemetry.capture("call_ended", {platform: "teams",
28
+ * duration_s: 312})`. Names are lowercase letters, digits and underscores; values are flat. Never personal data: no
29
+ * names, emails, phone numbers, typed text or content.
30
+ */
31
+ capture(event: string, properties?: TelemetryProperties): void {
32
+ try {
33
+ const message = {type: MiniappRequestType.TELEMETRY_CAPTURE, event, properties: properties ?? {}}
34
+ if (this.session.handshakeDone) {
35
+ if (this.session.hostFeatures?.telemetry === true) this.session.sendOneShot(message)
36
+ return
37
+ }
38
+ if (this.held.length >= MAX_HELD) this.held.shift()
39
+ this.held.push(message)
40
+ if (!this.waiting) {
41
+ this.waiting = true
42
+ const off = this.session.on("ready", () => {
43
+ off()
44
+ this.waiting = false
45
+ const held = this.held.splice(0)
46
+ if (this.session.hostFeatures?.telemetry !== true) return
47
+ for (const one of held) {
48
+ // Each on its own: one capture that cannot be sent never takes the others, or the session's other
49
+ // listeners, down with it.
50
+ try {
51
+ this.session.sendOneShot(one)
52
+ } catch {
53
+ // Lost.
54
+ }
55
+ }
56
+ })
57
+ }
58
+ } catch {
59
+ // Analytics never break the miniapp: a value that cannot be sent is lost.
60
+ }
61
+ }
62
+ }
@@ -6,7 +6,10 @@
6
6
  * session.transcription.on(handler) // auto-detect
7
7
  * session.transcription.forLanguage("en-US", handler) // single language
8
8
  * session.transcription.forLanguage(["en-US", "es-ES"], handler) // multi-language
9
+ * session.transcription.on(handler, {processing: "preferLocal"}) // on-device when it can
9
10
  * session.transcription.configure({languageHints, vocabulary, diarization})
11
+ * session.transcription.onModelStatus(handler) // on-device model state
12
+ * session.transcription.finishUtterance() // end the on-device line now
10
13
  * session.transcription.stop() // tear down all
11
14
  *
12
15
  * Hoisted to top-level (vs. nested under `session.mic`) because transcription
@@ -23,6 +26,7 @@ import {MiniappSession} from "../session"
23
26
  import type {TranscriptionData, UnsubscribeFn} from "./events"
24
27
  import {requireLanguageHint, requireTranscriptionLanguage} from "./languages"
25
28
  import type {LanguageHint, TranscriptionLanguage} from "./languages"
29
+ import {resolveSpeechProcessing, type SpeechProcessing} from "./speechProcessing"
26
30
 
27
31
  /** Configuration for cloud-side transcription behavior. */
28
32
  export interface TranscriptionConfig {
@@ -41,16 +45,56 @@ export interface TranscriptionConfig {
41
45
 
42
46
  export interface TranscriptionOptions {
43
47
  /**
44
- * Use only on-device STT for this listener; never deliver cloud transcripts.
45
- * Other listeners on the same stream keep their own routing choice. Requires
46
- * a downloaded local STT model.
48
+ * Where this listener's speech is transcribed. Default `"preferCloud"`.
49
+ *
50
+ * - `"preferCloud"`: the cloud; the phone's on-device model only while the
51
+ * cloud is unreachable.
52
+ * - `"preferLocal"`: the on-device model while it runs in this listener's
53
+ * language, otherwise the cloud. `on()` follows the model's language,
54
+ * unless `configure({languageHints})` names one the model can't
55
+ * transcribe; then it stays on the cloud.
56
+ * - `"localOnly"`: on-device only; never the cloud.
57
+ *
58
+ * The phone runs one on-device model, the one picked on its Speech page, and
59
+ * downloads it when a `preferLocal` or `localOnly` listener needs it; follow
60
+ * it with `onModelStatus`. A listener moves between the cloud and on-device
61
+ * during a pause in speech, once both have finished with what was said
62
+ * before it, so it never misses or repeats speech; `TranscriptionData.source`
63
+ * says where each result came from. Each listener routes on its own: other
64
+ * listeners on the same stream keep their choice.
47
65
  */
66
+ processing?: SpeechProcessing
67
+ /** @deprecated Use `processing: "localOnly"`. Removed in 4.0; ignored when `processing` is set. */
48
68
  forceLocal?: boolean
49
69
  }
50
70
 
71
+ /**
72
+ * State of the on-device speech-to-text model behind this miniapp's on-device
73
+ * transcription. The phone runs the one model picked on its Speech page for
74
+ * every miniapp.
75
+ */
76
+ export interface TranscriptionModelStatus {
77
+ /** BCP-47 language of the picked model, e.g. "en-US". */
78
+ language: string
79
+ /**
80
+ * - `downloading`: the model is being downloaded (`progress` is 0–100).
81
+ * - `loading`: the model is loading into memory.
82
+ * - `ready`: on-device transcripts are flowing.
83
+ * - `unavailable`: no on-device transcription right now; `reason` says why
84
+ * (for example no `preferLocal` or `localOnly` listener, a failed
85
+ * download, or a listener in a language other than the picked model's).
86
+ */
87
+ state: "downloading" | "loading" | "ready" | "unavailable"
88
+ progress?: number
89
+ reason?: string
90
+ }
91
+
51
92
  export class TranscriptionModule {
52
93
  private readonly unsubs = new Set<UnsubscribeFn>()
53
94
  private currentConfig: TranscriptionConfig | null = null
95
+ private readonly modelStatusHandlers = new Set<(status: TranscriptionModelStatus) => void>()
96
+ private modelStatusUnsub: UnsubscribeFn | null = null
97
+ private modelStatus: TranscriptionModelStatus | null = null
54
98
 
55
99
  constructor(private readonly session: MiniappSession) {}
56
100
 
@@ -63,8 +107,11 @@ export class TranscriptionModule {
63
107
  * event) preserves existing semantics.
64
108
  */
65
109
  on(handler: (data: TranscriptionData) => void, options: TranscriptionOptions = {}): UnsubscribeFn {
110
+ const processing = resolveSpeechProcessing(options, "transcription.on(options)")
66
111
  return this.track(
67
- this.session._subscribe(`${MiniappStreamType.TRANSCRIPTION}:auto`, handler as (data: unknown) => void, options),
112
+ this.session._subscribe(`${MiniappStreamType.TRANSCRIPTION}:auto`, handler as (data: unknown) => void, {
113
+ processing,
114
+ }),
68
115
  )
69
116
  }
70
117
 
@@ -90,16 +137,15 @@ export class TranscriptionModule {
90
137
  const langs = (Array.isArray(language) ? language : [language]).map((lang) =>
91
138
  requireTranscriptionLanguage(lang, "transcription.forLanguage(language)"),
92
139
  )
140
+ const processing = resolveSpeechProcessing(options, "transcription.forLanguage(options)")
93
141
  if (langs.length === 0) return () => {}
94
142
 
95
143
  const unsubs: UnsubscribeFn[] = []
96
144
  for (const lang of langs) {
97
145
  unsubs.push(
98
- this.session._subscribe(
99
- `${MiniappStreamType.TRANSCRIPTION}:${lang}`,
100
- handler as (data: unknown) => void,
101
- options,
102
- ),
146
+ this.session._subscribe(`${MiniappStreamType.TRANSCRIPTION}:${lang}`, handler as (data: unknown) => void, {
147
+ processing,
148
+ }),
103
149
  )
104
150
  }
105
151
  const combined: UnsubscribeFn = () => {
@@ -141,6 +187,57 @@ export class TranscriptionModule {
141
187
  .then(() => undefined)
142
188
  }
143
189
 
190
+ /**
191
+ * Follow the on-device speech-to-text model's state. You get the current
192
+ * state right away, then every change. Use it to show "downloading 40%" or
193
+ * to wait for `ready` before relying on on-device transcripts.
194
+ */
195
+ onModelStatus(handler: (status: TranscriptionModelStatus) => void): UnsubscribeFn {
196
+ this.modelStatusHandlers.add(handler)
197
+ if (!this.modelStatusUnsub) {
198
+ // One stream subscription per module; the host sends its current state on subscribe.
199
+ this.modelStatusUnsub = this.session._subscribe(MiniappStreamType.TRANSCRIPTION_MODEL_STATUS, (data) => {
200
+ const status = data as TranscriptionModelStatus
201
+ this.modelStatus = status
202
+ for (const listener of [...this.modelStatusHandlers]) listener(status)
203
+ })
204
+ } else if (this.modelStatus) {
205
+ // Later handlers get the last state locally, since the host only replays on subscribe.
206
+ const current = this.modelStatus
207
+ queueMicrotask(() => {
208
+ if (this.modelStatusHandlers.has(handler) && this.modelStatus === current) handler(current)
209
+ })
210
+ }
211
+ return this.track(() => {
212
+ this.modelStatusHandlers.delete(handler)
213
+ if (this.modelStatusHandlers.size > 0) return
214
+ this.modelStatusUnsub?.()
215
+ this.modelStatusUnsub = null
216
+ this.modelStatus = null
217
+ })
218
+ }
219
+
220
+ /**
221
+ * End the current on-device utterance now, instead of waiting for the
222
+ * recognizer's own end-of-speech pause. Call it when your own end-of-turn
223
+ * rule fires (for example after `mic.onVoiceActivity` reports enough
224
+ * silence).
225
+ *
226
+ * Resolves with the final text once that final transcript has been
227
+ * delivered to your on-device handlers, or `""` when nothing was pending.
228
+ * Resolves `null` when no on-device recognizer is running or the picked
229
+ * model can't finish early (models that transcribe in fixed chunks); their
230
+ * final text still arrives on its own.
231
+ *
232
+ * Applies only to on-device transcription and needs a `localOnly` listener
233
+ * or one that is getting on-device text right now. The phone runs one
234
+ * recognizer for every miniapp, so this ends the current line for every
235
+ * on-device subscriber, Captions included.
236
+ */
237
+ finishUtterance(): Promise<string | null> {
238
+ return this.session.sendRequest<string | null>({type: MiniappRequestType.TRANSCRIPTION_FINISH})
239
+ }
240
+
144
241
  /** Tear down every transcription subscription this module owns. */
145
242
  stop(): void {
146
243
  for (const u of this.unsubs) {