@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
@@ -1,5 +1,64 @@
1
1
  import { z } from "zod";
2
2
 
3
+ // ─── Served models ───
4
+
5
+ // qgrid 가 실제로 서비스하는 텍스트 모델(provider 별 최신순).
6
+ // dispatcher 는 provider prefix 없는 모델을 라우팅하지 못하므로 항상 접두사를 포함한다.
7
+ // ai-sdk 의 QgridSupportedModel union 중 실제로 서비스되는 모델만 provider 별로 최신순 나열한다.
8
+ // sonamu sync 로 web 에 내려가 대시보드 채팅과 GPT-Live 위임 모델 선택이 쓰고, liveCall 이 위임 모델을
9
+ // 이 목록으로 검사한다. ai-sdk 와 공유하지 않으므로 모델을 추가할 때 ai-sdk union 도 함께 갱신한다.
10
+ // union 에는 남아 있지만 여기서 제외한 항목:
11
+ // - `gpt-5.4`, `gpt-5.4-mini`: qgrid 가 쓰는 ChatGPT 구독 Codex 경로에서 2026-08-31 retired
12
+ // (대체 gpt-5.6-terra / gpt-5.6-luna).
13
+ // - `gpt-5.2`, `gpt-5.3-codex`: 같은 경로에서 이미 제공 종료.
14
+ // - `gpt-5.3-codex-spark`: 같은 경로에서 400("not supported when using Codex with a ChatGPT account"),
15
+ // Codex 카탈로그에서도 빠짐(2026-09-29 확인).
16
+ // - `gpt-5.5`: Codex/ChatGPT 경로에서 2026-10-14 은퇴 예정(대체 gpt-6.1-sol / gpt-6-luna).
17
+ // - `claude-opus-4`, `claude-sonnet-4`: 2026-06-15 retired, Claude Code 에서 모델 오류.
18
+ // - `claude-opus-4-1`: 2026-08-05 retired, Claude Code 가 claude-opus-5-5 로 대체 서빙.
19
+ // - `claude-sonnet-4-5`: 2026-09-30 deprecated, 2026-11-30 retirement 예정(대체 claude-sonnet-5-5).
20
+ // - `claude-sonnet-4-7`: 공식 카탈로그에 없는 유령 항목.
21
+ export const QGRID_MODEL_GROUPS: { label: string; models: string[] }[] = [
22
+ {
23
+ label: "OpenAI",
24
+ models: [
25
+ "openai/gpt-6-astra",
26
+ "openai/gpt-6.1-sol",
27
+ "openai/gpt-6.1-terra",
28
+ "openai/gpt-6-sol",
29
+ "openai/gpt-6-luna",
30
+ "openai/gpt-5.6-terra",
31
+ "openai/gpt-5.6-sol",
32
+ "openai/gpt-5.6-luna",
33
+ ],
34
+ },
35
+ {
36
+ label: "Anthropic",
37
+ models: [
38
+ "anthropic/claude-fable-5-1",
39
+ "anthropic/claude-fable-5",
40
+ "anthropic/claude-opus-5-5",
41
+ "anthropic/claude-opus-5",
42
+ "anthropic/claude-sonnet-5-5",
43
+ "anthropic/claude-sonnet-5",
44
+ "anthropic/claude-haiku-5-5",
45
+ "anthropic/claude-opus-4-8",
46
+ "anthropic/claude-opus-4-7",
47
+ "anthropic/claude-opus-4-6",
48
+ "anthropic/claude-opus-4-5",
49
+ "anthropic/claude-sonnet-4-6",
50
+ "anthropic/claude-haiku-4-5",
51
+ ],
52
+ },
53
+ {
54
+ label: "Grok",
55
+ // ai-sdk QgridGrokModel 의 구독 카탈로그 id(grok-4.7 이 기본). Grok 4.6/4.7 은 Build 모델로 라우팅된다.
56
+ models: ["grok/grok-4.7", "grok/grok-4.7-build-fast", "grok/grok-4.6", "grok/grok-4.5"],
57
+ },
58
+ ];
59
+
60
+ export const QGRID_MODELS = QGRID_MODEL_GROUPS.flatMap((group) => group.models);
61
+
3
62
  // ─── Query ───
4
63
 
5
64
  export const Effort = z.enum(["low", "medium", "high"]);
