@cartanova/qgrid-cli 2.19.1 → 2.19.3

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 (71) hide show
  1. package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +5 -2
  2. package/bundle/dist/application/qgrid/qgrid.dispatcher.js +3 -1
  3. package/bundle/dist/application/qgrid/qgrid.frame.js +225 -6
  4. package/bundle/dist/application/qgrid/qgrid.types.js +74 -2
  5. package/bundle/dist/application/request-log/request-log.model.js +11 -1
  6. package/bundle/dist/application/sonamu.generated.js +5 -3
  7. package/bundle/dist/i18n/sd.generated.js +3 -2
  8. package/bundle/dist/utils/providers/common/model-cost.js +8 -2
  9. package/bundle/dist/utils/providers/openai/openai-dispatcher.js +18 -1
  10. package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +120 -2
  11. package/bundle/dist/utils/providers/openai/openai-voice-client.js +184 -6
  12. package/bundle/src/application/qgrid/qgrid-run-lifecycle.test.ts +13 -0
  13. package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +11 -1
  14. package/bundle/src/application/qgrid/qgrid.dispatcher.test.ts +17 -0
  15. package/bundle/src/application/qgrid/qgrid.dispatcher.ts +8 -0
  16. package/bundle/src/application/qgrid/qgrid.frame.test.ts +223 -0
  17. package/bundle/src/application/qgrid/qgrid.frame.ts +304 -3
  18. package/bundle/src/application/qgrid/qgrid.types.ts +121 -0
  19. package/bundle/src/application/request-log/request-log.entity.json +3 -2
  20. package/bundle/src/application/request-log/request-log.model.test.ts +19 -0
  21. package/bundle/src/application/request-log/request-log.model.ts +20 -1
  22. package/bundle/src/application/sonamu.generated.http +28 -0
  23. package/bundle/src/application/sonamu.generated.ts +2 -1
  24. package/bundle/src/i18n/sd.generated.ts +2 -1
  25. package/bundle/src/utils/providers/common/model-cost.ts +15 -0
  26. package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +16 -0
  27. package/bundle/src/utils/providers/openai/openai-dispatcher.ts +26 -0
  28. package/bundle/src/utils/providers/openai/openai-realtime-protocol.ts +160 -0
  29. package/bundle/src/utils/providers/openai/openai-voice-client.test.ts +205 -0
  30. package/bundle/src/utils/providers/openai/openai-voice-client.ts +284 -5
  31. package/bundle/web-dist/client/assets/index-B5yorZqv.js +104 -0
  32. package/bundle/web-dist/client/assets/index-CpOwNalw.css +1 -0
  33. package/bundle/web-dist/client/assets/logs-Bx_jXEDZ.js +1 -0
  34. package/bundle/web-dist/client/assets/monit-CPQ18s_m.js +1 -0
  35. package/bundle/web-dist/client/assets/{routes--6kS1pgJ.js → routes-S4D5Ld4L.js} +2 -2
  36. package/bundle/web-dist/client/assets/{settings-Dah87LB2.js → settings-M4h_UV87.js} +1 -1
  37. package/bundle/web-dist/client/assets/show-BchF-T1a.js +2 -0
  38. package/bundle/web-dist/client/assets/{tokens-CIHja806.js → tokens-BgBD07ru.js} +1 -1
  39. package/bundle/web-dist/client/assets/{use-oauth-login-flow-DeJCqHDJ.js → use-oauth-login-flow-D_wI9MzM.js} +1 -1
  40. package/bundle/web-dist/client/assets/use-update-token-mutation-IvuH3Qje.js +1 -0
  41. package/bundle/web-dist/client/assets/{vendor-tanstack-6B86itGS.js → vendor-tanstack-DMgmqjm4.js} +1 -1
  42. package/bundle/web-dist/client/assets/voice-CnIiQMbo.js +1 -0
  43. package/bundle/web-dist/client/index.html +3 -3
  44. package/bundle/web-dist/server/assets/{TimedPlayer-DAwjkP4z.js → TimedPlayer-COqaTQSl.js} +1 -1
  45. package/bundle/web-dist/server/assets/{logs-BmBpBe-j.js → logs-HPho1SkC.js} +5 -6
  46. package/bundle/web-dist/server/assets/{monit-Db1WrIls.js → monit-Bl2kSkSF.js} +3 -3
  47. package/bundle/web-dist/server/assets/{plus-CW9y_K7l.js → plus-CQ8AHpih.js} +1 -1
  48. package/bundle/web-dist/server/assets/{refresh-cw-CRgcH5bT.js → refresh-cw-pYSuvt4c.js} +1 -1
  49. package/bundle/web-dist/server/assets/{request-model-DRF7hmJC.js → request-model-ZulJMbGm.js} +1 -1
  50. package/bundle/web-dist/server/assets/{routes-CARZj7or.js → routes-BNHCX4VI.js} +4 -4
  51. package/bundle/web-dist/server/assets/{services.generated-B6QpnL_N.js → services.generated-C3b31_vt.js} +23209 -22930
  52. package/bundle/web-dist/server/assets/{settings-B4jdpP5N.js → settings-NJUyaSrJ.js} +4 -4
  53. package/bundle/web-dist/server/assets/{show-CnLDFCtW.js → show-Dz5QGL7l.js} +8 -9
  54. package/bundle/web-dist/server/assets/{tokens-TDQguTdh.js → tokens-BPQvjIGq.js} +5 -5
  55. package/bundle/web-dist/server/assets/{use-oauth-login-flow-du7pOh_H.js → use-oauth-login-flow-CCc8LEmn.js} +1 -1
  56. package/bundle/web-dist/server/assets/{use-update-token-mutation-DA6HiiWS.js → use-update-token-mutation-Ba-sEhq1.js} +1 -1
  57. package/bundle/web-dist/server/assets/{voice-BvAl-vTr.js → voice-xFFT4zqK.js} +307 -22
  58. package/bundle/web-dist/server/entry-server.generated.js +5590 -71
  59. package/package.json +1 -1
  60. package/skills/qgrid/references/decision-rationale.md +4 -0
  61. package/skills/qgrid/references/openai-codex-runtime.md +16 -0
  62. package/skills/qgrid/references/request-log-run-lifecycle.md +2 -1
  63. package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
  64. package/bundle/web-dist/client/assets/index-Co8uAhSV.css +0 -1
  65. package/bundle/web-dist/client/assets/index-DvW4Yb82.js +0 -104
  66. package/bundle/web-dist/client/assets/logs-DAif2re1.js +0 -1
  67. package/bundle/web-dist/client/assets/monit-DYczkiu0.js +0 -1
  68. package/bundle/web-dist/client/assets/show-DQWFaVDW.js +0 -2
  69. package/bundle/web-dist/client/assets/use-update-token-mutation-Cn_Po_rH.js +0 -1
  70. package/bundle/web-dist/client/assets/voice-6i785ieC.js +0 -1
  71. package/bundle/web-dist/server/assets/link-DrdV092C.js +0 -4919
