@cartanova/qgrid-cli 2.19.1 → 2.19.2

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 +213 -5
  4. package/bundle/dist/application/qgrid/qgrid.types.js +65 -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 +112 -2
  11. package/bundle/dist/utils/providers/openai/openai-voice-client.js +183 -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 +187 -0
  17. package/bundle/src/application/qgrid/qgrid.frame.ts +284 -2
  18. package/bundle/src/application/qgrid/qgrid.types.ts +103 -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 +22 -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 +125 -0
  29. package/bundle/src/utils/providers/openai/openai-voice-client.test.ts +184 -0
  30. package/bundle/src/utils/providers/openai/openai-voice-client.ts +277 -5
  31. package/bundle/web-dist/client/assets/index-BeceW0U9.js +104 -0
  32. package/bundle/web-dist/client/assets/index-hUNCpC11.css +1 -0
  33. package/bundle/web-dist/client/assets/logs-jMJnTwZn.js +1 -0
  34. package/bundle/web-dist/client/assets/monit-B1xRKwua.js +1 -0
  35. package/bundle/web-dist/client/assets/{routes--6kS1pgJ.js → routes-fsiyivXx.js} +2 -2
  36. package/bundle/web-dist/client/assets/{settings-Dah87LB2.js → settings-CHX44roa.js} +1 -1
  37. package/bundle/web-dist/client/assets/show-BDMwKfEY.js +2 -0
  38. package/bundle/web-dist/client/assets/{tokens-CIHja806.js → tokens-zGl36OfE.js} +1 -1
  39. package/bundle/web-dist/client/assets/{use-oauth-login-flow-DeJCqHDJ.js → use-oauth-login-flow-DYWj4645.js} +1 -1
  40. package/bundle/web-dist/client/assets/use-update-token-mutation-BRXXrEf5.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-Bwcp-KAu.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-V-E3tRqD.js} +289 -22
  58. package/bundle/web-dist/server/entry-server.generated.js +5581 -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 +15 -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
@@ -431,6 +431,25 @@ describe("RequestLogModel run lifecycle", () => {
431
431
  expect(candidateChain.where).toHaveBeenCalledWith("request_log_steps.error", null);
432
432
  });
433
433
 
