@cartanova/qgrid-cli 2.18.0 → 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 (42) 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 +28 -43
  5. package/bundle/dist/application/qgrid/qgrid.types.js +4 -4
  6. package/bundle/dist/startup-migrations.js +1 -1
  7. package/bundle/dist/utils/providers/common/schema-validation.js +2 -2
  8. package/bundle/dist/utils/providers/grok/grok-voice-client.js +10 -5
  9. package/bundle/dist/utils/speech-aligner.js +302 -0
  10. package/bundle/dist/utils/speech-alignment.js +2 -102
  11. package/bundle/src/application/qgrid/qgrid.frame.test.ts +56 -17
  12. package/bundle/src/application/qgrid/qgrid.frame.ts +38 -50
  13. package/bundle/src/application/qgrid/qgrid.types.ts +14 -11
  14. package/bundle/src/utils/providers/common/schema-validation.ts +1 -1
  15. package/bundle/src/utils/providers/grok/grok-voice-client.test.ts +4 -3
  16. package/bundle/src/utils/providers/grok/grok-voice-client.ts +13 -1
  17. package/bundle/src/utils/speech-aligner.test.ts +100 -0
  18. package/bundle/src/utils/speech-aligner.ts +435 -0
  19. package/bundle/src/utils/speech-alignment.test.ts +2 -50
  20. package/bundle/src/utils/speech-alignment.ts +1 -141
  21. package/bundle/web-dist/client/assets/{index-CbElySnT.js → index-DYYtV8Qx.js} +3 -3
  22. package/bundle/web-dist/client/assets/{logs-BJZmjJan.js → logs-CbDtQif1.js} +1 -1
  23. package/bundle/web-dist/client/assets/{monit-CO4TQDhe.js → monit-DtW8o_yF.js} +1 -1
  24. package/bundle/web-dist/client/assets/{routes-D_pSsIQS.js → routes-Dw227enb.js} +1 -1
  25. package/bundle/web-dist/client/assets/{settings-LKaZCi07.js → settings-BXmAToY1.js} +1 -1
  26. package/bundle/web-dist/client/assets/{show-BvATehjq.js → show-5qj6wFgp.js} +2 -2
  27. package/bundle/web-dist/client/assets/{tokens-D5KX_VAe.js → tokens-D8L8AC4v.js} +1 -1
  28. package/bundle/web-dist/client/assets/{use-oauth-login-flow-DcqeDFdp.js → use-oauth-login-flow-BcEUkszt.js} +1 -1
  29. package/bundle/web-dist/client/assets/{use-update-token-mutation-IqmKULKf.js → use-update-token-mutation-Ca0n_WnM.js} +1 -1
  30. package/bundle/web-dist/client/assets/voice-D-c1Eyp3.js +1 -0
  31. package/bundle/web-dist/client/index.html +1 -1
  32. package/bundle/web-dist/server/assets/{show-B_l5dOcT.js → show-CnLDFCtW.js} +2 -5
  33. package/bundle/web-dist/server/assets/{voice-BhVkiSJl.js → voice-BvAl-vTr.js} +12 -6
  34. package/bundle/web-dist/server/entry-server.generated.js +3 -3
  35. package/dist/cli.js +141 -3
  36. package/package.json +1 -1
  37. package/skills/qgrid/references/cli-env-and-server-boot.md +1 -0
  38. package/skills/qgrid/references/grok-runtime.md +3 -3
  39. package/skills/qgrid/references/openai-codex-runtime.md +2 -0
  40. package/skills/qgrid/references/request-log-run-lifecycle.md +1 -1
  41. package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
  42. package/bundle/web-dist/client/assets/voice-BvjMZbB5.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.
@@ -1260,32 +1255,29 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
1260
1255
  // pcm output is always 24 kHz PCM16, so the log copy is wrapped as WAV to stay playable.
1261
1256
  const wav = mediaType === "audio/wav" ? audio : wrapPcmAsWav(audio);
1262
1257
  const logAudio = mediaType === "audio/wav" ? output.audio : Buffer.from(wav).toString("base64");
1263
- let alignment: Awaited<ReturnType<typeof alignOpenAISpeech>> | undefined;
1258
+ let alignMs: number | undefined;
1264
1259
 
