@cartanova/qgrid-cli 2.17.1 → 2.19.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 (53) hide show
  1. package/README.ko.md +26 -0
  2. package/README.md +29 -0
  3. package/bundle/dist/_virtual/_rolldown/runtime.js +1 -0
  4. package/bundle/dist/application/qgrid/qgrid.frame.js +32 -44
  5. package/bundle/dist/application/qgrid/qgrid.types.js +5 -4
  6. package/bundle/dist/startup-migrations.js +1 -1
  7. package/bundle/dist/utils/providers/common/model-cost.js +10 -18
  8. package/bundle/dist/utils/providers/common/schema-validation.js +2 -2
  9. package/bundle/dist/utils/providers/grok/grok-types.js +3 -2
  10. package/bundle/dist/utils/providers/grok/grok-voice-client.js +12 -6
  11. package/bundle/dist/utils/providers/openai/openai-dispatcher.js +3 -2
  12. package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +4 -8
  13. package/bundle/dist/utils/speech-aligner.js +302 -0
  14. package/bundle/dist/utils/speech-alignment.js +2 -102
  15. package/bundle/src/application/qgrid/qgrid.frame.test.ts +56 -17
  16. package/bundle/src/application/qgrid/qgrid.frame.ts +46 -50
  17. package/bundle/src/application/qgrid/qgrid.types.ts +16 -11
  18. package/bundle/src/application/sonamu.generated.http +1 -0
  19. package/bundle/src/utils/providers/common/model-cost.ts +0 -1
  20. package/bundle/src/utils/providers/common/schema-validation.ts +1 -1
  21. package/bundle/src/utils/providers/grok/grok-types.ts +1 -0
  22. package/bundle/src/utils/providers/grok/grok-voice-client.test.ts +7 -4
  23. package/bundle/src/utils/providers/grok/grok-voice-client.ts +14 -1
  24. package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +18 -0
  25. package/bundle/src/utils/providers/openai/openai-dispatcher.ts +6 -1
  26. package/bundle/src/utils/providers/openai/openai-realtime-protocol.ts +3 -7
  27. package/bundle/src/utils/speech-aligner.test.ts +100 -0
  28. package/bundle/src/utils/speech-aligner.ts +435 -0
  29. package/bundle/src/utils/speech-alignment.test.ts +2 -50
  30. package/bundle/src/utils/speech-alignment.ts +1 -141
  31. package/bundle/web-dist/client/assets/{index-D56cIqxW.js → index-DYYtV8Qx.js} +3 -3
  32. package/bundle/web-dist/client/assets/{logs-pMW62Hvw.js → logs-CbDtQif1.js} +1 -1
  33. package/bundle/web-dist/client/assets/{monit-COC4S7gf.js → monit-DtW8o_yF.js} +1 -1
  34. package/bundle/web-dist/client/assets/{routes-C38qmify.js → routes-Dw227enb.js} +1 -1
  35. package/bundle/web-dist/client/assets/{settings-BWGSVpiQ.js → settings-BXmAToY1.js} +1 -1
  36. package/bundle/web-dist/client/assets/{show-aQTLNz5k.js → show-5qj6wFgp.js} +2 -2
  37. package/bundle/web-dist/client/assets/{tokens-Ha8SwMPG.js → tokens-D8L8AC4v.js} +1 -1
  38. package/bundle/web-dist/client/assets/{use-oauth-login-flow-JoEnKQis.js → use-oauth-login-flow-BcEUkszt.js} +1 -1
  39. package/bundle/web-dist/client/assets/{use-update-token-mutation-cdCVcOY5.js → use-update-token-mutation-Ca0n_WnM.js} +1 -1
  40. package/bundle/web-dist/client/assets/voice-D-c1Eyp3.js +1 -0
  41. package/bundle/web-dist/client/index.html +1 -1
  42. package/bundle/web-dist/server/assets/{show-B_l5dOcT.js → show-CnLDFCtW.js} +2 -5
  43. package/bundle/web-dist/server/assets/{voice-CHoPEIfo.js → voice-BvAl-vTr.js} +32 -8
  44. package/bundle/web-dist/server/entry-server.generated.js +3 -3
  45. package/dist/cli.js +141 -3
  46. package/package.json +1 -1
  47. package/skills/qgrid/references/ai-sdk-provider-contract.md +1 -1
  48. package/skills/qgrid/references/cli-env-and-server-boot.md +1 -0
  49. package/skills/qgrid/references/grok-runtime.md +5 -3
  50. package/skills/qgrid/references/openai-codex-runtime.md +3 -1
  51. package/skills/qgrid/references/request-log-run-lifecycle.md +1 -1
  52. package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
  53. package/bundle/web-dist/client/assets/voice-COmvUTZO.js +0 -1
