@cartanova/qgrid-cli 2.15.4 → 2.16.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 (135) hide show
  1. package/bundle/dist/application/qgrid/qgrid.frame.js +43 -13
  2. package/bundle/dist/application/qgrid/qgrid.types.js +8 -2
  3. package/bundle/dist/application/request-log/request-log.model.js +4 -3
  4. package/bundle/dist/application/sonamu.generated.js +20 -5
  5. package/bundle/dist/application/sonamu.generated.sso.js +5 -3
  6. package/bundle/dist/i18n/sd.generated.js +6 -1
  7. package/bundle/dist/migrations/20261109110340_alter_request_logs_add1_alter1.js +15 -0
  8. package/bundle/dist/utils/providers/grok/grok-types.js +3 -2
  9. package/bundle/dist/utils/providers/grok/grok-voice-client.js +38 -3
  10. package/bundle/dist/utils/providers/openai/openai-voice-client.js +6 -2
  11. package/bundle/src/application/qgrid/qgrid.frame.test.ts +62 -0
  12. package/bundle/src/application/qgrid/qgrid.frame.ts +78 -11
  13. package/bundle/src/application/qgrid/qgrid.types.ts +12 -0
  14. package/bundle/src/application/request-log/request-log.entity.json +17 -2
  15. package/bundle/src/application/request-log/request-log.model.test.ts +17 -0
  16. package/bundle/src/application/request-log/request-log.model.ts +11 -3
  17. package/bundle/src/application/sonamu.generated.http +3 -1
  18. package/bundle/src/application/sonamu.generated.sso.ts +2 -0
  19. package/bundle/src/application/sonamu.generated.ts +14 -0
  20. package/bundle/src/i18n/sd.generated.ts +6 -0
  21. package/bundle/src/migrations/20261109110340_alter_request_logs_add1_alter1.ts +15 -0
  22. package/bundle/src/utils/providers/grok/grok-types.ts +16 -0
  23. package/bundle/src/utils/providers/grok/grok-voice-client.test.ts +32 -0
  24. package/bundle/src/utils/providers/grok/grok-voice-client.ts +56 -0
  25. package/bundle/src/utils/providers/openai/openai-voice-client.test.ts +6 -0
  26. package/bundle/src/utils/providers/openai/openai-voice-client.ts +6 -0
  27. package/bundle/web-dist/client/assets/index-DyrPRt6O.css +1 -0
  28. package/bundle/web-dist/client/assets/{index-CRdZwZsw.js → index-SGfYBzGT.js} +34 -34
  29. package/bundle/web-dist/client/assets/{logs-DyLC_2Rf.js → logs-DrTz38re.js} +1 -1
  30. package/bundle/web-dist/client/assets/{monit-C0hO3Fy6.js → monit-klIY-HEI.js} +1 -1
  31. package/bundle/web-dist/client/assets/{routes-DTw4jsHI.js → routes-bGN3y2NW.js} +1 -1
  32. package/bundle/web-dist/client/assets/{settings-Dg-1zSMq.js → settings-BHwEvAZL.js} +1 -1
  33. package/bundle/web-dist/client/assets/{show-BmqUEs1O.js → show-BiJkyrfB.js} +2 -2
  34. package/bundle/web-dist/client/assets/{tokens-FQ82u55y.js → tokens-DMWMG9O5.js} +1 -1
  35. package/bundle/web-dist/client/assets/{use-oauth-login-flow-BXmbUSjc.js → use-oauth-login-flow-D1v4h9zA.js} +1 -1
  36. package/bundle/web-dist/client/assets/{use-update-token-mutation-BWlMl3qg.js → use-update-token-mutation-BVBUlqBN.js} +1 -1
  37. package/bundle/web-dist/client/assets/voice-CwD3asSF.js +1 -0
  38. package/bundle/web-dist/client/index.html +2 -2
  39. package/bundle/web-dist/client/voice-samples/grok/altair.mp3 +0 -0
  40. package/bundle/web-dist/client/voice-samples/grok/ara.mp3 +0 -0
  41. package/bundle/web-dist/client/voice-samples/grok/atlas.mp3 +0 -0
  42. package/bundle/web-dist/client/voice-samples/grok/aurora.mp3 +0 -0
  43. package/bundle/web-dist/client/voice-samples/grok/carina.mp3 +0 -0
  44. package/bundle/web-dist/client/voice-samples/grok/castor.mp3 +0 -0
  45. package/bundle/web-dist/client/voice-samples/grok/celeste.mp3 +0 -0
  46. package/bundle/web-dist/client/voice-samples/grok/cosmo.mp3 +0 -0
  47. package/bundle/web-dist/client/voice-samples/grok/eve.mp3 +0 -0
  48. package/bundle/web-dist/client/voice-samples/grok/helios.mp3 +0 -0
  49. package/bundle/web-dist/client/voice-samples/grok/helix.mp3 +0 -0
  50. package/bundle/web-dist/client/voice-samples/grok/iris.mp3 +0 -0
  51. package/bundle/web-dist/client/voice-samples/grok/kepler.mp3 +0 -0
  52. package/bundle/web-dist/client/voice-samples/grok/leo.mp3 +0 -0
  53. package/bundle/web-dist/client/voice-samples/grok/liora.mp3 +0 -0
  54. package/bundle/web-dist/client/voice-samples/grok/lumen.mp3 +0 -0
  55. package/bundle/web-dist/client/voice-samples/grok/luna.mp3 +0 -0
  56. package/bundle/web-dist/client/voice-samples/grok/lux.mp3 +0 -0
  57. package/bundle/web-dist/client/voice-samples/grok/naksh.mp3 +0 -0
  58. package/bundle/web-dist/client/voice-samples/grok/orion.mp3 +0 -0
  59. package/bundle/web-dist/client/voice-samples/grok/perseus.mp3 +0 -0
  60. package/bundle/web-dist/client/voice-samples/grok/rex.mp3 +0 -0
  61. package/bundle/web-dist/client/voice-samples/grok/rigel.mp3 +0 -0
  62. package/bundle/web-dist/client/voice-samples/grok/sal.mp3 +0 -0
  63. package/bundle/web-dist/client/voice-samples/grok/sirius.mp3 +0 -0
  64. package/bundle/web-dist/client/voice-samples/grok/ursa.mp3 +0 -0
  65. package/bundle/web-dist/client/voice-samples/grok/zagan.mp3 +0 -0
  66. package/bundle/web-dist/client/voice-samples/grok/zenith.mp3 +0 -0
  67. package/bundle/web-dist/client/voice-samples/openai/alloy.mp3 +0 -0
  68. package/bundle/web-dist/client/voice-samples/openai/ash.mp3 +0 -0
  69. package/bundle/web-dist/client/voice-samples/openai/ballad.mp3 +0 -0
  70. package/bundle/web-dist/client/voice-samples/openai/cedar.mp3 +0 -0
  71. package/bundle/web-dist/client/voice-samples/openai/coral.mp3 +0 -0
  72. package/bundle/web-dist/client/voice-samples/openai/echo.mp3 +0 -0
  73. package/bundle/web-dist/client/voice-samples/openai/marin.mp3 +0 -0
  74. package/bundle/web-dist/client/voice-samples/openai/sage.mp3 +0 -0
  75. package/bundle/web-dist/client/voice-samples/openai/shimmer.mp3 +0 -0
  76. package/bundle/web-dist/client/voice-samples/openai/verse.mp3 +0 -0
  77. package/bundle/web-dist/server/assets/link-DrdV092C.js +4919 -0
  78. package/bundle/web-dist/server/assets/{logs-WZMx5ErO.js → logs-BmBpBe-j.js} +13 -6
  79. package/bundle/web-dist/server/assets/{monit-Bf6U1Xp5.js → monit-Db1WrIls.js} +2 -2
  80. package/bundle/web-dist/server/assets/{plus-BwpfWi3W.js → plus-CW9y_K7l.js} +1 -1
  81. package/bundle/web-dist/server/assets/{refresh-cw-Xk9nLu8E.js → refresh-cw-CRgcH5bT.js} +1 -1
  82. package/bundle/web-dist/server/assets/{request-model-ByadPBS5.js → request-model-DRF7hmJC.js} +1 -1
  83. package/bundle/web-dist/server/assets/{routes-WFysbWfc.js → routes-CARZj7or.js} +4 -4
  84. package/bundle/web-dist/server/assets/{services.generated-Bej_fJ74.js → services.generated-B6QpnL_N.js} +5 -0
  85. package/bundle/web-dist/server/assets/{settings-DnAbfheS.js → settings-B4jdpP5N.js} +4 -4
  86. package/bundle/web-dist/server/assets/{show-DvpdOIGn.js → show-D8r2sVK0.js} +17 -9
  87. package/bundle/web-dist/server/assets/{tokens-CAc4t_kZ.js → tokens-TDQguTdh.js} +5 -5
  88. package/bundle/web-dist/server/assets/{use-oauth-login-flow-Cxm_7Qg6.js → use-oauth-login-flow-du7pOh_H.js} +1 -1
  89. package/bundle/web-dist/server/assets/{use-update-token-mutation-DnxqIThp.js → use-update-token-mutation-DA6HiiWS.js} +1 -1
  90. package/bundle/web-dist/server/assets/voice-C2HfwkGp.js +668 -0
  91. package/bundle/web-dist/server/entry-server.generated.js +125 -4989
  92. package/bundle/web-dist/server/voice-samples/grok/altair.mp3 +0 -0
  93. package/bundle/web-dist/server/voice-samples/grok/ara.mp3 +0 -0
  94. package/bundle/web-dist/server/voice-samples/grok/atlas.mp3 +0 -0
  95. package/bundle/web-dist/server/voice-samples/grok/aurora.mp3 +0 -0
  96. package/bundle/web-dist/server/voice-samples/grok/carina.mp3 +0 -0
  97. package/bundle/web-dist/server/voice-samples/grok/castor.mp3 +0 -0
  98. package/bundle/web-dist/server/voice-samples/grok/celeste.mp3 +0 -0
  99. package/bundle/web-dist/server/voice-samples/grok/cosmo.mp3 +0 -0
  100. package/bundle/web-dist/server/voice-samples/grok/eve.mp3 +0 -0
  101. package/bundle/web-dist/server/voice-samples/grok/helios.mp3 +0 -0
  102. package/bundle/web-dist/server/voice-samples/grok/helix.mp3 +0 -0
  103. package/bundle/web-dist/server/voice-samples/grok/iris.mp3 +0 -0
  104. package/bundle/web-dist/server/voice-samples/grok/kepler.mp3 +0 -0
  105. package/bundle/web-dist/server/voice-samples/grok/leo.mp3 +0 -0
  106. package/bundle/web-dist/server/voice-samples/grok/liora.mp3 +0 -0
  107. package/bundle/web-dist/server/voice-samples/grok/lumen.mp3 +0 -0
  108. package/bundle/web-dist/server/voice-samples/grok/luna.mp3 +0 -0
  109. package/bundle/web-dist/server/voice-samples/grok/lux.mp3 +0 -0
  110. package/bundle/web-dist/server/voice-samples/grok/naksh.mp3 +0 -0
  111. package/bundle/web-dist/server/voice-samples/grok/orion.mp3 +0 -0
  112. package/bundle/web-dist/server/voice-samples/grok/perseus.mp3 +0 -0
  113. package/bundle/web-dist/server/voice-samples/grok/rex.mp3 +0 -0
  114. package/bundle/web-dist/server/voice-samples/grok/rigel.mp3 +0 -0
  115. package/bundle/web-dist/server/voice-samples/grok/sal.mp3 +0 -0
  116. package/bundle/web-dist/server/voice-samples/grok/sirius.mp3 +0 -0
  117. package/bundle/web-dist/server/voice-samples/grok/ursa.mp3 +0 -0
  118. package/bundle/web-dist/server/voice-samples/grok/zagan.mp3 +0 -0
  119. package/bundle/web-dist/server/voice-samples/grok/zenith.mp3 +0 -0
  120. package/bundle/web-dist/server/voice-samples/openai/alloy.mp3 +0 -0
  121. package/bundle/web-dist/server/voice-samples/openai/ash.mp3 +0 -0
  122. package/bundle/web-dist/server/voice-samples/openai/ballad.mp3 +0 -0
  123. package/bundle/web-dist/server/voice-samples/openai/cedar.mp3 +0 -0
  124. package/bundle/web-dist/server/voice-samples/openai/coral.mp3 +0 -0
  125. package/bundle/web-dist/server/voice-samples/openai/echo.mp3 +0 -0
  126. package/bundle/web-dist/server/voice-samples/openai/marin.mp3 +0 -0
  127. package/bundle/web-dist/server/voice-samples/openai/sage.mp3 +0 -0
  128. package/bundle/web-dist/server/voice-samples/openai/shimmer.mp3 +0 -0
  129. package/bundle/web-dist/server/voice-samples/openai/verse.mp3 +0 -0
  130. package/package.json +1 -1
  131. package/skills/qgrid/references/ai-sdk-provider-contract.md +2 -0
  132. package/skills/qgrid/references/grok-runtime.md +2 -0
  133. package/skills/qgrid/references/request-log-run-lifecycle.md +5 -0
  134. package/skills/qgrid/references/sonamu-api-web-flow.md +5 -1
  135. package/bundle/web-dist/client/assets/index-DLo1QCw7.css +0 -1