@@ -47,6 +47,7 @@ const {
47
47
  requestLogFinishRunMock,
48
48
  appendStepMock,
49
49
  continueToolRunMock,
50
+ recordRunProgressMock,
50
51
  dispatcherQueryMock,
51
52
  dispatcherQueryStreamMock,
52
53
  beforeQueryMock,
@@ -75,6 +76,7 @@ const {
75
76
  requestLogFinishRunMock: vi.fn(),
76
77
  appendStepMock: vi.fn(),
77
78
  continueToolRunMock: vi.fn(),
79
+ recordRunProgressMock: vi.fn(),
78
80
  dispatcherQueryMock: vi.fn(),
79
81
  dispatcherQueryStreamMock: vi.fn(),
80
82
  beforeQueryMock: vi.fn(),
@@ -126,6 +128,7 @@ vi.mock("../request-log/request-log.model", () => ({
126
128
  finishRun: requestLogFinishRunMock,
127
129
  appendStep: appendStepMock,
128
130
  continueToolRun: continueToolRunMock,
131
+ recordRunProgress: recordRunProgressMock,
129
132
  },
130
133
  }));
131
134
 
@@ -2394,6 +2397,226 @@ describe("QgridFrame Grok media and voice (U11)", () => {
2394
2397
  });
2395
2398
  });
2396
2399
 