@@ -85,10 +85,12 @@ import {
85
85
  OPENAI_REALTIME_DEFAULT_TRANSCRIPTION_MODEL,
86
86
  OPENAI_REALTIME_DEFAULT_VOICE,
87
87
  OPENAI_REALTIME_SAMPLE_RATE,
88
+ prepareRealtimeInput,
88
89
  wrapPcmAsWav,
89
90
  } from "../../utils/providers/openai/openai-realtime-protocol";
90
91
  import { OpenAIVoiceInputError } from "../../utils/providers/openai/openai-voice-client";
91
- import { alignScriptToWords, wordsFromCharTimestamps } from "../../utils/speech-alignment";
92
+ import { alignSpeech } from "../../utils/speech-aligner";
93
+ import { wordsFromCharTimestamps } from "../../utils/speech-alignment";
92
94
  import {
93
95
  type FinishRunParams,
94
96
  MICRO_USD,
@@ -1143,6 +1145,20 @@ async function transcribeOpenAI(input: TranscribeInput): Promise<TranscribeOutpu
1143
1145
  if (input.language) output.language = input.language;
1144
1146
 
1145
1147
  if (requestLogId !== undefined) output.requestLogId = requestLogId;
1148
+ let alignMs: number | undefined;
1149
+ let wordsError: string | undefined;
1150
+
1151
+ // Realtime transcription carries no timing: the in-process aligner places the transcript in the
1152
+ // input audio. Best-effort like speech timing: without it the transcript returns with no words.
1153
+ try {
1154
+ const alignStart = performance.now();
1155
+ const pcm = prepareRealtimeInput(audio, input.mediaType);
1156
+ const timestamps = await alignSpeech(pcm, OPENAI_REALTIME_SAMPLE_RATE, text);
1157
+ output.words = wordsFromCharTimestamps(timestamps);
1158
+ alignMs = Math.round(performance.now() - alignStart);
1159
+ } catch (error) {
1160
+ wordsError = error instanceof Error ? error.message : String(error);
1161
+ }
1146
1162
 
1147
1163
  const log: MediaRunLog = {
1148
1164
  tokenName: output.tokenName,
@@ -1162,7 +1178,15 @@ async function transcribeOpenAI(input: TranscribeInput): Promise<TranscribeOutpu
1162
1178
  prompt: input.prompt,
1163
1179
  durationSec,
1164
1180
  },
1165
- result: JSON.stringify({ text, durationSec, callId }),
1181
+ result: JSON.stringify({
1182
+ text,
1183
+ durationSec,
1184
+ callId,
1185
+ alignMs,
1186
+ wordsError,
1187
+ // Word timing of the input audio, as returned to the caller.
1188
+ words: output.words,
1189
+ }),
1166
1190
  },
1167
1191
  ],
1168
1192
  };
@@ -1171,35 +1195,6 @@ async function transcribeOpenAI(input: TranscribeInput): Promise<TranscribeOutpu
1171
1195
  });
1172
1196
  }
1173
1197
 