@@ -2202,6 +2202,10 @@ describe("QgridFrame Grok media and voice (U11)", () => {
2202
2202
  77,
2203
2203
  expect.objectContaining({ status: "succeeded", response: "hello there", cost_usd: null, cost_source: null }),
2204
2204
  );
2205
+ // The input audio is kept playable in the user prompt, as TTS output is in the response.
2206
+ expect(requestLogCreateRunMock).toHaveBeenCalledWith(
2207
+ expect.objectContaining({ user_prompt: `<audio src="data:audio/wav;base64,${audio}"></audio>`, media_kind: "stt" }),
2208
+ );
2205
2209
  });
2206
2210
 
2207
2211
  it("transcribe rejects non-base64 and non-audio input before dispatch", async () => {
@@ -2233,6 +2237,64 @@ describe("QgridFrame Grok media and voice (U11)", () => {
2233
2237
  );
2234
2238
  });
2235
2239
 
2240
+ it("speak logs a tts row with playable audio and time to first byte", async () => {
2241
+ vi.useFakeTimers({ toFake: ["Date"], now: 10_000 });
2242
+ const bytes = new Uint8Array([0xff, 0xfb, 1, 2]);
2243
+ grok.speak!.mockResolvedValueOnce({
2244
+ result: { audio: bytes, mediaType: "audio/mpeg", firstByteAt: 10_250 },
2245
+ tokenId: 3,
2246
+ tokenName: "grok/a",
2247
+ });
2248
+
2249
+ await QgridFrame.speak({ text: "hi" });
2250
+ vi.useRealTimers();
2251
+
2252
+ expect(requestLogCreateRunMock).toHaveBeenCalledWith(expect.objectContaining({ media_kind: "tts" }));
2253
+ expect(requestLogFinishRunMock).toHaveBeenCalledWith(
2254
+ 77,
2255
+ expect.objectContaining({
2256
+ response: `<audio src="data:audio/mpeg;base64,${Buffer.from(bytes).toString("base64")}"></audio>`,
2257
+ ttft_ms: 250,
2258
+ }),
2259
+ );
2260
+ });
2261
+
2262
+ it("speak passes withTimestamps to Grok and returns the character timing", async () => {
2263
+ const audioTimestamps = { graphChars: ["h", "i"], graphTimes: [[0, 0.1], [0.1, 0.3]] as Array<[number, number]> };
2264
+ grok.speak!.mockResolvedValueOnce({
2265
+ result: { audio: new Uint8Array([1, 2]), mediaType: "audio/mpeg", audioTimestamps, durationSec: 0.3 },
2266
+ tokenId: 3,
2267
+ tokenName: "grok/a",
2268
+ });
2269
+
2270
+ const out = await QgridFrame.speak({ text: "hi", withTimestamps: true });
2271
+
2272
+ expect(grok.speak).toHaveBeenCalledWith(expect.objectContaining({ with_timestamps: true }));
2273
+ expect(out).toMatchObject({ audioTimestamps, durationSec: 0.3 });
2274
+ });
2275
+
2276
+ it("speak rejects withTimestamps for OpenAI before any log or dispatch", async () => {
2277
+ await expect(
2278
+ QgridFrame.speak({ model: "openai/gpt-realtime-2.1-mini", text: "hi", withTimestamps: true }),
2279
+ ).rejects.toThrow("withTimestamps is available only for grok/");
2280
+ expect(requestLogCreateRunMock).not.toHaveBeenCalled();
2281
+ });
2282
+
2283
+ it("speak keeps the byte-count placeholder for audio a browser cannot play", async () => {
2284
+ grok.speak!.mockResolvedValueOnce({
2285
+ result: { audio: new Uint8Array(6), mediaType: "audio/pcm" },
2286
+ tokenId: 3,
2287
+ tokenName: "grok/a",
2288
+ });
2289
+
2290
+ await QgridFrame.speak({ text: "hi", format: "pcm" });
2291
+
2292
+ expect(requestLogFinishRunMock).toHaveBeenCalledWith(
2293
+ 77,
2294
+ expect.objectContaining({ response: "[audio audio/pcm 6 bytes]" }),
2295
+ );
2296
+ });
2297
+
2236
2298
  it("media endpoints answer not-ready when no Grok media dispatcher is registered", async () => {
2237
2299
  Object.assign(QgridDispatcher, { grokDispatcher: null });
2238
2300
  await expect(QgridFrame.speak({ text: "hi" })).rejects.toThrow(SD("qgrid.dispatcherStarting")("Grok"));
@@ -80,6 +80,7 @@ import {
80
80
  OPENAI_REALTIME_DEFAULT_SPEECH_MODEL,
81
81
  OPENAI_REALTIME_DEFAULT_TRANSCRIPTION_MODEL,
82
82
  OPENAI_REALTIME_DEFAULT_VOICE,
83
+ wrapPcmAsWav,
83
84
  } from "../../utils/providers/openai/openai-realtime-protocol";
84
85
  import { OpenAIVoiceInputError } from "../../utils/providers/openai/openai-voice-client";
85
86
  import {
@@ -784,6 +785,7 @@ async function startMediaRun(
784
785
  requested_model_name: start.model,
785
786
  project_name: start.projectName,
786
787
  is_image_generation: start.kind === "image",
788
+ media_kind: start.kind,
787
789
  });
788
790
  }
789
791
 
@@ -823,8 +825,33 @@ type MediaLogSuccess = {
823
825
  response: string;
824
826
  steps: MediaLogSteps;
825
827
  cost?: GrokMediaCost;
828
+ /** Speech only: time to the first audio byte, measured from the same start as `durationMs`. */
829
+ ttftMs?: number;
826
830
  };
827
831
 
832
+ // Voice rows embed browser-playable audio (TTS output in the response, STT input in the user
833
+ // prompt) so the request-log detail page can play it, as image rows embed their images. Other
834
+ // formats (raw PCM, mu-law, A-law) keep the byte-count placeholder.
835
+ const LOG_PLAYABLE_AUDIO = new Set([
836
+ "audio/wav",
837
+ "audio/x-wav",
838
+ "audio/wave",
839
+ "audio/mpeg",
840
+ "audio/mp3",
841
+ "audio/mp4",
842
+ "audio/ogg",
843
+ "audio/webm",
844
+ "audio/flac",
845
+ ]);
846
+
847
+ function audioForLog(b64: string, mimeType: string, byteLength: number): string {
848
+ const base = mimeType.split(";")[0]!.trim().toLowerCase();
849
+
850
+ return LOG_PLAYABLE_AUDIO.has(base)
851
+ ? `<audio src="data:${base};base64,${b64}"></audio>`
852
+ : `[audio ${mimeType} ${byteLength} bytes]`;
853
+ }
854
+
828
855
  function mediaToolSteps(
829
856
  kind: MediaKind,
830
857
  steps: MediaLogSteps,
@@ -884,6 +911,7 @@ function mediaFinishFields(success: Omit<MediaLogSuccess, "steps">): FinishRunPa
884
911
  cache_read_tokens: 0,
885
912
  cache_creation_tokens: 0,
886
913
  duration_ms: success.durationMs,
914
+ ...(success.ttftMs !== undefined && { ttft_ms: success.ttftMs }),
887
915
  ...mediaCostFields(success.kind, success.model, success.cost),
888
916
  };
889
917
  }
@@ -952,7 +980,10 @@ async function dispatchMediaCall<T>(
952
980
  return result;
953
981
  }
954
982
 
955
- type MediaRunLog = Omit<MediaLogSuccess, "kind" | "model" | "durationMs">;
983
+ /** `firstOutputAt` is the epoch-ms first audio byte; the endpoint turns it into `ttftMs`. */
984
+ type MediaRunLog = Omit<MediaLogSuccess, "kind" | "model" | "durationMs" | "ttftMs"> & {
985
+ firstOutputAt?: number;
986
+ };
956
987
 
957
988
  /**
958
989
  * A one-shot media endpoint: open the run, make the provider call, then log the result. `dispatch`
@@ -968,15 +999,17 @@ async function runMediaEndpoint<T>(
968
999
  const requestLogId = await startMediaRun(start.logger, start);
969
1000
  const startedAt = Date.now();
970
1001
 
971
- const { output, log } = await dispatchMediaCall(requestLogId, (signal) =>
972
- dispatch(signal, requestLogId),
973
- );
1002
+ const {
1003
+ output,
1004
+ log: { firstOutputAt, ...log },
1005
+ } = await dispatchMediaCall(requestLogId, (signal) => dispatch(signal, requestLogId));
974
1006
 
975
1007
  await finishMediaRun(requestLogId, {
976
1008
  ...log,
977
1009
  kind: start.kind,
978
1010
  model: start.model,
979
1011
  durationMs: Date.now() - startedAt,
1012
+ ...(firstOutputAt !== undefined && { ttftMs: Math.max(0, firstOutputAt - startedAt) }),
980
1013
  });
981
1014
 
982
1015
  return output;
@@ -1077,7 +1110,7 @@ async function transcribeOpenAI(input: TranscribeInput): Promise<TranscribeOutpu
1077
1110
  const start = {
1078
1111
  kind: "stt",
1079
1112
  model: route,
1080
- prompt: `[audio ${input.mediaType} ${audio.byteLength} bytes]`,
1113
+ prompt: audioForLog(input.audio, input.mediaType, audio.byteLength),
1081
1114
  projectName: input.projectName,
1082
1115
  logger: input.logger,
1083
1116
  } as const;
@@ -1172,7 +1205,7 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
1172
1205
 
1173
1206
  return runMediaEndpoint(start, async (signal, requestLogId) => {
1174
1207
  const dispatched = await dispatcher.speak({ ...request, signal, ...selection });
1175
- const { audio, mediaType, transcript, usage } = dispatched.result;
1208
+ const { audio, mediaType, transcript, usage, firstAudioAt } = dispatched.result;
1176
1209
 
1177
1210
  const output: SpeakOutput = {
1178
1211
  audio: Buffer.from(audio).toString("base64"),
@@ -1182,9 +1215,16 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
1182
1215
 
1183
1216
  if (requestLogId !== undefined) output.requestLogId = requestLogId;
1184
1217
 
1218
+ // pcm output is always 24 kHz PCM16, so the log copy is wrapped as WAV to stay playable.
1219
+ const logAudio =
1220
+ mediaType === "audio/wav"
1221
+ ? output.audio
1222
+ : Buffer.from(wrapPcmAsWav(audio)).toString("base64");
1223
+
1185
1224
  const log: MediaRunLog = {
1186
1225
  tokenName: output.tokenName,
1187
- response: `[audio ${mediaType} ${audio.byteLength} bytes]`,
1226
+ response: audioForLog(logAudio, "audio/wav", audio.byteLength),
1227
+ firstOutputAt: firstAudioAt,
1188
1228
  steps: [
1189
1229
  {
1190
1230
  toolCallId: "speech:0",
@@ -2172,7 +2212,7 @@ class QgridFrameClass extends BaseFrameClass {
2172
2212
  const start = {
2173
2213
  kind: "stt",
2174
2214
  model: route,
2175
- prompt: `[audio ${input.mediaType} ${audio.byteLength} bytes]`,
2215
+ prompt: audioForLog(input.audio, input.mediaType, audio.byteLength),
2176
2216
  projectName: input.projectName,
2177
2217
  logger: input.logger,
2178
2218
  } as const;
@@ -2229,7 +2269,18 @@ class QgridFrameClass extends BaseFrameClass {
2229
2269
  async speak(params: SpeakInput): Promise<SpeakOutput> {
2230
2270
  const input = parseMediaInput(SpeakInput, params);
2231
2271
 
2232
- if (voiceProvider(input.model) === "openai") return speakOpenAI(input);
2272
+ if (voiceProvider(input.model) === "openai") {
2273
+ if (input.withTimestamps) {
2274
+ throw new BadRequestException(
2275
+ SD("qgrid.openaiVoiceInvalidRequest")(
2276
+ "withTimestamps is available only for grok/ speech; OpenAI realtime has no timing data",
2277
+ ),
2278
+ );
2279
+ }
2280
+
2281
+ return speakOpenAI(input);
2282
+ }
2283
+
2233
2284
  const voice = grokVoice();
2234
2285
  const selection = await resolveGrokTokenSelection(input.tokenName);
2235
2286
  const route = input.model ?? GROK_TTS_LOG_MODEL;
@@ -2239,6 +2290,7 @@ class QgridFrameClass extends BaseFrameClass {
2239
2290
  voice: input.voice ?? GROK_TTS_DEFAULT_VOICE,
2240
2291
  language: input.language ?? GROK_TTS_DEFAULT_LANGUAGE,
2241
2292
  format: input.format ?? GROK_TTS_DEFAULT_FORMAT,
2293
+ ...(input.withTimestamps === true && { with_timestamps: true }),
2242
2294
  };
2243
2295
 
2244
2296
  const start = {
@@ -2261,9 +2313,18 @@ class QgridFrameClass extends BaseFrameClass {
2261
2313
 
2262
2314
  if (requestLogId !== undefined) output.requestLogId = requestLogId;
2263
2315
 
2316
+ if (dispatched.result.audioTimestamps) {
2317
+ output.audioTimestamps = dispatched.result.audioTimestamps;
2318
+ }
2319
+
2320
+ if (dispatched.result.durationSec !== undefined) {
2321
+ output.durationSec = dispatched.result.durationSec;
2322
+ }
2323
+
2264
2324
  const log: MediaRunLog = {
2265
2325
  tokenName: output.tokenName,
2266
- response: `[audio ${output.mimeType} ${audioBytes} bytes]`,
2326
+ response: audioForLog(output.audio, output.mimeType, audioBytes),
2327
+ firstOutputAt: dispatched.result.firstByteAt,
2267
2328
  steps: [
2268
2329
  {
2269
2330
  toolCallId: "speech:0",
@@ -2273,9 +2334,15 @@ class QgridFrameClass extends BaseFrameClass {
2273
2334
  voice: request.voice,
2274
2335
  language: request.language,
2275
2336
  format: request.format,
2337
+ withTimestamps: input.withTimestamps,
2276
2338
  characters: input.text.length,
2277
2339
  },
2278
- result: JSON.stringify({ mimeType: output.mimeType, audioBytes }),
2340
+ result: JSON.stringify({
2341
+ mimeType: output.mimeType,
2342
+ audioBytes,
2343
+ durationSec: output.durationSec,
2344
+ timedCharacters: output.audioTimestamps?.graphChars.length,
2345
+ }),
2279
2346
  },
2280
2347
  ],
2281
2348
  };
@@ -549,6 +549,9 @@ export const SpeakInput = z.object({
549
549
  format: z.enum(["mp3", "wav", "pcm", "mulaw", "alaw"]).optional(),
550
550
  // OpenAI realtime speech only: style guidance appended to the verbatim-repeat instruction.
551
551
  instructions: z.string().min(1).max(2_000).optional(),
552
+ // Grok speech only: per-character timing in the output (`audioTimestamps`). OpenAI realtime has
553
+ // no timing data and rejects it with 400.
554
+ withTimestamps: z.boolean().optional(),
552
555
  ...MediaCallOptions,
553
556
  });
554
557
 
@@ -560,6 +563,15 @@ export const SpeakOutput = z.object({
560
563
  mimeType: z.string(),
561
564
  tokenName: z.string(),
562
565
  requestLogId: z.number().optional(),
566
+ // Only with `withTimestamps`: input characters (spaces, punctuation, tags included) and the
567
+ // `[start, end]` seconds of each, index-aligned; named as @ai-sdk/xai exposes them.
568
+ audioTimestamps: z
569
+ .object({
570
+ graphChars: z.array(z.string()),
571
+ graphTimes: z.array(z.tuple([z.number(), z.number()])),
572
+ })
573
+ .optional(),
574
+ durationSec: z.number().optional(),
563
575
  });
564
576
 
565
577
  export type SpeakOutput = z.infer<typeof SpeakOutput>;
@@ -220,6 +220,13 @@
220
220
  "type": "boolean",
221
221
  "desc": "structured output(jsonSchema) 요청 여부 (목록 구분 표시용)",
222
222
  "dbDefault": "false"
223
+ },
224
+ {
225
+ "name": "media_kind",
226
+ "type": "enum",
227
+ "id": "RequestLogMediaKind",
228
+ "nullable": true,
229
+ "desc": "미디어 엔드포인트 종류(image/video/stt/tts). 텍스트 요청은 null (목록 Fmt 표시용)"
223
230
  }
224
231
  ],
225
232
  "indexes": [
@@ -311,7 +318,8 @@
311
318
  "error_message",
312
319
  "tool_call_count",
313
320
  "is_image_generation",
314
- "is_structured"
321
+ "is_structured",
322
+ "media_kind"
315
323
  ],
316
324
  "P": [
317
325
  "id",
@@ -339,7 +347,8 @@
339
347
  "response_json_ok",
340
348
  "tool_call_count",
341
349
  "is_image_generation",
342
- "is_structured"
350
+ "is_structured",
351
+ "media_kind"
343
352
  ],
344
353
  "C": [
345
354
  "id",
@@ -386,6 +395,12 @@
386
395
  "succeeded": "성공",
387
396
  "error": "에러",
388
397
  "aborted": "중단"
398
+ },
399
+ "RequestLogMediaKind": {
400
+ "image": "이미지",
401
+ "video": "비디오",
402
+ "stt": "음성 인식",
403
+ "tts": "음성 합성"
389
404
  }
390
405
  }
391
406
  }
@@ -154,6 +154,23 @@ describe("RequestLogModel TTFT", () => {
154
154
  }),
155
155
  );
156
156
  });
157
+
158
+ it("prefers an explicit ttft_ms for runs without generate steps", async () => {
159
+ const ubRegister = vi.fn();
160
+ const transaction = vi.fn(async (cb: (trx: { ubUpsert: () => Promise<number[]> }) => void) =>
161
+ cb({ ubUpsert: vi.fn(async () => [7]) }),
162
+ );
163
+ const derived = vi.spyOn(RequestLogModel, "firstGenerateStepTtft").mockResolvedValue(55);
164
+ vi.spyOn(
165
+ RequestLogModel as unknown as { getPuri: () => { ubRegister: typeof ubRegister; transaction: typeof transaction } },
166
+ "getPuri",
167
+ ).mockReturnValue({ ubRegister, transaction });
168
+
169
+ await RequestLogModel.finishRun(7, { status: "error", error_message: "boom", ttft_ms: 240 });
170
+
171
+ expect(ubRegister).toHaveBeenCalledWith("request_logs", expect.objectContaining({ id: 7, ttft_ms: 240 }));
172
+ expect(derived).not.toHaveBeenCalled();
173
+ });
157
174
  });
158
175
 
159
176
  describe("RequestLogModel toolsView", () => {
@@ -22,7 +22,11 @@ import {
22
22
  type ProviderId,
23
23
  } from "../../utils/providers/common/provider-types";
24
24
  import { type RequestLogStepSaveParams } from "../request-log-step/request-log-step.types";
25
- import { type RequestLogSubsetKey, type RequestLogSubsetMapping } from "../sonamu.generated";
25
+ import {
26
+ type RequestLogMediaKind,
27
+ type RequestLogSubsetKey,
28
+ type RequestLogSubsetMapping,
29
+ } from "../sonamu.generated";
26
30
  import { requestLogLoaderQueries, requestLogSubsetQueries } from "../sonamu.generated.sso";
27
31
  import { renderJsonSchemaZodText, renderParsedJsonSchemaTypeText } from "./json-schema-type-text";
28
32
  import {
@@ -111,9 +115,11 @@ export interface FinishRunParams {
111
115
  image_cost_method?: string | null;
112
116
  is_image_generation?: boolean;
113
117
  response_json_ok?: boolean | null;
118
+ /** Explicit TTFT for runs without generate steps (speech); otherwise derived from the steps. */
119
+ ttft_ms?: number;
114
120
  }
