@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
package/dist/cli.js CHANGED
@@ -1,9 +1,139 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFileSync, execSync, spawnSync } from "node:child_process";
3
- import { existsSync, readFileSync } from "node:fs";
4
- import { delimiter, join } from "node:path";
3
+ import { createWriteStream, existsSync, readFileSync } from "node:fs";
4
+ import { delimiter, dirname, join } from "node:path";
5
5
  import { Command } from "commander";
6
6
  import { z } from "zod";
7
+ import { createHash } from "node:crypto";
8
+ import { mkdir, mkdtemp, readdir, rename, rm } from "node:fs/promises";
9
+ import { homedir } from "node:os";
10
+ import { pipeline } from "node:stream/promises";
11
+ //#region src/aligner.ts
12
+ const QGRID_CACHE = join(homedir(), ".cache", "qgrid");
13
+ const RUNTIME_DIR = join(QGRID_CACHE, "runtime");
14
+ const ONNXRUNTIME_VERSION = "1.31.1";
15
+ const MODEL = {
16
+ url: "https://github.com/cartanova-ai/qgrid/releases/download/aligner-model-v1/mms-300m-fa-int8.onnx",
17
+ integrity: "sha256-2Tw7L2Lp/EKmGWSGeUTsuHMwaYgu2TUrWtLfnOJuGYo="
18
+ };
19
+ const RUNTIME_PACKAGES = [{
20
+ name: "onnxruntime-common",
21
+ url: `https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-${ONNXRUNTIME_VERSION}.tgz`,
22
+ integrity: "sha512-F+nnYNiQtmNJ95V6R/isBJqiVpdANCrsMEg1OaF+Bkbl3GAtzWLR7Ng17Ld0QtYtYJyotOHPJzOQn1Y6PLZjpg=="
23
+ }, {
24
+ name: "onnxruntime-node",
25
+ url: `https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-${ONNXRUNTIME_VERSION}.tgz`,
26
+ integrity: "sha512-ijnSghbDHVWaQ2nDPmVccPlCHI8kH1Mx1aJ4a/qzRP16bBcVs4E3EqZQKZCkhWnbqN1tuQWxagimFtDpbPYYQw=="
27
+ }];
28
+ function alignerModelPath(env = process.env) {
29
+ return env.QGRID_ALIGNER_MODEL || join(QGRID_CACHE, "models", "mms-300m-fa-int8.onnx");
30
+ }
31
+ /** Streams `url` to `path` through a temporary file that is kept only if it matches `integrity`. */
32
+ async function downloadVerified(url, path, integrity) {
33
+ const dash = integrity.indexOf("-");
34
+ const hash = createHash(integrity.slice(0, dash));
35
+ const response = await fetch(url);
36
+ if (!response.ok || !response.body) throw new Error(`HTTP ${response.status} from ${url}`);
37
+ await mkdir(dirname(path), { recursive: true });
38
+ const partial = `${path}.download`;
39
+ try {
40
+ await pipeline(response.body, async function* (source) {
41
+ for await (const chunk of source) {
42
+ hash.update(chunk);
43
+ yield chunk;
44
+ }
45
+ }, createWriteStream(partial));
46
+ const actual = `${integrity.slice(0, dash)}-${hash.digest("base64")}`;
47
+ if (actual !== integrity) throw new Error(`integrity mismatch for ${url}: expected ${integrity}, got ${actual}`);
48
+ await rename(partial, path);
49
+ } finally {
50
+ await rm(partial, { force: true });
51
+ }
52
+ }
53
+ /** Unpacks the pinned runtime packages into RUNTIME_DIR, keeping only this platform's binary. */
54
+ async function installRuntime() {
55
+ const nodeModules = join(RUNTIME_DIR, "node_modules");
56
+ await mkdir(nodeModules, { recursive: true });
57
+ const work = await mkdtemp(join(RUNTIME_DIR, ".install-"));
58
+ try {
59
+ for (const pkg of RUNTIME_PACKAGES) {
60
+ const tarball = join(work, `${pkg.name}.tgz`);
61
+ const unpacked = join(work, pkg.name);
62
+ await downloadVerified(pkg.url, tarball, pkg.integrity);
63
+ await mkdir(unpacked);
64
+ if (spawnSync("tar", [
65
+ "-xzf",
66
+ tarball,
67
+ "-C",
68
+ unpacked
69
+ ], { stdio: "inherit" }).status !== 0) throw new Error(`tar could not unpack ${pkg.name}`);
70
+ const target = join(nodeModules, pkg.name);
71
+ await rm(target, {
72
+ recursive: true,
73
+ force: true
74
+ });
75
+ await rename(join(unpacked, "package"), target);
76
+ }
77
+ const binaries = join(nodeModules, "onnxruntime-node", "bin", "napi-v6");
78
+ await keepOnly(binaries, process.platform);
79
+ await keepOnly(join(binaries, process.platform), process.arch);
80
+ if (!existsSync(join(binaries, process.platform, process.arch, "onnxruntime_binding.node"))) throw new Error(`onnxruntime-node has no binary for ${process.platform}/${process.arch}`);
81
+ } finally {
82
+ await rm(work, {
83
+ recursive: true,
84
+ force: true
85
+ });
86
+ }
87
+ }
88
+ async function keepOnly(dir, keep) {
89
+ const entries = existsSync(dir) ? await readdir(dir) : [];
90
+ for (const entry of entries) if (entry !== keep) await rm(join(dir, entry), {
91
+ recursive: true,
92
+ force: true
93
+ });
94
+ }
95
+ const runtimePackageSchema = z.object({ version: z.string() });
96
+ /** onnxruntime-node is importable as installed, or unpacked by --install-aligner at this version. */
97
+ function runtimeInstalled() {
98
+ if (canResolve("onnxruntime-node")) return true;
99
+ try {
100
+ const manifest = join(RUNTIME_DIR, "node_modules", "onnxruntime-node", "package.json");
101
+ const { version } = runtimePackageSchema.parse(JSON.parse(readFileSync(manifest, "utf-8")));
102
+ return version === ONNXRUNTIME_VERSION;
103
+ } catch {
104
+ return false;
105
+ }
106
+ }
107
+ /** `qgrid --install-aligner`: downloads whatever part of the aligner is missing. */
108
+ async function installSpeechAligner() {
109
+ const model = alignerModelPath();
110
+ if (existsSync(model)) console.log(`Speech aligner model already at ${model}`);
111
+ else {
112
+ console.log(`Downloading the speech aligner model (355 MB) to ${model}`);
113
+ await downloadVerified(MODEL.url, model, MODEL.integrity);
114
+ }
115
+ if (runtimeInstalled()) console.log("onnxruntime-node already installed.");
116
+ else {
117
+ console.log(`Downloading onnxruntime-node ${ONNXRUNTIME_VERSION} (115 MB) to ${RUNTIME_DIR}`);
118
+ await installRuntime();
119
+ }
120
+ console.log("Speech aligner installed. Restart qgrid if it is running.");
121
+ }
122
+ /** Without the model or onnxruntime-node the server returns OpenAI voice results without timing. */
123
+ function warnMissingSpeechAligner(env = process.env) {
124
+ if (existsSync(alignerModelPath(env)) && runtimeInstalled()) return;
125
+ console.warn("Warning: speech aligner not installed. OpenAI speech and transcription return no timing.");
126
+ console.warn("Install it with: qgrid --install-aligner");
127
+ }
128
+ function canResolve(specifier) {
129
+ try {
130
+ import.meta.resolve(specifier);
131
+ return true;
132
+ } catch {
133
+ return false;
134
+ }
135
+ }
136
+ //#endregion
7
137
  //#region src/database-env.ts