434
+ it("closes only live runs still running past the threshold", async () => {
435
+ const chain = { from: vi.fn(), where: vi.fn(), update: vi.fn(async () => 2) };
436
+ chain.from.mockReturnValue(chain);
437
+ chain.where.mockReturnValue(chain);
438
+ vi.spyOn(
439
+ RequestLogModel as unknown as { getPuri: () => typeof chain },
440
+ "getPuri",
441
+ ).mockReturnValue(chain);
442
+ const threshold = new Date("2026-11-10T00:00:00.000Z");
443
+
444
+ await expect(RequestLogModel.expireStaleLiveRuns(threshold, "server stopped")).resolves.toBe(2);
445
+
446
+ expect(chain.from).toHaveBeenCalledWith("request_logs");
447
+ expect(chain.where).toHaveBeenCalledWith("media_kind", "live");
448
+ expect(chain.where).toHaveBeenCalledWith("status", "running");
449
+ expect(chain.where).toHaveBeenCalledWith("created_at", "<", threshold);
450
+ expect(chain.update).toHaveBeenCalledWith({ status: "error", error_message: "server stopped" });
451
+ });
452
+
434
453
  it("expires stale candidates independently", async () => {
435
454
  vi.spyOn(Date, "now").mockReturnValue(new Date("2026-07-23T01:00:00.000Z").getTime());
436
455
  const findCandidates = vi
@@ -121,7 +121,13 @@ export interface FinishRunParams {
121
121
 
122
122
  type FinishRunUpdate = Partial<FinishRunParams> & { id: number };
123
123
 
124
- export type RunProgressUpdate = { token_name?: string; model_name?: string; ttft_ms?: number };
124
+ export type RunProgressUpdate = {
125
+ token_name?: string;
126
+ model_name?: string;
127
+ ttft_ms?: number;
128
+ /** A live voice session's conversation so far, rewritten after every finished turn. */
129
+ response?: string;
130
+ };
125
131
 
126
132
  /** Copies `key` only when the caller supplied it, so omitted columns stay untouched. */
127
133
  function copyDefined<T>(target: Partial<T>, source: T, key: keyof T): void {
@@ -617,6 +623,19 @@ class RequestLogModelClass extends BaseModelClass<
617
623
  .update(progress);
618
624
  }
619
625
 
626
+ /**
627
+ * Live voice sessions end within two hours and log themselves at the end; a live run still
628
+ * running past `threshold` lost its server mid-session. Returns how many were closed.
629
+ */
630
+ async expireStaleLiveRuns(threshold: Date, errorMessage: string): Promise<number> {
631
+ return this.getPuri("w")
632
+ .from("request_logs")
633
+ .where("media_kind", "live")
634
+ .where("status", "running")
635
+ .where("created_at", "<", threshold)
636
+ .update({ status: "error", error_message: errorMessage });
637
+ }
638
+
620
639
  async finishRun(requestLogId: number, params: FinishRunParams): Promise<void> {
621
640
  if (params.status === "succeeded" && !params.token_name) {
622
641
  throw new Error("tokenName is required for succeeded runs");
@@ -733,6 +733,28 @@ Content-Type: application/json
733
733
 
734
734
  ###
735
735
 
736
+ POST {{baseUrl}}/api/qgrid/liveCall
737
+ Content-Type: application/json
738
+
739
+ {
740
+ "params": {
741
+ "model": "openai/gpt-live-1",
742
+ "sdp": "SDP",
743
+ "voice": "VOICE",
744
+ "instructions": "INSTRUCTIONS",
745
+ "delegation": {
746
+ "model": "MODEL",
747
+ "effort": "low",
748
+ "webSearch": false
749
+ },
750
+ "tokenName": "TOKENNAME",
751
+ "projectName": "PROJECTNAME",
752
+ "logger": false
753
+ }
754
+ }
755
+
756
+ ###
757
+
736
758
  GET {{baseUrl}}/api/qgrid/usage
737
759
  ?tokenId=0
738
760
  Content-Type: application/json
@@ -140,7 +140,7 @@ export const RequestLogStatusLabel = {
140
140
  aborted: "중단",
141
141
  };
142
142
  export const RequestLogMediaKind = z
143
- .enum(["image", "video", "stt", "tts"])
143
+ .enum(["image", "video", "stt", "tts", "live"])
144
144
  .describe("RequestLogMediaKind");
145
145
  export type RequestLogMediaKind = z.infer<typeof RequestLogMediaKind>;
146
146
  export const RequestLogMediaKindLabel = {
@@ -148,6 +148,7 @@ export const RequestLogMediaKindLabel = {
148
148
  video: "비디오",
149
149
  stt: "음성 인식",
150
150
  tts: "음성 합성",
151
+ live: "실시간 대화",
151
152
  };
152
153
 
153
154
  // Enums: RequestLogStep
@@ -251,7 +251,7 @@ const entityLabels = {
251
251
  "entity.RequestLog.is_image_generation": "이미지 생성 turn 여부 (quota 귀속용)",
252
252
  "entity.RequestLog.is_structured": "structured output(jsonSchema) 요청 여부 (목록 구분 표시용)",
253
253
  "entity.RequestLog.media_kind":
254
- "미디어 엔드포인트 종류(image/video/stt/tts). 텍스트 요청은 null (목록 Fmt 표시용)",
254
+ "미디어 엔드포인트 종류(image/video/stt/tts/live). 텍스트 요청은 null (목록 Fmt 표시용)",
255
255
  "enum.RequestLogOrderBy.id-desc": "ID최신순",
256
256
  "enum.RequestLogOrderBy.id-asc": "ID오래된순",
257
257
  "enum.RequestLogOrderBy.created_at-desc": "등록일시최신순",
@@ -281,6 +281,7 @@ const entityLabels = {
281
281
  "enum.RequestLogMediaKind.video": "비디오",
282
282
  "enum.RequestLogMediaKind.stt": "음성 인식",
283
283
  "enum.RequestLogMediaKind.tts": "음성 합성",
284
+ "enum.RequestLogMediaKind.live": "실시간 대화",
284
285
  "entity.RequestLogStep": "RequestLogStep",
285
286
  "entity.RequestLogStep.id": "ID",
286
287
  "entity.RequestLogStep.created_at": "등록일시",
@@ -477,6 +477,9 @@ const STT_USD_PER_MINUTE = new Map([
477
477
  ["grok/grok-voice-transcribe-2.0", 0.1 / 60],
478
478
  ]);
479
479
 
480
+ // GPT-Live, USD per minute of session audio (OpenAI list price, billed per second; checked 2026-11-10).
481
+ const LIVE_USD_PER_MINUTE = new Map([["openai/gpt-live-1", 0.05]]);
482
+
480
483
  const GROK_TTS_USD_PER_CHARACTER = 15 / 1_000_000;
481
484
 
482
485
  const priced = (costUsd: number): VoiceCost => ({ costUsd, costSource: "pricing_table" });
@@ -507,6 +510,18 @@ export function sttCost(route: string, durationSec: number | undefined): VoiceCo
507
510
  : priced((perMinute * durationSec) / 60);
508
511
  }
509
512
 
513
+ /** A live session by the audio time the session reported; unknown time stays unpriced. */
514
+ export function liveCost(
515
+ route: string,
516
+ audioDurationMs: number | undefined,
517
+ ): VoiceCost | undefined {
518
+ const perMinute = LIVE_USD_PER_MINUTE.get(route);
519
+
520
+ return perMinute === undefined || audioDurationMs === undefined
521
+ ? undefined
522
+ : priced((perMinute * audioDurationMs) / 60_000);
523
+ }
524
+
510
525
  /** Grok `/tts` by input characters. */
511
526
  export function grokSpeechCost(characters: number): VoiceCost {
512
527
  return priced(characters * GROK_TTS_USD_PER_CHARACTER);
@@ -53,6 +53,22 @@ async function tickTimer(): Promise<void> {
53
53
  }
54
54
 
55
55
  describe("OpenAIDispatcher direct runtime", () => {
56
+ it("sends Codex's hosted web search only when the request asks for it", async () => {
57
+ const seen: OpenAIResponsesOptions[] = [];
58
+
59
+ const d = dispatcher((options) => {
60
+ seen.push(options);
61
+ return events({ type: "completed", responseId: "r" });
62
+ });
63
+
64
+ await d.onTokenAdded(1, "one", credentials);
65
+ await d.generate(request({ tools: [{ type: "web_search" }] }));
66
+ await d.generate(request());
67
+
68
+ expect(seen[0]?.tools).toEqual([{ type: "web_search", external_web_access: true }]);
69
+ expect(seen[1]?.tools).toBeUndefined();
70
+ });
71
+
56
72
  it.each(["gpt-6.1-terra", "gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5"])(
57
73
  "disables thinking and omits summaries through generate/stream for %s",
58
74
  async (model) => {
@@ -33,6 +33,8 @@ import { handleChatgptAuthTokensRefresh } from "./openai-refresh";
33
33
  import { type OpenAITransportKind, resolveOpenAITransportKind } from "./openai-transport-config";
34
34
  import {
35
35
  isUnauthorizedRealtimeError,
36
+ type OpenAILiveCall,
37
+ type OpenAILiveCallRequest,
36
38
  type OpenAISpeakRequest,
37
39
  type OpenAISpeechResult,
38
40
  type OpenAITranscribeRequest,
@@ -246,6 +248,12 @@ const AUTO_IMAGE_TOOL: OpenAIResponseItem = {
246
248
  },
247
249
  };
248
250
 
251
+ /**
252
+ * Hosted web search as Codex sends it (tools/src/tool_spec.rs); `external_web_access` asks for
253
+ * live search rather than the cached index. Answered on the subscription route (2026-11-10).
254
+ */
255
+ const WEB_SEARCH_TOOL: OpenAIResponseItem = { type: "web_search", external_web_access: true };
256
+
249
257
  function requestOptions(req: GenerateRequest): OpenAIResponsesOptions {
250
258
  const { outputFormat, ...imageControls } = req.imageGenerationOptions ?? {};
251
259
  const auto = req.imageGeneration === "auto";
@@ -271,6 +279,11 @@ function requestOptions(req: GenerateRequest): OpenAIResponsesOptions {
271
279
  options.tools = [AUTO_IMAGE_TOOL];
272
280
  }
273
281
 
282
+ // Function tools reach OpenAI through qgrid's tool emulation; only hosted search goes native.
283
+ if (req.tools?.some((tool) => tool.type === "web_search")) {
284
+ options.tools = [...(options.tools ?? []), WEB_SEARCH_TOOL];
285
+ }
286
+
274
287
  const reasoning = asReasoning(req);
275
288
 
276
289
  if (reasoning) options.reasoning = reasoning;
@@ -356,6 +369,18 @@ export class OpenAIDispatcher implements ProviderDispatcher {
356
369
  );
357
370
  }
358
371
 
372
+ async startLive(
373
+ request: OpenAILiveCallRequest & OpenAIVoiceSelection,
374
+ ): Promise<OpenAIVoiceDispatchResult<OpenAILiveCall>> {
375
+ const { preferredTokenId, requirePreferredToken, ...liveRequest } = request;
376
+
377
+ return this.runVoice(
378
+ { preferredTokenId, requirePreferredToken },
379
+ request.signal,
380
+ (credentials) => this.voiceClient.createLiveCall(credentials, liveRequest),
381
+ );
382
+ }
383
+
359
384
  /**
360
385
  * Selects a token, runs the realtime call, and on one 401 refreshes that token's credentials and
361
386
  * retries once (as the Responses transports do). Any other failure propagates: a realtime
@@ -416,6 +441,7 @@ export class OpenAIDispatcher implements ProviderDispatcher {
416
441
  }
417
442
 
418
443
  async stop(): Promise<void> {
444
+ this.voiceClient.closeLiveSessions();
419
445
  this.clients.forEach(({ client }) => client.close?.());
420
446
  this.clients.clear();
421
447
  this.retiredClients.forEach((entry) => entry.client.close?.());
@@ -81,6 +81,131 @@ export const OPENAI_TRANSCRIPTION_MODELS_WITHOUT_PROMPT: ReadonlySet<string> = n
81
81
  */
82
82
  export const OPENAI_SPEECH_MODELS = ["gpt-realtime-2.1-mini", "gpt-realtime-2.1"] as const;
83
83
 
84
+ // GPT-Live (Codex realtime v3, "frameless") on a ChatGPT subscription, mirroring openai/codex main
85
+ // @ 2026-11-10. The caller's own WebRTC peer carries the audio; qgrid only exchanges its SDP offer
86
+ // through /realtime/calls and watches the call's sideband for the transcript and usage. The direct
87
+ // /v1/live sockets refuse the subscription token ("Voice session access denied"), as Codex expects
88
+ // (core/src/realtime_conversation.rs realtime_api_key). Probe notes: SON-591, SON-592.
89
+
90
+ /** codex-api/src/endpoint/realtime_call.rs configure_realtime_call_request (backend shape + v3). */
91
+ export const OPENAI_LIVE_CALLS_QUERY = "intent=quicksilver&architecture=avas";
92
+
93
+ /**
94
+ * Undocumented; Codex sends it for v3 (core/src/realtime_conversation.rs realtime_request_headers).
95
+ * Required on both the /calls POST (else 400 invalid_quicksilver_alpha_header) and the sideband.
96
+ */
97
+ export const OPENAI_LIVE_ALPHA_HEADER = { "OpenAI-Alpha": "quicksilver=v2" } as const;
98
+
99
+ /** Sideband base: wss://api.openai.com/v1/live/<rtc_id> (realtime_websocket/methods.rs). */
100
+ export const OPENAI_LIVE_WS_URL = "wss://api.openai.com/v1/live" as const;
101
+
102
+ /** The only live model qgrid exposes. */
103
+ export const OPENAI_LIVE_MODEL = "gpt-live-1";
104
+
105
+ /**
106
+ * Sent as session.model, as Codex does (DEFAULT_FRAMELESS_REALTIME_MODEL). The backend ignores the
107
+ * field on this route: made-up names opened a session too (2026-11-10).
108
+ */
109
+ const OPENAI_LIVE_WIRE_MODEL = "gpt-live-1-codex";
110
+
111
+ /**
112
+ * protocol/src/protocol.rs RealtimeVoicesList::builtin v3; Codex's live default is cove. Any other
113
+ * voice still gets a 201 from /calls, but the session never starts (sideband 404).
114
+ */
115
+ export const OPENAI_LIVE_VOICES = [
116
+ "cove",
117
+ "juniper",
118
+ "maple",
119
+ "spruce",
120
+ "ember",
121
+ "vale",
122
+ "breeze",
123
+ "arbor",
124
+ "sol",
125
+ "aube",
126
+ "bubbie",
127
+ "haetsal",
128
+ "hanul",
129
+ "himari",
130
+ "leher",
131
+ "miko",
132
+ "neer",
133
+ "porto",
134
+ "rindo",
135
+ "rio",
136
+ "rivage",
137
+ "selva",
138
+ "sonna",
139
+ "tinta",
140
+ "viola",
141
+ ] as const;
142
+
143
+ export const OPENAI_LIVE_DEFAULT_VOICE = "cove";
144
+
145
+ export function isOpenAILiveVoice(value: string): boolean {
146
+ return OPENAI_LIVE_VOICES.some((voice) => voice === value);
147
+ }
148
+
149
+ /** codex-api methods_frameless_bidi.rs session_json, without initial items or handoffs. */
150
+ export function buildLiveSession(options: { voice: string; instructions?: string }): JsonValue {
151
+ return {
152
+ model: OPENAI_LIVE_WIRE_MODEL,
153
+ instructions: options.instructions ?? "",
154
+ audio: { output: { voice: options.voice } },
155
+ delegation: { type: "client" },
156
+ };
157
+ }
158
+
159
+ /** One finished turn; the sideband also mirrors both audio streams, which qgrid skips. */
160
+ export const liveTurnDoneEvent = z.looseObject({
161
+ type: z.literal("turn.done"),
162
+ turn: z.looseObject({
163
+ role: z.string(),
164
+ transcript: z.string(),
165
+ start_ms: z.number(),
166
+ end_ms: z.number(),
167
+ }),
168
+ });
169
+
170
+ /**
171
+ * With `delegation.type: "client"` the voice model hands work it cannot do itself (lookups,
172
+ * reasoning) to the client and keeps talking until the answer arrives; Codex runs it as a turn of
173
+ * its own agent (core/src/realtime_conversation.rs route_realtime_text_input). Left unanswered,
174
+ * the voice stalls with filler indefinitely (SON-592). `responses` delegation, where OpenAI runs
175
+ * the backend, fails on the subscription route (2026-11-10).
176
+ */
177
+ export const liveDelegationCreatedEvent = z.looseObject({
178
+ type: z.literal("delegation.created"),
179
+ item: z.looseObject({
180
+ id: z.string(),
181
+ target: z.literal("client"),
182
+ content: z.array(z.looseObject({ type: z.string(), text: z.string().optional() })),
183
+ }),
184
+ });
185
+
186
+ /** The answer to a delegation; no channel means speakable (codex-api methods_frameless_bidi.rs). */
187
+ export function liveDelegationAnswerEvent(delegationItemId: string, text: string): JsonValue {
188
+ return {
189
+ type: "delegation.context.append",
190
+ delegation_item_id: delegationItemId,
191
+ content: [{ type: "input_text", text }],
192
+ };
193
+ }
194
+
195
+ const liveUsage = z.looseObject({ audio_duration_ms: z.number() });
196
+
197
+ /** Running usage, about every 15 s; the last one stands in when the session ends without close. */
198
+ export const liveUsageUpdatedEvent = z.looseObject({
199
+ type: z.literal("session.usage.updated"),
200
+ usage: liveUsage,
201
+ });
202
+
203
+ export const liveSessionClosedEvent = z.looseObject({
204
+ type: z.literal("session.closed"),
205
+ reason: z.string().optional(),
206
+ usage: liveUsage.optional(),
207
+ });
208
+
84
209
  /**
85
210
  * A minimal Opus-only SDP offer. Codex sends a real WebRTC offer; qgrid has no RTP peer and only
86
211
  * needs the call id from the response. The server has accepted this offer on every probe
@@ -3,10 +3,12 @@ import { describe, expect, it, vi } from "vitest";
3
3
  import { CODEX_CLI_ORIGINATOR } from "./openai-backend-protocol";
4
4
  import type { OpenAIWebSocketFactory, OpenAIWebSocketLike } from "./openai-direct-client";
5
5
  import {
6
+ buildLiveSession,
6
7
  buildOpenAIRealtimeHeaders,
7
8
  buildSpeechSession,
8
9
  buildTranscriptionSession,
9
10
  decodeWav,
11
+ OPENAI_LIVE_WS_URL,
10
12
  OPENAI_REALTIME_CALLS_URL,
11
13
  OPENAI_REALTIME_WS_URL,
12
14
  prepareRealtimeInput,
@@ -580,3 +582,185 @@ describe("OpenAIVoiceClient.speak", () => {
580
582
  });
581
583
  });
582
584
 
585
+ describe("OpenAIVoiceClient.createLiveCall", () => {
586
+ // Shapes observed live on 2026-11-10 (SON-592): a browser peer in conversation with gpt-live-1.
587
+ const userTurn = {
588
+ type: "turn.done",
589
+ turn: { id: "turn_u", role: "user", start_ms: 600, end_ms: 5800, transcript: "Hi there?" },
590
+ };
591
+
592
+ const assistantTurn = {
593
+ type: "turn.done",
594
+ turn: { id: "turn_a", role: "assistant", start_ms: 5600, end_ms: 9400, transcript: "Hello!" },
595
+ };
596
+
597
+ it("exchanges the offer through /calls with the alpha header and summarizes the sideband", async () => {
598
+ const fetchMock = vi.fn(async () => callsResponse("rtc_live"));
599
+ const ws = mockedWebSocket();
600
+
601
+ const client = new OpenAIVoiceClient({
602
+ fetch: fetchMock as unknown as typeof fetch,
603
+ webSocketFactory: ws.factory,
604
+ });
605
+
606
+ const progress: number[] = [];
607
+
608
+ const call = await client.createLiveCall(credentials, {
609
+ sdp: "v=0\r\noffer",
610
+ voice: "hanul",
611
+ instructions: "Be brief.",
612
+ onTurn: (turns) => progress.push(turns.length),
613
+ });
614
+
615
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
616
+ expect(url).toBe(`${OPENAI_REALTIME_CALLS_URL}?intent=quicksilver&architecture=avas`);
617
+ const headers = init.headers as Record<string, string>;
618
+ expect(headers["OpenAI-Alpha"]).toBe("quicksilver=v2");
619
+ expect(headers.Authorization).toBe("Bearer access");
620
+
621
+ expect(JSON.parse(String(init.body))).toEqual({
622
+ sdp: "v=0\r\noffer",
623
+ session: {
624
+ model: "gpt-live-1-codex",
625
+ instructions: "Be brief.",
626
+ audio: { output: { voice: "hanul" } },
627
+ delegation: { type: "client" },
628
+ },
629
+ });
630
+
631
+ expect(buildLiveSession({ voice: "cove" })).toMatchObject({ instructions: "" });
632
+ expect(call).toMatchObject({ sdp: "v=0", callId: "rtc_live" });
633
+ expect(call.quotaHeaders.get("x-codex-primary-used-percent")).toBe("88");
634
+ expect(ws.calls[0]?.url).toBe(`${OPENAI_LIVE_WS_URL}/rtc_live`);
635
+ expect(ws.calls[0]?.headers["OpenAI-Alpha"]).toBe("quicksilver=v2");
636
+
637
+ const socket = ws.sockets[0]!;
638
+ socket.emit("open");
639
+ socket.message({ type: "session.started", session: { id: "rtc_live", expires_at: 1 } });
640
+ socket.message({ type: "session.input_audio.append", audio: "AAAA" });
641
+ socket.message(userTurn);
642
+ socket.message({ type: "session.output_audio.delta", delta: "AAAA" });
643
+ socket.message(assistantTurn);
644
+ socket.message({ type: "session.usage.updated", usage: { audio_duration_ms: 5000 } });
645
+
646
+ socket.message({
647
+ type: "session.closed",
648
+ reason: "client_request",
649
+ usage: { audio_duration_ms: 9400 },
650
+ });
651
+
652
+ await expect(call.ended).resolves.toMatchObject({
653
+ turns: [
654
+ { role: "user", transcript: "Hi there?", startMs: 600, endMs: 5800 },
655
+ { role: "assistant", transcript: "Hello!", startMs: 5600, endMs: 9400 },
656
+ ],
657
+ audioDurationMs: 9400,
658
+ endReason: "client_request",
659
+ });
660
+ expect(progress).toEqual([1, 2]);
661
+ // The session belongs to the caller's peer: qgrid sends nothing on the sideband.
662
+ expect(socket.sent).toHaveLength(0);
663
+ expect(socket.closed?.code).toBe(1000);
664
+ });
665
+
666
+ it("answers a delegation on the sideband and keeps the session's events", async () => {
667
+ const ws = mockedWebSocket();
668
+
669
+ const client = new OpenAIVoiceClient({
670
+ fetch: (async () => callsResponse("rtc_live")) as unknown as typeof fetch,
671
+ webSocketFactory: ws.factory,
672
+ });
673
+
674
+ const onDelegation = vi.fn(async () => "Nvidia is in today's top story.");
675
+ const call = await client.createLiveCall(credentials, { sdp: "v=0", onDelegation });
676
+ const socket = ws.sockets[0]!;
677
+ socket.emit("open");
678
+ socket.message({ type: "session.input_audio.append", audio: "AAAA" });
679
+ socket.message({ type: "turn.delta", delta: " news", turn_id: "turn_u" });
680
+
681
+ socket.message({
682
+ type: "delegation.created",
683
+ item: {
684
+ id: "item_d",
685
+ type: "delegation",
686
+ target: "client",
687
+ handoff_id: "handoff_1",
688
+ content: [{ type: "input_text", text: "Look up today's top tech news" }],
689
+ },
690
+ });
691
+
692
+ await tick();
693
+ await tick();
694
+
695
+ expect(onDelegation).toHaveBeenCalledWith({ itemId: "item_d", text: "Look up today's top tech news" });
696
+ expect(socket.sentEvents()).toEqual([
697
+ {
698
+ type: "delegation.context.append",
699
+ delegation_item_id: "item_d",
700
+ content: [{ type: "input_text", text: "Nvidia is in today's top story." }],
701
+ },
702
+ ]);
703
+
704
+ socket.message({ type: "session.closed", reason: "client_request", usage: { audio_duration_ms: 1 } });
705
+ const summary = await call.ended;
706
+
707
+ // Audio copies and word-level text are skipped; qgrid's own answer is logged with them.
708
+ expect(summary.events.map(({ event }) => (event as { type: string }).type)).toEqual([
709
+ "delegation.created",
710
+ "delegation.context.append",
711
+ "session.closed",
712
+ ]);
713
+ });
714
+
715
+ it("ends at a bare sideband close with the last reported usage", async () => {
716
+ const ws = mockedWebSocket();
717
+
718
+ const client = new OpenAIVoiceClient({
719
+ fetch: (async () => callsResponse("rtc_live")) as unknown as typeof fetch,
720
+ webSocketFactory: ws.factory,
721
+ });
722
+
723
+ const call = await client.createLiveCall(credentials, { sdp: "v=0" });
724
+ const socket = ws.sockets[0]!;
725
+ socket.emit("open");
726
+ socket.message(userTurn);
727
+ socket.message({ type: "session.usage.updated", usage: { audio_duration_ms: 27_400 } });
728
+ socket.emit("close", 1006, Buffer.from(""));
729
+
730
+ await expect(call.ended).resolves.toMatchObject({
731
+ turns: [{ role: "user" }],
732
+ audioDurationMs: 27_400,
733
+ endReason: "sideband closed (1006)",
734
+ });
735
+ });
736
+
737
+ it("resolves, never rejects, when the sideband handshake fails", async () => {
738
+ const ws = mockedWebSocket();
739
+
740
+ const client = new OpenAIVoiceClient({
741
+ fetch: (async () => callsResponse("rtc_live")) as unknown as typeof fetch,
742
+ webSocketFactory: ws.factory,
743
+ });
744
+
745
+ const call = await client.createLiveCall(credentials, { sdp: "v=0" });
746
+ ws.sockets[0]!.emit("unexpected-response", {}, { statusCode: 404 });
747
+
748
+ await expect(call.ended).resolves.toEqual({
749
+ turns: [],
750
+ events: [],
751
+ audioDurationMs: undefined,
752
+ endReason: "sideband error",
753
+ error: "realtime socket handshake rejected with HTTP 404",
754
+ });
755
+ });
756
+
757
+ it("rejects voices outside the live list before any network call", async () => {
758
+ const fetchMock = vi.fn();
759
+ const client = new OpenAIVoiceClient({ fetch: fetchMock as unknown as typeof fetch });
760
+
761
+ await expect(
762
+ client.createLiveCall(credentials, { sdp: "v=0", voice: "marin" }),
763
+ ).rejects.toBeInstanceOf(OpenAIVoiceInputError);
764
+ expect(fetchMock).not.toHaveBeenCalled();
765
+ });
766
+ });