115
121
 
116
- type FinishRunUpdate = Partial<FinishRunParams> & { id: number; ttft_ms?: number };
122
+ type FinishRunUpdate = Partial<FinishRunParams> & { id: number };
117
123
 
118
124
  export type RunProgressUpdate = { token_name?: string; model_name?: string; ttft_ms?: number };
119
125
 
@@ -544,6 +550,7 @@ class RequestLogModelClass extends BaseModelClass<
544
550
  is_image_generation?: boolean;
545
551
  is_structured?: boolean;
546
552
  json_schema?: string | null;
553
+ media_kind?: RequestLogMediaKind | null;
547
554
  }): Promise<number> {
548
555
  const wdb = this.getPuri("w");
549
556
 
@@ -569,6 +576,7 @@ class RequestLogModelClass extends BaseModelClass<
569
576
  json_schema: params.json_schema ?? null,
570
577
  is_structured:
571
578
  params.is_structured ?? (params.json_schema !== null && params.json_schema !== undefined),
579
+ media_kind: params.media_kind ?? null,
572
580
  };
573
581
 
574
582
  if (params.history !== undefined) row.history = params.history;
@@ -643,7 +651,7 @@ class RequestLogModelClass extends BaseModelClass<
643
651
  for (const key of fields) copyDefined(update, params, key);
