@mycadet/assistant 0.12.11 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/__tests__/ingress.test.ts +2 -2
  2. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/ingress.ts +2 -2
  3. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/__tests__/ingress.test.ts +2 -2
  4. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/ingress.ts +2 -2
  5. package/node_modules/@mycadet/gateway-client/src/gateway-ipc-contracts.ts +0 -20
  6. package/node_modules/@mycadet/service-contracts/src/__tests__/ingress.test.ts +2 -2
  7. package/node_modules/@mycadet/service-contracts/src/ingress.ts +2 -2
  8. package/openapi.yaml +2 -708
  9. package/package.json +2 -3
  10. package/scripts/sync-web-search-catalog.ts +1 -2
  11. package/src/__tests__/cloud-profile-guard.test.ts +2 -2
  12. package/src/__tests__/config-schema.test.ts +6 -38
  13. package/src/__tests__/conversation-queue.test.ts +45 -6
  14. package/src/__tests__/db-readiness-http-gate.test.ts +0 -6
  15. package/src/__tests__/persist-onboarding-artifacts.test.ts +0 -1
  16. package/src/__tests__/persona-resolver.test.ts +0 -51
  17. package/src/__tests__/provider-cloud-proxy-integration.test.ts +2 -110
  18. package/src/__tests__/run-due-schedules.test.ts +0 -4
  19. package/src/__tests__/schedule-store.test.ts +0 -12
  20. package/src/__tests__/stt-stream-session.test.ts +4 -4
  21. package/src/__tests__/telephony-tts-guard.test.ts +2 -50
  22. package/src/__tests__/voice-config-update.test.ts +12 -167
  23. package/src/__tests__/web-search-catalog-parity.test.ts +0 -2
  24. package/src/__tests__/workspace-migration-130-speech-mode-to-provider.test.ts +9 -7
  25. package/src/__tests__/workspace-migration-132-web-search-mode-to-provider.test.ts +6 -6
  26. package/src/calls/__tests__/voice-session-bridge.test.ts +1 -4
  27. package/src/calls/resolve-call-tts-provider.ts +6 -25
  28. package/src/calls/telephony-credential-preflight.ts +0 -10
  29. package/src/calls/telephony-tts-capability.ts +1 -17
  30. package/src/cli/commands/tts.ts +1 -2
  31. package/src/cli/index.help.ts +0 -2
  32. package/src/cli/program.ts +0 -2
  33. package/src/config/bundled-skills/settings/tools/voice-config-update.ts +4 -42
  34. package/src/config/schemas/__tests__/stt.test.ts +10 -14
  35. package/src/config/schemas/services.ts +5 -6
  36. package/src/config/schemas/stt.ts +1 -3
  37. package/src/config/schemas/tts.ts +1 -30
  38. package/src/daemon/daemon-readiness.ts +4 -29
  39. package/src/daemon/lifecycle.ts +0 -31
  40. package/src/daemon/providers-setup.ts +0 -8
  41. package/src/heartbeat/__tests__/heartbeat-service.test.ts +0 -1
  42. package/src/heartbeat/heartbeat-service.ts +1 -66
  43. package/src/ipc/__tests__/db-readiness-ipc-gate.test.ts +1 -9
  44. package/src/live-voice/__tests__/live-voice-credential-preflight.test.ts +0 -44
  45. package/src/live-voice/__tests__/live-voice-flux-turn-end.test.ts +4 -6
  46. package/src/live-voice/__tests__/live-voice-stt.test.ts +1 -1
  47. package/src/live-voice/live-voice-credential-preflight.ts +9 -33
  48. package/src/live-voice/live-voice-session.ts +10 -6
  49. package/src/live-voice/live-voice-tts.ts +1 -8
  50. package/src/plugins/defaults/memory/worker.ts +3 -3
  51. package/src/prompts/persona-resolver.ts +0 -35
  52. package/src/providers/__tests__/search-provider-catalog.test.ts +5 -8
  53. package/src/providers/__tests__/voice-error-copy.test.ts +9 -10
  54. package/src/providers/search-provider-catalog.ts +7 -39
  55. package/src/providers/speech-to-text/__tests__/provider-catalog.test.ts +3 -47
  56. package/src/providers/speech-to-text/__tests__/resolve.test.ts +6 -372
  57. package/src/providers/speech-to-text/provider-catalog.ts +2 -73
  58. package/src/providers/speech-to-text/resolve.ts +3 -120
  59. package/src/runtime/http-router-types.ts +1 -3
  60. package/src/runtime/http-server.ts +1 -1
  61. package/src/runtime/routes/__tests__/tts-routes.test.ts +2 -6
  62. package/src/runtime/routes/inbound-stages/transcribe-audio.test.ts +7 -7
  63. package/src/runtime/routes/index.ts +0 -4
  64. package/src/runtime/routes/live-voice-routes.test.ts +4 -11
  65. package/src/runtime/routes/live-voice-routes.ts +8 -11
  66. package/src/runtime/routes/secret-routes.ts +0 -6
  67. package/src/runtime/routes/tts-routes.ts +0 -38
  68. package/src/schedule/__tests__/plugin-schedule-reconciler.test.ts +1 -7
  69. package/src/schedule/__tests__/worker-mcp-readiness.test.ts +0 -4
  70. package/src/schedule/schedule-store.ts +0 -7
  71. package/src/schedule/scheduler.ts +0 -5
  72. package/src/schedule/worker.ts +1 -1
  73. package/src/stt/__tests__/daemon-batch-transcriber.test.ts +2 -10
  74. package/src/stt/daemon-batch-transcriber.ts +4 -38
  75. package/src/stt/types.ts +1 -9
  76. package/src/tools/network/__tests__/web-search.test.ts +3 -250
  77. package/src/tools/network/web-search.ts +4 -165
  78. package/src/tts/__tests__/provider-resolution.test.ts +0 -5
  79. package/src/tts/provider-catalog.ts +0 -4
  80. package/src/tts/types.ts +0 -1
  81. package/src/__tests__/cloud-speech-defaults.test.ts +0 -330
  82. package/src/__tests__/migration-cross-version-compatibility.test.ts +0 -1708
  83. package/src/__tests__/migration-export-http.test.ts +0 -557
  84. package/src/__tests__/migration-export-streaming.test.ts +0 -350
  85. package/src/__tests__/migration-export-to-gcs.test.ts +0 -706
  86. package/src/__tests__/migration-import-commit-http.test.ts +0 -1176
  87. package/src/__tests__/migration-import-from-gcs.test.ts +0 -534
  88. package/src/__tests__/migration-import-from-path.test.ts +0 -324
  89. package/src/__tests__/migration-import-from-url.test.ts +0 -588
  90. package/src/__tests__/migration-import-preflight-http.test.ts +0 -739
  91. package/src/__tests__/migration-jobs-status.test.ts +0 -139
  92. package/src/__tests__/migration-parity-persistence.test.ts +0 -1891
  93. package/src/__tests__/migration-transport.test.ts +0 -1089
  94. package/src/__tests__/migration-validate-http.test.ts +0 -634
  95. package/src/__tests__/migration-wizard.test.ts +0 -1395
  96. package/src/__tests__/rebind-secrets-screen.test.ts +0 -876
  97. package/src/__tests__/sanitize-config-for-transfer.test.ts +0 -259
  98. package/src/__tests__/transfer-progress-screen.test.ts +0 -1217
  99. package/src/__tests__/validation-results-screen.test.ts +0 -1130
  100. package/src/__tests__/vbundle-pax-and-symlink.test.ts +0 -147
  101. package/src/background-wake/background-wake-routes.test.ts +0 -906
  102. package/src/background-wake/cloud-client.test.ts +0 -328
  103. package/src/background-wake/cloud-client.ts +0 -196
  104. package/src/background-wake/next-wake.test.ts +0 -335
  105. package/src/background-wake/next-wake.ts +0 -188
  106. package/src/background-wake/publisher.ts +0 -93
  107. package/src/background-wake/wake-intent-hooks.test.ts +0 -234
  108. package/src/cli/commands/__tests__/backup.test.ts +0 -363
  109. package/src/cli/commands/backup.help.ts +0 -180
  110. package/src/cli/commands/backup.ts +0 -398
  111. package/src/cloud/cloud-speech.test.ts +0 -335
  112. package/src/cloud/cloud-speech.ts +0 -300
  113. package/src/config/cloud-speech-defaults.ts +0 -300
  114. package/src/config/sanitize-for-transfer.ts +0 -111
  115. package/src/live-voice/__tests__/live-voice-cloud-speech-fallback.test.ts +0 -250
  116. package/src/providers/speech-to-text/__tests__/cadet-cloud-realtime.test.ts +0 -457
  117. package/src/providers/speech-to-text/__tests__/cadet-cloud.test.ts +0 -271
  118. package/src/providers/speech-to-text/__tests__/cadet-speech-relay-connection.test.ts +0 -126
  119. package/src/providers/speech-to-text/cadet-cloud-flux-realtime.ts +0 -309
  120. package/src/providers/speech-to-text/cadet-cloud-realtime.ts +0 -315
  121. package/src/providers/speech-to-text/cadet-cloud.ts +0 -108
  122. package/src/providers/speech-to-text/cadet-speech-relay-connection.ts +0 -176
  123. package/src/runtime/migrations/__tests__/gcs-signed-url.test.ts +0 -254
  124. package/src/runtime/migrations/__tests__/job-registry.test.ts +0 -346
  125. package/src/runtime/migrations/__tests__/origin-mode.test.ts +0 -62
  126. package/src/runtime/migrations/__tests__/rebind-secrets-credentials.test.ts +0 -184
  127. package/src/runtime/migrations/__tests__/staged-import-path.test.ts +0 -110
  128. package/src/runtime/migrations/__tests__/v1-test-helpers.ts +0 -112
  129. package/src/runtime/migrations/__tests__/vbundle-builder-credentials.test.ts +0 -285
  130. package/src/runtime/migrations/__tests__/vbundle-builder-fd-leak.test.ts +0 -126
  131. package/src/runtime/migrations/__tests__/vbundle-builder-v1-shape.test.ts +0 -253
  132. package/src/runtime/migrations/__tests__/vbundle-import-credentials.test.ts +0 -208
  133. package/src/runtime/migrations/__tests__/vbundle-import-parity.test.ts +0 -485
  134. package/src/runtime/migrations/__tests__/vbundle-import-policy.test.ts +0 -349
  135. package/src/runtime/migrations/__tests__/vbundle-import-version-compat.test.ts +0 -196
  136. package/src/runtime/migrations/__tests__/vbundle-legacy-user-md.test.ts +0 -551
  137. package/src/runtime/migrations/__tests__/vbundle-metadata-merge-integration.test.ts +0 -428
  138. package/src/runtime/migrations/__tests__/vbundle-metadata-merge.test.ts +0 -220
  139. package/src/runtime/migrations/__tests__/vbundle-streaming-importer.test.ts +0 -1823
  140. package/src/runtime/migrations/__tests__/vbundle-streaming-validator.test.ts +0 -598
  141. package/src/runtime/migrations/__tests__/vbundle-symlink-importer.test.ts +0 -463
  142. package/src/runtime/migrations/__tests__/vbundle-symlink-streaming-importer.test.ts +0 -538
  143. package/src/runtime/migrations/__tests__/vbundle-symlink-streaming.test.ts +0 -515
  144. package/src/runtime/migrations/__tests__/vbundle-symlink-tar.test.ts +0 -453
  145. package/src/runtime/migrations/__tests__/vbundle-symlink-walker.test.ts +0 -319
  146. package/src/runtime/migrations/__tests__/vbundle-tar-stream.test.ts +0 -240
  147. package/src/runtime/migrations/__tests__/vbundle-validator-v1-schema.test.ts +0 -473
  148. package/src/runtime/migrations/gcs-signed-url.ts +0 -190
  149. package/src/runtime/migrations/job-registry.ts +0 -297
  150. package/src/runtime/migrations/migration-transport.ts +0 -612
  151. package/src/runtime/migrations/migration-wizard.ts +0 -747
  152. package/src/runtime/migrations/origin-mode.ts +0 -42
  153. package/src/runtime/migrations/rebind-secrets-screen.ts +0 -412
  154. package/src/runtime/migrations/staged-import-path.ts +0 -116
  155. package/src/runtime/migrations/transfer-progress-screen.ts +0 -323
  156. package/src/runtime/migrations/validation-results-screen.ts +0 -469
  157. package/src/runtime/migrations/vbundle-builder.ts +0 -1382
  158. package/src/runtime/migrations/vbundle-import-analyzer.ts +0 -405
  159. package/src/runtime/migrations/vbundle-import-policy.ts +0 -241
  160. package/src/runtime/migrations/vbundle-importer.ts +0 -826
  161. package/src/runtime/migrations/vbundle-metadata-merge.ts +0 -113
  162. package/src/runtime/migrations/vbundle-streaming-importer.ts +0 -2844
  163. package/src/runtime/migrations/vbundle-streaming-validator.ts +0 -426
  164. package/src/runtime/migrations/vbundle-tar-stream.ts +0 -244
  165. package/src/runtime/migrations/vbundle-validator.ts +0 -724
  166. package/src/runtime/routes/__tests__/migration-cadet-metadata-reconcile.test.ts +0 -227
  167. package/src/runtime/routes/__tests__/migration-export-secrets-redacted.test.ts +0 -54
  168. package/src/runtime/routes/__tests__/migration-import-allowed-hosts-env.test.ts +0 -70
  169. package/src/runtime/routes/__tests__/migration-import-credential-filter.test.ts +0 -257
  170. package/src/runtime/routes/background-wake-routes.ts +0 -387
  171. package/src/runtime/routes/migration-routes.ts +0 -2584
  172. package/src/tools/network/__tests__/cloud-search-proxy.test.ts +0 -282
  173. package/src/tools/network/cloud-search-proxy.ts +0 -211
  174. package/src/tts/__tests__/cadet-provider.test.ts +0 -253
  175. package/src/tts/providers/cadet-provider.ts +0 -244
  176. package/src/types/tar-stream.d.ts +0 -66