2400
+ describe("GPT-Live call", () => {
2401
+ type Summary = { turns: object[]; audioDurationMs?: number; endReason: string; error?: string };
2402
+ let endSession: (summary: Summary) => void;
2403
+ let startLive: ReturnType<typeof vi.fn>;
2404
+
2405
+ beforeEach(() => {
2406
+ recordRunProgressMock.mockReset().mockResolvedValue(undefined);
2407
+ dispatcherQueryMock.mockReset();
2408
+ const ended = new Promise<Summary>((resolve) => (endSession = resolve));
2409
+ startLive = vi.fn().mockResolvedValue({
2410
+ result: { sdp: "v=0 answer", callId: "rtc_x", quotaHeaders: new Map(), ended },
2411
+ tokenName: "openai/a",
2412
+ });
2413
+ Object.assign(QgridDispatcher, { openaiDispatcher: { startLive } });
2414
+ });
2415
+
2416
+ afterEach(() => {
2417
+ Object.assign(QgridDispatcher, { openaiDispatcher: null });
2418
+ });
2419
+
2420
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
2421
+
2422
+ it("answers at once, fills the running log turn by turn, and finishes it at the end", async () => {
2423
+ const out = await QgridFrame.liveCall({ sdp: "v=0 offer", instructions: "Be brief.", projectName: "p" });
2424
+
2425
+ expect(out).toEqual({
2426
+ sdp: "v=0 answer",
2427
+ callId: "rtc_x",
2428
+ model: "openai/gpt-live-1",
2429
+ voice: "cove",
2430
+ tokenName: "openai/a",
2431
+ requestLogId: 77,
2432
+ });
2433
+ expect(startLive).toHaveBeenCalledWith(
2434
+ expect.objectContaining({ sdp: "v=0 offer", voice: "cove", instructions: "Be brief." }),
2435
+ );
2436
+ expect(requestLogCreateRunMock).toHaveBeenCalledWith(
2437
+ expect.objectContaining({ media_kind: "live", system_prompt: "Be brief.", requested_model_name: "openai/gpt-live-1" }),
2438
+ );
2439
+ // A resolved step: a pending one would fall to the 30-minute tool-wait cleanup.
2440
+ expect(appendStepMock).toHaveBeenCalledWith(
2441
+ 77,
2442
+ expect.objectContaining({
2443
+ tool_name: "live_session",
2444
+ tool_call_id: "live_session:rtc_x",
2445
+ tool_result: JSON.stringify({ status: "live", callId: "rtc_x" }),
2446
+ }),
2447
+ );
2448
+ expect(recordRunProgressMock).toHaveBeenCalledWith(77, { token_name: "openai/a" });
2449
+
2450
+ // The watcher reports each finished turn; the running row's conversation follows it.
2451
+ const { onTurn } = startLive.mock.calls[0]![0] as { onTurn: (turns: object[]) => void };
2452
+ onTurn([{ role: "user", transcript: "Hi there?", startMs: 600, endMs: 5800 }]);
2453
+ await settle();
2454
+ expect(recordRunProgressMock).toHaveBeenLastCalledWith(77, { response: "**user** 0:00 \nHi there?" });
2455
+ expect(requestLogFinishRunMock).not.toHaveBeenCalled();
2456
+
2457
+ const summary = {
2458
+ turns: [
2459
+ { role: "user", transcript: "Hi there?", startMs: 600, endMs: 5800 },
2460
+ { role: "assistant", transcript: " Hello!", startMs: 65_600, endMs: 69_400 },
2461
+ ],
2462
+ audioDurationMs: 60_000,
2463
+ endReason: "client_request",
2464
+ };
2465
+ endSession(summary);
2466
+ await settle();
2467
+
2468
+ expect(continueToolRunMock).toHaveBeenCalledWith(77, [
2469
+ { toolCallId: "live_session:rtc_x", output: JSON.stringify(summary), isError: false },
2470
+ ]);
2471
+ expect(requestLogFinishRunMock).toHaveBeenCalledWith(
2472
+ 77,
2473
+ expect.objectContaining({
2474
+ status: "succeeded",
2475
+ token_name: "openai/a",
2476
+ response: "**user** 0:00 \nHi there?\n\n**assistant** 1:05 \nHello!",
2477
+ // One minute of session audio at $0.05/min.
2478
+ cost_usd: 50_000,
2479
+ cost_source: "pricing_table",
2480
+ }),
2481
+ );
2482
+ });
2483
+
2484
+ type LiveHooks = {
2485
+ onTurn: (turns: object[]) => void;
2486
+ onDelegation: (delegation: { itemId: string; text: string }) => Promise<string>;
2487
+ };
2488
+
2489
+ const hooks = () => startLive.mock.calls[0]![0] as LiveHooks;
2490
+
2491
+ it("answers delegations with a query on the session's model and logs each as a step", async () => {
2492
+ await QgridFrame.liveCall({
2493
+ sdp: "v=0 offer",
2494
+ instructions: "Be a tutor.",
2495
+ delegation: { model: "grok/grok-4.7", effort: "medium", webSearch: true },
2496
+ });
2497
+ dispatcherQueryMock.mockResolvedValueOnce({
2498
+ text: "Here is today's news.",
2499
+ model: "grok-4.7",
2500
+ tokenName: "grok/a",
2501
+ usage: { input_tokens: 10, output_tokens: 5 },
2502
+ costUsd: 0.002,
2503
+ });
2504
+
2505
+ hooks().onTurn([{ role: "user", transcript: "What's new?", startMs: 0, endMs: 1000 }]);
2506
+ const reply = await hooks().onDelegation({ itemId: "item_d", text: "Look up the news" });
2507
+
2508
+ expect(reply).toBe("Here is today's news.");
2509
+ expect(dispatcherQueryMock).toHaveBeenCalledWith(
2510
+ expect.objectContaining({
2511
+ model: "grok/grok-4.7",
2512
+ effort: "medium",
2513
+ webSearch: true,
2514
+ prompt: "Conversation so far:\nuser: What's new?\n\nRequest from the voice assistant:\nLook up the news",
2515
+ system: expect.stringContaining("The voice assistant's instructions:\nBe a tutor."),
2516
+ }),
2517
+ );
2518
+ expect(appendStepMock).toHaveBeenLastCalledWith(
2519
+ 77,
2520
+ expect.objectContaining({
2521
+ tool_name: "delegation",
2522
+ tool_call_id: "delegation:item_d",
2523
+ tool_call_index: 1,
2524
+ tool_result: expect.stringContaining("Here is today's news."),
2525
+ }),
2526
+ );
2527
+
2528
+ // The run's cost is the session audio plus every delegation's backend call.
2529
+ endSession({ turns: [], audioDurationMs: 60_000, endReason: "client_request" });
2530
+ await settle();
2531
+ expect(requestLogFinishRunMock).toHaveBeenCalledWith(77, expect.objectContaining({ cost_usd: 52_000 }));
2532
+ });
2533
+
2534
+ it("starts from a history, logs it, and gives it to delegations before the session's turns", async () => {
2535
+ const history = [
2536
+ { role: "user" as const, text: "My dog is Kuma." },
2537
+ { role: "assistant" as const, text: "Kuma is a lovely name." },
2538
+ ];
2539
+
2540
+ await QgridFrame.liveCall({ sdp: "v=0 offer", history });
2541
+
2542
+ expect(startLive).toHaveBeenCalledWith(expect.objectContaining({ history }));
2543
+ expect(requestLogCreateRunMock).toHaveBeenCalledWith(
2544
+ expect.objectContaining({
2545
+ history: [
2546
+ { type: "message", role: "user", content: "My dog is Kuma." },
2547
+ { type: "message", role: "assistant", content: "Kuma is a lovely name." },
2548
+ ],
2549
+ }),
2550
+ );
2551
+
2552
+ dispatcherQueryMock.mockResolvedValueOnce({ text: "ok", usage: {}, costUsd: 0 });
2553
+ hooks().onTurn([{ role: "user", transcript: "What's his name?", startMs: 0, endMs: 1 }]);
2554
+ await hooks().onDelegation({ itemId: "item_d", text: "Recall the dog's name" });
2555
+
2556
+ expect(dispatcherQueryMock).toHaveBeenCalledWith(
2557
+ expect.objectContaining({
2558
+ prompt:
2559
+ "Conversation so far:\nuser: My dog is Kuma.\nassistant: Kuma is a lovely name.\nuser: What's his name?\n\nRequest from the voice assistant:\nRecall the dog's name",
2560
+ }),
2561
+ );
2562
+
2563
+ // Past 128 items OpenAI never starts the session, so qgrid refuses first.
2564
+ const tooLong = Array.from({ length: 129 }, () => ({ role: "user" as const, text: "hi" }));
2565
+ await expect(QgridFrame.liveCall({ sdp: "v=0", history: tooLong })).rejects.toMatchObject({
2566
+ statusCode: 400,
2567
+ });
2568
+ });
2569
+
2570
+ it("tells the voice when a delegation fails instead of leaving it waiting", async () => {
2571
+ await QgridFrame.liveCall({ sdp: "v=0 offer" });
2572
+ dispatcherQueryMock.mockRejectedValueOnce(new Error("quota exceeded"));
2573
+
2574
+ const reply = await hooks().onDelegation({ itemId: "item_d", text: "Look up the news" });
2575
+
2576
+ expect(dispatcherQueryMock).toHaveBeenCalledWith(
2577
+ expect.objectContaining({ model: "openai/gpt-6-luna", effort: "low", webSearch: false }),
2578
+ );
2579
+ expect(reply).toContain("could not answer (quota exceeded)");
2580
+ expect(appendStepMock).toHaveBeenLastCalledWith(
2581
+ 77,
2582
+ expect.objectContaining({ tool_name: "delegation", error: "quota exceeded" }),
2583
+ );
2584
+ });
2585
+
2586
+ it("rejects an unserved delegation model or anthropic web search before logging or dispatch", async () => {
2587
+ await expect(
2588
+ QgridFrame.liveCall({ sdp: "v=0", delegation: { model: "openai/gpt-5.5" } }),
2589
+ ).rejects.toMatchObject({ statusCode: 400 });
2590
+ await expect(
2591
+ QgridFrame.liveCall({
2592
+ sdp: "v=0",
2593
+ delegation: { model: "anthropic/claude-sonnet-5", webSearch: true },
2594
+ }),
2595
+ ).rejects.toMatchObject({ statusCode: 400 });
2596
+ expect(requestLogCreateRunMock).not.toHaveBeenCalled();
2597
+ expect(startLive).not.toHaveBeenCalled();
2598
+ });
2599
+
2600
+ it("records a sideband that failed before any turn as an error run", async () => {
2601
+ await QgridFrame.liveCall({ sdp: "v=0 offer", voice: "hanul" });
2602
+ endSession({ turns: [], endReason: "sideband error", error: "handshake rejected with HTTP 404" });
2603
+ await settle();
2604
+
2605
+ expect(requestLogFinishRunMock).toHaveBeenCalledWith(
2606
+ 77,
2607
+ expect.objectContaining({ status: "error", error_message: "handshake rejected with HTTP 404" }),
2608
+ );
2609
+ });
2610
+
2611
+ it("rejects any model but openai/gpt-live-1 before logging or dispatch", async () => {
2612
+ await expect(
2613
+ QgridFrame.liveCall({ model: "openai/gpt-realtime-2.1", sdp: "v=0" } as never),
2614
+ ).rejects.toMatchObject({ statusCode: 400 });
2615
+ expect(requestLogCreateRunMock).not.toHaveBeenCalled();
2616
+ expect(startLive).not.toHaveBeenCalled();
2617
+ });
2618
+ });
2619
+
2397
2620
  it("speak keeps the byte-count placeholder for audio a browser cannot play", async () => {
2398
2621
  grok.speak!.mockResolvedValueOnce({
2399
2622
  result: { audio: new Uint8Array(6), mediaType: "audio/pcm" },
@@ -28,6 +28,7 @@ import {
28
28
  grokImageCost,
29
29
  grokReportedCost,
30
30
  grokSpeechCost,
31
+ liveCost,
31
32
  openaiSpeechCost,
32
33
  sttCost,
33
34
  type VoiceCost,
@@ -81,6 +82,8 @@ import {
81
82
  generateOpenAIPKCE,
82
83
  } from "../../utils/providers/openai/openai-oauth";
83
84
  import {
85
+ OPENAI_LIVE_DEFAULT_VOICE,
86
+ OPENAI_LIVE_MODEL,
84
87
  OPENAI_REALTIME_DEFAULT_SPEECH_MODEL,
85
88
  OPENAI_REALTIME_DEFAULT_TRANSCRIPTION_MODEL,
86
89
  OPENAI_REALTIME_DEFAULT_VOICE,
@@ -88,7 +91,12 @@ import {
88
91
  prepareRealtimeInput,
89
92
  wrapPcmAsWav,
90
93
  } from "../../utils/providers/openai/openai-realtime-protocol";
91
- import { OpenAIVoiceInputError } from "../../utils/providers/openai/openai-voice-client";
94
+ import {
95
+ type OpenAILiveDelegation,
96
+ type OpenAILiveSummary,
97
+ type OpenAILiveTurn,
98
+ OpenAIVoiceInputError,
99
+ } from "../../utils/providers/openai/openai-voice-client";
92
100
  import { alignSpeech } from "../../utils/speech-aligner";
93
101
  import { wordsFromCharTimestamps } from "../../utils/speech-alignment";
94
102
  import {
@@ -97,7 +105,7 @@ import {
97
105
  RequestLogModel,
98
106
  type RequestLogStepFields,
99
107
  } from "../request-log/request-log.model";
100
- import { type RequestLogListParams } from "../request-log/request-log.types";
108
+ import { type HistoryItems, type RequestLogListParams } from "../request-log/request-log.types";
101
109
  import { type TokenSubsetA } from "../sonamu.generated";
102
110
 
103
111
  /** Fields token refresh reads; dispatchers pass their pooled view of a token. */
@@ -137,6 +145,9 @@ import {
137
145
  type FinishRunInput,
138
146
  GenerateImagesInput,
139
147
  type GenerateImagesOutput,
148
+ LiveCallInput,
149
+ type LiveCallOutput,
150
+ type LiveHistoryItem,
140
151
  SpeakInput,
141
152
  type SpeakOutput,
142
153
  TranscribeInput,
@@ -515,13 +526,14 @@ const inflightAnthropicRefresh = new Map<number, Promise<string>>();
515
526
 
516
527
  const mediaLogger = getLogger(["qgrid", "media"]);
517
528
 
518
- type MediaKind = "image" | "video" | "stt" | "tts";
529
+ type MediaKind = "image" | "video" | "stt" | "tts" | "live";
519
530
 
520
531
  const MEDIA_TOOL_NAMES: Record<MediaKind, string> = {
521
532
  image: "image_generation",
522
533
  video: "video_generation",
523
534
  stt: "transcription",
524
535
  tts: "speech",
536
+ live: "live_session",
525
537
  };
526
538
 
527
539
  function grokNotReady(): Error {
@@ -787,6 +799,8 @@ type MediaLogStart = {
787
799
  projectName?: string;
788
800
  /** OpenAI speech style instructions or STT prompt, shown as the run's system prompt. */
789
801
  systemPrompt?: string;
802
+ /** The earlier conversation a live session starts from. */
803
+ history?: HistoryItems;
790
804
  };
791
805
 
792
806
  // Creating the running row is a precondition of a logged provider call, as for query.
@@ -803,6 +817,7 @@ async function startMediaRun(
803
817
  project_name: start.projectName,
804
818
  is_image_generation: start.kind === "image",
805
819
  media_kind: start.kind,
820
+ history: start.history,
806
821
  });
807
822
  }
808
823
 
@@ -1310,6 +1325,188 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
1310
1325
  });
1311
1326
  }
1312
1327
 
1328
+ const OPENAI_LIVE_ROUTE = `openai/${OPENAI_LIVE_MODEL}`;
1329
+
1330
+ /** Session time as m:ss. */
1331
+ function sessionClock(ms: number): string {
1332
+ const seconds = Math.floor(ms / 1000);
1333
+
1334
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
1335
+ }
1336
+
1337
+ /** The conversation as the run's response: each finished turn with its session time. */
1338
+ function liveTranscript(turns: readonly OpenAILiveTurn[]): string {
1339
+ return turns
1340
+ .map((turn) => `**${turn.role}** ${sessionClock(turn.startMs)} \n${turn.transcript.trim()}`)
1341
+ .join("\n\n");
1342
+ }
1343
+
1344
+ /** Rewrites the running row's conversation after each turn, in order, so the log fills live. */
1345
+ function liveProgressRecorder(requestLogId: number): (turns: readonly OpenAILiveTurn[]) => void {
1346
+ let pending = Promise.resolve();
1347
+
1348
+ return (turns) => {
1349
+ const response = liveTranscript(turns);
1350
+
1351
+ pending = pending.then(async () => {
1352
+ try {
1353
+ await RequestLogModel.recordRunProgress(requestLogId, { response });
1354
+ } catch (e) {
1355
+ mediaLogger.warn(`live progress failed: ${e instanceof Error ? e.message : String(e)}`);
1356
+ }
1357
+ });
1358
+ };
1359
+ }
1360
+
1361
+ const LIVE_DELEGATION_DEFAULTS = { model: "openai/gpt-6-luna", effort: "low" } as const;
1362
+
1363
+ // The voice keeps talking while it waits; a stuck backend still has to end.
1364
+ const LIVE_DELEGATION_TIMEOUT_MS = 90_000;
1365
+
1366
+ const LIVE_DELEGATION_SYSTEM =
1367
+ "You work behind a real-time voice assistant. It hands you what it cannot answer on its own, and it says your reply aloud. Reply with exactly what it should say: short, natural spoken language in the language of the conversation, with no markdown, lists, links or citations.";
1368
+
1369
+ type LiveDelegationOptions = { model: string; effort: string; webSearch: boolean };
1370
+
1371
+ /**
1372
+ * The backend sees the conversation so far, the seeded history first, as Codex's agent has it in
1373
+ * its own thread.
1374
+ */
1375
+ function delegationPrompt(
1376
+ history: readonly LiveHistoryItem[],
1377
+ turns: readonly OpenAILiveTurn[],
1378
+ request: string,
1379
+ ): string {
1380
+ const conversation = [
1381
+ ...history.map((item) => `${item.role}: ${item.text.trim()}`),
1382
+ ...turns.map((turn) => `${turn.role}: ${turn.transcript.trim()}`),
1383
+ ].join("\n");
1384
+
1385
+ return [
1386
+ conversation && `Conversation so far:\n${conversation}`,
1387
+ `Request from the voice assistant:\n${request}`,
1388
+ ]
1389
+ .filter(Boolean)
1390
+ .join("\n\n");
1391
+ }
1392
+
1393
+ /**
1394
+ * Answers the voice model's delegations with a qgrid query on the chosen model and, when the run
1395
+ * is logged, records each as a `delegation` tool step beside the session step.
1396
+ */
1397
+ function liveDelegationHandler(
1398
+ options: LiveDelegationOptions,
1399
+ instructions: string | undefined,
1400
+ history: readonly LiveHistoryItem[],
1401
+ turnsSoFar: () => readonly OpenAILiveTurn[],
1402
+ log: { requestLogId: number; costs: { delegationUsd: number } } | undefined,
1403
+ ): (delegation: OpenAILiveDelegation) => Promise<string> {
1404
+ let callIndex = 0;
1405
+
1406
+ return async ({ itemId, text }) => {
1407
+ const startedAt = Date.now();
1408
+ let reply: string;
1409
+ let outcome: Pick<RequestLogStepFields, "tool_result" | "error">;
1410
+
1411
+ try {
1412
+ const result = await QgridDispatcher.query({
1413
+ prompt: delegationPrompt(history, turnsSoFar(), text),
1414
+ system: [
1415
+ LIVE_DELEGATION_SYSTEM,
1416
+ instructions && `The voice assistant's instructions:\n${instructions}`,
1417
+ ]
1418
+ .filter(Boolean)
1419
+ .join("\n\n"),
1420
+ model: options.model,
1421
+ effort: options.effort,
1422
+ webSearch: options.webSearch,
1423
+ timeout: LIVE_DELEGATION_TIMEOUT_MS,
1424
+ });
1425
+
1426
+ reply = result.text;
1427
+
1428
+ if (log) log.costs.delegationUsd += result.costUsd;
1429
+
1430
+ outcome = {
1431
+ tool_result: JSON.stringify({
1432
+ answer: result.text,
1433
+ model: result.model,
1434
+ tokenName: result.tokenName,
1435
+ usage: result.usage,
1436
+ costUsd: result.costUsd,
1437
+ }),
1438
+ };
1439
+ } catch (e) {
1440
+ const message = e instanceof Error ? e.message : String(e);
1441
+ // The voice adapts this to the conversation instead of stalling on an unanswered request.
1442
+ reply = `The backend could not answer (${message}). Tell the user briefly that you could not get it.`;
1443
+ outcome = { error: message };
1444
+ }
1445
+
1446
+ if (log) {
1447
+ callIndex += 1;
1448
+
1449
+ const step: RequestLogStepFields = {
1450
+ step_index: 0,
1451
+ type: "tool_call",
1452
+ tool_call_index: callIndex,
1453
+ tool_call_id: `delegation:${itemId}`,
1454
+ tool_name: "delegation",
1455
+ tool_args: JSON.stringify({ request: text, ...options }),
1456
+ tool_duration_ms: Date.now() - startedAt,
1457
+ ...outcome,
1458
+ };
1459
+
1460
+ void RequestLogModel.appendStep(log.requestLogId, step).catch((e: Error) =>
1461
+ mediaLogger.error(`live delegation log failed: ${e.message}`),
1462
+ );
1463
+ }
1464
+
1465
+ return reply;
1466
+ };
1467
+ }
1468
+
1469
+ type LiveRun = {
1470
+ requestLogId: number;
1471
+ toolCallId: string;
1472
+ tokenName: string;
1473
+ startedAt: number;
1474
+ costs: { delegationUsd: number };
1475
+ };
1476
+
1477
+ // Replaces the session step's result with the summary and finishes the run when the session ends.
1478
+ // Best-effort, as for video: the session already happened, so a failure only loses the record.
1479
+ async function finishLiveRun(run: LiveRun, summary: OpenAILiveSummary): Promise<void> {
1480
+ try {
1481
+ await RequestLogModel.continueToolRun(run.requestLogId, [
1482
+ { toolCallId: run.toolCallId, output: JSON.stringify(summary), isError: false },
1483
+ ]);
1484
+
1485
+ // The session's audio time plus every delegation's backend call.
1486
+ const audio = liveCost(OPENAI_LIVE_ROUTE, summary.audioDurationMs);
1487
+ const costUsd = (audio?.costUsd ?? 0) + run.costs.delegationUsd;
1488
+
1489
+ const fields = mediaFinishFields({
1490
+ kind: "live",
1491
+ model: OPENAI_LIVE_ROUTE,
1492
+ tokenName: run.tokenName,
1493
+ durationMs: Date.now() - run.startedAt,
1494
+ response: liveTranscript(summary.turns),
1495
+ cost: audio || costUsd ? { costUsd, costSource: "pricing_table" } : undefined,
1496
+ });
1497
+
1498
+ // A sideband that failed before any turn says nothing about the session; record why.
1499
+ await RequestLogModel.finishRun(
1500
+ run.requestLogId,
1501
+ summary.error !== undefined && summary.turns.length === 0
1502
+ ? { ...fields, status: "error", error_message: summary.error }
1503
+ : fields,
1504
+ );
1505
+ } catch (e) {
1506
+ mediaLogger.error(`live request log failed: ${e instanceof Error ? e.message : String(e)}`);
1507
+ }
1508
+ }
1509
+
1313
1510
  class QgridFrameClass extends BaseFrameClass {
1314
1511
  constructor() {
1315
1512
  super("Qgrid");
@@ -2411,6 +2608,110 @@ class QgridFrameClass extends BaseFrameClass {
2411
2608
  });
2412
2609
  }
2413
2610
 
2611
+ // GPT-Live: exchanges the caller's WebRTC offer and returns the answer at once. The run stays
2612
+ // running for the whole session (up to two hours), its conversation rewritten after each turn;
2613
+ // a run left behind by a server restart is closed by the live stale sweep.
2614
+ @api({ httpMethod: "POST", clients: ["axios", "tanstack-mutation"] })
2615
+ async liveCall(params: LiveCallInput): Promise<LiveCallOutput> {
2616
+ const input = parseMediaInput(LiveCallInput, params);
2617
+ const dispatcher = openaiVoice();
2618
+ const selection = await resolveMediaTokenSelection("openai", input.tokenName);
2619
+ const voice = input.voice ?? OPENAI_LIVE_DEFAULT_VOICE;
2620
+
2621
+ const delegation: LiveDelegationOptions = {
2622
+ model: input.delegation?.model ?? LIVE_DELEGATION_DEFAULTS.model,
2623
+ effort: input.delegation?.effort ?? LIVE_DELEGATION_DEFAULTS.effort,
2624
+ webSearch: input.delegation?.webSearch ?? false,
2625
+ };
2626
+
2627
+ if (delegation.webSearch && delegation.model.startsWith("anthropic/")) {
2628
+ throw new BadRequestException(
2629
+ SD("qgrid.invalidInput")("delegation.webSearch is available on openai/ and grok/ models"),
2630
+ );
2631
+ }
2632
+
2633
+ const requestLogId = await startMediaRun(input.logger, {
2634
+ kind: "live",
2635
+ model: OPENAI_LIVE_ROUTE,
2636
+ prompt: "",
2637
+ systemPrompt: input.instructions,
2638
+ projectName: input.projectName,
2639
+ history: input.history?.map(({ role, text }) => ({ type: "message", role, content: text })),
2640
+ });
2641
+
2642
+ const startedAt = Date.now();
2643
+ const costs = { delegationUsd: 0 };
2644
+ const progress = requestLogId === undefined ? undefined : liveProgressRecorder(requestLogId);
2645
+ let turnsSoFar: readonly OpenAILiveTurn[] = [];
2646
+
2647
+ const started = await dispatchMediaCall(requestLogId, (signal) =>
2648
+ dispatcher.startLive({
2649
+ sdp: input.sdp,
2650
+ voice,
2651
+ instructions: input.instructions,
2652
+ history: input.history,
2653
+ onTurn: (turns) => {
2654
+ turnsSoFar = turns;
2655
+ progress?.(turns);
2656
+ },
2657
+ onDelegation: liveDelegationHandler(
2658
+ delegation,
2659
+ input.instructions,
2660
+ input.history ?? [],
2661
+ () => turnsSoFar,
2662
+ requestLogId === undefined ? undefined : { requestLogId, costs },
2663
+ ),
2664
+ signal,
2665
+ ...selection,
2666
+ }),
2667
+ );
2668
+
2669
+ const { sdp, callId, ended } = started.result;
2670
+
2671
+ if (requestLogId !== undefined) {
2672
+ const toolCallId = `live_session:${callId}`;
2673
+
2674
+ const args = {
2675
+ kind: "live",
2676
+ model: OPENAI_LIVE_ROUTE,
2677
+ voice,
2678
+ instructions: input.instructions,
2679
+ historyItems: input.history?.length ?? 0,
2680
+ delegation,
2681
+ transport: "webrtc",
2682
+ callId,
2683
+ };
2684
+
2685
+ // Not a pending step (that would fall to the 30-minute tool-wait cleanup): the result says
2686
+ // the session is live until the summary replaces it.
2687
+ const result = JSON.stringify({ status: "live", callId });
2688
+
2689
+ const [step] = mediaToolSteps("live", [{ toolCallId, args, result }], Date.now() - startedAt);
2690
+
2691
+ try {
2692
+ await RequestLogModel.appendStep(requestLogId, step!);
2693
+ await RequestLogModel.recordRunProgress(requestLogId, { token_name: started.tokenName });
2694
+ } catch (e) {
2695
+ mediaLogger.error(`live request log failed: ${e instanceof Error ? e.message : String(e)}`);
2696
+ }
2697
+
2698
+ const run = { requestLogId, toolCallId, tokenName: started.tokenName, startedAt, costs };
2699
+ void ended.then((summary) => finishLiveRun(run, summary));
2700
+ }
2701
+
2702
+ const output: LiveCallOutput = {
2703
+ sdp,
2704
+ callId,
2705
+ model: OPENAI_LIVE_ROUTE,
2706
+ voice,
2707
+ tokenName: started.tokenName,
2708
+ };
2709
+
2710
+ if (requestLogId !== undefined) output.requestLogId = requestLogId;
2711
+
2712
+ return output;
2713
+ }
2714
+
2414
2715
  @api({ httpMethod: "GET", clients: ["axios", "tanstack-query"] })
2415
2716
  async usage(tokenId?: number): Promise<UsageResponse> {
2416
2717
  const { rows: allTokens } = await TokenModel.findMany("A");