644
652
 
645
653
  if (params.history !== undefined) update.history = params.history;
646
- update.ttft_ms = (await this.firstGenerateStepTtft(requestLogId)) ?? 0;
654
+ update.ttft_ms = params.ttft_ms ?? (await this.firstGenerateStepTtft(requestLogId)) ?? 0;
647
655
 
648
656
  // 서버 run 경로는 step 에서 확정한 exact cost 와 출처를 넘긴다. 출처 없이 끝난 외부/legacy
649
657
  // run 은 저장된 모델+usage 로 여기서 확정해, 읽기 경로가 다시 계산하지 않게 한다.
@@ -236,7 +236,8 @@ Content-Type: application/json
236
236
  "response_json_ok": null,
237
237
  "tool_call_count": 0,
238
238
  "is_image_generation": false,
239
- "is_structured": false
239
+ "is_structured": false,
240
+ "media_kind": null
240
241
  }
241
242
  ]
242
243
  }
@@ -722,6 +723,7 @@ Content-Type: application/json
722
723
  "language": "LANGUAGE",
723
724
  "format": "mp3",
724
725
  "instructions": "INSTRUCTIONS",
726
+ "withTimestamps": false,
725
727
  "tokenName": "TOKENNAME",
726
728
  "projectName": "PROJECTNAME",
