@cartanova/qgrid-cli 2.19.3 → 2.21.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 (36) hide show
  1. package/bundle/dist/application/qgrid/qgrid.types.js +75 -2
  2. package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +19 -51
  3. package/bundle/dist/utils/providers/openai/openai-voice-client.js +1 -1
  4. package/bundle/src/application/qgrid/qgrid.types.ts +72 -0
  5. package/bundle/src/utils/providers/openai/openai-realtime-protocol.ts +26 -53
  6. package/bundle/src/utils/providers/openai/openai-voice-client.test.ts +6 -2
  7. package/bundle/web-dist/client/assets/TimedPlayer-UGSsgTKj.js +1 -0
  8. package/bundle/web-dist/client/assets/{index-CpOwNalw.css → index-BITKCBxB.css} +1 -1
  9. package/bundle/web-dist/client/assets/{index-B5yorZqv.js → index-NGqKa5_C.js} +14 -14
  10. package/bundle/web-dist/client/assets/{logs-Bx_jXEDZ.js → logs-BLhlxqoB.js} +1 -1
  11. package/bundle/web-dist/client/assets/{monit-CPQ18s_m.js → monit-C3stGFEK.js} +1 -1
  12. package/bundle/web-dist/client/assets/{routes-S4D5Ld4L.js → routes-Dgh-_yS5.js} +1 -1
  13. package/bundle/web-dist/client/assets/{settings-M4h_UV87.js → settings-DiOZwvRj.js} +1 -1
  14. package/bundle/web-dist/client/assets/show-DucEoTrr.js +2 -0
  15. package/bundle/web-dist/client/assets/{tokens-BgBD07ru.js → tokens-DvCT1bbk.js} +1 -1
  16. package/bundle/web-dist/client/assets/{use-oauth-login-flow-D_wI9MzM.js → use-oauth-login-flow-DazQfaBL.js} +1 -1
  17. package/bundle/web-dist/client/assets/{use-update-token-mutation-IvuH3Qje.js → use-update-token-mutation-CfGbUel6.js} +1 -1
  18. package/bundle/web-dist/client/assets/voice-zPre2iO8.js +4 -0
  19. package/bundle/web-dist/client/index.html +2 -2
  20. package/bundle/web-dist/server/assets/TimedPlayer-CcClBzGi.js +193 -0
  21. package/bundle/web-dist/server/assets/{logs-HPho1SkC.js → logs-CxAwuDKc.js} +1 -1
  22. package/bundle/web-dist/server/assets/{routes-BNHCX4VI.js → routes-W-pd1Hps.js} +1 -1
  23. package/bundle/web-dist/server/assets/{settings-NJUyaSrJ.js → settings-CFdTg1_f.js} +1 -1
  24. package/bundle/web-dist/server/assets/{show-Dz5QGL7l.js → show-DVEIHsXh.js} +35 -157
  25. package/bundle/web-dist/server/assets/{tokens-BPQvjIGq.js → tokens-BO1hyBuB.js} +1 -1
  26. package/bundle/web-dist/server/assets/voice-BCF-Pkzo.js +1115 -0
  27. package/bundle/web-dist/server/entry-server.generated.js +81 -8
  28. package/package.json +1 -1
  29. package/skills/qgrid/references/ai-sdk-provider-contract.md +4 -0
  30. package/skills/qgrid/references/openai-codex-runtime.md +1 -0
  31. package/skills/qgrid/references/sonamu-api-web-flow.md +1 -1
  32. package/bundle/web-dist/client/assets/TimedPlayer-cuEgYA3Q.js +0 -1
  33. package/bundle/web-dist/client/assets/show-BchF-T1a.js +0 -2
  34. package/bundle/web-dist/client/assets/voice-CnIiQMbo.js +0 -1
  35. package/bundle/web-dist/server/assets/TimedPlayer-COqaTQSl.js +0 -54
  36. package/bundle/web-dist/server/assets/voice-xFFT4zqK.js +0 -985