8
138
  const DATABASE_ENV_DEFAULTS = {
9
139
  HOST: "localhost",
@@ -208,7 +338,14 @@ function normalizePort(value) {
208
338
  return value;
209
339
  }
210
340
  const program = new Command();
211
- program.name("qgrid").version(pkg.version).description("Qgrid — LLM subscription token proxy server").option("--db <url>", "PostgreSQL connection URL (e.g. postgres://user:pw@host:port/dbname)").option("-p, --port <port>", "server port (default: 44900)").option("--skip-update", "skip qgrid self-update check").action(async (opts) => {
341
+ program.name("qgrid").version(pkg.version).description("Qgrid — LLM subscription token proxy server").option("--db <url>", "PostgreSQL connection URL (e.g. postgres://user:pw@host:port/dbname)").option("-p, --port <port>", "server port (default: 44900)").option("--skip-update", "skip qgrid self-update check").option("--install-aligner", "download the speech aligner model and install onnxruntime-node, then exit").action(async (opts) => {
342
+ if (opts.installAligner) try {
343
+ await installSpeechAligner();
344
+ process.exit(0);
345
+ } catch (e) {
346
+ console.error("Speech aligner install failed:", e instanceof Error ? e.message : e);
347
+ process.exit(1);
348
+ }
212
349
  const serverPort = normalizePort(opts.port ?? "44900");
213
350
  try {
214
351
  const pid = execSync(`lsof -ti :${serverPort}`, { encoding: "utf-8" }).trim();
@@ -238,6 +375,7 @@ program.name("qgrid").version(pkg.version).description("Qgrid — LLM subscripti
238
375
  if (outcome.kind === "exit") process.exit(outcome.exitCode);
239
376
  }
240
377
  warnMissingRuntimeCliDependencies();
378
+ warnMissingSpeechAligner();
241
379
  if (opts.db) {
242
380
  const m = opts.db.match(/^postgres(?:ql)?:\/\/([^:]+):(.+)@([^:]+):(\d+)\/(.+)$/);
243
381
  if (!m) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cartanova/qgrid-cli",
3
- "version": "2.17.1",
3
+ "version": "2.19.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/cartanova-ai/qgrid"
@@ -263,4 +263,4 @@ For external providers, the logger reads AI SDK's provider-neutral `onStart.outp
263
263
 
264
264
  `qgrid.transcription("openai/<id>")` and `qgrid.speech("openai/<id>")` share the Grok voice factories; the `openai/` prefix selects the realtime route and switches the option namespace to `providerOptions.openai`, whose schemas are copied field-for-field from `@ai-sdk/openai` (`openAITranscriptionModelOptions`, `openaiSpeechModelOptionsSchema`, vercel/ai `fce9210`). Honored: transcription `language`, `prompt` (`gpt-realtime-whisper` rejects `prompt` with HTTP 400 from the server; `whisper-1` accepts it but the upstream ignores it); speech `voice` (one of OpenAI realtime's 10 preset voices: `alloy ash ballad coral echo sage shimmer verse marin cedar`, default `marin`; others fail with HTTP 400), `instructions`/`openai.instructions`, `outputFormat` `wav` (default) or `pcm`. Every other set key emits the AI SDK `unsupported` warning; `language` on speech reuses the official provider's warning text and an unknown `outputFormat` falls back to `wav` with a warning (the official provider falls back to `mp3`). `providerOptions.qgrid.tokenName` must carry the `openai/` prefix. Transcription input must be PCM16 WAV or raw PCM; `segments` is empty, `durationInSeconds` is computed server-side from the audio, `language` echoes the request. Speech `providerMetadata.qgrid.mediaType` is `audio/wav` or `audio/pcm;rate=24000`. Keep model unions equal to the server's candidate lists and prune both from the live matrix (`openai-codex-runtime.md`, "Realtime voice").
265
265
 
266
- Speech timing: `qgrid.speech("grok/...")` honors one `providerOptions.xai` key, `withTimestamps` (2.16.0+); `providerOptions.qgrid.withTimestamps` (2.17.0+) works for both `grok/` and `openai/` speech and is read straight from the namespace because the qgrid option parsers drop unknown keys. Every other `xai` key still warns. Timing comes back in `providerMetadata.qgrid.audioTimestamps` (`graphChars`, `graphTimes` `[start, end]` seconds, index-aligned) plus `duration` and `timestampsSource` (`provider` for Grok, `aligned` for OpenAI); the field names match `@ai-sdk/xai`'s `providerMetadata.xai`. A failed timing step returns the audio with `timestampsError` and an `other` warning. Grok transcription maps the server's `words` to AI SDK `segments` (`startSecond`/`endSecond`, 2.17.0+); OpenAI transcription segments stay empty.
266
+ Grok speech passes the standard `speed` through as `@ai-sdk/xai` does (2.18.0+; the server enforces 0.7-1.5). Speech timing: `qgrid.speech("grok/...")` honors one `providerOptions.xai` key, `withTimestamps` (2.16.0+); `providerOptions.qgrid.withTimestamps` (2.17.0+) works for both `grok/` and `openai/` speech and is read straight from the namespace because the qgrid option parsers drop unknown keys. Every other `xai` key still warns. Timing comes back in `providerMetadata.qgrid.audioTimestamps` (`graphChars`, `graphTimes` `[start, end]` seconds, index-aligned) plus `duration` and `timestampsSource` (`provider` for Grok, `aligned` for OpenAI); the field names match `@ai-sdk/xai`'s `providerMetadata.xai`. A failed timing step returns the audio with `timestampsError` and an `other` warning. Grok transcription maps the server's `words` to AI SDK `segments` (`startSecond`/`endSecond`, 2.17.0+); OpenAI transcription segments stay empty.
@@ -44,6 +44,7 @@ Sonamu's native `SONAMU_DB_HOST`, `SONAMU_DB_PORT`, `SONAMU_DB_USER`,
44
44
  | `HOST` | `localhost` | Sonamu server listen host when running API directly. |
45
45
  | `PORT` | `44900` | Sonamu server listen port. In CLI mode this is derived from `--port`, not read as user input. |
46
46
  | `PROJECT_NAME` | `Qgrid` | Sonamu project name. Not the same as request log `projectName`. |
47
+ | `QGRID_ALIGNER_MODEL` | `~/.cache/qgrid/models/mms-300m-fa-int8.onnx` (`qgrid --install-aligner` downloads it there; a source checkout's `sonamu dev` needs only this file, since `onnxruntime-node` is an api devDependency); the Docker image sets `/opt/qgrid/models/mms-300m-fa-int8.onnx` | Speech aligner model for OpenAI speech `withTimestamps` and OpenAI transcript `words` (`openai-codex-runtime.md`, Realtime voice). Missing file or no `onnxruntime-node`: the CLI warns at startup and points to `qgrid --install-aligner` (`packages/cli/src/aligner.ts`), OpenAI speech returns `timestampsError`, and OpenAI transcripts omit `words`. |
47
48
 
48
49
  Do not treat CLI bundle bootstrapping internals as user-facing qgrid configuration.
49
50
  The packaged CLI accepts only `staging` and `production`; `development` and `test`
@@ -83,9 +83,11 @@ Qgrid exposes image generation/editing, asynchronous video start/status, transcr
83
83
 
84
84
  TTS timestamps (2.16.0+): `withTimestamps: true` on `speak` sends `with_timestamps: true`, and `/tts` then answers with a JSON envelope (`audio` base64, `content_type`, `duration`, `audio_timestamps.graph_chars` / `graph_times`) instead of raw bytes; the client decodes it and `speak` returns `audioTimestamps` (`graphChars`, `graphTimes`, character-level `[start, end]` seconds), `durationSec`, and `timestampsSource: "provider"`. Verified with the subscription token on 2026-11-09 (42 characters for a 42-character line, 0.87 s to the response).
85
85
 
86
- STT words (2.17.0+): `/stt` sends word-level `words` (`text`, `start`, `end`; `speaker` with diarize) by default; `transcribe` returns them as `TranscribeOutput.words` (`text`, `start`, `end` only). Against Grok TTS timing of the same clip, 17/17 words matched with a median boundary difference of 46 ms (p90 67 ms, STT consistently about 45 ms later), in 0.5 s.
86
+ TTS voices and delivery: the subscription token lists 28 `/tts` voices (9 female, 19 male), and all 28 generated English mp3 on 2026-11-09 (the dashboard samples); other languages and codecs are unverified. The body's `voice` is accepted as an alias of xAI's documented `voice_id`. Tags from xAI's speech-tag list (`[pause]`, `[long-pause]`, `[laugh]`, `<whisper>`, `<slow>`, `<soft>`) are performed, not read aloud; ElevenLabs-style emotion tags such as `[deadpan]` are not in the list. `speed` (2.18.0+, xAI's documented 0.7-1.5, enforced by `SpeakInput`) passes through to `/tts`: one line ran 6.91 / 4.79 / 3.23 s at 0.7 / 1.0 / 1.5 on 2026-11-09. OpenAI realtime speech rejects `speed` with HTTP 400, and the SDK still warns `unsupported` for it there.
87
87
 
88
- OpenAI speech timing (2.17.0+): OpenAI realtime has no timing data, so `speak` with `withTimestamps` transcribes the generated WAV with Grok STT on an automatically selected Grok token and aligns the heard words to the script (`utils/speech-alignment.ts`: edit-distance pairing, so mis-heard words keep their slot and a spoken preamble is skipped; unpaired script words split the gap between neighbours; each word's span is split over its characters). The result is `timestampsSource: "aligned"`; the step log records the heard text and matched/script word counts. A failed Grok step is fail-soft: the audio returns with `timestampsError`.
88
+ STT words (2.17.0+): `/stt` sends word-level `words` (`text`, `start`, `end`; `speaker` with diarize) by default; `transcribe` returns them as `TranscribeOutput.words` (`text`, `start`, `end` only). Against Grok TTS timing of the same clip, 17/17 words matched with a median boundary difference of 46 ms (p90 67 ms, in 0.5 s. The constant ~45 ms offset is not STT lag: the Grok TTS mp3 has no LAME/Xing gapless tag, so a decoder keeps the ~46 ms encoder delay and the audio starts later than `audioTimestamps` say (SON-589 bench, where an independent aligner showed the same offset). Since 2.19.0 the Grok client adds that delay (1105 samples at 24 kHz, 46 ms) to every time in mp3 responses (`grok-voice-client.ts`), so timing matches the decoded audio (residual against the aligner: 3 ms); earlier servers returned the raw xAI timing.
89
+
90
+ OpenAI speech timing no longer touches Grok (2.19.0+; 2.17.x ran a Grok STT pass): see `openai-codex-runtime.md`, Realtime voice.
89
91
 
90
92
  Image generation and editing default to `grok-imagine-image-2.0`; the public SDK lists it and
91
93
  `grok-imagine-image` (1.0). Quality omission passes through as upstream `auto`, currently low for
@@ -95,7 +97,7 @@ uses the active model's output resolution/quality and input-image count at the o
95
97
 
96
98
  Chat turns also accept `imageGeneration` (the dashboard chat sends `"auto"`): the dispatcher adds the proxy's server-side `{ "type": "image_generation" }` tool, and completed `image_generation_call` items (base64 JPEG, Grok Imagine) become `GenerateResult.images`, so generation and edits of earlier images work inside a conversation. `imageGenerationOptions` (OpenAI quality/size/background) is rejected. The turn's provider-reported cost already includes the image, so the request log stores `image_cost_usd = 0` with `image_cost_method = "included:grok-provider-cost"`. Verified 2026-10-21 through the subscription proxy; the model occasionally answers "I'll do it" without calling the tool (1 of 5 edit attempts).
97
99
 
98
- Inline audio, each inline image, and the aggregate inline images in one request are capped at 7 MiB decoded. The server maps Fastify's oversized-body error to HTTP 413 (`packages/api/src/application/qgrid/qgrid.types.ts`, `qgrid.frame.ts`).
100
+ Inline audio, each inline image, and the aggregate inline images in one request are capped at 19 MiB decoded, inside a 26 MiB JSON body limit (2.19.0+). The server maps Fastify's oversized-body error to HTTP 413 (`packages/api/src/application/qgrid/qgrid.types.ts`, `qgrid.frame.ts`).
99
101
 
100
102
  Video starts return a random 128-bit in-memory job handle. Handles expire after 24 hours, polling stays pinned to the starting token, and `projectName` must match the owner supplied at start. A started job is already admitted and billed, so `getVideo` polls with `ungated: true`: it checks only credential state (inactive, reauth, refresh failure) and skips the quota-threshold, cooldown, in-flight, on-demand, and ZDR gates that admit new requests. After the upstream poll returns, `videoStatus` re-checks `job.final`, so overlapping polls of a finished job write the request log once and return the same result. D4 returns the upstream `api.x.ai` video URL unchanged; qgrid does not fetch, proxy, or store the bytes (`qgrid.frame.ts`, `grok-media-client.ts`, `packages/ai-sdk/README.md`).
101
103
 
@@ -236,5 +236,7 @@ Sources: `openai-realtime-protocol.ts` (wire constants, session builders, PCM he
236
236
 
237
237
  - STT is the Codex subscription path: `POST https://chatgpt.com/backend-api/codex/realtime/calls` with `{sdp, session}` (synthetic Opus-only SDP offer; the transcription session is Codex's exact V2 shape), `201` + `Location: /v1/realtime/calls/rtc_…`, then a sideband `wss://api.openai.com/v1/realtime?call_id=…`. Per-request `language`/`prompt` and `turn_detection: null` go in a sideband `session.update`; audio goes as 1 s `input_audio_buffer.append` chunks plus one `commit`; the result is `conversation.item.input_audio_transcription.completed`. A call with no ICE connection is torn down about 30 s after creation (25 s idle fine, 31 s gone), so the client enforces a 25 s deadline from the POST. When that attempt ends in teardown (deadline, sideband closed/errored or handshake rejected before the transcript — `isSidebandTeardownError`), the client retries once on the direct `wss://api.openai.com/v1/realtime?intent=transcription` socket with the same headers and session (`OpenAIVoiceClientOptions.sttDirectFallback`, default on; 60 s bound). Server `error` events and `/calls` 4xx never trigger the fallback. The request log records `transport` (`realtime-calls` | `realtime-ws`) and `fallbackReason`; `callId` and quota headers are absent after a fallback. The direct socket is the same non-Codex path as TTS, so a 401/403 there means it was gated. Input must already be PCM16: WAV (`audio/wav`) or raw PCM (`audio/pcm;rate=…;channels=…`), downmixed and linearly resampled to 24 kHz mono like Codex's `convert_pcm16`; compressed input is a 400. The server reports no language or duration: `durationSec` is computed from the PCM sent and `language` echoes the request.
238
238
  - TTS is the one deviation from Codex. The `/calls` sideband never carries `response.output_audio.delta` (media stays on RTP, verified twice), and qgrid has no RTP stack, so speech uses the direct `wss://api.openai.com/v1/realtime?model=<id>` socket, which Codex itself treats as API-key-only (`realtime_conversation.rs:1931-1955`) but which accepts the ChatGPT bearer today. The session is Codex's V2 conversational payload minus `tools`, with a verbatim-reading system prompt (labeled `# Role & Objective` / `# Rules` / `# Examples` sections with capitalized never-answer rules; the caller's `instructions` follow as `# Style`), the text wrapped in `<script>…</script>` as the one `conversation.item.create` user item, and `response.create`; the output is concatenated PCM16 24 kHz returned as WAV (default) or raw PCM. OpenAI realtime has 10 preset voices, matching the Codex v2 list (`alloy ash ballad coral echo sage shimmer verse marin cedar`, default `marin`); others fail with 400. The model's own `response.output_audio_transcript.done` and `response.done.usage` audio/text tokens are logged with the request for fidelity checks. Treat a 401/403 on this socket as the path being gated: fail with the upstream error, do not fall back.
239
+ - TTS timing (2.19.0+): realtime speech carries no timing, so `speak` with `withTimestamps` force-aligns the text to the generated PCM in process (`utils/speech-aligner.ts`; 2.17.x transcribed the audio with Grok STT instead, removed by user decision 2026-11-09). The model is MMS-FA (Meta's CTC forced aligner, 1,130 languages, CC BY-NC 4.0, adopted with that license risk accepted) converted to int8 ONNX by us (355 MB, about 640 MB resident, about 0.17 s per 6 s clip on Apple Silicon). It scores 20 ms frames of 16 kHz audio against 28 letters; a Viterbi pass walks the script's letters in order. The script is romanized (Hangul per syllable, Latin accents stripped); digits, symbols, and other scripts become a star token (log-probability 0, matches any sound), and a star also wraps the script so a spoken preamble is absorbed. Audio over 30 s is scored in 30 s windows with 2 s context. The session loads on first use and unloads after 10 idle minutes. Output keeps `timestampsSource: "aligned"`; the step log records `alignMs`. The model path is `QGRID_ALIGNER_MODEL`, else `~/.cache/qgrid/models/mms-300m-fa-int8.onnx` (where `qgrid --install-aligner` downloads it), and `onnxruntime-node` is an api devDependency kept external in the build (`tsdown.config.ts` `neverBundle`; a bundled import resolves to a missing pnpm path): the Docker image installs both in layers before Claude Code and qgrid (model from the `aligner-model-v1` GitHub release, pinned by checksum, attribution in `/opt/qgrid/models/NOTICE.md`), and the image smoke test runs one alignment. An npm or pnpm install lacks both until `qgrid --install-aligner`, which fetches the model and the pinned `onnxruntime-node`/`onnxruntime-common` tarballs straight from their URLs (SRI hashes checked), unpacks the runtime with `tar` into `~/.cache/qgrid/runtime/node_modules` keeping only this platform's binary, and never calls npm or pnpm: a pnpm v11 global install isolates each global package, so a globally installed `onnxruntime-node` was invisible to qgrid (verified 2026-11-09). The server imports `onnxruntime-node` normally and falls back to that folder through `createRequire`. The Viterbi back-pointer table is frames x (2 x tokens + 1) bytes, capped at 100 MB: both grow with the audio, so about 4 minutes of dense English (251 s at 16.7 chars/s) is the most it can time; `alignSpeech` rejects longer input before running the model. Bench (SON-589): against Grok TTS character timing, word-boundary error median 4 ms / p90 20 ms / p99 25 ms on 523 words (the STT pass: 5 / 24 / 165 ms, failing on dropped fillers like "Hmm" and code-switched lines), digit words median 9 ms / p90 63 ms; on 126 OpenAI clips it agreed with the STT pass within one frame for 96% of words.
240
+ - STT words (2.19.0+): `transcribe` aligns the OpenAI transcript to the input audio with the same aligner (`prepareRealtimeInput` PCM at 24 kHz) and returns `TranscribeOutput.words`, the shape Grok STT returns; the step log records `alignMs`, or `wordsError` when alignment fails and the transcript returns without words. Measured 2026-11-09 on Apple Silicon: 2.9 s for a 54 s clip (cold load included), 9.9 s for 3.6 min; a 4.9 min clip exceeded the table cap.
239
241
  - Dispatcher: `OpenAIDispatcher.runVoice` selects a token with the same quota gate as Responses, refreshes once on a 401 and retries once, and invalidates the rate-limit cache afterwards. `OpenAIVoiceInputError` (unsupported audio, bad voice, empty text) becomes HTTP 400 `qgrid.openaiVoiceInvalidRequest`; everything else propagates as an upstream failure.
240
- - Exposed ids (user decision 2026-10-17: keep every reachable id, document limits): STT `gpt-4o-mini-transcribe`, `gpt-4o-transcribe`, `gpt-transcribe` (4/4 on the matrix), `gpt-live-transcribe` and `gpt-realtime-whisper` (return about half of a 60 s clip; whisper also mangles Korean), `whisper-1` (ignores `prompt`). `gpt-realtime-whisper` rejects `prompt` upstream, so `OPENAI_TRANSCRIPTION_MODELS_WITHOUT_PROMPT` makes the client fail with a 400 before the realtime call. TTS `gpt-realtime-2.1-mini` (13/13 verbatim, default), `gpt-realtime-2.1` (12/13), `gpt-realtime-1.5` (6/13, often answers instead of repeating) on the 2026-10-17 statement texts. Realtime models are conversational and answer text addressed to the listener: on question-form character lines the original one-sentence prompt let `gpt-realtime-2.1` answer 7 of 12, while the current sectioned prompt with `<script>` delimiters read 12/12 on both 2.1 and 2.1-mini (`docs/diagnosis/2026-11-06-openai-realtime-tts-prompt.md`; 1.5 not re-run). Keep every instruction in the system prompt: an instruction placed in the user item was read aloud. Model behavior is tracked by the live matrix (`OPENAI_LIVE=1 pnpm tsx scripts/live-openai-voice-matrix.ts`, results in `docs/diagnosis/2026-10-17-openai-realtime-audio-probe.md`). Remove an id from `OPENAI_TRANSCRIPTION_MODELS`/`OPENAI_SPEECH_MODELS`, the SDK unions, and the READMEs together when it stops passing. Unavailable on subscription (verified 2026-10-17): `/backend-api/codex/audio/transcriptions`, `/audio/speech`, `gpt-4o-mini-tts`, `tts-1*`, `gpt-transcribe` via `/codex/responses`, Responses `input_audio`. The ChatGPT-web `POST /backend-api/transcribe` works but is not used (removed from Codex in PR #16114, ignores model/language, retains uploads 30 days).
242
+ - Exposed ids (user decision 2026-10-17: keep every reachable id, document limits): STT `gpt-4o-mini-transcribe`, `gpt-4o-transcribe`, `gpt-transcribe` (4/4 on the matrix), `gpt-live-transcribe` and `gpt-realtime-whisper` (return about half of a 60 s clip; whisper also mangles Korean), `whisper-1` (ignores `prompt`). `gpt-realtime-whisper` rejects `prompt` upstream, so `OPENAI_TRANSCRIPTION_MODELS_WITHOUT_PROMPT` makes the client fail with a 400 before the realtime call. TTS `gpt-realtime-2.1-mini` (13/13 verbatim, default), `gpt-realtime-2.1` (12/13) on the 2026-10-17 statement texts; `gpt-realtime-1.5` (6/13, often answers instead of repeating) was removed from the server list, SDK union and READMEs on 2026-11-09 (user decision, 2.18.0). Realtime models are conversational and answer text addressed to the listener: on question-form character lines the original one-sentence prompt let `gpt-realtime-2.1` answer 7 of 12, while the current sectioned prompt with `<script>` delimiters read 12/12 on both 2.1 and 2.1-mini (`docs/diagnosis/2026-11-06-openai-realtime-tts-prompt.md`). That 12/12 was judged by the model's own transcript, which can omit a spoken preamble; on 2026-11-09 two independent STT models (gpt-4o-transcribe, Grok) judged 108 English clips (6 lines x `marin` `cedar` `ballad` x 3): 2.1 54/54, 2.1-mini 53/54 (one take opened with "Sure, let me read that out loud for you exactly as written."), and both read all 9 Korean/English mixed takes in full. gpt-4o-transcribe itself dropped the English part of 3 of 18 mixed clips that Grok STT heard in full. Keep every instruction in the system prompt: an instruction placed in the user item was read aloud. Model behavior is tracked by the live matrix (`OPENAI_LIVE=1 pnpm tsx scripts/live-openai-voice-matrix.ts`, results in `docs/diagnosis/2026-10-17-openai-realtime-audio-probe.md`). Remove an id from `OPENAI_TRANSCRIPTION_MODELS`/`OPENAI_SPEECH_MODELS`, the SDK unions, and the READMEs together when it stops passing. Unavailable on subscription (verified 2026-10-17): `/backend-api/codex/audio/transcriptions`, `/audio/speech`, `gpt-4o-mini-tts`, `tts-1*`, `gpt-transcribe` via `/codex/responses`, Responses `input_audio`. The ChatGPT-web `POST /backend-api/transcribe` works but is not used (removed from Codex in PR #16114, ignores model/language, retains uploads 30 days).
@@ -107,7 +107,7 @@ Input images are not stored in `request_logs.user_prompt`; that field remains th
107
107
  - `media_kind`: nullable enum (`image`, `video`, `stt`, `tts`) written at `createRun` by `startMediaRun` from the media endpoint's kind; text and chat runs keep NULL (chat-generated images are marked only by `is_image_generation`). The list `Fmt` column reads it, so any new media endpoint must open its run through `startMediaRun` or set it explicitly.
108
108
  - Speech `response`: browser-playable audio is embedded as an `<audio>` data URL (see `sonamu-api-web-flow.md`); speech `ttft_ms` is the first audio byte, passed explicitly to `finishRun` because media runs have no generate step to derive it from.
109
109
 
110
- - Voice cost (2.17.1+): subscription voice calls have no per-call bill, so `cost_usd` records the public API list-price estimate with `cost_source: "pricing_table"` (`model-cost.ts`, prices checked 2026-11-09): OpenAI realtime speech from its response usage per token type (cached input is not split out, so all input is charged as uncached text), plus the Grok STT alignment pass when timing was requested; transcription per minute of audio (OpenAI's published per-minute estimates, Grok $0.10/hour); Grok TTS $15 per 1M input characters. Unknown model ids stay unpriced (NULL). The detail page labels the figure "Voice" instead of "Driver". OpenAI speech rows store the caller's style `instructions`, and OpenAI transcription rows the STT `prompt`, as `system_prompt` (2.17.1+); the detail page titles that panel "Style instructions" or "Prompt".
110
+ - Voice cost (2.17.1+): subscription voice calls have no per-call bill, so `cost_usd` records the public API list-price estimate with `cost_source: "pricing_table"` (`model-cost.ts`, prices checked 2026-11-09): OpenAI realtime speech from its response usage per token type (cached input is not split out, so all input is charged as uncached text; the in-process timing alignment costs nothing, 2.19.0+); transcription per minute of audio (OpenAI's published per-minute estimates, Grok $0.10/hour); Grok TTS $15 per 1M input characters. Unknown model ids stay unpriced (NULL). The detail page labels the figure "Voice" instead of "Driver". OpenAI speech rows store the caller's style `instructions`, and OpenAI transcription rows the STT `prompt`, as `system_prompt` (2.17.1+); the detail page titles that panel "Style instructions" or "Prompt".
111
111
 
112
112
  ## Structured output fields
113
113
 
@@ -64,9 +64,9 @@ The list header ends its filter row with a reload button (2.10.2+) that calls th
64
64
 
65
65
  Structured output visibility: the list has an `Fmt` column (`voice/stt` or `voice/tts` when `media_kind` is `stt` or `tts`, `video` when it is `video`, otherwise `img` when `is_image_generation` is true, otherwise `json` when `is_structured` is true, otherwise `text`) and a `broken` badge driven by `response_json_ok = false`; there is no broken-JSON list filter. At review time, all 114,647 succeeded structured rows had `response_json_ok = true` and zero false rows existed; the unindexed zero-result lookup scanned 1,286,016 rows and took about 3 seconds. Before reinstating the filter, validate the failure-signal semantics and index the predicate. The detail page shows a dark Response Type panel (zod expression by default, `type` declaration via toggle) rendered server-side from the stored `json_schema`. Plain-text rows render no panel. Rows written by pre-2.7.2 servers show `text`.
66
66
 
67
- Media rows (2.15.5+): `startMediaRun` writes the nullable `media_kind` column (`image`, `video`, `stt`, `tts`) at `createRun`; text runs keep it NULL, and media rows written before the column stay NULL and show their old `Fmt` label (no backfill). Speech rows store browser-playable audio (`audio/wav`, `audio/mpeg`) in `response` as `<audio src="data:...;base64,..."></audio>`, the same inline pattern image rows use, and the detail page renders it as an `<audio controls>` player; OpenAI `pcm` output is wrapped as WAV for the log copy only, while Grok `pcm`/`mulaw`/`alaw` keep the `[audio <mime> <bytes> bytes]` placeholder. The audio is stored once, not repeated in the `speech` step result. Speech `ttft_ms` is time to the first audio byte measured from the same start as `duration_ms`: the first `response.output_audio.delta` for OpenAI realtime, response-header arrival for Grok `/tts` (not streamed, so it is close to the full duration). `finishRun` takes an explicit `ttft_ms` for runs without generate steps and otherwise derives it from the first generate step. STT rows record no TTFT; since 2.16.0 their browser-playable input audio is embedded the same way in `user_prompt` (the detail page renders the USER panel through the same media parser), and other input types keep the placeholder. Inline audio grows the request-log table with every logged voice call; `logger: false` skips it. Voice step results keep word timing (`words`: TTS output words, or the words Grok heard in the STT input; 2.17.0+); the detail page fetches that one step (subset `A`) for `tts`/`stt` rows and renders the RESPONSE or USER clip with the shared `TimedPlayer` (highlighted, clickable words).
67
+ Media rows (2.15.5+): `startMediaRun` writes the nullable `media_kind` column (`image`, `video`, `stt`, `tts`) at `createRun`; text runs keep it NULL, and media rows written before the column stay NULL and show their old `Fmt` label (no backfill). Speech rows store browser-playable audio (`audio/wav`, `audio/mpeg`) in `response` as `<audio src="data:...;base64,..."></audio>`, the same inline pattern image rows use, and the detail page renders it as an `<audio controls>` player; OpenAI `pcm` output is wrapped as WAV for the log copy only, while Grok `pcm`/`mulaw`/`alaw` keep the `[audio <mime> <bytes> bytes]` placeholder. The audio is stored once, not repeated in the `speech` step result. Speech `ttft_ms` is time to the first audio byte measured from the same start as `duration_ms`: the first `response.output_audio.delta` for OpenAI realtime, response-header arrival for Grok `/tts` (not streamed, so it is close to the full duration). `finishRun` takes an explicit `ttft_ms` for runs without generate steps and otherwise derives it from the first generate step. STT rows record no TTFT; since 2.16.0 their browser-playable input audio is embedded the same way in `user_prompt` (the detail page renders the USER panel through the same media parser), and other input types keep the placeholder. Inline audio grows the request-log table with every logged voice call; `logger: false` skips it. Voice step results keep word timing (`words`: TTS output words, or the words heard in the STT input; 2.17.0+). The detail page fetches that one step (subset `A`) only for `tts` rows and renders the RESPONSE clip with the shared `TimedPlayer` (highlighted, clickable words); `stt` rows show the input audio as a plain player (2.19.0+, by user decision 2026-11-09: timing on the user prompt read as wrong).
68
68
 
69
- Voice playground (2.15.5+): the sidebar's Playground section links `/voice`, a dashboard-only test page with Text to speech and Speech to text panels that call the generated `QgridService.useSpeakMutation` / `useTranscribeMutation` with project name `qgrid_voice`; no API was added. Voice lists are web constants: OpenAI's 10 realtime presets and the 28 Grok `/tts` voices (9 female, 19 male) listed for the subscription token on 2026-11-06; the server still validates them. Instructions and the STT prompt are shown only for `openai/` models. STT sends no `language`: a 2026-11-09 run (6 OpenAI STT models × auto/en/ko × 6 synthetic learner clips) found `en` no better than auto and `ko` translating English audio into Korean on gpt-4o-transcribe and whisper-1. The STT model list keeps only `openai/gpt-4o-transcribe` (default), `openai/gpt-4o-mini-transcribe`, and the unmeasured `grok/grok-voice-transcribe-2.0`; the server still accepts the other ids. The page is one card with Text to speech / Speech to text tabs; both panels stay mounted (the inactive one is hidden) so form state and history survive tab switches. Each result is prepended to an in-memory history row (removable, lost on reload) with a request-log link that opens in a new tab so the history is kept. TTS voices are chips (Grok split Female/Male) above the text: a name selects the voice, and ▶ plays a bundled sample from `packages/web/public/voice-samples/{openai,grok}/<voice>.mp3` without a request (and selects it; pressing again stops). Each of the 38 samples introduces itself ("I'm <Voice>. Nice to meet you. How's it going?"), regenerated on 2026-11-09 through qgrid (`grok/grok-tts`, `openai/gpt-realtime-2.1-mini`) and checked with STT; re-encoded to 40 kbps mono MP3 (about 640 KB, shipped in the CLI bundle via `web-dist`). Do not trust the OpenAI speech self-transcript as a verbatim check: one ballad take carried an audible "Okay, let's read that line aloud exactly as written." preamble that two STT models heard while `response.output_audio_transcript.done` showed only the script. A voice added upstream needs a sample file or its ▶ fails to load. STT recordings and uploads are numbered clips so one clip run through several models reads as a comparison. A "Word timing" checkbox (default on, 2.17.0+) sends `withTimestamps`; TTS rows and Grok STT rows then render the clip with its words under the player (`TimedPlayer`), highlight the word being spoken (animation-frame polling with a `timeupdate` fallback when frames are throttled), and show the timing source (Grok TTS, aligned via Grok STT, or the failure). Clicking a word plays from its start. Recordings (MediaRecorder webm/opus) and uploads are decoded with `AudioContext` at 24 kHz, mixed to mono, and sent as PCM16 WAV (`voice-audio.ts`), because the OpenAI transcription route accepts only WAV or raw PCM. Results link to their request log.
69
+ Voice playground (2.15.5+): the sidebar's Playground section links `/voice`, a dashboard-only test page with Text to speech and Speech to text panels that call the generated `QgridService.useSpeakMutation` / `useTranscribeMutation` with project name `qgrid_voice`; no API was added. Voice lists are web constants: OpenAI's 10 realtime presets and the 28 Grok `/tts` voices (9 female, 19 male) listed for the subscription token on 2026-11-06; the server still validates them. Instructions and the STT prompt are shown only for `openai/` models; in their place Grok TTS shows a Speed slider (0.7-1.5 in 0.05 steps, 2.18.0+), sent as `speed` only when it is not 1, and the history row title carries the speed. STT sends no `language`: a 2026-11-09 run (6 OpenAI STT models × auto/en/ko × 6 synthetic learner clips) found `en` no better than auto and `ko` translating English audio into Korean on gpt-4o-transcribe and whisper-1. The STT model list keeps only `openai/gpt-4o-transcribe` (default), `openai/gpt-4o-mini-transcribe`, and the unmeasured `grok/grok-voice-transcribe-2.0`; the server still accepts the other ids. The page is one card with Text to speech / Speech to text tabs; both panels stay mounted (the inactive one is hidden) so form state and history survive tab switches. Each result is prepended to an in-memory history row (removable, lost on reload) with a request-log link that opens in a new tab so the history is kept. TTS voices are chips (Grok split Female/Male) above the text: a name selects the voice, and ▶ plays a bundled sample from `packages/web/public/voice-samples/{openai,grok}/<voice>.mp3` without a request (and selects it; pressing again stops). Each of the 38 samples introduces itself ("I'm <Voice>. Nice to meet you. How's it going?"), regenerated on 2026-11-09 through qgrid (`grok/grok-tts`, `openai/gpt-realtime-2.1-mini`) and checked with STT; re-encoded to 40 kbps mono MP3 (about 640 KB, shipped in the CLI bundle via `web-dist`). Do not trust the OpenAI speech self-transcript as a verbatim check: one ballad take carried an audible "Okay, let's read that line aloud exactly as written." preamble that two STT models heard while `response.output_audio_transcript.done` showed only the script. A voice added upstream needs a sample file or its ▶ fails to load. STT recordings and uploads are numbered clips so one clip run through several models reads as a comparison. A "Word timing" checkbox (default on, 2.17.0+) sends `withTimestamps`; TTS rows and STT rows with word timing (Grok, or OpenAI through the qgrid aligner, 2.19.0+) then render the clip with its words under the player (`TimedPlayer`), highlight the word being spoken (animation-frame polling with a `timeupdate` fallback when frames are throttled), and show the timing source (Grok TTS, qgrid aligner, or the failure). Clicking a word plays from its start. For OpenAI models, recordings (MediaRecorder webm/opus) and uploads are decoded with `AudioContext` at 24 kHz, mixed to mono, and sent as PCM16 WAV (`voice-audio.ts`), because the OpenAI transcription route accepts only WAV or raw PCM; Grok gets the original file (2.19.0+), which keeps a compressed upload far under the 19 MiB inline limit. Results link to their request log.
70
70
 
71
71
  Tool contract visibility: the detail page renders a Tools panel between Response Type and Steps for requests whose `tools` is non-empty. It starts collapsed and its header shows the tool count plus a responsive, truncated name list built from the detail subset — collapsed views issue no extra query. Expanding fires `toolsView` once and caches it for that request id, since a stored tool contract never changes. Each card shows the name, the full description, the parameter count, and a compact display-only zod shape; enum values past the sixth collapse to `/* +N */`, with the full shape reachable through hover and keyboard focus. All JSON Schema conversion happens server-side — the web renders completed strings and holds no schema logic.
72
72
 
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{i as t,r as n}from"./vendor-react-8xo7RSum.js";import{u as r}from"./vendor-tanstack-6B86itGS.js";import{b as i,o as a,y as o}from"./index-D56cIqxW.js";import{t as s}from"./TimedPlayer-cuEgYA3Q.js";var c=e(t()),l=n(),u=(0,c.forwardRef)(({title:e,titleId:t,...n},r)=>(0,l.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`1.2em`,height:`1.2em`,ref:r,"aria-labelledby":t,...n,children:[e?(0,l.jsx)(`title`,{id:t,children:e}):null,(0,l.jsx)(`path`,{fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M15 3h6v6m-11 5L21 3m-3 10v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`})]})),d=(0,c.forwardRef)(({title:e,titleId:t,...n},r)=>(0,l.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`1.2em`,height:`1.2em`,ref:r,"aria-labelledby":t,...n,children:[e?(0,l.jsx)(`title`,{id:t,children:e}):null,(0,l.jsx)(`path`,{fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M21 12a9 9 0 1 1-6.219-8.56`})]})),f=(0,c.forwardRef)(({title:e,titleId:t,...n},r)=>(0,l.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`1.2em`,height:`1.2em`,ref:r,"aria-labelledby":t,...n,children:[e?(0,l.jsx)(`title`,{id:t,children:e}):null,(0,l.jsxs)(`g`,{fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,children:[(0,l.jsx)(`path`,{d:`M12 19v3m7-12v2a7 7 0 0 1-14 0v-2`}),(0,l.jsx)(`rect`,{width:6,height:13,x:9,y:2,rx:3})]})]})),p=(0,c.forwardRef)(({title:e,titleId:t,...n},r)=>(0,l.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`1.2em`,height:`1.2em`,ref:r,"aria-labelledby":t,...n,children:[e?(0,l.jsx)(`title`,{id:t,children:e}):null,(0,l.jsx)(`path`,{fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`})]})),m=24e3;function h(e,t=m){let n=new Uint8Array(44+e.length*2),r=new DataView(n.buffer),i=(e,t)=>{for(let n=0;n<t.length;n++)r.setUint8(e+n,t.charCodeAt(n))};return i(0,`RIFF`),r.setUint32(4,36+e.length*2,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0),e.forEach((e,t)=>{let n=Math.max(-1,Math.min(1,e));r.setInt16(44+t*2,n<0?n*32768:n*32767,!0)}),n}function g(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}async function _(e){let t=new AudioContext({sampleRate:m});try{let n=await t.decodeAudioData(await e.arrayBuffer()),r=new Float32Array(n.length);for(let e=0;e<n.numberOfChannels;e++){let t=n.getChannelData(e);for(let e=0;e<t.length;e++)r[e]+=t[e]/n.numberOfChannels}return g(h(r))}finally{await t.close()}}var v=`qgrid_voice`,y=[`grok/grok-tts`,`openai/gpt-realtime-2.1-mini`,`openai/gpt-realtime-2.1`],b=[`openai/gpt-4o-transcribe`,`openai/gpt-4o-mini-transcribe`,`grok/grok-voice-transcribe-2.0`],x=`marin cedar alloy ash ballad coral echo sage shimmer verse`.split(` `),S=[{label:`Female`,voices:`ara aurora carina celeste eve iris liora luna ursa`.split(` `)},{label:`Male`,voices:`altair atlas castor cosmo helios helix kepler leo lumen lux naksh orion perseus rex rigel sal sirius zagan zenith`.split(` `)}],C=[{label:``,voices:x}],w={provider:`timing from Grok TTS`,aligned:`timing aligned via Grok STT`},T=e=>e.startsWith(`openai/`),E=`w-full rounded-lg border border-sand-200/80 bg-white px-2.5 py-1.5 text-[12px] text-sand-800 placeholder:text-sand-400 focus:outline-none focus:border-sienna-300 disabled:opacity-50`,D=`${E} h-8`,O=`px-3.5 py-1.5 text-[12px] font-medium rounded-lg bg-sienna-500 text-white hover:bg-sienna-600 disabled:opacity-50 transition-all duration-150 active:scale-[0.97] inline-flex items-center gap-1.5 shadow-sm`;function k({label:e,children:t}){return(0,l.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,l.jsx)(`span`,{className:`text-[11px] font-medium text-sand-500`,children:e}),t]})}var A=e=>e.slice(e.indexOf(`/`)+1);function j({title:e,meta:t,requestLogId:n,onRemove:i,children:a}){return(0,l.jsxs)(`li`,{className:`flex flex-col gap-1.5 px-4 py-3`,children:[(0,l.jsxs)(`div`,{className:`flex items-center gap-2 text-[12px]`,children:[(0,l.jsx)(`span`,{className:`font-medium text-sand-800`,children:e}),(0,l.jsx)(`span`,{className:`tabular-nums text-sand-400`,children:t}),(0,l.jsxs)(`span`,{className:`ml-auto flex items-center gap-2`,children:[n!==void 0&&(0,l.jsxs)(r,{to:`/requests/show`,search:{id:n},target:`_blank`,className:`inline-flex items-center gap-1 tabular-nums text-sand-500 hover:text-sienna-500`,children:[`request log #`,n,(0,l.jsx)(u,{className:`size-3`})]}),(0,l.jsx)(`button`,{type:`button`,onClick:i,title:`Remove from history`,className:`text-sand-300 hover:text-sand-600`,children:(0,l.jsx)(o,{className:`size-3.5`})})]})]}),a]})}function M({empty:e,children:t}){return t.length===0?(0,l.jsx)(`p`,{className:`px-4 py-6 text-center text-[12px] text-sand-400`,children:e}):(0,l.jsx)(`ul`,{className:`divide-y divide-sand-100`,children:t})}function N(e){if(!e)return;let t=[],n;return e.graphChars.forEach((r,i)=>{let[a,o]=e.graphTimes[i];/\s/.test(r)?n=void 0:n?(n.text+=r,n.end=o):(n={text:r,start:a,end:o},t.push(n))}),t}function P(){let[e,t]=(0,c.useState)(y[0]),[n,r]=(0,c.useState)(`ara`),[o,u]=(0,c.useState)(``),[f,m]=(0,c.useState)(`Hi! What did you do this weekend?`),[h,g]=(0,c.useState)([]),[_,b]=(0,c.useState)(!0),P=(0,c.useRef)(0),F=a.useSpeakMutation(),I=T(e),L=e=>{T(e)!==I&&r(T(e)?x[0]:`ara`),t(e)},R=I&&o.trim()?o.trim():void 0,z=t=>{let n=performance.now(),r={model:e,text:f,voice:t,projectName:v};R&&(r.instructions=R),_&&(r.withTimestamps=!0),F.mutate({params:r},{onSuccess:i=>{let a={key:P.current++,src:`data:${i.mimeType};base64,${i.audio}`,model:e,voice:t,instructions:r.instructions,text:f,elapsedMs:performance.now()-n,requestLogId:i.requestLogId,words:N(i.audioTimestamps),timing:i.timestampsError?`timing failed: ${i.timestampsError}`:i.timestampsSource&&w[i.timestampsSource]};g(e=>[a,...e])}})},B=(0,c.useRef)(null),[V,H]=(0,c.useState)();(0,c.useEffect)(()=>()=>B.current?.pause(),[]);let U=e=>{if(r(e),B.current?.pause(),V===e){H(void 0);return}let t=new Audio(`/voice-samples/${I?`openai`:`grok`}/${e}.mp3`);t.addEventListener(`ended`,()=>H(t=>t===e?void 0:t),{once:!0}),B.current=t,H(e),t.play()};return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`flex flex-col gap-3 p-4`,children:[(0,l.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,l.jsx)(k,{label:`Model`,children:(0,l.jsx)(`select`,{value:e,onChange:e=>L(e.target.value),className:D,children:y.map(e=>(0,l.jsx)(`option`,{value:e,children:e},e))})}),I&&(0,l.jsx)(k,{label:`Style instructions (OpenAI only)`,children:(0,l.jsx)(`input`,{value:o,onChange:e=>u(e.target.value),placeholder:`e.g. Speak with a gentle Irish accent.`,className:D})})]}),(0,l.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,l.jsx)(`span`,{className:`text-[11px] font-medium text-sand-500`,children:`Voice — ▶ plays a short self-introduction sample, a name selects it`}),(I?C:S).map(e=>(0,l.jsxs)(`div`,{className:`flex items-start gap-2`,children:[e.label&&(0,l.jsx)(`span`,{className:`w-12 shrink-0 pt-1 text-[11px] text-sand-400`,children:e.label}),(0,l.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.voices.map(e=>(0,l.jsxs)(`span`,{className:`inline-flex items-center overflow-hidden rounded-full border text-[12px] ${n===e?`border-sienna-400 bg-sienna-50 text-sienna-700`:`border-sand-200/80 bg-white text-sand-700`}`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>r(e),"aria-pressed":n===e,className:`py-0.5 pl-2.5 pr-1 hover:text-sienna-600`,children:e}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>U(e),title:V===e?`Stop "${e}"`:`Play a "${e}" sample`,className:`py-1 pl-1 pr-2 hover:text-sienna-500 ${V===e?`text-sienna-500`:`text-sand-400`}`,children:V===e?(0,l.jsx)(i,{className:`size-3`}):(0,l.jsx)(p,{className:`size-3`})})]},e))})]},e.label))]}),(0,l.jsx)(k,{label:`Text`,children:(0,l.jsx)(`textarea`,{value:f,onChange:e=>m(e.target.value),rows:3,className:`${E} resize-y`})}),(0,l.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,l.jsxs)(`button`,{type:`button`,onClick:()=>z(n),disabled:F.isPending||!f.trim(),className:O,children:[F.isPending&&(0,l.jsx)(d,{className:`size-3.5 animate-spin`}),`Generate with `,n]}),(0,l.jsxs)(`label`,{className:`flex items-center gap-1.5 text-[12px] text-sand-600`,children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:_,onChange:e=>b(e.target.checked),className:`accent-sienna-500`}),`Word timing`]}),F.isError&&(0,l.jsx)(`p`,{className:`text-[12px] text-danger-500 break-words`,children:F.error?.message})]})]}),(0,l.jsx)(`div`,{className:`border-t border-sand-100`,children:(0,l.jsx)(M,{empty:`Generated clips stack here, newest first, so voices can be compared side by side.`,children:h.map(e=>(0,l.jsxs)(j,{title:`${e.voice} · ${A(e.model)}`,meta:[`${(e.elapsedMs/1e3).toFixed(1)}s`,e.timing].filter(Boolean).join(` · `),requestLogId:e.requestLogId,onRemove:()=>g(t=>t.filter(t=>t.key!==e.key)),children:[(!e.words||e.instructions)&&(0,l.jsxs)(`p`,{className:`truncate text-[12px] text-sand-600`,title:e.text,children:[!e.words&&e.text,e.instructions&&(0,l.jsxs)(`span`,{className:`text-sand-400`,children:[` — `,e.instructions]})]}),(0,l.jsx)(s,{src:e.src,words:e.words,autoPlay:!0})]},e.key))})})]})}function F(){let[e,t]=(0,c.useState)(b[0]),[n,r]=(0,c.useState)(``),[o,u]=(0,c.useState)(),[p,m]=(0,c.useState)(!1),[h,g]=(0,c.useState)(),[y,x]=(0,c.useState)([]),S=(0,c.useRef)(null),C=(0,c.useRef)([]),w=(0,c.useRef)(0),E=a.useTranscribeMutation(),N=T(e);(0,c.useEffect)(()=>()=>{S.current?.stream.getTracks().forEach(e=>e.stop()),C.current.forEach(e=>URL.revokeObjectURL(e))},[]);let P=e=>{let t=URL.createObjectURL(e);C.current.push(t),u({blob:e,url:t,clip:C.current.length})};return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`flex flex-col gap-3 p-4`,children:[(0,l.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,l.jsx)(k,{label:`Model`,children:(0,l.jsx)(`select`,{value:e,onChange:e=>t(e.target.value),className:D,children:b.map(e=>(0,l.jsx)(`option`,{value:e,children:e},e))})}),N&&(0,l.jsx)(k,{label:`Prompt (OpenAI only)`,children:(0,l.jsx)(`input`,{value:n,onChange:e=>r(e.target.value),placeholder:`domain words, e.g. qgrid, Kuma`,className:D})})]}),(0,l.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,l.jsxs)(`button`,{type:`button`,onClick:async()=>{if(p)S.current?.stop(),m(!1);else{g(void 0);try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e),n=[];t.ondataavailable=e=>n.push(e.data),t.onstop=()=>{e.getTracks().forEach(e=>e.stop()),P(new Blob(n,{type:t.mimeType}))},t.start(),S.current=t,m(!0)}catch(e){g(e instanceof Error?e.message:String(e))}}},className:`${O} ${p?`bg-danger-500 hover:bg-danger-500`:``}`,children:[p?(0,l.jsx)(i,{className:`size-3.5`}):(0,l.jsx)(f,{className:`size-3.5`}),p?`Stop`:`Record`]}),(0,l.jsxs)(`label`,{className:`text-[12px] text-sand-600 cursor-pointer hover:text-sienna-500`,children:[`or upload a file`,(0,l.jsx)(`input`,{type:`file`,accept:`audio/*`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];t&&P(t)}})]}),h&&(0,l.jsx)(`p`,{className:`text-[12px] text-danger-500 break-words`,children:h})]}),o&&(0,l.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,l.jsxs)(`span`,{className:`shrink-0 text-[11px] font-medium text-sand-500`,children:[`clip `,o.clip]}),(0,l.jsx)(`audio`,{controls:!0,src:o.url,className:`h-8 w-full`})]}),(0,l.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,l.jsxs)(`button`,{type:`button`,onClick:async()=>{if(!o)return;g(void 0);let t;try{t=await _(o.blob)}catch(e){g(`could not decode audio: ${e instanceof Error?e.message:String(e)}`);return}let r={model:e,audio:t,mediaType:`audio/wav`,projectName:v};N&&n.trim()&&(r.prompt=n.trim());let i=performance.now();E.mutate({params:r},{onSuccess:t=>{let n={key:w.current++,clip:o.clip,clipUrl:o.url,model:e,prompt:r.prompt,text:t.text,elapsedMs:performance.now()-i,durationSec:t.durationSec,requestLogId:t.requestLogId,words:t.words};x(e=>[n,...e])}})},disabled:!o||p||E.isPending,className:O,children:[E.isPending&&(0,l.jsx)(d,{className:`size-3.5 animate-spin`}),`Transcribe`]}),E.isError&&(0,l.jsx)(`p`,{className:`text-[12px] text-danger-500 break-words`,children:E.error?.message})]})]}),(0,l.jsx)(`div`,{className:`border-t border-sand-100`,children:(0,l.jsx)(M,{empty:`Transcripts stack here, newest first; run one clip through several models to compare.`,children:y.map(e=>(0,l.jsx)(j,{title:`clip ${e.clip} · ${A(e.model)}`,meta:[`${(e.elapsedMs/1e3).toFixed(1)}s`,e.durationSec===void 0?``:`${e.durationSec.toFixed(1)}s audio`,e.prompt?`prompt: ${e.prompt}`:``].filter(Boolean).join(` · `),requestLogId:e.requestLogId,onRemove:()=>x(t=>t.filter(t=>t.key!==e.key)),children:e.words&&e.words.length>0?(0,l.jsx)(s,{src:e.clipUrl,words:e.words}):(0,l.jsx)(`p`,{className:`rounded-lg bg-sand-50 px-3 py-2 text-[13px] text-sand-800 whitespace-pre-wrap`,children:e.text||`(empty transcript)`})},e.key))})})]})}var I=[{id:`tts`,label:`Text to speech`},{id:`stt`,label:`Speech to text`}];function L(){let[e,t]=(0,c.useState)(`tts`);return(0,l.jsxs)(`section`,{className:`rounded-xl border border-sand-200/70 bg-white overflow-hidden`,children:[(0,l.jsx)(`div`,{role:`tablist`,className:`flex gap-1 border-b border-sand-100 px-3 pt-2`,children:I.map(n=>(0,l.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":e===n.id,onClick:()=>t(n.id),className:`-mb-px border-b-2 px-3 py-2 text-[13px] transition-colors duration-150 ${e===n.id?`border-sienna-500 font-medium text-sand-800`:`border-transparent text-sand-500 hover:text-sand-700`}`,children:n.label},n.id))}),(0,l.jsx)(`div`,{role:`tabpanel`,hidden:e!==`tts`,children:(0,l.jsx)(P,{})}),(0,l.jsx)(`div`,{role:`tabpanel`,hidden:e!==`stt`,children:(0,l.jsx)(F,{})})]})}function R(){return(0,l.jsx)(`div`,{className:`max-w-3xl mx-auto`,children:(0,l.jsx)(L,{})})}export{R as component};