1174
- /**
1175
- * OpenAI realtime speech carries no timing, so the generated audio is transcribed with Grok STT and
1176
- * the heard words are aligned to the script (`alignScriptToWords`). The Grok call goes through the
1177
- * Grok dispatcher on an automatically selected token, like any Grok STT request.
1178
- */
1179
- async function alignOpenAISpeech(wav: Uint8Array, script: string, signal: AbortSignal) {
1180
- const selection = await resolveGrokTokenSelection(undefined);
1181
-
1182
- const dispatched = await grokVoice().transcribe({
1183
- audio: wav,
1184
- mediaType: "audio/wav",
1185
- model: GROK_STT_DEFAULT_MODEL,
1186
- signal,
1187
- ...selection,
1188
- });
1189
-
1190
- const words = dispatched.result.words ?? [];
1191
-
1192
- if (words.length === 0) throw new Error("Grok STT returned no word timing");
1193
- // 44-byte WAV header, PCM16 mono at the realtime sample rate.
1194
- const durationSec = (wav.byteLength - 44) / (2 * OPENAI_REALTIME_SAMPLE_RATE);
1195
-
1196
- return {
1197
- ...alignScriptToWords(script, words, durationSec),
1198
- durationSec,
1199
- heard: dispatched.result.text,
1200
- };
1201
- }
1202
-
1203
1198
  /**
1204
1199
  * OpenAI realtime speech (openai/<id>): a conversational realtime model repeating the text over
1205
1200
  * the direct realtime socket. Output is PCM16 24 kHz, wrapped as WAV unless `format` is pcm.
@@ -1222,6 +1217,12 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
1222
1217
  );
1223
1218
  }
1224
1219
 
1220
+ if (input.speed !== undefined) {
1221
+ throw new BadRequestException(
1222
+ SD("qgrid.openaiVoiceInvalidRequest")("speed is available only on Grok speech"),
1223
+ );
1224
+ }
1225
+
1225
1226
  const request = {
1226
1227
  text: input.text,
1227
1228
  model: id,
@@ -1254,32 +1255,29 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
1254
1255
  // pcm output is always 24 kHz PCM16, so the log copy is wrapped as WAV to stay playable.
1255
1256
  const wav = mediaType === "audio/wav" ? audio : wrapPcmAsWav(audio);
1256
1257
  const logAudio = mediaType === "audio/wav" ? output.audio : Buffer.from(wav).toString("base64");
1257
- let alignment: Awaited<ReturnType<typeof alignOpenAISpeech>> | undefined;
1258
+ let alignMs: number | undefined;
1258
1259
 
1259
1260
  if (input.withTimestamps) {
1261
+ // Realtime speech carries no timing: the in-process aligner places the script in the audio.
1260
1262
  try {
1261
- alignment = await alignOpenAISpeech(wav, input.text, signal);
1262
- output.audioTimestamps = alignment.audioTimestamps;
1263
- output.durationSec = alignment.durationSec;
1263
+ const alignStart = performance.now();
1264
+ // 44-byte WAV header (wrapPcmAsWav), then PCM16 mono at the realtime sample rate.
1265
+ const pcm = wav.subarray(44);
1266
+ output.audioTimestamps = await alignSpeech(pcm, OPENAI_REALTIME_SAMPLE_RATE, input.text);
1267
+ output.durationSec = pcm.byteLength / 2 / OPENAI_REALTIME_SAMPLE_RATE;
1264
1268
  output.timestampsSource = "aligned";
1269
+ alignMs = Math.round(performance.now() - alignStart);
1265
1270
  } catch (error) {
1266
1271
  // The speech itself succeeded; timing is best-effort and its failure is reported, not thrown.
1267
1272
  output.timestampsError = error instanceof Error ? error.message : String(error);
1268
1273
  }
1269
1274
  }
1270
1275
 
1271
- const speechCost = openaiSpeechCost(id, usage);
1272
-
1273
- // The alignment pass is a Grok STT call over the same audio, priced with the speech.
1274
- const alignCost = alignment
1275
- ? (sttCost(`grok/${GROK_STT_DEFAULT_MODEL}`, alignment.durationSec)?.costUsd ?? 0)
1276
- : 0;
1277
-
1278
1276
  const log: MediaRunLog = {
1279
1277
  tokenName: output.tokenName,
1280
1278
  response: audioForLog(logAudio, "audio/wav", audio.byteLength),
1281
1279
  firstOutputAt: firstAudioAt,
1282
- cost: speechCost && { ...speechCost, costUsd: speechCost.costUsd + alignCost },
1280
+ cost: openaiSpeechCost(id, usage),
1283
1281
  steps: [
1284
1282
  {
1285
1283
  toolCallId: "speech:0",
@@ -1298,14 +1296,10 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
1298
1296
  audioBytes: audio.byteLength,
1299
1297
  transcript,
1300
1298
  usage,
1301
- alignment: alignment && {
1302
- heard: alignment.heard,
1303
- matchedWords: alignment.matchedWords,
1304
- scriptWords: alignment.scriptWords,
1305
- },
1299
+ alignMs,
1306
1300
  timestampsError: output.timestampsError,
1307
1301
  // Word timing for the request-log detail player.
1308
- words: alignment && wordsFromCharTimestamps(alignment.audioTimestamps),
1302
+ words: output.audioTimestamps && wordsFromCharTimestamps(output.audioTimestamps),
1309
1303
  }),
1310
1304
  },
1311
1305
  ],
@@ -2322,7 +2316,7 @@ class QgridFrameClass extends BaseFrameClass {
2322
2316
  text: output.text,
2323
2317
  language: output.language,
2324
2318
  durationSec: output.durationSec,
2325
- // Word timing of the input audio for the request-log detail player.
2319
+ // Word timing of the input audio, as returned to the caller.
2326
2320
  words: output.words,
2327
2321
  }),
2328
2322
  },
@@ -2350,6 +2344,7 @@ class QgridFrameClass extends BaseFrameClass {
2350
2344
  language: input.language ?? GROK_TTS_DEFAULT_LANGUAGE,
2351
2345
  format: input.format ?? GROK_TTS_DEFAULT_FORMAT,
2352
2346
  with_timestamps: input.withTimestamps,
2347
+ speed: input.speed,
2353
2348
  };
2354
2349
 
2355
2350
  const start = {
@@ -2396,6 +2391,7 @@ class QgridFrameClass extends BaseFrameClass {
2396
2391
  language: request.language,
2397
2392
  format: request.format,
2398
2393
  withTimestamps: input.withTimestamps,
2394
+ speed: input.speed,
2399
2395
  characters: input.text.length,
2400
2396
  },
2401
2397
  result: JSON.stringify({
@@ -316,14 +316,16 @@ export type StreamEvents = z.infer<typeof StreamEvents>;
316
316
 
317
317
  const MiB = 1024 * 1024;
318
318
 
319
- // Fastify bodyLimit for every JSON request; sonamu.config.ts reads it from here.
320
- export const REQUEST_BODY_LIMIT_BYTES = 10 * MiB;
319
+ // Fastify bodyLimit for every JSON request; sonamu.config.ts reads it from here. Sized so a ~5 MB
320
+ // compressed recording still fits once a browser decodes it to the 24 kHz PCM16 WAV that OpenAI
321
+ // realtime transcription requires (19 MiB holds about 6.9 minutes).
322
+ export const REQUEST_BODY_LIMIT_BYTES = 26 * MiB;
321
323
 
322
- // Media rides inside that JSON body as base64 (4 chars per 3 bytes), so a 10 MiB body carries at
323
- // most 10 MiB x 3/4 = 7.5 MiB of decoded bytes; 0.5 MiB is left for the prompt, options and JSON
324
+ // Media rides inside that JSON body as base64 (4 chars per 3 bytes), so a 26 MiB body carries at
325
+ // most 26 MiB x 3/4 = 19.5 MiB of decoded bytes; 0.5 MiB is left for the prompt, options and JSON
324
326
  // framing. The same budget bounds the audio clip, each inline image, and the sum of a request's
325
327
  // inline images, so every request the schema accepts also fits the transport.
326
- export const MEDIA_MAX_INLINE_BYTES = 7 * MiB;
328
+ export const MEDIA_MAX_INLINE_BYTES = 19 * MiB;
327
329
  const MEDIA_MAX_INLINE_LABEL = `${MEDIA_MAX_INLINE_BYTES / MiB} MiB`;
328
330
  export const MEDIA_MAX_REFERENCE_IMAGES = 5;
329
331
 
@@ -543,8 +545,9 @@ export const TranscribeOutput = z.object({
543
545
  model: z.string(),
544
546
  tokenName: z.string(),
545
547
  requestLogId: z.number().optional(),
546
- // Grok only: each heard word with its [start, end] seconds. OpenAI realtime transcription
547
- // reports no timing.
548
+ // Each heard word with its [start, end] seconds. Grok times its own transcript; for OpenAI qgrid's
549
+ // aligner places the transcript in the input audio (omitted without the aligner model, or when the
550
+ // clip is too long to align).
548
551
  words: z.array(TranscribedWord).optional(),
549
552
  });
550
553
 
@@ -558,9 +561,11 @@ export const SpeakInput = z.object({
558
561
  format: z.enum(["mp3", "wav", "pcm", "mulaw", "alaw"]).optional(),
559
562
  // OpenAI realtime speech only: style guidance appended to the verbatim-repeat instruction.
560
563
  instructions: z.string().min(1).max(2_000).optional(),
564
+ // Grok only: speaking rate, xAI's documented 0.7–1.5 (1 = normal).
565
+ speed: z.number().min(0.7).max(1.5).optional(),
561
566
  // Per-character timing in the output (`audioTimestamps`). Grok returns it natively; for OpenAI
562
- // realtime (no timing data) qgrid transcribes the generated audio with Grok STT and aligns the
563
- // heard words to the text (`timestampsSource: "aligned"`).
567
+ // realtime (no timing data) qgrid force-aligns the text to the generated audio with its built-in
568
+ // aligner (`timestampsSource: "aligned"`; without the aligner model, `timestampsError`).
564
569
  withTimestamps: z.boolean().optional(),
565
570
  ...MediaCallOptions,
566
571
  });
@@ -582,8 +587,8 @@ export const SpeakOutput = z.object({
582
587
  })
583
588
  .optional(),
584
589
  durationSec: z.number().optional(),
585
- // "provider" when the TTS provider timed the audio itself, "aligned" when qgrid inferred it from
586
- // Grok STT word timing.
590
+ // "provider" when the TTS provider timed the audio itself, "aligned" when qgrid's aligner placed
591
+ // the text in the audio.
587
592
  timestampsSource: z.enum(["provider", "aligned"]).optional(),
588
593
  // Set when timestamps were requested but could not be produced; the audio is still returned.
589
594
  timestampsError: z.string().optional(),
@@ -723,6 +723,7 @@ Content-Type: application/json
723
723
  "language": "LANGUAGE",
724
724
  "format": "mp3",
725
725
  "instructions": "INSTRUCTIONS",
726
+ "speed": 0.7,
726
727
  "withTimestamps": false,
727
728
  "tokenName": "TOKENNAME",
728
729
  "projectName": "PROJECTNAME",
@@ -464,7 +464,6 @@ export type VoiceCost = { costUsd: number; costSource: "pricing_table"; ticks?:
464
464
  const OPENAI_SPEECH_PRICES = new Map([
465
465
  ["gpt-realtime-2.1", { textIn: 4, textOut: 24, audioOut: 64 }],
466
466
  ["gpt-realtime-2.1-mini", { textIn: 0.6, textOut: 2.4, audioOut: 20 }],
467
- ["gpt-realtime-1.5", { textIn: 4, textOut: 16, audioOut: 64 }],
468
467
  ]);
469
468
 
470
469
  // Transcription, USD per minute of audio (OpenAI's published per-minute estimates; Grok $0.10/hour).
@@ -7,7 +7,7 @@ import { isJsonObject, type JsonValue } from "./provider-types";
7
7
  /**
8
8
  * Caller-provided schemas are serialized, copied, and recursively normalized before dispatch.
9
9
  * Keep these limits comfortably above normal generated schemas while bounding that preprocessing
10
- * well below the API's 10 MiB request-body ceiling.
10
+ * well below the API's 26 MiB request-body ceiling.
11
11
  */