727
729
  "logger": false
@@ -55,6 +55,7 @@ export const requestLogSubsetQueries = {
55
55
  tool_call_count: "request_logs.tool_call_count",
56
56
  is_image_generation: "request_logs.is_image_generation",
57
57
  is_structured: "request_logs.is_structured",
58
+ media_kind: "request_logs.media_kind",
58
59
  });
59
60
  },
60
61
  P: (qbWrapper: PuriWrapper<DatabaseSchemaExtend>) => {
@@ -85,6 +86,7 @@ export const requestLogSubsetQueries = {
85
86
  tool_call_count: "request_logs.tool_call_count",
86
87
  is_image_generation: "request_logs.is_image_generation",
87
88
  is_structured: "request_logs.is_structured",
89
+ media_kind: "request_logs.media_kind",
88
90
  });
89
91
  },
90
92
  C: (qbWrapper: PuriWrapper<DatabaseSchemaExtend>) => {
@@ -139,6 +139,16 @@ export const RequestLogStatusLabel = {
139
139
  error: "에러",
140
140
  aborted: "중단",
141
141
  };
142
+ export const RequestLogMediaKind = z
143
+ .enum(["image", "video", "stt", "tts"])
144
+ .describe("RequestLogMediaKind");
145
+ export type RequestLogMediaKind = z.infer<typeof RequestLogMediaKind>;
146
+ export const RequestLogMediaKindLabel = {
147
+ image: "이미지",
148
+ video: "비디오",
149
+ stt: "음성 인식",
150
+ tts: "음성 합성",
151
+ };
142
152
 
143
153
  // Enums: RequestLogStep
144
154
  export const RequestLogStepType = z.enum(["generate", "tool_call"]).describe("RequestLogStepType");
@@ -203,6 +213,7 @@ export const RequestLogBaseSchema = z.object({
203
213
  tool_call_count: z.int(),
204
214
  is_image_generation: z.boolean(),
205
215
  is_structured: z.boolean(),
216
+ media_kind: RequestLogMediaKind.nullable(),
206
217
  });
207
218
  export type RequestLogBaseSchema = z.infer<typeof RequestLogBaseSchema> & {
208
219
  readonly __hasDefault__: readonly [
@@ -239,6 +250,7 @@ export type RequestLogBaseSchema = z.infer<typeof RequestLogBaseSchema> & {
239
250
  "tool_call_count",
240
251
  "is_image_generation",
241
252
  "is_structured",
253
+ "media_kind",
242
254
  "id",
243
255
  ];
244
256
  readonly __json__: readonly ["history", "input_images", "tools"];
@@ -445,6 +457,7 @@ export const RequestLogSubsetA = z.object({
445
457
  tool_call_count: z.int(),
446
458
  is_image_generation: z.boolean(),
447
459
  is_structured: z.boolean(),
460
+ media_kind: RequestLogMediaKind.nullable(),
448
461
  });
449
462
  export type RequestLogSubsetA = z.infer<typeof RequestLogSubsetA>;
450
463
  export const RequestLogSubsetP = z.object({
@@ -474,6 +487,7 @@ export const RequestLogSubsetP = z.object({
474
487
  tool_call_count: z.int(),
475
488
  is_image_generation: z.boolean(),
476
489
  is_structured: z.boolean(),
490
+ media_kind: RequestLogMediaKind.nullable(),
477
491
  });
478
492
  export type RequestLogSubsetP = z.infer<typeof RequestLogSubsetP>;
479
493
  export const RequestLogSubsetC = z.object({
@@ -250,6 +250,8 @@ const entityLabels = {
250
250
  "entity.RequestLog.tool_call_count": "tool call 횟수",
251
251
  "entity.RequestLog.is_image_generation": "이미지 생성 turn 여부 (quota 귀속용)",
252
252
  "entity.RequestLog.is_structured": "structured output(jsonSchema) 요청 여부 (목록 구분 표시용)",
253
+ "entity.RequestLog.media_kind":
254
+ "미디어 엔드포인트 종류(image/video/stt/tts). 텍스트 요청은 null (목록 Fmt 표시용)",
253
255
  "enum.RequestLogOrderBy.id-desc": "ID최신순",
254
256
  "enum.RequestLogOrderBy.id-asc": "ID오래된순",
255
257
  "enum.RequestLogOrderBy.created_at-desc": "등록일시최신순",
@@ -275,6 +277,10 @@ const entityLabels = {
275
277
  "enum.RequestLogStatus.succeeded": "성공",
276
278
  "enum.RequestLogStatus.error": "에러",
277
279
  "enum.RequestLogStatus.aborted": "중단",
280
+ "enum.RequestLogMediaKind.image": "이미지",
281
+ "enum.RequestLogMediaKind.video": "비디오",
282
+ "enum.RequestLogMediaKind.stt": "음성 인식",
283
+ "enum.RequestLogMediaKind.tts": "음성 합성",
278
284
  "entity.RequestLogStep": "RequestLogStep",
279
285
  "entity.RequestLogStep.id": "ID",
280
286
  "entity.RequestLogStep.created_at": "등록일시",
@@ -0,0 +1,15 @@
1
+ import { type Knex } from "knex";
2
+
3
+ export async function up(knex: Knex): Promise<void> {
4
+ await knex.schema.alterTable("request_logs", (table) => {
5
+ // add
6
+ table.text("media_kind").nullable();
7
+ });
8
+ }
9
+
10
+ export async function down(knex: Knex): Promise<void> {
11
+ await knex.schema.alterTable("request_logs", (table) => {
12
+ // rollback - add
13
+ table.dropColumns("media_kind");
14
+ });
15
+ }
@@ -284,6 +284,9 @@ export const GrokTtsRequest = z.object({
284
284
  voice: z.string().min(1),
285
285
  language: z.string().min(1),
286
286
  format: z.string().min(1),
287
+ // true switches /tts to a JSON envelope with per-character timing (verified on the subscription
288
+ // token 2026-11-09).
289
+ with_timestamps: z.boolean().optional(),
287
290
  });
288
291
 
289
292
  export type GrokTtsRequest = z.infer<typeof GrokTtsRequest>;
@@ -361,9 +364,22 @@ export interface GrokTranscribeRequest {
361
364
  signal?: AbortSignal;
362
365
  }
363
366
 
367
+ /** Per-character timing of the spoken text, named as `@ai-sdk/xai` exposes it. */
368
+ export interface GrokAudioTimestamps {
369
+ /** Input characters, including spaces, punctuation and speech tags. */
370
+ graphChars: string[];
371
+ /** `[start, end]` seconds for the character at the same index. */
372
+ graphTimes: Array<[number, number]>;
373
+ }
374
+
364
375
  export interface GrokSpeechResult {
365
376
  audio: Uint8Array;
366
377
  mediaType: string;
378
+ /** Only with `with_timestamps`. */
379
+ audioTimestamps?: GrokAudioTimestamps;
380
+ durationSec?: number;
381
+ /** Epoch ms when the response headers arrived; /tts is not streamed, so this is first byte. */
382
+ firstByteAt?: number;
367
383
  }
368
384
 
369
385
  export interface GrokVoicePort {
@@ -187,10 +187,12 @@ describe("GrokVoiceClient.speak", () => {
187
187
  () => new Response(mp3, { status: 200, headers: { "content-type": "audio/mpeg" } }),
188
188
  );
189
189
  const client = new GrokVoiceClient({ fetch: fake.impl, platform });
190
+ const before = Date.now();
190
191
  const result = await client.speak("tok", { text: "hello", voice: "ara" });
191
192
 
192
193
  expect(result.mediaType).toBe("audio/mpeg");
193
194
  expect(result.audio).toEqual(mp3);
195
+ expect(result.firstByteAt).toBeGreaterThanOrEqual(before);
194
196
  expect(fake.calls).toHaveLength(1);
195
197
  const { url, init } = fake.calls[0]!;
196
198
  expect(url).toBe("https://api.x.ai/v1/tts");
@@ -226,6 +228,36 @@ describe("GrokVoiceClient.speak", () => {
226
228
  });
227
229
  });
228
230
 
231
+ it("asks for timestamps and decodes the JSON envelope into audio plus character timing", async () => {
232
+ const fake = fakeFetch(
233
+ () =>
234
+ new Response(
235
+ JSON.stringify({
236
+ audio: Buffer.from(mp3).toString("base64"),
237
+ content_type: "audio/mpeg",
238
+ duration: 0.5,
239
+ audio_timestamps: { graph_chars: ["H", "i"], graph_times: [[0.08, 0.2], [0.2, 0.5]] },
240
+ }),
241
+ { status: 200, headers: { "content-type": "application/json" } },
242
+ ),
243
+ );
244
+ const client = new GrokVoiceClient({ fetch: fake.impl });
245
+ const result = await client.speak("tok", { text: "Hi", with_timestamps: true });
246
+
247
+ const body = fake.calls[0]!.init.body;
248
+ expect(typeof body === "string" && JSON.parse(body)).toMatchObject({ with_timestamps: true });
249
+ expect(result.audio).toEqual(mp3);
250
+ expect(result.mediaType).toBe("audio/mpeg");
251
+ expect(result.durationSec).toBe(0.5);
252
+ expect(result.audioTimestamps).toEqual({
253
+ graphChars: ["H", "i"],
254
+ graphTimes: [
255
+ [0.08, 0.2],
256
+ [0.2, 0.5],
257
+ ],
258
+ });
259
+ });
260
+
229
261
  it("falls back to the format's media type when content-type is missing", async () => {
230
262
  const client = new GrokVoiceClient({
231
263
  fetch: fakeFetch(() => {