1265
1260
  if (input.withTimestamps) {
1261
+ // Realtime speech carries no timing: the in-process aligner places the script in the audio.
1266
1262
  try {
1267
- alignment = await alignOpenAISpeech(wav, input.text, signal);
1268
- output.audioTimestamps = alignment.audioTimestamps;
1269
- 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;
1270
1268
  output.timestampsSource = "aligned";
1269
+ alignMs = Math.round(performance.now() - alignStart);
1271
1270
  } catch (error) {
1272
1271
  // The speech itself succeeded; timing is best-effort and its failure is reported, not thrown.
1273
1272
  output.timestampsError = error instanceof Error ? error.message : String(error);
1274
1273
  }
1275
1274
  }
1276
1275
 
1277
- const speechCost = openaiSpeechCost(id, usage);
1278
-
1279
- // The alignment pass is a Grok STT call over the same audio, priced with the speech.
1280
- const alignCost = alignment
1281
- ? (sttCost(`grok/${GROK_STT_DEFAULT_MODEL}`, alignment.durationSec)?.costUsd ?? 0)
1282
- : 0;
1283
-
1284
1276
  const log: MediaRunLog = {
1285
1277
  tokenName: output.tokenName,
1286
1278
  response: audioForLog(logAudio, "audio/wav", audio.byteLength),
1287
1279
  firstOutputAt: firstAudioAt,
1288
- cost: speechCost && { ...speechCost, costUsd: speechCost.costUsd + alignCost },
1280
+ cost: openaiSpeechCost(id, usage),
1289
1281
  steps: [
1290
1282
  {
1291
1283
  toolCallId: "speech:0",
@@ -1304,14 +1296,10 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
1304
1296
  audioBytes: audio.byteLength,
1305
1297
  transcript,
1306
1298
  usage,
1307
- alignment: alignment && {
1308
- heard: alignment.heard,
1309
- matchedWords: alignment.matchedWords,
1310
- scriptWords: alignment.scriptWords,
1311
- },
1299
+ alignMs,
1312
1300
  timestampsError: output.timestampsError,
1313
1301
  // Word timing for the request-log detail player.
1314
- words: alignment && wordsFromCharTimestamps(alignment.audioTimestamps),
1302
+ words: output.audioTimestamps && wordsFromCharTimestamps(output.audioTimestamps),
1315
1303
  }),
1316
1304
  },
1317
1305
  ],
@@ -2328,7 +2316,7 @@ class QgridFrameClass extends BaseFrameClass {
2328
2316
  text: output.text,
2329
2317
  language: output.language,
2330
2318
  durationSec: output.durationSec,
2331
- // Word timing of the input audio for the request-log detail player.
2319
+ // Word timing of the input audio, as returned to the caller.
2332
2320
  words: output.words,
2333
2321
  }),
2334
2322
  },
@@ -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
 
@@ -561,8 +564,8 @@ export const SpeakInput = z.object({
561
564
  // Grok only: speaking rate, xAI's documented 0.7–1.5 (1 = normal).
562
565
  speed: z.number().min(0.7).max(1.5).optional(),
563
566
  // Per-character timing in the output (`audioTimestamps`). Grok returns it natively; for OpenAI
564
- // realtime (no timing data) qgrid transcribes the generated audio with Grok STT and aligns the
565
- // 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`).
566
569
  withTimestamps: z.boolean().optional(),
567
570
  ...MediaCallOptions,
568
571
  });
@@ -584,8 +587,8 @@ export const SpeakOutput = z.object({
584
587
  })
585
588
  .optional(),
586
589
  durationSec: z.number().optional(),
587
- // "provider" when the TTS provider timed the audio itself, "aligned" when qgrid inferred it from
588
- // 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.
589
592
  timestampsSource: z.enum(["provider", "aligned"]).optional(),
590
593
  // Set when timestamps were requested but could not be produced; the audio is still returned.
591
594
  timestampsError: z.string().optional(),
@@ -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,
@@ -230,7 +230,7 @@ describe("GrokVoiceClient.speak", () => {
230
230
  });
231
231
  });
232
232
 
233
- 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 () => {
234
234
  const fake = fakeFetch(
235
235
  () =>
236
236
  new Response(
@@ -251,11 +251,12 @@ describe("GrokVoiceClient.speak", () => {
251
251
  expect(result.audio).toEqual(mp3);
252
252
  expect(result.mediaType).toBe("audio/mpeg");
253
253
  expect(result.durationSec).toBe(0.5);
254
+ // +46 ms: the mp3 decoder delay (1105 samples at 24 kHz).
254
255
  expect(result.audioTimestamps).toEqual({
255
256
  graphChars: ["H", "i"],
256
257
  graphTimes: [
257
- [0.08, 0.2],
258
- [0.2, 0.5],
258
+ [0.126, 0.246],
259
+ [0.246, 0.546],
259
260
  ],
260
261
  });
261
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
 
@@ -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
+ });