12
12
  export const CALLER_SCHEMA_LIMITS = {
13
13
  maxUtf8Bytes: 512 * 1024,
@@ -300,6 +300,7 @@ export const GrokTtsRequest = z.object({
300
300
  // true switches /tts to a JSON envelope with per-character timing (verified on the subscription
301
301
  // token 2026-11-09).
302
302
  with_timestamps: z.boolean().optional(),
303
+ speed: z.number().optional(),
303
304
  });
304
305
 
305
306
  export type GrokTtsRequest = z.infer<typeof GrokTtsRequest>;
@@ -208,7 +208,7 @@ describe("GrokVoiceClient.speak", () => {
208
208
  });
209
209
  });
210
210
 
211
- it("passes explicit language and format and strips content-type parameters", async () => {
211
+ it("passes explicit language, format and speed and strips content-type parameters", async () => {
212
212
  const fake = fakeFetch(
213
213
  () =>
214
214
  new Response(mp3, { status: 200, headers: { "content-type": "audio/wav; codecs=1" } }),
@@ -219,16 +219,18 @@ describe("GrokVoiceClient.speak", () => {
219
219
  voice: "eve",
220
220
  language: "fr",
221
221
  format: "wav",
222
+ speed: 0.8,
222
223
  });
223
224
  expect(result.mediaType).toBe("audio/wav");
224
225
  const body = fake.calls[0]!.init.body;
225
226
  expect(typeof body === "string" && JSON.parse(body)).toMatchObject({
226
227
  language: "fr",
227
228
  format: "wav",
229
+ speed: 0.8,
228
230
  });
229
231
  });
230
232
 
231
- it("asks for timestamps and decodes the JSON envelope into audio plus character timing", async () => {
233
+ it("asks for timestamps and decodes the JSON envelope, shifting mp3 timing by the encoder delay", async () => {
232
234
  const fake = fakeFetch(
233
235
  () =>
234
236
  new Response(
@@ -249,11 +251,12 @@ describe("GrokVoiceClient.speak", () => {
249
251
  expect(result.audio).toEqual(mp3);
250
252
  expect(result.mediaType).toBe("audio/mpeg");
251
253
  expect(result.durationSec).toBe(0.5);
254
+ // +46 ms: the mp3 decoder delay (1105 samples at 24 kHz).
252
255
  expect(result.audioTimestamps).toEqual({
253
256
  graphChars: ["H", "i"],
254
257
  graphTimes: [
255
- [0.08, 0.2],
256
- [0.2, 0.5],
258
+ [0.126, 0.246],
259
+ [0.246, 0.546],
257
260
  ],
258
261
  });
259
262
  });
@@ -141,6 +141,11 @@ function invalidBodyError(response: Response, message: string, cause?: unknown):
141
141
  }
142
142
 
143
143
  /** Decodes the `with_timestamps` JSON envelope into audio bytes plus per-character timing. */
144
+ // LAME's 1105-sample encoder delay at the 24 kHz /tts output (SON-589 measured ~46-49 ms).
145
+ const MP3_DECODER_DELAY_SEC = 1105 / 24_000;
146
+
147
+ const roundMs = (seconds: number) => Math.round(seconds * 1000) / 1000;
148
+
144
149
  async function readTimestampsBody(
145
150
  response: Response,
146
151
  format: string,
@@ -166,9 +171,16 @@ async function readTimestampsBody(
166
171
  };
167
172
 
168
173
  if (parsed.audio_timestamps) {
174
+ // Timing refers to the audio before mp3 encoding. The mp3 has no gapless tag, so decoders keep
175
+ // the encoder delay and play the speech later; shift the timing to match what plays.
176
+ const shift = result.mediaType === "audio/mpeg" ? MP3_DECODER_DELAY_SEC : 0;
177
+
169
178
  result.audioTimestamps = {
170
179
  graphChars: parsed.audio_timestamps.graph_chars,
171
- graphTimes: parsed.audio_timestamps.graph_times,
180
+ graphTimes: parsed.audio_timestamps.graph_times.map(([start, end]): [number, number] => [
181
+ roundMs(start + shift),
182
+ roundMs(end + shift),
183
+ ]),
172
184
  };
173
185
  }
174
186
 
@@ -255,6 +267,7 @@ export class GrokVoiceClient implements GrokVoicePort {
255
267
  language: request.language ?? GROK_TTS_DEFAULT_LANGUAGE,
256
268
  format: request.format ?? GROK_TTS_DEFAULT_FORMAT,
257
269
  with_timestamps: request.with_timestamps,
270
+ speed: request.speed,
258
271
  });
259
272
 
260
273
  const headers = {
@@ -251,6 +251,24 @@ describe("OpenAIDispatcher direct runtime", () => {
251
251
  expect(fetchMock).toHaveBeenCalledTimes(2);
252
252
  });
253
253
 
254
+ it("re-judges a token updated during its quota lookup instead of reporting it over quota", async () => {
255
+ let finishOld!: (value: Response) => void;
256
+ const quota = (percent: number) => new Response(JSON.stringify({
257
+ rate_limits: { primary_window: { used_percent: percent } },
258
+ }));
259
+ const fetchMock = vi.fn()
260
+ .mockImplementationOnce(() => new Promise((resolve) => { finishOld = resolve; }))
261
+ .mockResolvedValueOnce(quota(65));
262
+ const d = new OpenAIDispatcher(config(), { fetch: fetchMock });
263
+ await d.onTokenAdded(1, "one", credentials, 100);
264
+ const selection = d.selectToken(1, true, new AbortController().signal);
265
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
266
+ await d.onTokenUpdated(1, "one", { ...credentials, accessToken: "refreshed" }, 100);
267
+ finishOld(quota(65));
268
+ await expect(selection).resolves.toMatchObject({ tokenId: 1 });
269
+ expect(fetchMock).toHaveBeenCalledTimes(2);
270
+ });
271
+
254
272
  it("rejects unsupported image backgrounds", () => {
255
273
  expect(QueryInput.safeParse({
256
274
  prompt: "a circle", imageGeneration: true,
@@ -1075,8 +1075,13 @@ export class OpenAIDispatcher implements ProviderDispatcher {
1075
1075
  if (token.quotaThreshold === null || token.quotaThreshold === undefined) return true;
1076
1076
  const generation = token.generation;
1077
1077
  const result = await readOpenAIQuotaUsage(async () => this.getRateLimitsByTokenId(id, signal));
1078
+ const current = this.tokenMetadata.get(id);
1078
1079
 
1079
- if (this.tokenMetadata.get(id) !== token || token.generation !== generation) return false;
1080
+ // A token update (credential refresh, sync) landed mid-lookup: judge the updated token
1081
+ // instead of reporting it over quota.
1082
+ if (current !== token || token.generation !== generation) {
1083
+ return current?.active ? this.isQuotaEligible(id, current, signal) : false;
1084
+ }
1080
1085
 
1081
1086
  if (result.kind === "lookup_failed") {
1082
1087
  this.quotaBlocked.delete(id);
@@ -76,14 +76,10 @@ export const OPENAI_TRANSCRIPTION_MODELS_WITHOUT_PROMPT: ReadonlySet<string> = n
76
76
 
77
77
  /**
78
78
  * Text-to-speech (realtime conversational) ids. Verbatim fidelity on the 2026-10-17 matrix:
79
- * gpt-realtime-2.1-mini 13/13, gpt-realtime-2.1 12/13 (one paraphrase), gpt-realtime-1.5 6/13
80
- * (often answers the text instead of repeating it). Default stays 2.1-mini.
79
+ * gpt-realtime-2.1-mini 13/13, gpt-realtime-2.1 12/13 (one paraphrase). Default stays 2.1-mini.
80
+ * gpt-realtime-1.5 was removed on 2026-11-09: it answered the text instead of repeating it (6/13).
81
81
  */
82
- export const OPENAI_SPEECH_MODELS = [
83
- "gpt-realtime-2.1-mini",
84
- "gpt-realtime-2.1",
85
- "gpt-realtime-1.5",
86
- ] as const;
82
+ export const OPENAI_SPEECH_MODELS = ["gpt-realtime-2.1-mini", "gpt-realtime-2.1"] as const;
87
83
 
88
84
  /**
89
85
  * A minimal Opus-only SDP offer. Codex sends a real WebRTC offer; qgrid has no RTP peer and only
@@ -0,0 +1,100 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+
3
+ import {
4
+ alignSpeech,
5
+ charTimestamps,
6
+ forcedAlign,
7
+ scriptTargets,
8
+ SpeechAlignerUnavailableError,
9
+ } from "./speech-aligner";
10
+
11
+ const BLANK = 0;
12
+ const H = 18;
13
+ const I = 5;
14
+ const STAR = 31;
15
+
16
+ /** Emission rows (log-probabilities) where each frame strongly favours the given class. */
17
+ function frames(...classes: number[]): Float64Array[] {
18
+ return classes.map((favoured) => {
19
+ const row = new Float64Array(32).fill(Math.log(0.001));
20
+ row[favoured] = Math.log(0.97);
21
+ row[STAR] = 0;
22
+
23
+ return row;
24
+ });
25
+ }
26
+
27
+ describe("scriptTargets", () => {
28
+ it("spells Latin letters, romanizes Hangul, strips accents, and stars digit runs", () => {
29
+ expect(scriptTargets(Array.from("Hi 쿠마")).ids).toEqual([H, I, 14, 9, 13, 4]);
30
+ expect(scriptTargets(Array.from("café")).ids).toEqual([23, 4, 27, 6]);
31
+
32
+ const twentyFirst = scriptTargets(Array.from("21st"));
33
+ expect(twentyFirst.ids).toEqual([STAR, 11, 10]);
34
+ expect(twentyFirst.owners[0]).toEqual([0, 1]);
35
+
36
+ // Silent punctuation keeps one star over "3:30"; whitespace ends a run.
37
+ expect(scriptTargets(Array.from("3:30")).owners).toEqual([[0, 2, 3]]);
38
+ expect(scriptTargets(Array.from("1 2")).ids).toEqual([STAR, STAR]);
39
+ });
40
+ });
41
+
42
+ describe("forcedAlign", () => {
43
+ it("walks the script's tokens through the frames in order", () => {
44
+ expect(forcedAlign(frames(BLANK, H, H, I, BLANK), [H, I])).toEqual([
45
+ [1, 3],
46
+ [3, 4],
47
+ ]);
48
+ });
49
+
50
+ it("refuses audio too long for the script with the limit in seconds", () => {
51
+ const longClip = Array.from({ length: 20_000 }, () => new Float64Array(32));
52
+ const script = Array.from({ length: 3_000 }, () => H);
53
+
54
+ expect(() => forcedAlign(longClip, script)).toThrow(/up to \d+ s of audio/);
55
+ });
56
+
57
+ it("lets a leading star absorb speech before the script", () => {
58
+ // The audio says "hi" twice; the script is the second "hi".
59
+ const emissions = frames(H, I, BLANK, BLANK, H, I);
60
+ const [, h, i] = forcedAlign(emissions, [STAR, H, I]);
61
+
62
+ expect([h, i]).toEqual([
63
+ [4, 5],
64
+ [5, 6],
65
+ ]);
66
+ });
67
+ });
68
+
69
+ describe("charTimestamps", () => {
70
+ it("keeps words contiguous, gives spaces the pause, and splits a star over its digits", () => {
71
+ const chars = Array.from("hi, 21");
72
+ const owners = [[0], [1], [4, 5]];
73
+ const spans: Array<[number, number]> = [
74
+ [0, 1],
75
+ [2, 3],
76
+ [6, 10],
77
+ ];
78
+
79
+ expect(charTimestamps(chars, owners, spans, 0.1, 1.2).graphTimes).toEqual([
80
+ [0, 0.2], // h runs until i starts
81
+ [0.2, 0.3],
82
+ [0.3, 0.3], // comma: zero length after "i"
83
+ [0.3, 0.6], // space: the pause to the next word
84
+ [0.6, 0.8],
85
+ [0.8, 1],
86
+ ]);
87
+ });
88
+ });
89
+
90
+ describe("alignSpeech", () => {
91
+ afterEach(() => vi.unstubAllEnvs());
92
+
93
+ it("reports a missing model as unavailable", async () => {
94
+ vi.stubEnv("QGRID_ALIGNER_MODEL", "/nonexistent/mms-300m-fa-int8.onnx");
95
+
96
+ await expect(alignSpeech(new Uint8Array(4800), 24_000, "hi")).rejects.toBeInstanceOf(
97
+ SpeechAlignerUnavailableError,
98
+ );
99
+ });
100
+ });