Anirudh1950 commited on
Commit
074ebca
·
verified ·
1 Parent(s): d9e3e09

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. cloud-v2/packages/runtime/src/services/audio/providers/audioTimeline.test.ts +17 -0
  2. cloud-v2/packages/runtime/src/services/audio/providers/audioTimeline.ts +36 -0
  3. cloud-v2/packages/runtime/src/services/audio/providers/mock.ts +65 -0
  4. cloud-v2/packages/runtime/src/services/audio/providers/provider.ts +85 -0
  5. cloud-v2/packages/runtime/src/services/audio/providers/soniox.auth.test.ts +108 -0
  6. cloud-v2/packages/runtime/src/services/audio/providers/soniox.test.ts +861 -0
  7. cloud-v2/packages/runtime/src/services/audio/providers/soniox.ts +1062 -0
  8. cloud-v2/packages/runtime/src/services/audio/result.test.ts +105 -0
  9. cloud-v2/packages/runtime/src/services/audio/result.ts +110 -0
  10. cloud-v2/packages/runtime/src/services/audio/workers/identity.fixture.ts +14 -0
  11. cloud-v2/packages/runtime/src/services/audio/workers/identity.test.ts +75 -0
  12. cloud-v2/packages/runtime/src/services/audio/workers/identity.ts +44 -0
  13. cloud-v2/packages/runtime/src/services/audio/workers/lc3.ts +179 -0
  14. cloud-v2/packages/runtime/src/services/audio/workers/pool.ts +349 -0
  15. cloud-v2/packages/runtime/src/services/audio/workers/worker.ts +925 -0
  16. cloud-v2/packages/runtime/src/services/camera/camera.service.ts +177 -0
  17. cloud-v2/packages/runtime/src/services/maps/maps.service.test.ts +302 -0
  18. cloud-v2/packages/runtime/src/services/maps/maps.service.ts +250 -0
  19. cloud-v2/packages/runtime/src/services/maps/providers/mapbox.provider.ts +391 -0
  20. cloud-v2/packages/runtime/src/services/maps/providers/provider.ts +64 -0
  21. cloud-v2/packages/runtime/src/services/meetings/acs-teams.service.test.ts +396 -0
  22. cloud-v2/packages/runtime/src/services/meetings/acs-teams.service.ts +354 -0
  23. cloud-v2/packages/runtime/src/services/meetings/meeting-providers.test.ts +16 -0
  24. cloud-v2/packages/runtime/src/services/meetings/meeting-providers.ts +26 -0
  25. cloud-v2/packages/runtime/src/services/meetings/teams-identity-selection.test.ts +73 -0
  26. cloud-v2/packages/runtime/src/services/meetings/teams-meetings.service.test.ts +146 -0
  27. cloud-v2/packages/runtime/src/services/meetings/teams-meetings.service.ts +235 -0
  28. cloud-v2/packages/runtime/src/services/session/control-stream.ts +99 -0
  29. cloud-v2/packages/runtime/src/services/session/frame-timeline.test.ts +18 -0
  30. cloud-v2/packages/runtime/src/services/session/frame-timeline.ts +8 -0
  31. cloud-v2/packages/runtime/src/services/session/ownership.ts +235 -0
  32. cloud-v2/packages/runtime/src/services/session/stream.ts +376 -0
  33. cloud-v2/packages/runtime/src/services/session/subscriptions-store.ts +300 -0
  34. cloud-v2/packages/runtime/src/services/session/subscriptions.ts +43 -0
  35. cloud-v2/packages/runtime/src/services/storage/providers/local.provider.ts +94 -0
  36. cloud-v2/packages/runtime/src/services/storage/providers/s3.provider.ts +97 -0
  37. cloud-v2/packages/runtime/src/services/storage/storage.service.ts +86 -0
  38. cloud-v2/packages/runtime/src/services/stream/providers/cloudflare-stream.provider.ts +407 -0
  39. cloud-v2/packages/runtime/src/services/stream/stream.service.ts +286 -0
  40. cloud-v2/packages/runtime/src/services/tts/providers/elevenlabs.provider.ts +135 -0
  41. cloud-v2/packages/runtime/src/services/tts/tts-formats.ts +19 -0
  42. cloud-v2/packages/runtime/src/services/tts/tts.service.ts +48 -0
  43. cloud-v2/packages/shared/package.json +24 -0
  44. cloud-v2/packages/shared/src/auth.test.ts +394 -0
  45. cloud-v2/packages/shared/src/auth.ts +443 -0
  46. cloud-v2/packages/shared/src/health.ts +84 -0
  47. cloud-v2/packages/shared/src/index.ts +21 -0
  48. cloud-v2/packages/shared/src/logger.ts +85 -0
  49. cloud-v2/packages/shared/src/oidc.ts +81 -0
  50. cloud-v2/packages/shared/tsconfig.json +9 -0
cloud-v2/packages/runtime/src/services/audio/providers/audioTimeline.test.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { expect, test } from "bun:test";
2
+ import { AudioTimeline } from "./audioTimeline";
3
+
4
+ test("provider samples map back to submitted frames despite gaps, loss and session changes", () => {
5
+ const timeline = new AudioTimeline();
6
+ timeline.add(160, { sessionTag: 1, offsetMs: 100 });
7
+ timeline.add(160, { sessionTag: 1, offsetMs: 140 });
8
+ expect(timeline.at(5)).toEqual({ sessionTag: 1, offsetMs: 105 });
9
+ expect(timeline.at(10)).toEqual({ sessionTag: 1, offsetMs: 140 });
10
+ timeline.add(160, { sessionTag: 2, offsetMs: 0 });
11
+ expect(timeline.at(20)).toEqual({ sessionTag: 2, offsetMs: 0 });
12
+ timeline.prune(10);
13
+ expect(timeline.at(0)).toBeUndefined();
14
+ timeline.reset();
15
+ timeline.add(160, { sessionTag: 2, offsetMs: 90 });
16
+ expect(timeline.at(0)).toEqual({ sessionTag: 2, offsetMs: 90 });
17
+ });
cloud-v2/packages/runtime/src/services/audio/providers/audioTimeline.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { AudioPosition } from "@mentra/cloud-protocol";
2
+
3
+ /** Maps Soniox's contiguous submitted-sample clock back to phone frame positions. */
4
+ export class AudioTimeline {
5
+ private endMs = 0;
6
+ private spans: Array<{
7
+ start: number;
8
+ end: number;
9
+ position?: AudioPosition;
10
+ }> = [];
11
+
12
+ add(sampleCount: number, position?: AudioPosition): void {
13
+ const end = this.endMs + sampleCount / 16;
14
+ this.spans.push({ start: this.endMs, end, position });
15
+ this.endMs = end;
16
+ }
17
+
18
+ at(startMs: number): AudioPosition | undefined {
19
+ const span = this.spans.find((s) => startMs >= s.start && startMs < s.end);
20
+ return (
21
+ span?.position && {
22
+ sessionTag: span.position.sessionTag,
23
+ offsetMs: span.position.offsetMs + startMs - span.start,
24
+ }
25
+ );
26
+ }
27
+
28
+ prune(beforeMs: number): void {
29
+ this.spans = this.spans.filter((s) => s.end > beforeMs);
30
+ }
31
+
32
+ reset(): void {
33
+ this.endMs = 0;
34
+ this.spans = [];
35
+ }
36
+ }
cloud-v2/packages/runtime/src/services/audio/providers/mock.ts ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview MockProvider — synthetic transcripts for tests and local dev.
3
+ *
4
+ * Emits a deterministic transcript on every `writeAudio` call so end-to-end
5
+ * tests can verify "PCM reached a provider and a transcript flowed back"
6
+ * without depending on a real ASR API.
7
+ *
8
+ * Text format: `mock <scope> <n>` where `n` increments per write. Includes
9
+ * the scope (typically the user identifier) so multi-user tests can confirm
10
+ * routing didn't cross-talk.
11
+ */
12
+
13
+ import type {
14
+ ProviderOptions,
15
+ TranscriptionProvider,
16
+ } from "./provider";
17
+
18
+ export interface CreateMockProviderOptions extends ProviderOptions {
19
+ /**
20
+ * If true, emit one interim then one final per write (mimics a real ASR
21
+ * that streams partials). Default: false — single final per write.
22
+ */
23
+ emitInterim?: boolean;
24
+ }
25
+
26
+ export async function createMockProvider(
27
+ opts: CreateMockProviderOptions,
28
+ ): Promise<TranscriptionProvider> {
29
+ let writeCount = 0;
30
+ let totalSamples = 0;
31
+ let closed = false;
32
+
33
+ return {
34
+ name: "mock",
35
+ writeAudio(pcm: Int16Array): void {
36
+ if (closed) return;
37
+ writeCount++;
38
+ // Audio is 16kHz mono Int16 → 16 samples per millisecond.
39
+ const startMs = Math.round(totalSamples / 16);
40
+ totalSamples += pcm.length;
41
+ const endMs = Math.round(totalSamples / 16);
42
+ const text = `mock ${opts.scope} ${writeCount}`;
43
+
44
+ if (opts.emitInterim) {
45
+ opts.onTranscript({
46
+ text,
47
+ isFinal: false,
48
+ startMs,
49
+ endMs,
50
+ language: opts.language,
51
+ });
52
+ }
53
+ opts.onTranscript({
54
+ text,
55
+ isFinal: true,
56
+ startMs,
57
+ endMs,
58
+ language: opts.language,
59
+ });
60
+ },
61
+ async close(): Promise<void> {
62
+ closed = true;
63
+ },
64
+ };
65
+ }
cloud-v2/packages/runtime/src/services/audio/providers/provider.ts ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Transcription provider interface.
3
+ *
4
+ * Abstracts the "PCM in, transcript out" pipeline so we can swap between:
5
+ * - `MockProvider` for tests + local dev (no API key needed)
6
+ * - `SonioxProvider` (next iteration) wrapping `@soniox/node`
7
+ * - Future: alternative ASR vendors as failover or for specific languages
8
+ *
9
+ * Lifecycle:
10
+ * const provider = await createMockProvider({ onTranscript: handler });
11
+ * provider.writeAudio(pcm); // many times
12
+ * await provider.close(); // on detach
13
+ *
14
+ * Callbacks are passed at construction time (set-and-forget). Providers
15
+ * don't expose subscribe/unsubscribe — there's one handler per provider
16
+ * instance, owned by the worker that created it.
17
+ */
18
+
19
+ import type { AudioPosition, TranscriptionToken } from "@mentra/cloud-protocol";
20
+
21
+ export interface TranscriptEvent {
22
+ frameTimelineVersion?: 1;
23
+ /** Transcribed text. May be a partial token or a complete word/phrase. */
24
+ text: string;
25
+ /** Whether the provider considers this finalized (vs. interim/in-progress). */
26
+ isFinal: boolean;
27
+ /**
28
+ * Stable id for the utterance this event belongs to. Interim and final
29
+ * events for the same speech segment share one id so the client can
30
+ * correlate them and update a single card in place, then commit it on
31
+ * the final. Reset at each utterance boundary (endpoint / speaker change).
32
+ */
33
+ utteranceId?: string;
34
+ /** Speaker id if the provider reports diarization (e.g. `"1"`, `"2"`). */
35
+ speakerId?: string;
36
+ /** Audio timeline window this transcript covers, in milliseconds. */
37
+ startMs?: number;
38
+ endMs?: number;
39
+ /** ISO language code if the provider reports it (e.g. `"en"`). */
40
+ language?: string;
41
+ /**
42
+ * For translation: the source-language text of the same window, when the
43
+ * provider supplies original tokens alongside the translated ones. Lets a
44
+ * client render combined original + translated captions from one stream.
45
+ */
46
+ originalText?: string;
47
+ /**
48
+ * For translation: the DETECTED source-audio language (e.g. `"en"`), taken
49
+ * from the original-language tokens. `language` carries the language of
50
+ * `text` (the target language), so the detected source needs its own field.
51
+ */
52
+ sourceLanguage?: string;
53
+ /** Internal timing retained for phone-runtime subscription projection. */
54
+ tokens?: TranscriptionToken[];
55
+ }
56
+
57
+ export interface ProviderOptions {
58
+ /** Identifier for logging — typically the user's `mentraUserId`. */
59
+ scope: string;
60
+ /** Source language (`"auto"` for detection, otherwise BCP-47 code). */
61
+ language: string;
62
+ /**
63
+ * Optional detection hints for `language: "auto"` — bare ISO 639-1 codes
64
+ * ("en", "ja") that bias language identification without pinning it. Ignored
65
+ * for a specific `language` (the language itself is the hint there). Carries
66
+ * the miniapp's `transcription.configure({languageHints})` through to the
67
+ * provider (issue 021).
68
+ */
69
+ languageHints?: string[];
70
+ /** Fired when the provider has a transcript event to emit. */
71
+ onTranscript: (event: TranscriptEvent) => void;
72
+ /** Fired on provider-side errors. Worker logs + decides whether to recreate. */
73
+ onError?: (err: Error) => void;
74
+ }
75
+
76
+ export interface TranscriptionProvider {
77
+ /** Feed a PCM (Int16 mono, 16kHz) chunk. Non-blocking. */
78
+ writeAudio(pcm: Int16Array, position?: AudioPosition): void;
79
+
80
+ /** Close cleanly. Best-effort flushes any pending interim transcripts. */
81
+ close(): Promise<void>;
82
+
83
+ /** Provider identifier for diagnostics — `"mock"`, `"soniox"`, etc. */
84
+ readonly name: string;
85
+ }
cloud-v2/packages/runtime/src/services/audio/providers/soniox.auth.test.ts ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {describe, expect, test} from "bun:test";
2
+ import {createRequire} from "node:module";
3
+ import {SonioxNodeClient} from "@soniox/node";
4
+
5
+ import {createSonioxProvider} from "./soniox";
6
+ import type {TranscriptEvent, TranscriptionProvider} from "./provider";
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const clients: Array<[string, typeof SonioxNodeClient]> = [
10
+ ["ESM", SonioxNodeClient],
11
+ ["CommonJS", require("@soniox/node").SonioxNodeClient],
12
+ ];
13
+
14
+ async function waitUntil(check: () => boolean): Promise<void> {
15
+ const deadline = Date.now() + 5_000;
16
+ while (!check()) {
17
+ if (Date.now() >= deadline) throw new Error("Timed out waiting for Soniox session");
18
+ await Bun.sleep(10);
19
+ }
20
+ }
21
+
22
+ describe("Soniox connection authentication", () => {
23
+ for (const [format, Client] of clients) {
24
+ for (const targetLanguage of [undefined, "es"] as const) {
25
+ test(`${format}: ${targetLanguage ? "translation" : "transcription"} authenticates initial and replacement sessions`, async () => {
26
+ const apiKey = "soniox-auth-test-key";
27
+ const connections: string[] = [];
28
+ const configs: Array<Record<string, unknown>> = [];
29
+ const events: TranscriptEvent[] = [];
30
+ let upstream: Bun.ServerWebSocket<undefined> | undefined;
31
+ let provider: TranscriptionProvider | undefined;
32
+ const server = Bun.serve<undefined>({
33
+ hostname: "127.0.0.1",
34
+ port: 0,
35
+ fetch(request, server) {
36
+ const protocols = request.headers.get("sec-websocket-protocol") ?? "";
37
+ // Simulate the post-deadline service: refuse connections without
38
+ // connection authentication, even if a later message has api_key.
39
+ if (protocols.split(",").map((p) => p.trim()).join(",") !== `soniox-api-key,${apiKey}`) {
40
+ return new Response("Unauthenticated", {status: 401});
41
+ }
42
+ connections.push(protocols);
43
+ if (server.upgrade(request, {headers: {"Sec-WebSocket-Protocol": "soniox-api-key"}})) return;
44
+ return new Response("Upgrade required", {status: 400});
45
+ },
46
+ websocket: {
47
+ open(ws) {
48
+ upstream = ws;
49
+ },
50
+ message(ws, message) {
51
+ if (message === "") {
52
+ ws.send(JSON.stringify({tokens: [], finished: true}));
53
+ } else if (typeof message === "string") {
54
+ const config = JSON.parse(message);
55
+ if (config.model) configs.push(config);
56
+ } else {
57
+ ws.send(JSON.stringify({tokens: [
58
+ {text: targetLanguage ? "Hola" : "Hello", is_final: true, confidence: 1,
59
+ language: targetLanguage ?? "en",
60
+ ...(targetLanguage ? {translation_status: "translation"} : {})},
61
+ {text: "<end>", is_final: true, confidence: 1},
62
+ ]}));
63
+ }
64
+ },
65
+ },
66
+ });
67
+ try {
68
+ provider = await createSonioxProvider({
69
+ scope: "auth-test",
70
+ language: "en",
71
+ targetLanguage,
72
+ client: new Client({api_key: apiKey, realtime: {
73
+ ws_base_url: `ws://127.0.0.1:${server.port}`,
74
+ }}),
75
+ onTranscript: (event) => events.push(event),
76
+ });
77
+ await waitUntil(() => configs.length === 1);
78
+ provider.writeAudio(new Int16Array(160));
79
+ await waitUntil(() => events.some((event) => event.isFinal));
80
+ upstream!.close(1011, "test reconnect");
81
+ await waitUntil(() => configs.length === 2);
82
+ const beforeReconnectAudio = events.length;
83
+ provider.writeAudio(new Int16Array(160));
84
+ await waitUntil(() => events.length > beforeReconnectAudio);
85
+
86
+ expect(connections).toHaveLength(2);
87
+ for (const config of configs) {
88
+ expect(config).not.toHaveProperty("api_key");
89
+ expect(config.model).toBe(process.env.SONIOX_MODEL ?? "stt-rt-v5");
90
+ expect(config.audio_format).toBe("pcm_s16le");
91
+ if (targetLanguage) {
92
+ expect(config.translation).toEqual({type: "one_way", target_language: "es"});
93
+ } else {
94
+ expect(config).not.toHaveProperty("translation");
95
+ }
96
+ }
97
+ expect(events.at(-1)?.text).toBe(targetLanguage ? "Hola" : "Hello");
98
+ } finally {
99
+ try {
100
+ await provider?.close();
101
+ } finally {
102
+ server.stop(true);
103
+ }
104
+ }
105
+ }, 15_000);
106
+ }
107
+ }
108
+ });
cloud-v2/packages/runtime/src/services/audio/providers/soniox.test.ts ADDED
@@ -0,0 +1,861 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Tests for SonioxProvider's utterance lifecycle.
3
+ *
4
+ * Focus: the transcript pile-up bug. Soniox delivers a ROLLING WINDOW that it
5
+ * RE-DIARIZES across results, so a token's `speaker` label can flip between
6
+ * rounds within ONE real utterance. The provider must NOT finalize / mint a new
7
+ * utteranceId on that per-token flicker — it must emit interims under a single
8
+ * stable utteranceId and commit exactly one FINAL on the Soniox `endpoint`
9
+ * boundary (or on close()).
10
+ *
11
+ * We inject a fake Soniox client/session so we can drive `result` / `endpoint`
12
+ * events deterministically without a network or API key.
13
+ */
14
+ import { describe, test, expect } from "bun:test";
15
+
16
+ // Shrink the self-heal backoff so reconnect tests run in milliseconds. Read
17
+ // per-provider inside createSonioxProvider, so setting it here (before any
18
+ // provider is constructed) is sufficient.
19
+ process.env.SONIOX_RECONNECT_BASE_MS = "1";
20
+ process.env.SONIOX_RECONNECT_MAX_MS = "4";
21
+ process.env.SONIOX_RECONNECT_MAX_ATTEMPTS = "5";
22
+ process.env.SONIOX_ENDPOINT_DEBOUNCE_MS = "1";
23
+
24
+ import { createSonioxProvider, sonioxLanguageHints, sonioxTranslationTarget } from "./soniox";
25
+ import type { TranscriptEvent } from "./provider";
26
+
27
+ // Minimal shape of a Soniox realtime token we care about in these tests.
28
+ type FakeToken = {
29
+ text: string;
30
+ confidence: number;
31
+ is_final: boolean;
32
+ speaker?: string;
33
+ language?: string;
34
+ start_ms?: number;
35
+ end_ms?: number;
36
+ /** Set on translation-session tokens; absent for same-language passthrough. */
37
+ translation_status?: "original" | "translation";
38
+ };
39
+
40
+ /**
41
+ * A fake `RealtimeSttSession` that records event handlers so the test can
42
+ * synthesize Soniox `result` / `endpoint` events. Stands in for the real
43
+ * `@soniox/node` session, which is otherwise a live WebSocket.
44
+ */
45
+ class FakeSession {
46
+ private handlers = new Map<string, Array<(arg?: unknown) => void>>();
47
+
48
+ on(event: string, handler: (arg?: unknown) => void): this {
49
+ const list = this.handlers.get(event) ?? [];
50
+ list.push(handler);
51
+ this.handlers.set(event, list);
52
+ return this;
53
+ }
54
+
55
+ off(event: string, handler: (arg?: unknown) => void): this {
56
+ const list = this.handlers.get(event);
57
+ if (list) this.handlers.set(event, list.filter((h) => h !== handler));
58
+ return this;
59
+ }
60
+
61
+ emit(event: string, arg?: unknown): void {
62
+ for (const h of this.handlers.get(event) ?? []) h(arg);
63
+ }
64
+
65
+ // Lifecycle methods the provider calls. Instrumented so self-heal tests can
66
+ // assert connect/sendAudio/close behavior and inject a connect failure.
67
+ connectCount = 0;
68
+ sendAudioCount = 0;
69
+ closeCount = 0;
70
+ pauseCount = 0;
71
+ resumeCount = 0;
72
+ /** When > 0, the next N connect() calls reject (simulate a flaky reconnect). */
73
+ failNextConnects = 0;
74
+
75
+ async connect(): Promise<void> {
76
+ this.connectCount += 1;
77
+ if (this.failNextConnects > 0) {
78
+ this.failNextConnects -= 1;
79
+ throw new Error("fake connect failure");
80
+ }
81
+ }
82
+ sendAudio(): void {
83
+ this.sendAudioCount += 1;
84
+ }
85
+ pause(): void {
86
+ this.pauseCount += 1;
87
+ this.emit("finalized");
88
+ }
89
+ resume(): void {
90
+ this.resumeCount += 1;
91
+ }
92
+ async finish(): Promise<void> {}
93
+ async close(): Promise<void> {
94
+ this.closeCount += 1;
95
+ }
96
+
97
+ /** Simulate an unexpected upstream drop (not triggered by our close()). */
98
+ disconnect(reason = "upstream closed"): void {
99
+ this.emit("disconnected", reason);
100
+ }
101
+
102
+ /** Convenience: push a Soniox result with the given rolling token window. */
103
+ result(tokens: FakeToken[]): void {
104
+ this.emit("result", { tokens });
105
+ }
106
+
107
+ /** Convenience: fire the endpoint (real utterance boundary). */
108
+ endpoint(): void {
109
+ this.emit("endpoint");
110
+ }
111
+ }
112
+
113
+ /** Build a fake SonioxNodeClient whose `realtime.stt()` returns our session. */
114
+ function fakeClient(session: FakeSession): any {
115
+ return {
116
+ realtime: {
117
+ stt: () => session,
118
+ },
119
+ };
120
+ }
121
+
122
+ /**
123
+ * A fake client that hands out a NEW session per `realtime.stt()` call, in
124
+ * order. Mirrors the real client, which mints a fresh session each call — the
125
+ * self-heal path builds a replacement session, so the test needs more than one.
126
+ * Records every session it produced so the test can drive/inspect them.
127
+ */
128
+ function multiSessionClient(): { client: any; sessions: FakeSession[] } {
129
+ const sessions: FakeSession[] = [];
130
+ const client = {
131
+ realtime: {
132
+ stt: () => {
133
+ const s = new FakeSession();
134
+ sessions.push(s);
135
+ return s;
136
+ },
137
+ },
138
+ };
139
+ return { client, sessions };
140
+ }
141
+
142
+ /** Resolve after `ms` of real time (kept small so tests stay fast). */
143
+ function wait(ms: number): Promise<void> {
144
+ return new Promise((resolve) => setTimeout(resolve, ms));
145
+ }
146
+
147
+ async function withFastGapConfig<T>(fn: () => Promise<T>): Promise<T> {
148
+ const prevCheck = process.env.SONIOX_GAP_CHECK_INTERVAL_MS;
149
+ const prevThreshold = process.env.SONIOX_AUDIO_GAP_THRESHOLD_MS;
150
+ process.env.SONIOX_GAP_CHECK_INTERVAL_MS = "5";
151
+ process.env.SONIOX_AUDIO_GAP_THRESHOLD_MS = "20";
152
+ try {
153
+ return await fn();
154
+ } finally {
155
+ if (prevCheck == null) {
156
+ delete process.env.SONIOX_GAP_CHECK_INTERVAL_MS;
157
+ } else {
158
+ process.env.SONIOX_GAP_CHECK_INTERVAL_MS = prevCheck;
159
+ }
160
+ if (prevThreshold == null) {
161
+ delete process.env.SONIOX_AUDIO_GAP_THRESHOLD_MS;
162
+ } else {
163
+ process.env.SONIOX_AUDIO_GAP_THRESHOLD_MS = prevThreshold;
164
+ }
165
+ }
166
+ }
167
+
168
+ async function makeProvider(): Promise<{
169
+ session: FakeSession;
170
+ events: TranscriptEvent[];
171
+ provider: Awaited<ReturnType<typeof createSonioxProvider>>;
172
+ }> {
173
+ const session = new FakeSession();
174
+ const events: TranscriptEvent[] = [];
175
+ const provider = await createSonioxProvider({
176
+ scope: "user_test",
177
+ language: "auto",
178
+ client: fakeClient(session) as never,
179
+ onTranscript: (e) => events.push(e),
180
+ });
181
+ return { session, events, provider };
182
+ }
183
+
184
+ async function makeTranslationProvider(target: string): Promise<{
185
+ session: FakeSession;
186
+ events: TranscriptEvent[];
187
+ provider: Awaited<ReturnType<typeof createSonioxProvider>>;
188
+ }> {
189
+ const session = new FakeSession();
190
+ const events: TranscriptEvent[] = [];
191
+ const provider = await createSonioxProvider({
192
+ scope: "user_xlate_test",
193
+ language: "auto",
194
+ targetLanguage: target,
195
+ client: fakeClient(session) as never,
196
+ onTranscript: (e) => events.push(e),
197
+ });
198
+ return { session, events, provider };
199
+ }
200
+
201
+ describe("SonioxProvider translation same-language passthrough", () => {
202
+ test("untagged tokens (spoken language == target) emit as transcription text with their source language", async () => {
203
+ const { session, events, provider } = await makeTranslationProvider("es-ES");
204
+
205
+ // Soniox emits NO translation_status when there is nothing to translate
206
+ // (verified live: EN speech -> target en). Simulate Spanish speech with a
207
+ // Spanish target: plain untagged tokens.
208
+ session.result([
209
+ { text: "Hola ", confidence: 0.9, is_final: false, language: "es" },
210
+ { text: "mundo", confidence: 0.9, is_final: false, language: "es" },
211
+ ]);
212
+ session.endpoint();
213
+ await wait(5);
214
+
215
+ const finals = events.filter((e) => e.isFinal);
216
+ expect(finals.length).toBe(1);
217
+ expect(finals[0]!.text).toBe("Hola mundo");
218
+ expect(finals[0]!.sourceLanguage).toBe("es");
219
+ expect(finals[0]!.originalText).toBeUndefined();
220
+
221
+ await provider.close();
222
+ });
223
+
224
+ test("cross-language windows still emit only the translation half with originalText", async () => {
225
+ const { session, events, provider } = await makeTranslationProvider("es-ES");
226
+
227
+ session.result([
228
+ { text: "Hello ", confidence: 0.9, is_final: false, language: "en", translation_status: "original" },
229
+ { text: "world", confidence: 0.9, is_final: false, language: "en", translation_status: "original" },
230
+ { text: "Hola ", confidence: 0.9, is_final: false, language: "es", translation_status: "translation" },
231
+ { text: "mundo", confidence: 0.9, is_final: false, language: "es", translation_status: "translation" },
232
+ ]);
233
+ session.endpoint();
234
+ await wait(5);
235
+
236
+ const finals = events.filter((e) => e.isFinal);
237
+ expect(finals.length).toBe(1);
238
+ expect(finals[0]!.text).toBe("Hola mundo");
239
+ expect(finals[0]!.originalText).toBe("Hello world");
240
+ expect(finals[0]!.sourceLanguage).toBe("en");
241
+
242
+ await provider.close();
243
+ });
244
+ });
245
+
246
+ describe("sonioxLanguageHints", () => {
247
+ test("a specific language becomes its own bare-code hint (region stripped)", () => {
248
+ expect(sonioxLanguageHints("fr-FR", undefined)).toEqual(["fr"]);
249
+ expect(sonioxLanguageHints("en-US", ["ja"])).toEqual(["en"]); // specific wins; hints ignored
250
+ expect(sonioxLanguageHints("ZH-hans", undefined)).toEqual(["zh"]);
251
+ });
252
+
253
+ test("auto with no hints yields undefined (never a BCP-47 tag)", () => {
254
+ expect(sonioxLanguageHints("auto", undefined)).toBeUndefined();
255
+ expect(sonioxLanguageHints("auto", [])).toBeUndefined();
256
+ expect(sonioxLanguageHints(undefined, undefined)).toBeUndefined();
257
+ });
258
+
259
+ test("auto passes detection hints, reduced to bare codes and deduped", () => {
260
+ expect(sonioxLanguageHints("auto", ["en", "ja"])).toEqual(["en", "ja"]);
261
+ expect(sonioxLanguageHints("auto", ["en-US", "en-GB"])).toEqual(["en"]);
262
+ expect(sonioxLanguageHints("auto", ["fr-FR", "ja"])).toEqual(["fr", "ja"]);
263
+ });
264
+ });
265
+
266
+ describe("sonioxTranslationTarget", () => {
267
+ test("strips the region to a bare code (Soniox rejects BCP-47 targets)", () => {
268
+ expect(sonioxTranslationTarget("es-ES")).toBe("es");
269
+ expect(sonioxTranslationTarget("zh-CN")).toBe("zh");
270
+ expect(sonioxTranslationTarget("en")).toBe("en");
271
+ expect(sonioxTranslationTarget("PT-BR")).toBe("pt");
272
+ });
273
+ });
274
+
275
+ describe("SonioxProvider session configuration", () => {
276
+ test("configures one-way translation with a bare target_language", async () => {
277
+ const session = new FakeSession();
278
+ let sessionConfig: Record<string, unknown> | undefined;
279
+ const client = {
280
+ realtime: {
281
+ stt: (config: Record<string, unknown>) => {
282
+ sessionConfig = config;
283
+ return session;
284
+ },
285
+ },
286
+ };
287
+
288
+ const provider = await createSonioxProvider({
289
+ scope: "user_xlate",
290
+ language: "auto",
291
+ targetLanguage: "es-ES",
292
+ client: client as never,
293
+ onTranscript: () => {},
294
+ });
295
+
296
+ expect(sessionConfig).toMatchObject({
297
+ translation: { type: "one_way", target_language: "es" },
298
+ });
299
+
300
+ await provider.close();
301
+ });
302
+
303
+ test("passes auto-mode detection hints to Soniox language_hints", async () => {
304
+ const session = new FakeSession();
305
+ let sessionConfig: Record<string, unknown> | undefined;
306
+ const client = {
307
+ realtime: {
308
+ stt: (config: Record<string, unknown>) => {
309
+ sessionConfig = config;
310
+ return session;
311
+ },
312
+ },
313
+ };
314
+
315
+ const provider = await createSonioxProvider({
316
+ scope: "user_hints",
317
+ language: "auto",
318
+ languageHints: ["ja", "en-US"],
319
+ client: client as never,
320
+ onTranscript: () => {},
321
+ });
322
+
323
+ expect(sessionConfig).toMatchObject({
324
+ enable_language_identification: true,
325
+ language_hints: ["ja", "en"],
326
+ });
327
+
328
+ await provider.close();
329
+ });
330
+
331
+ test("sends the Mentra activation phrase as recognition context", async () => {
332
+ const session = new FakeSession();
333
+ let sessionConfig: Record<string, unknown> | undefined;
334
+ const client = {
335
+ realtime: {
336
+ stt: (config: Record<string, unknown>) => {
337
+ sessionConfig = config;
338
+ return session;
339
+ },
340
+ },
341
+ };
342
+
343
+ const provider = await createSonioxProvider({
344
+ scope: "user_test",
345
+ language: "auto",
346
+ client: client as never,
347
+ onTranscript: () => {},
348
+ });
349
+
350
+ expect(sessionConfig).toMatchObject({
351
+ context: {
352
+ terms: ["Mentra", "Hey Mentra"],
353
+ text: "Mentra, Hey Mentra (an AI assistant)",
354
+ },
355
+ });
356
+
357
+ await provider.close();
358
+ });
359
+ });
360
+
361
+ describe("SonioxProvider utterance lifecycle", () => {
362
+ test("endpoint character overlap keeps token timing without losing interim/final text", async () => {
363
+ const {session, provider, events} = await makeProvider();
364
+ try {
365
+ provider.writeAudio(new Int16Array(480), {sessionTag: 1, offsetMs: 0});
366
+ session.result([{text: "Hello wonderful world", confidence: 1, is_final: false, start_ms: 0, end_ms: 10}]);
367
+ session.endpoint();
368
+ session.result([{text: "wonderful world again", confidence: 1, is_final: false, start_ms: 10, end_ms: 20}]);
369
+ const interim = events.at(-1)!;
370
+ expect(interim.text).toBe("Hello wonderful world again");
371
+ expect(interim.tokens?.map((t) => t.text).join("")).toBe(interim.text);
372
+ expect(interim.tokens?.at(-1)?.audioPosition).toEqual({sessionTag: 1, offsetMs: 10});
373
+ session.emit("finalized");
374
+ expect(events.at(-1)?.tokens?.map((t) => t.text).join("")).toBe("Hello wonderful world again");
375
+ } finally {await provider.close()}
376
+ });
377
+ test("timing survives repeated/compacted windows, endpoint merge and mapping pruning", async () => {
378
+ const {session, events, provider} = await makeProvider();
379
+ const word = (text: string, start_ms: number): FakeToken => ({
380
+ text, start_ms, end_ms: start_ms + 10, confidence: 1, is_final: true,
381
+ });
382
+ try {
383
+ provider.writeAudio(new Int16Array(320), {sessionTag: 1, offsetMs: 100});
384
+ provider.writeAudio(new Int16Array(320), {sessionTag: 1, offsetMs: 120});
385
+ const before = word("BEFORE ", 0), after = word("AFTER", 10), more = word(" MORE", 20);
386
+ session.emit("result", {tokens: [before, after], final_audio_proc_ms: 20});
387
+ session.endpoint();
388
+ session.result([before, after, more]);
389
+ session.result([more]);
390
+ session.emit("finalized");
391
+ const final = events.at(-1)!;
392
+ expect(final.text).toBe("BEFORE AFTER MORE");
393
+ expect(final.tokens?.map((t) => t.text)).toEqual(["BEFORE ", "AFTER", " MORE"]);
394
+ expect(final.tokens?.map((t) => t.audioPosition)).toEqual([
395
+ {sessionTag: 1, offsetMs: 100}, {sessionTag: 1, offsetMs: 110}, {sessionTag: 1, offsetMs: 120},
396
+ ]);
397
+ expect(events.filter((event) => event.isFinal)).toHaveLength(1);
398
+ } finally {await provider.close()}
399
+ });
400
+
401
+ test("provider replacement restarts its sample clock without reusing old frame positions", async () => {
402
+ const {client, sessions} = multiSessionClient();
403
+ const events: TranscriptEvent[] = [];
404
+ const provider = await createSonioxProvider({scope: "timed-heal", language: "auto", client: client as never, onTranscript: (event) => events.push(event)});
405
+ const timed = (text: string): FakeToken => ({text, confidence: 1, is_final: true, start_ms: 0, end_ms: 10});
406
+ try {
407
+ provider.writeAudio(new Int16Array(160), {sessionTag: 1, offsetMs: 10});
408
+ sessions[0]!.result([timed("BEFORE ")]);
409
+ sessions[0]!.disconnect();
410
+ await wait(50);
411
+ provider.writeAudio(new Int16Array(160), {sessionTag: 1, offsetMs: 100});
412
+ sessions[1]!.result([timed("AFTER")]);
413
+ expect(events.at(-1)?.text).toBe("BEFORE AFTER");
414
+ expect(events.at(-1)?.tokens?.map((t) => t.audioPosition?.offsetMs)).toEqual([10, 100]);
415
+ } finally {await provider.close()}
416
+ });
417
+
418
+ test("retains timed confirmed tokens and replaces interims through the final", async () => {
419
+ const session = new FakeSession();
420
+ const events: TranscriptEvent[] = [];
421
+ const provider = await createSonioxProvider({
422
+ scope: "timing",
423
+ language: "auto",
424
+ client: fakeClient(session),
425
+ onTranscript: (event) => events.push(event),
426
+ });
427
+ try {
428
+ provider.writeAudio(new Int16Array(160), { sessionTag: 1, offsetMs: 0 });
429
+ provider.writeAudio(new Int16Array(320), { sessionTag: 1, offsetMs: 20 });
430
+ const before = {
431
+ text: "BEFORE ",
432
+ is_final: true,
433
+ confidence: 1,
434
+ start_ms: 0,
435
+ end_ms: 10,
436
+ };
437
+ session.result([
438
+ before,
439
+ {
440
+ text: "guess",
441
+ is_final: false,
442
+ confidence: 1,
443
+ start_ms: 10,
444
+ end_ms: 20,
445
+ },
446
+ ]);
447
+ session.result([
448
+ {
449
+ text: "AFTER",
450
+ is_final: true,
451
+ confidence: 1,
452
+ start_ms: 10,
453
+ end_ms: 20,
454
+ },
455
+ ]);
456
+ expect(events.at(-1)?.text).toBe("BEFORE AFTER");
457
+ expect(
458
+ events.at(-1)?.tokens?.map((token) => token.audioPosition),
459
+ ).toEqual([
460
+ { sessionTag: 1, offsetMs: 0 },
461
+ { sessionTag: 1, offsetMs: 20 },
462
+ ]);
463
+ session.emit("finalized");
464
+ expect(events.at(-1)?.isFinal).toBe(true);
465
+ expect(events.at(-1)?.tokens?.map((token) => token.text)).toEqual([
466
+ "BEFORE ",
467
+ "AFTER",
468
+ ]);
469
+ expect(events.at(-1)?.tokens?.every((token) => token.isFinal)).toBe(true);
470
+ expect(events.at(-1)?.frameTimelineVersion).toBe(1);
471
+ } finally {
472
+ await provider.close();
473
+ }
474
+ });
475
+ test("missing token timing retains the negotiated occurrence capability through its final", async () => {
476
+ const {session, provider, events} = await makeProvider();
477
+ try {
478
+ provider.writeAudio(new Int16Array(160), {sessionTag: 1, offsetMs: 0});
479
+ session.result([{text: "unknown", confidence: 1, is_final: false}]);
480
+ expect(events.at(-1)?.frameTimelineVersion).toBe(1);
481
+ expect(events.at(-1)?.tokens).toEqual([]);
482
+ session.endpoint();
483
+ // A legacy frame arriving while the prior final is pending does not
484
+ // change that positioned occurrence's missing-timing policy.
485
+ provider.writeAudio(new Int16Array(160));
486
+ session.emit("finalized");
487
+ expect(events.at(-1)?.frameTimelineVersion).toBe(1);
488
+ expect(events.at(-1)?.tokens).toEqual([]);
489
+ } finally {await provider.close()}
490
+ });
491
+ test("does not churn finals/utteranceIds when the rolling window's speaker flips mid-utterance", async () => {
492
+ const { session, events, provider } = await makeProvider();
493
+
494
+ // Round 1: rolling window where the (single, non-final) token is speaker "1".
495
+ session.result([
496
+ { text: "Okay ", confidence: 0.9, is_final: false, speaker: "1" },
497
+ ]);
498
+
499
+ // Round 2: SAME logical utterance, but Soniox re-diarized the window — the
500
+ // first token now reads speaker "2", and more text has streamed in. Under
501
+ // the old per-token speaker-compare this would emitFinal + mint a new id.
502
+ session.result([
503
+ { text: "Okay ", confidence: 0.9, is_final: false, speaker: "2" },
504
+ { text: "um I should ", confidence: 0.9, is_final: false, speaker: "2" },
505
+ ]);
506
+
507
+ // Round 3: window keeps growing, speaker flips back to "1" — still one
508
+ // logical utterance, no endpoint yet.
509
+ session.result([
510
+ { text: "Okay um I should ", confidence: 0.9, is_final: false, speaker: "1" },
511
+ { text: "buy my ticket", confidence: 0.9, is_final: false, speaker: "1" },
512
+ ]);
513
+
514
+ // Before the endpoint: every event so far must be an interim, all sharing
515
+ // ONE utteranceId. No finals, no new ids — i.e. no pile-up.
516
+ expect(events.length).toBeGreaterThan(0);
517
+ expect(events.every((e) => e.isFinal === false)).toBe(true);
518
+ const interimIds = new Set(events.map((e) => e.utteranceId));
519
+ expect(interimIds.size).toBe(1);
520
+ const utteranceId = events[0]!.utteranceId;
521
+ expect(utteranceId).toBeDefined();
522
+
523
+ // The interim text grows in place (cumulative) under the same card.
524
+ expect(events.at(-1)!.text).toBe("Okay um I should buy my ticket");
525
+
526
+ // Now the real utterance boundary fires: exactly ONE final, same id.
527
+ session.endpoint();
528
+ await wait(5);
529
+
530
+ const finals = events.filter((e) => e.isFinal);
531
+ expect(finals.length).toBe(1);
532
+ expect(finals[0]!.utteranceId).toBe(utteranceId);
533
+ expect(finals[0]!.text).toBe("Okay um I should buy my ticket");
534
+
535
+ await provider.close();
536
+ });
537
+
538
+ test("emits one final per endpoint-bounded utterance and starts a fresh id after", async () => {
539
+ const { session, events, provider } = await makeProvider();
540
+
541
+ // Utterance A.
542
+ session.result([
543
+ { text: "first utterance", confidence: 0.9, is_final: false, speaker: "1" },
544
+ ]);
545
+ session.endpoint();
546
+
547
+ // Utterance B (after a commit, a fresh id is minted lazily on next token).
548
+ session.result([
549
+ { text: "second utterance", confidence: 0.9, is_final: false, speaker: "1" },
550
+ ]);
551
+ session.endpoint();
552
+ await wait(5);
553
+
554
+ const finals = events.filter((e) => e.isFinal);
555
+ expect(finals.length).toBe(2);
556
+ expect(finals[0]!.text).toBe("first utterance");
557
+ expect(finals[1]!.text).toBe("second utterance");
558
+ // Distinct utterances → distinct ids.
559
+ expect(finals[0]!.utteranceId).not.toBe(finals[1]!.utteranceId);
560
+
561
+ await provider.close();
562
+ });
563
+
564
+ test("merges a repeated rolling window after endpoint instead of emitting a duplicate utterance", async () => {
565
+ const { session, events, provider } = await makeProvider();
566
+
567
+ session.result([
568
+ { text: "Can you hear me?", confidence: 0.9, is_final: false, speaker: "1" },
569
+ ]);
570
+ const utteranceId = events.at(-1)!.utteranceId;
571
+
572
+ // Soniox can fire an endpoint, then keep the previous words in the next
573
+ // rolling window. This is the exact shape that produced a duplicate local
574
+ // captions card in E2E testing.
575
+ session.endpoint();
576
+ session.result([
577
+ { text: " Can", confidence: 0.9, is_final: false, speaker: "1" },
578
+ ]);
579
+ session.result([
580
+ {
581
+ text: " Can you hear me? What did you do?",
582
+ confidence: 0.9,
583
+ is_final: false,
584
+ speaker: "1",
585
+ },
586
+ ]);
587
+ session.endpoint();
588
+ await wait(5);
589
+
590
+ const finals = events.filter((e) => e.isFinal);
591
+ expect(finals.length).toBe(1);
592
+ expect(finals[0]!.utteranceId).toBe(utteranceId);
593
+ expect(finals[0]!.text).toBe("Can you hear me? What did you do?");
594
+
595
+ const ids = new Set(events.map((e) => e.utteranceId));
596
+ expect(ids.size).toBe(1);
597
+
598
+ await provider.close();
599
+ });
600
+
601
+ test("keeps fuller interim when Soniox later emits a shorter finalized window", async () => {
602
+ const { session, events, provider } = await makeProvider();
603
+
604
+ const fullText =
605
+ "Two app fan out test, local captions and local merge should both receive this final transcript.";
606
+ const regressedText =
607
+ "Two app fan out test, local cap both receive this final transcript.";
608
+
609
+ session.result([
610
+ { text: fullText, confidence: 0.9, is_final: false, speaker: "1" },
611
+ ]);
612
+ session.result([
613
+ { text: regressedText, confidence: 0.9, is_final: true, speaker: "1" },
614
+ ]);
615
+ session.endpoint();
616
+ await wait(5);
617
+
618
+ expect(events.some((e) => e.text === regressedText)).toBe(false);
619
+ expect(events.at(-1)).toMatchObject({
620
+ text: fullText,
621
+ isFinal: true,
622
+ });
623
+
624
+ await provider.close();
625
+ });
626
+
627
+ test("does not reuse the first utterance id across provider instances with the same scope", async () => {
628
+ const sessionA = new FakeSession();
629
+ const eventsA: TranscriptEvent[] = [];
630
+ const providerA = await createSonioxProvider({
631
+ scope: "user_test",
632
+ language: "auto",
633
+ client: fakeClient(sessionA) as never,
634
+ onTranscript: (e) => eventsA.push(e),
635
+ });
636
+
637
+ const sessionB = new FakeSession();
638
+ const eventsB: TranscriptEvent[] = [];
639
+ const providerB = await createSonioxProvider({
640
+ scope: "user_test",
641
+ language: "auto",
642
+ client: fakeClient(sessionB) as never,
643
+ onTranscript: (e) => eventsB.push(e),
644
+ });
645
+
646
+ sessionA.result([
647
+ { text: "first provider", confidence: 0.9, is_final: false, speaker: "1" },
648
+ ]);
649
+ sessionB.result([
650
+ { text: "second provider", confidence: 0.9, is_final: false, speaker: "1" },
651
+ ]);
652
+
653
+ expect(eventsA[0]!.utteranceId).toBeDefined();
654
+ expect(eventsB[0]!.utteranceId).toBeDefined();
655
+ expect(eventsA[0]!.utteranceId).not.toBe(eventsB[0]!.utteranceId);
656
+
657
+ await providerA.close();
658
+ await providerB.close();
659
+ });
660
+
661
+ test("close() flushes an in-flight utterance as a single final", async () => {
662
+ const { session, events, provider } = await makeProvider();
663
+
664
+ session.result([
665
+ { text: "dangling text", confidence: 0.9, is_final: false, speaker: "3" },
666
+ ]);
667
+
668
+ // No endpoint — detach mid-utterance. close() should commit it once.
669
+ await provider.close();
670
+
671
+ const finals = events.filter((e) => e.isFinal);
672
+ expect(finals.length).toBe(1);
673
+ expect(finals[0]!.text).toBe("dangling text");
674
+ });
675
+ });
676
+
677
+ describe("SonioxProvider audio-gap pause/resume", () => {
678
+ test("auto-pauses after an idle audio gap and commits buffered interim text", async () => {
679
+ await withFastGapConfig(async () => {
680
+ const { session, events, provider } = await makeProvider();
681
+
682
+ session.result([
683
+ { text: "pending words", confidence: 0.9, is_final: false, speaker: "1" },
684
+ ]);
685
+ const utteranceId = events.at(-1)!.utteranceId;
686
+
687
+ await wait(50);
688
+
689
+ expect(session.pauseCount).toBe(1);
690
+ const finals = events.filter((e) => e.isFinal);
691
+ expect(finals.length).toBe(1);
692
+ expect(finals[0]!.text).toBe("pending words");
693
+ expect(finals[0]!.utteranceId).toBe(utteranceId);
694
+
695
+ await provider.close();
696
+ });
697
+ });
698
+
699
+ test("resumes before sending the first audio chunk after an idle pause", async () => {
700
+ await withFastGapConfig(async () => {
701
+ const { session, provider } = await makeProvider();
702
+
703
+ await wait(50);
704
+ expect(session.pauseCount).toBe(1);
705
+
706
+ provider.writeAudio(new Int16Array([1, 2, 3, 4]));
707
+
708
+ expect(session.resumeCount).toBe(1);
709
+ expect(session.sendAudioCount).toBe(1);
710
+
711
+ await provider.close();
712
+ });
713
+ });
714
+
715
+ test("does not auto-pause repeatedly while already paused", async () => {
716
+ await withFastGapConfig(async () => {
717
+ const { session, provider } = await makeProvider();
718
+
719
+ await wait(80);
720
+
721
+ expect(session.pauseCount).toBe(1);
722
+
723
+ await provider.close();
724
+ });
725
+ });
726
+ });
727
+
728
+ /**
729
+ * Self-heal: the "captions freeze after a hostile network drop" wedge.
730
+ *
731
+ * The underlying Soniox session can die WITHOUT our close() (network blip,
732
+ * Soniox idle timeout). The provider object stays in the worker's per-user
733
+ * provider map, keyed by subscription identity, and the worker's reconcile is
734
+ * idempotent by that key — so it never recreates the provider. Without
735
+ * self-heal, audio keeps flowing into the dead session and transcripts stop
736
+ * until a full app restart forces a real detach. These tests assert the
737
+ * provider reconnects its own session in place and resumes emitting.
738
+ */
739
+ describe("SonioxProvider self-heal reconnect", () => {
740
+ test("resumes transcripts after an unexpected upstream disconnect", async () => {
741
+ const { client, sessions } = multiSessionClient();
742
+ const events: TranscriptEvent[] = [];
743
+ const provider = await createSonioxProvider({
744
+ scope: "user_heal",
745
+ language: "auto",
746
+ client: client as never,
747
+ onTranscript: (e) => events.push(e),
748
+ });
749
+
750
+ const first = sessions[0]!;
751
+ // Transcripts flow on the original session.
752
+ first.result([{ text: "hello", confidence: 0.9, is_final: false, speaker: "1" }]);
753
+ expect(events.at(-1)!.text).toBe("hello");
754
+
755
+ // The upstream session dies unexpectedly (the hostile-drop wedge).
756
+ first.disconnect();
757
+
758
+ // The provider should build + connect a replacement session.
759
+ await wait(50);
760
+ expect(sessions.length).toBe(2);
761
+ const second = sessions[1]!;
762
+ expect(second.connectCount).toBe(1);
763
+
764
+ // Audio that arrives after the heal must reach the NEW session, and its
765
+ // transcripts must reach the consumer — captions resume, no restart needed.
766
+ provider.writeAudio(new Int16Array([1, 2, 3, 4]));
767
+ expect(second.sendAudioCount).toBe(1);
768
+ second.result([{ text: "world", confidence: 0.9, is_final: false, speaker: "1" }]);
769
+ expect(events.at(-1)!.text).toBe("world");
770
+
771
+ await provider.close();
772
+ });
773
+
774
+ test("retries with backoff when a reconnect attempt fails, then succeeds", async () => {
775
+ // Mint sessions where the FIRST replacement's connect() rejects once, so the
776
+ // self-heal loop must back off and try again before it gets a live session.
777
+ const sessions: FakeSession[] = [];
778
+ let nextFailCount = 0;
779
+ const client = {
780
+ realtime: {
781
+ stt: () => {
782
+ const s = new FakeSession();
783
+ s.failNextConnects = nextFailCount;
784
+ nextFailCount = 0;
785
+ sessions.push(s);
786
+ return s;
787
+ },
788
+ },
789
+ };
790
+ const errors: Error[] = [];
791
+ const provider = await createSonioxProvider({
792
+ scope: "user_retry",
793
+ language: "auto",
794
+ client: client as never,
795
+ onTranscript: () => {},
796
+ onError: (e) => errors.push(e),
797
+ });
798
+
799
+ const first = sessions[0]!;
800
+ // Arm the next-built session to fail its first connect, then drop the live
801
+ // one. Heal builds replacement #1 (connect rejects) → backs off → builds
802
+ // replacement #2 (connect ok).
803
+ nextFailCount = 1;
804
+ first.disconnect();
805
+
806
+ await wait(80);
807
+
808
+ // At least two replacements were built (the failed one + the live one), and
809
+ // self-heal did NOT give up (no error surfaced).
810
+ expect(sessions.length).toBeGreaterThanOrEqual(3);
811
+ expect(errors.length).toBe(0);
812
+
813
+ // The final session is live and takes audio.
814
+ const last = sessions.at(-1)!;
815
+ provider.writeAudio(new Int16Array([1, 2]));
816
+ expect(last.sendAudioCount).toBe(1);
817
+
818
+ await provider.close();
819
+ });
820
+
821
+ test("does NOT reconnect on an expected close()", async () => {
822
+ const { client, sessions } = multiSessionClient();
823
+ const provider = await createSonioxProvider({
824
+ scope: "user_close",
825
+ language: "auto",
826
+ client: client as never,
827
+ onTranscript: () => {},
828
+ });
829
+
830
+ // close() finishes the session, which fires a `disconnected` on the real
831
+ // SDK. That expected disconnect must NOT spin up a replacement session.
832
+ await provider.close();
833
+ sessions[0]!.disconnect(); // late teardown event, post-close
834
+ await wait(30);
835
+
836
+ expect(sessions.length).toBe(1);
837
+ });
838
+
839
+ test("drops audio frames while a reconnect is in flight", async () => {
840
+ const { client, sessions } = multiSessionClient();
841
+ const provider = await createSonioxProvider({
842
+ scope: "user_gap",
843
+ language: "auto",
844
+ client: client as never,
845
+ onTranscript: () => {},
846
+ // Slow the heal so we can observe the in-flight window.
847
+ onError: () => {},
848
+ });
849
+
850
+ const first = sessions[0]!;
851
+ first.disconnect();
852
+ // Immediately after the drop, before the replacement connects, frames are
853
+ // dropped (no live session to take them) — no throw, no send on the dead one.
854
+ const beforeSends = first.sendAudioCount;
855
+ provider.writeAudio(new Int16Array([9, 9]));
856
+ expect(first.sendAudioCount).toBe(beforeSends);
857
+
858
+ await wait(50);
859
+ await provider.close();
860
+ });
861
+ });
cloud-v2/packages/runtime/src/services/audio/providers/soniox.ts ADDED
@@ -0,0 +1,1062 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview SonioxProvider — real Soniox streaming transcription.
3
+ *
4
+ * Wraps `@soniox/node`'s `RealtimeSttSession` behind the cloud-v2
5
+ * `TranscriptionProvider` interface. One Soniox session per active
6
+ * subscription (per user). Sends PCM as it arrives, emits transcripts
7
+ * back via the provider callback.
8
+ *
9
+ * Configuration:
10
+ * - Requires `SONIOX_API_KEY` env var.
11
+ * - Model defaults to `"stt-rt-v5"`; override via `SONIOX_MODEL`.
12
+ * - Audio format hardcoded to s16le, 16kHz, mono (matches our LC3 output).
13
+ *
14
+ * What this does NOT include (deferred from v1's SonioxSdkStream port):
15
+ * - Endpoint debounce / merge (mid-utterance endpoint suppression)
16
+ * - Token compaction handling beyond what the SDK does
17
+ *
18
+ * Those land as we hit them in real-traffic testing. The minimum here is
19
+ * enough to produce real transcripts from real audio; refinements come from
20
+ * observing actual usage.
21
+ *
22
+ * Spec: docs/issues/003-audio/design.md.
23
+ */
24
+
25
+ import {
26
+ SonioxNodeClient,
27
+ type RealtimeResult,
28
+ type RealtimeSttSession,
29
+ type SttSessionConfig,
30
+ } from "@soniox/node";
31
+ import { randomUUID } from "node:crypto";
32
+
33
+ import type {
34
+ ProviderOptions,
35
+ TranscriptionProvider,
36
+ TranscriptEvent,
37
+ } from "./provider";
38
+ import { createLogger } from "@mentra/cloud-shared";
39
+ import type { AudioPosition, TranscriptionToken } from "@mentra/cloud-protocol";
40
+ import { AudioTimeline } from "./audioTimeline";
41
+
42
+ const logger = createLogger("runtime").child({ module: "soniox" });
43
+
44
+ const SONIOX_MODEL = process.env.SONIOX_MODEL ?? "stt-rt-v5";
45
+
46
+ /** Preserve timing through the adapter's existing overlap merge; never guess alignment. */
47
+ function mergeTimedTokens(
48
+ text: string,
49
+ left: TranscriptionToken[],
50
+ right: TranscriptionToken[],
51
+ ): TranscriptionToken[] {
52
+ const a = left
53
+ .map((t) => t.text)
54
+ .join("")
55
+ .trim();
56
+ const b = right
57
+ .map((t) => t.text)
58
+ .join("")
59
+ .trim();
60
+ if (text === b) return right;
61
+ if (text === a) return left;
62
+ // The existing text merger can overlap inside a provider token. Remove
63
+ // duplicated characters without inventing a later timestamp for that token.
64
+ // Its retained suffix keeps the original start and crossing tokens remain
65
+ // excluded by the phone subscription cutoff.
66
+ const slice = (tokens: TranscriptionToken[], start: number, end: number) => {
67
+ let offset = 0;
68
+ return tokens.flatMap((token) => {
69
+ const from = Math.max(0, start - offset);
70
+ const to = Math.min(token.text.length, end - offset);
71
+ offset += token.text.length;
72
+ return to > from ? [{...token, text: token.text.slice(from, to)}] : [];
73
+ });
74
+ };
75
+ const rawLeft = left.map((token) => token.text).join("");
76
+ const rawRight = right.map((token) => token.text).join("");
77
+ const suffix = text.slice(a.length);
78
+ if (text.startsWith(a) && b.endsWith(suffix)) {
79
+ const prefixTokens = slice(left, rawLeft.indexOf(a), rawLeft.indexOf(a) + a.length);
80
+ const suffixStart = rawRight.indexOf(b) + b.length - suffix.length;
81
+ return [...prefixTokens, ...slice(right, suffixStart, suffixStart + suffix.length)];
82
+ }
83
+ return [];
84
+ }
85
+ function audioGapConfig(): { checkIntervalMs: number; thresholdMs: number } {
86
+ return {
87
+ checkIntervalMs: Number(process.env.SONIOX_GAP_CHECK_INTERVAL_MS ?? 1_000),
88
+ thresholdMs: Number(process.env.SONIOX_AUDIO_GAP_THRESHOLD_MS ?? 2_000),
89
+ };
90
+ }
91
+
92
+ function endpointDebounceMs(): number {
93
+ return Number(process.env.SONIOX_ENDPOINT_DEBOUNCE_MS ?? 500);
94
+ }
95
+
96
+ const MIN_ENDPOINT_OVERLAP_CHARS = 3;
97
+ const MIN_REGRESSION_DROP_CHARS = 12;
98
+ const MIN_REGRESSION_PREFIX_CHARS = 12;
99
+
100
+ /**
101
+ * Self-heal backoff for an unexpected Soniox session drop.
102
+ *
103
+ * The underlying Soniox WebSocket can die WITHOUT our `close()` being called:
104
+ * a network blip, a Soniox-side idle timeout, or a transient upstream error.
105
+ * When that happens the provider object is still held (alive) in the worker's
106
+ * per-user provider map, keyed by subscription identity — and the worker's
107
+ * reconcile is idempotent by that key, so it will NEVER recreate the provider.
108
+ * Audio keeps flowing into a dead session and transcripts silently stop.
109
+ *
110
+ * This is exactly the "captions freeze after a hostile network drop" wedge: a
111
+ * clean pod-roll recovers (it DETACHes the user → the provider map is cleared →
112
+ * a fresh ATTACH recreates providers), but a same-pod reconnect keeps the same
113
+ * worker + the same (now-dead) provider, so only a full app restart recovers.
114
+ *
115
+ * The fix is for the provider to reconnect its OWN Soniox session in place on an
116
+ * unexpected drop, so its identity in the worker map stays valid and transcripts
117
+ * resume without any teardown/recreate. Bounded retries with capped backoff; we
118
+ * give up (and surface onError) only after exhausting them.
119
+ */
120
+ /**
121
+ * Read the self-heal backoff tunables. Read per-provider (not at module load)
122
+ * so tests can shrink the delays via env before constructing a provider; in
123
+ * production these are stable for the process lifetime.
124
+ */
125
+ function reconnectConfig(): { baseMs: number; maxMs: number; maxAttempts: number } {
126
+ return {
127
+ baseMs: Number(process.env.SONIOX_RECONNECT_BASE_MS ?? 500),
128
+ maxMs: Number(process.env.SONIOX_RECONNECT_MAX_MS ?? 8_000),
129
+ maxAttempts: Number(process.env.SONIOX_RECONNECT_MAX_ATTEMPTS ?? 10),
130
+ };
131
+ }
132
+
133
+ export interface CreateSonioxProviderOptions extends ProviderOptions {
134
+ /** Provide the Soniox client to reuse a single client across multiple streams. */
135
+ client?: SonioxNodeClient;
136
+ /**
137
+ * If set, configure Soniox one-way translation. Result tokens with
138
+ * `translation_status: "translation"` are emitted; original tokens are
139
+ * dropped. If unset, the provider behaves as a transcription stream
140
+ * (all tokens emitted as source-language text).
141
+ */
142
+ targetLanguage?: string;
143
+ }
144
+
145
+ /**
146
+ * Build Soniox `language_hints` from the subscription. A specific language is
147
+ * its own hint (region stripped: "en-US" -> "en"). For "auto" we pass the
148
+ * miniapp's detection hints, each reduced to Soniox's bare-code format and
149
+ * deduped; unknown/empty yields undefined (no hints). Passing a BCP-47 tag or
150
+ * an unrecognized code makes Soniox reject the session ("Invalid language
151
+ * hint"), so everything is normalized here (issue 021).
152
+ */
153
+ export function sonioxLanguageHints(
154
+ language: string | undefined,
155
+ hints: string[] | undefined,
156
+ ): string[] | undefined {
157
+ const toBareCode = (code: string) => code.split("-")[0].toLowerCase();
158
+ if (language && language !== "auto") {
159
+ return [toBareCode(language)];
160
+ }
161
+ if (!hints || hints.length === 0) return undefined;
162
+ const bare = [...new Set(hints.map(toBareCode).filter(Boolean))];
163
+ return bare.length > 0 ? bare : undefined;
164
+ }
165
+
166
+ /**
167
+ * Soniox one-way translation target. Like `language_hints`, Soniox's
168
+ * `translation.target_language` takes a bare ISO 639-1 code — a BCP-47 tag
169
+ * ("es-ES") is rejected with "Invalid language in translation.target_language"
170
+ * and kills the session, so strip the region (mirrors v1's SonioxSdkStream,
171
+ * which used `targetLanguage.split("-")[0]`). Subscription keys and result
172
+ * routing keep the full tag; only the provider config is reduced (issue 021).
173
+ */
174
+ export function sonioxTranslationTarget(target: string): string {
175
+ return target.split("-")[0].toLowerCase();
176
+ }
177
+
178
+ /** Shared client per worker. Soniox SDK is happy with one client for many streams. */
179
+ let sharedClient: SonioxNodeClient | null = null;
180
+ function getClient(): SonioxNodeClient {
181
+ if (sharedClient) return sharedClient;
182
+ const apiKey = process.env.SONIOX_API_KEY;
183
+ if (!apiKey) {
184
+ throw new Error(
185
+ "SONIOX_API_KEY is not set — required to use the soniox provider. Run Cloud V2 through Doppler with access to the cloud-v2/dev config.",
186
+ );
187
+ }
188
+ sharedClient = new SonioxNodeClient({ api_key: apiKey });
189
+ return sharedClient;
190
+ }
191
+
192
+ export async function createSonioxProvider(
193
+ opts: CreateSonioxProviderOptions,
194
+ ): Promise<TranscriptionProvider> {
195
+ const client = opts.client ?? getClient();
196
+ const gapConfig = audioGapConfig();
197
+ const endpointDebounce = endpointDebounceMs();
198
+
199
+ // Build session config. For language="auto" we enable detection; for a
200
+ // specific code we pass it as hint with detection still on. (Letting
201
+ // Soniox identify even when hinted is robust to user accent / code-switch.)
202
+ //
203
+ // Endpoint detection + diarization mirror v1's SonioxSdkStream:
204
+ // `enable_endpoint_detection` makes Soniox emit an `<end>` (surfaced here as
205
+ // the `endpoint` event) at natural utterance boundaries, which is our ONLY
206
+ // signal to commit a single FINAL per utterance (besides stream close).
207
+ // `enable_speaker_diarization` tags tokens with a `speaker` id used purely for
208
+ // the "Speaker N" label; a speaker change does NOT close an utterance, because
209
+ // Soniox re-diarizes its rolling window and the per-token speaker flickers
210
+ // mid-utterance (see handleResult for the full rationale).
211
+ // `max_endpoint_delay_ms` is the v2 SDK's analogue of v1's
212
+ // `max_non_final_tokens_duration_ms` (both bound how long Soniox waits before
213
+ // finalizing after speech ends); v1 used 2000ms.
214
+ const sessionConfig: SttSessionConfig = {
215
+ audio_format: "pcm_s16le",
216
+ sample_rate: 16_000,
217
+ num_channels: 1,
218
+ model: SONIOX_MODEL,
219
+ enable_language_identification: true,
220
+ enable_endpoint_detection: true,
221
+ enable_speaker_diarization: true,
222
+ max_endpoint_delay_ms: 2_000,
223
+ // Soniox hints take bare ISO 639-1 codes ("en"), but subscriptions carry
224
+ // BCP-47 tags ("en-US") — strip the region like v1's SonioxSdkStream did,
225
+ // or the hint is unrecognized and does nothing. For a specific language the
226
+ // language itself is the hint; for "auto" we pass the miniapp's detection
227
+ // hints (already bare codes) so language identification is biased without
228
+ // being pinned.
229
+ language_hints: sonioxLanguageHints(opts.language, opts.languageHints),
230
+ context: {
231
+ terms: ["Mentra", "Hey Mentra"],
232
+ text: "Mentra, Hey Mentra (an AI assistant)",
233
+ },
234
+ // For translation subs, configure Soniox's one-way translation. Result
235
+ // tokens then carry `translation_status: "original" | "translation"`
236
+ // and we filter to the translation half.
237
+ translation: opts.targetLanguage
238
+ ? { type: "one_way", target_language: sonioxTranslationTarget(opts.targetLanguage) }
239
+ : undefined,
240
+ } as SttSessionConfig;
241
+ const isTranslation = !!opts.targetLanguage;
242
+
243
+ // The live Soniox session. Mutable because we replace it on a self-heal
244
+ // reconnect (the old one is dead; a fresh `client.realtime.stt(...)` takes its
245
+ // place) while keeping THIS provider object — and therefore its identity in
246
+ // the worker's per-user provider map — stable.
247
+ let session: RealtimeSttSession = client.realtime.stt(sessionConfig);
248
+
249
+ // True once `close()` has run. Gates the self-heal path so an expected
250
+ // teardown (our own `session.finish()` → `disconnected`) does not trigger a
251
+ // reconnect, and so a frame written after close is dropped, not sent.
252
+ let closed = false;
253
+
254
+ // True while a self-heal reconnect is in flight. Audio written during this
255
+ // window is dropped (there is no live upstream session to take it); the rest
256
+ // of the pipeline already tolerates dropped frames during a reconnect.
257
+ let reconnecting = false;
258
+ let reconnectAttempts = 0;
259
+ let gapCheckInterval: ReturnType<typeof setInterval> | null = null;
260
+ let lastAudioWriteTime = Date.now();
261
+ let pausedForGap = false;
262
+
263
+ // === Per-utterance state (ports v1's SonioxTranscriptionProvider) ===
264
+ //
265
+ // Soniox emits a rolling token window where finalized tokens accumulate then
266
+ // may be compacted (pruned). To avoid the interim text shrinking under us we
267
+ // capture finalized text into `stablePrefix` and prepend it to non-final
268
+ // tokens on each result. All of this state is scoped to ONE utterance and is
269
+ // reset by `startNewUtterance` at each boundary.
270
+ let stablePrefix = "";
271
+ const audioTimeline = new AudioTimeline();
272
+ let providerGeneration = 0;
273
+ let confirmedTokens = new Map<string, TranscriptionToken>();
274
+ let lastTokens: TranscriptionToken[] = [];
275
+ let pendingTokens: TranscriptionToken[] = [];
276
+ let pendingTokenGeneration = 0;
277
+ let lastEmittedTokens: TranscriptionToken[] = [];
278
+ let frameTimelineVersion: 1 | undefined;
279
+ let activeFrameTimelineVersion: 1 | undefined;
280
+ let pendingFrameTimelineVersion: 1 | undefined;
281
+ const emitTranscript = (event: TranscriptEvent): void => {
282
+ opts.onTranscript({
283
+ ...event,
284
+ frameTimelineVersion: event.frameTimelineVersion ??
285
+ (event.tokens?.some((token) => token.audioPosition) ? 1 : undefined),
286
+ });
287
+ };
288
+ let prevFinalLen = 0;
289
+ // Last interim string we emitted for this utterance. Doubles as the text we
290
+ // commit when an utterance closes (endpoint / speaker change), and as a
291
+ // dedupe guard so we don't re-emit an unchanged interim.
292
+ let lastSentInterim = "";
293
+
294
+ // Translation subs only: parallel accumulator for the ORIGINAL-language
295
+ // tokens of the same utterance (same rolling-window semantics as above), so
296
+ // results can carry `originalText` for combined original+translated captions.
297
+ // Also tracks the detected SOURCE language — translation-status tokens carry
298
+ // the TARGET language, so the source must come from the original tokens.
299
+ let originalStablePrefix = "";
300
+ let originalPrevFinalLen = 0;
301
+ let lastOriginalText = "";
302
+ let currentSourceLanguage: string | undefined = undefined;
303
+
304
+ // Utterance correlation: interim + final events for one speech segment share
305
+ // a `utteranceId`, so the client (local-captions' `updateByUtteranceId`)
306
+ // keeps a single card and updates it in place, committing on the final.
307
+ let currentUtteranceId: string | null = null;
308
+ let currentSpeakerId: string | undefined = undefined;
309
+ let currentLanguage: string | undefined = undefined;
310
+
311
+ // Soniox endpoint is a soft signal. It can fire while the SDK still carries
312
+ // the same rolling-window text into the next result, which previously caused
313
+ // a duplicate new utterance/card. Hold the candidate final briefly, and if
314
+ // following results overlap, keep extending the original utterance instead.
315
+ let pendingFinalText = "";
316
+ let pendingFinalUtteranceId: string | null = null;
317
+ let pendingFinalSpeakerId: string | undefined = undefined;
318
+ let pendingFinalLanguage: string | undefined = undefined;
319
+ let pendingFinalOriginalText = "";
320
+ let pendingFinalSourceLanguage: string | undefined = undefined;
321
+ let pendingFinalStartMs: number | undefined = undefined;
322
+ let pendingFinalEndMs: number | undefined = undefined;
323
+ let pendingFinalTimer: ReturnType<typeof setTimeout> | null = null;
324
+
325
+ // Monotonic id minting: a provider-instance nonce prevents collisions when the
326
+ // cloud process/provider restarts with the same scope and sequence number.
327
+ // `opts.scope` (user + sub identity) keeps ids readable per subscription.
328
+ let utteranceSeq = 0;
329
+ const providerInstanceId = randomUUID();
330
+ const mintUtteranceId = (): string => {
331
+ utteranceSeq += 1;
332
+ return `utt_${opts.scope}_${providerInstanceId}_${utteranceSeq}`;
333
+ };
334
+
335
+ const startNewUtterance = (speakerId?: string, language?: string): void => {
336
+ activeFrameTimelineVersion = frameTimelineVersion;
337
+ currentUtteranceId = mintUtteranceId();
338
+ confirmedTokens = new Map();
339
+ lastTokens = [];
340
+ lastEmittedTokens = [];
341
+ currentSpeakerId = speakerId;
342
+ currentLanguage = language;
343
+ stablePrefix = "";
344
+ prevFinalLen = 0;
345
+ lastSentInterim = "";
346
+ originalStablePrefix = "";
347
+ originalPrevFinalLen = 0;
348
+ lastOriginalText = "";
349
+ currentSourceLanguage = undefined;
350
+ };
351
+
352
+ const resetActiveUtterance = (): void => {
353
+ activeFrameTimelineVersion = undefined;
354
+ confirmedTokens = new Map();
355
+ lastTokens = [];
356
+ lastEmittedTokens = [];
357
+ stablePrefix = "";
358
+ prevFinalLen = 0;
359
+ lastSentInterim = "";
360
+ originalStablePrefix = "";
361
+ originalPrevFinalLen = 0;
362
+ lastOriginalText = "";
363
+ currentSourceLanguage = undefined;
364
+ currentUtteranceId = null;
365
+ currentSpeakerId = undefined;
366
+ currentLanguage = undefined;
367
+ };
368
+
369
+ const emitFinalEvent = (event: {
370
+ text: string;
371
+ utteranceId?: string;
372
+ speakerId?: string;
373
+ language?: string;
374
+ originalText?: string;
375
+ sourceLanguage?: string;
376
+ startMs?: number;
377
+ endMs?: number;
378
+ tokens?: TranscriptionToken[];
379
+ frameTimelineVersion?: 1;
380
+ }): void => {
381
+ emitTranscript({
382
+ text: event.text,
383
+ isFinal: true,
384
+ utteranceId: event.utteranceId,
385
+ speakerId: event.speakerId,
386
+ language: event.language,
387
+ originalText: event.originalText || undefined,
388
+ sourceLanguage: event.sourceLanguage,
389
+ startMs: event.startMs,
390
+ endMs: event.endMs,
391
+ tokens: event.tokens?.map((token) => ({ ...token, isFinal: true })),
392
+ frameTimelineVersion: event.frameTimelineVersion,
393
+ });
394
+ };
395
+
396
+ const clearPendingFinal = (): void => {
397
+ if (pendingFinalTimer) {
398
+ clearTimeout(pendingFinalTimer);
399
+ pendingFinalTimer = null;
400
+ }
401
+ pendingFinalText = "";
402
+ pendingTokens = [];
403
+ pendingFrameTimelineVersion = undefined;
404
+ pendingFinalUtteranceId = null;
405
+ pendingFinalSpeakerId = undefined;
406
+ pendingFinalLanguage = undefined;
407
+ pendingFinalOriginalText = "";
408
+ pendingFinalSourceLanguage = undefined;
409
+ pendingFinalStartMs = undefined;
410
+ pendingFinalEndMs = undefined;
411
+ };
412
+
413
+ const tryMergeOverlap = (a: string, b: string): string | null => {
414
+ const left = a.trim();
415
+ const right = b.trim();
416
+ if (!left || !right) return null;
417
+ if (left === right || left.startsWith(right)) return left;
418
+ if (right.startsWith(left)) return left + right.slice(left.length);
419
+
420
+ const maxOverlap = Math.min(left.length, right.length);
421
+ for (let len = maxOverlap; len >= MIN_ENDPOINT_OVERLAP_CHARS; len -= 1) {
422
+ if (left.endsWith(right.slice(0, len))) {
423
+ return left + right.slice(len);
424
+ }
425
+ }
426
+ return null;
427
+ };
428
+
429
+ const isLikelyWindowRegression = (next: string, previous: string): boolean => {
430
+ const normalizedNext = next.trim();
431
+ const normalizedPrevious = previous.trim();
432
+ if (!normalizedNext || !normalizedPrevious) return false;
433
+ const drop = normalizedPrevious.length - normalizedNext.length;
434
+ if (drop < MIN_REGRESSION_DROP_CHARS) return false;
435
+
436
+ let sharedPrefix = 0;
437
+ const maxPrefix = Math.min(
438
+ normalizedNext.length,
439
+ normalizedPrevious.length,
440
+ );
441
+ while (
442
+ sharedPrefix < maxPrefix &&
443
+ normalizedNext[sharedPrefix] === normalizedPrevious[sharedPrefix]
444
+ ) {
445
+ sharedPrefix += 1;
446
+ }
447
+
448
+ return (
449
+ sharedPrefix >=
450
+ Math.min(MIN_REGRESSION_PREFIX_CHARS, normalizedNext.length)
451
+ );
452
+ };
453
+
454
+ const commitPendingFinal = (): void => {
455
+ if (!pendingFinalText) {
456
+ clearPendingFinal();
457
+ return;
458
+ }
459
+
460
+ const committedText = pendingFinalText;
461
+ const committedUtteranceId = pendingFinalUtteranceId;
462
+ emitFinalEvent({
463
+ text: committedText,
464
+ utteranceId: committedUtteranceId ?? undefined,
465
+ speakerId: pendingFinalSpeakerId,
466
+ language: pendingFinalLanguage,
467
+ originalText: pendingFinalOriginalText,
468
+ sourceLanguage: pendingFinalSourceLanguage,
469
+ startMs: pendingFinalStartMs,
470
+ endMs: pendingFinalEndMs,
471
+ tokens: pendingTokens,
472
+ frameTimelineVersion: pendingFrameTimelineVersion,
473
+ });
474
+ if (
475
+ committedUtteranceId &&
476
+ currentUtteranceId === committedUtteranceId &&
477
+ lastSentInterim.trim() === committedText
478
+ ) {
479
+ resetActiveUtterance();
480
+ }
481
+ clearPendingFinal();
482
+ };
483
+
484
+ const schedulePendingFinalCommit = (): void => {
485
+ if (pendingFinalTimer) clearTimeout(pendingFinalTimer);
486
+ pendingFinalTimer = setTimeout(() => {
487
+ commitPendingFinal();
488
+ }, endpointDebounce);
489
+ };
490
+
491
+ const setPendingFinalFromActive = (text: string): void => {
492
+ pendingFinalText = text;
493
+ pendingTokens = lastEmittedTokens;
494
+ pendingTokenGeneration = providerGeneration;
495
+ pendingFrameTimelineVersion = activeFrameTimelineVersion;
496
+ pendingFinalUtteranceId = currentUtteranceId;
497
+ pendingFinalSpeakerId = currentSpeakerId;
498
+ pendingFinalLanguage = currentLanguage;
499
+ pendingFinalOriginalText = lastOriginalText;
500
+ pendingFinalSourceLanguage = currentSourceLanguage;
501
+ };
502
+
503
+ /**
504
+ * Commit the current utterance as a single FINAL and reset for the next one.
505
+ * Called only at a real utterance boundary: the Soniox `endpoint` event and
506
+ * stream `close()`. NOT on per-token speaker flicker (see handleResult). No-op
507
+ * if there is nothing buffered, so back-to-back boundaries don't emit empty
508
+ * finals.
509
+ */
510
+ const emitFinal = (startMs?: number, endMs?: number): void => {
511
+ const text = lastSentInterim.trim();
512
+ if (!text) {
513
+ // Nothing to commit; still close the utterance so the next token batch
514
+ // starts fresh.
515
+ resetActiveUtterance();
516
+ return;
517
+ }
518
+ emitFinalEvent({
519
+ text,
520
+ utteranceId: currentUtteranceId ?? undefined,
521
+ speakerId: currentSpeakerId,
522
+ language: currentLanguage,
523
+ originalText: lastOriginalText || undefined,
524
+ sourceLanguage: currentSourceLanguage,
525
+ startMs,
526
+ endMs,
527
+ tokens: lastEmittedTokens,
528
+ frameTimelineVersion: activeFrameTimelineVersion,
529
+ });
530
+ // Reset for the next utterance. A fresh id is minted lazily when the next
531
+ // token arrives (see handleResult).
532
+ resetActiveUtterance();
533
+ };
534
+
535
+ const handleResult = (result: RealtimeResult) => {
536
+ const allTokens = result.tokens ?? [];
537
+
538
+ // For translation subs, split the window: translation-status tokens are
539
+ // the emitted `text` (target language); original-status tokens feed the
540
+ // parallel `originalText` accumulator and the detected SOURCE language.
541
+ // For transcription subs, keep everything (translation_status will be
542
+ // 'none' since we didn't request translation).
543
+ //
544
+ // SAME-LANGUAGE PASSTHROUGH (issue 021 / OS-1762): when the spoken
545
+ // language already equals the translation target, Soniox skips translation
546
+ // entirely and emits plain transcription tokens with NO translation_status
547
+ // (verified empirically 2026-07-21: EN speech -> target en yields only
548
+ // untagged tokens; EN -> es yields original/translation pairs). Keep those
549
+ // untagged tokens as emitted text so target-language speech surfaces as a
550
+ // transcription instead of silently vanishing. Because the SAME session
551
+ // makes both the detection and the translation decision, this cannot
552
+ // double-emit: an utterance either has translation tokens (cross-language)
553
+ // or untagged tokens (same-language), never both halves for one segment.
554
+ const tokens = isTranslation
555
+ ? allTokens.filter(
556
+ (t) =>
557
+ (t as { translation_status?: string }).translation_status !==
558
+ "original",
559
+ )
560
+ : allTokens;
561
+ const originalTokens = isTranslation
562
+ ? allTokens.filter(
563
+ (t) =>
564
+ (t as { translation_status?: string }).translation_status ===
565
+ "original",
566
+ )
567
+ : [];
568
+
569
+ let interimText = "";
570
+ let language: string | undefined;
571
+ let startMs: number | undefined;
572
+ let endMs: number | undefined;
573
+ let currentFinalText = "";
574
+
575
+ for (const t of tokens) {
576
+ // First token of the stream (or first after a commit): open an utterance.
577
+ //
578
+ // IMPORTANT: we deliberately do NOT split the utterance when a token's
579
+ // `speaker` label differs from `currentSpeakerId`. Soniox delivers a
580
+ // ROLLING WINDOW that it RE-DIARIZES across results, so a given token's
581
+ // `speaker` can flicker/flip between rounds within one real utterance.
582
+ // The previous implementation called `emitFinal` + `startNewUtterance` on
583
+ // every such per-token change, which fired spuriously many times within a
584
+ // single utterance — committing a FINAL and minting a NEW utteranceId per
585
+ // partial. On the captions client that produced a pile-up of growing,
586
+ // cumulative cards (one per partial, uncorrelatable), worse with
587
+ // diarization. We instead finalize ONLY on the real utterance boundary:
588
+ // the Soniox `endpoint` event (`handleEndpoint`) and on `close()`.
589
+ //
590
+ // This mirrors the retired V1 Soniox stream behavior, whose `handleResult`
591
+ // used the LAST token's speaker for attribution and
592
+ // documents: "Speaker changes within the window do NOT rotate the
593
+ // utteranceId." Speaker is still tracked below for the "Speaker N" label;
594
+ // it just doesn't trigger a finalize/restart.
595
+ if (!currentUtteranceId) {
596
+ startNewUtterance(t.speaker, t.language ?? opts.language);
597
+ }
598
+
599
+ // Track the latest token's speaker so the emitted interim/final carries
600
+ // the current (dominant) speaker for the label — without splitting.
601
+ if (t.speaker) currentSpeakerId = t.speaker;
602
+ // Track detected language for output but DON'T split the utterance on a
603
+ // language change — Soniox's per-token language can flap mid-utterance.
604
+ if (t.language) {
605
+ language = t.language;
606
+ currentLanguage = t.language;
607
+ // Untagged tokens on a translation session are the same-language
608
+ // passthrough: their language IS the detected source. (Cross-language
609
+ // source tracking comes from the original-token loop below.)
610
+ if (
611
+ isTranslation &&
612
+ (t as { translation_status?: string }).translation_status == null
613
+ ) {
614
+ currentSourceLanguage = t.language;
615
+ }
616
+ }
617
+
618
+ if (t.is_final) {
619
+ currentFinalText += t.text;
620
+ if (t.start_ms != null && startMs == null) startMs = t.start_ms;
621
+ if (t.end_ms != null) endMs = t.end_ms;
622
+ } else {
623
+ interimText += t.text;
624
+ }
625
+ }
626
+
627
+ // Original-language tokens (translation subs only): same rolling-window
628
+ // accumulation as the main stream, into the parallel buffers. The first
629
+ // original token may arrive before any translation token; the utterance is
630
+ // opened lazily by either stream above, and `originalText` simply rides
631
+ // along on whichever emit happens next.
632
+ if (originalTokens.length > 0) {
633
+ let originalInterim = "";
634
+ let originalFinal = "";
635
+ for (const t of originalTokens) {
636
+ if (!currentUtteranceId) {
637
+ startNewUtterance(t.speaker, undefined);
638
+ }
639
+ if (t.language) currentSourceLanguage = t.language;
640
+ if (t.is_final) originalFinal += t.text;
641
+ else originalInterim += t.text;
642
+ }
643
+ if (originalFinal.length > originalPrevFinalLen) {
644
+ originalStablePrefix += originalFinal.slice(originalPrevFinalLen);
645
+ }
646
+ originalPrevFinalLen = originalFinal.length;
647
+ const originalComposite = originalStablePrefix + originalInterim;
648
+ if (originalComposite.length > 0) lastOriginalText = originalComposite;
649
+ }
650
+
651
+ // Accumulate finalized text. On window growth, append the delta. On
652
+ // shrink (compaction), keep stablePrefix; reset tracker to new length.
653
+ if (currentFinalText.length > prevFinalLen) {
654
+ stablePrefix += currentFinalText.slice(prevFinalLen);
655
+ }
656
+ prevFinalLen = currentFinalText.length;
657
+
658
+ const timed = tokens.filter(
659
+ (t) => t.text !== "<end>" && t.text !== "<fin>",
660
+ );
661
+ const hasTiming =
662
+ !isTranslation &&
663
+ timed.length > 0 &&
664
+ timed.every((t) => t.start_ms != null && t.end_ms != null);
665
+ if (hasTiming) {
666
+ for (const t of timed.filter((t) => t.is_final)) {
667
+ const key = `${providerGeneration}:${t.start_ms}:${t.end_ms}:${t.text}`;
668
+ confirmedTokens.set(key, {
669
+ text: t.text,
670
+ startMs: t.start_ms!,
671
+ endMs: t.end_ms!,
672
+ confidence: t.confidence,
673
+ isFinal: true,
674
+ speaker: t.speaker,
675
+ detectedLanguage: t.language,
676
+ audioPosition:
677
+ confirmedTokens.get(key)?.audioPosition ??
678
+ (pendingTokenGeneration === providerGeneration
679
+ ? pendingTokens.find((token) => token.startMs === t.start_ms && token.endMs === t.end_ms && token.text === t.text)?.audioPosition
680
+ : undefined) ??
681
+ audioTimeline.at(t.start_ms!),
682
+ });
683
+ }
684
+ lastTokens = [
685
+ ...confirmedTokens.values(),
686
+ ...timed
687
+ .filter((t) => !t.is_final)
688
+ .map((t) => ({
689
+ text: t.text,
690
+ startMs: t.start_ms!,
691
+ endMs: t.end_ms!,
692
+ confidence: t.confidence,
693
+ isFinal: false,
694
+ speaker: t.speaker,
695
+ detectedLanguage: t.language,
696
+ audioPosition: audioTimeline.at(t.start_ms!),
697
+ })),
698
+ ];
699
+ } else if (timed.length > 0) {
700
+ lastTokens = [];
701
+ }
702
+ if (result.final_audio_proc_ms > 0)
703
+ audioTimeline.prune(result.final_audio_proc_ms);
704
+ const compositeText = hasTiming || (!isTranslation && timed.length === 0 && lastTokens.length > 0)
705
+ ? lastTokens
706
+ .map((t) => t.text)
707
+ .join("")
708
+ .trim()
709
+ : (stablePrefix + interimText).trim();
710
+ if (compositeText.length === 0) return;
711
+
712
+ if (pendingFinalText && pendingFinalTimer) {
713
+ const pendingBefore = pendingFinalText;
714
+ const merged = tryMergeOverlap(pendingFinalText, compositeText);
715
+ if (merged !== null) {
716
+ currentUtteranceId = pendingFinalUtteranceId ?? currentUtteranceId;
717
+ if (currentSpeakerId) pendingFinalSpeakerId = currentSpeakerId;
718
+ else currentSpeakerId = pendingFinalSpeakerId;
719
+ if (currentLanguage) pendingFinalLanguage = currentLanguage;
720
+ else currentLanguage = pendingFinalLanguage;
721
+ if (lastOriginalText) {
722
+ pendingFinalOriginalText =
723
+ tryMergeOverlap(pendingFinalOriginalText, lastOriginalText) ??
724
+ lastOriginalText;
725
+ }
726
+ if (currentSourceLanguage) {
727
+ pendingFinalSourceLanguage = currentSourceLanguage;
728
+ }
729
+
730
+ pendingFinalText = merged;
731
+ pendingTokens = mergeTimedTokens(merged, pendingTokens, lastTokens);
732
+ lastTokens = pendingTokens;
733
+ lastEmittedTokens = pendingTokens;
734
+ if (activeFrameTimelineVersion === 1) pendingFrameTimelineVersion = 1;
735
+ lastSentInterim = merged;
736
+
737
+ if (merged !== pendingBefore) {
738
+ emitTranscript({
739
+ text: merged,
740
+ isFinal: false,
741
+ utteranceId: currentUtteranceId ?? undefined,
742
+ speakerId: currentSpeakerId,
743
+ language,
744
+ originalText: pendingFinalOriginalText || undefined,
745
+ sourceLanguage: pendingFinalSourceLanguage,
746
+ startMs,
747
+ endMs,
748
+ tokens: pendingTokens,
749
+ frameTimelineVersion: pendingFrameTimelineVersion,
750
+ });
751
+ schedulePendingFinalCommit();
752
+ }
753
+ return;
754
+ }
755
+
756
+ commitPendingFinal();
757
+ }
758
+
759
+ // Emit an INTERIM only. We deliberately do NOT emit a final on every round
760
+ // that has finalized tokens (v1 lesson: that piles up one card per partial
761
+ // on the client). The single final is emitted at the utterance boundary by
762
+ // `emitFinal`, driven by the Soniox `endpoint` event (and on `close()`).
763
+ if (isLikelyWindowRegression(compositeText, lastSentInterim)) {
764
+ return;
765
+ }
766
+
767
+ if (compositeText !== lastSentInterim) {
768
+ emitTranscript({
769
+ text: compositeText,
770
+ isFinal: false,
771
+ utteranceId: currentUtteranceId ?? undefined,
772
+ speakerId: currentSpeakerId,
773
+ language,
774
+ originalText: lastOriginalText || undefined,
775
+ sourceLanguage: currentSourceLanguage,
776
+ startMs,
777
+ endMs,
778
+ tokens: lastTokens,
779
+ frameTimelineVersion: activeFrameTimelineVersion,
780
+ });
781
+ lastSentInterim = compositeText;
782
+ lastEmittedTokens = lastTokens;
783
+ } else if (lastTokens.map((token) => token.text).join("").trim() === compositeText) {
784
+ lastEmittedTokens = lastTokens;
785
+ }
786
+ };
787
+
788
+ const handleEndpoint = () => {
789
+ // Endpoint fires when Soniox detects an utterance boundary (the `<end>`
790
+ // token). It is a soft signal, so defer the FINAL briefly; if Soniox's
791
+ // next rolling window overlaps, we merge it back into this utterance.
792
+ const candidate = lastSentInterim.trim();
793
+ if (candidate) {
794
+ if (pendingFinalText && pendingFinalTimer) {
795
+ const merged = tryMergeOverlap(pendingFinalText, candidate);
796
+ if (merged !== null) {
797
+ pendingFinalText = merged;
798
+ pendingTokens = mergeTimedTokens(merged, pendingTokens, lastEmittedTokens);
799
+ if (currentSpeakerId) pendingFinalSpeakerId = currentSpeakerId;
800
+ if (currentLanguage) pendingFinalLanguage = currentLanguage;
801
+ if (lastOriginalText) {
802
+ pendingFinalOriginalText =
803
+ tryMergeOverlap(pendingFinalOriginalText, lastOriginalText) ??
804
+ lastOriginalText;
805
+ }
806
+ if (currentSourceLanguage) {
807
+ pendingFinalSourceLanguage = currentSourceLanguage;
808
+ }
809
+ } else {
810
+ commitPendingFinal();
811
+ setPendingFinalFromActive(candidate);
812
+ }
813
+ } else {
814
+ setPendingFinalFromActive(candidate);
815
+ }
816
+ schedulePendingFinalCommit();
817
+ }
818
+ resetActiveUtterance();
819
+ };
820
+
821
+ const handleFinalized = () => {
822
+ // The SDK fires this after session.pause() or session.finalize(). For our
823
+ // audio-gap pause, it is the trusted "speech segment ended" signal.
824
+ commitPendingFinal();
825
+ emitFinal();
826
+ };
827
+
828
+ const handleError = (err: Error) => {
829
+ stopGapDetection();
830
+ opts.onError?.(err);
831
+ // A provider-side error usually precedes (or accompanies) the socket dying.
832
+ // Treat it as a trigger for the self-heal path: if the session is no longer
833
+ // usable, `scheduleReconnect` brings up a fresh one; if it is still alive,
834
+ // the reconnect is a no-op once `connected` re-fires.
835
+ scheduleReconnect("error");
836
+ };
837
+
838
+ // The `disconnected` handler is named so the same function is wired onto every
839
+ // session instance (original + each reconnect) and can be `off`-ed on close.
840
+ const handleDisconnected = (reason: unknown) => {
841
+ logger.info(`disconnected scope=${opts.scope} reason=${typeof reason === "string" ? reason : JSON.stringify(reason)}`);
842
+ // An UNEXPECTED disconnect (not our own close()) means the upstream session
843
+ // is gone. Self-heal in place so the provider keeps producing transcripts
844
+ // for the audio that is still arriving. An expected disconnect (closed=true)
845
+ // is the normal teardown and must NOT reconnect.
846
+ scheduleReconnect("disconnected");
847
+ };
848
+
849
+ const handleConnected = () => {
850
+ logger.info(
851
+ `connected scope=${opts.scope} lang=${opts.language}${opts.targetLanguage ? ` → ${opts.targetLanguage}` : ""}`,
852
+ );
853
+ };
854
+
855
+ const handleFinished = () => {
856
+ logger.info(`finished scope=${opts.scope}`);
857
+ commitPendingFinal();
858
+ emitFinal();
859
+ };
860
+
861
+ /**
862
+ * Wire our handlers onto a Soniox session instance. Visibility events
863
+ * (`connected`/`finished`) and the data/lifecycle events (`result`,
864
+ * `endpoint`, `error`, `disconnected`). Called for the initial session and
865
+ * for every replacement built on a self-heal reconnect.
866
+ */
867
+ const wireSession = (s: RealtimeSttSession): void => {
868
+ s.on("connected", handleConnected);
869
+ s.on("disconnected", handleDisconnected);
870
+ s.on("finished", handleFinished);
871
+ s.on("result", handleResult);
872
+ s.on("endpoint", handleEndpoint);
873
+ s.on("finalized", handleFinalized);
874
+ s.on("error", handleError);
875
+ };
876
+
877
+ /** Detach our handlers from a session instance (on replace or close). */
878
+ const unwireSession = (s: RealtimeSttSession): void => {
879
+ try {
880
+ s.off("connected", handleConnected);
881
+ s.off("disconnected", handleDisconnected);
882
+ s.off("finished", handleFinished);
883
+ s.off("result", handleResult);
884
+ s.off("endpoint", handleEndpoint);
885
+ s.off("finalized", handleFinalized);
886
+ s.off("error", handleError);
887
+ } catch {
888
+ /* best-effort */
889
+ }
890
+ };
891
+
892
+ const stopGapDetection = (): void => {
893
+ if (gapCheckInterval) {
894
+ clearInterval(gapCheckInterval);
895
+ gapCheckInterval = null;
896
+ }
897
+ };
898
+
899
+ const startGapDetection = (): void => {
900
+ stopGapDetection();
901
+ lastAudioWriteTime = Date.now();
902
+ pausedForGap = false;
903
+
904
+ gapCheckInterval = setInterval(() => {
905
+ if (closed || reconnecting || pausedForGap) return;
906
+ if (Date.now() - lastAudioWriteTime < gapConfig.thresholdMs) return;
907
+
908
+ try {
909
+ session.pause();
910
+ pausedForGap = true;
911
+ logger.info(`auto-paused scope=${opts.scope} after audio gap`);
912
+ } catch (err) {
913
+ logger.warn({ err }, `auto-pause failed scope=${opts.scope}`);
914
+ }
915
+ }, gapConfig.checkIntervalMs);
916
+ };
917
+
918
+ /**
919
+ * Rebuild the underlying Soniox session in place after an unexpected drop.
920
+ *
921
+ * Reentrancy-guarded by `reconnecting`, so a burst of `disconnected` + `error`
922
+ * for the same drop schedules exactly one heal. Each attempt builds a fresh
923
+ * session, wires it, and connects; on failure it backs off and retries up to
924
+ * `SONIOX_RECONNECT_MAX_ATTEMPTS`, after which it surfaces the failure via
925
+ * `onError` and stops (the next provider recreate, e.g. a real detach, is the
926
+ * recovery path of last resort). We do NOT flush a final on the dead session's
927
+ * in-flight utterance — the rolling-window state is preserved so the resumed
928
+ * session continues the same card where possible.
929
+ */
930
+ const reconnect = reconnectConfig();
931
+ const scheduleReconnect = (trigger: string): void => {
932
+ if (closed || reconnecting) return;
933
+ stopGapDetection();
934
+ pausedForGap = false;
935
+ reconnecting = true;
936
+
937
+ const attempt = async (): Promise<void> => {
938
+ while (!closed) {
939
+ reconnectAttempts += 1;
940
+ if (reconnectAttempts > reconnect.maxAttempts) {
941
+ logger.error(`self-heal gave up scope=${opts.scope} after ${reconnect.maxAttempts} attempts (trigger=${trigger})`);
942
+ opts.onError?.(
943
+ new Error(`soniox session lost and could not reconnect (scope=${opts.scope})`),
944
+ );
945
+ reconnecting = false;
946
+ return;
947
+ }
948
+
949
+ const delay = Math.min(
950
+ reconnect.maxMs,
951
+ reconnect.baseMs * 2 ** (reconnectAttempts - 1),
952
+ );
953
+ logger.info(`self-heal reconnect scope=${opts.scope} attempt=${reconnectAttempts} delayMs=${delay} trigger=${trigger}`);
954
+ await new Promise((resolve) => setTimeout(resolve, delay));
955
+ if (closed) break;
956
+
957
+ // Drop the dead session's handlers so its late events can't drive us.
958
+ unwireSession(session);
959
+
960
+ const next = client.realtime.stt(sessionConfig);
961
+ wireSession(next);
962
+ try {
963
+ await next.connect();
964
+ // Connected: swap in the fresh session and clear the heal state.
965
+ session = next;
966
+ providerGeneration += 1;
967
+ audioTimeline.reset();
968
+ reconnecting = false;
969
+ reconnectAttempts = 0;
970
+ startGapDetection();
971
+ logger.info(`self-heal reconnected scope=${opts.scope}`);
972
+ return;
973
+ } catch (err) {
974
+ logger.error(
975
+ { err },
976
+ `self-heal connect failed scope=${opts.scope} attempt=${reconnectAttempts}`,
977
+ );
978
+ unwireSession(next);
979
+ try {
980
+ await next.close();
981
+ } catch {
982
+ /* best-effort */
983
+ }
984
+ // Loop and back off again.
985
+ }
986
+ }
987
+ reconnecting = false;
988
+ };
989
+
990
+ void attempt();
991
+ };
992
+
993
+ // Wire the initial session and connect it.
994
+ wireSession(session);
995
+ try {
996
+ await session.connect();
997
+ startGapDetection();
998
+ } catch (err) {
999
+ logger.error({ err }, `connect failed scope=${opts.scope}`);
1000
+ opts.onError?.(err as Error);
1001
+ throw err;
1002
+ }
1003
+
1004
+ return {
1005
+ name: "soniox",
1006
+ writeAudio(pcm: Int16Array, position?: AudioPosition): void {
1007
+ // Drop frames while a self-heal reconnect is in flight (or after close):
1008
+ // there is no live upstream session to take them, and the pipeline already
1009
+ // tolerates a brief audio gap across a reconnect.
1010
+ if (closed || reconnecting) return;
1011
+ // Soniox SDK accepts Uint8Array of raw PCM bytes.
1012
+ const bytes = new Uint8Array(pcm.buffer, pcm.byteOffset, pcm.byteLength);
1013
+ lastAudioWriteTime = Date.now();
1014
+ if (pausedForGap) {
1015
+ try {
1016
+ session.resume();
1017
+ pausedForGap = false;
1018
+ resetActiveUtterance();
1019
+ logger.info(`resumed scope=${opts.scope} after audio gap`);
1020
+ } catch (err) {
1021
+ logger.warn({ err }, `resume failed scope=${opts.scope}`);
1022
+ }
1023
+ }
1024
+ try {
1025
+ frameTimelineVersion = position ? 1 : undefined;
1026
+ if (position && currentUtteranceId) activeFrameTimelineVersion = 1;
1027
+ audioTimeline.add(pcm.length, position);
1028
+ session.sendAudio(bytes);
1029
+ } catch (err) {
1030
+ // A throw here usually means the socket died between checks: surface it
1031
+ // and kick off self-heal so the next frames have somewhere to land.
1032
+ opts.onError?.(err as Error);
1033
+ scheduleReconnect("writeAudio");
1034
+ }
1035
+ },
1036
+ async close(): Promise<void> {
1037
+ // Mark closed FIRST so any disconnect/error fired by our own teardown does
1038
+ // not spin up a self-heal reconnect.
1039
+ closed = true;
1040
+ stopGapDetection();
1041
+ // Flush any in-flight utterance as a final so a card that was mid-update
1042
+ // gets committed instead of being left dangling on detach.
1043
+ try {
1044
+ commitPendingFinal();
1045
+ emitFinal();
1046
+ } catch {
1047
+ /* best-effort */
1048
+ }
1049
+ try {
1050
+ await session.finish();
1051
+ } catch {
1052
+ /* best-effort */
1053
+ }
1054
+ try {
1055
+ unwireSession(session);
1056
+ await session.close();
1057
+ } catch {
1058
+ /* best-effort */
1059
+ }
1060
+ },
1061
+ };
1062
+ }
cloud-v2/packages/runtime/src/services/audio/result.test.ts ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Tests for transcriptToStreamMessage, pinning the
3
+ * resolvedLanguage contract (OS-1746).
4
+ *
5
+ * The phone routes results to miniapp handlers by exact stream key
6
+ * (`transcription:<resolvedLanguage>`), so a specific-language subscription
7
+ * MUST get its own code echoed back — never the provider's detected code,
8
+ * which is a bare ISO 639-1 ("en") while subscriptions carry BCP-47 ("en-US").
9
+ */
10
+ import { describe, test, expect } from "bun:test";
11
+
12
+ import { transcriptToStreamMessage } from "./result";
13
+ import type { TranscriptMessage } from "./workers/worker";
14
+
15
+ function transcriptMessage(overrides: Partial<TranscriptMessage>): TranscriptMessage {
16
+ return {
17
+ type: "TRANSCRIPT",
18
+ kind: "transcription",
19
+ mentraUserId: "user@example.com",
20
+ text: "hello",
21
+ isFinal: true,
22
+ language: undefined,
23
+ source: "soniox",
24
+ subscription: { kind: "transcription", language: { mode: "auto" } },
25
+ ...overrides,
26
+ } as TranscriptMessage;
27
+ }
28
+
29
+ describe("transcriptToStreamMessage resolvedLanguage", () => {
30
+ test("preserves token timing and phone position for internal runtime projection", () => {
31
+ const tokens = [
32
+ {
33
+ text: "word",
34
+ startMs: 2,
35
+ endMs: 3,
36
+ confidence: 1,
37
+ isFinal: true,
38
+ audioPosition: { sessionTag: 9, offsetMs: 100 },
39
+ },
40
+ ];
41
+ const msg = transcriptToStreamMessage(transcriptMessage({ tokens, frameTimelineVersion: 1 }));
42
+ if (msg.type !== "stream.transcript")
43
+ throw new Error("expected transcript");
44
+ expect(msg.payload.tokens).toEqual(tokens);
45
+ expect(msg.payload.frameTimelineVersion).toBe(1);
46
+ });
47
+ test("specific subscription echoes its own code even when the provider detected a different tag", () => {
48
+ const msg = transcriptToStreamMessage(
49
+ transcriptMessage({
50
+ subscription: {
51
+ kind: "transcription",
52
+ language: { mode: "specific", code: "en-US" },
53
+ },
54
+ language: "en", // Soniox detected code (bare ISO 639-1)
55
+ }),
56
+ );
57
+ expect(msg.type).toBe("stream.transcript");
58
+ if (msg.type !== "stream.transcript") return;
59
+ expect(msg.payload.resolvedLanguage).toBe("en-US");
60
+ expect(msg.payload.languageDetected).toBe(false);
61
+ });
62
+
63
+ test("auto subscription resolves to the detected language", () => {
64
+ const msg = transcriptToStreamMessage(
65
+ transcriptMessage({
66
+ subscription: { kind: "transcription", language: { mode: "auto" } },
67
+ language: "es",
68
+ }),
69
+ );
70
+ if (msg.type !== "stream.transcript") throw new Error("expected transcript");
71
+ expect(msg.payload.resolvedLanguage).toBe("es");
72
+ expect(msg.payload.languageDetected).toBe(true);
73
+ });
74
+
75
+ test("auto subscription with no detection falls back to auto", () => {
76
+ const msg = transcriptToStreamMessage(
77
+ transcriptMessage({
78
+ subscription: { kind: "transcription", language: { mode: "auto" } },
79
+ language: undefined,
80
+ }),
81
+ );
82
+ if (msg.type !== "stream.transcript") throw new Error("expected transcript");
83
+ expect(msg.payload.resolvedLanguage).toBe("auto");
84
+ expect(msg.payload.languageDetected).toBe(true);
85
+ });
86
+
87
+ test("translation with specific source echoes the source code", () => {
88
+ const msg = transcriptToStreamMessage(
89
+ transcriptMessage({
90
+ kind: "translation",
91
+ subscription: {
92
+ kind: "translation",
93
+ source: { mode: "specific", code: "zh-CN" },
94
+ target: "en-US",
95
+ },
96
+ sourceLanguage: "zh",
97
+ } as Partial<TranscriptMessage>),
98
+ );
99
+ expect(msg.type).toBe("stream.translation");
100
+ if (msg.type !== "stream.translation") return;
101
+ expect(msg.payload.source.language).toBe("zh-CN");
102
+ expect(msg.payload.source.detected).toBe(false);
103
+ expect(msg.payload.target.language).toBe("en-US");
104
+ });
105
+ });
cloud-v2/packages/runtime/src/services/audio/result.ts ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Map a worker-emitted transcript into a v2 wire message.
3
+ *
4
+ * The worker (a Bun Worker thread) speaks a small IPC shape, `TranscriptMessage`,
5
+ * carrying the text plus the subscription that produced it. The client speaks
6
+ * the v2 protocol: `stream.transcript` (transcription) and `stream.translation`
7
+ * (translation), each a `TranscriptionData` / `TranslationData` payload wrapped
8
+ * in the standard envelope.
9
+ *
10
+ * This module is the one place that translation happens, so the worker stays
11
+ * free of protocol types and the WS layer just forwards whatever this returns.
12
+ *
13
+ * Protocol: src/protocol/{audio,messages,envelope}.ts.
14
+ */
15
+
16
+ import { PROTOCOL_MAJOR, type Envelope } from "@mentra/cloud-protocol/envelope";
17
+ import type {
18
+ LanguageSource,
19
+ TranscriptionData,
20
+ TranscriptionSubscription,
21
+ TranslationData,
22
+ TranslationSubscription,
23
+ } from "@mentra/cloud-protocol/audio";
24
+ import type { TranscriptMessage } from "./workers/worker";
25
+
26
+ /** The two push messages a transcript can become. */
27
+ export type StreamMessage =
28
+ | (Envelope<TranscriptionData> & { type: "stream.transcript" })
29
+ | (Envelope<TranslationData> & { type: "stream.translation" });
30
+
31
+ /** A specified language resolves to its code; an "auto" source resolves to the
32
+ * language the provider actually detected, falling back to "auto" if it never
33
+ * reported one.
34
+ *
35
+ * For specific mode the subscription's code MUST win over the provider's
36
+ * detected language: the phone routes results to miniapp handlers by exact
37
+ * stream key (`transcription:<resolvedLanguage>`), and providers report bare
38
+ * ISO 639-1 codes ("en") while subscriptions carry BCP-47 tags ("en-US").
39
+ * Echoing the detected code broke every specific-language subscription —
40
+ * results went out keyed `transcription:en` and the `transcription:en-US`
41
+ * handler never fired (OS-1746). */
42
+ function resolvedLanguage(
43
+ source: LanguageSource,
44
+ detected: string | undefined,
45
+ ): { language: string; detected: boolean } {
46
+ if (source.mode === "specific") {
47
+ return { language: source.code, detected: false };
48
+ }
49
+ return { language: detected ?? "auto", detected: true };
50
+ }
51
+
52
+ /**
53
+ * Convert a worker transcript into its v2 envelope. The discriminant is the
54
+ * subscription kind, not the loose `kind` string, so the payload type is
55
+ * sound.
56
+ */
57
+ export function transcriptToStreamMessage(t: TranscriptMessage): StreamMessage {
58
+ const timestamp = Date.now();
59
+
60
+ if (t.subscription.kind === "translation") {
61
+ const sub: TranslationSubscription = t.subscription;
62
+ const src = resolvedLanguage(sub.source, t.sourceLanguage);
63
+ const payload: TranslationData = {
64
+ userId: t.mentraUserId,
65
+ subscription: sub,
66
+ text: t.text,
67
+ isFinal: t.isFinal,
68
+ originalText: t.originalText,
69
+ utteranceId: t.utteranceId,
70
+ speakerId: t.speakerId,
71
+ startMs: t.startMs ?? 0,
72
+ endMs: t.endMs ?? 0,
73
+ source: { language: src.language, detected: src.detected },
74
+ target: { language: sub.target },
75
+ provider: t.source,
76
+ timestamp,
77
+ };
78
+ return {
79
+ v: PROTOCOL_MAJOR,
80
+ type: "stream.translation",
81
+ timestamp,
82
+ payload,
83
+ };
84
+ }
85
+
86
+ const sub: TranscriptionSubscription = t.subscription;
87
+ const lang = resolvedLanguage(sub.language, t.language);
88
+ const payload: TranscriptionData = {
89
+ userId: t.mentraUserId,
90
+ subscription: sub,
91
+ text: t.text,
92
+ isFinal: t.isFinal,
93
+ utteranceId: t.utteranceId,
94
+ speakerId: t.speakerId,
95
+ startMs: t.startMs ?? 0,
96
+ endMs: t.endMs ?? 0,
97
+ resolvedLanguage: lang.language,
98
+ languageDetected: lang.detected,
99
+ tokens: t.tokens ?? [],
100
+ frameTimelineVersion: t.frameTimelineVersion,
101
+ provider: t.source,
102
+ timestamp,
103
+ };
104
+ return {
105
+ v: PROTOCOL_MAJOR,
106
+ type: "stream.transcript",
107
+ timestamp,
108
+ payload,
109
+ };
110
+ }
cloud-v2/packages/runtime/src/services/audio/workers/identity.fixture.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Test-only worker entry: reports the identity it resolves, using the same
3
+ * code path as worker.ts (resolveWorkerIdentity over workerData + env), without
4
+ * needing Redis.
5
+ */
6
+ import { workerData } from "node:worker_threads";
7
+ import { resolveWorkerIdentity } from "./identity";
8
+
9
+ const identity = resolveWorkerIdentity(workerData, {
10
+ // Static reads, exactly as worker.ts does.
11
+ WORKER_ID: process.env.WORKER_ID,
12
+ POD_ID: process.env.POD_ID,
13
+ });
14
+ (globalThis as unknown as { postMessage(message: unknown): void }).postMessage(identity);
cloud-v2/packages/runtime/src/services/audio/workers/identity.test.ts ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+ import { resolveWorkerIdentity, type WorkerIdentity } from "./identity";
3
+ import { buildWorkerOptions } from "./pool";
4
+
5
+ describe("resolveWorkerIdentity", () => {
6
+ test("workerData wins over env", () => {
7
+ expect(
8
+ resolveWorkerIdentity({ workerId: "w3", podId: "pod-a" }, { WORKER_ID: "x", POD_ID: "y" }),
9
+ ).toEqual({ workerId: "w3", podId: "pod-a", consumerName: "pod-a:w3" });
10
+ });
11
+
12
+ test("falls back to env when workerData is absent (main thread)", () => {
13
+ expect(resolveWorkerIdentity(null, { WORKER_ID: "w9", POD_ID: "pod-z" })).toEqual({
14
+ workerId: "w9",
15
+ podId: "pod-z",
16
+ consumerName: "pod-z:w9",
17
+ });
18
+ });
19
+
20
+ test("falls back to defaults, ignoring empty or non-string values", () => {
21
+ expect(resolveWorkerIdentity({ workerId: "", podId: 5 }, {})).toEqual({
22
+ workerId: "worker",
23
+ podId: "pod",
24
+ consumerName: "pod:worker",
25
+ });
26
+ });
27
+ });
28
+
29
+ describe("worker started with buildWorkerOptions", () => {
30
+ const workers: Worker[] = [];
31
+ const saved = { WORKER_ID: process.env.WORKER_ID, POD_ID: process.env.POD_ID };
32
+
33
+ afterEach(() => {
34
+ for (const w of workers.splice(0)) w.terminate();
35
+ for (const [k, v] of Object.entries(saved)) {
36
+ if (v === undefined) delete process.env[k];
37
+ else process.env[k] = v;
38
+ }
39
+ });
40
+
41
+ function reportedIdentity(workerId: string, podId: string): Promise<WorkerIdentity> {
42
+ const worker = new Worker(
43
+ new URL("./identity.fixture.ts", import.meta.url),
44
+ buildWorkerOptions(workerId, podId),
45
+ );
46
+ workers.push(worker);
47
+ return new Promise((resolve, reject) => {
48
+ worker.onmessage = (e: MessageEvent<WorkerIdentity>) => resolve(e.data);
49
+ worker.onerror = (e: ErrorEvent) => reject(new Error(e.message));
50
+ });
51
+ }
52
+
53
+ test("reports its own worker and pod ids", async () => {
54
+ expect(await reportedIdentity("w1", "pod-a")).toEqual({
55
+ workerId: "w1",
56
+ podId: "pod-a",
57
+ consumerName: "pod-a:w1",
58
+ });
59
+ });
60
+
61
+ test("distinct workers resolve distinct consumer names", async () => {
62
+ const ids = await Promise.all([reportedIdentity("w0", "pod-a"), reportedIdentity("w1", "pod-a")]);
63
+ expect(ids.map((i) => i.consumerName)).toEqual(["pod-a:w0", "pod-a:w1"]);
64
+ });
65
+
66
+ test("parent env already holding WORKER_ID / POD_ID does not override the pool's ids", async () => {
67
+ process.env.WORKER_ID = "parent-worker";
68
+ process.env.POD_ID = "parent-pod";
69
+ expect(await reportedIdentity("w2", "pod-b")).toEqual({
70
+ workerId: "w2",
71
+ podId: "pod-b",
72
+ consumerName: "pod-b:w2",
73
+ });
74
+ });
75
+ });
cloud-v2/packages/runtime/src/services/audio/workers/identity.ts ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Audio worker identity (worker id, pod id, Redis consumer name).
3
+ *
4
+ * The pool hands identity to each worker thread through `workerData`, not the
5
+ * `env` option of `new Worker`. Bun's `env` option is unreliable for this:
6
+ * `process.env` inside a worker keeps the parent's value for any key the parent
7
+ * already has, so a pod-level `POD_ID` (or a stray `WORKER_ID`) silently wins
8
+ * over the value the pool passed. `workerData` is structured-cloned verbatim.
9
+ *
10
+ * The identity feeds the Redis consumer name (`<podId>:<workerId>`) used for
11
+ * XREADGROUP / XAUTOCLAIM, so each worker must resolve a distinct one.
12
+ */
13
+
14
+ export interface WorkerBootData {
15
+ workerId: string;
16
+ podId: string;
17
+ }
18
+
19
+ export interface WorkerIdentity extends WorkerBootData {
20
+ /** Redis consumer-group consumer name: `<podId>:<workerId>`. */
21
+ consumerName: string;
22
+ }
23
+
24
+ const DEFAULT_WORKER_ID = "worker";
25
+ const DEFAULT_POD_ID = "pod";
26
+
27
+ function nonEmptyString(value: unknown): string | undefined {
28
+ return typeof value === "string" && value.length > 0 ? value : undefined;
29
+ }
30
+
31
+ /**
32
+ * Resolve identity from `workerData` first (set by the pool), then from the
33
+ * environment (a worker started outside the pool, or on the main thread where
34
+ * `workerData` is null), then from defaults.
35
+ */
36
+ export function resolveWorkerIdentity(
37
+ data: unknown,
38
+ env: Record<string, string | undefined>,
39
+ ): WorkerIdentity {
40
+ const boot = (data && typeof data === "object" ? data : {}) as Partial<WorkerBootData>;
41
+ const workerId = nonEmptyString(boot.workerId) ?? nonEmptyString(env.WORKER_ID) ?? DEFAULT_WORKER_ID;
42
+ const podId = nonEmptyString(boot.podId) ?? nonEmptyString(env.POD_ID) ?? DEFAULT_POD_ID;
43
+ return { workerId, podId, consumerName: `${podId}:${workerId}` };
44
+ }
cloud-v2/packages/runtime/src/services/audio/workers/lc3.ts ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview LC3 audio decoder, per-user instance.
3
+ *
4
+ * Wraps the WASM-compiled liblc3 reference codec (Bluetooth SIG) for use in
5
+ * audio workers. Ported from v1 cloud's `lc3.service.ts`, narrowed to
6
+ * decode-only (cloud-v2 doesn't re-encode audio for the glasses path).
7
+ *
8
+ * Fixed parameters:
9
+ * - Frame duration: 10ms
10
+ * - Sample rate: 16kHz
11
+ * - Frame samples: 160 per decoded frame (lc3_frame_samples query)
12
+ * - Output: Int16 mono PCM
13
+ *
14
+ * Per-instance LC3 decoder state — one instance per user (per worker).
15
+ * The compiled WASM module is shared across instances within a process via
16
+ * a module-level cache.
17
+ */
18
+
19
+ import { readFileSync } from "node:fs";
20
+ import { join } from "node:path";
21
+
22
+ const FRAME_DURATION_US = 10_000;
23
+ const SAMPLE_RATE_HZ = 16_000;
24
+ const FRAME_BUFFER_BYTES = 1024; // generous upper bound — real frames are ≤60B
25
+ const PCM_FORMAT_S16 = 0; // liblc3 PCM format code for signed 16-bit
26
+
27
+ /** Supported LC3 frame sizes in bytes. Each maps to a bitrate at 16kHz/10ms. */
28
+ export const SUPPORTED_FRAME_BYTES = new Set([20, 40, 60]);
29
+
30
+ interface Lc3Exports {
31
+ memory: WebAssembly.Memory;
32
+ lc3_frame_samples(durationUs: number, sampleRate: number): number;
33
+ lc3_decoder_size(durationUs: number, sampleRate: number): number;
34
+ lc3_setup_decoder(
35
+ durationUs: number,
36
+ sampleRate: number,
37
+ srPcm: number,
38
+ decoderPtr: number,
39
+ ): void;
40
+ lc3_decode(
41
+ decoderPtr: number,
42
+ framePtr: number,
43
+ frameBytes: number,
44
+ format: number,
45
+ samplePtr: number,
46
+ stride: number,
47
+ ): number;
48
+ }
49
+
50
+ /** WASM module compiled once per process, shared across decoder instances. */
51
+ let cachedWasmModule: WebAssembly.Module | null = null;
52
+
53
+ async function getWasmModule(): Promise<WebAssembly.Module> {
54
+ if (cachedWasmModule) return cachedWasmModule;
55
+ const wasmPath = join(import.meta.dir, "liblc3.wasm");
56
+ const wasmBytes = readFileSync(wasmPath);
57
+ cachedWasmModule = await WebAssembly.compile(new Uint8Array(wasmBytes));
58
+ return cachedWasmModule;
59
+ }
60
+
61
+ export class LC3Decoder {
62
+ private exports!: Lc3Exports;
63
+ private decoderPtr = 0;
64
+ private samplePtr = 0;
65
+ private framePtr = 0;
66
+ private frameSamples = 0;
67
+ private framesView!: Uint8Array;
68
+ private samplesView!: Int16Array;
69
+
70
+ private constructor(public readonly frameBytes: number) {
71
+ if (!SUPPORTED_FRAME_BYTES.has(frameBytes)) {
72
+ throw new Error(
73
+ `LC3Decoder: unsupported frameBytes ${frameBytes} (must be 20, 40, or 60)`,
74
+ );
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Create + initialize a decoder. Async because WASM compile/instantiate
80
+ * is async. Default `frameBytes` = 20 (16kbps) matches v1's default.
81
+ */
82
+ static async create(frameBytes = 20): Promise<LC3Decoder> {
83
+ const d = new LC3Decoder(frameBytes);
84
+ await d.init();
85
+ return d;
86
+ }
87
+
88
+ private async init(): Promise<void> {
89
+ const wasmModule = await getWasmModule();
90
+ const instance = await WebAssembly.instantiate(wasmModule, {});
91
+ this.exports = instance.exports as unknown as Lc3Exports;
92
+
93
+ this.frameSamples = this.exports.lc3_frame_samples(
94
+ FRAME_DURATION_US,
95
+ SAMPLE_RATE_HZ,
96
+ );
97
+ const decoderSize = this.exports.lc3_decoder_size(
98
+ FRAME_DURATION_US,
99
+ SAMPLE_RATE_HZ,
100
+ );
101
+
102
+ // Layout in WASM memory: [decoder_state | sample_buffer | frame_buffer].
103
+ const memory = this.exports.memory;
104
+ const basePtr = memory.buffer.byteLength;
105
+ const allocSize =
106
+ decoderSize + this.frameSamples * 2 + FRAME_BUFFER_BYTES;
107
+
108
+ const pagesNeeded = Math.ceil((basePtr + allocSize) / (64 * 1024));
109
+ const currentPages = memory.buffer.byteLength / (64 * 1024);
110
+ if (pagesNeeded > currentPages) {
111
+ memory.grow(pagesNeeded - currentPages);
112
+ }
113
+
114
+ this.decoderPtr = basePtr;
115
+ this.samplePtr = this.decoderPtr + decoderSize;
116
+ this.framePtr = this.samplePtr + this.frameSamples * 2;
117
+
118
+ this.exports.lc3_setup_decoder(
119
+ FRAME_DURATION_US,
120
+ SAMPLE_RATE_HZ,
121
+ PCM_FORMAT_S16,
122
+ this.decoderPtr,
123
+ );
124
+
125
+ // Persistent views into WASM memory — these point at our allocated
126
+ // regions so we can read/write samples and frames without re-slicing.
127
+ this.framesView = new Uint8Array(
128
+ memory.buffer,
129
+ this.framePtr,
130
+ FRAME_BUFFER_BYTES,
131
+ );
132
+ this.samplesView = new Int16Array(
133
+ memory.buffer,
134
+ this.samplePtr,
135
+ this.frameSamples,
136
+ );
137
+ }
138
+
139
+ /**
140
+ * Decode an LC3 payload containing one or more whole frames. Returns null
141
+ * if the input is empty or smaller than one frame. Bad frames within a
142
+ * multi-frame payload yield silence for that frame; we never throw.
143
+ */
144
+ decode(lc3Bytes: Uint8Array): Int16Array | null {
145
+ if (lc3Bytes.byteLength === 0) return null;
146
+
147
+ const numFrames = Math.floor(lc3Bytes.byteLength / this.frameBytes);
148
+ if (numFrames === 0) return null;
149
+
150
+ const out = new Int16Array(numFrames * this.frameSamples);
151
+
152
+ for (let i = 0; i < numFrames; i++) {
153
+ try {
154
+ this.framesView.set(
155
+ lc3Bytes.subarray(i * this.frameBytes, (i + 1) * this.frameBytes),
156
+ );
157
+ this.exports.lc3_decode(
158
+ this.decoderPtr,
159
+ this.framePtr,
160
+ this.frameBytes,
161
+ PCM_FORMAT_S16,
162
+ this.samplePtr,
163
+ 1, // stride
164
+ );
165
+ out.set(this.samplesView, i * this.frameSamples);
166
+ } catch {
167
+ // Per-frame failure → silence. Continue with the next frame.
168
+ out.fill(0, i * this.frameSamples, (i + 1) * this.frameSamples);
169
+ }
170
+ }
171
+
172
+ return out;
173
+ }
174
+
175
+ /** Samples produced per frame (160 at 10ms / 16kHz). */
176
+ get samplesPerFrame(): number {
177
+ return this.frameSamples;
178
+ }
179
+ }
cloud-v2/packages/runtime/src/services/audio/workers/pool.ts ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Worker pool — spawns N Bun Workers per pod, assigns users
3
+ * by least-loaded, forwards inbound transcripts to the user's WebSocket.
4
+ *
5
+ * Why workers own their stream reads (instead of main thread routing):
6
+ * - At 200–1000 users/pod target, main-thread per-entry routing becomes
7
+ * the bottleneck (one event loop dispatching tens of thousands of
8
+ * entries/sec). Workers reading directly scales linearly with worker
9
+ * count.
10
+ * - Worker death stays local: ioredis cleans up when the thread exits;
11
+ * main thread reassigns the dead worker's users and the new worker
12
+ * XAUTOCLAIMs any unacked PEL entries.
13
+ *
14
+ * Assignment policy:
15
+ * - **Least-loaded** by session count (not hash). Each session is roughly
16
+ * equivalent workload at session-time, and reconnects typically cross
17
+ * pod boundaries anyway, so hash's "sticky on reconnect" property
18
+ * doesn't survive the failure case it'd most matter for. Least-loaded
19
+ * avoids the hash-collision-stacks-two-heavy-users-on-one-worker class
20
+ * of problems with no real cost.
21
+ *
22
+ * IPC surface (worker side: `./worker.ts`):
23
+ * - main → worker: `ATTACH_USER`, `DETACH_USER`, `UPDATE_SUBSCRIPTIONS`,
24
+ * `SET_CODEC`, `SHUTDOWN`
25
+ * - worker → main: `WORKER_READY`, `TRANSCRIPT_STUB`, `TRANSCRIPT`,
26
+ * `UDP_LIVENESS_ACK`
27
+ */
28
+
29
+ import { createLogger } from "@mentra/cloud-shared";
30
+ import type { WorkerBootData } from "./identity";
31
+ import type {
32
+ AudioCodec,
33
+ SetCodecMessage,
34
+ TranscriptMessage,
35
+ TranscriptStubMessage,
36
+ UdpLivenessAckMessage,
37
+ WorkerInMessage,
38
+ WorkerOutMessage,
39
+ } from "./worker";
40
+
41
+ const logger = createLogger("audio").child({ service: "worker-pool" });
42
+
43
+ const WORKER_URL = new URL("./worker.ts", import.meta.url);
44
+
45
+ interface WorkerSlot {
46
+ id: string;
47
+ worker: Worker;
48
+ sessionCount: number;
49
+ ready: boolean;
50
+ /** Users this worker owns; recomputed if it dies and we reassign. */
51
+ ownedUsers: Set<string>;
52
+ /** ATTACH_USER messages queued while waiting for WORKER_READY. */
53
+ pendingAttaches: string[];
54
+ /**
55
+ * Users with a pending reconcile nudge (UPDATE_SUBSCRIPTIONS) queued while
56
+ * waiting for WORKER_READY. A Set, not a list of snapshots: the nudge carries
57
+ * no subs (the worker reads the subscription key), so duplicate nudges
58
+ * collapse to one.
59
+ */
60
+ pendingSubscriptions: Set<string>;
61
+ /** SET_CODEC messages queued while waiting for WORKER_READY. */
62
+ pendingCodecs: Map<string, SetCodecMessage>;
63
+ }
64
+
65
+ interface WorkerPoolState {
66
+ podId: string;
67
+ workers: WorkerSlot[];
68
+ /** mentraUserId → WorkerSlot. So DETACH/release knows which worker holds them. */
69
+ userToWorker: Map<string, WorkerSlot>;
70
+ /**
71
+ * Callback set by session.service: route worker-emitted messages to the
72
+ * user's WS. Receives real transcripts, routing stubs, and control acks.
73
+ */
74
+ transcriptHandler:
75
+ | ((msg: TranscriptStubMessage | TranscriptMessage | UdpLivenessAckMessage) => void)
76
+ | null;
77
+ /** Cleared by stopWorkerPool to suppress respawn during shutdown. */
78
+ shuttingDown: boolean;
79
+ }
80
+
81
+ let pool: WorkerPoolState | null = null;
82
+
83
+ export interface StartWorkerPoolOptions {
84
+ podId: string;
85
+ /** Number of workers to spawn. Default: 2 if not set (tests can pass 1–4). */
86
+ count?: number;
87
+ }
88
+
89
+ export function startWorkerPool(opts: StartWorkerPoolOptions): void {
90
+ if (pool) {
91
+ logger.warn("startWorkerPool called twice; ignoring");
92
+ return;
93
+ }
94
+ const count = opts.count ?? 2;
95
+ pool = {
96
+ podId: opts.podId,
97
+ workers: [],
98
+ userToWorker: new Map(),
99
+ transcriptHandler: null,
100
+ shuttingDown: false,
101
+ };
102
+ for (let i = 0; i < count; i++) {
103
+ pool.workers.push(spawnWorkerSlot(`w${i}`));
104
+ }
105
+ logger.info({ count }, "worker pool started");
106
+ }
107
+
108
+ export async function stopWorkerPool(): Promise<void> {
109
+ if (!pool) return;
110
+ pool.shuttingDown = true;
111
+ const slots = pool.workers;
112
+ pool = null;
113
+ // Tell each worker to drain Redis + exit, then terminate after a grace
114
+ // period if they don't ack.
115
+ await Promise.all(
116
+ slots.map(async (slot) => {
117
+ try {
118
+ slot.worker.postMessage({ type: "SHUTDOWN" } satisfies WorkerInMessage);
119
+ } catch {
120
+ /* worker may already be gone */
121
+ }
122
+ // Give it 500ms to close Redis cleanly; then terminate.
123
+ await Bun.sleep(500);
124
+ slot.worker.terminate();
125
+ }),
126
+ );
127
+ }
128
+
129
+ /**
130
+ * Register the callback that routes worker → main messages onward to the
131
+ * user's WebSocket. Called once by `session.service` at boot.
132
+ */
133
+ export function onTranscript(
134
+ handler: (msg: TranscriptStubMessage | TranscriptMessage | UdpLivenessAckMessage) => void,
135
+ ): void {
136
+ if (!pool) throw new Error("worker pool not started");
137
+ pool.transcriptHandler = handler;
138
+ }
139
+
140
+ /**
141
+ * Assign a user to the least-loaded worker. Idempotent for the SAME user
142
+ * (returns the existing slot if already assigned — useful for the
143
+ * `already-ours` ownership case where the same user might re-attach
144
+ * during a reconnect race).
145
+ */
146
+ export function assignUser(mentraUserId: string): void {
147
+ if (!pool) throw new Error("worker pool not started");
148
+ const existing = pool.userToWorker.get(mentraUserId);
149
+ if (existing) return;
150
+ const slot = pickLeastLoaded(pool);
151
+ slot.sessionCount++;
152
+ slot.ownedUsers.add(mentraUserId);
153
+ pool.userToWorker.set(mentraUserId, slot);
154
+ if (slot.ready) {
155
+ slot.worker.postMessage({
156
+ type: "ATTACH_USER",
157
+ mentraUserId,
158
+ } satisfies WorkerInMessage);
159
+ } else {
160
+ // Worker hasn't finished its Redis-ready bootstrap. Queue the attach;
161
+ // we drain it once WORKER_READY arrives.
162
+ slot.pendingAttaches.push(mentraUserId);
163
+ }
164
+ logger.debug(
165
+ { mentraUserId, workerId: slot.id, sessionCount: slot.sessionCount },
166
+ "user assigned to worker",
167
+ );
168
+ }
169
+
170
+ /**
171
+ * Nudge the worker holding `mentraUserId` to reconcile its subscriptions from
172
+ * the Redis subscription key (the source of truth). Called by the main thread
173
+ * after it seeds the key at `connection.init`. Cross-pod REST writes reach the
174
+ * owning worker through the control stream instead; this IPC path is only for
175
+ * the local same-pod seed. No-op if the user isn't assigned to a worker here.
176
+ *
177
+ * Idempotent: the worker re-reads the key and diffs against its current state,
178
+ * so reissuing the nudge is harmless.
179
+ */
180
+ export function reconcileSubscriptions(mentraUserId: string): void {
181
+ if (!pool) return;
182
+ const slot = pool.userToWorker.get(mentraUserId);
183
+ if (!slot) return;
184
+ const msg: WorkerInMessage = {
185
+ type: "UPDATE_SUBSCRIPTIONS",
186
+ mentraUserId,
187
+ };
188
+ if (slot.ready) {
189
+ slot.worker.postMessage(msg);
190
+ } else {
191
+ slot.pendingSubscriptions.add(mentraUserId);
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Set the audio codec for `mentraUserId` on whichever worker holds them.
197
+ * Called once per session from the connection.init handler, before audio
198
+ * flows. No-op if the user isn't assigned to a worker on this pod.
199
+ */
200
+ export function setUserCodec(
201
+ mentraUserId: string,
202
+ codec: AudioCodec,
203
+ frameSizeBytes?: SetCodecMessage["frameSizeBytes"],
204
+ ): void {
205
+ if (!pool) return;
206
+ const slot = pool.userToWorker.get(mentraUserId);
207
+ if (!slot) return;
208
+ const msg: WorkerInMessage = { type: "SET_CODEC", mentraUserId, codec, frameSizeBytes };
209
+ if (slot.ready) {
210
+ slot.worker.postMessage(msg);
211
+ } else {
212
+ slot.pendingCodecs.set(mentraUserId, msg);
213
+ }
214
+ }
215
+
216
+ export function releaseUser(mentraUserId: string): void {
217
+ if (!pool) return;
218
+ const slot = pool.userToWorker.get(mentraUserId);
219
+ if (!slot) return;
220
+ slot.sessionCount = Math.max(0, slot.sessionCount - 1);
221
+ slot.ownedUsers.delete(mentraUserId);
222
+ pool.userToWorker.delete(mentraUserId);
223
+ try {
224
+ slot.worker.postMessage({
225
+ type: "DETACH_USER",
226
+ mentraUserId,
227
+ } satisfies WorkerInMessage);
228
+ } catch {
229
+ /* worker already dead — its replacement won't have this user */
230
+ }
231
+ logger.debug(
232
+ { mentraUserId, workerId: slot.id, sessionCount: slot.sessionCount },
233
+ "user released from worker",
234
+ );
235
+ }
236
+
237
+ export function getPoolStats(): {
238
+ workerCount: number;
239
+ perWorker: Array<{ id: string; sessionCount: number; ready: boolean }>;
240
+ } {
241
+ if (!pool) return { workerCount: 0, perWorker: [] };
242
+ return {
243
+ workerCount: pool.workers.length,
244
+ perWorker: pool.workers.map((w) => ({
245
+ id: w.id,
246
+ sessionCount: w.sessionCount,
247
+ ready: w.ready,
248
+ })),
249
+ };
250
+ }
251
+
252
+ // === Internals ===
253
+
254
+ function pickLeastLoaded(p: WorkerPoolState): WorkerSlot {
255
+ let best = p.workers[0]!;
256
+ for (let i = 1; i < p.workers.length; i++) {
257
+ if (p.workers[i]!.sessionCount < best.sessionCount) best = p.workers[i]!;
258
+ }
259
+ return best;
260
+ }
261
+
262
+ /**
263
+ * Options for `new Worker`. Identity travels in `workerData` (reliable), not
264
+ * the `env` option, which Bun does not apply to keys the parent already has.
265
+ * Exported for tests.
266
+ */
267
+ export function buildWorkerOptions(workerId: string, podId: string): WorkerOptions {
268
+ // Type cast keeps lib.dom WebWorker types from complaining about the
269
+ // Bun-specific `workerData` option.
270
+ return {
271
+ type: "module",
272
+ workerData: { workerId, podId } satisfies WorkerBootData,
273
+ } as WorkerOptions;
274
+ }
275
+
276
+ function spawnWorkerSlot(id: string): WorkerSlot {
277
+ const worker = new Worker(WORKER_URL, buildWorkerOptions(id, pool?.podId ?? process.env.POD_ID ?? "pod"));
278
+
279
+ const slot: WorkerSlot = {
280
+ id,
281
+ worker,
282
+ sessionCount: 0,
283
+ ready: false,
284
+ ownedUsers: new Set(),
285
+ pendingAttaches: [],
286
+ pendingSubscriptions: new Set(),
287
+ pendingCodecs: new Map(),
288
+ };
289
+
290
+ worker.onmessage = (e: MessageEvent<WorkerOutMessage>) => {
291
+ const msg = e.data;
292
+ if (msg.type === "WORKER_READY") {
293
+ slot.ready = true;
294
+ logger.info({ workerId: id, podId: msg.podId, consumerName: msg.consumerName, pendingAttaches: slot.pendingAttaches.length }, "worker ready");
295
+ // Drain queued attaches and any subscriptions that arrived before ready.
296
+ for (const userId of slot.pendingAttaches) {
297
+ worker.postMessage({ type: "ATTACH_USER", mentraUserId: userId } satisfies WorkerInMessage);
298
+ }
299
+ slot.pendingAttaches.length = 0;
300
+ for (const msg of slot.pendingCodecs.values()) {
301
+ worker.postMessage(msg);
302
+ }
303
+ slot.pendingCodecs.clear();
304
+ for (const userId of slot.pendingSubscriptions) {
305
+ worker.postMessage({
306
+ type: "UPDATE_SUBSCRIPTIONS",
307
+ mentraUserId: userId,
308
+ } satisfies WorkerInMessage);
309
+ }
310
+ slot.pendingSubscriptions.clear();
311
+ return;
312
+ }
313
+ if (msg.type === "TRANSCRIPT_STUB" || msg.type === "TRANSCRIPT" || msg.type === "UDP_LIVENESS_ACK") {
314
+ pool?.transcriptHandler?.(msg);
315
+ return;
316
+ }
317
+ };
318
+
319
+ worker.onerror = (ev: ErrorEvent) => {
320
+ logger.error({ workerId: id, message: ev.message }, "worker error event");
321
+ };
322
+
323
+ // Worker death: Bun fires no standard "exit" event — `terminate()` /
324
+ // crash propagates as the worker becoming unable to postMessage. We
325
+ // wrap with a check on next message attempt; for explicit detection,
326
+ // a stub heartbeat would help. For now (stub stage), restart on
327
+ // catastrophic ws.onerror is good enough.
328
+ return slot;
329
+ }
330
+
331
+ /**
332
+ * Test hook — terminate a worker by index (or all) and respawn. Used by
333
+ * the multi-pod failover tests; not for production use.
334
+ */
335
+ export function _killWorkerForTest(index: number): void {
336
+ if (!pool) return;
337
+ const slot = pool.workers[index];
338
+ if (!slot) return;
339
+ slot.worker.terminate();
340
+ // Reassign its users to other workers.
341
+ const orphans = [...slot.ownedUsers];
342
+ pool.workers[index] = spawnWorkerSlot(slot.id);
343
+ // The new worker comes up empty; reassign orphans via assignUser
344
+ // (which now picks the least-loaded, naturally including the fresh one).
345
+ for (const userId of orphans) {
346
+ pool.userToWorker.delete(userId);
347
+ assignUser(userId);
348
+ }
349
+ }
cloud-v2/packages/runtime/src/services/audio/workers/worker.ts ADDED
@@ -0,0 +1,925 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Audio worker — per-CPU thread that owns a slice of users.
3
+ *
4
+ * What this worker does:
5
+ * 1. Maintains its own ioredis streams client.
6
+ * 2. Receives `ATTACH_USER` / `DETACH_USER` postMessages from the main
7
+ * thread when ownership changes.
8
+ * 3. Runs an XREADGROUP loop for the streams of its currently-assigned
9
+ * users; for each entry it decodes the audio (LC3 to PCM, or passes
10
+ * raw PCM through), feeds it to that user's transcription/translation
11
+ * providers, ACKs the entry, and emits results back to the main thread.
12
+ * 4. Runs an XAUTOCLAIM loop for failover replay — entries stuck in a
13
+ * dead consumer's PEL get picked up here.
14
+ *
15
+ * Two kinds of message go back to the main thread:
16
+ * - TRANSCRIPT: real provider output (text), one per result event.
17
+ * - TRANSCRIPT_STUB: one per stream entry, regardless of subscriptions.
18
+ * It reports "audio reached a worker and decoded to N PCM bytes" and is
19
+ * what the routing/failover tests assert against without needing a
20
+ * provider in the loop.
21
+ *
22
+ * Spec: cloud-v2/docs/issues/002-cloud-runtime/design.md ("Workers handle
23
+ * their own stream reads.")
24
+ */
25
+
26
+ import {Redis} from "ioredis"
27
+ import {workerData} from "node:worker_threads"
28
+ import type {TranscriptionToken} from "@mentra/cloud-protocol"
29
+ import {createLogger} from "@mentra/cloud-shared"
30
+ import {AUDIO_STREAM_GROUP, audioStreamKey} from "../../session/stream"
31
+ import {CONTROL_STREAM_GROUP, controlStreamKey} from "../../session/control-stream"
32
+ import type {SubscriptionRecord} from "../../session/subscriptions-store"
33
+ import {resolveWorkerIdentity} from "./identity"
34
+ import {LC3Decoder} from "./lc3"
35
+ import {createMockProvider} from "../providers/mock"
36
+ import {createSonioxProvider} from "../providers/soniox"
37
+ import type {TranscriptionProvider, TranscriptEvent} from "../providers/provider"
38
+ import {
39
+ subscriptionKey,
40
+ type AudioSubscription,
41
+ type LanguageSource,
42
+ type TranscriptionSubscription,
43
+ } from "../../session/subscriptions"
44
+
45
+ const logger = createLogger("runtime").child({module: "audio-worker"})
46
+
47
+ // === Worker IPC types ===
48
+
49
+ export interface AttachUserMessage {
50
+ type: "ATTACH_USER"
51
+ mentraUserId: string
52
+ }
53
+ export interface DetachUserMessage {
54
+ type: "DETACH_USER"
55
+ mentraUserId: string
56
+ }
57
+ /**
58
+ * Tell the worker to reconcile a user's subscriptions. This is a NUDGE, not a
59
+ * payload: the worker re-reads the `{user:X}:subscriptions` Redis key (the
60
+ * source of truth) and reconciles its provider set from that. The main thread
61
+ * sends this after seeding the key at `connection.init`; the same reconcile
62
+ * also fires when the worker reads a control-stream entry. Keeping the subs out
63
+ * of the message is deliberate: there is exactly one source of truth (the key),
64
+ * so no path can hand the worker a snapshot that disagrees with it.
65
+ */
66
+ export interface UpdateSubscriptionsMessage {
67
+ type: "UPDATE_SUBSCRIPTIONS"
68
+ mentraUserId: string
69
+ }
70
+ /** Audio codec for a user's stream. Set from the client's connection.init. */
71
+ export type AudioCodec = "lc3" | "pcm"
72
+ export type Lc3FrameSizeBytes = 20 | 40 | 60
73
+ export interface SetCodecMessage {
74
+ type: "SET_CODEC"
75
+ mentraUserId: string
76
+ codec: AudioCodec
77
+ frameSizeBytes?: Lc3FrameSizeBytes
78
+ }
79
+ export interface ShutdownMessage {
80
+ type: "SHUTDOWN"
81
+ }
82
+ export type WorkerInMessage =
83
+ | AttachUserMessage
84
+ | DetachUserMessage
85
+ | UpdateSubscriptionsMessage
86
+ | SetCodecMessage
87
+ | ShutdownMessage
88
+
89
+ /**
90
+ * Emitted per Redis Stream entry to signal "audio reached a worker and was
91
+ * decoded." Useful for testing the routing layer without a provider in the
92
+ * loop. Real transcript text comes via TranscriptMessage below.
93
+ */
94
+ export interface TranscriptStubMessage {
95
+ type: "TRANSCRIPT_STUB"
96
+ mentraUserId: string
97
+ seq: number
98
+ /** Length of the raw LC3 payload bytes (before decode). */
99
+ payloadLen: number
100
+ /** Length of the decoded PCM (Int16 mono) in bytes. 0 if decode failed. */
101
+ pcmBytesLen: number
102
+ audioSessionId: string
103
+ /** Where this entry came from — "live" = new XREADGROUP, "replay" = XAUTOCLAIM */
104
+ origin: "live" | "replay"
105
+ }
106
+
107
+ /**
108
+ * Emitted by transcription/translation providers. `kind` discriminates:
109
+ * - "transcription": text is in the source language
110
+ * - "translation": text is in the TARGET language; `sourceLanguage` is set
111
+ * Same shape for both so clients can route via a single handler.
112
+ */
113
+ export interface TranscriptMessage {
114
+ frameTimelineVersion?: 1
115
+ tokens?: TranscriptionToken[]
116
+ type: "TRANSCRIPT"
117
+ kind: "transcription" | "translation"
118
+ mentraUserId: string
119
+ text: string
120
+ isFinal: boolean
121
+ /**
122
+ * Stable id correlating interim + final results for one utterance. The
123
+ * client updates a single card in place across interims and commits it on
124
+ * the final. Undefined for providers that don't track utterances.
125
+ */
126
+ utteranceId?: string
127
+ /** Speaker id if the provider reports diarization. */
128
+ speakerId?: string
129
+ /** Language of the emitted text. */
130
+ language?: string
131
+ /**
132
+ * For translation: the source-audio language — the provider's DETECTED
133
+ * language when it reports one, else the subscription's (may be `"auto"`).
134
+ */
135
+ sourceLanguage?: string
136
+ /** For translation: source-language text of the same window, if available. */
137
+ originalText?: string
138
+ /** Audio timeline window in milliseconds. */
139
+ startMs?: number
140
+ endMs?: number
141
+ /** Provider that produced this — `"mock"`, `"soniox"`, etc. */
142
+ source: string
143
+ /**
144
+ * The subscription that produced this transcript. Carried through so the
145
+ * main thread can build the v2 `stream.transcript` / `stream.translation`
146
+ * result (which echoes the subscription back to the client) without
147
+ * re-deriving it from the language fields.
148
+ */
149
+ subscription: AudioSubscription
150
+ }
151
+
152
+ export interface WorkerReadyMessage {
153
+ type: "WORKER_READY"
154
+ /** Identity this worker resolved at boot (see identity.ts). */
155
+ workerId: string
156
+ podId: string
157
+ consumerName: string
158
+ }
159
+
160
+ export interface UdpLivenessAckMessage {
161
+ type: "UDP_LIVENESS_ACK"
162
+ mentraUserId: string
163
+ sessionTag: number
164
+ audioSessionId: string
165
+ probeId: string
166
+ receivedAt: number
167
+ }
168
+
169
+ export type WorkerOutMessage = TranscriptStubMessage | TranscriptMessage | UdpLivenessAckMessage | WorkerReadyMessage
170
+
171
+ // === Worker state ===
172
+
173
+ const ownedUsers = new Set<string>()
174
+ /** Per-user LC3 decoder. Created on ATTACH_USER, disposed on DETACH_USER. */
175
+ const decoders = new Map<string, LC3Decoder>()
176
+ /**
177
+ * Per-user transcription providers, keyed by subscription identity. A user
178
+ * can have multiple active subscriptions; we keep one provider instance per
179
+ * unique transcription sub.
180
+ *
181
+ * For translation subs, we currently track the sub but don't open a
182
+ * provider — translation lands in a follow-up iteration.
183
+ */
184
+ const userProviders = new Map<string, Map<string, TranscriptionProvider>>()
185
+ const userProviderCreates = new Map<string, Map<string, Promise<TranscriptionProvider>>>()
186
+ /** Most recently received subscription list per user, for reconciliation. */
187
+ const userSubs = new Map<string, AudioSubscription[]>()
188
+ /**
189
+ * Per-user audio codec. "lc3" (default) decodes each stream entry through the
190
+ * LC3 decoder; "pcm" treats the payload as raw Int16 mono PCM and feeds it to
191
+ * providers without decoding. Set from the client's connection.init.
192
+ */
193
+ const userCodecs = new Map<string, AudioCodec>()
194
+ const userLc3FrameSizes = new Map<string, Lc3FrameSizeBytes>()
195
+ let running = true
196
+
197
+ /**
198
+ * Which transcription provider to use. Defaults to the real Soniox provider, so
199
+ * production is real unless told otherwise. Tests can override this when they
200
+ * exercise routing / scaling / failover without depending on transcription.
201
+ */
202
+ const PROVIDER_KIND = process.env.AUDIO_PROVIDER ?? "soniox"
203
+
204
+ const REDIS_URL = process.env.REDIS_URL ?? "redis://127.0.0.1:6379"
205
+ // Identity comes from `workerData` (set by pool.ts); see identity.ts for why
206
+ // the `env` option of `new Worker` is not used.
207
+ const IDENTITY = resolveWorkerIdentity(workerData, {
208
+ WORKER_ID: process.env.WORKER_ID,
209
+ POD_ID: process.env.POD_ID,
210
+ })
211
+ /**
212
+ * Consumer name combines pod + worker so the consumer-group view in Redis
213
+ * shows distinct entries per worker. Useful for ops + lets XAUTOCLAIM
214
+ * reassign entries from a dead worker to a peer on the same pod.
215
+ */
216
+ const CONSUMER_NAME = IDENTITY.consumerName
217
+
218
+ const XREAD_COUNT_PER_STREAM = 100
219
+ const XREAD_IDLE_SLEEP_MS = 50
220
+ /** Both control and audio reads poll per-user (one stream per command) to stay
221
+ * Redis Cluster-safe; this is the idle backoff when no control stream had
222
+ * entries this pass. */
223
+ const CONTROL_IDLE_SLEEP_MS = 100
224
+ const XAUTOCLAIM_COUNT = 500
225
+ const XAUTOCLAIM_MIN_IDLE_MS = 0
226
+ const XAUTOCLAIM_LOOP_INTERVAL_MS = 2_000
227
+
228
+ // Note: we DO want offline queue here, unlike the audio-ingress XADD path.
229
+ // Worker clients do control operations (xgroup, xack, xautoclaim, xreadgroup);
230
+ // briefly queueing those while the socket finishes connecting is harmless.
231
+ // The "don't silently buffer audio for a dead Redis" rationale that drives
232
+ // enableOfflineQueue:false in redis.connection.ts only applies to the
233
+ // main-thread XADD path.
234
+ const streamsClient = new Redis(REDIS_URL, {
235
+ maxRetriesPerRequest: 3,
236
+ })
237
+
238
+ const mainClient = new Redis(REDIS_URL, {
239
+ maxRetriesPerRequest: 3,
240
+ })
241
+
242
+ // Dedicated client for the control-stream read so control polling + XACKs
243
+ // don't serialize behind the audio read's per-user XREADGROUPs (and vice versa).
244
+ const controlClient = new Redis(REDIS_URL, {
245
+ maxRetriesPerRequest: 3,
246
+ })
247
+
248
+ // === Receive assignments from main thread ===
249
+
250
+ declare const self: Worker
251
+
252
+ /**
253
+ * Users whose consumer group has been ensured. We only XREADGROUP for users
254
+ * in this set — the unfiltered `ownedUsers` set gets users added the moment
255
+ * ATTACH_USER arrives, but the group-create is async; gating the read loop
256
+ * on this set avoids the NOGROUP race.
257
+ */
258
+ const readyUsers = new Set<string>()
259
+
260
+ /** Users whose control-stream consumer group has been ensured. */
261
+ const controlReadyUsers = new Set<string>()
262
+
263
+ async function handleAttach(mentraUserId: string): Promise<void> {
264
+ ownedUsers.add(mentraUserId)
265
+ // Decoder is needed for any audio activity; create it eagerly so the very
266
+ // first packet has somewhere to land. Providers are NOT created until the
267
+ // subscription set names one (or never, if the session only wants raw audio
268
+ // routing).
269
+ if (!decoders.has(mentraUserId)) {
270
+ try {
271
+ decoders.set(mentraUserId, await LC3Decoder.create(userLc3FrameSizes.get(mentraUserId) ?? 20))
272
+ } catch (err) {
273
+ logger.error({err}, "LC3Decoder.create failed")
274
+ }
275
+ }
276
+ const ok = await ensureConsumerGroup(mentraUserId)
277
+ // Control-stream group too, so subscription-change nudges for this user land
278
+ // in our consumer once we own them. Independent of the audio group result;
279
+ // we still want to read control even if the audio stream isn't ready yet.
280
+ await ensureControlConsumerGroup(mentraUserId)
281
+ if (ok && ownedUsers.has(mentraUserId)) {
282
+ readyUsers.add(mentraUserId)
283
+ }
284
+ // Reconcile from the subscription key on attach/ownership-acquire. A takeover
285
+ // worker inherits the live subscription set from the key, so providers come
286
+ // back up without waiting for the next REST write. The key is the source of
287
+ // truth; a missing key means "no subscriptions yet" (empty set).
288
+ await reconcileFromKey(mentraUserId)
289
+ }
290
+
291
+ /**
292
+ * Read the user's authoritative subscription set from the Redis key and
293
+ * reconcile providers against it. The key is the single source of truth; this
294
+ * runs on attach, on a control-stream nudge, and on the main thread's
295
+ * post-seed nudge. A missing key reconciles to an empty set.
296
+ */
297
+ async function reconcileFromKey(mentraUserId: string): Promise<void> {
298
+ let subs: AudioSubscription[] = []
299
+ try {
300
+ const raw = await mainClient.get(subscriptionsKey(mentraUserId))
301
+ if (raw) {
302
+ const record = JSON.parse(raw) as SubscriptionRecord
303
+ subs = record.subscriptions ?? []
304
+ }
305
+ } catch (err) {
306
+ logger.error({err}, "reconcileFromKey read failed")
307
+ return
308
+ }
309
+ await reconcileProviders(mentraUserId, subs)
310
+ }
311
+
312
+ /** Subscription key, mirrored from `subscriptions-store.ts` (hash-tagged per user). */
313
+ function subscriptionsKey(mentraUserId: string): string {
314
+ return `{user:${mentraUserId}}:subscriptions`
315
+ }
316
+
317
+ /**
318
+ * Reconcile a user's active providers against a fresh subscription list.
319
+ * Closes providers whose subscriptions disappeared; opens providers for
320
+ * new subs. Idempotent for unchanged subs (no recreation).
321
+ */
322
+ async function reconcileProviders(mentraUserId: string, subs: AudioSubscription[]): Promise<void> {
323
+ userSubs.set(mentraUserId, subs)
324
+
325
+ const existing = userProviders.get(mentraUserId) ?? new Map<string, TranscriptionProvider>()
326
+ userProviders.set(mentraUserId, existing)
327
+ const creating = userProviderCreates.get(mentraUserId) ?? new Map<string, Promise<TranscriptionProvider>>()
328
+ userProviderCreates.set(mentraUserId, creating)
329
+
330
+ // Compute desired set: one entry per subscription, transcription AND
331
+ // translation. They share the provider interface; output messages
332
+ // carry a `kind` discriminator so the client knows which is which.
333
+ const desired = new Map<string, AudioSubscription>()
334
+ for (const sub of subs) {
335
+ desired.set(subscriptionKey(sub), sub)
336
+ }
337
+
338
+ // Close providers whose subs are gone.
339
+ for (const [key, provider] of existing) {
340
+ if (!desired.has(key)) {
341
+ existing.delete(key)
342
+ provider.close().catch((err) => {
343
+ logger.error({err}, "provider close failed")
344
+ })
345
+ }
346
+ }
347
+
348
+ // Open providers for new subs.
349
+ for (const [key, sub] of desired) {
350
+ if (existing.has(key)) continue
351
+ const pending = creating.get(key)
352
+ if (pending) {
353
+ try {
354
+ const provider = await pending
355
+ if (shouldKeepProvider(mentraUserId, key) && !existing.has(key)) {
356
+ existing.set(key, provider)
357
+ } else if (!existing.has(key)) {
358
+ provider.close().catch((err) => {
359
+ logger.error({err}, "provider close failed")
360
+ })
361
+ }
362
+ } catch (err) {
363
+ logger.error({err}, "provider create failed")
364
+ }
365
+ continue
366
+ }
367
+
368
+ const creation = createProvider(mentraUserId, sub)
369
+ creating.set(key, creation)
370
+ try {
371
+ const provider = await creation
372
+ if (shouldKeepProvider(mentraUserId, key) && !existing.has(key)) {
373
+ existing.set(key, provider)
374
+ } else {
375
+ provider.close().catch((err) => {
376
+ logger.error({err}, "provider close failed")
377
+ })
378
+ }
379
+ } catch (err) {
380
+ logger.error({err}, "provider create failed")
381
+ } finally {
382
+ if (creating.get(key) === creation) creating.delete(key)
383
+ if (creating.size === 0) userProviderCreates.delete(mentraUserId)
384
+ }
385
+ }
386
+ }
387
+
388
+ function shouldKeepProvider(mentraUserId: string, key: string): boolean {
389
+ if (!ownedUsers.has(mentraUserId)) return false
390
+ if (!userProviders.has(mentraUserId)) return false
391
+ const subs = userSubs.get(mentraUserId) ?? []
392
+ return subs.some((sub) => subscriptionKey(sub) === key)
393
+ }
394
+
395
+ function langCode(lang: LanguageSource): string {
396
+ return lang.mode === "specific" ? lang.code : "auto"
397
+ }
398
+
399
+ async function createProvider(mentraUserId: string, sub: AudioSubscription): Promise<TranscriptionProvider> {
400
+ const isTranslation = sub.kind === "translation"
401
+ const sourceLanguage = isTranslation ? langCode(sub.source) : undefined
402
+ const target = isTranslation ? sub.target : undefined
403
+ // Provider scope = user + sub identity, for log clarity and as the mock's
404
+ // text-content prefix so multiple subs from the same user produce distinct
405
+ // transcripts.
406
+ const scope = isTranslation
407
+ ? `${mentraUserId}:${sourceLanguage}>${target}`
408
+ : `${mentraUserId}:${langCode((sub as TranscriptionSubscription).language)}`
409
+ const providerLanguage = isTranslation ? (target as string) : langCode((sub as TranscriptionSubscription).language)
410
+ // Detection hints only exist on an auto-mode transcription source; carry them
411
+ // to the provider so `configure({languageHints})` actually biases Soniox
412
+ // (issue 021). A specific language ignores them — the language is the hint.
413
+ const languageHints =
414
+ !isTranslation && sub.kind === "transcription" && sub.language.mode === "auto"
415
+ ? sub.language.hints
416
+ : undefined
417
+
418
+ const onTranscript = (event: TranscriptEvent) => {
419
+ const out: TranscriptMessage = {
420
+ type: "TRANSCRIPT",
421
+ kind: sub.kind,
422
+ mentraUserId,
423
+ text: event.text,
424
+ isFinal: event.isFinal,
425
+ utteranceId: event.utteranceId,
426
+ speakerId: event.speakerId,
427
+ // For transcription: text is in the source/auto language.
428
+ // For translation: text is in the target language.
429
+ language: event.language ?? providerLanguage,
430
+ // Detected source language wins over the subscription's static value
431
+ // (often "auto"), so clients can show what was actually spoken.
432
+ sourceLanguage: event.sourceLanguage ?? sourceLanguage,
433
+ originalText: event.originalText,
434
+ startMs: event.startMs,
435
+ endMs: event.endMs,
436
+ tokens: event.tokens,
437
+ frameTimelineVersion: event.frameTimelineVersion,
438
+ source: PROVIDER_KIND,
439
+ subscription: sub,
440
+ }
441
+ self.postMessage(out)
442
+ }
443
+ const onError = (err: Error) => {
444
+ logger.error({err, mentraUserId}, `provider(${PROVIDER_KIND}) error`)
445
+ }
446
+
447
+ switch (PROVIDER_KIND) {
448
+ case "mock":
449
+ return createMockProvider({
450
+ scope,
451
+ language: providerLanguage,
452
+ onTranscript,
453
+ onError,
454
+ })
455
+ case "soniox":
456
+ return createSonioxProvider({
457
+ scope,
458
+ // Soniox: source language config in either case. For translation
459
+ // subs we additionally pass `targetLanguage` — Soniox does the
460
+ // translation in-session and we filter result tokens accordingly.
461
+ language: isTranslation ? (sourceLanguage as string) : langCode((sub as TranscriptionSubscription).language),
462
+ languageHints,
463
+ targetLanguage: isTranslation ? (target as string) : undefined,
464
+ onTranscript,
465
+ onError,
466
+ })
467
+ default:
468
+ throw new Error(`unknown AUDIO_PROVIDER: ${PROVIDER_KIND}`)
469
+ }
470
+ }
471
+
472
+ self.onmessage = (e: MessageEvent<WorkerInMessage>) => {
473
+ const msg = e.data
474
+ switch (msg.type) {
475
+ case "ATTACH_USER":
476
+ void handleAttach(msg.mentraUserId)
477
+ break
478
+ case "SET_CODEC":
479
+ userCodecs.set(msg.mentraUserId, msg.codec)
480
+ if (msg.frameSizeBytes) {
481
+ userLc3FrameSizes.set(msg.mentraUserId, msg.frameSizeBytes)
482
+ const existing = decoders.get(msg.mentraUserId)
483
+ if (existing && existing.frameBytes !== msg.frameSizeBytes) {
484
+ void LC3Decoder.create(msg.frameSizeBytes)
485
+ .then((decoder) => {
486
+ decoders.set(msg.mentraUserId, decoder)
487
+ })
488
+ .catch((err) => {
489
+ logger.error({err}, "LC3Decoder.create failed")
490
+ })
491
+ }
492
+ }
493
+ break
494
+ case "DETACH_USER": {
495
+ ownedUsers.delete(msg.mentraUserId)
496
+ readyUsers.delete(msg.mentraUserId)
497
+ controlReadyUsers.delete(msg.mentraUserId)
498
+ decoders.delete(msg.mentraUserId)
499
+ userLc3FrameSizes.delete(msg.mentraUserId)
500
+ userSubs.delete(msg.mentraUserId)
501
+ userCodecs.delete(msg.mentraUserId)
502
+ userProviderCreates.delete(msg.mentraUserId)
503
+ const providers = userProviders.get(msg.mentraUserId)
504
+ if (providers) {
505
+ userProviders.delete(msg.mentraUserId)
506
+ for (const provider of providers.values()) {
507
+ provider.close().catch((err) => {
508
+ logger.error({err}, "provider close failed")
509
+ })
510
+ }
511
+ }
512
+ break
513
+ }
514
+ case "UPDATE_SUBSCRIPTIONS":
515
+ // Nudge: re-read the subscription key and reconcile. The message carries
516
+ // no subs on purpose; the key is the source of truth.
517
+ void reconcileFromKey(msg.mentraUserId)
518
+ break
519
+ case "SHUTDOWN":
520
+ running = false
521
+ void shutdown()
522
+ break
523
+ }
524
+ }
525
+
526
+ async function ensureConsumerGroup(mentraUserId: string): Promise<boolean> {
527
+ try {
528
+ // Group start = `0` (beginning of stream) rather than `$` (end of stream
529
+ // = new entries only). Reason: UDP ingress may have XADDed packets to
530
+ // the stream BEFORE the worker finished creating the group (the assign
531
+ // happens at WS-open time, but UDP packets can arrive within
532
+ // milliseconds of connection.ack reaching the client). `$` would
533
+ // silently skip those entries. `0` delivers everything that's in the
534
+ // stream — `MAXLEN ~ 1000` keeps the backlog bounded so this isn't
535
+ // unbounded replay.
536
+ await mainClient.xgroup("CREATE", audioStreamKey(mentraUserId), AUDIO_STREAM_GROUP, "0", "MKSTREAM")
537
+ return true
538
+ } catch (err) {
539
+ const msg = (err as Error).message ?? ""
540
+ // BUSYGROUP = "already exists" — that's success for our purposes.
541
+ if (msg.includes("BUSYGROUP")) return true
542
+ logger.error({err}, "xgroup create failed")
543
+ return false
544
+ }
545
+ }
546
+
547
+ async function ensureControlConsumerGroup(mentraUserId: string): Promise<boolean> {
548
+ try {
549
+ // Start at `0` rather than `$`: UDP liveness ACKs can be published by a
550
+ // non-owner pod milliseconds after connection.ack, before the owner worker
551
+ // has finished creating this group. Starting at `$` would skip that ACK
552
+ // forever. Control streams are bounded and nudges are idempotent, so
553
+ // replaying a tiny backlog is safer than missing a liveness result.
554
+ await controlClient.xgroup("CREATE", controlStreamKey(mentraUserId), CONTROL_STREAM_GROUP, "0", "MKSTREAM")
555
+ controlReadyUsers.add(mentraUserId)
556
+ return true
557
+ } catch (err) {
558
+ const msg = (err as Error).message ?? ""
559
+ if (msg.includes("BUSYGROUP")) {
560
+ controlReadyUsers.add(mentraUserId)
561
+ return true
562
+ }
563
+ logger.error({err}, "control xgroup create failed")
564
+ return false
565
+ }
566
+ }
567
+
568
+ // === Main loops ===
569
+
570
+ /**
571
+ * Read the control stream for owned users and reconcile on each nudge. Separate
572
+ * from the audio loop (and on its own Redis client) so subscription changes are
573
+ * never stuck behind the blocking audio read, and the audio hot path never has
574
+ * to branch on control entries.
575
+ */
576
+ async function controlReadLoop(): Promise<void> {
577
+ while (running) {
578
+ const users = [...controlReadyUsers]
579
+ if (users.length === 0) {
580
+ await Bun.sleep(100)
581
+ continue
582
+ }
583
+
584
+ let sawEntries = false
585
+ for (const userId of users) {
586
+ try {
587
+ // One stream per command: Redis Cluster requires all keys in a command
588
+ // to share a hash slot, and each user's control stream hashes to that
589
+ // user. A per-user read avoids CROSSSLOT (mirrors freshReadLoop).
590
+ const result = (await controlClient.xreadgroup(
591
+ "GROUP",
592
+ CONTROL_STREAM_GROUP,
593
+ CONSUMER_NAME,
594
+ "COUNT",
595
+ 100,
596
+ "STREAMS",
597
+ controlStreamKey(userId),
598
+ ">",
599
+ )) as Array<[string, Array<[string, string[]]>]> | null
600
+
601
+ if (!result) continue
602
+ sawEntries = true
603
+
604
+ for (const [streamKey, entries] of result) {
605
+ const mentraUserId = controlUserFromKey(streamKey)
606
+ let shouldReconcile = false
607
+
608
+ for (const [, fields] of entries) {
609
+ const map = fieldArrayToMap(fields)
610
+ switch (map.kind) {
611
+ case "subscriptions-changed":
612
+ // Reconcile once per batch, not once per entry: every subscription
613
+ // entry is the same "re-read the key" nudge.
614
+ shouldReconcile = true
615
+ break
616
+ case "udp-liveness-ack":
617
+ logger.debug(
618
+ {
619
+ mentraUserId,
620
+ sessionTag: map.sessionTag,
621
+ probeId: map.probeId,
622
+ },
623
+ "udp liveness ack control received",
624
+ )
625
+ self.postMessage({
626
+ type: "UDP_LIVENESS_ACK",
627
+ mentraUserId,
628
+ sessionTag: Number(map.sessionTag ?? 0),
629
+ audioSessionId: map.audioSessionId ?? "",
630
+ probeId: map.probeId ?? "",
631
+ receivedAt: Number(map.receivedAt ?? Date.now()),
632
+ } satisfies UdpLivenessAckMessage)
633
+ break
634
+ }
635
+ }
636
+
637
+ if (shouldReconcile) await reconcileFromKey(mentraUserId)
638
+
639
+ for (const [entryId] of entries) {
640
+ try {
641
+ await controlClient.xack(streamKey, CONTROL_STREAM_GROUP, entryId)
642
+ } catch (err) {
643
+ logger.error({err}, "control xack failed")
644
+ }
645
+ }
646
+ }
647
+ } catch (err) {
648
+ const msg = (err as Error).message ?? ""
649
+ if (msg.includes("NOGROUP")) {
650
+ await ensureControlConsumerGroup(userId)
651
+ continue
652
+ }
653
+ logger.error({err}, "control xreadgroup failed")
654
+ await Bun.sleep(500)
655
+ }
656
+ }
657
+ if (!sawEntries) await Bun.sleep(CONTROL_IDLE_SLEEP_MS)
658
+ }
659
+ }
660
+
661
+ /** Recover the user id from a `{user:X}:control` stream key. */
662
+ function controlUserFromKey(streamKey: string): string {
663
+ return streamKey.replace(/^\{user:/, "").replace(/\}:control$/, "")
664
+ }
665
+
666
+ async function freshReadLoop(): Promise<void> {
667
+ while (running) {
668
+ // Only stream-read for users whose consumer group has been verified to
669
+ // exist. A user that JUST ATTACHed but hasn't finished XGROUP CREATE
670
+ // yet skips this iteration; they're picked up once group-ensure resolves.
671
+ const users = [...readyUsers]
672
+ if (users.length === 0) {
673
+ await Bun.sleep(100)
674
+ continue
675
+ }
676
+
677
+ let sawEntries = false
678
+ for (const userId of users) {
679
+ try {
680
+ // One stream per command: Redis Cluster requires all keys in a command
681
+ // to share a hash slot, and each user's audio stream intentionally
682
+ // hashes to that user. A per-user read avoids CROSSSLOT while keeping
683
+ // the worker's ownership set unchanged.
684
+ const result = (await streamsClient.xreadgroup(
685
+ "GROUP",
686
+ AUDIO_STREAM_GROUP,
687
+ CONSUMER_NAME,
688
+ "COUNT",
689
+ XREAD_COUNT_PER_STREAM,
690
+ "STREAMS",
691
+ audioStreamKey(userId),
692
+ ">",
693
+ )) as Array<[string, Array<[string, string[]]>]> | null
694
+
695
+ if (result) {
696
+ sawEntries = true
697
+ await processBatch(result, "live")
698
+ }
699
+ } catch (err) {
700
+ const msg = (err as Error).message ?? ""
701
+ // NOGROUP can happen if a stream got DEL'd out from under us (tests
702
+ // wipe Redis between cases; production this would only happen if
703
+ // someone manually nuked a stream key). Re-ensure this user's group;
704
+ // the next iteration picks up cleanly.
705
+ if (msg.includes("NOGROUP")) {
706
+ await ensureConsumerGroup(userId)
707
+ continue
708
+ }
709
+ logger.error({err}, "xreadgroup failed")
710
+ await Bun.sleep(500)
711
+ }
712
+ }
713
+ if (!sawEntries) await Bun.sleep(XREAD_IDLE_SLEEP_MS)
714
+ }
715
+ }
716
+
717
+ async function autoclaimLoop(): Promise<void> {
718
+ while (running) {
719
+ for (const userId of readyUsers) {
720
+ try {
721
+ await drainAutoclaim(userId)
722
+ } catch (err) {
723
+ logger.error({err}, "autoclaim failed")
724
+ }
725
+ }
726
+ await Bun.sleep(XAUTOCLAIM_LOOP_INTERVAL_MS)
727
+ }
728
+ }
729
+
730
+ async function drainAutoclaim(userId: string): Promise<void> {
731
+ let cursor = "0-0"
732
+ while (running) {
733
+ let result: [string, Array<[string, string[]]>, string[]] | null = null
734
+ try {
735
+ // XAUTOCLAIM <key> <group> <consumer> <min-idle-ms> <start-id> COUNT N
736
+ // Returns [next-cursor, [[id, [field, value, ...]], ...]]
737
+ result = (await mainClient.xautoclaim(
738
+ audioStreamKey(userId),
739
+ AUDIO_STREAM_GROUP,
740
+ CONSUMER_NAME,
741
+ XAUTOCLAIM_MIN_IDLE_MS,
742
+ cursor,
743
+ "COUNT",
744
+ XAUTOCLAIM_COUNT,
745
+ )) as [string, Array<[string, string[]]>, string[]]
746
+ } catch (err) {
747
+ const msg = (err as Error).message ?? ""
748
+ // Stream got dropped; re-ensure and bail. Next loop iteration retries.
749
+ if (msg.includes("NOGROUP")) {
750
+ await ensureConsumerGroup(userId)
751
+ return
752
+ }
753
+ throw err
754
+ }
755
+
756
+ if (!result) return
757
+ const [nextCursor, entries] = result
758
+
759
+ if (entries.length === 0) return
760
+ await processBatch([[audioStreamKey(userId), entries]], "replay")
761
+
762
+ if (nextCursor === "0-0") return // Redis convention: done.
763
+ cursor = nextCursor
764
+ }
765
+ }
766
+
767
+ async function processBatch(
768
+ result: Array<[string, Array<[string, string[]]>]>,
769
+ origin: "live" | "replay",
770
+ ): Promise<void> {
771
+ for (const [streamKey, entries] of result) {
772
+ // Stream keys are `{user:X}:audio` (hash-tagged so a user's keys share a
773
+ // cluster shard — see audioStreamKey). The old `audio:X` parse silently
774
+ // produced a mangled user id, so decoder/provider lookups missed and every
775
+ // frame was dropped on the floor (providers saw "No audio received").
776
+ const keyMatch = /^\{user:(.+)\}:audio$/.exec(streamKey)
777
+ const mentraUserId = keyMatch ? keyMatch[1]! : streamKey.replace(/^audio:/, "")
778
+ const decoder = decoders.get(mentraUserId)
779
+ const codec = userCodecs.get(mentraUserId) ?? "lc3"
780
+
781
+ for (const [entryId, fields] of entries) {
782
+ const map = fieldArrayToMap(fields)
783
+ const seq = Number(map.seq ?? 0)
784
+ const audioSessionId = map.audioSessionId ?? ""
785
+
786
+ // Recover the binary payload from the base64 we encoded on XADD.
787
+ const payloadBytes = typeof map.payload === "string" ? Buffer.from(map.payload, "base64") : Buffer.alloc(0)
788
+ const payloadLen = payloadBytes.byteLength
789
+
790
+ // Turn the payload into Int16 mono PCM, then feed it to each subscribed
791
+ // provider for this user. For "lc3" we decode; for "pcm" the payload
792
+ // already IS PCM, so we wrap it as Int16 directly (no encoder needed on
793
+ // the sending side — handy for tests and raw-PCM clients).
794
+ //
795
+ // If the user has no subscriptions, the PCM is computed (so the
796
+ // TRANSCRIPT_STUB byte count is accurate) but no provider fires — the
797
+ // correct behavior for a session that hasn't asked to be transcribed.
798
+ let pcm: Int16Array | null = null
799
+ if (payloadLen > 0) {
800
+ if (codec === "pcm") {
801
+ // Align to Int16 (drop a trailing odd byte if present).
802
+ const usableSamples = Math.floor(payloadLen / 2)
803
+ pcm = new Int16Array(payloadBytes.buffer, payloadBytes.byteOffset, usableSamples)
804
+ } else if (decoder) {
805
+ pcm = decoder.decode(new Uint8Array(payloadBytes.buffer, payloadBytes.byteOffset, payloadLen))
806
+ }
807
+ }
808
+
809
+ let pcmBytesLen = 0
810
+ if (pcm) {
811
+ pcmBytesLen = pcm.byteLength
812
+ const providers = userProviders.get(mentraUserId)
813
+ if (providers) {
814
+ for (const provider of providers.values()) {
815
+ try {
816
+ const offsetMs = map.offsetMs === "" || map.offsetMs == null ? NaN : Number(map.offsetMs)
817
+ const sessionTag = Number(map.sessionTag)
818
+ provider.writeAudio(
819
+ pcm,
820
+ Number.isFinite(offsetMs) && offsetMs >= 0 && Number.isInteger(sessionTag)
821
+ ? {sessionTag, offsetMs}
822
+ : undefined,
823
+ )
824
+ } catch (err) {
825
+ logger.error({err}, "provider.writeAudio failed")
826
+ }
827
+ }
828
+ }
829
+ }
830
+
831
+ // One log per ~5s of audio (every 128th entry) so the feed path is
832
+ // observable without flooding: payload size, codec, decode result, and
833
+ // how many providers the PCM actually reached.
834
+ if (seq % 128 === 0) {
835
+ logger.info(
836
+ {
837
+ mentraUserId,
838
+ seq,
839
+ payloadBytes: payloadLen,
840
+ codec,
841
+ hasDecoder: decoders.has(mentraUserId),
842
+ pcmBytes: pcmBytesLen,
843
+ providers: userProviders.get(mentraUserId)?.size ?? 0,
844
+ },
845
+ "feed",
846
+ )
847
+ }
848
+
849
+ const out: TranscriptStubMessage = {
850
+ type: "TRANSCRIPT_STUB",
851
+ mentraUserId,
852
+ seq,
853
+ payloadLen,
854
+ pcmBytesLen,
855
+ audioSessionId,
856
+ origin,
857
+ }
858
+ self.postMessage(out)
859
+
860
+ // ACK so Redis can stop tracking this in our consumer's PEL.
861
+ try {
862
+ await streamsClient.xack(streamKey, AUDIO_STREAM_GROUP, entryId)
863
+ } catch (err) {
864
+ logger.error({err}, "xack failed")
865
+ }
866
+ }
867
+ }
868
+ }
869
+
870
+ function fieldArrayToMap(fields: string[]): Record<string, string> {
871
+ const out: Record<string, string> = {}
872
+ for (let i = 0; i < fields.length; i += 2) {
873
+ out[fields[i]!] = fields[i + 1]!
874
+ }
875
+ return out
876
+ }
877
+
878
+ // === Lifecycle ===
879
+
880
+ async function shutdown(): Promise<void> {
881
+ try {
882
+ await Promise.all([
883
+ streamsClient.quit().catch(() => undefined),
884
+ mainClient.quit().catch(() => undefined),
885
+ controlClient.quit().catch(() => undefined),
886
+ ])
887
+ } catch {
888
+ /* ignore */
889
+ }
890
+ }
891
+
892
+ // Boot: wait for BOTH Redis clients to be `ready` before announcing
893
+ // WORKER_READY. ioredis with `enableOfflineQueue: false` rejects commands
894
+ // during the connecting phase, so any ATTACH_USER that arrives before the
895
+ // clients are up would hit "Stream isn't writeable."
896
+ async function bootstrap(): Promise<void> {
897
+ await Promise.all([waitForReady(streamsClient), waitForReady(mainClient), waitForReady(controlClient)])
898
+ self.postMessage({
899
+ type: "WORKER_READY",
900
+ workerId: IDENTITY.workerId,
901
+ podId: IDENTITY.podId,
902
+ consumerName: IDENTITY.consumerName,
903
+ } satisfies WorkerReadyMessage)
904
+ void freshReadLoop()
905
+ void autoclaimLoop()
906
+ void controlReadLoop()
907
+ }
908
+
909
+ function waitForReady(client: Redis): Promise<void> {
910
+ if (client.status === "ready") return Promise.resolve()
911
+ return new Promise<void>((resolve, reject) => {
912
+ const onReady = () => {
913
+ client.off("error", onError)
914
+ resolve()
915
+ }
916
+ const onError = (err: Error) => {
917
+ client.off("ready", onReady)
918
+ reject(err)
919
+ }
920
+ client.once("ready", onReady)
921
+ client.once("error", onError)
922
+ })
923
+ }
924
+
925
+ void bootstrap()
cloud-v2/packages/runtime/src/services/camera/camera.service.ts ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Camera service: managed photo + managed stream.
3
+ *
4
+ * Sits on top of the storage service. A managed photo is a request-then-push
5
+ * flow: presign an upload + read URL, record the pending request, and push
6
+ * `photo.ready` when the upload lands. Completion arrives one of two ways:
7
+ * - local provider: the runtime serves the upload, so its PUT handler calls
8
+ * `completeUpload` directly (instant, no polling).
9
+ * - r2/s3 provider: the object-created event reaches the storage webhook,
10
+ * which calls `completeUpload`.
11
+ * The device (glasses) does the actual capture + upload to the presigned URL.
12
+ *
13
+ * Managed stream is provisioned synchronously (stub coordinates today; a real
14
+ * Cloudflare Stream provider lands later) and has no push.
15
+ *
16
+ * Pending requests live in Redis keyed by requestId, so a completion event that
17
+ * lands on any pod can resolve the user to push to. The push itself currently
18
+ * targets the user's WS on this pod; cross-pod push routing lands with the same
19
+ * work the audio path needs.
20
+ *
21
+ * Spec: docs/issues/002-cloud-runtime/camera/spec.md.
22
+ */
23
+
24
+ import { ulid } from "ulid";
25
+ import { createLogger } from "@mentra/cloud-shared";
26
+ import { getRedis } from "../../clients/redis.client";
27
+ import { getStorageProvider } from "../storage/storage.service";
28
+ import {
29
+ provisionStream,
30
+ stopStream as stopManagedStream,
31
+ streamStatus as getManagedStreamStatus,
32
+ } from "../stream/stream.service";
33
+ import { forwardToUserSessions } from "../../net/ws";
34
+ import { PROTOCOL_MAJOR } from "@mentra/cloud-protocol/envelope";
35
+ import type {
36
+ StreamOptions,
37
+ ManagedStream,
38
+ StreamStatusResult,
39
+ } from "@mentra/cloud-protocol/camera";
40
+
41
+ const logger = createLogger("audio").child({ service: "camera.service" });
42
+
43
+ const PHOTO_CONTENT_TYPE = "image/jpeg";
44
+ /** Pending photo requests TTL: long enough for an upload, then abandoned. */
45
+ const PHOTO_REQUEST_TTL_SEC = 300;
46
+
47
+ interface PendingPhoto {
48
+ mentraUserId: string;
49
+ key: string;
50
+ readUrl: string;
51
+ }
52
+
53
+ function photoKey(requestId: string): string {
54
+ return `photos/${requestId}`;
55
+ }
56
+ function requestIdFromKey(key: string): string | null {
57
+ return key.startsWith("photos/") ? key.slice("photos/".length) : null;
58
+ }
59
+ function pendingRedisKey(requestId: string): string {
60
+ return `photo-request:${requestId}`;
61
+ }
62
+
63
+ export interface PhotoRequestResult {
64
+ requestId: string;
65
+ uploadUrl: string;
66
+ readUrl: string;
67
+ }
68
+
69
+ /**
70
+ * Create a managed-photo request: presign the upload + read URLs and record the
71
+ * pending request. Returns the URLs the device uses; the caller gets
72
+ * `photo.ready` over its WS on completion.
73
+ */
74
+ export async function requestPhoto(
75
+ mentraUserId: string,
76
+ origin: string,
77
+ ): Promise<PhotoRequestResult> {
78
+ const provider = getStorageProvider();
79
+ const requestId = `photo_${ulid()}`;
80
+ const key = photoKey(requestId);
81
+
82
+ const upload = await provider.presignUpload(key, {
83
+ contentType: PHOTO_CONTENT_TYPE,
84
+ origin,
85
+ });
86
+ const readUrl = await provider.presignDownload(key, { origin });
87
+
88
+ const pending: PendingPhoto = { mentraUserId, key, readUrl };
89
+ await getRedis().set(
90
+ pendingRedisKey(requestId),
91
+ JSON.stringify(pending),
92
+ "EX",
93
+ PHOTO_REQUEST_TTL_SEC,
94
+ );
95
+
96
+ logger.info({ mentraUserId, requestId, provider: provider.name }, "managed photo requested");
97
+
98
+ // The device (glasses) uploads the captured image to `uploadUrl` out of band.
99
+ // Completion arrives via the local upload handler (local provider) or the
100
+ // storage-events webhook (r2/s3); both call `completeUpload`.
101
+ return { requestId, uploadUrl: upload.url, readUrl };
102
+ }
103
+
104
+ /**
105
+ * Mark a photo upload complete and push `photo.ready` to the requester. Called
106
+ * by the local provider's upload handler and by the storage event webhook.
107
+ * Idempotent: a duplicate event finds no pending entry and is a no-op.
108
+ */
109
+ export async function completeUpload(key: string): Promise<void> {
110
+ const requestId = requestIdFromKey(key);
111
+ if (!requestId) return;
112
+ const pending = await takePending(requestId);
113
+ if (!pending) return;
114
+
115
+ forwardToUserSessions(pending.mentraUserId, {
116
+ v: PROTOCOL_MAJOR,
117
+ type: "photo.ready",
118
+ timestamp: Date.now(),
119
+ payload: { requestId, readUrl: pending.readUrl },
120
+ });
121
+ logger.info({ mentraUserId: pending.mentraUserId, requestId }, "managed photo ready");
122
+ }
123
+
124
+ /** Mark a photo request failed and push `photo.error`. */
125
+ export async function failUpload(requestId: string, reason: string): Promise<void> {
126
+ const pending = await takePending(requestId);
127
+ if (!pending) return;
128
+ forwardToUserSessions(pending.mentraUserId, {
129
+ v: PROTOCOL_MAJOR,
130
+ type: "photo.error",
131
+ timestamp: Date.now(),
132
+ payload: { requestId, reason },
133
+ });
134
+ logger.warn({ mentraUserId: pending.mentraUserId, requestId, reason }, "managed photo failed");
135
+ }
136
+
137
+ /** Read and remove a pending request, so it settles exactly once. */
138
+ async function takePending(requestId: string): Promise<PendingPhoto | null> {
139
+ const redis = getRedis();
140
+ const raw = await redis.get(pendingRedisKey(requestId));
141
+ if (!raw) return null;
142
+ await redis.del(pendingRedisKey(requestId));
143
+ try {
144
+ return JSON.parse(raw) as PendingPhoto;
145
+ } catch {
146
+ return null;
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Provision a managed stream on the configured stream provider (Cloudflare
152
+ * Stream). Fully answered by this response (no push). Throws if no stream
153
+ * provider is configured, rather than returning fake coordinates.
154
+ */
155
+ export async function startStream(
156
+ mentraUserId: string,
157
+ opts: StreamOptions,
158
+ ): Promise<ManagedStream> {
159
+ const stream = await provisionStream(mentraUserId, opts);
160
+ logger.info({ mentraUserId, streamId: stream.streamId }, "managed stream provisioned");
161
+ return stream;
162
+ }
163
+
164
+ /** The provider's view of a managed stream's ingest (is the push arriving?). */
165
+ export async function streamStatus(
166
+ mentraUserId: string,
167
+ streamId: string,
168
+ ): Promise<StreamStatusResult> {
169
+ void mentraUserId;
170
+ return await getManagedStreamStatus(streamId);
171
+ }
172
+
173
+ /** Stop a managed stream. */
174
+ export async function stopStream(mentraUserId: string, streamId: string): Promise<void> {
175
+ await stopManagedStream(streamId);
176
+ logger.info({ mentraUserId, streamId }, "managed stream stopped");
177
+ }
cloud-v2/packages/runtime/src/services/maps/maps.service.test.ts ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Tests for the maps service: cache behavior + provider dispatch.
3
+ *
4
+ * These exercise the REAL Mapbox provider (createMapboxProvider) against a
5
+ * stubbed `globalThis.fetch`, so we cover the full path — service -> promise
6
+ * cache -> provider -> normalization — without a network or a real token. The
7
+ * fetch stub also counts calls, which is how we assert the cache's headline
8
+ * behaviors: a hit serves without a second upstream call, and concurrent
9
+ * identical calls coalesce onto ONE call (in-flight dedup).
10
+ *
11
+ * Env + cache state is module-global (provider singleton, two caches), so each
12
+ * test restores `MAPBOX_ACCESS_TOKEN`, resets the provider, clears the caches,
13
+ * and restores the original fetch in afterEach.
14
+ */
15
+ import { describe, test, expect, afterEach } from "bun:test";
16
+
17
+ import {
18
+ directions,
19
+ reverseGeocode,
20
+ placeAutocomplete,
21
+ placeDetails,
22
+ resetMapsProvider,
23
+ clearMapsCaches,
24
+ } from "./maps.service";
25
+
26
+ const realFetch = globalThis.fetch;
27
+ const savedToken = process.env.MAPBOX_ACCESS_TOKEN;
28
+
29
+ /**
30
+ * Install a fake `fetch` that returns `body` (JSON) for every call and counts
31
+ * how many times it was invoked. Returns the counter so a test can assert the
32
+ * cache suppressed/coalesced upstream calls.
33
+ */
34
+ function stubFetch(body: unknown, status = 200): { calls: () => number } {
35
+ let count = 0;
36
+ globalThis.fetch = (async () => {
37
+ count += 1;
38
+ return new Response(JSON.stringify(body), { status });
39
+ }) as unknown as typeof fetch;
40
+ return { calls: () => count };
41
+ }
42
+
43
+ /** A minimal Mapbox Directions response with one route + one step. */
44
+ function mapboxDirectionsBody() {
45
+ return {
46
+ routes: [
47
+ {
48
+ // polyline6 for a couple of points near SF; exact geometry is not
49
+ // asserted, only that decoding produces points.
50
+ geometry: "yapwFhhbjV???",
51
+ distance: 1234,
52
+ duration: 567,
53
+ legs: [
54
+ {
55
+ steps: [
56
+ {
57
+ distance: 1234,
58
+ name: "Fell St",
59
+ maneuver: { type: "depart", modifier: "left", instruction: "Head out" },
60
+ geometry: "yapwFhhbjV",
61
+ },
62
+ ],
63
+ },
64
+ ],
65
+ },
66
+ ],
67
+ };
68
+ }
69
+
70
+ /**
71
+ * A minimal Mapbox reverse-geocode response carrying a street name + full
72
+ * address. When `road` is null, returns no features (the off-grid case).
73
+ */
74
+ function mapboxGeocodeBody(road: string | null, fullAddress?: string) {
75
+ return {
76
+ features: road
77
+ ? [
78
+ {
79
+ properties: {
80
+ name: road,
81
+ full_address: fullAddress ?? `123 ${road}, San Francisco, California`,
82
+ context: { street: { name: road } },
83
+ },
84
+ },
85
+ ]
86
+ : [],
87
+ };
88
+ }
89
+
90
+ const REQ = {
91
+ origin: { lat: 37.7749, lng: -122.4194 },
92
+ stops: [{ lat: 37.7858, lng: -122.4064 }],
93
+ mode: "walking" as const,
94
+ };
95
+
96
+ afterEach(() => {
97
+ globalThis.fetch = realFetch;
98
+ if (savedToken === undefined) {
99
+ delete process.env.MAPBOX_ACCESS_TOKEN;
100
+ } else {
101
+ process.env.MAPBOX_ACCESS_TOKEN = savedToken;
102
+ }
103
+ resetMapsProvider();
104
+ clearMapsCaches();
105
+ });
106
+
107
+ describe("maps.service directions", () => {
108
+ test("returns normalized routes from the provider", async () => {
109
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
110
+ stubFetch(mapboxDirectionsBody());
111
+
112
+ const result = await directions(REQ);
113
+
114
+ expect(result.routes).toHaveLength(1);
115
+ expect(result.routes[0].totalDistanceMeters).toBe(1234);
116
+ expect(result.routes[0].totalDurationSeconds).toBe(567);
117
+ // The neutral step carries the road name + mapped maneuver, not Mapbox shapes.
118
+ expect(result.routes[0].steps?.[0].road).toBe("Fell St");
119
+ expect(result.routes[0].steps?.[0].maneuver).toBe("DEPART");
120
+ });
121
+
122
+ test("a second identical request is served from cache (no second fetch)", async () => {
123
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
124
+ const fetchStub = stubFetch(mapboxDirectionsBody());
125
+
126
+ await directions(REQ);
127
+ await directions(REQ);
128
+
129
+ expect(fetchStub.calls()).toBe(1);
130
+ });
131
+
132
+ test("concurrent identical requests coalesce onto one upstream call (in-flight dedup)", async () => {
133
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
134
+ const fetchStub = stubFetch(mapboxDirectionsBody());
135
+
136
+ // Fire many at once, before the first resolves, so they hit the in-flight
137
+ // promise rather than a settled cache entry.
138
+ const results = await Promise.all(
139
+ Array.from({ length: 50 }, () => directions(REQ)),
140
+ );
141
+
142
+ expect(results).toHaveLength(50);
143
+ expect(fetchStub.calls()).toBe(1);
144
+ });
145
+
146
+ test("a different request is a cache miss (separate fetch)", async () => {
147
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
148
+ const fetchStub = stubFetch(mapboxDirectionsBody());
149
+
150
+ await directions(REQ);
151
+ await directions({ ...REQ, mode: "driving" });
152
+
153
+ expect(fetchStub.calls()).toBe(2);
154
+ });
155
+
156
+ test("an upstream failure is NOT cached: the next call retries upstream", async () => {
157
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
158
+ // First a 500 (provider throws), then a success.
159
+ let call = 0;
160
+ globalThis.fetch = (async () => {
161
+ call += 1;
162
+ if (call === 1) return new Response("upstream boom", { status: 500 });
163
+ return new Response(JSON.stringify(mapboxDirectionsBody()), { status: 200 });
164
+ }) as unknown as typeof fetch;
165
+
166
+ await expect(directions(REQ)).rejects.toThrow();
167
+ // The failure must have been evicted, so this re-hits upstream and succeeds.
168
+ const ok = await directions(REQ);
169
+ expect(ok.routes).toHaveLength(1);
170
+ expect(call).toBe(2);
171
+ });
172
+
173
+ test("throws a clear error when MAPBOX_ACCESS_TOKEN is unset", async () => {
174
+ delete process.env.MAPBOX_ACCESS_TOKEN;
175
+ stubFetch(mapboxDirectionsBody());
176
+
177
+ await expect(directions(REQ)).rejects.toThrow(/MAPBOX_ACCESS_TOKEN/);
178
+ });
179
+ });
180
+
181
+ describe("maps.service reverseGeocode", () => {
182
+ test("returns the resolved road name + full address", async () => {
183
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
184
+ stubFetch(mapboxGeocodeBody("Market St", "1 Market St, San Francisco, California 94105"));
185
+
186
+ const result = await reverseGeocode({ lat: 37.7749, lng: -122.4194 });
187
+
188
+ expect(result.road).toBe("Market St");
189
+ expect(result.address).toBe("1 Market St, San Francisco, California 94105");
190
+ });
191
+
192
+ test("returns { road: null, address: null } when nothing is found nearby", async () => {
193
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
194
+ stubFetch(mapboxGeocodeBody(null));
195
+
196
+ const result = await reverseGeocode({ lat: 0, lng: 0 });
197
+
198
+ expect(result.road).toBeNull();
199
+ expect(result.address).toBeNull();
200
+ });
201
+
202
+ test("coordinates within ~1 m share a cache entry (one fetch)", async () => {
203
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
204
+ const fetchStub = stubFetch(mapboxGeocodeBody("Market St"));
205
+
206
+ // Same 5-decimal grid cell (~1 m) -> one cache key -> one upstream call.
207
+ await reverseGeocode({ lat: 37.774901, lng: -122.419401 });
208
+ await reverseGeocode({ lat: 37.774902, lng: -122.419402 });
209
+
210
+ expect(fetchStub.calls()).toBe(1);
211
+ });
212
+ });
213
+
214
+ /** A minimal Mapbox Search Box /suggest response. */
215
+ function mapboxSuggestBody(name: string) {
216
+ return {
217
+ suggestions: [
218
+ { mapbox_id: "abc123", name, place_formatted: `${name}, San Francisco` },
219
+ // A suggestion without a mapbox_id must be dropped (un-retrievable).
220
+ { name: "no id place", place_formatted: "somewhere" },
221
+ ],
222
+ };
223
+ }
224
+
225
+ /** A minimal Mapbox Search Box /retrieve FeatureCollection. */
226
+ function mapboxRetrieveBody() {
227
+ return {
228
+ features: [
229
+ {
230
+ geometry: { coordinates: [-122.4194, 37.7749] },
231
+ properties: {
232
+ mapbox_id: "abc123",
233
+ name: "Blue Bottle Coffee",
234
+ full_address: "66 Mint St, San Francisco, California 94103",
235
+ },
236
+ },
237
+ ],
238
+ };
239
+ }
240
+
241
+ describe("maps.service placeAutocomplete", () => {
242
+ test("returns normalized suggestions, dropping ones with no id", async () => {
243
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
244
+ stubFetch(mapboxSuggestBody("Blue Bottle Coffee"));
245
+
246
+ const result = await placeAutocomplete("blue bottle", undefined, "sess-1");
247
+
248
+ expect(result.suggestions).toHaveLength(1);
249
+ expect(result.suggestions[0]).toEqual({
250
+ placeId: "abc123",
251
+ mainText: "Blue Bottle Coffee",
252
+ secondaryText: "Blue Bottle Coffee, San Francisco",
253
+ });
254
+ });
255
+
256
+ test("an empty query short-circuits with no upstream call", async () => {
257
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
258
+ const fetchStub = stubFetch(mapboxSuggestBody("x"));
259
+
260
+ const result = await placeAutocomplete(" ", undefined, "sess-1");
261
+
262
+ expect(result.suggestions).toEqual([]);
263
+ expect(fetchStub.calls()).toBe(0);
264
+ });
265
+
266
+ test("identical (query, session) coalesces onto one upstream call", async () => {
267
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
268
+ const fetchStub = stubFetch(mapboxSuggestBody("Blue Bottle Coffee"));
269
+
270
+ await placeAutocomplete("blue bottle", undefined, "sess-1");
271
+ await placeAutocomplete("Blue Bottle", undefined, "sess-1"); // case-insensitive key
272
+
273
+ expect(fetchStub.calls()).toBe(1);
274
+ });
275
+ });
276
+
277
+ describe("maps.service placeDetails", () => {
278
+ test("resolves a suggestion to coordinates + address", async () => {
279
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
280
+ stubFetch(mapboxRetrieveBody());
281
+
282
+ const place = await placeDetails("abc123", "sess-1");
283
+
284
+ expect(place).toEqual({
285
+ placeId: "abc123",
286
+ name: "Blue Bottle Coffee",
287
+ address: "66 Mint St, San Francisco, California 94103",
288
+ lat: 37.7749,
289
+ lng: -122.4194,
290
+ });
291
+ });
292
+
293
+ test("is not cached: a second identical call re-hits upstream", async () => {
294
+ process.env.MAPBOX_ACCESS_TOKEN = "pk.test";
295
+ const fetchStub = stubFetch(mapboxRetrieveBody());
296
+
297
+ await placeDetails("abc123", "sess-1");
298
+ await placeDetails("abc123", "sess-1");
299
+
300
+ expect(fetchStub.calls()).toBe(2);
301
+ });
302
+ });
cloud-v2/packages/runtime/src/services/maps/maps.service.ts ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Runtime maps service: geocoding + directions, provider-agnostic.
3
+ *
4
+ * The API layer owns HTTP/validation; this service owns provider CHOICE and the
5
+ * thin domain calls. It only ever touches the `MapsProvider` interface, so it is
6
+ * unaware of whether Mapbox or Google is behind it — that is the whole point of
7
+ * the abstraction.
8
+ *
9
+ * Provider is chosen by `MAPS_PROVIDER` (default "mapbox"), mirroring
10
+ * `STORAGE_PROVIDER` / `STREAM_PROVIDER`. The provider is built once per process
11
+ * and cached; `resetMapsProvider()` clears it for tests / config switches.
12
+ *
13
+ * Mapbox is the only provider today. The selection switch is intentionally kept
14
+ * so adding another vendor (Google, etc.) is a one-file change: implement the
15
+ * `MapsProvider` interface in a new `<vendor>.provider.ts`, add a `case` here,
16
+ * and set `MAPS_PROVIDER=<vendor>`. Nothing else in the service, API, protocol,
17
+ * or client changes.
18
+ *
19
+ * Caching — the real protection against accidental client render loops (the v1
20
+ * cloud was burned by an un-cached geocoding endpoint; this restores that). Both
21
+ * caches store the in-flight PROMISE, so concurrent identical requests share one
22
+ * upstream call (in-flight dedup), not just sequential ones. We cache the
23
+ * NEUTRAL result (Route[] / {road}) above the provider, so the cache is
24
+ * provider-agnostic. Failures are never cached, so one upstream blip can't pin an
25
+ * error. Ported from the retired V1 navigation service.
26
+ *
27
+ * See docs/issues/002-cloud-runtime/maps/spec.md.
28
+ */
29
+ import type {
30
+ DirectionsRequest,
31
+ DirectionsResult,
32
+ LatLng,
33
+ PlaceAutocompleteResult,
34
+ PlaceDetailsResult,
35
+ PlaceSuggestion,
36
+ ReverseGeocodeResult,
37
+ Route,
38
+ } from "@mentra/cloud-protocol/maps";
39
+ import { createMapboxProvider } from "./providers/mapbox.provider";
40
+ import type { MapsProvider } from "./providers/provider";
41
+
42
+ let provider: MapsProvider | null = null;
43
+
44
+ /** The configured maps provider (built once per process). */
45
+ export function getMapsProvider(): MapsProvider {
46
+ if (provider) return provider;
47
+ const kind = process.env.MAPS_PROVIDER ?? "mapbox";
48
+ switch (kind) {
49
+ case "mapbox":
50
+ provider = createMapboxProvider();
51
+ break;
52
+ default:
53
+ // Add a `case "<vendor>"` above (and a `<vendor>.provider.ts`) to support
54
+ // another maps provider.
55
+ throw new Error(`unknown MAPS_PROVIDER: ${kind}`);
56
+ }
57
+ return provider;
58
+ }
59
+
60
+ /** Test/boot hook: reset the cached provider (for example to switch config). */
61
+ export function resetMapsProvider(): void {
62
+ provider = null;
63
+ }
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // Promise cache (TTL + in-flight dedup, FIFO-bounded)
67
+ // ---------------------------------------------------------------------------
68
+
69
+ // Routes embed traffic-aware durations, so the cache only needs to outlive a
70
+ // render-loop burst, not a reroute cycle.
71
+ const ROUTE_CACHE_TTL_MS = 30_000;
72
+ const ROUTE_CACHE_MAX_ENTRIES = 500;
73
+
74
+ // Road names are effectively static; the mobile road-name resolver re-probes the
75
+ // same step midpoints on every route recompute, so long TTLs pay off.
76
+ const GEOCODE_CACHE_TTL_MS = 24 * 60 * 60_000;
77
+ const GEOCODE_CACHE_MAX_ENTRIES = 5_000;
78
+
79
+ // Autocomplete is type-ahead: the same prefix recurs constantly as the user
80
+ // backspaces/retypes, but results go stale fast and are session-scoped. A short
81
+ // TTL coalesces the burst (and in-flight-dedups concurrent keystrokes) without
82
+ // serving yesterday's suggestions. `placeDetails` is a one-shot pick — not
83
+ // cached (a retrieve closes the billing session; replaying it buys nothing).
84
+ const AUTOCOMPLETE_CACHE_TTL_MS = 60_000;
85
+ const AUTOCOMPLETE_CACHE_MAX_ENTRIES = 1_000;
86
+
87
+ interface CacheEntry<T> {
88
+ // When a SETTLED entry expires. While the upstream call is still in flight
89
+ // this is `Infinity`, so a concurrent caller always reuses the pending promise
90
+ // (in-flight dedup) instead of firing a second billed request — even if the
91
+ // nominal TTL has elapsed. The real TTL clock starts only when the value
92
+ // resolves (see `cachedUpstream`).
93
+ expiresAt: number;
94
+ promise: Promise<T>;
95
+ }
96
+
97
+ const routeCache = new Map<string, CacheEntry<Route[]>>();
98
+ const geocodeCache = new Map<string, CacheEntry<ReverseGeocodeResult>>();
99
+ const autocompleteCache = new Map<string, CacheEntry<PlaceSuggestion[]>>();
100
+
101
+ /** Test hook: drop all cached entries. */
102
+ export function clearMapsCaches(): void {
103
+ routeCache.clear();
104
+ geocodeCache.clear();
105
+ autocompleteCache.clear();
106
+ }
107
+
108
+ /**
109
+ * Return the cached promise for `key`, or create one via `fn`. The promise is
110
+ * stored BEFORE it settles, so concurrent identical calls coalesce onto one
111
+ * upstream request (in-flight dedup) — and they keep coalescing for the whole
112
+ * lifetime of that request, not just until its nominal TTL elapses (the entry's
113
+ * TTL clock starts on RESOLUTION). A promise that REJECTS is evicted on settle,
114
+ * so a failure is never served from cache (and the rejection still propagates to
115
+ * every waiter, matching `fn`'s own throw-on-failure contract).
116
+ */
117
+ function cachedUpstream<T>(
118
+ cache: Map<string, CacheEntry<T>>,
119
+ key: string,
120
+ ttlMs: number,
121
+ maxEntries: number,
122
+ fn: () => Promise<T>,
123
+ ): Promise<T> {
124
+ const existing = cache.get(key);
125
+ if (existing && existing.expiresAt > Date.now()) {
126
+ return existing.promise;
127
+ }
128
+
129
+ // Insert with `expiresAt: Infinity` so that while this call is in flight,
130
+ // concurrent identical calls reuse it regardless of TTL (an upstream that
131
+ // stalls past the TTL must not spawn a second billed request). On SUCCESS we
132
+ // stamp the real expiry, measured from resolution. On FAILURE we evict so one
133
+ // upstream blip can't pin an error. Both branches guard on object identity so
134
+ // a concurrent FIFO eviction / refresh can't clobber a newer entry.
135
+ const entry: CacheEntry<T> = {
136
+ expiresAt: Infinity,
137
+ promise: undefined as unknown as Promise<T>,
138
+ };
139
+ entry.promise = fn().then(
140
+ (value) => {
141
+ if (cache.get(key) === entry) {
142
+ entry.expiresAt = Date.now() + ttlMs;
143
+ }
144
+ return value;
145
+ },
146
+ (err: unknown) => {
147
+ if (cache.get(key) === entry) {
148
+ cache.delete(key);
149
+ }
150
+ throw err;
151
+ },
152
+ );
153
+
154
+ cache.set(key, entry);
155
+
156
+ // FIFO bound (Map preserves insertion order). At these caps and TTLs a true
157
+ // LRU buys nothing.
158
+ while (cache.size > maxEntries) {
159
+ const oldest = cache.keys().next().value;
160
+ if (oldest === undefined) break;
161
+ cache.delete(oldest);
162
+ }
163
+
164
+ return entry.promise;
165
+ }
166
+
167
+ // ---------------------------------------------------------------------------
168
+ // Public API
169
+ // ---------------------------------------------------------------------------
170
+
171
+ /** Compute routes for a directions request. Primary route first, alternates after. */
172
+ export async function directions(req: DirectionsRequest): Promise<DirectionsResult> {
173
+ // Key on the normalized request. Render loops / retries resend identical
174
+ // inputs; a stable field order keeps those hits (semantically-equal-but-
175
+ // reordered inputs simply miss, which is safe).
176
+ const key = JSON.stringify({
177
+ origin: req.origin,
178
+ stops: req.stops,
179
+ mode: req.mode ?? null,
180
+ avoid: req.avoid ?? null,
181
+ alternatives: req.alternatives ?? null,
182
+ });
183
+ const routes = await cachedUpstream(
184
+ routeCache,
185
+ key,
186
+ ROUTE_CACHE_TTL_MS,
187
+ ROUTE_CACHE_MAX_ENTRIES,
188
+ () => getMapsProvider().directions(req),
189
+ );
190
+ return { routes };
191
+ }
192
+
193
+ /**
194
+ * Resolve a coordinate to a short road name + full formatted address (each null
195
+ * when none found nearby). Both are derived from one upstream lookup and cached
196
+ * together under the same key.
197
+ */
198
+ export async function reverseGeocode(coord: LatLng): Promise<ReverseGeocodeResult> {
199
+ // ~1 m grid: step midpoints recur exactly on recompute, and probes within a
200
+ // meter of each other are the same road by any standard.
201
+ const key = `${coord.lat.toFixed(5)},${coord.lng.toFixed(5)}`;
202
+ return cachedUpstream(
203
+ geocodeCache,
204
+ key,
205
+ GEOCODE_CACHE_TTL_MS,
206
+ GEOCODE_CACHE_MAX_ENTRIES,
207
+ () => getMapsProvider().reverseGeocode(coord),
208
+ );
209
+ }
210
+
211
+ /**
212
+ * Type-ahead place search. Cached briefly per (query, near, session) so a burst
213
+ * of keystrokes / backspaces over the same prefix coalesces onto one upstream
214
+ * call. An empty query short-circuits to no suggestions without a cache entry or
215
+ * an upstream call.
216
+ */
217
+ export async function placeAutocomplete(
218
+ query: string,
219
+ near: LatLng | undefined,
220
+ sessionToken: string,
221
+ ): Promise<PlaceAutocompleteResult> {
222
+ if (!query.trim()) return { suggestions: [] };
223
+ // Session token is part of the key: results are session-scoped, and two users
224
+ // typing the same prefix must not share a suggestion list / billing session.
225
+ const key = JSON.stringify({
226
+ q: query.trim().toLowerCase(),
227
+ near: near ? { lat: near.lat.toFixed(3), lng: near.lng.toFixed(3) } : null,
228
+ session: sessionToken,
229
+ });
230
+ const suggestions = await cachedUpstream(
231
+ autocompleteCache,
232
+ key,
233
+ AUTOCOMPLETE_CACHE_TTL_MS,
234
+ AUTOCOMPLETE_CACHE_MAX_ENTRIES,
235
+ () => getMapsProvider().placeAutocomplete(query, near, sessionToken),
236
+ );
237
+ return { suggestions };
238
+ }
239
+
240
+ /**
241
+ * Resolve a suggestion (`placeId` + the autocomplete's `sessionToken`) to a full
242
+ * place with coordinates. Not cached: a pick is one-shot and the retrieve closes
243
+ * the provider's billing session.
244
+ */
245
+ export async function placeDetails(
246
+ placeId: string,
247
+ sessionToken: string,
248
+ ): Promise<PlaceDetailsResult> {
249
+ return getMapsProvider().placeDetails(placeId, sessionToken);
250
+ }
cloud-v2/packages/runtime/src/services/maps/providers/mapbox.provider.ts ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Mapbox maps provider.
3
+ *
4
+ * The ONLY Mapbox-aware code in the runtime. Everything vendor-specific lives
5
+ * here: the `api.mapbox.com` endpoints, the access token, polyline6 decoding,
6
+ * and the Mapbox maneuver/profile/exclude vocabulary -> our neutral vocabulary.
7
+ * It returns the protocol-neutral `Route[]` / `{road}` so callers never see a
8
+ * Mapbox shape.
9
+ *
10
+ * Mirrors the request shapes the mobile host already used against Mapbox
11
+ * (mobile/src/services/NavigationService.ts): Directions v5 with
12
+ * geometries=polyline6, overview=full, steps=true, banner_instructions=true;
13
+ * Geocoding v6 reverse with types=address,street.
14
+ */
15
+ import { createLogger } from "@mentra/cloud-shared";
16
+ import type {
17
+ DirectionsRequest,
18
+ LatLng,
19
+ ManeuverKind,
20
+ PlaceDetailsResult,
21
+ PlaceSuggestion,
22
+ Route,
23
+ RouteStep,
24
+ RouteAvoidances,
25
+ TravelMode,
26
+ } from "@mentra/cloud-protocol/maps";
27
+ import type { MapsProvider } from "./provider";
28
+
29
+ const logger = createLogger("maps").child({ service: "mapbox.maps.provider" });
30
+
31
+ const DIRECTIONS_BASE = "https://api.mapbox.com/directions/v5/mapbox";
32
+ const GEOCODE_REVERSE_URL = "https://api.mapbox.com/search/geocode/v6/reverse";
33
+ const SEARCHBOX_SUGGEST_URL = "https://api.mapbox.com/search/searchbox/v1/suggest";
34
+ const SEARCHBOX_RETRIEVE_URL = "https://api.mapbox.com/search/searchbox/v1/retrieve";
35
+
36
+ /** Read + validate the token at call time (not module load) so tests/boot can set it late. */
37
+ function getToken(): string {
38
+ const token = process.env.MAPBOX_ACCESS_TOKEN;
39
+ if (!token) {
40
+ throw new Error(
41
+ "MAPBOX_ACCESS_TOKEN is not set (required for the Mapbox maps provider)",
42
+ );
43
+ }
44
+ return token;
45
+ }
46
+
47
+ /** Our TravelMode -> Mapbox Directions profile. */
48
+ function mapboxProfile(mode: TravelMode | undefined): string {
49
+ switch (mode) {
50
+ case "walking":
51
+ return "walking";
52
+ case "cycling":
53
+ return "cycling";
54
+ case "two_wheeler":
55
+ // Mapbox has no two-wheeler profile; driving is the closest match.
56
+ return "driving";
57
+ case "driving":
58
+ default:
59
+ return "driving-traffic";
60
+ }
61
+ }
62
+
63
+ /** Our avoidance flags -> Mapbox `exclude` param value, or null when none apply. */
64
+ function mapboxExclude(avoid: RouteAvoidances | undefined): string | null {
65
+ if (!avoid) return null;
66
+ const ex: string[] = [];
67
+ if (avoid.tolls) ex.push("toll");
68
+ if (avoid.ferries) ex.push("ferry");
69
+ if (avoid.highways) ex.push("motorway");
70
+ return ex.length > 0 ? ex.join(",") : null;
71
+ }
72
+
73
+ /** Mapbox maneuver `type` + `modifier` -> our neutral ManeuverKind. */
74
+ function mapboxManeuverToKind(
75
+ type: string | undefined,
76
+ modifier: string | undefined,
77
+ ): ManeuverKind | undefined {
78
+ switch (type) {
79
+ case "depart":
80
+ return "DEPART";
81
+ case "arrive":
82
+ return "ARRIVE";
83
+ case "new name":
84
+ return "NAME_CHANGE";
85
+ case "continue":
86
+ return "CONTINUE";
87
+ default:
88
+ break;
89
+ }
90
+ switch (modifier) {
91
+ case "uturn":
92
+ return "U_TURN";
93
+ case "sharp left":
94
+ return "SHARP_LEFT";
95
+ case "left":
96
+ return "TURN_LEFT";
97
+ case "slight left":
98
+ return "SLIGHT_LEFT";
99
+ case "straight":
100
+ return "STRAIGHT";
101
+ case "slight right":
102
+ return "SLIGHT_RIGHT";
103
+ case "right":
104
+ return "TURN_RIGHT";
105
+ case "sharp right":
106
+ return "SHARP_RIGHT";
107
+ default:
108
+ return undefined;
109
+ }
110
+ }
111
+
112
+ /** Decode a Mapbox precision-6 polyline into [lng,lat]-ordered LatLng points. */
113
+ function decodePolyline6(encoded: string): LatLng[] {
114
+ const points: LatLng[] = [];
115
+ let index = 0;
116
+ let lat = 0;
117
+ let lng = 0;
118
+ const factor = 1e6;
119
+
120
+ while (index < encoded.length) {
121
+ let result = 1;
122
+ let shift = 0;
123
+ let b: number;
124
+ do {
125
+ b = encoded.charCodeAt(index++) - 63 - 1;
126
+ result += b << shift;
127
+ shift += 5;
128
+ } while (b >= 0x1f);
129
+ lat += result & 1 ? ~(result >> 1) : result >> 1;
130
+
131
+ result = 1;
132
+ shift = 0;
133
+ do {
134
+ b = encoded.charCodeAt(index++) - 63 - 1;
135
+ result += b << shift;
136
+ shift += 5;
137
+ } while (b >= 0x1f);
138
+ lng += result & 1 ? ~(result >> 1) : result >> 1;
139
+
140
+ points.push({ lat: lat / factor, lng: lng / factor });
141
+ }
142
+ return points;
143
+ }
144
+
145
+ /** Pull a road name out of a Mapbox Directions step, preferring the named ref. */
146
+ function stepRoad(step: MapboxStep): string | null {
147
+ if (typeof step.name === "string" && step.name.trim().length > 0) {
148
+ return step.name;
149
+ }
150
+ if (typeof step.ref === "string" && step.ref.trim().length > 0) {
151
+ return step.ref;
152
+ }
153
+ return null;
154
+ }
155
+
156
+ // --- Minimal shapes of the Mapbox responses we read -------------------------
157
+ // Deliberately narrow: only the fields this provider consumes, so a Mapbox
158
+ // response shape change surfaces here rather than leaking outward.
159
+
160
+ interface MapboxManeuver {
161
+ type?: string;
162
+ modifier?: string;
163
+ instruction?: string;
164
+ }
165
+ interface MapboxStep {
166
+ distance?: number;
167
+ name?: string;
168
+ ref?: string;
169
+ maneuver?: MapboxManeuver;
170
+ geometry?: string;
171
+ }
172
+ interface MapboxLeg {
173
+ steps?: MapboxStep[];
174
+ }
175
+ interface MapboxRoute {
176
+ geometry?: string;
177
+ distance?: number;
178
+ duration?: number;
179
+ legs?: MapboxLeg[];
180
+ }
181
+ interface MapboxDirectionsResponse {
182
+ routes?: MapboxRoute[];
183
+ }
184
+
185
+ /** Normalize one Mapbox route into our neutral Route. */
186
+ function toNeutralRoute(mb: MapboxRoute): Route {
187
+ const points = mb.geometry ? decodePolyline6(mb.geometry) : [];
188
+ const tail = points[points.length - 1];
189
+
190
+ const flatSteps: MapboxStep[] = (mb.legs ?? []).flatMap((leg) => leg.steps ?? []);
191
+ const steps: RouteStep[] = flatSteps.map((s, i) => {
192
+ const start = s.geometry ? decodePolyline6(s.geometry)[0] : undefined;
193
+ const next = flatSteps[i + 1];
194
+ const nextStart = next?.geometry ? decodePolyline6(next.geometry)[0] : undefined;
195
+ const lat = start?.lat ?? tail?.lat ?? 0;
196
+ const lng = start?.lng ?? tail?.lng ?? 0;
197
+ return {
198
+ lat,
199
+ lng,
200
+ endLat: nextStart?.lat ?? tail?.lat ?? lat,
201
+ endLng: nextStart?.lng ?? tail?.lng ?? lng,
202
+ distanceMeters: s.distance ?? 0,
203
+ maneuver: mapboxManeuverToKind(s.maneuver?.type, s.maneuver?.modifier),
204
+ instruction: s.maneuver?.instruction,
205
+ road: stepRoad(s),
206
+ };
207
+ });
208
+
209
+ return {
210
+ points,
211
+ totalDistanceMeters: mb.distance ?? 0,
212
+ totalDurationSeconds: mb.duration ?? 0,
213
+ steps: steps.length > 0 ? steps : undefined,
214
+ };
215
+ }
216
+
217
+ export function createMapboxProvider(): MapsProvider {
218
+ return {
219
+ name: "mapbox",
220
+
221
+ async directions(req: DirectionsRequest): Promise<Route[]> {
222
+ const token = getToken();
223
+ const profile = mapboxProfile(req.mode);
224
+ // Mapbox wants `lng,lat;lng,lat;...` with origin first, then each stop.
225
+ const coords = [req.origin, ...req.stops]
226
+ .map((c) => `${c.lng},${c.lat}`)
227
+ .join(";");
228
+
229
+ const params = new URLSearchParams({
230
+ access_token: token,
231
+ geometries: "polyline6",
232
+ overview: "full",
233
+ steps: "true",
234
+ banner_instructions: "true",
235
+ alternatives: String((req.alternatives ?? 1) > 1),
236
+ });
237
+ const exclude = mapboxExclude(req.avoid);
238
+ if (exclude) params.set("exclude", exclude);
239
+
240
+ // Walking-only: bias Mapbox's routing toward walkways/footpaths so the
241
+ // route follows the SIDEWALK rather than the road centerline — but ONLY
242
+ // where OSM has the sidewalk mapped as a separate footway. Where it isn't
243
+ // mapped, Mapbox has nothing to bias toward and returns the road as
244
+ // before (no fake offset). `walkway_bias` is a walking-profile-only param;
245
+ // Mapbox rejects it on driving/cycling, so it's gated on the profile.
246
+ if (profile === "walking") {
247
+ params.set("walkway_bias", "1");
248
+ }
249
+
250
+ const url = `${DIRECTIONS_BASE}/${profile}/${coords}?${params.toString()}`;
251
+ const res = await fetch(url);
252
+ if (!res.ok) {
253
+ const body = await res.text().catch(() => "");
254
+ logger.error({ status: res.status, body }, "mapbox directions request failed");
255
+ throw new Error(`mapbox directions failed: ${res.status}`);
256
+ }
257
+ const data = (await res.json()) as MapboxDirectionsResponse;
258
+ return (data.routes ?? []).map(toNeutralRoute);
259
+ },
260
+
261
+ async reverseGeocode(
262
+ coord: LatLng,
263
+ ): Promise<{ road: string | null; address: string | null }> {
264
+ const token = getToken();
265
+ const params = new URLSearchParams({
266
+ access_token: token,
267
+ longitude: String(coord.lng),
268
+ latitude: String(coord.lat),
269
+ // `address` first so the top feature carries the house number (and thus
270
+ // `full_address`); `street`/`place` keep us returning SOMETHING for a
271
+ // coord with no exact street address.
272
+ types: "address,street,place",
273
+ limit: "1",
274
+ });
275
+ const url = `${GEOCODE_REVERSE_URL}?${params.toString()}`;
276
+ const res = await fetch(url);
277
+ if (!res.ok) {
278
+ const body = await res.text().catch(() => "");
279
+ logger.error({ status: res.status, body }, "mapbox reverse geocode failed");
280
+ throw new Error(`mapbox reverse geocode failed: ${res.status}`);
281
+ }
282
+ const data = (await res.json()) as {
283
+ features?: Array<{
284
+ properties?: {
285
+ name?: string;
286
+ full_address?: string;
287
+ place_formatted?: string;
288
+ context?: { street?: { name?: string } };
289
+ };
290
+ }>;
291
+ };
292
+ const feature = data.features?.[0]?.properties;
293
+ // Short road name for the pivot fallback…
294
+ const road = feature?.context?.street?.name ?? feature?.name ?? null;
295
+ // …and the full formatted address for dropped-pin / POI labels. Prefer
296
+ // `full_address` (carries the house number), fall back to `name` then
297
+ // `place_formatted`.
298
+ const address =
299
+ feature?.full_address ?? feature?.name ?? feature?.place_formatted ?? null;
300
+ return { road: road ?? null, address: address ?? null };
301
+ },
302
+
303
+ async placeAutocomplete(
304
+ query: string,
305
+ near: LatLng | undefined,
306
+ sessionToken: string,
307
+ ): Promise<PlaceSuggestion[]> {
308
+ // An empty query is a no-op, not an upstream call — Search Box would 422.
309
+ if (!query.trim()) return [];
310
+ const token = getToken();
311
+ const params = new URLSearchParams({
312
+ q: query,
313
+ access_token: token,
314
+ session_token: sessionToken,
315
+ // POIs + addresses + places — the things a user navigates to.
316
+ types: "poi,address,place,street",
317
+ limit: "10",
318
+ });
319
+ // Bias toward the user's location when we have it (Mapbox wants lng,lat).
320
+ if (near) params.set("proximity", `${near.lng},${near.lat}`);
321
+
322
+ const url = `${SEARCHBOX_SUGGEST_URL}?${params.toString()}`;
323
+ const res = await fetch(url);
324
+ if (!res.ok) {
325
+ const body = await res.text().catch(() => "");
326
+ logger.error({ status: res.status, body }, "mapbox searchbox suggest failed");
327
+ throw new Error(`mapbox place autocomplete failed: ${res.status}`);
328
+ }
329
+ const data = (await res.json()) as {
330
+ suggestions?: Array<{
331
+ mapbox_id?: string;
332
+ name?: string;
333
+ place_formatted?: string;
334
+ full_address?: string;
335
+ }>;
336
+ };
337
+ return (data.suggestions ?? [])
338
+ // Only suggestions we can later retrieve (need a mapbox_id) are useful.
339
+ .filter((s): s is { mapbox_id: string } & typeof s => !!s.mapbox_id)
340
+ .map((s) => ({
341
+ placeId: s.mapbox_id,
342
+ mainText: s.name ?? "",
343
+ secondaryText: s.place_formatted ?? s.full_address ?? "",
344
+ }));
345
+ },
346
+
347
+ async placeDetails(
348
+ placeId: string,
349
+ sessionToken: string,
350
+ ): Promise<PlaceDetailsResult> {
351
+ const token = getToken();
352
+ const params = new URLSearchParams({
353
+ access_token: token,
354
+ session_token: sessionToken,
355
+ });
356
+ const url = `${SEARCHBOX_RETRIEVE_URL}/${encodeURIComponent(placeId)}?${params.toString()}`;
357
+ const res = await fetch(url);
358
+ if (!res.ok) {
359
+ const body = await res.text().catch(() => "");
360
+ logger.error({ status: res.status, body }, "mapbox searchbox retrieve failed");
361
+ throw new Error(`mapbox place details failed: ${res.status}`);
362
+ }
363
+ // Retrieve returns a GeoJSON FeatureCollection; the picked place is the
364
+ // first feature. Coordinates are [lng, lat].
365
+ const data = (await res.json()) as {
366
+ features?: Array<{
367
+ geometry?: { coordinates?: [number, number] };
368
+ properties?: {
369
+ mapbox_id?: string;
370
+ name?: string;
371
+ full_address?: string;
372
+ place_formatted?: string;
373
+ };
374
+ }>;
375
+ };
376
+ const feature = data.features?.[0];
377
+ const coords = feature?.geometry?.coordinates;
378
+ if (!coords || coords.length < 2) {
379
+ throw new Error("mapbox place details: no coordinates in response");
380
+ }
381
+ const props = feature?.properties;
382
+ return {
383
+ placeId: props?.mapbox_id ?? placeId,
384
+ name: props?.name ?? "",
385
+ address: props?.full_address ?? props?.place_formatted ?? "",
386
+ lat: coords[1],
387
+ lng: coords[0],
388
+ };
389
+ },
390
+ };
391
+ }
cloud-v2/packages/runtime/src/services/maps/providers/provider.ts ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview The maps provider contract.
3
+ *
4
+ * This interface is the line where a vendor's dialect becomes our one neutral
5
+ * vocabulary. It speaks ONLY in the protocol-neutral types from
6
+ * `protocol/maps` (LatLng, Route, TravelMode, ...) — never a vendor's JSON
7
+ * shape. Each implementation owns its own HTTP endpoints, auth token, response
8
+ * decoding, and maneuver/profile mapping, and returns these neutral types.
9
+ *
10
+ * Mapbox (mapbox.provider) is the only implementation today. Adding a vendor
11
+ * (Google, etc.) is therefore: write one `create<Vendor>Provider()` that
12
+ * satisfies this interface, then teach `maps.service` to select it by env var.
13
+ * Nothing else in the service, API, protocol, or client changes.
14
+ *
15
+ * Following the codebase convention (StorageProvider, StreamProvider), providers
16
+ * are built by a factory function and expose a `readonly name` for diagnostics.
17
+ */
18
+ import type {
19
+ DirectionsRequest,
20
+ LatLng,
21
+ PlaceDetailsResult,
22
+ PlaceSuggestion,
23
+ Route,
24
+ } from "@mentra/cloud-protocol/maps";
25
+
26
+ export interface MapsProvider {
27
+ /** Diagnostic label, e.g. "mapbox". */
28
+ readonly name: string;
29
+
30
+ /**
31
+ * Compute one or more routes from `origin` through `stops`. Returns the
32
+ * primary route first, alternates after. Throws on a provider/transport
33
+ * failure; an empty `[]` means the provider found no route.
34
+ */
35
+ directions(req: DirectionsRequest): Promise<Route[]>;
36
+
37
+ /**
38
+ * Resolve a coordinate to a short road name (`road`) and a full formatted
39
+ * street address (`address`). Either field is null when nothing of that kind
40
+ * was found near the coordinate (a successful empty answer); throws only on an
41
+ * actual provider/transport failure.
42
+ */
43
+ reverseGeocode(coord: LatLng): Promise<{ road: string | null; address: string | null }>;
44
+
45
+ /**
46
+ * Type-ahead place search. Returns lightweight suggestions for `query`,
47
+ * optionally biased toward `near`. `sessionToken` groups this with the
48
+ * following `placeDetails` call into one billed search session. Resolves `[]`
49
+ * for an empty/whitespace query; throws only on a provider/transport failure.
50
+ */
51
+ placeAutocomplete(
52
+ query: string,
53
+ near: LatLng | undefined,
54
+ sessionToken: string,
55
+ ): Promise<PlaceSuggestion[]>;
56
+
57
+ /**
58
+ * Resolve a suggestion's `placeId` (from `placeAutocomplete`) to a full place
59
+ * with coordinates. `sessionToken` must match the autocomplete that produced
60
+ * the id so the provider closes the billing session. Throws on a
61
+ * provider/transport failure or an unresolvable id.
62
+ */
63
+ placeDetails(placeId: string, sessionToken: string): Promise<PlaceDetailsResult>;
64
+ }
cloud-v2/packages/runtime/src/services/meetings/acs-teams.service.test.ts ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {afterEach, beforeEach, describe, expect, test} from "bun:test"
2
+
3
+ import {
4
+ ACS_GUEST_STATE_MAX_ENTRIES,
5
+ getAcsGuestStateSizeForTests,
6
+ mintAcsGuestToken,
7
+ resetAcsTeamsAuthCache,
8
+ setAcsIdentityClientForTests,
9
+ bindTeamsSubject,
10
+ exchangeAcsTeamsUserToken,
11
+ type AcsIdentityClient,
12
+ } from "./acs-teams.service"
13
+
14
+ describe("ACS Teams opaque subject tokens", () => {
15
+ const names = ["ENTRA_TENANT_ID", "ENTRA_CLIENT_ID", "ACS_CONNECTION_STRING"] as const
16
+ let saved: (string | undefined)[]
17
+ const expected = {tenantId: "tenant-1", objectId: "employee-1"}
18
+ beforeEach(() => {
19
+ saved = names.map((name) => process.env[name])
20
+ process.env.ENTRA_TENANT_ID = expected.tenantId
21
+ process.env.ENTRA_CLIENT_ID = "mobile-client"
22
+ process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test"
23
+ })
24
+ afterEach(() => {
25
+ names.forEach((name, i) => {
26
+ if (saved[i] === undefined) delete process.env[name]
27
+ else process.env[name] = saved[i]
28
+ })
29
+ resetAcsTeamsAuthCache()
30
+ })
31
+
32
+ test("lets Microsoft validate opaque tokens against the trusted user and application", async () => {
33
+ const opaque = "opaque-microsoft-token-not-a-jwt"
34
+ setAcsIdentityClientForTests({
35
+ async createUserAndToken() {
36
+ throw new Error("must not mint a guest")
37
+ },
38
+ async getTokenForTeamsUser(input) {
39
+ expect(input).toEqual({teamsUserAadToken: opaque, userObjectId: expected.objectId, clientId: "mobile-client"})
40
+ return {token: "teams-credential", expiresOn: new Date("2030-01-01")}
41
+ },
42
+ })
43
+ expect(await exchangeAcsTeamsUserToken(bindTeamsSubject(opaque, expected))).toMatchObject({
44
+ identityMode: "teams-user",
45
+ })
46
+ })
47
+
48
+ test("rejects a foreign Runtime tenant before contacting Microsoft", () => {
49
+ expect(() => bindTeamsSubject("opaque", {...expected, tenantId: "other"})).toThrow("Runtime identity")
50
+ expect(() => bindTeamsSubject("opaque", {...expected, objectId: ""})).toThrow("Runtime identity")
51
+ })
52
+
53
+ test.each([400, 401, 403, 429, 500])(
54
+ "preserves Microsoft rejection %s without leaking its request",
55
+ async (statusCode) => {
56
+ setAcsIdentityClientForTests({
57
+ async createUserAndToken() {
58
+ throw new Error("must not mint a guest")
59
+ },
60
+ async getTokenForTeamsUser() {
61
+ throw Object.assign(new Error("secret-token"), {statusCode, request: {body: "secret-token"}})
62
+ },
63
+ })
64
+ try {
65
+ await exchangeAcsTeamsUserToken(bindTeamsSubject("opaque", expected))
66
+ throw new Error("expected failure")
67
+ } catch (error) {
68
+ expect(String(error)).not.toContain("secret-token")
69
+ expect(String(error)).toContain(
70
+ statusCode < 429 ? "could not verify" : statusCode === 429 ? "busy" : "unavailable",
71
+ )
72
+ }
73
+ },
74
+ )
75
+ })
76
+
77
+ describe("ACS guest credentials", () => {
78
+ const previousConnectionString = process.env.ACS_CONNECTION_STRING
79
+
80
+ afterEach(() => {
81
+ resetAcsTeamsAuthCache()
82
+ if (previousConnectionString === undefined) delete process.env.ACS_CONNECTION_STRING
83
+ else process.env.ACS_CONNECTION_STRING = previousConnectionString
84
+ })
85
+
86
+ test("creates one guest identity and reuses its fresh token for the authenticated user", async () => {
87
+ process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test"
88
+ let creates = 0
89
+ const expiresOn = new Date(Date.now() + 60 * 60 * 1000)
90
+ setAcsIdentityClientForTests({
91
+ async createUserAndToken(scopes, options) {
92
+ creates += 1
93
+ expect(scopes).toEqual(["voip"])
94
+ expect(options.tokenExpiresInMinutes).toBe(120)
95
+ return {
96
+ token: "guest-token",
97
+ expiresOn,
98
+ user: {communicationUserId: "guest-user"},
99
+ }
100
+ },
101
+ async getTokenForTeamsUser() {
102
+ throw new Error("not used")
103
+ },
104
+ } satisfies AcsIdentityClient)
105
+
106
+ const first = await mintAcsGuestToken("tenant:user")
107
+ const second = await mintAcsGuestToken("tenant:user")
108
+
109
+ expect(first).toEqual({
110
+ token: "guest-token",
111
+ expiresOn: expiresOn.toISOString(),
112
+ identityMode: "guest",
113
+ acsUserId: "guest-user",
114
+ })
115
+ expect(second).toEqual(first)
116
+ expect(creates).toBe(1)
117
+ })
118
+
119
+ test("shares one ACS request across concurrent guest-token callers", async () => {
120
+ process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test"
121
+ let creates = 0
122
+ let releaseCreate: (() => void) | undefined
123
+ const createMayFinish = new Promise<void>((resolve) => {
124
+ releaseCreate = resolve
125
+ })
126
+ setAcsIdentityClientForTests({
127
+ async createUserAndToken() {
128
+ creates += 1
129
+ await createMayFinish
130
+ return {
131
+ token: "shared-token",
132
+ expiresOn: new Date(Date.now() + 60 * 60 * 1000),
133
+ user: {communicationUserId: "shared-user"},
134
+ }
135
+ },
136
+ async getTokenForTeamsUser() {
137
+ throw new Error("not used")
138
+ },
139
+ } satisfies AcsIdentityClient)
140
+
141
+ const requests = Array.from({length: 20}, () => mintAcsGuestToken("tenant:concurrent-user"))
142
+ for (let attempt = 0; attempt < 10 && creates === 0; attempt += 1) {
143
+ await new Promise((resolve) => setTimeout(resolve, 0))
144
+ }
145
+ expect(creates).toBe(1)
146
+ releaseCreate?.()
147
+
148
+ const credentials = await Promise.all(requests)
149
+ expect(new Set(credentials.map(({token}) => token))).toEqual(new Set(["shared-token"]))
150
+ expect(creates).toBe(1)
151
+ })
152
+
153
+ test("preserves an existing ACS identity across transient refresh failures", async () => {
154
+ process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test"
155
+ let creates = 0
156
+ let refreshes = 0
157
+ setAcsIdentityClientForTests({
158
+ async createUserAndToken() {
159
+ creates += 1
160
+ return {
161
+ token: "expired-token",
162
+ expiresOn: new Date(0),
163
+ user: {communicationUserId: "stable-user"},
164
+ }
165
+ },
166
+ async getToken(user) {
167
+ expect(user.communicationUserId).toBe("stable-user")
168
+ refreshes += 1
169
+ if (refreshes === 1) throw {status: 401, code: "Denied"}
170
+ return {
171
+ token: "refreshed-token",
172
+ expiresOn: new Date(Date.now() + 60 * 60 * 1000),
173
+ }
174
+ },
175
+ async getTokenForTeamsUser() {
176
+ throw new Error("not used")
177
+ },
178
+ } satisfies AcsIdentityClient)
179
+
180
+ await mintAcsGuestToken("tenant:stable-user")
181
+ await expect(mintAcsGuestToken("tenant:stable-user")).rejects.toMatchObject({status: 502})
182
+ const refreshed = await mintAcsGuestToken("tenant:stable-user")
183
+
184
+ expect(refreshed).toMatchObject({
185
+ token: "refreshed-token",
186
+ acsUserId: "stable-user",
187
+ })
188
+ expect(creates).toBe(1)
189
+ expect(refreshes).toBe(2)
190
+ })
191
+
192
+ test("replaces an ACS identity after IdentityNotFound from the provider", async () => {
193
+ process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test"
194
+ let creates = 0
195
+ setAcsIdentityClientForTests({
196
+ async createUserAndToken() {
197
+ creates += 1
198
+ return {
199
+ token: `guest-token-${creates}`,
200
+ expiresOn: creates === 1 ? new Date(0) : new Date(Date.now() + 60 * 60 * 1000),
201
+ user: {communicationUserId: `guest-user-${creates}`},
202
+ }
203
+ },
204
+ async getToken() {
205
+ throw {status: 401, code: "IdentityNotFound"}
206
+ },
207
+ async getTokenForTeamsUser() {
208
+ throw new Error("not used")
209
+ },
210
+ } satisfies AcsIdentityClient)
211
+
212
+ await mintAcsGuestToken("tenant:missing-user")
213
+ await expect(mintAcsGuestToken("tenant:missing-user")).rejects.toMatchObject({status: 502})
214
+ const replacement = await mintAcsGuestToken("tenant:missing-user")
215
+
216
+ expect(replacement.acsUserId).toBe("guest-user-2")
217
+ expect(creates).toBe(2)
218
+ })
219
+
220
+ test("limits repeated guest-token mints for one authenticated user", async () => {
221
+ process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test"
222
+ let tokenNumber = 0
223
+ const expiredCredential = () => ({
224
+ token: `guest-token-${++tokenNumber}`,
225
+ expiresOn: new Date(0),
226
+ })
227
+ setAcsIdentityClientForTests({
228
+ async createUserAndToken() {
229
+ return {
230
+ ...expiredCredential(),
231
+ user: {communicationUserId: "guest-user"},
232
+ }
233
+ },
234
+ async getToken() {
235
+ return expiredCredential()
236
+ },
237
+ async getTokenForTeamsUser() {
238
+ throw new Error("not used")
239
+ },
240
+ } satisfies AcsIdentityClient)
241
+
242
+ for (let attempt = 0; attempt < 12; attempt += 1) {
243
+ await mintAcsGuestToken("tenant:rate-limited-user")
244
+ }
245
+ await expect(mintAcsGuestToken("tenant:rate-limited-user")).rejects.toMatchObject({status: 429})
246
+ })
247
+
248
+ test("bounds guest identity state without evicting live ACS identities", async () => {
249
+ process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test"
250
+ setAcsIdentityClientForTests({
251
+ async createUserAndToken() {
252
+ return {
253
+ token: "guest-token",
254
+ expiresOn: new Date(Date.now() + 60 * 60 * 1000),
255
+ user: {communicationUserId: "guest-user"},
256
+ }
257
+ },
258
+ async getTokenForTeamsUser() {
259
+ throw new Error("not used")
260
+ },
261
+ } satisfies AcsIdentityClient)
262
+
263
+ for (let userNumber = 0; userNumber < ACS_GUEST_STATE_MAX_ENTRIES + 2; userNumber += 1) {
264
+ if (userNumber < ACS_GUEST_STATE_MAX_ENTRIES) {
265
+ await mintAcsGuestToken(`tenant:user-${userNumber}`)
266
+ } else {
267
+ await expect(mintAcsGuestToken(`tenant:user-${userNumber}`)).rejects.toMatchObject({status: 503})
268
+ }
269
+ }
270
+
271
+ expect(getAcsGuestStateSizeForTests()).toBe(ACS_GUEST_STATE_MAX_ENTRIES)
272
+ })
273
+
274
+ test("deletes an expired idle ACS identity before evicting its state", async () => {
275
+ process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test"
276
+ const originalNow = Date.now
277
+ const deletedUsers: string[] = []
278
+ let now = 1_000_000
279
+ Date.now = () => now
280
+ try {
281
+ setAcsIdentityClientForTests({
282
+ async createUserAndToken() {
283
+ return {
284
+ token: "guest-token",
285
+ expiresOn: new Date(now + 60 * 60 * 1000),
286
+ user: {communicationUserId: "guest-user"},
287
+ }
288
+ },
289
+ async deleteUser(user) {
290
+ deletedUsers.push(user.communicationUserId)
291
+ },
292
+ async getTokenForTeamsUser() {
293
+ throw new Error("not used")
294
+ },
295
+ } satisfies AcsIdentityClient)
296
+
297
+ await mintAcsGuestToken("tenant:idle-user")
298
+ now += 4 * 60 * 60 * 1000 + 1
299
+ await mintAcsGuestToken("tenant:new-user")
300
+ await new Promise((resolve) => setTimeout(resolve, 0))
301
+
302
+ expect(deletedUsers).toEqual(["guest-user"])
303
+ expect(getAcsGuestStateSizeForTests()).toBe(1)
304
+ } finally {
305
+ Date.now = originalNow
306
+ }
307
+ })
308
+
309
+ test("evicts idle state when ACS reports the identity is already gone", async () => {
310
+ process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test"
311
+ const originalNow = Date.now
312
+ let now = 1_000_000
313
+ let creates = 0
314
+ Date.now = () => now
315
+ try {
316
+ setAcsIdentityClientForTests({
317
+ async createUserAndToken() {
318
+ creates += 1
319
+ return {
320
+ token: `guest-token-${creates}`,
321
+ expiresOn: new Date(now + 60 * 60 * 1000),
322
+ user: {communicationUserId: `guest-user-${creates}`},
323
+ }
324
+ },
325
+ async deleteUser() {
326
+ throw {status: 404, code: "IdentityNotFound"}
327
+ },
328
+ async getTokenForTeamsUser() {
329
+ throw new Error("not used")
330
+ },
331
+ } satisfies AcsIdentityClient)
332
+
333
+ await mintAcsGuestToken("tenant:gone-user")
334
+ now += 4 * 60 * 60 * 1000 + 1
335
+ await mintAcsGuestToken("tenant:new-user")
336
+
337
+ const replacement = await mintAcsGuestToken("tenant:gone-user")
338
+ expect(replacement.acsUserId).toBe("guest-user-3")
339
+ expect(getAcsGuestStateSizeForTests()).toBe(2)
340
+ } finally {
341
+ Date.now = originalNow
342
+ }
343
+ })
344
+
345
+ test("does not block unrelated issuance or delete a returning user's active identity", async () => {
346
+ process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test"
347
+ const originalNow = Date.now
348
+ let now = 1_000_000
349
+ let creates = 0
350
+ let releaseDeletion: (() => void) | undefined
351
+ const deletionMayFinish = new Promise<void>((resolve) => {
352
+ releaseDeletion = resolve
353
+ })
354
+ Date.now = () => now
355
+ try {
356
+ setAcsIdentityClientForTests({
357
+ async createUserAndToken() {
358
+ creates += 1
359
+ return {
360
+ token: `guest-token-${creates}`,
361
+ expiresOn: new Date(now + 60 * 60 * 1000),
362
+ user: {communicationUserId: `guest-user-${creates}`},
363
+ }
364
+ },
365
+ async deleteUser() {
366
+ await deletionMayFinish
367
+ },
368
+ async getToken() {
369
+ throw new Error("cleanup must finish before a returning user mints")
370
+ },
371
+ async getTokenForTeamsUser() {
372
+ throw new Error("not used")
373
+ },
374
+ } satisfies AcsIdentityClient)
375
+
376
+ await mintAcsGuestToken("tenant:idle-user")
377
+ now += 4 * 60 * 60 * 1000 + 1
378
+
379
+ const unrelated = await mintAcsGuestToken("tenant:new-user")
380
+ expect(unrelated.acsUserId).toBe("guest-user-2")
381
+
382
+ let returningFinished = false
383
+ const returning = mintAcsGuestToken("tenant:idle-user").then((credential) => {
384
+ returningFinished = true
385
+ return credential
386
+ })
387
+ await new Promise((resolve) => setTimeout(resolve, 0))
388
+ expect(returningFinished).toBe(false)
389
+
390
+ releaseDeletion?.()
391
+ expect((await returning).acsUserId).toBe("guest-user-3")
392
+ } finally {
393
+ Date.now = originalNow
394
+ }
395
+ })
396
+ })
cloud-v2/packages/runtime/src/services/meetings/acs-teams.service.ts ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {CommunicationIdentityClient, type CommunicationUserToken} from "@azure/communication-identity"
2
+
3
+ export const ACS_GUEST_TOKEN_EXPIRES_IN_MINUTES = 120
4
+ export const ACS_GUEST_MINT_LIMIT_PER_WINDOW = 12
5
+ export const ACS_GUEST_MINT_WINDOW_MS = 10 * 60 * 1000
6
+ export const ACS_GUEST_TOKEN_REUSE_MIN_REMAINING_MS = 15 * 60 * 1000
7
+ export const ACS_GUEST_STATE_IDLE_TTL_MS = 4 * 60 * 60 * 1000
8
+ export const ACS_GUEST_STATE_MAX_ENTRIES = 10_000
9
+ const ACS_GUEST_STATE_SWEEP_INTERVAL_MS = 5 * 60 * 1000
10
+ const ACS_GUEST_STATE_SWEEP_BATCH_SIZE = 25
11
+
12
+ export interface AcsIdentityClient {
13
+ createUserAndToken(
14
+ scopes: string[],
15
+ options: {tokenExpiresInMinutes: number},
16
+ ): Promise<Pick<CommunicationUserToken, "token" | "expiresOn" | "user">>
17
+ getToken?(
18
+ user: {communicationUserId: string},
19
+ scopes: string[],
20
+ options: {tokenExpiresInMinutes: number},
21
+ ): Promise<Pick<CommunicationUserToken, "token" | "expiresOn">>
22
+ deleteUser?(user: {communicationUserId: string}): Promise<void>
23
+ getTokenForTeamsUser(input: {
24
+ teamsUserAadToken: string
25
+ clientId: string
26
+ userObjectId: string
27
+ }): Promise<{token: string; expiresOn: Date}>
28
+ }
29
+
30
+ export type AcsMeetingCredential =
31
+ | {
32
+ token: string
33
+ expiresOn: string
34
+ identityMode: "guest"
35
+ acsUserId: string
36
+ guestReason?: "teams-license-unavailable"
37
+ }
38
+ | {
39
+ token: string
40
+ expiresOn: string
41
+ identityMode: "teams-user"
42
+ }
43
+
44
+ interface GuestMintState {
45
+ mints: number[]
46
+ acsUserId?: string
47
+ cached?: Extract<AcsMeetingCredential, {identityMode: "guest"}>
48
+ inFlight?: Promise<Extract<AcsMeetingCredential, {identityMode: "guest"}>>
49
+ cleanupInFlight?: Promise<void>
50
+ lastAccessedAt: number
51
+ }
52
+
53
+ const guestMintState = new Map<string, GuestMintState>()
54
+ let lastGuestStateSweepAt = 0
55
+ let testClient: AcsIdentityClient | null = null
56
+
57
+ export class TeamsIdentityRejectedError extends Error {
58
+ constructor(message: string) {
59
+ super(message)
60
+ this.name = "TeamsIdentityRejectedError"
61
+ }
62
+ }
63
+
64
+ export class AcsCredentialError extends Error {
65
+ constructor(
66
+ message: string,
67
+ readonly status: 429 | 502 | 503,
68
+ ) {
69
+ super(message)
70
+ this.name = "AcsCredentialError"
71
+ }
72
+ }
73
+
74
+ export interface TeamsSubject {
75
+ token: string
76
+ tenantId: string
77
+ objectId: string
78
+ }
79
+
80
+ export function assertAcsTeamsConfigured(): void {
81
+ if (!process.env.ACS_CONNECTION_STRING?.trim()) throw new Error("meetings service requires ACS_CONNECTION_STRING")
82
+ }
83
+
84
+ /**
85
+ * Bind the opaque Microsoft token to our authenticated Runtime caller. ACS, the
86
+ * token's resource server, validates it with the expected userObjectId/clientId.
87
+ * Microsoft-owned access tokens are not necessarily readable JWTs:
88
+ * https://learn.microsoft.com/entra/identity-platform/access-tokens#token-ownership
89
+ */
90
+ export function bindTeamsSubject(token: string, expected: {tenantId: string; objectId: string}): TeamsSubject {
91
+ const {tenantId} = teamsUserConfiguration()
92
+ if (expected.tenantId !== tenantId || !expected.objectId)
93
+ throw new TeamsIdentityRejectedError("Teams token subject does not match Runtime identity")
94
+ return {token, tenantId, objectId: expected.objectId}
95
+ }
96
+
97
+ export async function exchangeAcsTeamsUserToken(
98
+ subject: TeamsSubject,
99
+ ): Promise<Extract<AcsMeetingCredential, {identityMode: "teams-user"}>> {
100
+ const {tenantId, clientId} = teamsUserConfiguration()
101
+ if (subject.tenantId !== tenantId || !subject.objectId)
102
+ throw new TeamsIdentityRejectedError("Teams token subject does not match Runtime identity")
103
+ const client = identityClient()
104
+ let result
105
+ try {
106
+ // These trusted identifiers must never come from the request body or a decoded
107
+ // access token. Microsoft validates both against its opaque token.
108
+ result = await client.getTokenForTeamsUser({
109
+ teamsUserAadToken: subject.token,
110
+ clientId,
111
+ userObjectId: subject.objectId,
112
+ })
113
+ } catch (error) {
114
+ if (isTeamsLicenseUnavailable(error)) throw error
115
+ const status = error && typeof error === "object" && "statusCode" in error ? error.statusCode : undefined
116
+ if (status === 400 || status === 401 || status === 403)
117
+ throw new TeamsIdentityRejectedError(
118
+ "Microsoft could not verify your Teams account. Sign in again or contact your administrator",
119
+ )
120
+ if (status === 429) throw new AcsCredentialError("Microsoft Teams is busy; try again later", 429)
121
+ // Azure errors can include the request (and its bearer). Never forward/log them.
122
+ throw new AcsCredentialError("Teams identity provider unavailable", 502)
123
+ }
124
+ return {
125
+ token: result.token,
126
+ expiresOn: result.expiresOn.toISOString(),
127
+ identityMode: "teams-user",
128
+ }
129
+ }
130
+
131
+ /** Only Microsoft's explicit license rejection permits automatic guest joining. */
132
+ export function isTeamsLicenseUnavailable(error: unknown): boolean {
133
+ return (
134
+ typeof error === "object" && error !== null && "code" in error && error.code === "UserLicenseNotPresentForbidden"
135
+ )
136
+ }
137
+
138
+ /** The subject identifiers must come from the authenticated Runtime user. */
139
+ export async function issueAcsTeamsCredential(
140
+ subject: TeamsSubject,
141
+ authenticatedUserId: string,
142
+ ): Promise<AcsMeetingCredential> {
143
+ try {
144
+ return await exchangeAcsTeamsUserToken(subject)
145
+ } catch (error) {
146
+ if (!isTeamsLicenseUnavailable(error)) throw error
147
+ return {...(await mintAcsGuestToken(authenticatedUserId)), guestReason: "teams-license-unavailable"}
148
+ }
149
+ }
150
+
151
+ export async function mintAcsGuestToken(
152
+ authenticatedUserId: string,
153
+ ): Promise<Extract<AcsMeetingCredential, {identityMode: "guest"}>> {
154
+ const now = Date.now()
155
+ const state = await guestStateFor(authenticatedUserId, now)
156
+ if (state.cached && Date.parse(state.cached.expiresOn) - now > ACS_GUEST_TOKEN_REUSE_MIN_REMAINING_MS) {
157
+ return state.cached
158
+ }
159
+ if (state.inFlight) return state.inFlight
160
+
161
+ const mint = mintGuestTokenForState(state, now)
162
+ state.inFlight = mint
163
+ try {
164
+ return await mint
165
+ } finally {
166
+ if (state.inFlight === mint) state.inFlight = undefined
167
+ state.lastAccessedAt = Date.now()
168
+ }
169
+ }
170
+
171
+ async function mintGuestTokenForState(
172
+ state: GuestMintState,
173
+ now: number,
174
+ ): Promise<Extract<AcsMeetingCredential, {identityMode: "guest"}>> {
175
+ enforceGuestMintLimit(state, now)
176
+
177
+ try {
178
+ const client = identityClient()
179
+ const options = {
180
+ tokenExpiresInMinutes: ACS_GUEST_TOKEN_EXPIRES_IN_MINUTES,
181
+ }
182
+ let credential: Extract<AcsMeetingCredential, {identityMode: "guest"}>
183
+ if (state.acsUserId && client.getToken) {
184
+ const result = await client.getToken({communicationUserId: state.acsUserId}, ["voip"], options)
185
+ credential = {
186
+ token: result.token,
187
+ expiresOn: result.expiresOn.toISOString(),
188
+ identityMode: "guest",
189
+ acsUserId: state.acsUserId,
190
+ }
191
+ } else {
192
+ const result = await client.createUserAndToken(["voip"], options)
193
+ credential = {
194
+ token: result.token,
195
+ expiresOn: result.expiresOn.toISOString(),
196
+ identityMode: "guest",
197
+ acsUserId: result.user.communicationUserId,
198
+ }
199
+ }
200
+ state.acsUserId = credential.acsUserId
201
+ state.cached = credential
202
+ return credential
203
+ } catch (error) {
204
+ if (error instanceof AcsCredentialError) throw error
205
+ // Only a confirmed missing ACS user invalidates the reusable identity.
206
+ // Network, throttling, and provider failures must not rotate the caller to
207
+ // a new communication user on the next retry.
208
+ if (isMissingAcsUserError(error)) {
209
+ state.acsUserId = undefined
210
+ state.cached = undefined
211
+ }
212
+ throw new AcsCredentialError("Teams meeting provider unavailable", 502)
213
+ }
214
+ }
215
+
216
+ export function resetAcsTeamsAuthCache(): void {
217
+ guestMintState.clear()
218
+ lastGuestStateSweepAt = 0
219
+ testClient = null
220
+ }
221
+
222
+ /** Test-only observation for the bounded in-process guest state. */
223
+ export function getAcsGuestStateSizeForTests(): number {
224
+ return guestMintState.size
225
+ }
226
+
227
+ /** Test-only seam for exercising both ACS identity operations without Azure. */
228
+ export function setAcsIdentityClientForTests(client: AcsIdentityClient | null): void {
229
+ testClient = client
230
+ guestMintState.clear()
231
+ lastGuestStateSweepAt = 0
232
+ }
233
+
234
+ function identityClient(): AcsIdentityClient {
235
+ assertAcsTeamsConfigured()
236
+ return testClient ?? new CommunicationIdentityClient(process.env.ACS_CONNECTION_STRING!)
237
+ }
238
+
239
+ function teamsUserConfiguration(): {
240
+ tenantId: string
241
+ clientId: string
242
+ } {
243
+ const tenantId = process.env.ENTRA_TENANT_ID?.trim()
244
+ const clientId = process.env.ENTRA_CLIENT_ID?.trim()
245
+ if (!tenantId || !clientId) {
246
+ throw new AcsCredentialError("Microsoft Teams employee identity is not configured", 503)
247
+ }
248
+ return {tenantId, clientId}
249
+ }
250
+
251
+ async function guestStateFor(authenticatedUserId: string, now: number): Promise<GuestMintState> {
252
+ let state = guestMintState.get(authenticatedUserId)
253
+ if (state) {
254
+ if (state.cleanupInFlight) {
255
+ await state.cleanupInFlight
256
+ return guestStateFor(authenticatedUserId, Date.now())
257
+ }
258
+ state.lastAccessedAt = now
259
+ return state
260
+ }
261
+
262
+ pruneGuestMintState(now)
263
+ if (guestMintState.size >= ACS_GUEST_STATE_MAX_ENTRIES) {
264
+ const cleanup = [...guestMintState.values()].find(({cleanupInFlight}) => cleanupInFlight)?.cleanupInFlight
265
+ if (cleanup) {
266
+ await cleanup
267
+ if (guestMintState.size >= ACS_GUEST_STATE_MAX_ENTRIES) {
268
+ throw new AcsCredentialError("Teams credential service is temporarily at capacity", 503)
269
+ }
270
+ return guestStateFor(authenticatedUserId, Date.now())
271
+ }
272
+ throw new AcsCredentialError("Teams credential service is temporarily at capacity", 503)
273
+ }
274
+
275
+ state = {mints: [], lastAccessedAt: now}
276
+ guestMintState.set(authenticatedUserId, state)
277
+ return state
278
+ }
279
+
280
+ function pruneGuestMintState(now: number): void {
281
+ if (
282
+ now - lastGuestStateSweepAt >= ACS_GUEST_STATE_SWEEP_INTERVAL_MS ||
283
+ guestMintState.size >= ACS_GUEST_STATE_MAX_ENTRIES
284
+ ) {
285
+ lastGuestStateSweepAt = now
286
+ let started = 0
287
+ for (const [userId, state] of guestMintState) {
288
+ if (
289
+ started < ACS_GUEST_STATE_SWEEP_BATCH_SIZE &&
290
+ !state.inFlight &&
291
+ !state.cleanupInFlight &&
292
+ now - state.lastAccessedAt >= ACS_GUEST_STATE_IDLE_TTL_MS
293
+ ) {
294
+ startGuestStateCleanup(userId, state)
295
+ started += 1
296
+ }
297
+ }
298
+ }
299
+ }
300
+
301
+ function startGuestStateCleanup(userId: string, state: GuestMintState): void {
302
+ const client = identityClient()
303
+ if (state.acsUserId && !client.deleteUser) return
304
+ const deletion = state.acsUserId
305
+ ? Promise.resolve().then(() => client.deleteUser!({communicationUserId: state.acsUserId!}))
306
+ : Promise.resolve()
307
+ const cleanup = deletion
308
+ .then(
309
+ () => true,
310
+ (error) => isMissingAcsUserError(error),
311
+ )
312
+ .then((identityIsGone) => {
313
+ if (
314
+ identityIsGone &&
315
+ guestMintState.get(userId) === state &&
316
+ state.cleanupInFlight === cleanup &&
317
+ !state.inFlight
318
+ ) {
319
+ guestMintState.delete(userId)
320
+ }
321
+ })
322
+ .finally(() => {
323
+ // Retain the mapping when ACS cleanup fails transiently so we never lose
324
+ // track of a persistent identity and create an orphan on the next request.
325
+ if (guestMintState.get(userId) === state && state.cleanupInFlight === cleanup) {
326
+ state.cleanupInFlight = undefined
327
+ }
328
+ })
329
+ state.cleanupInFlight = cleanup
330
+ }
331
+
332
+ function isMissingAcsUserError(error: unknown): boolean {
333
+ if (!error || typeof error !== "object") return false
334
+ const candidate = error as {
335
+ status?: unknown
336
+ statusCode?: unknown
337
+ code?: unknown
338
+ }
339
+ return (
340
+ candidate.status === 404 ||
341
+ candidate.statusCode === 404 ||
342
+ candidate.code === "ResourceNotFound" ||
343
+ candidate.code === "UserNotFound" ||
344
+ candidate.code === "IdentityNotFound"
345
+ )
346
+ }
347
+
348
+ function enforceGuestMintLimit(state: GuestMintState, now: number): void {
349
+ state.mints = state.mints.filter((mintedAt) => now - mintedAt < ACS_GUEST_MINT_WINDOW_MS)
350
+ if (state.mints.length >= ACS_GUEST_MINT_LIMIT_PER_WINDOW) {
351
+ throw new AcsCredentialError("Too many Teams credential requests. Try again in a few minutes.", 429)
352
+ }
353
+ state.mints.push(now)
354
+ }
cloud-v2/packages/runtime/src/services/meetings/meeting-providers.test.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {describe, expect, test} from "bun:test";
2
+
3
+ import {resolveMeetingProviders} from "./meeting-providers";
4
+
5
+ describe("Runtime meeting providers", () => {
6
+ test("selects the ACS Teams implementation explicitly", () => {
7
+ expect([...resolveMeetingProviders("acs-teams")]).toEqual(["acs-teams"]);
8
+ });
9
+
10
+ test("rejects missing and unknown providers", () => {
11
+ expect(() => resolveMeetingProviders("")).toThrow("MEETING_PROVIDERS");
12
+ expect(() => resolveMeetingProviders("zoom")).toThrow(
13
+ "unknown providers: zoom",
14
+ );
15
+ });
16
+ });
cloud-v2/packages/runtime/src/services/meetings/meeting-providers.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const MEETING_PROVIDER_NAMES = ["acs-teams"] as const;
2
+
3
+ export type MeetingProviderName = (typeof MEETING_PROVIDER_NAMES)[number];
4
+
5
+ export function resolveMeetingProviders(
6
+ value = process.env.MEETING_PROVIDERS,
7
+ ): Set<MeetingProviderName> {
8
+ const requested = (value ?? "")
9
+ .split(",")
10
+ .map((entry) => entry.trim())
11
+ .filter(Boolean);
12
+ if (requested.length === 0) {
13
+ throw new Error(
14
+ "meetings service requires at least one MEETING_PROVIDERS value",
15
+ );
16
+ }
17
+
18
+ const known = new Set<string>(MEETING_PROVIDER_NAMES);
19
+ const unknown = requested.filter((entry) => !known.has(entry));
20
+ if (unknown.length > 0) {
21
+ throw new Error(
22
+ `MEETING_PROVIDERS contains unknown providers: ${unknown.join(", ")}`,
23
+ );
24
+ }
25
+ return new Set(requested as MeetingProviderName[]);
26
+ }
cloud-v2/packages/runtime/src/services/meetings/teams-identity-selection.test.ts ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {afterEach, beforeEach, describe, expect, test} from "bun:test"
2
+ import {issueAcsTeamsCredential, resetAcsTeamsAuthCache, setAcsIdentityClientForTests} from "./acs-teams.service"
3
+
4
+ const subject = {token: "verified-subject", tenantId: "tenant", objectId: "employee"}
5
+ const saved = {
6
+ connection: process.env.ACS_CONNECTION_STRING,
7
+ tenant: process.env.ENTRA_TENANT_ID,
8
+ client: process.env.ENTRA_CLIENT_ID,
9
+ }
10
+ let exchangeError: unknown
11
+ let guestMints = 0
12
+
13
+ beforeEach(() => {
14
+ process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test"
15
+ process.env.ENTRA_TENANT_ID = "tenant"
16
+ process.env.ENTRA_CLIENT_ID = "mobile-client"
17
+ guestMints = 0
18
+ exchangeError = undefined
19
+ setAcsIdentityClientForTests({
20
+ async getTokenForTeamsUser(input) {
21
+ expect(input).toEqual({teamsUserAadToken: subject.token, clientId: "mobile-client", userObjectId: "employee"})
22
+ if (exchangeError) throw exchangeError
23
+ return {token: "employee-token", expiresOn: new Date("2030-01-01")}
24
+ },
25
+ async createUserAndToken() {
26
+ guestMints++
27
+ return {token: "guest-token", expiresOn: new Date("2030-01-01"), user: {communicationUserId: "acs-guest"}}
28
+ },
29
+ })
30
+ })
31
+ afterEach(() => {
32
+ resetAcsTeamsAuthCache()
33
+ for (const [key, value] of Object.entries({
34
+ ACS_CONNECTION_STRING: saved.connection,
35
+ ENTRA_TENANT_ID: saved.tenant,
36
+ ENTRA_CLIENT_ID: saved.client,
37
+ })) {
38
+ if (value === undefined) delete process.env[key]
39
+ else process.env[key] = value
40
+ }
41
+ })
42
+
43
+ describe("Teams identity selection", () => {
44
+ test("uses the licensed employee identity", async () => {
45
+ expect(await issueAcsTeamsCredential(subject, "user")).toMatchObject({
46
+ token: "employee-token",
47
+ identityMode: "teams-user",
48
+ })
49
+ expect(guestMints).toBe(0)
50
+ })
51
+ test("automatically joins as a guest only for Microsoft's missing-license code", async () => {
52
+ exchangeError = Object.assign(new Error("Teams disabled in user licenses"), {
53
+ code: "UserLicenseNotPresentForbidden",
54
+ })
55
+ expect(await issueAcsTeamsCredential(subject, "user")).toMatchObject({
56
+ identityMode: "guest",
57
+ guestReason: "teams-license-unavailable",
58
+ })
59
+ expect(guestMints).toBe(1)
60
+ })
61
+ for (const error of [
62
+ {code: "Forbidden"},
63
+ {code: "Unauthorized"},
64
+ {code: "TooManyRequests"},
65
+ new Error("UserLicenseNotPresentForbidden"),
66
+ new Error("network unavailable"),
67
+ ])
68
+ test(`does not downgrade ${JSON.stringify(error)}`, async () => {
69
+ exchangeError = error
70
+ await expect(issueAcsTeamsCredential(subject, "user")).rejects.toThrow("unavailable")
71
+ expect(guestMints).toBe(0)
72
+ })
73
+ })
cloud-v2/packages/runtime/src/services/meetings/teams-meetings.service.test.ts ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {afterEach, beforeEach, describe, expect, test} from "bun:test"
2
+ import {resetAcsTeamsAuthCache, setAcsIdentityClientForTests} from "./acs-teams.service"
3
+ import {createTeamsMeeting, resetTeamsMeetingStateForTests, retireTeamsMeeting} from "./teams-meetings.service"
4
+
5
+ const fetchBefore = globalThis.fetch
6
+ const saved = new Map<string, string | undefined>()
7
+ let exchangeError: unknown
8
+ let graphStatus: number
9
+ let requests: Array<{url: string; method?: string; body?: unknown}>
10
+ const subject = {tenantId: "tenant", objectId: "employee", token: "verified-teams-token"}
11
+ const create = (employee = false, actor = "caller") =>
12
+ createTeamsMeeting({
13
+ actor,
14
+ title: "Daily standup",
15
+ durationMinutes: 30,
16
+ ...(employee ? {subject} : {}),
17
+ })
18
+
19
+ beforeEach(() => {
20
+ for (const [key, value] of Object.entries({
21
+ ACS_CONNECTION_STRING: "endpoint=https://test.communication.azure.com/;accesskey=test",
22
+ ENTRA_TENANT_ID: "tenant",
23
+ ENTRA_CLIENT_ID: "mobile-client",
24
+ TEAMS_GRAPH_TENANT_ID: "tenant",
25
+ TEAMS_GRAPH_CLIENT_ID: "graph-app",
26
+ TEAMS_GRAPH_CLIENT_SECRET: "graph-secret",
27
+ TEAMS_GRAPH_ORGANIZER_ID: "fallback-organizer",
28
+ })) {
29
+ saved.set(key, process.env[key])
30
+ process.env[key] = value
31
+ }
32
+ exchangeError = undefined
33
+ graphStatus = 200
34
+ requests = []
35
+ resetTeamsMeetingStateForTests()
36
+ setAcsIdentityClientForTests({
37
+ async getTokenForTeamsUser() {
38
+ if (exchangeError) throw exchangeError
39
+ return {token: "employee-acs-token", expiresOn: new Date("2030-01-01")}
40
+ },
41
+ async createUserAndToken() {
42
+ throw new Error("Creation must not mint a guest ACS user")
43
+ },
44
+ })
45
+ globalThis.fetch = (async (input, init) => {
46
+ const url = String(input)
47
+ requests.push({url, method: init?.method, body: typeof init?.body === "string" ? JSON.parse(init.body) : undefined})
48
+ if (url.startsWith("https://login.microsoftonline.com/")) {
49
+ expect(init?.body).toBeInstanceOf(URLSearchParams)
50
+ expect((init?.body as URLSearchParams).get("scope")).toBe("https://graph.microsoft.com/.default")
51
+ return Response.json({access_token: "graph-token", expires_in: 3600})
52
+ }
53
+ expect(new Headers(init?.headers).get("authorization")).toBe("Bearer graph-token")
54
+ if (graphStatus !== 200) return Response.json({error: {code: "provider-error"}}, {status: graphStatus})
55
+ if (init?.method === "DELETE") return new Response(null, {status: 204})
56
+ return Response.json({id: "meeting/id", joinWebUrl: "https://teams.microsoft.com/meet/123456?p=secret"})
57
+ }) as typeof fetch
58
+ })
59
+
60
+ afterEach(() => {
61
+ globalThis.fetch = fetchBefore
62
+ resetTeamsMeetingStateForTests()
63
+ resetAcsTeamsAuthCache()
64
+ for (const [key, value] of saved) {
65
+ if (value === undefined) delete process.env[key]
66
+ else process.env[key] = value
67
+ }
68
+ saved.clear()
69
+ })
70
+
71
+ describe("Runtime Teams meeting creation", () => {
72
+ test("uses the configured organizer without Entra and returns only public meeting data", async () => {
73
+ const result = await create()
74
+ expect(result).toMatchObject({provider: "acs-teams", identityMode: "guest", guestReason: "no-entra-identity"})
75
+ expect(Object.keys(result).sort()).toEqual(["guestReason", "identityMode", "joinUrl", "meetingRef", "provider"])
76
+ expect(requests.at(-1)?.url).toEndWith("/users/fallback-organizer/onlineMeetings")
77
+ expect(requests.at(-1)?.body).toMatchObject({subject: "Daily standup", lobbyBypassSettings: {scope: "everyone"}})
78
+ expect(JSON.stringify(result)).not.toContain("graph-secret")
79
+ })
80
+ test("uses the verified licensed employee as organizer", async () => {
81
+ expect(await create(true)).toMatchObject({identityMode: "teams-user"})
82
+ expect(requests.at(-1)?.url).toEndWith("/users/employee/onlineMeetings")
83
+ })
84
+ test("falls back only for the explicit missing Teams license response", async () => {
85
+ exchangeError = {code: "UserLicenseNotPresentForbidden"}
86
+ expect(await create(true)).toMatchObject({identityMode: "guest", guestReason: "teams-license-unavailable"})
87
+ expect(requests.at(-1)?.url).toEndWith("/users/fallback-organizer/onlineMeetings")
88
+ })
89
+ for (const error of [{code: "Forbidden"}, {code: "Unauthorized"}, {code: "TooManyRequests"}, new Error("network")]) {
90
+ test(`does not create with the fallback organizer after ${JSON.stringify(error)}`, async () => {
91
+ exchangeError = error
92
+ await expect(create(true)).rejects.toThrow("unavailable")
93
+ expect(requests).toEqual([])
94
+ })
95
+ }
96
+ test("rejects an employee from a different Graph tenant before any provider call", async () => {
97
+ process.env.TEAMS_GRAPH_TENANT_ID = "different-tenant"
98
+ await expect(create(true)).rejects.toMatchObject({status: 403})
99
+ expect(requests).toEqual([])
100
+ })
101
+ test("does not fall back when Graph denies the employee access policy", async () => {
102
+ graphStatus = 403
103
+ await expect(create(true)).rejects.toMatchObject({status: 403})
104
+ expect(requests.filter((r) => r.url.includes("graph.microsoft.com"))).toHaveLength(1)
105
+ expect(requests.at(-1)?.url).toEndWith("/users/employee/onlineMeetings")
106
+ })
107
+ test("requires a configured fallback organizer only for guest creation", async () => {
108
+ delete process.env.TEAMS_GRAPH_ORGANIZER_ID
109
+ await expect(create()).rejects.toMatchObject({status: 503})
110
+ expect(requests).toEqual([])
111
+ expect(await create(true)).toMatchObject({identityMode: "teams-user"})
112
+ })
113
+ test("rate limits creation per caller", async () => {
114
+ for (let i = 0; i < 12; i++) await create()
115
+ await expect(create()).rejects.toMatchObject({status: 429})
116
+ expect(await create(false, "other-caller")).toMatchObject({identityMode: "guest"})
117
+ })
118
+ })
119
+
120
+ describe("Runtime Teams retirement ownership", () => {
121
+ test("retires only the meeting encoded in the authenticated caller's receipt", async () => {
122
+ const created = await create(true)
123
+ await retireTeamsMeeting("caller", created.meetingRef)
124
+ expect(requests.at(-1)).toMatchObject({
125
+ method: "DELETE",
126
+ url: "https://graph.microsoft.com/v1.0/users/employee/onlineMeetings/meeting%2Fid",
127
+ })
128
+ })
129
+ test("rejects another caller, tampering, and changed Graph tenant", async () => {
130
+ const created = await create()
131
+ const before = requests.length
132
+ await expect(retireTeamsMeeting("other-caller", created.meetingRef)).rejects.toMatchObject({status: 403})
133
+ await expect(retireTeamsMeeting("caller", `x${created.meetingRef}`)).rejects.toMatchObject({status: 403})
134
+ await expect(
135
+ retireTeamsMeeting("caller", `${created.meetingRef.split(".")[0]}.${"é".repeat(43)}`),
136
+ ).rejects.toMatchObject({status: 403})
137
+ process.env.TEAMS_GRAPH_TENANT_ID = "other-tenant"
138
+ await expect(retireTeamsMeeting("caller", created.meetingRef)).rejects.toMatchObject({status: 403})
139
+ expect(requests).toHaveLength(before)
140
+ })
141
+ test("treats an already deleted meeting as retired", async () => {
142
+ const created = await create()
143
+ graphStatus = 404
144
+ await expect(retireTeamsMeeting("caller", created.meetingRef)).resolves.toBeUndefined()
145
+ })
146
+ })
cloud-v2/packages/runtime/src/services/meetings/teams-meetings.service.ts ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {createHash, createHmac, timingSafeEqual} from "node:crypto"
2
+
3
+ import {exchangeAcsTeamsUserToken, isTeamsLicenseUnavailable, type TeamsSubject} from "./acs-teams.service"
4
+
5
+ const GRAPH = "https://graph.microsoft.com/v1.0"
6
+ const TIMEOUT_MS = 15_000
7
+ const CREATE_WINDOW_MS = 10 * 60 * 1000
8
+ const createWindows = new Map<string, {started: number; count: number}>()
9
+ let cachedToken: {key: string; token: string; expiresAt: number} | undefined
10
+
11
+ export class TeamsMeetingError extends Error {
12
+ constructor(
13
+ message: string,
14
+ readonly status: 403 | 429 | 502 | 503,
15
+ ) {
16
+ super(message)
17
+ }
18
+ }
19
+
20
+ interface GraphConfiguration {
21
+ tenantId: string
22
+ clientId: string
23
+ clientSecret: string
24
+ organizerId: string
25
+ }
26
+
27
+ export interface CreatedTeamsMeeting {
28
+ provider: "acs-teams"
29
+ joinUrl: string
30
+ meetingRef: string
31
+ identityMode: "teams-user" | "guest"
32
+ guestReason?: "no-entra-identity" | "teams-license-unavailable"
33
+ }
34
+
35
+ function configuration(): GraphConfiguration {
36
+ const tenantId = process.env.TEAMS_GRAPH_TENANT_ID?.trim()
37
+ const clientId = process.env.TEAMS_GRAPH_CLIENT_ID?.trim()
38
+ const clientSecret = process.env.TEAMS_GRAPH_CLIENT_SECRET?.trim()
39
+ if (!tenantId || !clientId || !clientSecret) {
40
+ throw new TeamsMeetingError("Teams meeting creation is not configured on this Runtime", 503)
41
+ }
42
+ return {tenantId, clientId, clientSecret, organizerId: process.env.TEAMS_GRAPH_ORGANIZER_ID?.trim() ?? ""}
43
+ }
44
+
45
+ export async function createTeamsMeeting(input: {
46
+ actor: string
47
+ subject?: TeamsSubject
48
+ title: string
49
+ durationMinutes: number
50
+ }): Promise<CreatedTeamsMeeting> {
51
+ const config = configuration()
52
+ limitCreation(input.actor)
53
+ let organizerId = config.organizerId
54
+ let identityMode: CreatedTeamsMeeting["identityMode"] = "guest"
55
+ let guestReason: CreatedTeamsMeeting["guestReason"] = "no-entra-identity"
56
+ if (input.subject) {
57
+ if (input.subject.tenantId !== config.tenantId) {
58
+ throw new TeamsMeetingError("Teams organizer does not belong to this Runtime's Graph tenant", 403)
59
+ }
60
+ try {
61
+ // Reuse Microsoft's existing license decision, not a subscription-name heuristic.
62
+ // This token stays server-side; joining obtains its own fresh credential.
63
+ await exchangeAcsTeamsUserToken(input.subject)
64
+ organizerId = input.subject.objectId
65
+ identityMode = "teams-user"
66
+ guestReason = undefined
67
+ } catch (error) {
68
+ if (!isTeamsLicenseUnavailable(error)) throw error
69
+ guestReason = "teams-license-unavailable"
70
+ }
71
+ }
72
+ if (!organizerId) throw new TeamsMeetingError("A fallback Teams organizer is not configured on this Runtime", 503)
73
+
74
+ const start = Date.now()
75
+ const end = start + input.durationMinutes * 60_000
76
+ const response = await graphRequest(config, `/users/${encodeURIComponent(organizerId)}/onlineMeetings`, {
77
+ method: "POST",
78
+ body: JSON.stringify({
79
+ startDateTime: new Date(start).toISOString(),
80
+ endDateTime: new Date(end).toISOString(),
81
+ subject: input.title,
82
+ lobbyBypassSettings: {scope: "everyone", isDialInBypassEnabled: true},
83
+ allowedPresenters: "everyone",
84
+ joinMeetingIdSettings: {isPasscodeRequired: true},
85
+ }),
86
+ })
87
+ const meeting = (await response.json()) as {id?: unknown; joinWebUrl?: unknown}
88
+ if (typeof meeting.id !== "string" || !meeting.id || typeof meeting.joinWebUrl !== "string") {
89
+ throw new TeamsMeetingError("Microsoft Graph returned an invalid meeting", 502)
90
+ }
91
+ const url = new URL(meeting.joinWebUrl)
92
+ if (url.protocol !== "https:" || !["teams.microsoft.com", "teams.cloud.microsoft"].includes(url.hostname)) {
93
+ throw new TeamsMeetingError("Microsoft Graph returned an invalid meeting link", 502)
94
+ }
95
+ // A signed ownership receipt avoids adding a Runtime database. It authorizes only
96
+ // retiring this caller's meeting in this Graph tenant/application, never an arbitrary ID.
97
+ const payload = Buffer.from(
98
+ JSON.stringify({
99
+ actor: input.actor,
100
+ tenantId: config.tenantId,
101
+ clientId: config.clientId,
102
+ organizerId,
103
+ meetingId: meeting.id,
104
+ expiresAt: end + 24 * 60 * 60_000,
105
+ }),
106
+ ).toString("base64url")
107
+ return {
108
+ provider: "acs-teams",
109
+ joinUrl: meeting.joinWebUrl,
110
+ meetingRef: `${payload}.${signReference(config, payload)}`,
111
+ identityMode,
112
+ ...(guestReason ? {guestReason} : {}),
113
+ }
114
+ }
115
+
116
+ /** Retiring a Graph resource does not hang up the participants in an active call. */
117
+ export async function retireTeamsMeeting(actor: string, meetingRef: string): Promise<void> {
118
+ const config = configuration()
119
+ const [payload, signature, extra] = meetingRef.split(".")
120
+ const expected = signReference(config, payload ?? "")
121
+ if (
122
+ !payload ||
123
+ !signature ||
124
+ extra !== undefined ||
125
+ !/^[A-Za-z0-9_-]{43}$/.test(signature) ||
126
+ !timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
127
+ ) {
128
+ throw new TeamsMeetingError("Invalid meeting ownership reference", 403)
129
+ }
130
+ let receipt
131
+ try {
132
+ receipt = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"))
133
+ } catch {
134
+ throw new TeamsMeetingError("Invalid meeting ownership reference", 403)
135
+ }
136
+ if (
137
+ !receipt ||
138
+ typeof receipt !== "object" ||
139
+ receipt.actor !== actor ||
140
+ receipt.tenantId !== config.tenantId ||
141
+ receipt.clientId !== config.clientId ||
142
+ typeof receipt.expiresAt !== "number" ||
143
+ receipt.expiresAt <= Date.now() ||
144
+ typeof receipt.organizerId !== "string" ||
145
+ typeof receipt.meetingId !== "string"
146
+ ) {
147
+ throw new TeamsMeetingError("Meeting ownership reference does not belong to this caller or has expired", 403)
148
+ }
149
+ await graphRequest(
150
+ config,
151
+ `/users/${encodeURIComponent(receipt.organizerId)}/onlineMeetings/${encodeURIComponent(receipt.meetingId)}`,
152
+ {method: "DELETE"},
153
+ )
154
+ }
155
+
156
+ function signReference(config: GraphConfiguration, payload: string): string {
157
+ return createHmac("sha256", config.clientSecret).update(`mentra-teams-meeting-v1:${payload}`).digest("base64url")
158
+ }
159
+
160
+ async function graphRequest(config: GraphConfiguration, path: string, init: RequestInit): Promise<Response> {
161
+ const token = await graphToken(config)
162
+ let response: Response
163
+ try {
164
+ response = await fetch(`${GRAPH}${path}`, {
165
+ ...init,
166
+ headers: {"Authorization": `Bearer ${token}`, "Content-Type": "application/json"},
167
+ signal: AbortSignal.timeout(TIMEOUT_MS),
168
+ })
169
+ } catch {
170
+ throw new TeamsMeetingError("Microsoft Graph is unavailable; the meeting operation could not be confirmed", 502)
171
+ }
172
+ if (response.ok || (init.method === "DELETE" && response.status === 404)) return response
173
+ if (response.status === 403) {
174
+ throw new TeamsMeetingError(
175
+ "Microsoft Graph denied this organizer. Check Teams application access policy and permissions",
176
+ 403,
177
+ )
178
+ }
179
+ if (response.status === 429) throw new TeamsMeetingError("Microsoft Graph is busy; try again later", 429)
180
+ throw new TeamsMeetingError("Microsoft Graph could not complete the meeting operation", 502)
181
+ }
182
+
183
+ async function graphToken(config: GraphConfiguration): Promise<string> {
184
+ const key = createHash("sha256").update(JSON.stringify(config)).digest("hex")
185
+ if (cachedToken?.key === key && cachedToken.expiresAt > Date.now() + 60_000) return cachedToken.token
186
+ try {
187
+ const response = await fetch(
188
+ `https://login.microsoftonline.com/${encodeURIComponent(config.tenantId)}/oauth2/v2.0/token`,
189
+ {
190
+ method: "POST",
191
+ body: new URLSearchParams({
192
+ client_id: config.clientId,
193
+ client_secret: config.clientSecret,
194
+ grant_type: "client_credentials",
195
+ scope: "https://graph.microsoft.com/.default",
196
+ }),
197
+ signal: AbortSignal.timeout(TIMEOUT_MS),
198
+ },
199
+ )
200
+ if (!response.ok) throw new Error("token rejected")
201
+ const value = (await response.json()) as {access_token?: unknown; expires_in?: unknown}
202
+ if (
203
+ typeof value.access_token !== "string" ||
204
+ !value.access_token ||
205
+ typeof value.expires_in !== "number" ||
206
+ value.expires_in <= 0
207
+ ) {
208
+ throw new Error("invalid token response")
209
+ }
210
+ cachedToken = {key, token: value.access_token, expiresAt: Date.now() + value.expires_in * 1000}
211
+ return value.access_token
212
+ } catch {
213
+ throw new TeamsMeetingError("Runtime could not authenticate its Microsoft Graph application", 503)
214
+ }
215
+ }
216
+
217
+ function limitCreation(actor: string): void {
218
+ const now = Date.now()
219
+ for (const [key, state] of createWindows) {
220
+ if (now - state.started >= CREATE_WINDOW_MS) createWindows.delete(key)
221
+ }
222
+ let state = createWindows.get(actor)
223
+ if (!state) {
224
+ if (createWindows.size >= 10_000) throw new TeamsMeetingError("Meeting creation is temporarily at capacity", 503)
225
+ state = {started: now, count: 0}
226
+ createWindows.set(actor, state)
227
+ }
228
+ if (state.count >= 12) throw new TeamsMeetingError("Too many meeting creation requests; try again later", 429)
229
+ state.count += 1
230
+ }
231
+
232
+ export function resetTeamsMeetingStateForTests(): void {
233
+ cachedToken = undefined
234
+ createWindows.clear()
235
+ }
cloud-v2/packages/runtime/src/services/session/control-stream.ts ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Per-user control stream (`{user:X}:control`).
3
+ *
4
+ * The decided routing for subscription changes is "Option 2a": REST, delivered
5
+ * to the owning worker through a Redis stream, no pub/sub. We use a DEDICATED
6
+ * control stream rather than mixing control entries into the audio stream so
7
+ * the audio hot path never has to branch on entry type. The hash tag
8
+ * `{user:X}` keeps it on the same shard as the audio stream, ownership key, and
9
+ * subscription key.
10
+ *
11
+ * A control entry is only a NUDGE: it tells the owning worker "the subscription
12
+ * key changed, re-read it." The worker reconciles from the subscription key
13
+ * (the source of truth), never from the entry payload alone. That is what makes
14
+ * a REST write landing on a non-owner pod still correct: the non-owner writes
15
+ * the key and XADDs the nudge here; the owner's worker, which already reads this
16
+ * stream, picks up the nudge in order and reconciles from the key.
17
+ *
18
+ * Entries carry a `kind` field so control entry types can ride the same stream.
19
+ * Today:
20
+ * - `subscriptions-changed`: nudge the owner worker to re-read subscriptions.
21
+ * - `udp-liveness-ack`: a non-owner UDP ingress pod received a valid probe
22
+ * and asks the owner pod to ack it over the user's WebSocket.
23
+ */
24
+
25
+ import { getRedis } from "../../clients/redis.client";
26
+
27
+ /** Per-user control stream key. Hash-tagged to share a shard with the user's other keys. */
28
+ export function controlStreamKey(mentraUserId: string): string {
29
+ return `{user:${mentraUserId}}:control`;
30
+ }
31
+
32
+ /** Consumer group the owning worker joins to read control entries. */
33
+ export const CONTROL_STREAM_GROUP = "control-workers";
34
+
35
+ /**
36
+ * Length cap on the control stream. Control entries are rare (a subscription
37
+ * change is a human-paced event, not tens-per-second like audio), so a small
38
+ * cap is plenty; it exists only to keep the key from growing without bound if
39
+ * an owner is briefly absent.
40
+ */
41
+ export const CONTROL_STREAM_MAXLEN = 100;
42
+
43
+ /**
44
+ * XADD a `subscriptions-changed` nudge to the user's control stream. Called by
45
+ * the REST handler after it accepts a write to the subscription key. The
46
+ * `version` is carried for logging and tracing only; the worker still re-reads
47
+ * the key rather than trusting this number.
48
+ */
49
+ export async function publishSubscriptionsChanged(
50
+ mentraUserId: string,
51
+ version: number,
52
+ ): Promise<void> {
53
+ await getRedis().xadd(
54
+ controlStreamKey(mentraUserId),
55
+ "MAXLEN",
56
+ "~",
57
+ String(CONTROL_STREAM_MAXLEN),
58
+ "*",
59
+ "kind",
60
+ "subscriptions-changed",
61
+ "version",
62
+ String(version),
63
+ );
64
+ }
65
+
66
+ export interface UdpLivenessAckControl {
67
+ sessionTag: number;
68
+ audioSessionId: string;
69
+ probeId: string;
70
+ receivedAt: number;
71
+ }
72
+
73
+ /**
74
+ * Ask the owning pod to send an `audio.udp_liveness_ack` over the user's WS.
75
+ * Used when a UDP probe lands on a non-owner pod: ingress can prove UDP reached
76
+ * the cluster, but only the owner pod holds the client's WebSocket.
77
+ */
78
+ export async function publishUdpLivenessAck(
79
+ mentraUserId: string,
80
+ ack: UdpLivenessAckControl,
81
+ ): Promise<void> {
82
+ await getRedis().xadd(
83
+ controlStreamKey(mentraUserId),
84
+ "MAXLEN",
85
+ "~",
86
+ String(CONTROL_STREAM_MAXLEN),
87
+ "*",
88
+ "kind",
89
+ "udp-liveness-ack",
90
+ "sessionTag",
91
+ String(ack.sessionTag),
92
+ "audioSessionId",
93
+ ack.audioSessionId,
94
+ "probeId",
95
+ ack.probeId,
96
+ "receivedAt",
97
+ String(ack.receivedAt),
98
+ );
99
+ }
cloud-v2/packages/runtime/src/services/session/frame-timeline.test.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {expect, test} from "bun:test";
2
+ import {negotiatedFrameTimeline} from "./frame-timeline";
3
+
4
+ test("frame negotiation is default off until all ingress/worker readers are upgraded", () => {
5
+ const previous = process.env.AUDIO_FRAME_TIMELINE_ENABLED;
6
+ try {
7
+ delete process.env.AUDIO_FRAME_TIMELINE_ENABLED;
8
+ expect(negotiatedFrameTimeline(1)).toBeUndefined();
9
+ process.env.AUDIO_FRAME_TIMELINE_ENABLED = "false";
10
+ expect(negotiatedFrameTimeline(1)).toBeUndefined();
11
+ process.env.AUDIO_FRAME_TIMELINE_ENABLED = "true";
12
+ expect(negotiatedFrameTimeline(1)).toBe(1);
13
+ expect(negotiatedFrameTimeline()).toBeUndefined();
14
+ } finally {
15
+ if (previous === undefined) delete process.env.AUDIO_FRAME_TIMELINE_ENABLED;
16
+ else process.env.AUDIO_FRAME_TIMELINE_ENABLED = previous;
17
+ }
18
+ });
cloud-v2/packages/runtime/src/services/session/frame-timeline.ts ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Enable only after every UDP ingress and audio worker supports positioned
3
+ * frames. Handshake negotiation alone cannot protect older cross-pod readers.
4
+ */
5
+ export function negotiatedFrameTimeline(requested?: 1): 1 | undefined {
6
+ return requested === 1 && process.env.AUDIO_FRAME_TIMELINE_ENABLED === "true"
7
+ ? 1 : undefined;
8
+ }
cloud-v2/packages/runtime/src/services/session/ownership.ts ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Ownership: deciding which server instance is in charge of a user.
3
+ *
4
+ * Background. This service is the cloud side of live transcription: a user's
5
+ * glasses stream audio up, and we stream transcripts back down. To handle many
6
+ * users and to survive a machine dying, the service runs as many identical
7
+ * copies at once. Each copy is a "pod" (one running container), and a load
8
+ * balancer spreads incoming traffic across them.
9
+ *
10
+ * The problem this file solves. A user's audio packets can land on ANY pod (the
11
+ * load balancer doesn't care which), but the actual transcription for that user
12
+ * has to run on exactly ONE pod at a time: the one holding that user's WebSocket
13
+ * connection. We call that pod the user's "owner". So the pods need a way to
14
+ * agree on who owns each user, and to hand a user off automatically when the
15
+ * owner crashes.
16
+ *
17
+ * How it works. There is one Redis key per user that acts as a claim ticket:
18
+ * `{user:<id>}:owner` holds the owning pod's id. Two rules make it safe:
19
+ *
20
+ * 1. A pod can only take the key if nobody else holds it (Redis `SET ... NX`),
21
+ * so at most one pod owns a user at a time. This is a "distributed lock":
22
+ * a single shared flag that only one party can hold.
23
+ *
24
+ * 2. The key is set to expire after a few seconds (Redis `SET ... EX 5`). While
25
+ * a pod is alive it resets that timer every 1.5s. If it crashes, hangs, or
26
+ * loses its network, it stops resetting the timer, the key expires on its
27
+ * own, and another pod is free to claim the user. A missing refresh is the
28
+ * single signal for "the owner is gone", so we need no separate health check.
29
+ *
30
+ * Why the Lua scripts at the bottom. "Refresh" and "release" both mean "do
31
+ * something only if I'm still the owner". They run as Redis Lua scripts so the
32
+ * check and the action happen as one atomic step, otherwise another pod's claim
33
+ * could slip in between reading the key and acting on it, and we'd extend or
34
+ * delete a claim that is no longer ours.
35
+ */
36
+
37
+ import { createLogger } from "@mentra/cloud-shared";
38
+ import { getRedis } from "../../clients/redis.client";
39
+
40
+ const logger = createLogger("audio").child({ service: "ownership.service" });
41
+
42
+ /** TTL on the ownership key. Beyond this, the claim is forfeit. */
43
+ export const OWNERSHIP_TTL_SEC = 5;
44
+
45
+ /** How often the owner pod renews its claim. Comfortably inside TTL. */
46
+ export const OWNERSHIP_REFRESH_INTERVAL_MS = 1_500;
47
+
48
+ function ownerKey(mentraUserId: string): string {
49
+ return `{user:${mentraUserId}}:owner`;
50
+ }
51
+
52
+ export type ClaimResult = "claimed" | "already-ours" | "owned-by-other";
53
+
54
+ /**
55
+ * Try once to become this user's owner. Returns one of:
56
+ * - "claimed": we just took ownership (the key was free, our SET won).
57
+ * - "already-ours": the key was already set to our own pod id, so we still
58
+ * effectively own it. Calling this twice in a row is safe.
59
+ * - "owned-by-other": a different pod currently owns this user. The caller
60
+ * decides what to do next: retry and wait for that claim
61
+ * to expire, or give up and report the conflict.
62
+ */
63
+ export async function tryClaimOwnership(
64
+ mentraUserId: string,
65
+ podId: string,
66
+ ): Promise<ClaimResult> {
67
+ const redis = getRedis();
68
+ const set = await redis.set(
69
+ ownerKey(mentraUserId),
70
+ podId,
71
+ "EX",
72
+ OWNERSHIP_TTL_SEC,
73
+ "NX",
74
+ );
75
+ if (set === "OK") return "claimed";
76
+
77
+ // Failed. Was it us or someone else?
78
+ const current = await redis.get(ownerKey(mentraUserId));
79
+ if (current === podId) return "already-ours";
80
+ if (current === null) {
81
+ const retry = await redis.set(
82
+ ownerKey(mentraUserId),
83
+ podId,
84
+ "EX",
85
+ OWNERSHIP_TTL_SEC,
86
+ "NX",
87
+ );
88
+ if (retry === "OK") return "claimed";
89
+ const afterRetry = await redis.get(ownerKey(mentraUserId));
90
+ if (afterRetry === podId) return "already-ours";
91
+ }
92
+ return "owned-by-other";
93
+ }
94
+
95
+ /**
96
+ * Like `tryClaimOwnership`, but if another pod currently owns the user, keep
97
+ * retrying for a short while. This gives a crashed owner's claim time to expire
98
+ * on its own so we can then take over. The default deadline is twice the key's
99
+ * expiry, which is long enough that a dead owner's claim is always gone before
100
+ * we give up.
101
+ */
102
+ export async function claimOwnershipWithRetry(
103
+ mentraUserId: string,
104
+ podId: string,
105
+ deadlineMs = OWNERSHIP_TTL_SEC * 2 * 1000,
106
+ ): Promise<ClaimResult> {
107
+ const deadline = Date.now() + deadlineMs;
108
+ let result: ClaimResult = "owned-by-other";
109
+ while (Date.now() < deadline) {
110
+ result = await tryClaimOwnership(mentraUserId, podId);
111
+ if (result !== "owned-by-other") return result;
112
+ await Bun.sleep(500);
113
+ }
114
+ return result;
115
+ }
116
+
117
+ /**
118
+ * Reset the expiry timer on our claim, but only if we still own it. The owner
119
+ * pod calls this on a timer so its claim never expires while it is healthy.
120
+ * Returns true if the refresh worked. Returns false if some other pod has
121
+ * already taken the user over, which means we were too slow (our claim expired
122
+ * and someone grabbed it), and we should stop treating this user as ours.
123
+ */
124
+ export async function refreshOwnership(
125
+ mentraUserId: string,
126
+ podId: string,
127
+ ): Promise<boolean> {
128
+ const redis = getRedis();
129
+ const result = (await redis.eval(
130
+ REFRESH_SCRIPT,
131
+ 1,
132
+ ownerKey(mentraUserId),
133
+ podId,
134
+ String(OWNERSHIP_TTL_SEC),
135
+ )) as number;
136
+ return result === 1;
137
+ }
138
+
139
+ /**
140
+ * Give up ownership of a user, but only if we still own it. Called on a clean
141
+ * disconnect so the user can be claimed elsewhere right away instead of waiting
142
+ * for the timer to expire. If some other pod already holds the claim (ours
143
+ * expired and got grabbed), this does nothing, deleting their claim would be
144
+ * wrong.
145
+ */
146
+ export async function releaseOwnership(
147
+ mentraUserId: string,
148
+ podId: string,
149
+ ): Promise<boolean> {
150
+ const redis = getRedis();
151
+ const result = (await redis.eval(
152
+ RELEASE_SCRIPT,
153
+ 1,
154
+ ownerKey(mentraUserId),
155
+ podId,
156
+ )) as number;
157
+ return result === 1;
158
+ }
159
+
160
+ /** Read which pod currently owns this user, or null if nobody does. A plain
161
+ * read with no claiming; handy for tests and diagnostics. */
162
+ export async function getOwner(mentraUserId: string): Promise<string | null> {
163
+ return getRedis().get(ownerKey(mentraUserId));
164
+ }
165
+
166
+ // === Lua scripts ===
167
+ //
168
+ // These run inside Redis as a single atomic step. Each one reads the owner key
169
+ // and only acts if the stored pod id matches ours (KEYS[1] is the key, ARGV[1]
170
+ // is our pod id). Doing the read and the action together is what stops two pods
171
+ // from racing on the same claim.
172
+
173
+ const REFRESH_SCRIPT = `
174
+ if redis.call("GET", KEYS[1]) == ARGV[1] then
175
+ redis.call("EXPIRE", KEYS[1], ARGV[2])
176
+ return 1
177
+ else
178
+ return 0
179
+ end
180
+ `;
181
+
182
+ const RELEASE_SCRIPT = `
183
+ if redis.call("GET", KEYS[1]) == ARGV[1] then
184
+ redis.call("DEL", KEYS[1])
185
+ return 1
186
+ else
187
+ return 0
188
+ end
189
+ `;
190
+
191
+ // === Refresh loop ===
192
+
193
+ let refreshTimer: ReturnType<typeof setInterval> | null = null;
194
+
195
+ /**
196
+ * Start a background timer that keeps all of this pod's claims alive. On each
197
+ * tick it asks the caller which users this pod currently owns (via the
198
+ * `getOwnedUserIds` callback, normally the set of live WebSocket sessions) and
199
+ * refreshes each one's claim. Call this once at startup; calling it again does
200
+ * nothing, so a second call cannot create a duplicate timer.
201
+ */
202
+ export function startOwnershipRefreshLoop(opts: {
203
+ podId: string;
204
+ getOwnedUserIds: () => Iterable<string>;
205
+ onLostOwnership?: (mentraUserId: string) => void;
206
+ }): void {
207
+ if (refreshTimer) return;
208
+ refreshTimer = setInterval(async () => {
209
+ try {
210
+ for (const userId of opts.getOwnedUserIds()) {
211
+ const ok = await refreshOwnership(userId, opts.podId);
212
+ if (!ok) {
213
+ // We thought we owned this user but Redis disagrees. Could be a
214
+ // partition, could be a missed refresh that let TTL expire and
215
+ // someone else grabbed it. Either way, log; later batches will
216
+ // hand off the affected sessions cleanly.
217
+ logger.warn(
218
+ { mentraUserId: userId, podId: opts.podId },
219
+ "ownership refresh failed, claim no longer ours",
220
+ );
221
+ opts.onLostOwnership?.(userId);
222
+ }
223
+ }
224
+ } catch (err) {
225
+ logger.error({ err }, "ownership refresh loop threw");
226
+ }
227
+ }, OWNERSHIP_REFRESH_INTERVAL_MS);
228
+ }
229
+
230
+ export function stopOwnershipRefreshLoop(): void {
231
+ if (refreshTimer) {
232
+ clearInterval(refreshTimer);
233
+ refreshTimer = null;
234
+ }
235
+ }
cloud-v2/packages/runtime/src/services/session/stream.ts ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Audio Redis substrate. Owns three pieces of state in Redis:
3
+ *
4
+ * 1. **Per-user audio streams** (`{user:mentraUserId}:audio`). XADDed by any pod
5
+ * that receives a UDP packet for that user; XREADGROUPed by the owner
6
+ * pod (whichever pod holds the WS). Bounded by MAXLEN ~ retained-window.
7
+ *
8
+ * 2. **Session-tag registry** (`sessionTag:{u32}`). Maps the u32 in UDP
9
+ * packet headers to a Mentra user (and which pod owns the WS). Lets a
10
+ * pod that received a UDP packet for a session it doesn't own resolve
11
+ * "who is this for" without coordinating with the owner.
12
+ *
13
+ * 3. **Stream consumer-group name** (constant). All worker pools across
14
+ * pods join one group so XAUTOCLAIM can rebalance work after pod death.
15
+ *
16
+ * Wire-format and lifecycle decisions live in `docs/issues/003-audio/`.
17
+ */
18
+
19
+ import nacl from "tweetnacl";
20
+ import { getRedis } from "../../clients/redis.client";
21
+ import { UDP_LIVENESS_PROBE_PREFIX } from "@mentra/cloud-protocol/audio";
22
+
23
+ // === Stream constants ===
24
+
25
+ /** Per-user audio stream key. */
26
+ export function audioStreamKey(mentraUserId: string): string {
27
+ return `{user:${mentraUserId}}:audio`;
28
+ }
29
+
30
+ /** 6-byte UDP/WS audio packet header: [sessionTag:u32 BE][sequence:u16 BE]. */
31
+ export const AUDIO_PACKET_HEADER_SIZE = 6;
32
+
33
+ export interface ParsedAudioPacket {
34
+ sessionTag: number;
35
+ sequence: number;
36
+ payload: Uint8Array;
37
+ }
38
+
39
+ /**
40
+ * Parse the shared UDP/WS audio packet wire format:
41
+ * [sessionTag:u32 BE][sequence:u16 BE][lc3-payload]
42
+ *
43
+ * Returns null if the buffer is too short to contain a header.
44
+ */
45
+ export function parseAudioPacket(buf: Uint8Array): ParsedAudioPacket | null {
46
+ if (buf.byteLength < AUDIO_PACKET_HEADER_SIZE) return null;
47
+ const view = Buffer.isBuffer(buf)
48
+ ? buf
49
+ : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
50
+ return {
51
+ sessionTag: view.readUInt32BE(0),
52
+ sequence: view.readUInt16BE(4),
53
+ payload: view.subarray(AUDIO_PACKET_HEADER_SIZE),
54
+ };
55
+ }
56
+
57
+ export interface LocalSessionLookup {
58
+ mentraUserId: string;
59
+ audioSessionId: string;
60
+ /**
61
+ * The session's UDP frame key (base64). Needed to decrypt UDP frames on the
62
+ * same-pod fast path. Omitted by the WS-binary fallback path, whose frames
63
+ * are not secretbox-encrypted (they ride the TLS WebSocket).
64
+ */
65
+ encryptionKeyB64?: string;
66
+ frameTimelineVersion?: 1;
67
+ }
68
+
69
+ export interface IngestResult {
70
+ ok: boolean;
71
+ kind?: "audio" | "probe";
72
+ origin?: "local" | "redis";
73
+ mentraUserId?: string;
74
+ audioSessionId?: string;
75
+ /** Bytes written to the stream (the decrypted length for UDP frames). */
76
+ payloadLen?: number;
77
+ probeId?: string;
78
+ }
79
+
80
+ export interface IngestOptions {
81
+ /**
82
+ * Whether the payload is secretbox-encrypted. UDP frames are (the payload is
83
+ * `[nonce(24)|ciphertext]`); the WS-binary fallback is not. When true we
84
+ * decrypt with the session key and write plaintext to the stream, so the
85
+ * worker only ever sees decode-ready audio.
86
+ */
87
+ encrypted?: boolean;
88
+ }
89
+
90
+ /** secretbox (XSalsa20-Poly1305) nonce length, 24 bytes. */
91
+ const UDP_NONCE_BYTES = nacl.secretbox.nonceLength;
92
+
93
+ /**
94
+ * Decrypt a UDP frame payload `[nonce(24)|ciphertext]` with the session key.
95
+ * Returns the plaintext audio bytes, or null if the key is missing/wrong size,
96
+ * the frame is too short, or the Poly1305 tag does not verify (forged or
97
+ * corrupted packet).
98
+ */
99
+ function decryptUdpPayload(
100
+ payload: Uint8Array,
101
+ keyB64: string | undefined,
102
+ ): Uint8Array | null {
103
+ if (!keyB64) return null;
104
+ if (payload.byteLength <= UDP_NONCE_BYTES) return null;
105
+ const key = Buffer.from(keyB64, "base64");
106
+ if (key.byteLength !== nacl.secretbox.keyLength) return null;
107
+ const nonce = payload.subarray(0, UDP_NONCE_BYTES);
108
+ const ciphertext = payload.subarray(UDP_NONCE_BYTES);
109
+ return nacl.secretbox.open(ciphertext, nonce, key);
110
+ }
111
+
112
+ function decodeProbeId(payload: Uint8Array): string | null {
113
+ const prefix = UDP_LIVENESS_PROBE_PREFIX;
114
+ if (payload.byteLength <= prefix.length) return null;
115
+ for (let i = 0; i < prefix.length; i += 1) {
116
+ if (payload[i] !== prefix.charCodeAt(i)) return null;
117
+ }
118
+ let id = "";
119
+ for (let i = prefix.length; i < payload.byteLength; i += 1) {
120
+ const c = payload[i];
121
+ if (c < 0x20 || c > 0x7e) return null;
122
+ id += String.fromCharCode(c);
123
+ }
124
+ return id || null;
125
+ }
126
+
127
+ /**
128
+ * Resolve a sessionTag → user (local map first, Redis fallback), then XADD
129
+ * the packet to the user's audio stream. Shared by both ingress paths:
130
+ *
131
+ * - UDP ingress (`udp-ingress.service.ts`)
132
+ * - WS-binary fallback (`session.service.ts` message handler)
133
+ *
134
+ * Returns `{ ok: false }` when the sessionTag is unknown — typical when a
135
+ * packet arrives just before/after the session's lifetime, not an error.
136
+ *
137
+ * `localLookup` is the same-pod fast path: a callback the caller provides
138
+ * that consults the in-process session map. We accept a callback (rather
139
+ * than importing session.service directly) to keep the dependency direction
140
+ * one-way and avoid a circular import.
141
+ */
142
+ export async function ingestAudioPacket(
143
+ packet: ParsedAudioPacket,
144
+ localLookup: (tag: number) => LocalSessionLookup | undefined,
145
+ opts: IngestOptions = {},
146
+ ): Promise<IngestResult> {
147
+ let mentraUserId: string;
148
+ let audioSessionId: string;
149
+ let encryptionKeyB64: string | undefined;
150
+ let origin: "local" | "redis";
151
+ let frameTimelineVersion: 1 | undefined;
152
+
153
+ const local = localLookup(packet.sessionTag);
154
+ if (local) {
155
+ mentraUserId = local.mentraUserId;
156
+ audioSessionId = local.audioSessionId;
157
+ encryptionKeyB64 = local.encryptionKeyB64;
158
+ frameTimelineVersion = local.frameTimelineVersion;
159
+ origin = "local";
160
+ } else {
161
+ const remote = await lookupSessionTagInRedis(packet.sessionTag);
162
+ if (!remote) return { ok: false };
163
+ mentraUserId = remote.mentraUserId;
164
+ audioSessionId = remote.audioSessionId;
165
+ encryptionKeyB64 = remote.encryptionKeyB64;
166
+ frameTimelineVersion = remote.frameTimelineVersion;
167
+ origin = "redis";
168
+ }
169
+
170
+ // UDP frames are encrypted; decrypt before the stream so the worker only sees
171
+ // plaintext. A frame that fails the Poly1305 tag check (forged, corrupted, or
172
+ // wrong key) is dropped rather than stored.
173
+ let payload = packet.payload;
174
+ if (opts.encrypted) {
175
+ const plaintext = decryptUdpPayload(payload, encryptionKeyB64);
176
+ if (!plaintext) return { ok: false, origin, mentraUserId };
177
+ payload = plaintext;
178
+ }
179
+
180
+ const probeId = opts.encrypted ? decodeProbeId(payload) : null;
181
+ if (probeId) {
182
+ return {
183
+ ok: true,
184
+ kind: "probe",
185
+ origin,
186
+ mentraUserId,
187
+ audioSessionId,
188
+ payloadLen: payload.byteLength,
189
+ probeId,
190
+ };
191
+ }
192
+
193
+ let offsetMs: number | undefined;
194
+ if (frameTimelineVersion === 1) {
195
+ if (payload.byteLength < 8) return { ok: false, origin, mentraUserId };
196
+ offsetMs = new DataView(
197
+ payload.buffer,
198
+ payload.byteOffset,
199
+ payload.byteLength,
200
+ ).getFloat64(0, false);
201
+ if (!Number.isFinite(offsetMs) || offsetMs < 0)
202
+ return { ok: false, origin, mentraUserId };
203
+ payload = payload.subarray(8);
204
+ }
205
+ await appendAudioPacket(mentraUserId, {
206
+ seq: packet.sequence,
207
+ payload,
208
+ sessionTag: packet.sessionTag,
209
+ audioSessionId,
210
+ offsetMs,
211
+ });
212
+
213
+ return {
214
+ ok: true,
215
+ kind: "audio",
216
+ origin,
217
+ mentraUserId,
218
+ audioSessionId,
219
+ payloadLen: payload.byteLength,
220
+ };
221
+ }
222
+
223
+ /**
224
+ * Stream length cap. ~10 seconds at typical packet rates (≈100 pkt/s).
225
+ * The `~` (approximate) trimming lets Redis trim in efficient bulk —
226
+ * MAXLEN is enforced only loosely.
227
+ */
228
+ export const AUDIO_STREAM_MAXLEN = 1000;
229
+
230
+ /** Consumer group all worker dispatch loops join. Created lazily on first read. */
231
+ export const AUDIO_STREAM_GROUP = "audio-workers";
232
+
233
+ // === Stream operations ===
234
+
235
+ export interface AudioPacket {
236
+ seq: number;
237
+ /** The raw audio payload (LC3 frames or PCM bytes). */
238
+ payload: Uint8Array;
239
+ /** Useful for tracing — which u32 tag generated this entry. */
240
+ sessionTag: number;
241
+ /** Useful for tracing — which audio-session this entry belongs to. */
242
+ audioSessionId: string;
243
+ offsetMs?: number;
244
+ }
245
+
246
+ /**
247
+ * XADD an audio packet to a user's stream. Idempotent in the sense that
248
+ * "same user, different sequence" produces distinct entries; we do not
249
+ * de-dupe on `seq` (the producer is responsible for monotonicity).
250
+ *
251
+ * Payload is base64-encoded on write — ioredis returns stream values as
252
+ * strings by default, which corrupts binary bytes outside ASCII via UTF-8
253
+ * decoding. Base64 is binary-safe at the cost of ~33% storage overhead.
254
+ * Workers `Buffer.from(payload, "base64")` to recover the original bytes.
255
+ *
256
+ * Returns the Redis-assigned stream entry ID (`<ms>-<seq>`).
257
+ */
258
+ export async function appendAudioPacket(
259
+ mentraUserId: string,
260
+ packet: AudioPacket,
261
+ ): Promise<string> {
262
+ const redis = getRedis();
263
+ const id = await redis.xadd(
264
+ audioStreamKey(mentraUserId),
265
+ "MAXLEN",
266
+ "~",
267
+ String(AUDIO_STREAM_MAXLEN),
268
+ "*",
269
+ "seq",
270
+ String(packet.seq),
271
+ "sessionTag",
272
+ String(packet.sessionTag),
273
+ "audioSessionId",
274
+ packet.audioSessionId,
275
+ "offsetMs",
276
+ packet.offsetMs === undefined ? "" : String(packet.offsetMs),
277
+ "payload",
278
+ Buffer.from(packet.payload).toString("base64"),
279
+ );
280
+ return id ?? "";
281
+ }
282
+
283
+ // === Session-tag registry ===
284
+
285
+ /**
286
+ * How long a sessionTag registration is valid in Redis without a refresh.
287
+ * Owners refresh on a timer (well inside the TTL) and on clean WS close
288
+ * delete the key outright. The TTL is the recovery guarantee — if a pod
289
+ * crashes without releasing, abandoned tag mappings vanish within this
290
+ * window so the next reconnect's mapping can take over.
291
+ */
292
+ export const SESSION_TAG_TTL_SEC = 60;
293
+
294
+ /** Owner refreshes at this cadence — well inside the TTL. */
295
+ export const SESSION_TAG_REFRESH_INTERVAL_MS = 20_000;
296
+
297
+ export interface SessionTagRecord {
298
+ mentraUserId: string;
299
+ tenantId: string;
300
+ audioSessionId: string;
301
+ authSessionId: string;
302
+ /** Which pod's WebSocket owns this session. Used by dispatch later. */
303
+ podId: string;
304
+ /**
305
+ * The session's audio frame encryption key (base64). Carried so a UDP packet
306
+ * that lands on any pod can fetch this session's key by sessionTag and
307
+ * decrypt the frame.
308
+ */
309
+ encryptionKeyB64: string;
310
+ frameTimelineVersion?: 1;
311
+ }
312
+
313
+ /** Set before ACK; remote UDP ingress must decode the same format as local ingress. */
314
+ export async function enableSessionFrameTimeline(
315
+ tag: number,
316
+ audioSessionId: string,
317
+ ): Promise<void> {
318
+ const redis = getRedis();
319
+ const raw = await redis.get(sessionTagKey(tag));
320
+ if (!raw) throw new Error("audio session tag expired before init");
321
+ const record = JSON.parse(raw) as SessionTagRecord;
322
+ if (record.audioSessionId !== audioSessionId)
323
+ throw new Error("audio session tag replaced before init");
324
+ record.frameTimelineVersion = 1;
325
+ const result = await redis.set(
326
+ sessionTagKey(tag),
327
+ JSON.stringify(record),
328
+ "EX",
329
+ SESSION_TAG_TTL_SEC,
330
+ "XX",
331
+ );
332
+ if (result !== "OK") throw new Error("audio session tag expired during init");
333
+ }
334
+
335
+ function sessionTagKey(tag: number): string {
336
+ return `sessionTag:${tag}`;
337
+ }
338
+
339
+ export async function registerSessionTag(
340
+ tag: number,
341
+ record: SessionTagRecord,
342
+ ): Promise<boolean> {
343
+ const redis = getRedis();
344
+ const result = await redis.set(
345
+ sessionTagKey(tag),
346
+ JSON.stringify(record),
347
+ "EX",
348
+ SESSION_TAG_TTL_SEC,
349
+ "NX",
350
+ );
351
+ return result === "OK";
352
+ }
353
+
354
+ export async function refreshSessionTag(tag: number): Promise<void> {
355
+ const redis = getRedis();
356
+ await redis.expire(sessionTagKey(tag), SESSION_TAG_TTL_SEC);
357
+ }
358
+
359
+ export async function unregisterSessionTag(tag: number): Promise<void> {
360
+ const redis = getRedis();
361
+ await redis.del(sessionTagKey(tag));
362
+ }
363
+
364
+ /** Returns null if the tag is unknown or has TTL'd out. */
365
+ export async function lookupSessionTagInRedis(
366
+ tag: number,
367
+ ): Promise<SessionTagRecord | null> {
368
+ const redis = getRedis();
369
+ const raw = await redis.get(sessionTagKey(tag));
370
+ if (!raw) return null;
371
+ try {
372
+ return JSON.parse(raw) as SessionTagRecord;
373
+ } catch {
374
+ return null;
375
+ }
376
+ }
cloud-v2/packages/runtime/src/services/session/subscriptions-store.ts ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Subscription source of truth in Redis.
3
+ *
4
+ * The authoritative audio subscription set for a user lives in one Redis key,
5
+ * `{user:X}:subscriptions`. It holds the full subscription set plus the last
6
+ * accepted `sessionId` and `version`. The hash tag `{user:X}` matches the
7
+ * ownership key (`{user:X}:owner`) and the control stream (`{user:X}:control`)
8
+ * so all of one user's keys land on the same Redis Cluster shard.
9
+ *
10
+ * Why a single guarded key instead of applying REST writes directly to a
11
+ * worker: the legacy system had two scars this design closes.
12
+ * 1. Out-of-order application. A retried or reordered REST write could apply
13
+ * an older snapshot on top of a newer one. The monotonic `version` guard
14
+ * discards anything not strictly newer than what we already accepted.
15
+ * 2. A reconnect's empty snapshot wiping a live set. After reconnect the
16
+ * client briefly has an empty set; if that landed late it could clear a
17
+ * newer, populated set. Because an empty set must still carry a newer
18
+ * version for the current session to be accepted, a stale empty can never
19
+ * win against a live set.
20
+ *
21
+ * The key is also the source of truth the owning worker reconciles from. REST
22
+ * writes additionally drop a nudge into the control stream (see
23
+ * `control-stream.ts`); the worker reads that nudge and then re-reads THIS key,
24
+ * never trusting the nudge payload alone. That keeps a single source of truth
25
+ * and avoids the derived-cache drift the legacy system suffered.
26
+ */
27
+
28
+ import { getRedis } from "../../clients/redis.client";
29
+ import type { AudioSubscription } from "@mentra/cloud-protocol/audio";
30
+
31
+ /**
32
+ * Subscription key TTL. Refreshed by the owner while the session is live and
33
+ * deleted on clean disconnect. The TTL is the backstop: if a pod crashes
34
+ * without releasing, the abandoned set vanishes within this window so a later
35
+ * session for the same user starts clean rather than inheriting stale subs.
36
+ */
37
+ export const SUBSCRIPTIONS_TTL_SEC = 60;
38
+
39
+ /** What the subscription key holds, decoded. */
40
+ export interface SubscriptionRecord {
41
+ subscriptions: AudioSubscription[];
42
+ /** The session that last wrote this set (from `connection.ack.sessionId`). */
43
+ sessionId: string;
44
+ /** Monotonic per snapshot. A write must be strictly newer to be accepted. */
45
+ version: number;
46
+ }
47
+
48
+ /** Outcome of a guarded write. */
49
+ export interface WriteResult {
50
+ applied: boolean;
51
+ /** The version now in effect (the accepted one, or the existing one if rejected). */
52
+ version: number;
53
+ /** Present when `applied` is false: why the write was rejected. */
54
+ reason?: "stale-session" | "stale-version";
55
+ /**
56
+ * Present when rejected with "stale-session": the sessionId currently
57
+ * holding the key. The caller can check whether that session is actually
58
+ * alive and take over a dead session's record (see audio.api.ts).
59
+ */
60
+ currentSessionId?: string;
61
+ }
62
+
63
+ function subscriptionsKey(mentraUserId: string): string {
64
+ return `{user:${mentraUserId}}:subscriptions`;
65
+ }
66
+
67
+ /** Read the current subscription record, or null if none exists yet. */
68
+ export async function readSubscriptions(
69
+ mentraUserId: string,
70
+ ): Promise<SubscriptionRecord | null> {
71
+ const raw = await getRedis().get(subscriptionsKey(mentraUserId));
72
+ if (!raw) return null;
73
+ try {
74
+ return JSON.parse(raw) as SubscriptionRecord;
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Seed the key for a brand-new session without clobbering a live session. Called from
82
+ * `connection.init` so the initial subscription set is in place before any
83
+ * audio flows. A fresh handshake establishes a new `sessionId` baseline at
84
+ * `version` 0; subsequent REST writes for that session are then guarded
85
+ * against it by `writeSubscriptions`.
86
+ *
87
+ * If another live socket already seeded the user's key, this returns false
88
+ * rather than replacing that socket's session guard. The existing key TTL is
89
+ * refreshed by the owner and removed on clean last-session close.
90
+ */
91
+ export async function seedSubscriptions(
92
+ mentraUserId: string,
93
+ record: SubscriptionRecord,
94
+ ): Promise<boolean> {
95
+ const applied = (await getRedis().eval(
96
+ SEED_SCRIPT,
97
+ 1,
98
+ subscriptionsKey(mentraUserId),
99
+ JSON.stringify(record),
100
+ SUBSCRIPTIONS_TTL_SEC,
101
+ record.sessionId,
102
+ )) as number;
103
+ return applied === 1;
104
+ }
105
+
106
+ /**
107
+ * Guarded write of a full subscription snapshot, used by the REST endpoint.
108
+ *
109
+ * The read-check-write runs as one atomic Lua step so two concurrent REST
110
+ * writes (retry plus original, two pods) cannot interleave and accept an older
111
+ * snapshot. The guard rejects a write whose `sessionId` is not the current
112
+ * session, and any write whose `version` is not strictly greater than the last
113
+ * accepted version. An empty subscription set is just a normal snapshot under
114
+ * these rules: it is honored only when it is the newest version for the current
115
+ * session, so a stale empty can never wipe a live set.
116
+ *
117
+ * If no record exists yet (the seed somehow never ran, e.g. a write racing
118
+ * ahead of `connection.init`), the write is accepted and establishes the
119
+ * baseline, so a subscription change is never silently lost.
120
+ */
121
+ export async function writeSubscriptions(
122
+ mentraUserId: string,
123
+ record: SubscriptionRecord,
124
+ ): Promise<WriteResult> {
125
+ const result = (await getRedis().eval(
126
+ WRITE_SCRIPT,
127
+ 1,
128
+ subscriptionsKey(mentraUserId),
129
+ JSON.stringify(record.subscriptions),
130
+ record.sessionId,
131
+ String(record.version),
132
+ String(SUBSCRIPTIONS_TTL_SEC),
133
+ )) as [number, string, number, string?];
134
+
135
+ const [appliedFlag, reason, effectiveVersion, currentSessionId] = result;
136
+ if (appliedFlag === 1) {
137
+ return { applied: true, version: effectiveVersion };
138
+ }
139
+ return {
140
+ applied: false,
141
+ version: effectiveVersion,
142
+ reason: reason === "stale-session" ? "stale-session" : "stale-version",
143
+ ...(currentSessionId ? { currentSessionId } : {}),
144
+ };
145
+ }
146
+
147
+ /**
148
+ * Unconditional snapshot write that REPLACES whatever record exists. Reserved
149
+ * for taking over a DEAD session's record: the caller must have verified that
150
+ * the record's sessionId no longer corresponds to a live socket (and that this
151
+ * pod owns the user) before forcing. Establishes a fresh version baseline.
152
+ */
153
+ export async function takeoverSubscriptions(
154
+ mentraUserId: string,
155
+ record: SubscriptionRecord,
156
+ ): Promise<void> {
157
+ await getRedis().set(
158
+ subscriptionsKey(mentraUserId),
159
+ JSON.stringify(record),
160
+ "EX",
161
+ SUBSCRIPTIONS_TTL_SEC,
162
+ );
163
+ }
164
+
165
+ /**
166
+ * Refresh the key's TTL — but only when the record still belongs to the
167
+ * refreshing session. An unconditional refresh would let ANY open socket for
168
+ * the user keep a DEAD session's record alive forever (each reconnect's
169
+ * refresh loop re-arms the TTL), permanently wedging seeding and REST writes
170
+ * behind a session that no longer exists. Session-scoped refresh restores the
171
+ * TTL's role as the dead-record backstop: a record whose session is gone
172
+ * expires within {@link SUBSCRIPTIONS_TTL_SEC}.
173
+ */
174
+ export async function refreshSubscriptions(
175
+ mentraUserId: string,
176
+ sessionId: string,
177
+ ): Promise<void> {
178
+ await getRedis().eval(
179
+ REFRESH_IF_SESSION_SCRIPT,
180
+ 1,
181
+ subscriptionsKey(mentraUserId),
182
+ sessionId,
183
+ String(SUBSCRIPTIONS_TTL_SEC),
184
+ );
185
+ }
186
+
187
+ /** Delete the key on clean disconnect so the next session starts fresh. */
188
+ export async function deleteSubscriptions(mentraUserId: string): Promise<void> {
189
+ await getRedis().del(subscriptionsKey(mentraUserId));
190
+ }
191
+
192
+ /**
193
+ * Delete the key only if it is still owned by one of the given sessions.
194
+ * Used when a pod loses user ownership: its sessions are being torn down, but
195
+ * the new owner may have already seeded this key for a NEWER session — an
196
+ * unconditional delete from the stale pod would wipe the live owner's
197
+ * subscription state cluster-wide. Returns true when the key was deleted.
198
+ */
199
+ export async function deleteSubscriptionsIfSessionIn(
200
+ mentraUserId: string,
201
+ sessionIds: string[],
202
+ ): Promise<boolean> {
203
+ if (sessionIds.length === 0) return false;
204
+ const deleted = (await getRedis().eval(
205
+ DELETE_IF_SESSION_SCRIPT,
206
+ 1,
207
+ subscriptionsKey(mentraUserId),
208
+ JSON.stringify(sessionIds),
209
+ )) as number;
210
+ return deleted === 1;
211
+ }
212
+
213
+ // === Lua ===
214
+ //
215
+ // Atomic guarded write. KEYS[1] is the subscription key. ARGV: [1] the new
216
+ // subscription set as JSON, [2] the writer's sessionId, [3] the new version,
217
+ // [4] the TTL in seconds. Returns a 3-tuple [applied, reason, version]:
218
+ // - applied: 1 if written, 0 if rejected
219
+ // - reason: "" when applied; "stale-session" or "stale-version" when not
220
+ // - version: the version now in effect (the new one if applied, else the
221
+ // existing one) so the caller can echo the authoritative version
222
+ // back to the client.
223
+ //
224
+ // We store the record as a JSON object so a single GET in the read path
225
+ // recovers everything. The Lua decodes only the two scalar guard fields it
226
+ // needs (sessionId, version) and rewrites the whole object on accept.
227
+ const WRITE_SCRIPT = `
228
+ local existing = redis.call("GET", KEYS[1])
229
+ local newSubs = ARGV[1]
230
+ local newSession = ARGV[2]
231
+ local newVersion = tonumber(ARGV[3])
232
+ local ttl = ARGV[4]
233
+
234
+ if existing then
235
+ local decoded = cjson.decode(existing)
236
+ if decoded.sessionId ~= newSession then
237
+ return {0, "stale-session", decoded.version, decoded.sessionId}
238
+ end
239
+ if newVersion <= decoded.version then
240
+ return {0, "stale-version", decoded.version}
241
+ end
242
+ end
243
+
244
+ local record = string.format(
245
+ '{"subscriptions":%s,"sessionId":%s,"version":%d}',
246
+ newSubs, cjson.encode(newSession), newVersion
247
+ )
248
+ redis.call("SET", KEYS[1], record, "EX", ttl)
249
+ return {1, "", newVersion}
250
+ `;
251
+
252
+ // Conditional delete. ARGV[1] is a JSON array of sessionIds being torn down;
253
+ // the key is removed only when its record's sessionId is one of them.
254
+ const DELETE_IF_SESSION_SCRIPT = `
255
+ local existing = redis.call("GET", KEYS[1])
256
+ if not existing then
257
+ return 0
258
+ end
259
+ local decoded = cjson.decode(existing)
260
+ local sessions = cjson.decode(ARGV[1])
261
+ for _, id in ipairs(sessions) do
262
+ if decoded.sessionId == id then
263
+ redis.call("DEL", KEYS[1])
264
+ return 1
265
+ end
266
+ end
267
+ return 0
268
+ `;
269
+
270
+ // Conditional TTL refresh. ARGV: [1] the refreshing session's id, [2] TTL
271
+ // seconds. Only re-arms the TTL when the record still belongs to that session.
272
+ const REFRESH_IF_SESSION_SCRIPT = `
273
+ local existing = redis.call("GET", KEYS[1])
274
+ if not existing then
275
+ return 0
276
+ end
277
+ local decoded = cjson.decode(existing)
278
+ if decoded.sessionId ~= ARGV[1] then
279
+ return 0
280
+ end
281
+ redis.call("EXPIRE", KEYS[1], ARGV[2])
282
+ return 1
283
+ `;
284
+
285
+ const SEED_SCRIPT = `
286
+ local existing = redis.call("GET", KEYS[1])
287
+ local record = ARGV[1]
288
+ local ttl = ARGV[2]
289
+ local newSession = ARGV[3]
290
+
291
+ if existing then
292
+ local decoded = cjson.decode(existing)
293
+ if decoded.sessionId ~= newSession then
294
+ return 0
295
+ end
296
+ end
297
+
298
+ redis.call("SET", KEYS[1], record, "EX", ttl)
299
+ return 1
300
+ `;
cloud-v2/packages/runtime/src/services/session/subscriptions.ts ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Shared audio types used across services + workers.
3
+ *
4
+ * The canonical subscription/result types and their zod schemas live in
5
+ * `protocol/audio.ts` (the isomorphic `@mentra/cloud-runtime/protocol`
6
+ * entrypoint). This module re-exports the subscription types and adds the
7
+ * server-side `subscriptionKey()` canonicalization used for structural
8
+ * equality + Map keys.
9
+ *
10
+ * Per the design (docs/issues/002-cloud-runtime/audio/spec.md "Subscription
11
+ * model"): "Phone aggregates and dedupes across local miniapps; sends a flat
12
+ * list to cloud on every (re)connect. Identity is structural."
13
+ */
14
+ export type {
15
+ LanguageSource,
16
+ TranscriptionSubscription,
17
+ TranslationSubscription,
18
+ AudioSubscription,
19
+ } from "@mentra/cloud-protocol/audio";
20
+
21
+ import type { AudioSubscription, LanguageSource } from "@mentra/cloud-protocol/audio";
22
+
23
+ /**
24
+ * Stable string key for a subscription, used for equality + Map keys.
25
+ * Canonicalizes `hints` ordering so two subs with the same hints in
26
+ * different array orders compare equal.
27
+ */
28
+ export function subscriptionKey(sub: AudioSubscription): string {
29
+ if (sub.kind === "transcription") {
30
+ return `t:${languageKey(sub.language)}`;
31
+ }
32
+ return `x:${languageKey(sub.source)}>${sub.target}`;
33
+ }
34
+
35
+ function languageKey(lang: LanguageSource): string {
36
+ if (lang.mode === "specific") return `s:${lang.code}`;
37
+ const hints = lang.hints ? [...lang.hints].sort().join(",") : "";
38
+ return `a:${hints}`;
39
+ }
40
+
41
+ // WS inbound message envelopes (the v1 phone wire contract:
42
+ // `phone_subscription_update`, `ping`) live in `wire/phone-protocol.ts`,
43
+ // which translates them into the `AudioSubscription` shape above.
cloud-v2/packages/runtime/src/services/storage/providers/local.provider.ts ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Local-fs storage provider.
3
+ *
4
+ * Stores blobs in a temp directory and lets the runtime serve them itself: the
5
+ * presigned upload/download URLs point back at the runtime's own
6
+ * `/api/camera/blob/:key` endpoints (see api/camera.api.ts). Because the runtime
7
+ * is the upload endpoint, it knows the instant an upload lands, so there is no
8
+ * polling or webhook for completion.
9
+ *
10
+ * This is the default provider: local dev, CI, and a worked example of a custom
11
+ * implementation, with no third-party dependency. Production points
12
+ * `STORAGE_PROVIDER` at r2/s3 instead.
13
+ */
14
+
15
+ import { mkdir, readFile, writeFile, unlink, stat } from "node:fs/promises";
16
+ import { dirname, join } from "node:path";
17
+ import { tmpdir } from "node:os";
18
+ import type {
19
+ PresignedUpload,
20
+ PresignOptions,
21
+ StorageProvider,
22
+ StoredObject,
23
+ } from "../storage.service";
24
+
25
+ /** Where blobs live on disk. Override with CAMERA_LOCAL_DIR. */
26
+ const BLOB_DIR = process.env.CAMERA_LOCAL_DIR ?? join(tmpdir(), "mentra-camera-blobs");
27
+
28
+ /** The runtime path that serves local blobs. Kept in sync with camera.api.ts. */
29
+ const BLOB_ROUTE = "/api/camera/blob";
30
+
31
+ /** A tiny per-key content-type sidecar so `get` can return the right type. */
32
+ function paths(key: string): { blob: string; meta: string } {
33
+ const safe = key.replace(/\.\.(\/|\\)/g, ""); // defense-in-depth against traversal
34
+ const blob = join(BLOB_DIR, safe);
35
+ return { blob, meta: `${blob}.type` };
36
+ }
37
+
38
+ export function createLocalProvider(): StorageProvider {
39
+ return {
40
+ name: "local",
41
+ servesBytes: true,
42
+
43
+ async presignUpload(key: string, opts: PresignOptions): Promise<PresignedUpload> {
44
+ // No real signature: the local endpoints are unauthenticated dev URLs.
45
+ // The origin makes the URL absolute so a device (or a test) can PUT to it.
46
+ const base = opts.origin ?? "";
47
+ return {
48
+ url: `${base}${BLOB_ROUTE}/${key}`,
49
+ method: "PUT",
50
+ headers: opts.contentType ? { "Content-Type": opts.contentType } : undefined,
51
+ };
52
+ },
53
+
54
+ async presignDownload(key: string, opts?: PresignOptions): Promise<string> {
55
+ const base = opts?.origin ?? "";
56
+ return `${base}${BLOB_ROUTE}/${key}`;
57
+ },
58
+
59
+ async exists(key: string): Promise<boolean> {
60
+ try {
61
+ await stat(paths(key).blob);
62
+ return true;
63
+ } catch {
64
+ return false;
65
+ }
66
+ },
67
+
68
+ async delete(key: string): Promise<void> {
69
+ const { blob, meta } = paths(key);
70
+ await unlink(blob).catch(() => undefined);
71
+ await unlink(meta).catch(() => undefined);
72
+ },
73
+
74
+ async put(key: string, bytes: Uint8Array, contentType: string): Promise<void> {
75
+ const { blob, meta } = paths(key);
76
+ await mkdir(dirname(blob), { recursive: true });
77
+ await writeFile(blob, bytes);
78
+ await writeFile(meta, contentType);
79
+ },
80
+
81
+ async get(key: string): Promise<StoredObject | null> {
82
+ const { blob, meta } = paths(key);
83
+ try {
84
+ const bytes = await readFile(blob);
85
+ const contentType = await readFile(meta, "utf8").catch(
86
+ () => "application/octet-stream",
87
+ );
88
+ return { bytes: new Uint8Array(bytes), contentType };
89
+ } catch {
90
+ return null;
91
+ }
92
+ },
93
+ };
94
+ }
cloud-v2/packages/runtime/src/services/storage/providers/s3.provider.ts ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview S3-compatible storage provider (Cloudflare R2 and friends).
3
+ *
4
+ * Backed by Bun's native S3 client, so it needs no third-party SDK. The same
5
+ * client targets any S3-compatible store by endpoint + credentials: Cloudflare
6
+ * R2 (the default target), AWS S3, MinIO, and Alibaba OSS's S3-compatible
7
+ * endpoint (config-only, not separately validated yet).
8
+ *
9
+ * The byte path does NOT pass through the runtime: the device PUTs straight to
10
+ * the presigned upload URL and reads from the presigned download URL. The
11
+ * runtime learns an upload completed from the provider's object-created event,
12
+ * delivered to the camera storage webhook (see api/camera.api.ts); this provider
13
+ * only mints presigned URLs and does object existence/delete.
14
+ *
15
+ * Config (env), with R2_* fallbacks for the common case:
16
+ * STORAGE_S3_ENDPOINT (e.g. https://<account>.r2.cloudflarestorage.com)
17
+ * STORAGE_S3_BUCKET
18
+ * STORAGE_S3_ACCESS_KEY_ID
19
+ * STORAGE_S3_SECRET_ACCESS_KEY
20
+ * STORAGE_S3_REGION (default "auto", which R2 expects)
21
+ */
22
+
23
+ import type {
24
+ PresignedUpload,
25
+ PresignOptions,
26
+ StorageProvider,
27
+ } from "../storage.service";
28
+
29
+ /** Presigned URL lifetime. Long enough for a glasses upload, short enough to limit replay. */
30
+ const PRESIGN_EXPIRES_SEC = 600;
31
+
32
+ /** First defined value among the given env var names. */
33
+ function env(...names: string[]): string | undefined {
34
+ for (const name of names) {
35
+ if (process.env[name]) return process.env[name];
36
+ }
37
+ return undefined;
38
+ }
39
+
40
+ export function createS3Provider(): StorageProvider {
41
+ // Accept the v2 STORAGE_S3_* names, plus R2_* and the v1 CLOUDFLARE_R2_*
42
+ // names, so existing Cloudflare R2 credentials work without re-keying.
43
+ const endpoint = env("STORAGE_S3_ENDPOINT", "R2_ENDPOINT", "CLOUDFLARE_R2_S3_ENDPOINT");
44
+ const bucket = env("STORAGE_S3_BUCKET", "R2_BUCKET", "CLOUDFLARE_R2_GALLERY_BUCKET");
45
+ const accessKeyId = env("STORAGE_S3_ACCESS_KEY_ID", "R2_ACCESS_KEY_ID", "CLOUDFLARE_R2_ACCESS_KEY_ID");
46
+ const secretAccessKey = env(
47
+ "STORAGE_S3_SECRET_ACCESS_KEY",
48
+ "R2_SECRET_ACCESS_KEY",
49
+ "CLOUDFLARE_R2_SECRET_ACCESS_KEY",
50
+ );
51
+ const region = env("STORAGE_S3_REGION") ?? "auto";
52
+
53
+ if (!endpoint || !bucket || !accessKeyId || !secretAccessKey) {
54
+ throw new Error(
55
+ "STORAGE_PROVIDER=r2/s3 requires STORAGE_S3_ENDPOINT, STORAGE_S3_BUCKET, " +
56
+ "STORAGE_S3_ACCESS_KEY_ID, and STORAGE_S3_SECRET_ACCESS_KEY (R2_* fallbacks accepted).",
57
+ );
58
+ }
59
+
60
+ const client = new Bun.S3Client({
61
+ endpoint,
62
+ bucket,
63
+ accessKeyId,
64
+ secretAccessKey,
65
+ region,
66
+ });
67
+
68
+ return {
69
+ name: "s3",
70
+ servesBytes: false,
71
+
72
+ async presignUpload(key: string, opts: PresignOptions): Promise<PresignedUpload> {
73
+ const url = client.presign(key, {
74
+ method: "PUT",
75
+ expiresIn: PRESIGN_EXPIRES_SEC,
76
+ type: opts.contentType,
77
+ });
78
+ return {
79
+ url,
80
+ method: "PUT",
81
+ headers: opts.contentType ? { "Content-Type": opts.contentType } : undefined,
82
+ };
83
+ },
84
+
85
+ async presignDownload(key: string): Promise<string> {
86
+ return client.presign(key, { method: "GET", expiresIn: PRESIGN_EXPIRES_SEC });
87
+ },
88
+
89
+ async exists(key: string): Promise<boolean> {
90
+ return await client.exists(key);
91
+ },
92
+
93
+ async delete(key: string): Promise<void> {
94
+ await client.delete(key);
95
+ },
96
+ };
97
+ }
cloud-v2/packages/runtime/src/services/storage/storage.service.ts ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Blob storage abstraction for the runtime.
3
+ *
4
+ * A thin wrapper over swappable blob providers (Cloudflare R2, a local-fs dev
5
+ * provider, and the same S3 client points at Alibaba OSS / AWS / MinIO by
6
+ * config). Services use this instead of talking to a provider directly, so the
7
+ * camera service (and later miniapp bundles, if the runtime ever stores them)
8
+ * is provider-agnostic.
9
+ *
10
+ * Mirrors the provider-wrapper pattern in Cloud Core's storage-service, but
11
+ * instantiated within Mentra Runtime Services because the runtime is
12
+ * self-hostable: a self-hosted runtime points at the OEM's own blob config,
13
+ * independent of Cloud Core's instance.
14
+ *
15
+ * Provider is chosen by `STORAGE_PROVIDER`:
16
+ * - "local" (default): real temp-fs storage; the runtime serves the bytes
17
+ * itself (presigned URLs point at its own /api/camera/blob endpoints). For
18
+ * local dev, CI, and as the reference for a custom implementation, with no
19
+ * third-party dependency.
20
+ * - "r2" / "s3": Cloudflare R2 (or any S3-compatible store, including Alibaba
21
+ * OSS's S3 endpoint) via Bun's native S3 client. The byte path goes straight
22
+ * to the provider; completion arrives via the event webhook.
23
+ *
24
+ * See docs/issues/002-cloud-runtime/camera/spec.md and
25
+ * docs/issues/001-cloud-core/storage-service/.
26
+ */
27
+
28
+ import { createLocalProvider } from "./providers/local.provider";
29
+ import { createS3Provider } from "./providers/s3.provider";
30
+
31
+ /** A presigned upload target the caller hands to the device. */
32
+ export interface PresignedUpload {
33
+ url: string;
34
+ method: "PUT";
35
+ /** Headers the uploader must send (for example a fixed Content-Type). */
36
+ headers?: Record<string, string>;
37
+ }
38
+
39
+ export interface PresignOptions {
40
+ /** MIME type the upload will carry, fixed into the signature when relevant. */
41
+ contentType?: string;
42
+ /**
43
+ * The request origin (scheme + host), used by the local provider to build
44
+ * absolute URLs pointing back at this runtime. Ignored by remote providers,
45
+ * whose URLs are absolute provider URLs.
46
+ */
47
+ origin?: string;
48
+ }
49
+
50
+ /** Bytes plus their content type, returned by the local provider's `get`. */
51
+ export interface StoredObject {
52
+ bytes: Uint8Array;
53
+ contentType: string;
54
+ }
55
+
56
+ /**
57
+ * The provider contract. `put` / `get` are implemented only by the local
58
+ * provider (which serves its own bytes); remote providers leave them undefined
59
+ * because their byte path does not pass through the runtime.
60
+ */
61
+ export interface StorageProvider {
62
+ readonly name: string;
63
+ presignUpload(key: string, opts: PresignOptions): Promise<PresignedUpload>;
64
+ presignDownload(key: string, opts?: PresignOptions): Promise<string>;
65
+ exists(key: string): Promise<boolean>;
66
+ delete(key: string): Promise<void>;
67
+ /** True when the runtime serves this provider's bytes (the local provider). */
68
+ readonly servesBytes: boolean;
69
+ put?(key: string, bytes: Uint8Array, contentType: string): Promise<void>;
70
+ get?(key: string): Promise<StoredObject | null>;
71
+ }
72
+
73
+ let provider: StorageProvider | null = null;
74
+
75
+ /** The configured storage provider (built once per process). */
76
+ export function getStorageProvider(): StorageProvider {
77
+ if (provider) return provider;
78
+ const kind = process.env.STORAGE_PROVIDER ?? "local";
79
+ provider = kind === "r2" || kind === "s3" ? createS3Provider() : createLocalProvider();
80
+ return provider;
81
+ }
82
+
83
+ /** Test/boot hook: reset the cached provider (for example to switch config). */
84
+ export function resetStorageProvider(): void {
85
+ provider = null;
86
+ }
cloud-v2/packages/runtime/src/services/stream/providers/cloudflare-stream.provider.ts ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Cloudflare Stream provider (real live-input provisioning).
3
+ *
4
+ * Provisions a Cloudflare Stream live input over the Cloudflare API and returns
5
+ * its ingest (RTMPS + SRT + WebRTC/WHIP) and HLS/DASH playback coordinates.
6
+ * No SDK: a couple of authed fetch calls.
7
+ *
8
+ * All three ingest protocols are surfaced because real networks differ: office
9
+ * firewalls commonly kill RTMPS:443 mid-handshake while SRT passes, and the
10
+ * device-side publisher picks its protocol from the URL prefix. The composed
11
+ * `rtmpUrl`/`srtUrl`/`webrtcPublishUrl` are ready-to-publish (stream key /
12
+ * streamid+passphrase already embedded).
13
+ *
14
+ * Config (env):
15
+ * CF_STREAM_ACCOUNT_ID Cloudflare account id
16
+ * CF_STREAM_API_TOKEN API token with Stream:Edit
17
+ * CF_STREAM_CUSTOMER_SUBDOMAIN customer-<code>.cloudflarestream.com (for playback URLs)
18
+ *
19
+ * Cloudflare API:
20
+ * POST /accounts/:acct/stream/live_inputs -> { result: { uid, rtmps, srt, webRTC, ... } }
21
+ * GET /accounts/:acct/stream/live_inputs/:uid -> { result: { status: { current: {...} } } }
22
+ * DELETE /accounts/:acct/stream/live_inputs/:uid
23
+ * POST /accounts/:acct/stream/live_inputs/:uid/outputs (restream destinations)
24
+ * GET /accounts/:acct/stream/live_inputs/:uid/videos (recordings of this input)
25
+ * DELETE /accounts/:acct/stream/:videoUid (a recording)
26
+ *
27
+ * Recordings are separate objects from the live input and outlive it: deleting
28
+ * an input orphans its recordings, which keep counting against the account's
29
+ * storage quota. Recording cannot simply be turned off -- HLS playback requires
30
+ * `mode: automatic` -- so `stop()` deletes the recordings before the input, and
31
+ * `deleteRecordingAfterDays` is set as a floor for anything that slips past.
32
+ * Inputs are disabled before cleanup and retained whenever a recording is still
33
+ * finalizing, so no billable recording becomes unreachable through its input.
34
+ */
35
+
36
+ import type { ManagedStream, StreamOptions, StreamStatusResult } from "@mentra/cloud-protocol/camera";
37
+ import type {
38
+ StreamCleanupResult,
39
+ StreamDiscoveryResult,
40
+ StreamProvider,
41
+ } from "../stream.service";
42
+
43
+ const CF_API = "https://api.cloudflare.com/client/v4";
44
+
45
+ /** Cloudflare's minimum for `deleteRecordingAfterDays`. A floor, not the policy. */
46
+ const RECORDING_RETENTION_DAYS = 30;
47
+
48
+ interface LiveInputSummary {
49
+ uid?: string;
50
+ created?: string;
51
+ modified?: string;
52
+ meta?: unknown;
53
+ }
54
+
55
+ /** `GET /live_inputs` -- every input on the account. */
56
+ interface LiveInputListResult {
57
+ result?: {
58
+ liveInputs?: LiveInputSummary[];
59
+ range?: number;
60
+ total?: number;
61
+ };
62
+ success: boolean;
63
+ }
64
+
65
+ /** `GET /live_inputs/:uid/videos` -- the recordings produced by an input. */
66
+ interface VideoListResult {
67
+ result?: Array<{
68
+ uid: string;
69
+ status?: { state?: string } | null;
70
+ }>;
71
+ success: boolean;
72
+ }
73
+
74
+ interface LiveInputResult {
75
+ result?: {
76
+ uid: string;
77
+ enabled?: boolean;
78
+ meta?: unknown;
79
+ rtmps?: { url: string; streamKey: string };
80
+ rtmpsPlayback?: { url: string; streamKey: string };
81
+ srt?: { url: string; streamId: string; passphrase: string };
82
+ webRTC?: { url: string };
83
+ webRTCPlayback?: { url: string };
84
+ status?:
85
+ | string
86
+ | {
87
+ current?: {
88
+ state?: string | null;
89
+ statusEnteredAt?: string;
90
+ statusLastSeen?: string;
91
+ reason?: string;
92
+ } | null;
93
+ }
94
+ | null;
95
+ };
96
+ success: boolean;
97
+ errors?: Array<{ code: number; message: string }>;
98
+ }
99
+
100
+ /** First defined value among the given env var names. */
101
+ function env(...names: string[]): string | undefined {
102
+ for (const name of names) {
103
+ if (process.env[name]) return process.env[name];
104
+ }
105
+ return undefined;
106
+ }
107
+
108
+ export function createCloudflareStreamProvider(): StreamProvider {
109
+ // Accept the CF_STREAM_* names plus the v1 CLOUDFLARE_* names, so existing
110
+ // Cloudflare credentials work without re-keying. The token needs Stream:Edit.
111
+ const accountId = env("CF_STREAM_ACCOUNT_ID", "CLOUDFLARE_ACCOUNT_ID");
112
+ const apiToken = env("CF_STREAM_API_TOKEN", "CLOUDFLARE_API_TOKEN");
113
+ const customerSubdomain = env("CF_STREAM_CUSTOMER_SUBDOMAIN");
114
+
115
+ if (!accountId || !apiToken) {
116
+ throw new Error(
117
+ "STREAM_PROVIDER=cloudflare requires CF_STREAM_ACCOUNT_ID/CLOUDFLARE_ACCOUNT_ID " +
118
+ "and CF_STREAM_API_TOKEN/CLOUDFLARE_API_TOKEN.",
119
+ );
120
+ }
121
+
122
+ const base = `${CF_API}/accounts/${accountId}/stream/live_inputs`;
123
+ const authHeaders = { Authorization: `Bearer ${apiToken}` };
124
+
125
+ /** Playback host for a live input. Falls back to Cloudflare's shared host. */
126
+ function playbackUrls(uid: string): { hls: string; dash: string } {
127
+ const host = customerSubdomain
128
+ ? `https://${customerSubdomain}`
129
+ : "https://videodelivery.net";
130
+ return {
131
+ hls: `${host}/${uid}/manifest/video.m3u8`,
132
+ dash: `${host}/${uid}/manifest/video.mpd`,
133
+ };
134
+ }
135
+
136
+ function currentStatus(input: NonNullable<LiveInputResult["result"]>): {
137
+ state: string | null;
138
+ statusEnteredAt?: string;
139
+ statusLastSeen?: string;
140
+ reason?: string;
141
+ } {
142
+ if (typeof input.status === "string") return { state: input.status };
143
+ return {
144
+ state: input.status?.current?.state ?? null,
145
+ statusEnteredAt: input.status?.current?.statusEnteredAt,
146
+ statusLastSeen: input.status?.current?.statusLastSeen,
147
+ reason: input.status?.current?.reason,
148
+ };
149
+ }
150
+
151
+ function isReclaimProtectedState(state: string | null): boolean {
152
+ return (
153
+ state === "connected" ||
154
+ state === "reconnected" ||
155
+ state === "reconnecting" ||
156
+ state === "live"
157
+ );
158
+ }
159
+
160
+ function isConnectedState(state: string | null): boolean {
161
+ return state === "connected" || state === "reconnected" || state === "live";
162
+ }
163
+
164
+ function isMentraInput(input: LiveInputSummary): boolean {
165
+ if (!input.meta || typeof input.meta !== "object") return false;
166
+ const name = (input.meta as Record<string, unknown>).name;
167
+ return typeof name === "string" && name.startsWith("mentra-");
168
+ }
169
+
170
+ async function getLiveInput(inputUid: string): Promise<NonNullable<LiveInputResult["result"]> | null> {
171
+ const res = await fetch(`${base}/${inputUid}`, { headers: authHeaders });
172
+ if (res.status === 404) return null;
173
+
174
+ const body = (await res.json()) as LiveInputResult;
175
+ if (!res.ok || !body.success || !body.result) {
176
+ const detail = body.errors?.map((e) => e.message).join("; ") ?? res.statusText;
177
+ throw new Error(`cloudflare live input get failed: ${detail}`);
178
+ }
179
+ return body.result;
180
+ }
181
+
182
+ async function disableInput(inputUid: string): Promise<boolean> {
183
+ const res = await fetch(`${base}/${inputUid}`, {
184
+ method: "PUT",
185
+ headers: { ...authHeaders, "Content-Type": "application/json" },
186
+ body: JSON.stringify({ enabled: false }),
187
+ });
188
+ if (res.status === 404) return false;
189
+ if (!res.ok) throw new Error(`cloudflare live input disable failed: ${res.status}`);
190
+ return true;
191
+ }
192
+
193
+ async function deleteInput(inputUid: string): Promise<void> {
194
+ const res = await fetch(`${base}/${inputUid}`, {
195
+ method: "DELETE",
196
+ headers: authHeaders,
197
+ });
198
+ if (!res.ok && res.status !== 404) {
199
+ throw new Error(`cloudflare live input delete failed: ${res.status}`);
200
+ }
201
+ }
202
+
203
+ interface RecordingCleanupResult {
204
+ deleted: number;
205
+ failed: number;
206
+ pending: number;
207
+ seen: number;
208
+ }
209
+
210
+ /**
211
+ * Delete every finished recording belonging to a live input.
212
+ *
213
+ * A stream that has just ended may not have a recording yet (Cloudflare can
214
+ * take time to make one available). Callers use the returned pending/failure
215
+ * counts to retain the input for a later sweep instead of orphaning video.
216
+ *
217
+ * Returns a lifecycle summary so callers can distinguish complete cleanup
218
+ * from a safe deferral.
219
+ */
220
+ async function cleanupRecordings(inputUid: string): Promise<RecordingCleanupResult> {
221
+ const listed = await fetch(`${base}/${inputUid}/videos`, { headers: authHeaders });
222
+ if (!listed.ok) {
223
+ throw new Error(`cloudflare recording list failed: ${listed.status}`);
224
+ }
225
+
226
+ const body = (await listed.json()) as VideoListResult;
227
+ if (!body.success || !Array.isArray(body.result)) {
228
+ throw new Error("cloudflare recording list returned an invalid response");
229
+ }
230
+ const videos = body.result ?? [];
231
+ let deleted = 0;
232
+ let failed = 0;
233
+ let pending = 0;
234
+
235
+ for (const video of videos) {
236
+ const state = video.status?.state;
237
+ if (state !== "ready" && state !== "error") {
238
+ // Unknown and processing states are deliberately retained. Deleting
239
+ // the input now would orphan a recording that Cloudflare has not
240
+ // finished materializing yet.
241
+ pending += 1;
242
+ continue;
243
+ }
244
+
245
+ const res = await fetch(`${CF_API}/accounts/${accountId}/stream/${video.uid}`, {
246
+ method: "DELETE",
247
+ headers: authHeaders,
248
+ });
249
+ if (res.ok || res.status === 404) deleted += 1;
250
+ else failed += 1;
251
+ }
252
+ return { deleted, failed, pending, seen: videos.length };
253
+ }
254
+
255
+ async function listLiveInputs(): Promise<{
256
+ inputs: LiveInputSummary[];
257
+ total: number;
258
+ }> {
259
+ const listed = await fetch(base, { headers: authHeaders });
260
+ if (!listed.ok) throw new Error(`cloudflare live input list failed: ${listed.status}`);
261
+
262
+ const body = (await listed.json()) as LiveInputListResult;
263
+ const inputs = body.result?.liveInputs;
264
+ if (!body.success || !Array.isArray(inputs)) {
265
+ throw new Error("cloudflare live input list returned an invalid response");
266
+ }
267
+ return { inputs, total: body.result?.total ?? inputs.length };
268
+ }
269
+
270
+ /**
271
+ * Disable an input, delete terminal recordings, then delete the input only
272
+ * when no recording can be orphaned. Explicit stops defer an empty recording
273
+ * list because Cloudflare may still be materializing it; queue recovery can
274
+ * accept an empty list after its grace period.
275
+ */
276
+ async function cleanupInput(
277
+ inputUid: string,
278
+ allowEmpty: boolean,
279
+ ): Promise<StreamCleanupResult> {
280
+ if (!(await disableInput(inputUid))) return { recordings: 0, input: "missing" };
281
+
282
+ const cleanup = await cleanupRecordings(inputUid);
283
+ if (cleanup.failed > 0) {
284
+ throw new Error(`cloudflare recording cleanup failed for ${cleanup.failed} recording(s)`);
285
+ }
286
+ if (cleanup.pending > 0 || (!allowEmpty && cleanup.seen === 0)) {
287
+ return { recordings: cleanup.deleted, input: "retained" };
288
+ }
289
+
290
+ await deleteInput(inputUid);
291
+ return { recordings: cleanup.deleted, input: "deleted" };
292
+ }
293
+
294
+ async function reclaim(inputUid: string): Promise<StreamCleanupResult> {
295
+ // A registry entry may refer to a live stream lasting longer than the
296
+ // abandonment grace period. Verify provider state before disabling it.
297
+ const current = await getLiveInput(inputUid);
298
+ if (!current) return { recordings: 0, input: "missing" };
299
+ if (isReclaimProtectedState(currentStatus(current).state)) {
300
+ return { recordings: 0, input: "retained" };
301
+ }
302
+ return await cleanupInput(inputUid, true);
303
+ }
304
+
305
+ async function discover(): Promise<StreamDiscoveryResult> {
306
+ const listed = await listLiveInputs();
307
+ const inputs = listed.inputs.flatMap((input) => {
308
+ if (!input.uid || !isMentraInput(input)) return [];
309
+ const createdAt = Date.parse(input.created ?? input.modified ?? "");
310
+ if (!Number.isFinite(createdAt)) return [];
311
+ return [{ streamId: input.uid, createdAt }];
312
+ });
313
+ return { inputs, truncated: listed.total > listed.inputs.length };
314
+ }
315
+
316
+ return {
317
+ name: "cloudflare",
318
+
319
+ async provision(mentraUserId: string, opts: StreamOptions): Promise<ManagedStream> {
320
+ const res = await fetch(base, {
321
+ method: "POST",
322
+ headers: { ...authHeaders, "Content-Type": "application/json" },
323
+ body: JSON.stringify({
324
+ meta: { name: `mentra-${mentraUserId}` },
325
+ // `automatic` is required: HLS/DASH playback does not work with
326
+ // recording off, and Mentra Call needs the live HLS URL.
327
+ recording: { mode: "automatic" },
328
+ // Backstop only. `stop()` deletes recordings explicitly; this bounds
329
+ // anything it misses (a stream that ends by disconnect, a failed
330
+ // delete). Cloudflare's minimum for this field is 30 days, so it
331
+ // cannot replace explicit deletion.
332
+ deleteRecordingAfterDays: RECORDING_RETENTION_DAYS,
333
+ }),
334
+ });
335
+ const body = (await res.json()) as LiveInputResult;
336
+ if (!res.ok || !body.success || !body.result) {
337
+ const detail = body.errors?.map((e) => e.message).join("; ") ?? res.statusText;
338
+ throw new Error(`cloudflare live input create failed: ${detail}`);
339
+ }
340
+ const { uid, rtmps, srt, webRTC, webRTCPlayback } = body.result;
341
+
342
+ // Ready-to-publish URLs: key/credentials embedded so the device can use
343
+ // them verbatim (its publisher detects protocol from the URL prefix).
344
+ const rtmpUrl = rtmps?.url && rtmps?.streamKey ? `${rtmps.url}${rtmps.streamKey}` : undefined;
345
+ const srtUrl =
346
+ srt?.url && srt?.streamId && srt?.passphrase
347
+ ? `${srt.url}?streamid=${encodeURIComponent(srt.streamId)}&passphrase=${encodeURIComponent(srt.passphrase)}`
348
+ : undefined;
349
+
350
+ // Restream destinations (re-publish the ingest to external RTMP targets).
351
+ // Best-effort: a failed output should not fail the provision — the stream
352
+ // itself is healthy without it.
353
+ const destinations = opts.restreamDestinations ?? [];
354
+ for (const dest of destinations) {
355
+ const url = typeof dest === "string" ? dest : dest.url;
356
+ const name = typeof dest === "string" ? undefined : dest.name;
357
+ try {
358
+ await fetch(`${base}/${uid}/outputs`, {
359
+ method: "POST",
360
+ headers: { ...authHeaders, "Content-Type": "application/json" },
361
+ body: JSON.stringify({ url, enabled: true, ...(name ? { meta: { name } } : {}) }),
362
+ });
363
+ } catch {
364
+ /* best-effort; surfaced via status polling if it matters */
365
+ }
366
+ }
367
+
368
+ return {
369
+ streamId: uid,
370
+ ingest: {
371
+ protocol: "rtmps",
372
+ url: rtmps?.url ?? "",
373
+ streamKey: rtmps?.streamKey ?? "",
374
+ rtmpUrl,
375
+ srtUrl,
376
+ webrtcPublishUrl: webRTC?.url,
377
+ },
378
+ playback: {
379
+ ...playbackUrls(uid),
380
+ webrtc: webRTCPlayback?.url,
381
+ },
382
+ };
383
+ },
384
+
385
+ async status(streamId: string): Promise<StreamStatusResult> {
386
+ const input = await getLiveInput(streamId);
387
+ if (!input) throw new Error("cloudflare live input status failed: input not found");
388
+ const current = currentStatus(input);
389
+ const state = current.state;
390
+ return {
391
+ streamId,
392
+ isConnected: isConnectedState(state),
393
+ state,
394
+ connectedAt: current.statusEnteredAt,
395
+ lastSeenAt: current.statusLastSeen,
396
+ reason: current.reason,
397
+ };
398
+ },
399
+
400
+ async stop(streamId: string): Promise<StreamCleanupResult> {
401
+ return await cleanupInput(streamId, false);
402
+ },
403
+
404
+ reclaim,
405
+ discover,
406
+ };
407
+ }
cloud-v2/packages/runtime/src/services/stream/stream.service.ts ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Live-stream provisioning abstraction for managed stream.
3
+ *
4
+ * Managed stream provisions a real live video stream on a provider and returns
5
+ * the ingest (where the device pushes) and playback (where viewers watch)
6
+ * coordinates. Unlike blob storage there is no local-real equivalent (you can't
7
+ * stand up a real RTMP ingest + HLS playback with no dependency), so the only
8
+ * provider today is Cloudflare Stream. With no provider configured, provisioning
9
+ * fails loudly rather than returning fake coordinates.
10
+ *
11
+ * Provider is chosen by `STREAM_PROVIDER` (default "cloudflare").
12
+ *
13
+ * Spec: docs/issues/002-cloud-runtime/camera/spec.md ("Managed stream").
14
+ */
15
+
16
+ import type { ManagedStream, StreamOptions, StreamStatusResult } from "@mentra/cloud-protocol/camera";
17
+ import { createLogger } from "@mentra/cloud-shared";
18
+ import { getRedis } from "../../clients/redis.client";
19
+ import { createCloudflareStreamProvider } from "./providers/cloudflare-stream.provider";
20
+
21
+ const logger = createLogger("audio").child({ service: "stream.service" });
22
+
23
+ export interface StreamProvider {
24
+ readonly name: string;
25
+ provision(mentraUserId: string, opts: StreamOptions): Promise<ManagedStream>;
26
+ status(streamId: string): Promise<StreamStatusResult>;
27
+ stop(streamId: string): Promise<StreamCleanupResult>;
28
+ /**
29
+ * Reclaim a known abandoned input. Unlike an explicit stop, an empty
30
+ * recording list is terminal because the queue's grace period has elapsed.
31
+ */
32
+ reclaim?(streamId: string): Promise<StreamCleanupResult>;
33
+ /** Seed the durable queue with inputs created before the queue existed. */
34
+ discover?(): Promise<StreamDiscoveryResult>;
35
+ }
36
+
37
+ export interface StreamCleanupResult {
38
+ recordings: number;
39
+ input: "deleted" | "retained" | "missing";
40
+ }
41
+
42
+ export interface StreamDiscoveryResult {
43
+ inputs: Array<{ streamId: string; createdAt: number }>;
44
+ truncated: boolean;
45
+ }
46
+
47
+ let provider: StreamProvider | null = null;
48
+
49
+ /** The configured stream provider, or throws if none is configured. */
50
+ export function getStreamProvider(): StreamProvider {
51
+ if (provider) return provider;
52
+ const kind = process.env.STREAM_PROVIDER ?? "cloudflare";
53
+ if (kind === "cloudflare") {
54
+ provider = createCloudflareStreamProvider();
55
+ return provider;
56
+ }
57
+ throw new Error(`unknown STREAM_PROVIDER: ${kind}`);
58
+ }
59
+
60
+ /** Test/boot hook: reset the cached provider. */
61
+ export function resetStreamProvider(): void {
62
+ provider = null;
63
+ }
64
+
65
+ // === Managed stream lifecycle ===
66
+
67
+ const CLEANUP_QUEUE_KEY = "managed-stream:cleanup";
68
+ const ABANDONED_STREAM_GRACE_MS = 6 * 60 * 60 * 1000;
69
+ const STOP_CLEANUP_RETRY_MS = 60 * 1000;
70
+ const SWEEP_RETRY_MS = 15 * 60 * 1000;
71
+ const LEGACY_DISCOVERY_INTERVAL_MS = 60 * 60 * 1000;
72
+ const SWEEP_BATCH_SIZE = 100;
73
+
74
+ type CleanupAction = "reclaim" | "stop";
75
+
76
+ function cleanupQueueMember(action: CleanupAction, streamId: string): string {
77
+ return `${action}:${streamId}`;
78
+ }
79
+
80
+ function parseCleanupQueueMember(member: string): {
81
+ action: CleanupAction;
82
+ streamId: string;
83
+ } {
84
+ if (member.startsWith("stop:")) {
85
+ return { action: "stop", streamId: member.slice("stop:".length) };
86
+ }
87
+ if (member.startsWith("reclaim:")) {
88
+ return { action: "reclaim", streamId: member.slice("reclaim:".length) };
89
+ }
90
+ // Entries written by earlier builds used the bare stream id.
91
+ return { action: "reclaim", streamId: member };
92
+ }
93
+
94
+ function cleanupQueueMembers(streamId: string): [string, string] {
95
+ return [cleanupQueueMember("reclaim", streamId), cleanupQueueMember("stop", streamId)];
96
+ }
97
+
98
+ export async function provisionStream(
99
+ mentraUserId: string,
100
+ opts: StreamOptions,
101
+ ): Promise<ManagedStream> {
102
+ const p = getStreamProvider();
103
+ const stream = await p.provision(mentraUserId, opts);
104
+ try {
105
+ await getRedis().zadd(
106
+ CLEANUP_QUEUE_KEY,
107
+ Date.now() + ABANDONED_STREAM_GRACE_MS,
108
+ cleanupQueueMember("reclaim", stream.streamId),
109
+ );
110
+ } catch (err) {
111
+ // Do not hand out an input that recovery cannot find. This input has never
112
+ // been published to, so reclaiming an empty input is safe.
113
+ await p.reclaim?.(stream.streamId).catch(() => undefined);
114
+ throw err;
115
+ }
116
+ return stream;
117
+ }
118
+
119
+ export async function streamStatus(streamId: string): Promise<StreamStatusResult> {
120
+ const status = await getStreamProvider().status(streamId);
121
+ // Status is polled throughout an active managed stream. Treat each successful
122
+ // observation as activity so a long-running stream never becomes sweepable
123
+ // merely because its original provision time is old. XX prevents a status
124
+ // response that finishes after completed teardown from recreating the entry.
125
+ await getRedis()
126
+ .zadd(
127
+ CLEANUP_QUEUE_KEY,
128
+ "XX",
129
+ Date.now() + ABANDONED_STREAM_GRACE_MS,
130
+ cleanupQueueMember("reclaim", streamId),
131
+ )
132
+ .catch((err) => logger.warn({ err, streamId }, "stream activity refresh failed"));
133
+ return status;
134
+ }
135
+
136
+ export async function stopStream(streamId: string): Promise<void> {
137
+ const redis = getRedis();
138
+ const stopMember = cleanupQueueMember("stop", streamId);
139
+
140
+ // Persist the finalization retry before touching Cloudflare. It is separate
141
+ // from the inactivity deadline, so an in-flight status poll cannot postpone
142
+ // an explicit stop and an empty recording list remains protected until a
143
+ // later stop retry observes the finalized recording.
144
+ await redis.zadd(CLEANUP_QUEUE_KEY, Date.now() + STOP_CLEANUP_RETRY_MS, stopMember);
145
+
146
+ const result = await getStreamProvider().stop(streamId);
147
+ if (result.input !== "retained") {
148
+ await redis.zrem(CLEANUP_QUEUE_KEY, ...cleanupQueueMembers(streamId));
149
+ }
150
+ }
151
+
152
+ // === Recording sweep loop ===
153
+
154
+ /** How often to process the durable cleanup queue. */
155
+ const SWEEP_INTERVAL_MS = STOP_CLEANUP_RETRY_MS;
156
+
157
+ let sweepTimer: ReturnType<typeof setTimeout> | null = null;
158
+ let sweepLoopStarted = false;
159
+ let nextLegacyDiscoveryAt = 0;
160
+
161
+ export async function sweepStreamsOnce(): Promise<{ recordings: number; inputs: number }> {
162
+ const p = getStreamProvider();
163
+ const redis = getRedis();
164
+ const now = Date.now();
165
+
166
+ // Best-effort migration for inputs created before the durable registry.
167
+ // Cloudflare's endpoint exposes only its first window, so the registry is
168
+ // authoritative for all newly provisioned streams. Queue processing runs
169
+ // every minute, but account-wide discovery remains hourly.
170
+ let discovered: StreamDiscoveryResult | undefined;
171
+ if (now >= nextLegacyDiscoveryAt) {
172
+ nextLegacyDiscoveryAt = now + LEGACY_DISCOVERY_INTERVAL_MS;
173
+ try {
174
+ discovered = await p.discover?.();
175
+ } catch (err) {
176
+ // Migration is advisory. A list-endpoint failure must never block cleanup
177
+ // of inputs already present in the authoritative queue.
178
+ logger.warn({ err }, "Cloudflare legacy input discovery failed");
179
+ }
180
+ }
181
+ if (discovered) {
182
+ const pipeline = redis.pipeline();
183
+ for (const input of discovered.inputs) {
184
+ pipeline.zadd(
185
+ CLEANUP_QUEUE_KEY,
186
+ "NX",
187
+ input.createdAt + ABANDONED_STREAM_GRACE_MS,
188
+ cleanupQueueMember("reclaim", input.streamId),
189
+ );
190
+ }
191
+ await pipeline.exec();
192
+ if (discovered.truncated) {
193
+ logger.warn(
194
+ { discovered: discovered.inputs.length },
195
+ "Cloudflare legacy input discovery is truncated; durable registry remains authoritative",
196
+ );
197
+ }
198
+ }
199
+
200
+ const claimed = await redis.zrangebyscore(
201
+ CLEANUP_QUEUE_KEY,
202
+ "-inf",
203
+ now,
204
+ "LIMIT",
205
+ 0,
206
+ SWEEP_BATCH_SIZE,
207
+ );
208
+ if (claimed.length > 0) {
209
+ // Move the batch forward before touching Cloudflare. Concurrent pods may
210
+ // very occasionally select the same batch, but provider operations are
211
+ // idempotent and this avoids losing work if a pod exits mid-cleanup.
212
+ const pipeline = redis.pipeline();
213
+ for (const member of claimed) {
214
+ const { action } = parseCleanupQueueMember(member);
215
+ const retryMs = action === "stop" ? STOP_CLEANUP_RETRY_MS : SWEEP_RETRY_MS;
216
+ pipeline.zadd(CLEANUP_QUEUE_KEY, now + retryMs, member);
217
+ }
218
+ await pipeline.exec();
219
+ }
220
+
221
+ let recordings = 0;
222
+ let inputs = 0;
223
+ for (const member of claimed) {
224
+ const { action, streamId } = parseCleanupQueueMember(member);
225
+ try {
226
+ if (action === "reclaim" && !p.reclaim) continue;
227
+ const result = action === "stop" ? await p.stop(streamId) : await p.reclaim!(streamId);
228
+ recordings += result.recordings;
229
+ if (result.input === "deleted" || result.input === "missing") {
230
+ await redis.zrem(CLEANUP_QUEUE_KEY, ...cleanupQueueMembers(streamId), streamId);
231
+ if (result.input === "deleted") inputs += 1;
232
+ }
233
+ // Retained inputs already carry the claim's retry timestamp.
234
+ } catch (err) {
235
+ logger.warn({ err, streamId }, "stream cleanup retained input for retry");
236
+ }
237
+ }
238
+ return { recordings, inputs };
239
+ }
240
+
241
+ /**
242
+ * Start the background sweep that reclaims abandoned live inputs and their
243
+ * recordings.
244
+ *
245
+ * `stop()` handles the tidy case, but it only runs when a client explicitly
246
+ * ends a stream; anything that ends by disconnect leaks. Recordings cannot be
247
+ * disabled (HLS playback needs `mode: automatic`), and Cloudflare's built-in
248
+ * `deleteRecordingAfterDays` has a 30-day minimum, so without this the account
249
+ * fills and Cloudflare starts rejecting broadcasts at publish -- which reaches
250
+ * the user as an unexplained network failure.
251
+ *
252
+ * Call once at startup. Idempotent, so a second call cannot create a duplicate
253
+ * timer. Every pod running this is fine: deletes are idempotent and a 404
254
+ * counts as success.
255
+ */
256
+ export function startStreamSweepLoop(): void {
257
+ if (sweepLoopStarted) return;
258
+ sweepLoopStarted = true;
259
+
260
+ const run = async () => {
261
+ try {
262
+ const { recordings, inputs } = await sweepStreamsOnce();
263
+ if (recordings || inputs) {
264
+ logger.info({ recordings, inputs }, "stream sweep reclaimed abandoned inputs");
265
+ }
266
+ } catch (err) {
267
+ // A provider that is not configured, or a Cloudflare blip. Next tick retries.
268
+ logger.warn({ err }, "stream sweep failed");
269
+ } finally {
270
+ // Schedule only after this run settles so slow account cleanup can never
271
+ // overlap itself and multiply Cloudflare API traffic.
272
+ if (sweepLoopStarted) sweepTimer = setTimeout(run, SWEEP_INTERVAL_MS);
273
+ }
274
+ };
275
+
276
+ void run();
277
+ }
278
+
279
+ /** Test/shutdown hook: stop the sweep loop. */
280
+ export function stopStreamSweepLoop(): void {
281
+ sweepLoopStarted = false;
282
+ nextLegacyDiscoveryAt = 0;
283
+ if (!sweepTimer) return;
284
+ clearTimeout(sweepTimer);
285
+ sweepTimer = null;
286
+ }
cloud-v2/packages/runtime/src/services/tts/providers/elevenlabs.provider.ts ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview ElevenLabs streaming TTS provider.
3
+ */
4
+ import { createLogger } from "@mentra/cloud-shared";
5
+ import { DEFAULT_TTS_AUDIO_FORMAT, TTS_AUDIO_FORMATS, type TtsAudioFormat } from "../tts-formats";
6
+ import type { TtsProvider, TtsProviderSpeakRequest } from "../tts.service";
7
+
8
+ const logger = createLogger("tts").child({ service: "elevenlabs.tts.provider" });
9
+
10
+ const ELEVENLABS_DEFAULTS = {
11
+ voiceId: process.env.ELEVENLABS_DEFAULT_VOICE_ID || "8IRrZoKuYTPnpLc6lM6a",
12
+ modelId: process.env.ELEVENLABS_DEFAULT_MODEL_ID || "eleven_flash_v2_5",
13
+ speed: Number.parseFloat(process.env.ELEVENLABS_DEFAULT_SPEED || "1.13"),
14
+ stability: Number.parseFloat(process.env.ELEVENLABS_DEFAULT_STABILITY || "0.68"),
15
+ similarityBoost: Number.parseFloat(process.env.ELEVENLABS_DEFAULT_SIMILARITY || "0.75"),
16
+ style: Number.parseFloat(process.env.ELEVENLABS_DEFAULT_STYLE || "0.0"),
17
+ };
18
+
19
+ /**
20
+ * ElevenLabs `output_format` per runtime format. MP3 sends none, so the
21
+ * request stays exactly what older hosts relied on (ElevenLabs' MP3 default).
22
+ */
23
+ const ELEVENLABS_OUTPUT_FORMAT: Record<TtsAudioFormat, string | undefined> = {
24
+ mp3: undefined,
25
+ pcm_24000: "pcm_24000",
26
+ };
27
+
28
+ /** Exported for tests: the ElevenLabs streaming URL for a voice and format. */
29
+ export function elevenLabsStreamUrl(voiceId: string, format: TtsAudioFormat): string {
30
+ const outputFormat = ELEVENLABS_OUTPUT_FORMAT[format];
31
+ const base = `https://api.elevenlabs.io/v1/text-to-speech/${voiceId}/stream`;
32
+ return outputFormat ? `${base}?output_format=${outputFormat}` : base;
33
+ }
34
+
35
+ function json(data: unknown, status: number): Response {
36
+ return new Response(JSON.stringify(data), {
37
+ status,
38
+ headers: { "Content-Type": "application/json" },
39
+ });
40
+ }
41
+
42
+ export class ElevenLabsTtsProvider implements TtsProvider {
43
+ preflight(format: TtsAudioFormat = DEFAULT_TTS_AUDIO_FORMAT): Response {
44
+ if (!process.env.ELEVENLABS_API_KEY) {
45
+ logger.error("ELEVENLABS_API_KEY environment variable not set");
46
+ return json(
47
+ {
48
+ success: false,
49
+ message: "TTS service not configured",
50
+ },
51
+ 500,
52
+ );
53
+ }
54
+
55
+ return new Response(null, {
56
+ headers: {
57
+ "Content-Type": TTS_AUDIO_FORMATS[format].contentType,
58
+ "Cache-Control": "no-cache",
59
+ },
60
+ });
61
+ }
62
+
63
+ async speak(req: TtsProviderSpeakRequest): Promise<Response> {
64
+ const apiKey = process.env.ELEVENLABS_API_KEY;
65
+ if (!apiKey) {
66
+ logger.error("ELEVENLABS_API_KEY environment variable not set");
67
+ return json(
68
+ {
69
+ success: false,
70
+ message: "TTS service not configured",
71
+ },
72
+ 500,
73
+ );
74
+ }
75
+
76
+ const voiceId = req.voiceId || ELEVENLABS_DEFAULTS.voiceId;
77
+ const modelId = req.modelId || ELEVENLABS_DEFAULTS.modelId;
78
+ const voiceSettings = req.voiceSettings || {
79
+ speed: ELEVENLABS_DEFAULTS.speed,
80
+ stability: ELEVENLABS_DEFAULTS.stability,
81
+ similarity_boost: ELEVENLABS_DEFAULTS.similarityBoost,
82
+ style: ELEVENLABS_DEFAULTS.style,
83
+ };
84
+ const format = req.format ?? DEFAULT_TTS_AUDIO_FORMAT;
85
+ const elevenLabsUrl = elevenLabsStreamUrl(voiceId, format);
86
+
87
+ logger.info({ voiceId, modelId, format }, "streaming TTS request");
88
+
89
+ const response = await fetch(elevenLabsUrl, {
90
+ method: "POST",
91
+ headers: {
92
+ "Content-Type": "application/json",
93
+ "xi-api-key": apiKey,
94
+ },
95
+ body: JSON.stringify({
96
+ text: req.text,
97
+ model_id: modelId,
98
+ voice_settings: voiceSettings,
99
+ }),
100
+ });
101
+
102
+ if (!response.ok) {
103
+ const errorText = await response.text();
104
+ logger.error({ status: response.status, body: errorText }, "ElevenLabs TTS request failed");
105
+ return json(
106
+ {
107
+ success: false,
108
+ message: `TTS service error: ${response.status}`,
109
+ details: errorText,
110
+ },
111
+ response.status,
112
+ );
113
+ }
114
+
115
+ if (!response.body) {
116
+ return json(
117
+ {
118
+ success: false,
119
+ message: "No audio data received from TTS service",
120
+ },
121
+ 500,
122
+ );
123
+ }
124
+
125
+ // ElevenLabs relays PCM as it is synthesized; the body is raw samples with
126
+ // no container, so the content type carries the sample format.
127
+ return new Response(response.body, {
128
+ headers: {
129
+ "Content-Type": TTS_AUDIO_FORMATS[format].contentType,
130
+ "Cache-Control": "no-cache",
131
+ Connection: "keep-alive",
132
+ },
133
+ });
134
+ }
135
+ }
cloud-v2/packages/runtime/src/services/tts/tts-formats.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Audio encodings the runtime TTS route can return.
3
+ *
4
+ * `mp3` is the default so older hosts keep working. `pcm_24000` is raw signed
5
+ * 16-bit little-endian mono PCM at 24 kHz, for hosts that stream it straight
6
+ * into a PCM player.
7
+ */
8
+ export const TTS_AUDIO_FORMATS = {
9
+ mp3: { contentType: "audio/mpeg" },
10
+ pcm_24000: { contentType: "audio/pcm;encoding=s16le;rate=24000;channels=1" },
11
+ } as const;
12
+
13
+ export type TtsAudioFormat = keyof typeof TTS_AUDIO_FORMATS;
14
+
15
+ export const DEFAULT_TTS_AUDIO_FORMAT: TtsAudioFormat = "mp3";
16
+
17
+ export function isTtsAudioFormat(value: string): value is TtsAudioFormat {
18
+ return Object.prototype.hasOwnProperty.call(TTS_AUDIO_FORMATS, value);
19
+ }
cloud-v2/packages/runtime/src/services/tts/tts.service.ts ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Runtime TTS service.
3
+ *
4
+ * The API layer owns HTTP/query validation. This service owns provider choice
5
+ * and keeps the route independent from ElevenLabs-specific transport details.
6
+ */
7
+ import { ElevenLabsTtsProvider } from "./providers/elevenlabs.provider";
8
+ import { DEFAULT_TTS_AUDIO_FORMAT, type TtsAudioFormat } from "./tts-formats";
9
+
10
+ export {
11
+ DEFAULT_TTS_AUDIO_FORMAT,
12
+ isTtsAudioFormat,
13
+ TTS_AUDIO_FORMATS,
14
+ type TtsAudioFormat,
15
+ } from "./tts-formats";
16
+
17
+ export interface TtsSpeakOptions {
18
+ voiceId?: string;
19
+ modelId?: string;
20
+ voiceSettings?: Record<string, unknown>;
21
+ format?: TtsAudioFormat;
22
+ }
23
+
24
+ export interface TtsProviderSpeakRequest extends TtsSpeakOptions {
25
+ text: string;
26
+ }
27
+
28
+ export interface TtsProvider {
29
+ preflight(format: TtsAudioFormat): Response;
30
+ speak(req: TtsProviderSpeakRequest): Promise<Response>;
31
+ }
32
+
33
+ export class TtsService {
34
+ constructor(private readonly provider: TtsProvider = new ElevenLabsTtsProvider()) {}
35
+
36
+ preflight(format: TtsAudioFormat = DEFAULT_TTS_AUDIO_FORMAT): Response {
37
+ return this.provider.preflight(format);
38
+ }
39
+
40
+ speak(text: string, options: TtsSpeakOptions = {}): Promise<Response> {
41
+ return this.provider.speak({
42
+ text,
43
+ ...options,
44
+ });
45
+ }
46
+ }
47
+
48
+ export const ttsService = new TtsService();
cloud-v2/packages/shared/package.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@mentra/cloud-shared",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "exports": {
8
+ ".": "./src/index.ts",
9
+ "./logger": "./src/logger.ts",
10
+ "./health": "./src/health.ts",
11
+ "./auth": "./src/auth.ts"
12
+ },
13
+ "scripts": {
14
+ "test": "bun test"
15
+ },
16
+ "dependencies": {
17
+ "hono": "^4.11.1",
18
+ "jose": "^5.9.6",
19
+ "pino": "^9.6.0"
20
+ },
21
+ "devDependencies": {
22
+ "pino-pretty": "^11.3.0"
23
+ }
24
+ }
cloud-v2/packages/shared/src/auth.test.ts ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import crypto from "node:crypto"
2
+ import {afterEach, describe, expect, test} from "bun:test"
3
+ import * as jose from "jose"
4
+
5
+ import {
6
+ resetMentraKeyCache,
7
+ resetRuntimeAuthCache,
8
+ signRuntimeToken,
9
+ verifyAccessTokenSignature,
10
+ verifyRuntimeToken,
11
+ } from "./auth"
12
+
13
+ const savedEnv = {
14
+ MENTRA_JWT_PUBLIC_KEY: process.env.MENTRA_JWT_PUBLIC_KEY,
15
+ CLOUD_CORE_ISSUER: process.env.CLOUD_CORE_ISSUER,
16
+ CLOUD_RUNTIME_AUTH_AUDIENCE: process.env.CLOUD_RUNTIME_AUTH_AUDIENCE,
17
+ CLOUD_RUNTIME_AUTH_ISSUERS: process.env.CLOUD_RUNTIME_AUTH_ISSUERS,
18
+ TEST_RUNTIME_PUBLIC_KEY: process.env.TEST_RUNTIME_PUBLIC_KEY,
19
+ }
20
+
21
+ afterEach(() => {
22
+ restoreEnv("CLOUD_RUNTIME_AUTH_AUDIENCE", savedEnv.CLOUD_RUNTIME_AUTH_AUDIENCE)
23
+ restoreEnv("CLOUD_RUNTIME_AUTH_ISSUERS", savedEnv.CLOUD_RUNTIME_AUTH_ISSUERS)
24
+ restoreEnv("TEST_RUNTIME_PUBLIC_KEY", savedEnv.TEST_RUNTIME_PUBLIC_KEY)
25
+ restoreEnv("MENTRA_JWT_PUBLIC_KEY", savedEnv.MENTRA_JWT_PUBLIC_KEY)
26
+ restoreEnv("CLOUD_CORE_ISSUER", savedEnv.CLOUD_CORE_ISSUER)
27
+ resetRuntimeAuthCache()
28
+ resetMentraKeyCache()
29
+ })
30
+
31
+ // Core's signing key signs phone access tokens (kid mentra-access-1), runtime
32
+ // tokens and the sign-in server's tokens (kid mentra-oidc-1, typ at+jwt). Each
33
+ // verifier pins the key ID and type, not only the signature and claims.
34
+ describe("phone access token verification pins the key and type", () => {
35
+ async function signWithCoreKey(privateKey: string, header: jose.JWTHeaderParameters, claims: jose.JWTPayload = {}) {
36
+ const key = await jose.importPKCS8(`-----BEGIN PRIVATE KEY-----\n${privateKey}\n-----END PRIVATE KEY-----`, "EdDSA")
37
+ return new jose.SignJWT({tenant_id: "mentra", session_id: "sess_1", ...claims})
38
+ .setProtectedHeader(header)
39
+ .setIssuer("cloud-core")
40
+ .setAudience("cloud-core")
41
+ .setSubject("mu_1")
42
+ .setJti("jti_1")
43
+ .setIssuedAt()
44
+ .setExpirationTime("60s")
45
+ .sign(key)
46
+ }
47
+
48
+ function useCoreKey() {
49
+ const keypair = createEd25519Keypair()
50
+ process.env.MENTRA_JWT_PUBLIC_KEY = keypair.publicKey
51
+ delete process.env.CLOUD_CORE_ISSUER
52
+ resetMentraKeyCache()
53
+ return keypair
54
+ }
55
+
56
+ test("a phone access token (kid mentra-access-1, no typ) verifies", async () => {
57
+ const keypair = useCoreKey()
58
+ const token = await signWithCoreKey(keypair.privateKey, {alg: "EdDSA", kid: "mentra-access-1"})
59
+ await expect(verifyAccessTokenSignature(token)).resolves.toMatchObject({mentraUserId: "mu_1"})
60
+ })
61
+
62
+ test.each([
63
+ ["the sign-in server's kid", {alg: "EdDSA", kid: "mentra-oidc-1"}],
64
+ ["an at+jwt access token", {alg: "EdDSA", kid: "mentra-access-1", typ: "at+jwt"}],
65
+ ["the runtime kid", {alg: "EdDSA", kid: "cloud-core-runtime-1"}],
66
+ ["no kid", {alg: "EdDSA"}],
67
+ // The header is caller-controlled JSON: a non-string typ is refused, never a TypeError.
68
+ ["a numeric typ", {alg: "EdDSA", kid: "mentra-access-1", typ: 1}],
69
+ ["an object typ", {alg: "EdDSA", kid: "mentra-access-1", typ: {}}],
70
+ ])("a token with matching claims but %s is refused", async (_label, header) => {
71
+ const keypair = useCoreKey()
72
+ const token = await signWithCoreKey(keypair.privateKey, header as jose.JWTHeaderParameters)
73
+ await expect(verifyAccessTokenSignature(token)).rejects.toThrow("not a Mentra access token")
74
+ })
75
+ })
76
+
77
+ describe("runtime token verification pins the key and type", () => {
78
+ function configure(extra: Record<string, unknown> = {}) {
79
+ const keypair = createEd25519Keypair()
80
+ process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey
81
+ process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([
82
+ {issuer: "test-runtime", publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY", userIdClaim: "sub", tenantIdClaim: "tenant_id", ...extra},
83
+ ])
84
+ return keypair
85
+ }
86
+
87
+ test.each(["mentra-oidc-1", "mentra-access-1", "mentra-miniapp-1", "mentra-account-1"])(
88
+ "a token under Core's %s key ID is never a runtime token",
89
+ async (kid) => {
90
+ const keypair = configure()
91
+ const token = await signRuntimeToken({privateKey: keypair.privateKey, issuer: "test-runtime", subject: "u", tenantId: "t", expiresInSeconds: 60, kid})
92
+ await expect(verifyRuntimeToken(token)).rejects.toThrow("not a runtime token")
93
+ },
94
+ )
95
+
96
+ test("a typed at+jwt token is refused", async () => {
97
+ const keypair = configure()
98
+ const key = await jose.importPKCS8(`-----BEGIN PRIVATE KEY-----\n${keypair.privateKey}\n-----END PRIVATE KEY-----`, "EdDSA")
99
+ const token = await new jose.SignJWT({tenant_id: "t"})
100
+ .setProtectedHeader({alg: "EdDSA", kid: "cloud-core-runtime-1", typ: "at+jwt"})
101
+ .setIssuer("test-runtime")
102
+ .setAudience("cloud-runtime")
103
+ .setSubject("u")
104
+ .setIssuedAt()
105
+ .setExpirationTime("60s")
106
+ .sign(key)
107
+ await expect(verifyRuntimeToken(token)).rejects.toThrow("not a runtime token")
108
+ })
109
+
110
+ test.each([1, {}])("a non-string typ (%p) is refused, never a TypeError", async (typ) => {
111
+ const keypair = configure()
112
+ const key = await jose.importPKCS8(`-----BEGIN PRIVATE KEY-----\n${keypair.privateKey}\n-----END PRIVATE KEY-----`, "EdDSA")
113
+ const token = await new jose.SignJWT({tenant_id: "t"})
114
+ .setProtectedHeader({alg: "EdDSA", kid: "cloud-core-runtime-1", typ} as unknown as jose.JWTHeaderParameters)
115
+ .setIssuer("test-runtime")
116
+ .setAudience("cloud-runtime")
117
+ .setSubject("u")
118
+ .setIssuedAt()
119
+ .setExpirationTime("60s")
120
+ .sign(key)
121
+ await expect(verifyRuntimeToken(token)).rejects.toThrow("not a runtime token")
122
+ })
123
+
124
+ test("an issuer's keyIds pin the key ID", async () => {
125
+ const keypair = configure({keyIds: ["cloud-core-runtime-1"]})
126
+ const sign = (kid: string) => signRuntimeToken({privateKey: keypair.privateKey, issuer: "test-runtime", subject: "u", tenantId: "t", expiresInSeconds: 60, kid})
127
+ await expect(verifyRuntimeToken(await sign("cloud-core-runtime-1"))).resolves.toMatchObject({mentraUserId: "u"})
128
+ await expect(verifyRuntimeToken(await sign("other-1"))).rejects.toThrow("unexpected key ID")
129
+ })
130
+ })
131
+
132
+ describe("runtime token verification", () => {
133
+ test("requires explicit runtime issuer config", async () => {
134
+ delete process.env.CLOUD_RUNTIME_AUTH_ISSUERS
135
+
136
+ await expect(verifyRuntimeToken("not-a-runtime-token")).rejects.toThrow("runtime auth issuer config is required")
137
+ })
138
+
139
+ test("accepts a configured cloud-runtime issuer", async () => {
140
+ const keypair = createEd25519Keypair()
141
+ process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey
142
+ process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([
143
+ {
144
+ issuer: "test-runtime",
145
+ publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY",
146
+ userIdClaim: "sub",
147
+ tenantIdClaim: "tenant_id",
148
+ },
149
+ ])
150
+
151
+ const token = await signRuntimeToken({
152
+ privateKey: keypair.privateKey,
153
+ issuer: "test-runtime",
154
+ subject: "user-1",
155
+ tenantId: "oem-1",
156
+ jti: "runtime-jti",
157
+ expiresInSeconds: 60,
158
+ })
159
+
160
+ await expect(verifyRuntimeToken(token)).resolves.toEqual({
161
+ mentraUserId: "user-1",
162
+ tenantId: "oem-1",
163
+ sessionId: "runtime_runtime-jti",
164
+ jti: "runtime-jti",
165
+ exp: expect.any(Number),
166
+ })
167
+ })
168
+
169
+ test("preserves a Core-attested federated workforce identity", async () => {
170
+ const keypair = createEd25519Keypair()
171
+ process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey
172
+ process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([
173
+ {
174
+ issuer: "https://core.workspace.example",
175
+ publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY",
176
+ userIdClaim: "sub",
177
+ tenantIdClaim: "tenant_id",
178
+ },
179
+ ])
180
+
181
+ const token = await signRuntimeToken({
182
+ privateKey: keypair.privateKey,
183
+ issuer: "https://core.workspace.example",
184
+ subject: "mu_01TEST",
185
+ tenantId: "acme-private",
186
+ sessionId: "sess_01TEST",
187
+ federatedIdentity: {
188
+ providerId: "workforce",
189
+ providerKind: "microsoft-entra",
190
+ issuer: "https://login.microsoftonline.com/tenant/v2.0",
191
+ subject: "employee-object-id",
192
+ directoryTenantId: "tenant",
193
+ },
194
+ expiresInSeconds: 60,
195
+ })
196
+
197
+ await expect(verifyRuntimeToken(token)).resolves.toEqual({
198
+ mentraUserId: "mu_01TEST",
199
+ tenantId: "acme-private",
200
+ sessionId: "sess_01TEST",
201
+ jti: expect.any(String),
202
+ exp: expect.any(Number),
203
+ federatedIdentity: {
204
+ providerId: "workforce",
205
+ providerKind: "microsoft-entra",
206
+ issuer: "https://login.microsoftonline.com/tenant/v2.0",
207
+ subject: "employee-object-id",
208
+ directoryTenantId: "tenant",
209
+ },
210
+ })
211
+ })
212
+
213
+ test("accepts legacy issuer tenant config while preferring tenant_id tokens", async () => {
214
+ const keypair = createEd25519Keypair()
215
+ process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey
216
+ process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([
217
+ {
218
+ issuer: "test-runtime",
219
+ publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY",
220
+ userIdClaim: "sub",
221
+ oemIdClaim: "oem_id",
222
+ },
223
+ ])
224
+
225
+ const token = await signRuntimeToken({
226
+ privateKey: keypair.privateKey,
227
+ issuer: "test-runtime",
228
+ subject: "user-1",
229
+ tenantId: "tenant-1",
230
+ jti: "runtime-jti",
231
+ expiresInSeconds: 60,
232
+ })
233
+
234
+ await expect(verifyRuntimeToken(token)).resolves.toEqual({
235
+ mentraUserId: "user-1",
236
+ tenantId: "tenant-1",
237
+ sessionId: "runtime_runtime-jti",
238
+ jti: "runtime-jti",
239
+ exp: expect.any(Number),
240
+ })
241
+ })
242
+
243
+ test("accepts legacy fixed OEM config as fixed tenant config", async () => {
244
+ const keypair = createEd25519Keypair()
245
+ process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey
246
+ process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([
247
+ {
248
+ issuer: "test-runtime",
249
+ publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY",
250
+ userIdClaim: "sub",
251
+ fixedOemId: "tenant-legacy",
252
+ },
253
+ ])
254
+
255
+ const token = await signRuntimeToken({
256
+ privateKey: keypair.privateKey,
257
+ issuer: "test-runtime",
258
+ subject: "user-1",
259
+ tenantId: "tenant-token",
260
+ jti: "runtime-jti",
261
+ expiresInSeconds: 60,
262
+ })
263
+
264
+ await expect(verifyRuntimeToken(token)).resolves.toEqual({
265
+ mentraUserId: "user-1",
266
+ tenantId: "tenant-legacy",
267
+ sessionId: "runtime_runtime-jti",
268
+ jti: "runtime-jti",
269
+ exp: expect.any(Number),
270
+ })
271
+ })
272
+
273
+ test("rejects tokens with the wrong audience", async () => {
274
+ const keypair = createEd25519Keypair()
275
+ process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey
276
+ process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([
277
+ {
278
+ issuer: "test-runtime",
279
+ publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY",
280
+ userIdClaim: "sub",
281
+ fixedTenantId: "oem-1",
282
+ },
283
+ ])
284
+
285
+ const token = await signRuntimeToken({
286
+ privateKey: keypair.privateKey,
287
+ issuer: "test-runtime",
288
+ audience: "cloud-core",
289
+ subject: "user-1",
290
+ tenantId: "oem-1",
291
+ expiresInSeconds: 60,
292
+ })
293
+
294
+ await expect(verifyRuntimeToken(token)).rejects.toThrow("runtime_token rejected")
295
+ })
296
+
297
+ test("enforces configured delegated scopes and native client ids", async () => {
298
+ const keypair = createEd25519Keypair()
299
+ process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey
300
+ process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([
301
+ {
302
+ issuer: "https://login.example/tenant/v2.0",
303
+ publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY",
304
+ userIdClaim: "oid",
305
+ fixedTenantId: "tenant-1",
306
+ requiredScopes: ["mentra.runtime"],
307
+ allowedClientIds: ["native-client"],
308
+ },
309
+ ])
310
+
311
+ const valid = await signClaims(keypair.privateKey, {
312
+ iss: "https://login.example/tenant/v2.0",
313
+ aud: "cloud-runtime",
314
+ oid: "employee-1",
315
+ scp: "mentra.runtime",
316
+ azp: "native-client",
317
+ })
318
+ await expect(verifyRuntimeToken(valid)).resolves.toEqual({
319
+ mentraUserId: "employee-1",
320
+ tenantId: "tenant-1",
321
+ sessionId: expect.stringMatching(/^runtime_/),
322
+ jti: expect.any(String),
323
+ exp: expect.any(Number),
324
+ })
325
+
326
+ const wrongClient = await signClaims(keypair.privateKey, {
327
+ iss: "https://login.example/tenant/v2.0",
328
+ aud: "cloud-runtime",
329
+ oid: "employee-1",
330
+ scp: "mentra.runtime",
331
+ azp: "other-client",
332
+ })
333
+ await expect(verifyRuntimeToken(wrongClient)).rejects.toThrow("client is not allowed")
334
+ })
335
+
336
+ test("rejects symmetric algorithms and an explicitly empty client allowlist", async () => {
337
+ const keypair = createEd25519Keypair()
338
+ process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey
339
+ process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([
340
+ {
341
+ issuer: "test-runtime",
342
+ publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY",
343
+ fixedTenantId: "tenant-1",
344
+ algorithms: ["HS256"],
345
+ },
346
+ ])
347
+ await expect(verifyRuntimeToken("not-reached")).rejects.toThrow("algorithms must use EdDSA, RS256, or ES256")
348
+
349
+ process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([
350
+ {
351
+ issuer: "test-runtime",
352
+ publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY",
353
+ fixedTenantId: "tenant-1",
354
+ allowedClientIds: [],
355
+ },
356
+ ])
357
+ const token = await signRuntimeToken({
358
+ privateKey: keypair.privateKey,
359
+ issuer: "test-runtime",
360
+ subject: "user-1",
361
+ tenantId: "tenant-1",
362
+ expiresInSeconds: 60,
363
+ })
364
+ await expect(verifyRuntimeToken(token)).rejects.toThrow("client is not allowed")
365
+ })
366
+ })
367
+
368
+ async function signClaims(privateKey: string, claims: jose.JWTPayload): Promise<string> {
369
+ const key = await jose.importPKCS8(`-----BEGIN PRIVATE KEY-----\n${privateKey}\n-----END PRIVATE KEY-----`, "EdDSA")
370
+ return new jose.SignJWT(claims).setProtectedHeader({alg: "EdDSA"}).setIssuedAt().setExpirationTime("60s").sign(key)
371
+ }
372
+
373
+ function createEd25519Keypair(): {privateKey: string; publicKey: string} {
374
+ const {privateKey, publicKey} = crypto.generateKeyPairSync("ed25519")
375
+ return {
376
+ privateKey: stripPem(privateKey.export({type: "pkcs8", format: "pem"}).toString()),
377
+ publicKey: stripPem(publicKey.export({type: "spki", format: "pem"}).toString()),
378
+ }
379
+ }
380
+
381
+ function stripPem(pem: string): string {
382
+ return pem
383
+ .replace(/-----BEGIN [A-Z ]+-----/, "")
384
+ .replace(/-----END [A-Z ]+-----/, "")
385
+ .replace(/\s+/g, "")
386
+ }
387
+
388
+ function restoreEnv(key: string, value: string | undefined): void {
389
+ if (value === undefined) {
390
+ delete process.env[key]
391
+ } else {
392
+ process.env[key] = value
393
+ }
394
+ }
cloud-v2/packages/shared/src/auth.ts ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Mentra access-token verification, shared across packages.
3
+ *
4
+ * Pure-crypto: signature + claims. **Does not check revocation.** Revocation
5
+ * lives in core's Mongo, and only core's wrapper consults it. Other packages
6
+ * (audio, proxy) accept up-to-1h staleness on revoked access tokens — the
7
+ * actual revocation surface is the refresh token, which core owns.
8
+ *
9
+ * Both Mentra-issued private and public keys are PEM bodies (base64, no
10
+ * BEGIN/END wrapper) in env. See cloud-v2/docs/issues/001-oem-auth/design.md
11
+ * "Mentra-issued access token" for the claim shape.
12
+ */
13
+
14
+ import crypto from "node:crypto"
15
+ import * as jose from "jose"
16
+
17
+ const ALG = "EdDSA"
18
+ const CORE_AUDIENCE = "cloud-core"
19
+ /** The key ID Core signs its phone access tokens under. */
20
+ export const ACCESS_TOKEN_KID = "mentra-access-1"
21
+ /**
22
+ * Key IDs under which Core signs tokens that are never runtime tokens: phone
23
+ * access tokens, the sign-in server's ID and access tokens, miniapp tokens and
24
+ * account subject tokens. Some of them share Core's signing key with runtime
25
+ * tokens, so the key ID is pinned as well as the claims.
26
+ */
27
+ const CORE_NON_RUNTIME_KIDS: ReadonlySet<string> = new Set([ACCESS_TOKEN_KID, "mentra-oidc-1", "mentra-miniapp-1", "mentra-account-1"])
28
+
29
+ /**
30
+ * A plain signed JWT: no `typ`, or `typ` "JWT". Typed tokens, such as the
31
+ * sign-in server's `at+jwt` access tokens, are never accepted as phone or
32
+ * runtime tokens.
33
+ */
34
+ function isPlainJwtType(typ: unknown): boolean {
35
+ return typ === undefined || (typeof typ === "string" && typ.toUpperCase() === "JWT")
36
+ }
37
+
38
+ function protectedHeader(token: string, label: string): jose.ProtectedHeaderParameters {
39
+ try {
40
+ return jose.decodeProtectedHeader(token)
41
+ } catch {
42
+ throw new AccessTokenError(`${label} is not a parseable JWT`)
43
+ }
44
+ }
45
+
46
+ export interface FederatedIdentity {
47
+ providerId: string
48
+ providerKind: string
49
+ issuer: string
50
+ subject: string
51
+ directoryTenantId?: string
52
+ }
53
+
54
+ export interface VerifiedAccessToken {
55
+ mentraUserId: string
56
+ tenantId: string
57
+ sessionId: string
58
+ jti: string
59
+ exp: number
60
+ federatedIdentity?: FederatedIdentity
61
+ }
62
+
63
+ /**
64
+ * Thrown when an access token fails signature or claim verification. Marker
65
+ * class so callers can catch via `instanceof AccessTokenError` without
66
+ * coupling to specific error messages.
67
+ */
68
+ export class AccessTokenError extends Error {
69
+ constructor(message: string) {
70
+ super(message)
71
+ this.name = "AccessTokenError"
72
+ }
73
+ }
74
+
75
+ let publicKeyPromise: Promise<jose.KeyLike> | null = null
76
+ const RUNTIME_DEFAULT_AUDIENCE = "cloud-runtime"
77
+ const RUNTIME_DEFAULT_ALGORITHMS = ["EdDSA", "RS256", "ES256"] as const
78
+ const RUNTIME_ALLOWED_ALGORITHMS = new Set<string>(RUNTIME_DEFAULT_ALGORITHMS)
79
+
80
+ interface RuntimeIssuerConfig {
81
+ issuer: string
82
+ jwksUrl?: string
83
+ publicKey?: string
84
+ publicKeyEnv?: string
85
+ userIdClaim?: string
86
+ tenantIdClaim?: string
87
+ legacyTenantIdClaim?: string
88
+ fixedTenantId?: string
89
+ algorithms?: string[]
90
+ requiredScopes?: string[]
91
+ allowedClientIds?: string[]
92
+ /** When set, the token's `kid` must be one of these. */
93
+ keyIds?: string[]
94
+ }
95
+
96
+ const runtimeRemoteJwks = new Map<string, ReturnType<typeof jose.createRemoteJWKSet>>()
97
+ const runtimeStaticKeys = new Map<string, Promise<jose.KeyLike>>()
98
+
99
+ /** Reset the cached public key. Test-only — call after mutating env. */
100
+ export function resetMentraKeyCache(): void {
101
+ publicKeyPromise = null
102
+ resetRuntimeAuthCache()
103
+ }
104
+
105
+ async function getPublicKey(): Promise<jose.KeyLike> {
106
+ if (!publicKeyPromise) {
107
+ const pubBody = process.env.MENTRA_JWT_PUBLIC_KEY
108
+ if (!pubBody) {
109
+ throw new AccessTokenError("env var MENTRA_JWT_PUBLIC_KEY is not set")
110
+ }
111
+ const pem = `-----BEGIN PUBLIC KEY-----\n${pubBody}\n-----END PUBLIC KEY-----`
112
+ publicKeyPromise = jose.importSPKI(pem, ALG, {extractable: false})
113
+ }
114
+ return publicKeyPromise
115
+ }
116
+
117
+ /**
118
+ * Verify signature, issuer, audience, and expiry on a Mentra-issued access
119
+ * token. Throws `AccessTokenError` on failure. Does NOT check the revocation
120
+ * blacklist — see file header.
121
+ */
122
+ export async function verifyAccessTokenSignature(token: string): Promise<VerifiedAccessToken> {
123
+ // Core's signing key also signs runtime tokens and the sign-in server's tokens:
124
+ // pin the key ID and the token type as well as the issuer and audience.
125
+ const header = protectedHeader(token, "access_token")
126
+ if (header.kid !== ACCESS_TOKEN_KID || !isPlainJwtType(header.typ)) {
127
+ throw new AccessTokenError("access_token rejected: not a Mentra access token")
128
+ }
129
+ const publicKey = await getPublicKey()
130
+
131
+ let payload: jose.JWTPayload
132
+ try {
133
+ const result = await jose.jwtVerify(token, publicKey, {
134
+ audience: CORE_AUDIENCE,
135
+ issuer: process.env.CLOUD_CORE_ISSUER ?? "cloud-core",
136
+ algorithms: [ALG],
137
+ })
138
+ payload = result.payload
139
+ } catch (err) {
140
+ throw new AccessTokenError(`access_token rejected: ${(err as Error).message}`)
141
+ }
142
+
143
+ const sub = typeof payload.sub === "string" ? payload.sub : null
144
+ const tenantId = typeof payload.tenant_id === "string" ? payload.tenant_id : null
145
+ const sessionId = typeof payload.session_id === "string" ? payload.session_id : null
146
+ const jti = typeof payload.jti === "string" ? payload.jti : null
147
+ const exp = typeof payload.exp === "number" ? payload.exp : null
148
+ const federatedIdentity = parseFederatedIdentity(payload.federated_identity)
149
+
150
+ const missingClaims = [
151
+ !sub ? "sub" : null,
152
+ !tenantId ? "tenant_id" : null,
153
+ !sessionId ? "session_id" : null,
154
+ !jti ? "jti" : null,
155
+ !exp ? "exp" : null,
156
+ ].filter((claim): claim is string => Boolean(claim))
157
+ if (missingClaims.length > 0) {
158
+ throw new AccessTokenError(`access_token missing required claims: ${missingClaims.join(", ")}`)
159
+ }
160
+
161
+ return {
162
+ mentraUserId: sub!,
163
+ tenantId: tenantId!,
164
+ sessionId: sessionId!,
165
+ jti: jti!,
166
+ exp: exp!,
167
+ ...(federatedIdentity ? {federatedIdentity} : {}),
168
+ }
169
+ }
170
+
171
+ export async function verifyRuntimeToken(token: string): Promise<VerifiedAccessToken> {
172
+ const issuers = configuredRuntimeIssuers()
173
+ if (issuers.length === 0) {
174
+ throw new AccessTokenError("runtime auth issuer config is required")
175
+ }
176
+
177
+ const header = protectedHeader(token, "runtime_token")
178
+ if (!isPlainJwtType(header.typ) || (header.kid !== undefined && CORE_NON_RUNTIME_KIDS.has(header.kid))) {
179
+ throw new AccessTokenError("runtime_token rejected: not a runtime token")
180
+ }
181
+
182
+ let payload: jose.JWTPayload
183
+ let iss: string | undefined
184
+ try {
185
+ payload = jose.decodeJwt(token)
186
+ iss = typeof payload.iss === "string" ? payload.iss : undefined
187
+ } catch {
188
+ throw new AccessTokenError("runtime_token is not a parseable JWT")
189
+ }
190
+
191
+ const issuer = issuers.find((entry) => entry.issuer === iss)
192
+ if (!issuer) {
193
+ throw new AccessTokenError(`runtime_token issuer not trusted: ${iss ?? "missing"}`)
194
+ }
195
+
196
+ if (issuer.keyIds !== undefined && (header.kid === undefined || !issuer.keyIds.includes(header.kid))) {
197
+ throw new AccessTokenError("runtime_token rejected: unexpected key ID")
198
+ }
199
+
200
+ const key = await runtimeKeyForIssuer(issuer)
201
+ try {
202
+ const result = await jose.jwtVerify(token, key as jose.JWTVerifyGetKey, {
203
+ audience: process.env.CLOUD_RUNTIME_AUTH_AUDIENCE ?? RUNTIME_DEFAULT_AUDIENCE,
204
+ issuer: issuer.issuer,
205
+ algorithms: issuer.algorithms ?? [...RUNTIME_DEFAULT_ALGORITHMS],
206
+ clockTolerance: "5 minutes",
207
+ })
208
+ payload = result.payload
209
+ } catch (err) {
210
+ throw new AccessTokenError(`runtime_token rejected: ${(err as Error).message}`)
211
+ }
212
+
213
+ const scopes = new Set(typeof payload.scp === "string" ? payload.scp.split(" ").filter(Boolean) : [])
214
+ for (const requiredScope of issuer.requiredScopes ?? []) {
215
+ if (!scopes.has(requiredScope)) {
216
+ throw new AccessTokenError(`runtime_token missing required scope: ${requiredScope}`)
217
+ }
218
+ }
219
+ if (issuer.allowedClientIds !== undefined) {
220
+ const clientId = stringClaim(payload.azp) ?? stringClaim(payload.appid)
221
+ if (!clientId || !issuer.allowedClientIds.includes(clientId)) {
222
+ throw new AccessTokenError("runtime_token client is not allowed")
223
+ }
224
+ }
225
+
226
+ const userIdClaim = issuer.userIdClaim ?? "sub"
227
+ const userId = stringClaim(payload[userIdClaim])
228
+ const tenantId =
229
+ issuer.fixedTenantId ??
230
+ stringClaim(payload[issuer.tenantIdClaim ?? "tenant_id"]) ??
231
+ (issuer.legacyTenantIdClaim ? stringClaim(payload[issuer.legacyTenantIdClaim]) : undefined)
232
+ const jti = stringClaim(payload.jti) ?? cryptoRandomId()
233
+ const sessionId = stringClaim(payload.session_id) ?? `runtime_${jti}`
234
+ const exp = typeof payload.exp === "number" ? payload.exp : undefined
235
+
236
+ if (!userId || !tenantId || !exp) {
237
+ throw new AccessTokenError("runtime_token missing required identity claims")
238
+ }
239
+
240
+ const federatedIdentity = parseFederatedIdentity(payload.federated_identity)
241
+ return {
242
+ mentraUserId: userId,
243
+ tenantId,
244
+ sessionId,
245
+ jti,
246
+ exp,
247
+ ...(federatedIdentity ? {federatedIdentity} : {}),
248
+ }
249
+ }
250
+
251
+ export async function signRuntimeToken(args: {
252
+ privateKey: string
253
+ issuer: string
254
+ audience?: string
255
+ subject: string
256
+ tenantId: string
257
+ sessionId?: string
258
+ jti?: string
259
+ expiresInSeconds: number
260
+ kid?: string
261
+ federatedIdentity?: FederatedIdentity
262
+ }): Promise<string> {
263
+ const privateKey = await jose.importPKCS8(toPrivatePem(args.privateKey), "EdDSA", {extractable: false})
264
+ const claims: jose.JWTPayload = {
265
+ tenant_id: args.tenantId,
266
+ }
267
+ if (args.federatedIdentity) {
268
+ claims.federated_identity = serializeFederatedIdentity(args.federatedIdentity)
269
+ }
270
+ if (args.sessionId) claims.session_id = args.sessionId
271
+ const jwt = new jose.SignJWT(claims)
272
+ .setProtectedHeader({alg: "EdDSA", kid: args.kid ?? "cloud-runtime-1"})
273
+ .setIssuer(args.issuer)
274
+ .setAudience(args.audience ?? RUNTIME_DEFAULT_AUDIENCE)
275
+ .setSubject(args.subject)
276
+ .setIssuedAt()
277
+ .setExpirationTime(`${args.expiresInSeconds}s`)
278
+ if (args.jti) jwt.setJti(args.jti)
279
+ return jwt.sign(privateKey)
280
+ }
281
+
282
+ function serializeFederatedIdentity(identity: FederatedIdentity): Record<string, string> {
283
+ return {
284
+ provider_id: identity.providerId,
285
+ provider_kind: identity.providerKind,
286
+ issuer: identity.issuer,
287
+ subject: identity.subject,
288
+ ...(identity.directoryTenantId ? {directory_tenant_id: identity.directoryTenantId} : {}),
289
+ }
290
+ }
291
+
292
+ function parseFederatedIdentity(value: unknown): FederatedIdentity | undefined {
293
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
294
+ return undefined
295
+ }
296
+ const claims = value as Record<string, unknown>
297
+ const providerId = stringClaim(claims.provider_id)
298
+ const providerKind = stringClaim(claims.provider_kind)
299
+ const issuer = stringClaim(claims.issuer)
300
+ const subject = stringClaim(claims.subject)
301
+ if (!providerId || !providerKind || !issuer || !subject) return undefined
302
+ const directoryTenantId = stringClaim(claims.directory_tenant_id)
303
+ return {
304
+ providerId,
305
+ providerKind,
306
+ issuer,
307
+ subject,
308
+ ...(directoryTenantId ? {directoryTenantId} : {}),
309
+ }
310
+ }
311
+
312
+ export function resetRuntimeAuthCache(): void {
313
+ runtimeRemoteJwks.clear()
314
+ runtimeStaticKeys.clear()
315
+ }
316
+
317
+ export function assertRuntimeAuthConfigured(): void {
318
+ const issuers = configuredRuntimeIssuers()
319
+ if (issuers.length === 0) {
320
+ throw new AccessTokenError(
321
+ [
322
+ "CLOUD_RUNTIME_AUTH_ISSUERS must configure at least one issuer.",
323
+ "For local Cloud V2 development, run `bun run dev` from cloud-v2.",
324
+ "That command starts the integrated dev stack and generates matching local Core/Runtime auth keys.",
325
+ "Use `bun run dev:runtime` only when intentionally running Runtime in isolation with CLOUD_RUNTIME_AUTH_ISSUERS set yourself.",
326
+ ].join(" "),
327
+ )
328
+ }
329
+ }
330
+
331
+ function configuredRuntimeIssuers(): RuntimeIssuerConfig[] {
332
+ const raw = process.env.CLOUD_RUNTIME_AUTH_ISSUERS
333
+ if (!raw?.trim()) return []
334
+ try {
335
+ const parsed = JSON.parse(raw) as unknown
336
+ if (!Array.isArray(parsed)) throw new Error("expected array")
337
+ return parsed.map(parseRuntimeIssuerConfig)
338
+ } catch (err) {
339
+ throw new AccessTokenError(`CLOUD_RUNTIME_AUTH_ISSUERS is invalid: ${(err as Error).message}`)
340
+ }
341
+ }
342
+
343
+ function parseRuntimeIssuerConfig(value: unknown): RuntimeIssuerConfig {
344
+ if (!value || typeof value !== "object") {
345
+ throw new Error("issuer config must be an object")
346
+ }
347
+ const obj = value as Record<string, unknown>
348
+ const issuer = stringClaim(obj.issuer)
349
+ if (!issuer) throw new Error("issuer config missing issuer")
350
+
351
+ const legacyTenantIdClaim = stringClaim(obj.oemIdClaim)
352
+ const legacyFixedTenantId = stringClaim(obj.fixedOemId)
353
+ const tenantIdClaim = stringClaim(obj.tenantIdClaim) ?? (legacyTenantIdClaim ? "tenant_id" : undefined)
354
+ const fixedTenantId = stringClaim(obj.fixedTenantId) ?? legacyFixedTenantId
355
+ if (!tenantIdClaim && !fixedTenantId) {
356
+ throw new Error(`issuer ${issuer} must set tenantIdClaim or fixedTenantId`)
357
+ }
358
+ if (tenantIdClaim && fixedTenantId) {
359
+ throw new Error(`issuer ${issuer} cannot set both tenantIdClaim and fixedTenantId`)
360
+ }
361
+
362
+ const algorithms = Array.isArray(obj.algorithms)
363
+ ? obj.algorithms.filter((v): v is string => typeof v === "string")
364
+ : undefined
365
+ if (
366
+ algorithms !== undefined &&
367
+ (algorithms.length === 0 || algorithms.some((algorithm) => !RUNTIME_ALLOWED_ALGORITHMS.has(algorithm)))
368
+ ) {
369
+ throw new Error(`issuer ${issuer} algorithms must use EdDSA, RS256, or ES256`)
370
+ }
371
+ const requiredScopes = stringArrayClaim(obj.requiredScopes, "requiredScopes")
372
+ const allowedClientIds = stringArrayClaim(obj.allowedClientIds, "allowedClientIds")
373
+ const keyIds = stringArrayClaim(obj.keyIds, "keyIds")
374
+
375
+ return {
376
+ issuer,
377
+ jwksUrl: stringClaim(obj.jwksUrl),
378
+ publicKey: stringClaim(obj.publicKey),
379
+ publicKeyEnv: stringClaim(obj.publicKeyEnv),
380
+ userIdClaim: stringClaim(obj.userIdClaim),
381
+ tenantIdClaim,
382
+ legacyTenantIdClaim,
383
+ fixedTenantId,
384
+ algorithms,
385
+ requiredScopes,
386
+ allowedClientIds,
387
+ keyIds,
388
+ }
389
+ }
390
+
391
+ function stringArrayClaim(value: unknown, name: string): string[] | undefined {
392
+ if (value === undefined) return undefined
393
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || !entry.trim())) {
394
+ throw new Error(`${name} must be an array of non-empty strings`)
395
+ }
396
+ return value as string[]
397
+ }
398
+
399
+ async function runtimeKeyForIssuer(
400
+ issuer: RuntimeIssuerConfig,
401
+ ): Promise<jose.KeyLike | ReturnType<typeof jose.createRemoteJWKSet>> {
402
+ if (issuer.jwksUrl) {
403
+ let jwks = runtimeRemoteJwks.get(issuer.jwksUrl)
404
+ if (!jwks) {
405
+ jwks = jose.createRemoteJWKSet(new URL(issuer.jwksUrl), {
406
+ cooldownDuration: 30_000,
407
+ cacheMaxAge: 5 * 60_000,
408
+ })
409
+ runtimeRemoteJwks.set(issuer.jwksUrl, jwks)
410
+ }
411
+ return jwks
412
+ }
413
+
414
+ const keyMaterial = issuer.publicKey ?? (issuer.publicKeyEnv ? process.env[issuer.publicKeyEnv] : undefined)
415
+ if (!keyMaterial) {
416
+ throw new AccessTokenError(`issuer ${issuer.issuer} has no key source`)
417
+ }
418
+
419
+ let key = runtimeStaticKeys.get(keyMaterial)
420
+ if (!key) {
421
+ key = jose.importSPKI(toPublicPem(keyMaterial), issuer.algorithms?.[0] ?? "EdDSA", {extractable: false})
422
+ runtimeStaticKeys.set(keyMaterial, key)
423
+ }
424
+ return key
425
+ }
426
+
427
+ function toPublicPem(value: string): string {
428
+ if (value.includes("BEGIN PUBLIC KEY")) return value
429
+ return `-----BEGIN PUBLIC KEY-----\n${value}\n-----END PUBLIC KEY-----`
430
+ }
431
+
432
+ function toPrivatePem(value: string): string {
433
+ if (value.includes("BEGIN PRIVATE KEY")) return value
434
+ return `-----BEGIN PRIVATE KEY-----\n${value}\n-----END PRIVATE KEY-----`
435
+ }
436
+
437
+ function stringClaim(value: unknown): string | undefined {
438
+ return typeof value === "string" && value.length > 0 ? value : undefined
439
+ }
440
+
441
+ function cryptoRandomId(): string {
442
+ return crypto.randomBytes(16).toString("hex")
443
+ }
cloud-v2/packages/shared/src/health.ts ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Health and readiness endpoint factory.
3
+ *
4
+ * `/healthz` — liveness. Returns 200 if the event loop is responsive
5
+ * (which it is by definition if we're answering). K8s liveness probe
6
+ * uses this; a failure triggers pod restart.
7
+ *
8
+ * `/ready` — readiness. Returns 200 only if every configured readiness
9
+ * check passes. Otherwise 503 with the failing checks listed in the
10
+ * response body. K8s readiness probe uses this; a failure removes the
11
+ * pod from the Service's load balancer rotation but does NOT restart
12
+ * it. Useful for transient dependency outages (Mongo briefly down,
13
+ * etc.) where restarting wouldn't help.
14
+ *
15
+ * Each package wires its own readiness checks (Redis ping, Mongo ping,
16
+ * worker pool alive, etc.).
17
+ */
18
+
19
+ import { Hono } from "hono";
20
+
21
+ export type ReadinessCheck = {
22
+ name: string;
23
+ /** Return true if healthy. Throw or return false to fail. */
24
+ check: () => Promise<boolean> | boolean;
25
+ };
26
+
27
+ export type HealthAppOptions = {
28
+ /** Which cloud-v2 package this is. Echoed in responses for debugging. */
29
+ packageName: string;
30
+ /** Optional readiness checks evaluated on every /ready hit. */
31
+ readinessChecks?: ReadinessCheck[];
32
+ /** Non-secret static service composition surfaced for operators. */
33
+ details?: Record<string, unknown>;
34
+ };
35
+
36
+ type CheckResult = {
37
+ name: string;
38
+ ok: boolean;
39
+ error?: string;
40
+ };
41
+
42
+ export function createHealthApp(opts: HealthAppOptions): Hono {
43
+ const app = new Hono();
44
+
45
+ app.get("/healthz", (c) =>
46
+ c.json({ status: "ok", package: opts.packageName, ...opts.details }),
47
+ );
48
+
49
+ app.get("/ready", async (c) => {
50
+ const checks = opts.readinessChecks ?? [];
51
+ const results: CheckResult[] = [];
52
+
53
+ for (const rc of checks) {
54
+ try {
55
+ const ok = await rc.check();
56
+ results.push({ name: rc.name, ok });
57
+ } catch (err) {
58
+ console.error("readiness check failed", {
59
+ packageName: opts.packageName,
60
+ check: rc.name,
61
+ err,
62
+ });
63
+ results.push({
64
+ name: rc.name,
65
+ ok: false,
66
+ error: "readiness check failed",
67
+ });
68
+ }
69
+ }
70
+
71
+ const allOk = results.every((r) => r.ok);
72
+ return c.json(
73
+ {
74
+ status: allOk ? "ok" : "not_ready",
75
+ package: opts.packageName,
76
+ checks: results,
77
+ ...opts.details,
78
+ },
79
+ allOk ? 200 : 503,
80
+ );
81
+ });
82
+
83
+ return app;
84
+ }
cloud-v2/packages/shared/src/index.ts ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * `@mentra/cloud-shared` — types, config, observability primitives shared
3
+ * across the core, audio, and proxy packages.
4
+ */
5
+
6
+ export {createLogger, type Logger} from "./logger"
7
+ export {createHealthApp, type HealthAppOptions, type ReadinessCheck} from "./health"
8
+ export {
9
+ verifyAccessTokenSignature,
10
+ assertRuntimeAuthConfigured,
11
+ verifyRuntimeToken,
12
+ signRuntimeToken,
13
+ AccessTokenError,
14
+ resetMentraKeyCache,
15
+ resetRuntimeAuthCache,
16
+ type VerifiedAccessToken,
17
+ type FederatedIdentity,
18
+ } from "./auth"
19
+ export {verifyOidcToken, resetOidcVerifierCache, OidcTokenError, type OidcProviderConfig} from "./oidc"
20
+
21
+ export const PACKAGE_NAME = "@mentra/cloud-shared"
cloud-v2/packages/shared/src/logger.ts ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Cloud V2 logger. Pino-based, structured JSON.
3
+ *
4
+ * Two output modes, selected by `LOG_STDOUT_JSON` env var:
5
+ *
6
+ * LOG_STDOUT_JSON=true → raw JSON to stdout, picked up by Vector (BetterStack)
7
+ * (anything else) → pino-pretty for human-readable dev output
8
+ *
9
+ * Every log line carries pod-level metadata (hostname, env, region, package).
10
+ * Sub-loggers via `.child({ service: ... })` add scope without losing pod fields.
11
+ *
12
+ * Conventions: include a `feature` field for cross-cutting concerns
13
+ * (e.g. `feature: "audio-ingress"`) and a `service` field for the component
14
+ * emitting the log. Both fields are filterable in the future when needed.
15
+ */
16
+
17
+ import { hostname } from "node:os";
18
+ import pino, { type Logger, type LoggerOptions } from "pino";
19
+
20
+ const NODE_ENV = process.env.NODE_ENV ?? "development";
21
+ const REGION = process.env.REGION ?? process.env.DEPLOYMENT_REGION ?? "local";
22
+ const LOG_LEVEL = process.env.LOG_LEVEL ?? (NODE_ENV === "production" ? "info" : "debug");
23
+ const LOG_STDOUT_JSON = process.env.LOG_STDOUT_JSON === "true";
24
+
25
+ // pino-pretty types use a CJS export-assignment (`export =`), so the module
26
+ // type IS the factory; the runtime `.default` comes from Bun's ESM interop of
27
+ // that same assignment and needs a cast to line the two views up.
28
+ type PrettyFactory = typeof import("pino-pretty");
29
+
30
+ const PinoPretty: PrettyFactory | null = LOG_STDOUT_JSON
31
+ ? null
32
+ : ((await import("pino-pretty")) as unknown as { default: PrettyFactory }).default;
33
+
34
+ function podHostname(): string {
35
+ if (NODE_ENV === "production") {
36
+ return hostname();
37
+ }
38
+ return `local-${hostname()}-${process.pid}`;
39
+ }
40
+
41
+ /**
42
+ * Build a root logger for a specific package.
43
+ *
44
+ * @param packageName e.g. "core", "audio", "proxy". Becomes the `package` field on every log line.
45
+ */
46
+ export function createLogger(packageName: string): Logger {
47
+ const base = {
48
+ package: packageName,
49
+ pod: podHostname(),
50
+ env: NODE_ENV,
51
+ region: REGION,
52
+ };
53
+
54
+ const options: LoggerOptions = {
55
+ level: LOG_LEVEL,
56
+ base,
57
+ timestamp: pino.stdTimeFunctions.isoTime,
58
+ formatters: {
59
+ level(label) {
60
+ return { level: label };
61
+ },
62
+ },
63
+ };
64
+
65
+ if (LOG_STDOUT_JSON) {
66
+ // Raw JSON to stdout; Vector picks it up from the container's stdout.
67
+ return pino(options);
68
+ }
69
+
70
+ // Dev mode: pino-pretty as a direct stream.
71
+ // We avoid `transport: { target: "pino-pretty" }` because that uses Node
72
+ // worker_threads, which doesn't resolve pino-pretty's entry point cleanly
73
+ // under Bun. Passing the pretty stream directly to pino() works on both
74
+ // Bun and Node.
75
+ // Non-null: PinoPretty is only null when LOG_STDOUT_JSON, returned above.
76
+ const prettyStream = PinoPretty!({
77
+ colorize: true,
78
+ translateTime: "HH:MM:ss.l",
79
+ ignore: "pod,env,region",
80
+ singleLine: false,
81
+ });
82
+ return pino(options, prettyStream);
83
+ }
84
+
85
+ export type { Logger };
cloud-v2/packages/shared/src/oidc.ts ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as jose from "jose"
2
+
3
+ export interface OidcProviderConfig {
4
+ issuer: string
5
+ jwksUrl: string
6
+ audience: string
7
+ algorithms?: string[]
8
+ requiredScopes?: string[]
9
+ allowedClientIds?: string[]
10
+ }
11
+
12
+ export class OidcTokenError extends Error {
13
+ constructor(message: string) {
14
+ super(message)
15
+ this.name = "OidcTokenError"
16
+ }
17
+ }
18
+
19
+ const remoteJwks = new Map<string, ReturnType<typeof jose.createRemoteJWKSet>>()
20
+ const ALLOWED_OIDC_ALGORITHMS = new Set(["EdDSA", "RS256", "ES256"])
21
+
22
+ export async function verifyOidcToken(token: string, config: OidcProviderConfig): Promise<jose.JWTPayload> {
23
+ const algorithms = config.algorithms ?? ["RS256"]
24
+ if (algorithms.length === 0 || algorithms.some((algorithm) => !ALLOWED_OIDC_ALGORITHMS.has(algorithm))) {
25
+ throw new OidcTokenError("OIDC algorithms must use EdDSA, RS256, or ES256")
26
+ }
27
+
28
+ let keySet = remoteJwks.get(config.jwksUrl)
29
+ if (!keySet) {
30
+ let url: URL
31
+ try {
32
+ url = new URL(config.jwksUrl)
33
+ } catch {
34
+ throw new OidcTokenError("OIDC jwksUrl is not a valid URL")
35
+ }
36
+ if (url.protocol !== "https:") {
37
+ throw new OidcTokenError("OIDC jwksUrl must use HTTPS")
38
+ }
39
+ keySet = jose.createRemoteJWKSet(url, {
40
+ cooldownDuration: 30_000,
41
+ cacheMaxAge: 5 * 60_000,
42
+ })
43
+ remoteJwks.set(config.jwksUrl, keySet)
44
+ }
45
+
46
+ let payload: jose.JWTPayload
47
+ try {
48
+ ;({payload} = await jose.jwtVerify(token, keySet, {
49
+ issuer: config.issuer,
50
+ audience: config.audience,
51
+ algorithms,
52
+ clockTolerance: "5 minutes",
53
+ }))
54
+ } catch (err) {
55
+ throw new OidcTokenError(`OIDC token rejected: ${(err as Error).message}`)
56
+ }
57
+
58
+ const grantedScopes = new Set(typeof payload.scp === "string" ? payload.scp.split(" ").filter(Boolean) : [])
59
+ for (const requiredScope of config.requiredScopes ?? []) {
60
+ if (!grantedScopes.has(requiredScope)) {
61
+ throw new OidcTokenError(`OIDC token missing required scope: ${requiredScope}`)
62
+ }
63
+ }
64
+
65
+ if (config.allowedClientIds !== undefined) {
66
+ const clientId = stringClaim(payload.azp) ?? stringClaim(payload.appid)
67
+ if (!clientId || !config.allowedClientIds.includes(clientId)) {
68
+ throw new OidcTokenError("OIDC token client is not allowed")
69
+ }
70
+ }
71
+
72
+ return payload
73
+ }
74
+
75
+ export function resetOidcVerifierCache(): void {
76
+ remoteJwks.clear()
77
+ }
78
+
79
+ function stringClaim(value: unknown): string | undefined {
80
+ return typeof value === "string" && value.length > 0 ? value : undefined
81
+ }
cloud-v2/packages/shared/tsconfig.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "composite": true,
5
+ "outDir": "./dist",
6
+ "rootDir": "./src"
7
+ },
8
+ "include": ["src/**/*"]
9
+ }