@@ -596,6 +655,68 @@ export const SpeakOutput = z.object({
596
655
 
597
656
  export type SpeakOutput = z.infer<typeof SpeakOutput>;
598
657
 
658
+ // GPT-Live voice conversation (openai/gpt-live-1). The caller's WebRTC peer makes the SDP offer;
659
+ // qgrid exchanges it with the subscription token and returns the answer, then logs the
660
+ // conversation when the session ends. Audio flows between the caller and OpenAI only. The caller
661
+ // ends the session by sending {"type":"session.close"} on its "oai-events" data channel; a dropped
662
+ // peer keeps the session (and its billed time) running for about 30 s.
663
+ // An earlier conversation the session starts from: a past live session's turns or a text chat
664
+ // alike. Measured on the subscription route (2026-11-10): past 128 items, or with a system role,
665
+ // OpenAI accepts the call but never starts the session; 1,000,000 characters still opened.
666
+ export const LiveHistoryItem = z.object({
667
+ role: z.enum(["user", "assistant", "developer"]),
668
+ text: z.string().min(1),
669
+ });
670
+
671
+ export type LiveHistoryItem = z.infer<typeof LiveHistoryItem>;
672
+
673
+ export const LiveCallInput = z.object({
674
+ model: z.literal("openai/gpt-live-1").optional(),
675
+ sdp: z
676
+ .string()
677
+ .startsWith("v=0", "sdp must be an SDP offer")
678
+ .max(64 * 1024),
679
+ // One of the live voices (cove by default); the realtime TTS voices do not apply.
680
+ voice: z.string().min(1).max(64).optional(),
681
+ instructions: z.string().min(1).max(8_000).optional(),
682
+ history: z
683
+ .array(LiveHistoryItem)
684
+ .max(128, "history holds at most 128 items")
685
+ .refine(
686
+ (items) => items.reduce((total, item) => total + item.text.length, 0) <= 1_000_000,
687
+ "history text exceeds 1,000,000 characters",
688
+ )
689
+ .optional(),
690
+ // What the voice hands off (lookups, reasoning) runs as a qgrid query on this model, chosen per
691
+ // session: any served model in QGRID_MODELS (default openai/gpt-6-luna at low effort).
692
+ // webSearch turns on the provider's hosted web search (openai/ and grok/ only).
693
+ delegation: z
694
+ .object({
695
+ model: z
696
+ .string()
697
+ .refine((id) => QGRID_MODELS.includes(id), "model must be one of QGRID_MODELS")
698
+ .optional(),
699
+ effort: Effort.optional(),
700
+ webSearch: z.boolean().optional(),
701
+ })
702
+ .optional(),
703
+ ...MediaCallOptions,
704
+ });
705
+
706
+ export type LiveCallInput = z.infer<typeof LiveCallInput>;
707
+
708
+ export const LiveCallOutput = z.object({
709
+ // The SDP answer for the caller's peer connection.
710
+ sdp: z.string(),
711
+ callId: z.string(),
712
+ model: z.string(),
713
+ voice: z.string(),
714
+ tokenName: z.string(),
715
+ requestLogId: z.number().optional(),
716
+ });
717
+
718
+ export type LiveCallOutput = z.infer<typeof LiveCallOutput>;
719
+
599
720
  // ─── Run Lifecycle ───
600
721
 
601
722
  export const CreateRunInput = z.object({
@@ -226,7 +226,7 @@
226
226
  "type": "enum",
227
227
  "id": "RequestLogMediaKind",
228
228
  "nullable": true,
229
- "desc": "미디어 엔드포인트 종류(image/video/stt/tts). 텍스트 요청은 null (목록 Fmt 표시용)"
229
+ "desc": "미디어 엔드포인트 종류(image/video/stt/tts/live). 텍스트 요청은 null (목록 Fmt 표시용)"
230
230
  }
231
231
  ],
232
232
  "indexes": [
@@ -400,7 +400,8 @@
400
400
  "image": "이미지",
401
401
  "video": "비디오",
402
402
  "stt": "음성 인식",
403
- "tts": "음성 합성"
403
+ "tts": "음성 합성",
404
+ "live": "실시간 대화"
404
405
  }
405
406
  }
406
407
  }
@@ -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,34 @@ 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
+ "history": [
746
+ {
747
+ "role": "user",
748
+ "text": "TEXT"
749
+ }
750
+ ],
751
+ "delegation": {
752
+ "model": "MODEL",
753
+ "effort": "low",
754
+ "webSearch": false
755
+ },
756
+ "tokenName": "TOKENNAME",
757
+ "projectName": "PROJECTNAME",
758
+ "logger": false
759
+ }
760
+ }
761
+
762
+ ###
763
+
736
764
  GET {{baseUrl}}/api/qgrid/usage
