@cartanova/qgrid-cli 2.18.0 → 2.19.1
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.
- package/README.ko.md +26 -0
- package/README.md +29 -0
- package/bundle/dist/_virtual/_rolldown/runtime.js +1 -0
- package/bundle/dist/application/qgrid/qgrid-response-format.js +14 -5
- package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +8 -3
- package/bundle/dist/application/qgrid/qgrid.frame.js +30 -44
- package/bundle/dist/application/qgrid/qgrid.types.js +4 -4
- package/bundle/dist/startup-migrations.js +1 -1
- package/bundle/dist/utils/providers/common/schema-validation.js +2 -2
- package/bundle/dist/utils/providers/grok/grok-voice-client.js +10 -5
- package/bundle/dist/utils/speech-aligner.js +302 -0
- package/bundle/dist/utils/speech-alignment.js +2 -102
- package/bundle/src/application/qgrid/qgrid-response-format.test.ts +14 -4
- package/bundle/src/application/qgrid/qgrid-response-format.ts +18 -2
- package/bundle/src/application/qgrid/qgrid-run-lifecycle.test.ts +23 -1
- package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +14 -2
- package/bundle/src/application/qgrid/qgrid.frame.test.ts +56 -17
- package/bundle/src/application/qgrid/qgrid.frame.ts +41 -51
- package/bundle/src/application/qgrid/qgrid.types.ts +14 -11
- package/bundle/src/utils/providers/common/schema-validation.ts +1 -1
- package/bundle/src/utils/providers/grok/grok-voice-client.test.ts +4 -3
- package/bundle/src/utils/providers/grok/grok-voice-client.ts +13 -1
- package/bundle/src/utils/speech-aligner.test.ts +100 -0
- package/bundle/src/utils/speech-aligner.ts +435 -0
- package/bundle/src/utils/speech-alignment.test.ts +2 -50
- package/bundle/src/utils/speech-alignment.ts +1 -141
- package/bundle/web-dist/client/assets/{index-CbElySnT.js → index-DvW4Yb82.js} +3 -3
- package/bundle/web-dist/client/assets/{logs-BJZmjJan.js → logs-DAif2re1.js} +1 -1
- package/bundle/web-dist/client/assets/{monit-CO4TQDhe.js → monit-DYczkiu0.js} +1 -1
- package/bundle/web-dist/client/assets/{routes-D_pSsIQS.js → routes--6kS1pgJ.js} +1 -1
- package/bundle/web-dist/client/assets/{settings-LKaZCi07.js → settings-Dah87LB2.js} +1 -1
- package/bundle/web-dist/client/assets/{show-BvATehjq.js → show-DQWFaVDW.js} +2 -2
- package/bundle/web-dist/client/assets/{tokens-D5KX_VAe.js → tokens-CIHja806.js} +1 -1
- package/bundle/web-dist/client/assets/{use-oauth-login-flow-DcqeDFdp.js → use-oauth-login-flow-DeJCqHDJ.js} +1 -1
- package/bundle/web-dist/client/assets/{use-update-token-mutation-IqmKULKf.js → use-update-token-mutation-Cn_Po_rH.js} +1 -1
- package/bundle/web-dist/client/assets/voice-6i785ieC.js +1 -0
- package/bundle/web-dist/client/index.html +1 -1
- package/bundle/web-dist/server/assets/{show-B_l5dOcT.js → show-CnLDFCtW.js} +2 -5
- package/bundle/web-dist/server/assets/{voice-BhVkiSJl.js → voice-BvAl-vTr.js} +12 -6
- package/bundle/web-dist/server/entry-server.generated.js +3 -3
- package/dist/cli.js +141 -3
- package/package.json +1 -1
- package/skills/qgrid/references/cli-env-and-server-boot.md +1 -0
- package/skills/qgrid/references/decision-rationale.md +1 -1
- package/skills/qgrid/references/grok-runtime.md +3 -3
- package/skills/qgrid/references/openai-codex-runtime.md +2 -0
- package/skills/qgrid/references/request-log-run-lifecycle.md +2 -2
- package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
- package/bundle/web-dist/client/assets/voice-BvjMZbB5.js +0 -1
|
@@ -46,13 +46,22 @@ const StoredHistoryMessage = z.looseObject({
|
|
|
46
46
|
|
|
47
47
|
type StoredHistoryMessage = z.infer<typeof StoredHistoryMessage>;
|
|
48
48
|
|
|
49
|
+
// Images in history were stored with the run that sent or generated them, and nothing reads them
|
|
50
|
+
// back from here: keep only their length. Base64 has no quotes or escapes, so a match is exactly one
|
|
51
|
+
// JSON string value.
|
|
52
|
+
const DATA_URL_STRING = /"data:[^",;\\]*;base64,[A-Za-z0-9+/=]*"/g;
|
|
53
|
+
|
|
54
|
+
function maskDataUrls(rawHistory: string): string {
|
|
55
|
+
return rawHistory.replace(DATA_URL_STRING, (match) => `"[data-url ${match.length - 2} chars]"`);
|
|
56
|
+
}
|
|
57
|
+
|
|
49
58
|
function filterHistoryForStorage(
|
|
50
59
|
rawHistory: string | undefined,
|
|
51
60
|
): StoredHistoryMessage[] | undefined {
|
|
52
61
|
if (!rawHistory) return undefined;
|
|
53
62
|
|
|
54
63
|
try {
|
|
55
|
-
const items = z.array(z.unknown()).parse(JSON.parse(rawHistory));
|
|
64
|
+
const items = z.array(z.unknown()).parse(JSON.parse(maskDataUrls(rawHistory)));
|
|
56
65
|
|
|
57
66
|
const filtered = items.flatMap((item) => {
|
|
58
67
|
const message = StoredHistoryMessage.safeParse(item);
|
|
@@ -223,7 +232,10 @@ export async function afterQuery(
|
|
|
223
232
|
? 0
|
|
224
233
|
: estimateImageGenerationCostMicroUsd(result, args.imageGenerationOptions);
|
|
225
234
|
|
|
226
|
-
|
|
235
|
+
// A tool-calls step ends without a response, so only then do its steps keep the image bytes.
|
|
236
|
+
const imagesInResponse = result.finishReason !== "tool-calls";
|
|
237
|
+
|
|
238
|
+
for (const step of buildImageGenerationToolSteps(args, imageParts, stepIndex, imagesInResponse)) {
|
|
227
239
|
await RequestLogModel.appendStep(requestLogId, step);
|
|
228
240
|
}
|
|
229
241
|
|
|
@@ -105,6 +105,11 @@ vi.mock("sonamu/cache", () => {
|
|
|
105
105
|
};
|
|
106
106
|
});
|
|
107
107
|
|
|
108
|
+
// The aligner needs the MMS-FA model; its own tests cover the alignment itself.
|
|
109
|
+
const alignSpeechMock = vi.hoisted(() => vi.fn());
|
|
110
|
+
|
|
111
|
+
vi.mock("../../utils/speech-aligner", () => ({ alignSpeech: alignSpeechMock }));
|
|
112
|
+
|
|
108
113
|
// Token exchange and device endpoints hit xAI; startGrokOAuth stays real (fetch is stubbed).
|
|
109
114
|
vi.mock("../../utils/providers/grok", async (importOriginal) => ({
|
|
110
115
|
...(await importOriginal<typeof import("../../utils/providers/grok")>()),
|
|
@@ -1979,7 +1984,7 @@ describe("QgridFrame Grok media and voice (U11)", () => {
|
|
|
1979
1984
|
prompt: "x",
|
|
1980
1985
|
referenceImages: ["data:image/png;base64," + "A".repeat(28 * 1024 * 1024)],
|
|
1981
1986
|
},
|
|
1982
|
-
"
|
|
1987
|
+
"19 MiB",
|
|
1983
1988
|
],
|
|
1984
1989
|
])("generateImages rejects invalid input %#", async (input, message) => {
|
|
1985
1990
|
await expect(QgridFrame.generateImages(input)).rejects.toThrow(message);
|
|
@@ -2001,7 +2006,7 @@ describe("QgridFrame Grok media and voice (U11)", () => {
|
|
|
2001
2006
|
// The aggregate counts every inline image of the request, not just each one.
|
|
2002
2007
|
const split = GenerateImagesInput.safeParse({ ...largest, referenceImages: [half, half] });
|
|
2003
2008
|
expect(split.success).toBe(false);
|
|
2004
|
-
expect(split.error?.issues.map((issue) => issue.message)).toContain("inline images exceed
|
|
2009
|
+
expect(split.error?.issues.map((issue) => issue.message)).toContain("inline images exceed 19 MiB in total");
|
|
2005
2010
|
expect(
|
|
2006
2011
|
VideoStartInput.safeParse({ model: "grok/grok-imagine-video", prompt: "x", image: half, lastFrame: half }).success,
|
|
2007
2012
|
).toBe(false);
|
|
@@ -2040,7 +2045,7 @@ describe("QgridFrame Grok media and voice (U11)", () => {
|
|
|
2040
2045
|
payload,
|
|
2041
2046
|
});
|
|
2042
2047
|
expect(tooLarge.statusCode).toBe(413);
|
|
2043
|
-
expect(tooLarge.json()).toEqual({ name: "Error", message: SD("qgrid.requestBodyTooLarge")(
|
|
2048
|
+
expect(tooLarge.json()).toEqual({ name: "Error", message: SD("qgrid.requestBodyTooLarge")(26) });
|
|
2044
2049
|
|
|
2045
2050
|
const ok = await server.inject({ method: "POST", url: "/media", payload: { ok: true } });
|
|
2046
2051
|
expect(ok.statusCode).toBe(200);
|
|
@@ -2303,12 +2308,9 @@ describe("QgridFrame Grok media and voice (U11)", () => {
|
|
|
2303
2308
|
Object.assign(QgridDispatcher, { openaiDispatcher: { speak: openaiSpeak } });
|
|
2304
2309
|
});
|
|
2305
2310
|
|
|
2306
|
-
it("aligns
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
tokenId: 3,
|
|
2310
|
-
tokenName: "grok/a",
|
|
2311
|
-
});
|
|
2311
|
+
it("aligns the script in the generated audio without calling Grok", async () => {
|
|
2312
|
+
const audioTimestamps = { graphChars: Array.from("Hi"), graphTimes: [[0.1, 0.15], [0.15, 0.2]] };
|
|
2313
|
+
alignSpeechMock.mockResolvedValueOnce(audioTimestamps);
|
|
2312
2314
|
|
|
2313
2315
|
const out = await QgridFrame.speak({
|
|
2314
2316
|
model: "openai/gpt-realtime-2.1-mini",
|
|
@@ -2319,12 +2321,10 @@ describe("QgridFrame Grok media and voice (U11)", () => {
|
|
|
2319
2321
|
|
|
2320
2322
|
// The style instructions are kept as the run's system prompt for the request log.
|
|
2321
2323
|
expect(requestLogCreateRunMock).toHaveBeenCalledWith(expect.objectContaining({ system_prompt: "Speak warmly." }));
|
|
2322
|
-
|
|
2323
|
-
expect(
|
|
2324
|
-
expect(
|
|
2325
|
-
|
|
2326
|
-
expect(start).toBe(0.1);
|
|
2327
|
-
expect(end).toBeCloseTo(0.15);
|
|
2324
|
+
// PCM after the 44-byte WAV header, at the realtime sample rate.
|
|
2325
|
+
expect(alignSpeechMock).toHaveBeenCalledWith(wav.subarray(44), 24_000, "Hi there.");
|
|
2326
|
+
expect(grok.transcribe).not.toHaveBeenCalled();
|
|
2327
|
+
expect(out).toMatchObject({ timestampsSource: "aligned", durationSec: 0.5, audioTimestamps });
|
|
2328
2328
|
});
|
|
2329
2329
|
|
|
2330
2330
|
it("keeps the OpenAI STT prompt as the run's system prompt", async () => {
|
|
@@ -2344,14 +2344,53 @@ describe("QgridFrame Grok media and voice (U11)", () => {
|
|
|
2344
2344
|
expect(requestLogCreateRunMock).toHaveBeenCalledWith(expect.objectContaining({ system_prompt: "qgrid, Kuma", media_kind: "stt" }));
|
|
2345
2345
|
});
|
|
2346
2346
|
|
|
2347
|
+
describe("OpenAI transcription word timing", () => {
|
|
2348
|
+
// 0.5 s of raw PCM16 at the realtime sample rate.
|
|
2349
|
+
const pcm = new Uint8Array(24_000);
|
|
2350
|
+
const transcribeOnce = () => {
|
|
2351
|
+
const transcribe = vi.fn().mockResolvedValue({
|
|
2352
|
+
result: { text: "hi", durationSec: 0.5, callId: "c", transport: "realtime-calls" },
|
|
2353
|
+
tokenName: "openai/a",
|
|
2354
|
+
});
|
|
2355
|
+
Object.assign(QgridDispatcher, { openaiDispatcher: { transcribe } });
|
|
2356
|
+
|
|
2357
|
+
return QgridFrame.transcribe({
|
|
2358
|
+
model: "openai/gpt-4o-transcribe",
|
|
2359
|
+
audio: Buffer.from(pcm).toString("base64"),
|
|
2360
|
+
mediaType: "audio/pcm",
|
|
2361
|
+
});
|
|
2362
|
+
};
|
|
2363
|
+
const stepResult = () => JSON.parse((appendStepMock.mock.calls.at(-1)![1] as { tool_result: string }).tool_result);
|
|
2364
|
+
|
|
2365
|
+
it("aligns the transcript in the input audio", async () => {
|
|
2366
|
+
alignSpeechMock.mockResolvedValueOnce({ graphChars: Array.from("hi"), graphTimes: [[0.1, 0.2], [0.2, 0.3]] });
|
|
2367
|
+
|
|
2368
|
+
const out = await transcribeOnce();
|
|
2369
|
+
|
|
2370
|
+
expect(alignSpeechMock).toHaveBeenCalledWith(pcm, 24_000, "hi");
|
|
2371
|
+
expect(out.words).toEqual([{ text: "hi", start: 0.1, end: 0.3 }]);
|
|
2372
|
+
expect(stepResult().words).toEqual(out.words);
|
|
2373
|
+
});
|
|
2374
|
+
|
|
2375
|
+
it("returns the transcript without words when alignment fails", async () => {
|
|
2376
|
+
alignSpeechMock.mockRejectedValueOnce(new Error("speech is too long to align"));
|
|
2377
|
+
|
|
2378
|
+
const out = await transcribeOnce();
|
|
2379
|
+
|
|
2380
|
+
expect(out).toMatchObject({ text: "hi" });
|
|
2381
|
+
expect(out.words).toBeUndefined();
|
|
2382
|
+
expect(stepResult().wordsError).toBe("speech is too long to align");
|
|
2383
|
+
});
|
|
2384
|
+
});
|
|
2385
|
+
|
|
2347
2386
|
it("still returns the audio when the timing step fails", async () => {
|
|
2348
|
-
|
|
2387
|
+
alignSpeechMock.mockRejectedValueOnce(new Error("speech aligner model is not installed"));
|
|
2349
2388
|
|
|
2350
2389
|
const out = await QgridFrame.speak({ model: "openai/gpt-realtime-2.1-mini", text: "Hi there.", withTimestamps: true });
|
|
2351
2390
|
|
|
2352
2391
|
expect(out.audio).toBe(Buffer.from(wav).toString("base64"));
|
|
2353
2392
|
expect(out.audioTimestamps).toBeUndefined();
|
|
2354
|
-
expect(out.timestampsError).toBe("
|
|
2393
|
+
expect(out.timestampsError).toBe("speech aligner model is not installed");
|
|
2355
2394
|
});
|
|
2356
2395
|
});
|
|
2357
2396
|
|
|
@@ -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 {
|
|
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,
|
|
@@ -114,6 +116,7 @@ import {
|
|
|
114
116
|
RefreshFailedError,
|
|
115
117
|
} from "./oauth";
|
|
116
118
|
import { CODEX_IMAGE_GENERATION_MODEL } from "./qgrid-image-generation";
|
|
119
|
+
import { imagePlaceholderForLog } from "./qgrid-response-format";
|
|
117
120
|
import {
|
|
118
121
|
afterQuery,
|
|
119
122
|
beforeQuery,
|
|
@@ -1143,6 +1146,20 @@ async function transcribeOpenAI(input: TranscribeInput): Promise<TranscribeOutpu
|
|
|
1143
1146
|
if (input.language) output.language = input.language;
|
|
1144
1147
|
|
|
1145
1148
|
if (requestLogId !== undefined) output.requestLogId = requestLogId;
|
|
1149
|
+
let alignMs: number | undefined;
|
|
1150
|
+
let wordsError: string | undefined;
|
|
1151
|
+
|
|
1152
|
+
// Realtime transcription carries no timing: the in-process aligner places the transcript in the
|
|
1153
|
+
// input audio. Best-effort like speech timing: without it the transcript returns with no words.
|
|
1154
|
+
try {
|
|
1155
|
+
const alignStart = performance.now();
|
|
1156
|
+
const pcm = prepareRealtimeInput(audio, input.mediaType);
|
|
1157
|
+
const timestamps = await alignSpeech(pcm, OPENAI_REALTIME_SAMPLE_RATE, text);
|
|
1158
|
+
output.words = wordsFromCharTimestamps(timestamps);
|
|
1159
|
+
alignMs = Math.round(performance.now() - alignStart);
|
|
1160
|
+
} catch (error) {
|
|
1161
|
+
wordsError = error instanceof Error ? error.message : String(error);
|
|
1162
|
+
}
|
|
1146
1163
|
|
|
1147
1164
|
const log: MediaRunLog = {
|
|
1148
1165
|
tokenName: output.tokenName,
|
|
@@ -1162,7 +1179,15 @@ async function transcribeOpenAI(input: TranscribeInput): Promise<TranscribeOutpu
|
|
|
1162
1179
|
prompt: input.prompt,
|
|
1163
1180
|
durationSec,
|
|
1164
1181
|
},
|
|
1165
|
-
result: JSON.stringify({
|
|
1182
|
+
result: JSON.stringify({
|
|
1183
|
+
text,
|
|
1184
|
+
durationSec,
|
|
1185
|
+
callId,
|
|
1186
|
+
alignMs,
|
|
1187
|
+
wordsError,
|
|
1188
|
+
// Word timing of the input audio, as returned to the caller.
|
|
1189
|
+
words: output.words,
|
|
1190
|
+
}),
|
|
1166
1191
|
},
|
|
1167
1192
|
],
|
|
1168
1193
|
};
|
|
@@ -1171,35 +1196,6 @@ async function transcribeOpenAI(input: TranscribeInput): Promise<TranscribeOutpu
|
|
|
1171
1196
|
});
|
|
1172
1197
|
}
|
|
1173
1198
|
|
|
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
1199
|
/**
|
|
1204
1200
|
* OpenAI realtime speech (openai/<id>): a conversational realtime model repeating the text over
|
|
1205
1201
|
* the direct realtime socket. Output is PCM16 24 kHz, wrapped as WAV unless `format` is pcm.
|
|
@@ -1260,32 +1256,29 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
|
|
|
1260
1256
|
// pcm output is always 24 kHz PCM16, so the log copy is wrapped as WAV to stay playable.
|
|
1261
1257
|
const wav = mediaType === "audio/wav" ? audio : wrapPcmAsWav(audio);
|
|
1262
1258
|
const logAudio = mediaType === "audio/wav" ? output.audio : Buffer.from(wav).toString("base64");
|
|
1263
|
-
let
|
|
1259
|
+
let alignMs: number | undefined;
|
|
1264
1260
|
|
|
1265
1261
|
if (input.withTimestamps) {
|
|
1262
|
+
// Realtime speech carries no timing: the in-process aligner places the script in the audio.
|
|
1266
1263
|
try {
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1264
|
+
const alignStart = performance.now();
|
|
1265
|
+
// 44-byte WAV header (wrapPcmAsWav), then PCM16 mono at the realtime sample rate.
|
|
1266
|
+
const pcm = wav.subarray(44);
|
|
1267
|
+
output.audioTimestamps = await alignSpeech(pcm, OPENAI_REALTIME_SAMPLE_RATE, input.text);
|
|
1268
|
+
output.durationSec = pcm.byteLength / 2 / OPENAI_REALTIME_SAMPLE_RATE;
|
|
1270
1269
|
output.timestampsSource = "aligned";
|
|
1270
|
+
alignMs = Math.round(performance.now() - alignStart);
|
|
1271
1271
|
} catch (error) {
|
|
1272
1272
|
// The speech itself succeeded; timing is best-effort and its failure is reported, not thrown.
|
|
1273
1273
|
output.timestampsError = error instanceof Error ? error.message : String(error);
|
|
1274
1274
|
}
|
|
1275
1275
|
}
|
|
1276
1276
|
|
|
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
1277
|
const log: MediaRunLog = {
|
|
1285
1278
|
tokenName: output.tokenName,
|
|
1286
1279
|
response: audioForLog(logAudio, "audio/wav", audio.byteLength),
|
|
1287
1280
|
firstOutputAt: firstAudioAt,
|
|
1288
|
-
cost:
|
|
1281
|
+
cost: openaiSpeechCost(id, usage),
|
|
1289
1282
|
steps: [
|
|
1290
1283
|
{
|
|
1291
1284
|
toolCallId: "speech:0",
|
|
@@ -1304,14 +1297,10 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
|
|
|
1304
1297
|
audioBytes: audio.byteLength,
|
|
1305
1298
|
transcript,
|
|
1306
1299
|
usage,
|
|
1307
|
-
|
|
1308
|
-
heard: alignment.heard,
|
|
1309
|
-
matchedWords: alignment.matchedWords,
|
|
1310
|
-
scriptWords: alignment.scriptWords,
|
|
1311
|
-
},
|
|
1300
|
+
alignMs,
|
|
1312
1301
|
timestampsError: output.timestampsError,
|
|
1313
1302
|
// Word timing for the request-log detail player.
|
|
1314
|
-
words:
|
|
1303
|
+
words: output.audioTimestamps && wordsFromCharTimestamps(output.audioTimestamps),
|
|
1315
1304
|
}),
|
|
1316
1305
|
},
|
|
1317
1306
|
],
|
|
@@ -2103,7 +2092,8 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2103
2092
|
return {
|
|
2104
2093
|
toolCallId: `image_generation:0:${index}`,
|
|
2105
2094
|
args,
|
|
2106
|
-
|
|
2095
|
+
// The run's response already holds this image.
|
|
2096
|
+
result: imagePlaceholderForLog(image.mimeType, image.b64),
|
|
2107
2097
|
};
|
|
2108
2098
|
}),
|
|
2109
2099
|
};
|
|
@@ -2328,7 +2318,7 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2328
2318
|
text: output.text,
|
|
2329
2319
|
language: output.language,
|
|
2330
2320
|
durationSec: output.durationSec,
|
|
2331
|
-
// Word timing of the input audio
|
|
2321
|
+
// Word timing of the input audio, as returned to the caller.
|
|
2332
2322
|
words: output.words,
|
|
2333
2323
|
}),
|
|
2334
2324
|
},
|
|
@@ -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
|
-
|
|
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
|
|
323
|
-
// most
|
|
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 =
|
|
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
|
-
//
|
|
547
|
-
//
|
|
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
|
|
565
|
-
//
|
|
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
|
|
588
|
-
//
|
|
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
|
+
* 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
|
|
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.
|
|
258
|
-
[0.
|
|
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
|
+
});
|