@@ -1,457 +0,0 @@
1
- /**
2
- * Tests for the cadet managed realtime STT adapter (tunnel relay).
3
- *
4
- * The global WebSocket is replaced with a recording factory so tests can
5
- * assert on the dialed URL (query auth, no model param) and drive multiple
6
- * sequential sockets — the session-cap re-dial opens a second connection.
7
- */
8
- import { afterEach, beforeEach, describe, expect, test } from "bun:test";
9
-
10
- import { SttError, type SttStreamServerEvent } from "../../../stt/types.js";
11
- import { CadetManagedFluxRealtimeTranscriber } from "../cadet-cloud-flux-realtime.js";
12
- import { CadetManagedRealtimeTranscriber } from "../cadet-cloud-realtime.js";
13
- import type { SpeechRelayConnection } from "../cadet-speech-relay-connection.js";
14
-
15
- type WsListener = (...args: unknown[]) => void;
16
-
17
- class MockWebSocket {
18
- readyState = 0;
19
- bufferedAmount = 0;
20
- sentData: (string | Uint8Array)[] = [];
21
- closeCalled = false;
22
-
23
- constructor(
24
- readonly url: string,
25
- readonly ctorOptions?: { headers?: Record<string, string> },
26
- ) {}
27
-
28
- private listeners = new Map<string, WsListener[]>();
29
-
30
- addEventListener(type: string, listener: WsListener): void {
31
- const list = this.listeners.get(type) ?? [];
32
- list.push(listener);
33
- this.listeners.set(type, list);
34
- }
35
-
36
- removeEventListener(type: string, listener: unknown): void {
37
- const list = this.listeners.get(type);
38
- if (!list) {
39
- return;
40
- }
41
- const idx = list.indexOf(listener as WsListener);
42
- if (idx !== -1) {
43
- list.splice(idx, 1);
44
- }
45
- }
46
-
47
- send(data: string | Uint8Array): void {
48
- if (this.readyState !== 1) {
49
- throw new Error("WebSocket is not open");
50
- }
51
- this.sentData.push(data);
52
- }
53
-
54
- close(): void {
55
- this.closeCalled = true;
56
- this.readyState = 3;
57
- }
58
-
59
- simulateOpen(): void {
60
- this.readyState = 1;
61
- for (const l of this.listeners.get("open") ?? []) {
62
- l();
63
- }
64
- }
65
-
66
- simulateMessage(data: string): void {
67
- for (const l of this.listeners.get("message") ?? []) {
68
- l({ data });
69
- }
70
- }
71
-
72
- simulateClose(code = 1000, reason = ""): void {
73
- this.readyState = 3;
74
- for (const l of this.listeners.get("close") ?? []) {
75
- l({ code, reason });
76
- }
77
- }
78
- }
79
-
80
- function resultsFrame(
81
- transcript: string,
82
- options: { is_final?: boolean } = {},
83
- ): string {
84
- return JSON.stringify({
85
- type: "Results",
86
- is_final: options.is_final ?? false,
87
- channel: { alternatives: [{ transcript, confidence: 0.9 }] },
88
- });
89
- }
90
-
91
- function tunnelErrorFrame(code: string, detail = ""): string {
92
- return JSON.stringify({ type: "tunnel_error", code, detail });
93
- }
94
-
95
- const CONNECTION: SpeechRelayConnection = {
96
- wsBaseUrl: "ws://gateway.test",
97
- httpBaseUrl: "http://gateway.test",
98
- mintServiceToken: () => "vk-secret",
99
- };
100
-
101
- const tick = () => new Promise<void>((r) => setTimeout(r, 0));
102
-
103
- describe("Cadet Cloud realtime transcribers", () => {
104
- let sockets: MockWebSocket[];
105
- let originalWebSocket: unknown;
106
- let originalFetch: unknown;
107
-
108
- beforeEach(() => {
109
- sockets = [];
110
- originalWebSocket = (globalThis as Record<string, unknown>).WebSocket;
111
- (globalThis as Record<string, unknown>).WebSocket = class {
112
- constructor(url: string, options?: { headers?: Record<string, string> }) {
113
- const ws = new MockWebSocket(url, options);
114
- sockets.push(ws);
115
- return ws;
116
- }
117
- };
118
- originalFetch = globalThis.fetch;
119
- });
120
-
121
- afterEach(() => {
122
- (globalThis as Record<string, unknown>).WebSocket = originalWebSocket;
123
- globalThis.fetch = originalFetch as typeof fetch;
124
- });
125
-
126
- function collector(): {
127
- events: SttStreamServerEvent[];
128
- onEvent: (e: SttStreamServerEvent) => void;
129
- } {
130
- const events: SttStreamServerEvent[] = [];
131
- return { events, onEvent: (e) => events.push(e) };
132
- }
133
-
134
- async function startAdapter(
135
- options: ConstructorParameters<
136
- typeof CadetManagedRealtimeTranscriber
137
- >[1] = {},
138
- ) {
139
- const adapter = new CadetManagedRealtimeTranscriber(CONNECTION, options);
140
- const { events, onEvent } = collector();
141
- const startPromise = adapter.start(onEvent);
142
- sockets[0]!.simulateOpen();
143
- await startPromise;
144
- return { adapter, events };
145
- }
146
-
147
- test("dials the tunnel STT route with query auth and no model param", async () => {
148
- await startAdapter({ sampleRate: 24000 });
149
-
150
- const ws = sockets[0]!;
151
- const url = new URL(ws.url);
152
- expect(url.origin).toBe("ws://gateway.test");
153
- expect(url.pathname).toBe("/v1/speech/stt/stream");
154
- expect(url.searchParams.get("key")).toBe("vk-secret");
155
- expect(url.searchParams.get("encoding")).toBe("linear16");
156
- expect(url.searchParams.get("sample_rate")).toBe("24000");
157
- expect(url.searchParams.get("channels")).toBe("1");
158
- // tunnel pins the model server-side and rejects the param.
159
- expect(url.searchParams.has("model")).toBe(false);
160
- // tunnel's allowlist has no utterance_end_ms.
161
- expect(url.searchParams.has("utterance_end_ms")).toBe(false);
162
- // Auth travels in the URL, not a Deepgram Token header.
163
- expect(ws.ctorOptions?.headers?.Authorization).toBeUndefined();
164
- });
165
-
166
- test("streams interim and final transcripts through the shared pipeline", async () => {
167
- const { events } = await startAdapter();
168
-
169
- sockets[0]!.simulateMessage(resultsFrame("hello wor"));
170
- sockets[0]!.simulateMessage(
171
- resultsFrame("hello world", { is_final: true }),
172
- );
173
-
174
- expect(events).toEqual([
175
- expect.objectContaining({ type: "partial", text: "hello wor" }),
176
- expect.objectContaining({ type: "final", text: "hello world" }),
177
- ]);
178
- });
179
-
180
- test("maps a mid-stream tunnel_error to a categorized SttError", async () => {
181
- const { events } = await startAdapter();
182
-
183
- sockets[0]!.simulateMessage(
184
- tunnelErrorFrame("insufficient_balance", "balance is 0"),
185
- );
186
- sockets[0]!.simulateClose(1011, "insufficient_balance");
187
-
188
- expect(events).toEqual([
189
- expect.objectContaining({
190
- type: "error",
191
- category: "provider-error",
192
- message: expect.stringContaining("credits"),
193
- }),
194
- { type: "closed" },
195
- ]);
196
- });
197
-
198
- test("maps invalid_key to an auth error", async () => {
199
- const { events } = await startAdapter();
200
-
201
- sockets[0]!.simulateMessage(tunnelErrorFrame("invalid_key"));
202
- sockets[0]!.simulateClose(1008, "invalid_key");
203
-
204
- expect(events[0]).toEqual(
205
- expect.objectContaining({
206
- type: "error",
207
- category: "auth",
208
- message: expect.stringContaining("TUNNEL_BASE_URL"),
209
- }),
210
- );
211
- });
212
-
213
- test("drains the capped session's close cleanup before re-dialing", async () => {
214
- // In utterance-boundary mode, committed segments are withheld until a
215
- // boundary; the inner adapter flushes them during its close cleanup
216
- // (after the swallowed cap error, before `closed`). The swap must not
217
- // drop that flush — or an outstanding finalize's settlement.
218
- const { adapter, events } = await startAdapter({
219
- utteranceBoundaryFinals: true,
220
- });
221
-
222
- sockets[0]!.simulateMessage(resultsFrame("tail text", { is_final: true }));
223
- adapter.finalizeUtterance();
224
- sockets[0]!.simulateMessage(
225
- tunnelErrorFrame("session_duration_exceeded", "30m cap"),
226
- );
227
- sockets[0]!.simulateClose(1000, "session_duration_exceeded");
228
-
229
- await tick();
230
- expect(sockets).toHaveLength(2);
231
-
232
- expect(events).toEqual([
233
- expect.objectContaining({ type: "final", text: "tail text" }),
234
- { type: "finalized" },
235
- ]);
236
- });
237
-
238
- test("re-dials transparently when tunnel's session cap closes the stream", async () => {
239
- const { adapter, events } = await startAdapter({ sampleRate: 16000 });
240
-
241
- // Tunnel settles the in-flight utterance before closing.
242
- sockets[0]!.simulateMessage(resultsFrame("first leg", { is_final: true }));
243
- sockets[0]!.simulateMessage(
244
- tunnelErrorFrame("session_duration_exceeded", "30m cap"),
245
- );
246
- sockets[0]!.simulateClose(1000, "session_duration_exceeded");
247
-
248
- // Audio during the swap is dropped, not an error.
249
- adapter.sendAudio(Buffer.from([0, 1]), "audio/pcm");
250
-
251
- await tick();
252
- expect(sockets).toHaveLength(2);
253
- sockets[1]!.simulateOpen();
254
- await tick();
255
-
256
- sockets[1]!.simulateMessage(resultsFrame("second leg", { is_final: true }));
257
-
258
- expect(events).toEqual([
259
- expect.objectContaining({ type: "final", text: "first leg" }),
260
- expect.objectContaining({ type: "final", text: "second leg" }),
261
- ]);
262
- // The second dial reuses the same auth/params.
263
- expect(new URL(sockets[1]!.url).searchParams.get("key")).toBe("vk-secret");
264
- });
265
-
266
- test("Flux turn indices stay in one sequence across relay reconnects", async () => {
267
- const adapter = new CadetManagedFluxRealtimeTranscriber(CONNECTION);
268
- const { events, onEvent } = collector();
269
- const started = adapter.start(onEvent);
270
- sockets[0]!.simulateOpen();
271
- await started;
272
- try {
273
- for (let generation = 0; generation < 3; generation += 1) {
274
- const socket = sockets[generation]!;
275
- const turnIndex = generation === 0 ? 5 : 0;
276
- const startFrame = JSON.stringify({
277
- type: "TurnInfo",
278
- event: "StartOfTurn",
279
- turn_index: turnIndex,
280
- });
281
- socket.simulateMessage(startFrame);
282
- socket.simulateMessage(startFrame);
283
- socket.simulateMessage(
284
- JSON.stringify({
285
- type: "TurnInfo",
286
- event: "EndOfTurn",
287
- // A later end without its start still advances the sequence.
288
- turn_index: generation === 1 ? 2 : turnIndex,
289
- transcript: "hello",
290
- }),
291
- );
292
- if (generation < 2) {
293
- socket.simulateMessage(tunnelErrorFrame("session_duration_exceeded"));
294
- socket.simulateClose(1000, "session_duration_exceeded");
295
- await tick();
296
- sockets[generation + 1]!.simulateOpen();
297
- await tick();
298
- }
299
- }
300
- expect(
301
- events.flatMap((event) =>
302
- event.type === "turn-start" || event.type === "turn-end"
303
- ? [event.turnIndex]
304
- : [],
305
- ),
306
- ).toEqual([5, 5, 5, 6, 6, 8, 9, 9, 9]);
307
- expect(events.some((event) => event.type === "closed")).toBe(false);
308
- } finally {
309
- adapter.stop();
310
- sockets.at(-1)!.simulateClose();
311
- }
312
- });
313
-
314
- test("finalize during a re-dial settles immediately", async () => {
315
- const { adapter, events } = await startAdapter();
316
-
317
- sockets[0]!.simulateMessage(tunnelErrorFrame("session_duration_exceeded"));
318
- sockets[0]!.simulateClose(1000, "session_duration_exceeded");
319
-
320
- adapter.finalizeUtterance();
321
- expect(events).toEqual([{ type: "finalized" }]);
322
- });
323
-
324
- test("a rejected cap re-dial surfaces the relay's mapped error via the probe", async () => {
325
- globalThis.fetch = (async () =>
326
- new Response(
327
- JSON.stringify({ code: "insufficient_balance", detail: "empty" }),
328
- { status: 402 },
329
- )) as unknown as typeof fetch;
330
- const { events } = await startAdapter();
331
-
332
- sockets[0]!.simulateMessage(tunnelErrorFrame("session_duration_exceeded"));
333
- sockets[0]!.simulateClose(1000, "session_duration_exceeded");
334
- await tick();
335
-
336
- // The re-dial's handshake is rejected (credits ran out mid-call).
337
- sockets[1]!.simulateClose(1006, "");
338
- await tick();
339
- await tick();
340
-
341
- expect(events).toEqual([
342
- expect.objectContaining({
343
- type: "error",
344
- category: "provider-error",
345
- message: expect.stringContaining("credits"),
346
- }),
347
- { type: "closed" },
348
- ]);
349
- });
350
-
351
- test("stop during the initial dial tears down the session it raced", async () => {
352
- const adapter = new CadetManagedRealtimeTranscriber(CONNECTION);
353
- const { events, onEvent } = collector();
354
- const startPromise = adapter.start(onEvent);
355
-
356
- // Caller gives up while the handshake is still in flight.
357
- adapter.stop();
358
- expect(events).toEqual([{ type: "closed" }]);
359
-
360
- // The dial still resolves — the opened session must be stopped, not
361
- // kept alive to meter against tunnel.
362
- sockets[0]!.simulateOpen();
363
- await startPromise;
364
- expect(
365
- sockets[0]!.sentData.some((d) => String(d).includes("CloseStream")),
366
- ).toBe(true);
367
- expect(events).toEqual([{ type: "closed" }]);
368
- });
369
-
370
- test("stop during a re-dial closes exactly once", async () => {
371
- const { adapter, events } = await startAdapter();
372
-
373
- sockets[0]!.simulateMessage(tunnelErrorFrame("session_duration_exceeded"));
374
- sockets[0]!.simulateClose(1000, "session_duration_exceeded");
375
-
376
- adapter.stop();
377
- await tick();
378
- if (sockets.length > 1) {
379
- sockets[1]!.simulateOpen();
380
- await tick();
381
- }
382
-
383
- expect(events.filter((e) => e.type === "closed")).toHaveLength(1);
384
- expect(events.filter((e) => e.type === "error")).toHaveLength(0);
385
- });
386
-
387
- test("a failed dial surfaces tunnel's HTTP rejection via the probe", async () => {
388
- globalThis.fetch = (async () =>
389
- new Response(
390
- JSON.stringify({
391
- code: "insufficient_balance",
392
- detail: "balance is 0",
393
- }),
394
- { status: 402 },
395
- )) as unknown as typeof fetch;
396
-
397
- const adapter = new CadetManagedRealtimeTranscriber(CONNECTION);
398
- const startPromise = adapter.start(() => {});
399
- sockets[0]!.simulateClose(1006, "");
400
-
401
- await expect(startPromise).rejects.toThrow(/credits/);
402
- });
403
-
404
- test("an auth rejection at dial time keeps its category through the throw", async () => {
405
- globalThis.fetch = (async () =>
406
- new Response(JSON.stringify({ code: "invalid_key", detail: "bad" }), {
407
- status: 401,
408
- })) as unknown as typeof fetch;
409
-
410
- const adapter = new CadetManagedRealtimeTranscriber(CONNECTION);
411
- const startPromise = adapter.start(() => {});
412
- sockets[0]!.simulateClose(1006, "");
413
-
414
- let thrown: unknown;
415
- try {
416
- await startPromise;
417
- } catch (err) {
418
- thrown = err;
419
- }
420
- expect(thrown).toBeInstanceOf(SttError);
421
- expect((thrown as SttError).category).toBe("auth");
422
- });
423
-
424
- test("connect failures never leak the API key", async () => {
425
- globalThis.fetch = (async () => {
426
- throw new Error("refused");
427
- }) as unknown as typeof fetch;
428
-
429
- const adapter = new CadetManagedRealtimeTranscriber(CONNECTION);
430
- const startPromise = adapter.start(() => {});
431
- // Bun embeds the dialed URL (which carries ?key= under query auth) in
432
- // connection-failure details; the adapter must redact it everywhere.
433
- sockets[0]!.simulateClose(1006, `connect failed: ${sockets[0]!.url}`);
434
-
435
- let message = "";
436
- try {
437
- await startPromise;
438
- } catch (err) {
439
- message = (err as Error).message;
440
- }
441
- expect(message).not.toBe("");
442
- expect(message).not.toContain("vk-secret");
443
- expect(message).toContain("key=***");
444
- });
445
-
446
- test("a failed dial with no HTTP rejection keeps the transport error", async () => {
447
- globalThis.fetch = (async () => {
448
- throw new Error("connection refused");
449
- }) as unknown as typeof fetch;
450
-
451
- const adapter = new CadetManagedRealtimeTranscriber(CONNECTION);
452
- const startPromise = adapter.start(() => {});
453
- sockets[0]!.simulateClose(1006, "");
454
-
455
- await expect(startPromise).rejects.toThrow(/closed before open/);
456
- });
457
- });