737
765
  ?tokenId=0
738
766
  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,166 @@ 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
+ /** A message the session starts from; user and developer text is input, assistant text output. */
150
+ export interface LiveHistoryMessage {
151
+ role: "user" | "assistant" | "developer";
152
+ text: string;
153
+ }
154
+
155
+ type LiveInitialItem = {
156
+ type: "message";
157
+ role: LiveHistoryMessage["role"];
158
+ content: Array<{ type: "input_text" | "output_text"; text: string }>;
159
+ };
160
+
161
+ /** The session sent with the call: codex-api methods_frameless_bidi.rs session_json. */
162
+ export type LiveSessionPayload = {
163
+ model: string;
164
+ instructions: string;
165
+ audio: { output: { voice: string } };
166
+ delegation: { type: "client" };
167
+ /** The history, as Codex's initial items. */
168
+ initial_items?: LiveInitialItem[];
169
+ };
170
+
171
+ export function buildLiveSession(options: {
172
+ voice: string;
173
+ instructions?: string;
174
+ history?: readonly LiveHistoryMessage[];
175
+ }): LiveSessionPayload {
176
+ const session: LiveSessionPayload = {
177
+ model: OPENAI_LIVE_WIRE_MODEL,
178
+ instructions: options.instructions ?? "",
179
+ audio: { output: { voice: options.voice } },
180
+ delegation: { type: "client" },
181
+ };
182
+
183
+ if (options.history?.length) {
184
+ session.initial_items = options.history.map(({ role, text }) => ({
185
+ type: "message",
186
+ role,
187
+ content: [{ type: role === "assistant" ? "output_text" : "input_text", text }],
188
+ }));
189
+ }
190
+
191
+ return session;
192
+ }
193
+
194
+ /** One finished turn; the sideband also mirrors both audio streams, which qgrid skips. */
195
+ export const liveTurnDoneEvent = z.looseObject({
196
+ type: z.literal("turn.done"),
197
+ turn: z.looseObject({
198
+ role: z.string(),
199
+ transcript: z.string(),
200
+ start_ms: z.number(),
201
+ end_ms: z.number(),
202
+ }),
203
+ });
204
+
205
+ /**
206
+ * With `delegation.type: "client"` the voice model hands work it cannot do itself (lookups,
207
+ * reasoning) to the client and keeps talking until the answer arrives; Codex runs it as a turn of
208
+ * its own agent (core/src/realtime_conversation.rs route_realtime_text_input). Left unanswered,
209
+ * the voice stalls with filler indefinitely (SON-592). `responses` delegation, where OpenAI runs
210
+ * the backend, fails on the subscription route (2026-11-10).
211
+ */
212
+ export const liveDelegationCreatedEvent = z.looseObject({
213
+ type: z.literal("delegation.created"),
214
+ item: z.looseObject({
215
+ id: z.string(),
216
+ target: z.literal("client"),
217
+ content: z.array(z.looseObject({ type: z.string(), text: z.string().optional() })),
218
+ }),
219
+ });
220
+
221
+ /** The answer to a delegation; no channel means speakable (codex-api methods_frameless_bidi.rs). */
222
+ export function liveDelegationAnswerEvent(delegationItemId: string, text: string): JsonValue {
223
+ return {
224
+ type: "delegation.context.append",
225
+ delegation_item_id: delegationItemId,
226
+ content: [{ type: "input_text", text }],
227
+ };
228
+ }
229
+
230
+ const liveUsage = z.looseObject({ audio_duration_ms: z.number() });
231
+
232
+ /** Running usage, about every 15 s; the last one stands in when the session ends without close. */
233
+ export const liveUsageUpdatedEvent = z.looseObject({
234
+ type: z.literal("session.usage.updated"),
235
+ usage: liveUsage,
236
+ });
237
+
238
+ export const liveSessionClosedEvent = z.looseObject({
239
+ type: z.literal("session.closed"),
240
+ reason: z.string().optional(),
241
+ usage: liveUsage.optional(),
242
+ });
243
+
84
244
  /**
85
245
  * A minimal Opus-only SDP offer. Codex sends a real WebRTC offer; qgrid has no RTP peer and only
86
246
  * needs the call id from the response. The server has accepted this offer on every probe