@@ -0,0 +1,1115 @@
1
+ import { C as looseObject, D as string, X as require_jsx_runtime, Z as require_react, n as QgridService, tt as __toESM } from "./services.generated-C3b31_vt.js";
2
+ import { _ as VOICE_TAB_TITLES, b as Link, c as OPENAI_LIVE_VOICES, d as ForwardRef$4, f as ForwardRef$5, g as VOICE_TAB_IDS, l as OPENAI_SPEECH_VOICES, n as Route, o as Effort, s as GROK_TTS_VOICES, u as QGRID_MODEL_GROUPS } from "../entry-server.generated.js";
3
+ import { n as CodePanel, t as TimedPlayer } from "./TimedPlayer-CcClBzGi.js";
4
+ //#region ~icons/lucide/external-link.jsx
5
+ var import_react = /* @__PURE__ */ __toESM(require_react());
6
+ var import_jsx_runtime = require_jsx_runtime();
7
+ var lucideExternalLink = ({ title, titleId, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("svg", {
8
+ viewBox: "0 0 24 24",
9
+ width: "1.2em",
10
+ height: "1.2em",
11
+ ref,
12
+ "aria-labelledby": titleId,
13
+ ...props,
14
+ children: [title ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("title", {
15
+ id: titleId,
16
+ children: title
17
+ }) : null, /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", {
18
+ fill: "none",
19
+ stroke: "currentColor",
20
+ strokeLinecap: "round",
21
+ strokeLinejoin: "round",
22
+ strokeWidth: 2,
23
+ 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"
24
+ })]
25
+ });
26
+ var ForwardRef$3 = (0, import_react.forwardRef)(lucideExternalLink);
27
+ //#endregion
28
+ //#region ~icons/lucide/loader-circle.jsx
29
+ var lucideLoaderCircle = ({ title, titleId, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("svg", {
30
+ viewBox: "0 0 24 24",
31
+ width: "1.2em",
32
+ height: "1.2em",
33
+ ref,
34
+ "aria-labelledby": titleId,
35
+ ...props,
36
+ children: [title ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("title", {
37
+ id: titleId,
38
+ children: title
39
+ }) : null, /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", {
40
+ fill: "none",
41
+ stroke: "currentColor",
42
+ strokeLinecap: "round",
43
+ strokeLinejoin: "round",
44
+ strokeWidth: 2,
45
+ d: "M21 12a9 9 0 1 1-6.219-8.56"
46
+ })]
47
+ });
48
+ var ForwardRef$2 = (0, import_react.forwardRef)(lucideLoaderCircle);
49
+ //#endregion
50
+ //#region ~icons/lucide/mic.jsx
51
+ var lucideMic = ({ title, titleId, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("svg", {
52
+ viewBox: "0 0 24 24",
53
+ width: "1.2em",
54
+ height: "1.2em",
55
+ ref,
56
+ "aria-labelledby": titleId,
57
+ ...props,
58
+ children: [title ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("title", {
59
+ id: titleId,
60
+ children: title
61
+ }) : null, /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("g", {
62
+ fill: "none",
63
+ stroke: "currentColor",
64
+ strokeLinecap: "round",
65
+ strokeLinejoin: "round",
66
+ strokeWidth: 2,
67
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", { d: "M12 19v3m7-12v2a7 7 0 0 1-14 0v-2" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("rect", {
68
+ width: 6,
69
+ height: 13,
70
+ x: 9,
71
+ y: 2,
72
+ rx: 3
73
+ })]
74
+ })]
75
+ });
76
+ var ForwardRef$1 = (0, import_react.forwardRef)(lucideMic);
77
+ //#endregion
78
+ //#region ~icons/lucide/play.jsx
79
+ var lucidePlay = ({ title, titleId, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("svg", {
80
+ viewBox: "0 0 24 24",
81
+ width: "1.2em",
82
+ height: "1.2em",
83
+ ref,
84
+ "aria-labelledby": titleId,
85
+ ...props,
86
+ children: [title ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("title", {
87
+ id: titleId,
88
+ children: title
89
+ }) : null, /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", {
90
+ fill: "none",
91
+ stroke: "currentColor",
92
+ strokeLinecap: "round",
93
+ strokeLinejoin: "round",
94
+ strokeWidth: 2,
95
+ 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"
96
+ })]
97
+ });
98
+ var ForwardRef = (0, import_react.forwardRef)(lucidePlay);
99
+ //#endregion
100
+ //#region src/components/qgrid/voice-audio.ts
101
+ var VOICE_SAMPLE_RATE = 24e3;
102
+ /** Mono PCM16 WAV from float samples in [-1, 1]; out-of-range samples are clipped. */
103
+ function encodeWav(samples, sampleRate = VOICE_SAMPLE_RATE) {
104
+ const out = new Uint8Array(44 + samples.length * 2);
105
+ const view = new DataView(out.buffer);
106
+ const ascii = (offset, text) => {
107
+ for (let i = 0; i < text.length; i++) view.setUint8(offset + i, text.charCodeAt(i));
108
+ };
109
+ ascii(0, "RIFF");
110
+ view.setUint32(4, 36 + samples.length * 2, true);
111
+ ascii(8, "WAVE");
112
+ ascii(12, "fmt ");
113
+ view.setUint32(16, 16, true);
114
+ view.setUint16(20, 1, true);
115
+ view.setUint16(22, 1, true);
116
+ view.setUint32(24, sampleRate, true);
117
+ view.setUint32(28, sampleRate * 2, true);
118
+ view.setUint16(32, 2, true);
119
+ view.setUint16(34, 16, true);
120
+ ascii(36, "data");
121
+ view.setUint32(40, samples.length * 2, true);
122
+ samples.forEach((sample, i) => {
123
+ const clipped = Math.max(-1, Math.min(1, sample));
124
+ view.setInt16(44 + i * 2, clipped < 0 ? clipped * 32768 : clipped * 32767, true);
125
+ });
126
+ return out;
127
+ }
128
+ function bytesToBase64(bytes) {
129
+ let binary = "";
130
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
131
+ return btoa(binary);
132
+ }
133
+ /** Decodes any browser-playable audio, mixes it to mono at 24 kHz, and returns base64 WAV. */
134
+ async function audioToWavBase64(blob) {
135
+ const context = new AudioContext({ sampleRate: VOICE_SAMPLE_RATE });
136
+ try {
137
+ const buffer = await context.decodeAudioData(await blob.arrayBuffer());
138
+ const mono = new Float32Array(buffer.length);
139
+ for (let channel = 0; channel < buffer.numberOfChannels; channel++) {
140
+ const data = buffer.getChannelData(channel);
141
+ for (let i = 0; i < data.length; i++) mono[i] += data[i] / buffer.numberOfChannels;
142
+ }
143
+ return bytesToBase64(encodeWav(mono));
144
+ } finally {
145
+ await context.close();
146
+ }
147
+ }
148
+ //#endregion
149
+ //#region src/components/qgrid/voice-sdk-examples.ts
150
+ var literal = (value) => JSON.stringify(value);
151
+ var qgridImport = (...types) => `import { ${["qgrid", ...types.map((type) => `type ${type}`)].join(", ")} } from "@cartanova/qgrid-ai-sdk";`;
152
+ function ttsExample(options) {
153
+ const openai = options.model.startsWith("openai/");
154
+ const voiceType = openai ? "QgridOpenAISpeechVoice" : "QgridGrokVoice";
155
+ const lines = [
156
+ ` model: qgrid.speech(${literal(options.model)}),`,
157
+ ` text: ${literal(options.text)},`,
158
+ ` voice: ${literal(options.voice)} satisfies ${voiceType},`
159
+ ];
160
+ if (options.instructions) lines.push(` instructions: ${literal(options.instructions)},`);
161
+ if (options.speed !== void 0) lines.push(` speed: ${options.speed},`);
162
+ lines.push(` outputFormat: ${literal(openai ? "wav" : "mp3")},`);
163
+ if (options.withTimestamps) lines.push(" providerOptions: { qgrid: { withTimestamps: true } },");
164
+ return [
165
+ "import { generateSpeech } from \"ai\";",
166
+ qgridImport(voiceType),
167
+ "",
168
+ "const speech = await generateSpeech({",
169
+ ...lines,
170
+ "});"
171
+ ].join("\n");
172
+ }
173
+ function sttExample(options) {
174
+ const openai = options.model.startsWith("openai/");
175
+ const lines = [` model: qgrid.transcription(${literal(options.model)}),`, ...openai ? [" // OpenAI takes PCM16 WAV or raw PCM.", " audio: await readFile(\"recording.wav\"),"] : [" audio: await readFile(\"recording.mp3\"),"]];
176
+ if (options.prompt) lines.push(` providerOptions: { openai: { prompt: ${literal(options.prompt)} } },`);
177
+ return [
178
+ "import { readFile } from \"node:fs/promises\";",
179
+ "import { transcribe } from \"ai\";",
180
+ qgridImport(),
181
+ "",
182
+ "const transcript = await transcribe({",
183
+ ...lines,
184
+ "});"
185
+ ].join("\n");
186
+ }
187
+ function liveExample(options) {
188
+ const config = [`voice: ${literal(options.voice)} satisfies QgridLiveVoice`];
189
+ if (options.instructions) config.push(`instructions: ${literal(options.instructions)}`);
190
+ const { model, effort, webSearch } = options.delegation;
191
+ const qgrid = [
192
+ " delegation: {",
193
+ ` model: ${literal(model)},`,
194
+ ` effort: ${literal(effort)},`,
195
+ ` webSearch: ${webSearch},`,
196
+ " },"
197
+ ];
198
+ if (!options.logged) qgrid.push(" logger: false,");
199
+ if (options.continues) qgrid.push(" history, // earlier turns, at most 128");
200
+ return [
201
+ "// Browser",
202
+ "import { createQgridRealtime } from \"@cartanova/qgrid-ai-sdk/realtime\";",
203
+ "import { experimental_useRealtime } from \"@ai-sdk/react\";",
204
+ "",
205
+ "// Module scope: the hook starts a new session whenever it gets a new model object.",
206
+ "const model = createQgridRealtime(\"openai/gpt-live-1\");",
207
+ "",
208
+ "const realtime = experimental_useRealtime({",
209
+ " model,",
210
+ " api: { session: \"/api/live\" },",
211
+ "});",
212
+ "",
213
+ "// Server: POST /api/live",
214
+ qgridImport("QgridLiveVoice"),
215
+ "",
216
+ "const answer = await qgrid.realtime(\"openai/gpt-live-1\").doCreateWebRTCSession({",
217
+ " sdp,",
218
+ " // Voice and instructions are set here, on the server.",
219
+ " sessionConfig: {",
220
+ ...config.map((entry) => ` ${entry},`),
221
+ " providerOptions: {",
222
+ " qgrid: {",
223
+ ...qgrid,
224
+ " },",
225
+ " },",
226
+ " },",
227
+ "});"
228
+ ].join("\n");
229
+ }
230
+ //#endregion
231
+ //#region src/components/qgrid/VoicePlayground.tsx
232
+ var PROJECT_NAME = "qgrid_voice_playground";
233
+ var TTS_MODELS = [
234
+ "grok/grok-tts",
235
+ "openai/gpt-realtime-2.1-mini",
236
+ "openai/gpt-realtime-2.1"
237
+ ];
238
+ var STT_MODELS = ["openai/gpt-transcribe", "grok/grok-voice-transcribe-2.0"];
239
+ var GROK_VOICE_GROUPS = [{
240
+ label: "Female",
241
+ voices: GROK_TTS_VOICES.female
242
+ }, {
243
+ label: "Male",
244
+ voices: GROK_TTS_VOICES.male
245
+ }];
246
+ var OPENAI_VOICE_GROUPS = [{
247
+ label: "",
248
+ voices: OPENAI_SPEECH_VOICES
249
+ }];
250
+ var TIMING_SOURCE = {
251
+ provider: "timing from Grok TTS",
252
+ aligned: "timing from qgrid aligner"
253
+ };
254
+ var isOpenAI = (model) => model.startsWith("openai/");
255
+ var FIELD = "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";
256
+ var CONTROL = `${FIELD} h-8`;
257
+ var BUTTON = "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";
258
+ function Field({ label, children }) {
259
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", {
260
+ className: "flex flex-col gap-1",
261
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
262
+ className: "text-[11px] font-medium text-sand-500",
263
+ children: label
264
+ }), children]
265
+ });
266
+ }
267
+ var shortModel = (model) => model.slice(model.indexOf("/") + 1);
268
+ /**
269
+ * One past result. The request-log link opens a new tab so leaving the playground does not drop
270
+ * the in-memory history.
271
+ */
272
+ function HistoryRow({ title, meta, requestLogId, onRemove, children }) {
273
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", {
274
+ className: "flex flex-col gap-1.5 px-4 py-3",
275
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
276
+ className: "flex items-center gap-2 text-[12px]",
277
+ children: [
278
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
279
+ className: "font-medium text-sand-800",
280
+ children: title
281
+ }),
282
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
283
+ className: "tabular-nums text-sand-400",
284
+ children: meta
285
+ }),
286
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
287
+ className: "ml-auto flex items-center gap-2",
288
+ children: [requestLogId !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Link, {
289
+ to: "/requests/show",
290
+ search: { id: requestLogId },
291
+ target: "_blank",
292
+ className: "inline-flex items-center gap-1 tabular-nums text-sand-500 hover:text-sienna-500",
293
+ children: [
294
+ "request log #",
295
+ requestLogId,
296
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ForwardRef$3, { className: "size-3" })
297
+ ]
298
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", {
299
+ type: "button",
300
+ onClick: onRemove,
301
+ title: "Remove from history",
302
+ className: "text-sand-300 hover:text-sand-600",
303
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ForwardRef$4, { className: "size-3.5" })
304
+ })]
305
+ })
306
+ ]
307
+ }), children]
308
+ });
309
+ }
310
+ /**
311
+ * The panel beside its @cartanova/qgrid-ai-sdk call for the current settings, as two cards with a
312
+ * gap like the request log's columns; the call stacks below on narrower screens.
313
+ */
314
+ function WithSdkExample({ code, note, children }) {
315
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
316
+ className: "flex flex-col xl:flex-row gap-4 items-stretch xl:items-start",
317
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
318
+ className: "panel overflow-hidden flex-1 min-w-0",
319
+ children
320
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
321
+ className: "min-w-0 xl:w-[32rem] xl:shrink-0 xl:sticky xl:top-4",
322
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CodePanel, {
323
+ title: "AI SDK",
324
+ code,
325
+ scroll: false,
326
+ actions: note && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
327
+ className: "text-[11px] text-sand-400",
328
+ children: note
329
+ })
330
+ })
331
+ })]
332
+ });
333
+ }
334
+ function History({ empty, children }) {
335
+ return children.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
336
+ className: "px-4 py-6 text-center text-[12px] text-sand-400",
337
+ children: empty
338
+ }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", {
339
+ className: "divide-y divide-sand-100",
340
+ children
341
+ });
342
+ }
343
+ /** Words from per-character timing (Grok TTS shape): each run of non-space characters is a word. */
344
+ function wordsFromCharTimes(timestamps) {
345
+ if (!timestamps) return void 0;
346
+ const words = [];
347
+ let current;
348
+ timestamps.graphChars.forEach((char, i) => {
349
+ const [start, end] = timestamps.graphTimes[i];
350
+ if (/\s/.test(char)) {
351
+ current = void 0;
352
+ return;
353
+ }
354
+ if (current) {
355
+ current.text += char;
356
+ current.end = end;
357
+ } else {
358
+ current = {
359
+ text: char,
360
+ start,
361
+ end
362
+ };
363
+ words.push(current);
364
+ }
365
+ });
366
+ return words;
367
+ }
368
+ function TtsPanel() {
369
+ const [model, setModel] = (0, import_react.useState)(TTS_MODELS[0]);
370
+ const [voice, setVoice] = (0, import_react.useState)(GROK_TTS_VOICES.female[0]);
371
+ const [instructions, setInstructions] = (0, import_react.useState)("");
372
+ const [text, setText] = (0, import_react.useState)("Hi! What did you do this weekend?");
373
+ const [history, setHistory] = (0, import_react.useState)([]);
374
+ const [withTimestamps, setWithTimestamps] = (0, import_react.useState)(true);
375
+ const [speed, setSpeed] = (0, import_react.useState)(1);
376
+ const nextKey = (0, import_react.useRef)(0);
377
+ const speak = QgridService.useSpeakMutation();
378
+ const openai = isOpenAI(model);
379
+ const changeModel = (next) => {
380
+ if (isOpenAI(next) !== openai) setVoice(isOpenAI(next) ? OPENAI_SPEECH_VOICES[0] : GROK_TTS_VOICES.female[0]);
381
+ setModel(next);
382
+ };
383
+ const style = openai && instructions.trim() ? instructions.trim() : void 0;
384
+ const generate = (voiceId) => {
385
+ const startedAt = performance.now();
386
+ const params = {
387
+ model,
388
+ text,
389
+ voice: voiceId,
390
+ projectName: PROJECT_NAME
391
+ };
392
+ if (style) params.instructions = style;
393
+ if (withTimestamps) params.withTimestamps = true;
394
+ if (!openai && speed !== 1) params.speed = speed;
395
+ speak.mutate({ params }, { onSuccess: (out) => {
396
+ const item = {
397
+ key: nextKey.current++,
398
+ src: `data:${out.mimeType};base64,${out.audio}`,
399
+ model,
400
+ voice: voiceId,
401
+ instructions: params.instructions,
402
+ speed: params.speed,
403
+ text,
404
+ elapsedMs: performance.now() - startedAt,
405
+ requestLogId: out.requestLogId,
406
+ words: wordsFromCharTimes(out.audioTimestamps),
407
+ timing: out.timestampsError ? `timing failed: ${out.timestampsError}` : out.timestampsSource && TIMING_SOURCE[out.timestampsSource]
408
+ };
409
+ setHistory((items) => [item, ...items]);
410
+ } });
411
+ };
412
+ const sampleRef = (0, import_react.useRef)(null);
413
+ const [playing, setPlaying] = (0, import_react.useState)();
414
+ (0, import_react.useEffect)(() => () => sampleRef.current?.pause(), []);
415
+ const playSample = (voiceId) => {
416
+ setVoice(voiceId);
417
+ sampleRef.current?.pause();
418
+ if (playing === voiceId) {
419
+ setPlaying(void 0);
420
+ return;
421
+ }
422
+ const audio = new Audio(`/voice-samples/${openai ? "openai" : "grok"}/${voiceId}.mp3`);
423
+ audio.addEventListener("ended", () => setPlaying((current) => current === voiceId ? void 0 : current), { once: true });
424
+ sampleRef.current = audio;
425
+ setPlaying(voiceId);
426
+ audio.play();
427
+ };
428
+ const ttsCode = ttsExample({
429
+ model,
430
+ text,
431
+ voice,
432
+ instructions: style,
433
+ speed: !openai && speed !== 1 ? speed : void 0,
434
+ withTimestamps
435
+ });
436
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(WithSdkExample, {
437
+ code: ttsCode,
438
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
439
+ className: "flex flex-col gap-3 p-4",
440
+ children: [
441
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
442
+ className: "grid grid-cols-2 gap-2",
443
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Field, {
444
+ label: "Model",
445
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("select", {
446
+ value: model,
447
+ onChange: (e) => changeModel(e.target.value),
448
+ className: CONTROL,
449
+ children: TTS_MODELS.map((m) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
450
+ value: m,
451
+ children: m
452
+ }, m))
453
+ })
454
+ }), openai ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Field, {
455
+ label: "Style instructions (OpenAI only)",
456
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", {
457
+ value: instructions,
458
+ onChange: (e) => setInstructions(e.target.value),
459
+ placeholder: "e.g. Speak with a gentle Irish accent.",
460
+ className: CONTROL
461
+ })
462
+ }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Field, {
463
+ label: `Speed (Grok only) — ${speed.toFixed(2)}×`,
464
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", {
465
+ type: "range",
466
+ min: .7,
467
+ max: 1.5,
468
+ step: .05,
469
+ value: speed,
470
+ onChange: (e) => setSpeed(Number(e.target.value)),
471
+ className: "h-8 accent-sienna-500"
472
+ })
473
+ })]
474
+ }),
475
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
476
+ className: "flex flex-col gap-1.5",
477
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
478
+ className: "text-[11px] font-medium text-sand-500",
479
+ children: "Voice — ▶ plays a short self-introduction sample, a name selects it"
480
+ }), (openai ? OPENAI_VOICE_GROUPS : GROK_VOICE_GROUPS).map((group) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
481
+ className: "flex items-start gap-2",
482
+ children: [group.label && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
483
+ className: "w-12 shrink-0 pt-1 text-[11px] text-sand-400",
484
+ children: group.label
485
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
486
+ className: "flex flex-wrap gap-1.5",
487
+ children: group.voices.map((v) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
488
+ className: `inline-flex items-center overflow-hidden rounded-full border text-[12px] ${voice === v ? "border-sienna-400 bg-sienna-50 text-sienna-700" : "border-sand-200/80 bg-white text-sand-700"}`,
489
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", {
490
+ type: "button",
491
+ onClick: () => setVoice(v),
492
+ "aria-pressed": voice === v,
493
+ className: "py-0.5 pl-2.5 pr-1 hover:text-sienna-600",
494
+ children: v
495
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", {
496
+ type: "button",
497
+ onClick: () => playSample(v),
498
+ title: playing === v ? `Stop "${v}"` : `Play a "${v}" sample`,
499
+ className: `py-1 pl-1 pr-2 hover:text-sienna-500 ${playing === v ? "text-sienna-500" : "text-sand-400"}`,
500
+ children: playing === v ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ForwardRef$5, { className: "size-3" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ForwardRef, { className: "size-3" })
501
+ })]
502
+ }, v))
503
+ })]
504
+ }, group.label))]
505
+ }),
506
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Field, {
507
+ label: "Text",
508
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("textarea", {
509
+ value: text,
510
+ onChange: (e) => setText(e.target.value),
511
+ rows: 3,
512
+ className: `${FIELD} resize-y`
513
+ })
514
+ }),
515
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
516
+ className: "flex items-center gap-3",
517
+ children: [
518
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", {
519
+ type: "button",
520
+ onClick: () => generate(voice),
521
+ disabled: speak.isPending || !text.trim(),
522
+ className: BUTTON,
523
+ children: [
524
+ speak.isPending && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ForwardRef$2, { className: "size-3.5 animate-spin" }),
525
+ "Generate with ",
526
+ voice
527
+ ]
528
+ }),
529
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", {
530
+ className: "flex items-center gap-1.5 text-[12px] text-sand-600",
531
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", {
532
+ type: "checkbox",
533
+ checked: withTimestamps,
534
+ onChange: (e) => setWithTimestamps(e.target.checked),
535
+ className: "accent-sienna-500"
536
+ }), "Word timing"]
537
+ }),
538
+ speak.isError && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
539
+ className: "text-[12px] text-danger-500 break-words",
540
+ children: speak.error?.message
541
+ })
542
+ ]
543
+ })
544
+ ]
545
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
546
+ className: "border-t border-sand-100",
547
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(History, {
548
+ empty: "Generated clips stack here, newest first, so voices can be compared side by side.",
549
+ children: history.map((item) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(HistoryRow, {
550
+ title: [
551
+ item.voice,
552
+ shortModel(item.model),
553
+ item.speed && `${item.speed}×`
554
+ ].filter(Boolean).join(" · "),
555
+ meta: [`${(item.elapsedMs / 1e3).toFixed(1)}s`, item.timing].filter(Boolean).join(" · "),
556
+ requestLogId: item.requestLogId,
557
+ onRemove: () => setHistory((items) => items.filter((i) => i.key !== item.key)),
558
+ children: [(!item.words || item.instructions) && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", {
559
+ className: "truncate text-[12px] text-sand-600",
560
+ title: item.text,
561
+ children: [!item.words && item.text, item.instructions && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
562
+ className: "text-sand-400",
563
+ children: [" — ", item.instructions]
564
+ })]
565
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TimedPlayer, {
566
+ src: item.src,
567
+ words: item.words,
568
+ autoPlay: true
569
+ })]
570
+ }, item.key))
571
+ })
572
+ })]
573
+ });
574
+ }
575
+ function SttPanel() {
576
+ const [model, setModel] = (0, import_react.useState)(STT_MODELS[0]);
577
+ const [prompt, setPrompt] = (0, import_react.useState)("");
578
+ const [audio, setAudio] = (0, import_react.useState)();
579
+ const [recording, setRecording] = (0, import_react.useState)(false);
580
+ const [audioError, setAudioError] = (0, import_react.useState)();
581
+ const [history, setHistory] = (0, import_react.useState)([]);
582
+ const recorderRef = (0, import_react.useRef)(null);
583
+ const clipUrls = (0, import_react.useRef)([]);
584
+ const nextKey = (0, import_react.useRef)(0);
585
+ const transcribe = QgridService.useTranscribeMutation();
586
+ const openai = isOpenAI(model);
587
+ (0, import_react.useEffect)(() => () => {
588
+ recorderRef.current?.stream.getTracks().forEach((track) => track.stop());
589
+ clipUrls.current.forEach((url) => URL.revokeObjectURL(url));
590
+ }, []);
591
+ const takeAudio = (blob) => {
592
+ const url = URL.createObjectURL(blob);
593
+ clipUrls.current.push(url);
594
+ setAudio({
595
+ blob,
596
+ url,
597
+ clip: clipUrls.current.length
598
+ });
599
+ };
600
+ const toggleRecording = async () => {
601
+ if (recording) {
602
+ recorderRef.current?.stop();
603
+ setRecording(false);
604
+ return;
605
+ }
606
+ setAudioError(void 0);
607
+ try {
608
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
609
+ const recorder = new MediaRecorder(stream);
610
+ const chunks = [];
611
+ recorder.ondataavailable = (e) => chunks.push(e.data);
612
+ recorder.onstop = () => {
613
+ stream.getTracks().forEach((track) => track.stop());
614
+ takeAudio(new Blob(chunks, { type: recorder.mimeType }));
615
+ };
616
+ recorder.start();
617
+ recorderRef.current = recorder;
618
+ setRecording(true);
619
+ } catch (error) {
620
+ setAudioError(error instanceof Error ? error.message : String(error));
621
+ }
622
+ };
623
+ const submit = async () => {
624
+ if (!audio) return;
625
+ setAudioError(void 0);
626
+ const originalType = audio.blob.type.split(";")[0];
627
+ let clip;
628
+ try {
629
+ clip = !openai && originalType.startsWith("audio/") ? {
630
+ audio: bytesToBase64(new Uint8Array(await audio.blob.arrayBuffer())),
631
+ mediaType: originalType
632
+ } : {
633
+ audio: await audioToWavBase64(audio.blob),
634
+ mediaType: "audio/wav"
635
+ };
636
+ } catch (error) {
637
+ setAudioError(`could not decode audio: ${error instanceof Error ? error.message : String(error)}`);
638
+ return;
639
+ }
640
+ const params = {
641
+ model,
642
+ ...clip,
643
+ projectName: PROJECT_NAME
644
+ };
645
+ if (openai && prompt.trim()) params.prompt = prompt.trim();
646
+ const startedAt = performance.now();
647
+ transcribe.mutate({ params }, { onSuccess: (out) => {
648
+ const item = {
649
+ key: nextKey.current++,
650
+ clip: audio.clip,
651
+ clipUrl: audio.url,
652
+ model,
653
+ prompt: params.prompt,
654
+ text: out.text,
655
+ elapsedMs: performance.now() - startedAt,
656
+ durationSec: out.durationSec,
657
+ requestLogId: out.requestLogId,
658
+ words: out.words
659
+ };
660
+ setHistory((items) => [item, ...items]);
661
+ } });
662
+ };
663
+ const sttCode = sttExample({
664
+ model,
665
+ prompt: openai && prompt.trim() ? prompt.trim() : void 0
666
+ });
667
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(WithSdkExample, {
668
+ code: sttCode,
669
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
670
+ className: "flex flex-col gap-3 p-4",
671
+ children: [
672
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
673
+ className: "grid grid-cols-2 gap-2",
674
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Field, {
675
+ label: "Model",
676
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("select", {
677
+ value: model,
678
+ onChange: (e) => setModel(e.target.value),
679
+ className: CONTROL,
680
+ children: STT_MODELS.map((m) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
681
+ value: m,
682
+ children: m
683
+ }, m))
684
+ })
685
+ }), openai && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Field, {
686
+ label: "Prompt (OpenAI only)",
687
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", {
688
+ value: prompt,
689
+ onChange: (e) => setPrompt(e.target.value),
690
+ placeholder: "domain words, e.g. qgrid, Kuma",
691
+ className: CONTROL
692
+ })
693
+ })]
694
+ }),
695
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
696
+ className: "flex flex-wrap items-center gap-2",
697
+ children: [
698
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", {
699
+ type: "button",
700
+ onClick: toggleRecording,
701
+ className: `${BUTTON} ${recording ? "bg-danger-500 hover:bg-danger-500" : ""}`,
702
+ children: [recording ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ForwardRef$5, { className: "size-3.5" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ForwardRef$1, { className: "size-3.5" }), recording ? "Stop" : "Record"]
703
+ }),
704
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", {
705
+ className: "text-[12px] text-sand-600 cursor-pointer hover:text-sienna-500",
706
+ children: ["or upload a file", /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", {
707
+ type: "file",
708
+ accept: "audio/*",
709
+ className: "hidden",
710
+ onChange: (e) => {
711
+ const file = e.target.files?.[0];
712
+ if (file) takeAudio(file);
713
+ }
714
+ })]
715
+ }),
716
+ audioError && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
717
+ className: "text-[12px] text-danger-500 break-words",
718
+ children: audioError
719
+ })
720
+ ]
721
+ }),
722
+ audio && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
723
+ className: "flex items-center gap-2",
724
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
725
+ className: "shrink-0 text-[11px] font-medium text-sand-500",
726
+ children: ["clip ", audio.clip]
727
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("audio", {
728
+ controls: true,
729
+ src: audio.url,
730
+ className: "h-8 w-full"
731
+ })]
732
+ }),
733
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
734
+ className: "flex items-center gap-3",
735
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", {
736
+ type: "button",
737
+ onClick: submit,
738
+ disabled: !audio || recording || transcribe.isPending,
739
+ className: BUTTON,
740
+ children: [transcribe.isPending && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ForwardRef$2, { className: "size-3.5 animate-spin" }), "Transcribe"]
741
+ }), transcribe.isError && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
742
+ className: "text-[12px] text-danger-500 break-words",
743
+ children: transcribe.error?.message
744
+ })]
745
+ })
746
+ ]
747
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
748
+ className: "border-t border-sand-100",
749
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(History, {
750
+ empty: "Transcripts stack here, newest first; run one clip through several models to compare.",
751
+ children: history.map((item) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HistoryRow, {
752
+ title: `clip ${item.clip} · ${shortModel(item.model)}`,
753
+ meta: [
754
+ `${(item.elapsedMs / 1e3).toFixed(1)}s`,
755
+ item.durationSec !== void 0 ? `${item.durationSec.toFixed(1)}s audio` : "",
756
+ item.prompt ? `prompt: ${item.prompt}` : ""
757
+ ].filter(Boolean).join(" · "),
758
+ requestLogId: item.requestLogId,
759
+ onRemove: () => setHistory((items) => items.filter((i) => i.key !== item.key)),
760
+ children: item.words && item.words.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TimedPlayer, {
761
+ src: item.clipUrl,
762
+ words: item.words
763
+ }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
764
+ className: "rounded-lg bg-sand-50 px-3 py-2 text-[13px] text-sand-800 whitespace-pre-wrap",
765
+ children: item.text || "(empty transcript)"
766
+ })
767
+ }, item.key))
768
+ })
769
+ })]
770
+ });
771
+ }
772
+ var DEFAULT_DELEGATION_MODEL = "openai/gpt-6-luna";
773
+ var LiveEvent = looseObject({
774
+ type: string(),
775
+ turn: looseObject({
776
+ id: string(),
777
+ role: string(),
778
+ transcript: string()
779
+ }).optional(),
780
+ turn_id: string().optional(),
781
+ delta: string().optional()
782
+ });
783
+ var clock = (sec) => `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, "0")}`;
784
+ /** Ends the session at once; a peer that only disconnects keeps it (and its billed time) ~30 s. */
785
+ function endLiveSession({ pc, channel, mic }) {
786
+ if (channel.readyState === "open") channel.send(JSON.stringify({ type: "session.close" }));
787
+ mic.getTracks().forEach((track) => track.stop());
788
+ setTimeout(() => pc.close(), 500);
789
+ }
790
+ /**
791
+ * A GPT-Live conversation. The browser's own WebRTC peer talks to OpenAI; qgrid only exchanges the
792
+ * SDP offer with the subscription token and logs the transcript when the session ends.
793
+ */
794
+ function LivePanel() {
795
+ const [voice, setVoice] = (0, import_react.useState)(OPENAI_LIVE_VOICES[0]);
796
+ const [instructions, setInstructions] = (0, import_react.useState)("");
797
+ const [delegateModel, setDelegateModel] = (0, import_react.useState)(DEFAULT_DELEGATION_MODEL);
798
+ const [effort, setEffort] = (0, import_react.useState)("low");
799
+ const [webSearch, setWebSearch] = (0, import_react.useState)(false);
800
+ const [logged, setLogged] = (0, import_react.useState)(true);
801
+ const [earlier, setEarlier] = (0, import_react.useState)([]);
802
+ const searchable = !delegateModel.startsWith("anthropic/");
803
+ const [status, setStatus] = (0, import_react.useState)("idle");
804
+ const [error, setError] = (0, import_react.useState)();
805
+ const [turns, setTurns] = (0, import_react.useState)([]);
806
+ const [requestLogId, setRequestLogId] = (0, import_react.useState)();
807
+ const [elapsedSec, setElapsedSec] = (0, import_react.useState)(0);
808
+ const session = (0, import_react.useRef)(null);
809
+ const audioRef = (0, import_react.useRef)(null);
810
+ const liveCall = QgridService.useLiveCallMutation();
811
+ (0, import_react.useEffect)(() => () => {
812
+ if (session.current) endLiveSession(session.current);
813
+ }, []);
814
+ (0, import_react.useEffect)(() => {
815
+ if (status !== "live") return;
816
+ const startedAt = Date.now();
817
+ const timer = setInterval(() => setElapsedSec(Math.floor((Date.now() - startedAt) / 1e3)), 1e3);
818
+ return () => clearInterval(timer);
819
+ }, [status]);
820
+ const stop = () => {
821
+ if (session.current) endLiveSession(session.current);
822
+ session.current = null;
823
+ setStatus("idle");
824
+ };
825
+ const onEvent = (raw) => {
826
+ let json;
827
+ try {
828
+ json = LiveEvent.safeParse(JSON.parse(raw)).data;
829
+ } catch {
830
+ return;
831
+ }
832
+ if (!json) return;
833
+ const { type, turn, turn_id: turnId, delta } = json;
834
+ if (type === "session.closed") {
835
+ stop();
836
+ return;
837
+ }
838
+ if (turn && (type === "turn.created" || type === "turn.done")) {
839
+ const next = {
840
+ id: turn.id,
841
+ role: turn.role,
842
+ text: turn.transcript
843
+ };
844
+ setTurns((items) => items.some((item) => item.id === turn.id) ? items.map((item) => item.id === turn.id ? next : item) : [...items, next]);
845
+ } else if (type === "turn.delta" && turnId && delta) setTurns((items) => items.map((item) => item.id === turnId ? {
846
+ ...item,
847
+ text: item.text + delta
848
+ } : item));
849
+ };
850
+ const start = async (continueConversation) => {
851
+ const history = continueConversation ? [...earlier, ...turns.flatMap((turn) => turn.text.trim() ? [{
852
+ role: turn.role === "assistant" ? "assistant" : "user",
853
+ text: turn.text.trim()
854
+ }] : [])].slice(-128) : [];
855
+ setEarlier(history);
856
+ setError(void 0);
857
+ setTurns([]);
858
+ setRequestLogId(void 0);
859
+ setElapsedSec(0);
860
+ setStatus("connecting");
861
+ let mic;
862
+ let pc;
863
+ try {
864
+ mic = await navigator.mediaDevices.getUserMedia({ audio: true });
865
+ const peer = new RTCPeerConnection();
866
+ pc = peer;
867
+ mic.getTracks().forEach((track) => peer.addTrack(track));
868
+ peer.addEventListener("track", (event) => {
869
+ if (audioRef.current) audioRef.current.srcObject = new MediaStream([event.track]);
870
+ });
871
+ const channel = peer.createDataChannel("oai-events");
872
+ channel.addEventListener("message", (event) => onEvent(String(event.data)));
873
+ const offer = await peer.createOffer();
874
+ await peer.setLocalDescription(offer);
875
+ const params = {
876
+ sdp: offer.sdp ?? "",
877
+ voice,
878
+ delegation: {
879
+ model: delegateModel,
880
+ effort,
881
+ webSearch: searchable && webSearch
882
+ },
883
+ projectName: PROJECT_NAME
884
+ };
885
+ if (instructions.trim()) params.instructions = instructions.trim();
886
+ if (history.length) params.history = history;
887
+ if (!logged) params.logger = false;
888
+ const out = await liveCall.mutateAsync({ params });
889
+ await peer.setRemoteDescription({
890
+ type: "answer",
891
+ sdp: out.sdp
892
+ });
893
+ session.current = {
894
+ pc: peer,
895
+ channel,
896
+ mic
897
+ };
898
+ setRequestLogId(out.requestLogId);
899
+ setStatus("live");
900
+ } catch (e) {
901
+ mic?.getTracks().forEach((track) => track.stop());
902
+ pc?.close();
903
+ setError(e instanceof Error ? e.message : String(e));
904
+ setStatus("idle");
905
+ }
906
+ };
907
+ const liveCode = liveExample({
908
+ voice,
909
+ instructions: instructions.trim() || void 0,
910
+ delegation: {
911
+ model: delegateModel,
912
+ effort,
913
+ webSearch: searchable && webSearch
914
+ },
915
+ logged,
916
+ continues: earlier.length > 0
917
+ });
918
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WithSdkExample, {
919
+ code: liveCode,
920
+ note: "SDK 2.20.0+, experimental",
921
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
922
+ className: "flex flex-col gap-3 p-4",
923
+ children: [
924
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
925
+ className: "grid grid-cols-2 gap-2",
926
+ children: [
927
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Field, {
928
+ label: "Voice",
929
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("select", {
930
+ value: voice,
931
+ onChange: (e) => setVoice(e.target.value),
932
+ disabled: status !== "idle",
933
+ className: CONTROL,
934
+ children: OPENAI_LIVE_VOICES.map((v) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
935
+ value: v,
936
+ children: v
937
+ }, v))
938
+ })
939
+ }),
940
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Field, {
941
+ label: "Instructions",
942
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", {
943
+ value: instructions,
944
+ onChange: (e) => setInstructions(e.target.value),
945
+ disabled: status !== "idle",
946
+ placeholder: "e.g. You are a friendly English tutor. Keep answers short.",
947
+ className: CONTROL
948
+ })
949
+ }),
950
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Field, {
951
+ label: "Delegation model (answers lookups and reasoning)",
952
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("select", {
953
+ value: delegateModel,
954
+ onChange: (e) => setDelegateModel(e.target.value),
955
+ disabled: status !== "idle",
956
+ className: CONTROL,
957
+ children: QGRID_MODEL_GROUPS.map((group) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("optgroup", {
958
+ label: group.label,
959
+ children: group.models.map((m) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
960
+ value: m,
961
+ children: m
962
+ }, m))
963
+ }, group.label))
964
+ })
965
+ }),
966
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
967
+ className: "flex items-end gap-3",
968
+ children: [
969
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Field, {
970
+ label: "Effort",
971
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("select", {
972
+ value: effort,
973
+ onChange: (e) => setEffort(Effort.options.find((v) => v === e.target.value) ?? "low"),
974
+ disabled: status !== "idle",
975
+ className: CONTROL,
976
+ children: Effort.options.map((v) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
977
+ value: v,
978
+ children: v
979
+ }, v))
980
+ })
981
+ }),
982
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", {
983
+ className: "flex h-8 items-center gap-1.5 text-[12px] text-sand-600",
984
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", {
985
+ type: "checkbox",
986
+ checked: searchable && webSearch,
987
+ onChange: (e) => setWebSearch(e.target.checked),
988
+ disabled: status !== "idle" || !searchable,
989
+ className: "accent-sienna-500"
990
+ }), "Web search"]
991
+ }),
992
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", {
993
+ className: "flex h-8 items-center gap-1.5 text-[12px] text-sand-600",
994
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", {
995
+ type: "checkbox",
996
+ checked: logged,
997
+ onChange: (e) => setLogged(e.target.checked),
998
+ disabled: status !== "idle",
999
+ className: "accent-sienna-500"
1000
+ }), "Request log"]
1001
+ })
1002
+ ]
1003
+ })
1004
+ ]
1005
+ }),
1006
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
1007
+ className: "flex flex-wrap items-center gap-3",
1008
+ children: [
1009
+ status === "idle" ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", {
1010
+ type: "button",
1011
+ onClick: () => start(false),
1012
+ className: BUTTON,
1013
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(ForwardRef$1, { className: "size-3.5" }), "Start conversation"]
1014
+ }), turns.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", {
1015
+ type: "button",
1016
+ onClick: () => start(true),
1017
+ className: "text-[12px] font-medium text-sienna-600 hover:text-sienna-700",
1018
+ children: "Continue this conversation"
1019
+ })] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", {
1020
+ type: "button",
1021
+ onClick: stop,
1022
+ disabled: status === "connecting",
1023
+ className: `${BUTTON} bg-danger-500 hover:bg-danger-500`,
1024
+ children: [status === "connecting" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ForwardRef$2, { className: "size-3.5 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ForwardRef$5, { className: "size-3.5" }), status === "connecting" ? "Connecting" : "End"]
1025
+ }),
1026
+ status === "live" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
1027
+ className: "tabular-nums text-[12px] text-sand-500",
1028
+ children: [clock(elapsedSec), " · openai/gpt-live-1 · speak any time (ends by itself after 2 h)"]
1029
+ }),
1030
+ requestLogId !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Link, {
1031
+ to: "/requests/show",
1032
+ search: { id: requestLogId },
1033
+ target: "_blank",
1034
+ className: "inline-flex items-center gap-1 text-[12px] tabular-nums text-sand-500 hover:text-sienna-500",
1035
+ children: [
1036
+ "request log #",
1037
+ requestLogId,
1038
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ForwardRef$3, { className: "size-3" })
1039
+ ]
1040
+ }),
1041
+ error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
1042
+ className: "text-[12px] text-danger-500 break-words",
1043
+ children: error
1044
+ })
1045
+ ]
1046
+ }),
1047
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("audio", {
1048
+ ref: audioRef,
1049
+ autoPlay: true
1050
+ }),
1051
+ earlier.length === 0 && turns.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
1052
+ className: "py-6 text-center text-[12px] text-sand-400",
1053
+ children: "Start a conversation and talk; both sides of the transcript appear here."
1054
+ }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("ul", {
1055
+ className: "flex flex-col gap-1.5",
1056
+ children: [earlier.map((item, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", {
1057
+ className: "rounded-lg bg-sand-50/60 px-3 py-2 text-[13px] text-sand-500",
1058
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
1059
+ className: "mr-2 text-[10px] font-medium uppercase tracking-wider text-sand-400",
1060
+ children: item.role
1061
+ }), item.text]
1062
+ }, `earlier-${index}`)), turns.map((turn) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", {
1063
+ className: `rounded-lg px-3 py-2 text-[13px] text-sand-800 ${turn.role === "assistant" ? "bg-sage-50" : "bg-sand-50"}`,
1064
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
1065
+ className: "mr-2 text-[10px] font-medium uppercase tracking-wider text-sand-500",
1066
+ children: turn.role
1067
+ }), turn.text.trim()]
1068
+ }, turn.id))]
1069
+ })
1070
+ ]
1071
+ })
1072
+ });
1073
+ }
1074
+ function VoicePlayground({ tab }) {
1075
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", { children: [
1076
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
1077
+ role: "tablist",
1078
+ className: "panel mb-4 flex gap-1 px-3 pt-2 md:hidden",
1079
+ children: VOICE_TAB_IDS.map((id) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link, {
1080
+ to: "/voice",
1081
+ search: { tab: id },
1082
+ role: "tab",
1083
+ "aria-selected": tab === id,
1084
+ className: `-mb-px border-b-2 px-3 py-2 text-[13px] no-underline transition-colors duration-150 ${tab === id ? "border-sienna-500 font-medium text-sand-800" : "border-transparent text-sand-500 hover:text-sand-700"}`,
1085
+ children: VOICE_TAB_TITLES[id]
1086
+ }, id))
1087
+ }),
1088
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
1089
+ role: "tabpanel",
1090
+ hidden: tab !== "tts",
1091
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TtsPanel, {})
1092
+ }),
1093
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
1094
+ role: "tabpanel",
1095
+ hidden: tab !== "stt",
1096
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SttPanel, {})
1097
+ }),
1098
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
1099
+ role: "tabpanel",
1100
+ hidden: tab !== "live",
1101
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LivePanel, {})
1102
+ })
1103
+ ] });
1104
+ }
1105
+ //#endregion
1106
+ //#region src/routes/voice.tsx?tsr-split=component
1107
+ function VoicePage() {
1108
+ const { tab = "tts" } = Route.useSearch();
1109
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
1110
+ className: "max-w-3xl mx-auto xl:max-w-6xl",
1111
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(VoicePlayground, { tab })
1112
+ });
1113
+ }
1114
+ //#endregion
1115
+ export { VoicePage as component };