@cartanova/qgrid-cli 2.22.2 → 2.23.1

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 (77) hide show
  1. package/bundle/dist/application/qgrid/model-catalog.js +62 -0
  2. package/bundle/dist/application/qgrid/openai-compat.js +127 -0
  3. package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +2 -2
  4. package/bundle/dist/application/qgrid/qgrid.frame.js +204 -8
  5. package/bundle/dist/application/qgrid/qgrid.types.js +82 -2
  6. package/bundle/dist/application/qgrid/transcribe-stream.js +282 -0
  7. package/bundle/dist/application/queries.generated.js +2 -1
  8. package/bundle/dist/application/request-log/request-log.model.js +5 -4
  9. package/bundle/dist/server-error-handler.js +6 -3
  10. package/bundle/dist/sonamu.config.js +5 -2
  11. package/bundle/dist/utils/providers/anthropic/anthropic-constants.js +8 -2
  12. package/bundle/dist/utils/providers/anthropic/anthropic-quota.js +1 -1
  13. package/bundle/dist/utils/providers/common/model-cost.js +29 -2
  14. package/bundle/dist/utils/providers/openai/openai-dispatcher.js +9 -1
  15. package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +38 -6
  16. package/bundle/dist/utils/providers/openai/openai-voice-client.js +131 -3
  17. package/bundle/src/application/qgrid/model-catalog.test.ts +37 -0
  18. package/bundle/src/application/qgrid/model-catalog.ts +85 -0
  19. package/bundle/src/application/qgrid/openai-compat.test.ts +99 -0
  20. package/bundle/src/application/qgrid/openai-compat.ts +157 -0
  21. package/bundle/src/application/qgrid/qgrid-run-lifecycle.test.ts +1 -1
  22. package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +1 -1
  23. package/bundle/src/application/qgrid/qgrid.frame.test.ts +5 -0
  24. package/bundle/src/application/qgrid/qgrid.frame.ts +294 -0
  25. package/bundle/src/application/qgrid/qgrid.types.ts +134 -0
  26. package/bundle/src/application/qgrid/transcribe-stream.test.ts +165 -0
  27. package/bundle/src/application/qgrid/transcribe-stream.ts +381 -0
  28. package/bundle/src/application/queries.generated.ts +3 -0
  29. package/bundle/src/application/request-log/request-log.model.test.ts +4 -3
  30. package/bundle/src/application/request-log/request-log.model.ts +4 -3
  31. package/bundle/src/application/sonamu.generated.http +12 -0
  32. package/bundle/src/server-error-handler.ts +10 -7
  33. package/bundle/src/sonamu.config.ts +4 -0
  34. package/bundle/src/utils/providers/anthropic/anthropic-constants.test.ts +3 -0
  35. package/bundle/src/utils/providers/anthropic/anthropic-constants.ts +3 -1
  36. package/bundle/src/utils/providers/anthropic/anthropic-quota.ts +1 -1
  37. package/bundle/src/utils/providers/common/effort.test.ts +2 -0
  38. package/bundle/src/utils/providers/common/model-cost.test.ts +11 -0
  39. package/bundle/src/utils/providers/common/model-cost.ts +43 -5
  40. package/bundle/src/utils/providers/openai/openai-dispatcher.ts +15 -0
  41. package/bundle/src/utils/providers/openai/openai-realtime-protocol.ts +46 -5
  42. package/bundle/src/utils/providers/openai/openai-voice-client.test.ts +89 -2
  43. package/bundle/src/utils/providers/openai/openai-voice-client.ts +188 -0
  44. package/bundle/web-dist/client/assets/index-CtkfXtee.js +104 -0
  45. package/bundle/web-dist/client/assets/logs-C_U9lGtE.js +1 -0
  46. package/bundle/web-dist/client/assets/{monit-0qjGcPcD.js → monit-CNQyE4bk.js} +1 -1
  47. package/bundle/web-dist/client/assets/{routes-D53FyOOp.js → routes-72N6ogd2.js} +2 -2
  48. package/bundle/web-dist/client/assets/{settings-Cbz57odO.js → settings-DbwnDBrc.js} +1 -1
  49. package/bundle/web-dist/client/assets/{show-Boi25Rbi.js → show-BPkKGDnC.js} +2 -2
  50. package/bundle/web-dist/client/assets/tokens-2ig4rFfF.js +1 -0
  51. package/bundle/web-dist/client/assets/{use-oauth-login-flow-CjFv4NI0.js → use-oauth-login-flow-CvjEVH_T.js} +1 -1
  52. package/bundle/web-dist/client/assets/use-update-token-mutation-C8viUPmK.js +1 -0
  53. package/bundle/web-dist/client/assets/{voice-BDO8X2H0.js → voice-D2RSPjn9.js} +2 -2
  54. package/bundle/web-dist/client/index.html +1 -1
  55. package/bundle/web-dist/server/assets/{TimedPlayer-mpJpP5tQ.js → TimedPlayer-B9ds1sqM.js} +1 -1
  56. package/bundle/web-dist/server/assets/{logs-CFa_xamY.js → logs-JziKvWBp.js} +3 -3
  57. package/bundle/web-dist/server/assets/{monit-BF6osfj5.js → monit-CzjNOowb.js} +2 -2
  58. package/bundle/web-dist/server/assets/{plus-DwQFfeid.js → plus-BrRDgdaN.js} +1 -1
  59. package/bundle/web-dist/server/assets/{refresh-cw-Bj-Jxeb6.js → refresh-cw-wU5-wVTi.js} +1 -1
  60. package/bundle/web-dist/server/assets/{request-model-D_iYrudl.js → request-model-D07WSRKx.js} +1 -1
  61. package/bundle/web-dist/server/assets/{routes-B6be8sJP.js → routes-C1tDj0QN.js} +3 -3
  62. package/bundle/web-dist/server/assets/{services.generated-D0995hJr.js → services.generated-rlOX8J2n.js} +201 -0
  63. package/bundle/web-dist/server/assets/{settings-DAle7AgI.js → settings-DJQUI8bU.js} +3 -3
  64. package/bundle/web-dist/server/assets/{show-BTSdMDoM.js → show-BElTj6MG.js} +3 -3
  65. package/bundle/web-dist/server/assets/{tokens-Bc9flfLz.js → tokens-CRpUPv-5.js} +4 -4
  66. package/bundle/web-dist/server/assets/{use-oauth-login-flow-C7c0gCjf.js → use-oauth-login-flow-DLRPNhNE.js} +1 -1
  67. package/bundle/web-dist/server/assets/{use-update-token-mutation-DLJDGdxu.js → use-update-token-mutation-DJkct-j8.js} +1 -1
  68. package/bundle/web-dist/server/assets/{voice-CEQT57xZ.js → voice-BZBlBBpn.js} +4 -10
  69. package/bundle/web-dist/server/entry-server.generated.js +118 -26
  70. package/package.json +1 -1
  71. package/skills/qgrid/references/anthropic-claude-code-runtime.md +4 -3
  72. package/skills/qgrid/references/openai-codex-runtime.md +29 -10
  73. package/skills/qgrid/references/sonamu-api-web-flow.md +1 -1
  74. package/bundle/web-dist/client/assets/index-CiSsWsVT.js +0 -104
  75. package/bundle/web-dist/client/assets/logs-Bir9gDzp.js +0 -1
  76. package/bundle/web-dist/client/assets/tokens-BuK8BpAd.js +0 -1
  77. package/bundle/web-dist/client/assets/use-update-token-mutation-BKufO9oe.js +0 -1
@@ -35,7 +35,7 @@ export interface ModelCosts {
35
35
 
36
36
  // ── OpenAI ─────────────────────────────────────────────────────────
37
37
  //
38
- // Standard pricing verified 2026-09-23 (기존 모델 단가 변동 없음): https://developers.openai.com/api/docs/pricing
38
+ // Standard pricing re-verified 2026-11-23 for every OpenAI row below (변동 없음): https://developers.openai.com/api/docs/pricing
39
39
  // 신모델 출시마다 단가가 바뀌므로(5.2→5.4→5.5) 모델 추가 시 반드시 공식 페이지 재확인해야함
40
40
 
41
41
  // GPT-5.4에서 처음 도입된 long-context 할증 (5.2/5.3-codex는 해당 없음, 5.4-mini/nano는 공식 표에서 long-context 단가 없음)
@@ -55,6 +55,28 @@ type OpenAIModelSpec = ModelCosts & { maxEffort?: OpenAIEffort };
55
55
 
56
56
  const OPENAI_COSTS = new Map<string, OpenAIModelSpec>(
57
57
  Object.entries({
58
+ // GPT-6.2 Astra, Sol (2026-11-17 출시): Standard API pricing verified 2026-11-18.
59
+ // Astra 는 GPT-6 Astra 대비 input/output/cache write 20% 인하, cached input $0.40. Sol 은 GPT-6.1 Sol 과 같다.
60
+ // Codex 카탈로그(2026-11-18, client 0.169.0)는 둘 다 ultra 까지 허용하고 기본 effort 는 low,
61
+ // context_window 는 Astra 272K, Sol 500K 다.
62
+ // @see https://developers.openai.com/api/docs/models/gpt-6.2-astra
63
+ // @see https://developers.openai.com/api/docs/models/gpt-6.2-sol
64
+ "gpt-6.2-astra": {
65
+ maxEffort: "ultra",
66
+ inputTokens: 8,
67
+ outputTokens: 40,
68
+ cachedInputTokens: 0.4,
69
+ cacheCreationInputTokens: 10,
70
+ longContext: LONG_CONTEXT_272K,
71
+ },
72
+ "gpt-6.2-sol": {
73
+ maxEffort: "ultra",
74
+ inputTokens: 2,
75
+ outputTokens: 10,
76
+ cachedInputTokens: 0.1,
77
+ cacheCreationInputTokens: 2.5,
78
+ longContext: LONG_CONTEXT_272K,
79
+ },
58
80
  // GPT-6 Astra: Standard API-equivalent pricing, verified 2026-09-07.
59
81
  // Codex subscription catalog supports ultra; the public API lists only through max.
60
82
  // @see https://developers.openai.com/api/docs/models/gpt-6-astra
@@ -115,8 +137,8 @@ const OPENAI_COSTS = new Map<string, OpenAIModelSpec>(
115
137
  // @see https://developers.openai.com/api/docs/models/gpt-5.6-sol
116
138
  // @see https://developers.openai.com/api/docs/models/gpt-5.6-terra
117
139
  // @see https://developers.openai.com/api/docs/models/gpt-5.6-luna
118
- // Sol promotional rates are available at least through 2026-11-21.
119
- // No confirmed end date/replacement rate: recheck official pricing instead of auto-reverting.
140
+ // Sol's promotional pricing ends 2026-11-30 (pricing page footnote, checked 2026-11-23). The rate after
141
+ // that is not published: recheck official pricing in December instead of guessing a reversion.
120
142
  "gpt-5.6-sol": {
121
143
  maxEffort: "ultra",
122
144
  inputTokens: 4,
@@ -191,10 +213,14 @@ function anthropicCosts(
191
213
  return costs;
192
214
  }
193
215
 
194
- // 가격 출처: https://platform.claude.com/docs/en/about-claude/pricing (2026-10-08 확인. 2026-10-07 에 Sonnet 5.5
195
- // cache read 가 $0.20→$0.10(0.05x)으로 인하됐고, 그 외 기존 모델 단가는 변동 없음)
216
+ // 가격 출처: https://platform.claude.com/docs/en/about-claude/pricing (2026-11-23 재확인, 아래 행 모두 변동 없음.
217
+ // 2026-10-07 에 Sonnet 5.5 cache read 가 $0.20→$0.10(0.05x)으로 인하됐다)
196
218
  const ANTHROPIC_COSTS = new Map<string, ModelCosts>(
197
219
  Object.entries({
220
+ // Fable 5.2 (2026-11-09 출시): $8/$40. cache read 는 Fable 5.1 과 같은 0.025x($0.20) 특례,
221
+ // cache write 는 표준 배율($10/$16). 1M 컨텍스트, adaptive thinking 상시(끌 수 없음).
222
+ // @see https://platform.claude.com/docs/en/models/fable-5-2/overview
223
+ "claude-fable-5-2": anthropicCosts(8, 40, { cachedInputTokens: 0.2 }),
198
224
  // Fable 5.1 (2026-09-01 출시): input/output 은 Fable 5 와 같고 cache read 만 0.025x($0.25) 특례.
199
225
  // @see https://platform.claude.com/docs/en/models/fable-5-1/overview
200
226
  "claude-fable-5-1": anthropicCosts(10, 50, { cachedInputTokens: 0.25 }),
@@ -408,6 +434,8 @@ export function getModelCosts(model: string): ModelCosts {
408
434
  // https://developers.openai.com/api/docs/pricing
409
435
  const OPENAI_FAST_MULTIPLIERS = new Map<string, number>(
410
436
  Object.entries({
437
+ "gpt-6.2-astra": 2,
438
+ "gpt-6.2-sol": 2,
411
439
  "gpt-6-astra": 2,
412
440
  "gpt-6.1-sol": 2,
413
441
  "gpt-6.1-terra": 2,
@@ -419,6 +447,11 @@ const OPENAI_FAST_MULTIPLIERS = new Map<string, number>(
419
447
  }),
420
448
  );
421
449
 
450
+ /** Rate multiplier for serviceTier "fast"; undefined when the model has no fast tier. */
451
+ export function openaiFastMultiplier(model: string): number | undefined {
452
+ return OPENAI_FAST_MULTIPLIERS.get(model.split("/").pop() ?? model);
453
+ }
454
+
422
455
  export function calculateCostUsd(
423
456
  model: string,
424
457
  usage: {
@@ -554,6 +587,11 @@ export function openaiDecisionCost(usage: {
554
587
  );
555
588
  }
556
589
 
590
+ /** USD per minute of audio for a transcription route such as "openai/gpt-transcribe". */
591
+ export function sttUsdPerMinute(route: string): number | undefined {
592
+ return STT_USD_PER_MINUTE.get(route);
593
+ }
594
+
557
595
  /** Transcription by audio length; unknown models or a missing duration stay unpriced. */
558
596
  export function sttCost(route: string, durationSec: number | undefined): VoiceCost | undefined {
559
597
  const perMinute = STT_USD_PER_MINUTE.get(route);
@@ -24,6 +24,8 @@ import {
24
24
  type OpenAISpeechResult,
25
25
  type OpenAITranscribeRequest,
26
26
  type OpenAITranscription,
27
+ type OpenAITranscriptionStream,
28
+ type OpenAITranscriptionStreamRequest,
27
29
  OpenAIVoiceClient,
28
30
  } from "./openai-voice-client";
29
31
 
@@ -162,6 +164,19 @@ export class OpenAIDispatcher implements ProviderDispatcher {
162
164
  );
163
165
  }
164
166
 
167
+ /** Opens a long-lived transcription stream; the token is chosen (and a 401 refreshed) at open. */
168
+ async startTranscriptionStream(
169
+ request: OpenAITranscriptionStreamRequest & MediaTokenSelection,
170
+ ): Promise<MediaDispatchResult<OpenAITranscriptionStream>> {
171
+ const { preferredTokenId, requirePreferredToken, ...streamRequest } = request;
172
+
173
+ return this.pool.runWithToken(
174
+ { preferredTokenId, requirePreferredToken },
175
+ request.signal,
176
+ (credentials) => this.voiceClient.openTranscriptionStream(credentials, streamRequest),
177
+ );
178
+ }
179
+
165
180
  async startLive(
166
181
  request: OpenAILiveCallRequest & MediaTokenSelection,
167
182
  ): Promise<MediaDispatchResult<OpenAILiveCall>> {
@@ -98,10 +98,13 @@ export const OPENAI_LIVE_WS_URL = "wss://api.openai.com/v1/live" as const;
98
98
  export const OPENAI_LIVE_MODEL = "gpt-live-1";
99
99
 
100
100
  /**
101
- * Sent as session.model, as Codex does (DEFAULT_FRAMELESS_REALTIME_MODEL). The backend ignores the
102
- * field on this route: made-up names opened a session too (2026-11-10).
101
+ * Sent as session.model, as Codex does (DEFAULT_FRAMELESS_REALTIME_MODEL, gpt-live-1.1-codex since
102
+ * openai/codex b05266d6, 2026-11-13). The backend ignores the field on this route: made-up names,
103
+ * gpt-realtime-2.1 and an empty string all opened sessions that held the same conversation, and no
104
+ * event names the serving model (backend_model_usage stays empty) (2026-11-10, rechecked 2026-11-23).
105
+ * The served model is presumably Codex's current default, but it cannot be confirmed.
103
106
  */
104
- const OPENAI_LIVE_WIRE_MODEL = "gpt-live-1-codex";
107
+ const OPENAI_LIVE_WIRE_MODEL = "gpt-live-1.1-codex";
105
108
 
106
109
  export const OPENAI_LIVE_DEFAULT_VOICE = "cove";
107
110
 
@@ -143,8 +146,18 @@ export function buildLiveSession(options: {
143
146
  delegation: { type: "client" },
144
147
  };
145
148
 
146
- if (options.history?.length) {
147
- session.initial_items = options.history.map(({ role, text }) => ({
149
+ // The ChatGPT backend does not apply session.instructions to GPT-Live: on 2026-11-23 a session with
150
+ // only instructions answered as the default assistant and said the setting had not reached it,
151
+ // while the same text as a developer initial item was followed (persona, English-only reply to
152
+ // Korean speech). Codex sends instructions the same way, so the field stays and the text also
153
+ // leads the initial items.
154
+ const items: LiveHistoryMessage[] = [
155
+ ...(options.instructions ? [{ role: "developer" as const, text: options.instructions }] : []),
156
+ ...(options.history ?? []),
157
+ ];
158
+
159
+ if (items.length) {
160
+ session.initial_items = items.map(({ role, text }) => ({
148
161
  type: "message",
149
162
  role,
150
163
  content: [{ type: role === "assistant" ? "output_text" : "input_text", text }],
@@ -445,6 +458,34 @@ export const transcriptionCompletedEvent = z.looseObject({
445
458
  transcript: z.string(),
446
459
  });
447
460
 
461
+ /**
462
+ * Incremental text for the uncommitted buffer. gpt-live-transcribe streams these while audio is
463
+ * still arriving (first text about 1.3 s after speech starts, subscription probe 2026-11-18);
464
+ * gpt-transcribe sends them all at once after the commit.
465
+ */
466
+ export const transcriptionDeltaEvent = z.looseObject({
467
+ type: z.literal("conversation.item.input_audio_transcription.delta"),
468
+ item_id: z.string(),
469
+ delta: z.string(),
470
+ });
471
+
472
+ /** Acknowledges a commit; item_id names the buffer that the commit ended. */
473
+ export const audioBufferCommittedEvent = z.looseObject({
474
+ type: z.literal("input_audio_buffer.committed"),
475
+ item_id: z.string(),
476
+ });
477
+
478
+ /** item_id ties a completed transcript to the deltas that preceded it. */
479
+ export const transcriptionCompletedItemEvent = transcriptionCompletedEvent.extend({
480
+ item_id: z.string(),
481
+ });
482
+
483
+ export const transcriptionFailedItemEvent = z.looseObject({
484
+ type: z.literal("conversation.item.input_audio_transcription.failed"),
485
+ item_id: z.string(),
486
+ error: z.looseObject({ message: z.string().optional(), code: z.string().nullish() }).optional(),
487
+ });
488
+
448
489
  export const transcriptionFailedEvent = z.looseObject({
449
490
  type: z.literal("conversation.item.input_audio_transcription.failed"),
450
491
  error: z.looseObject({ message: z.string().optional(), code: z.string().nullish() }).optional(),
@@ -625,14 +625,23 @@ describe("OpenAIVoiceClient.createLiveCall", () => {
625
625
  expect(JSON.parse(String(init.body))).toEqual({
626
626
  sdp: "v=0\r\noffer",
627
627
  session: {
628
- model: "gpt-live-1-codex",
628
+ model: "gpt-live-1.1-codex",
629
629
  instructions: "Be brief.",
630
630
  audio: { output: { voice: "hanul" } },
631
631
  delegation: { type: "client" },
632
+ // The backend ignores session.instructions, so the same text leads the initial items
633
+ initial_items: [
634
+ { type: "message", role: "developer", content: [{ type: "input_text", text: "Be brief." }] },
635
+ ],
632
636
  },
633
637
  });
634
638
 
635
- expect(buildLiveSession({ voice: "cove" })).toMatchObject({ instructions: "" });
639
+ expect(buildLiveSession({ voice: "cove" })).toEqual({
640
+ model: "gpt-live-1.1-codex",
641
+ instructions: "",
642
+ audio: { output: { voice: "cove" } },
643
+ delegation: { type: "client" },
644
+ });
636
645
  expect(call).toMatchObject({ sdp: "v=0", callId: "rtc_live" });
637
646
  expect(call.quotaHeaders.get("x-codex-primary-used-percent")).toBe("88");
638
647
  expect(ws.calls[0]?.url).toBe(`${OPENAI_LIVE_WS_URL}/rtc_live`);
@@ -722,6 +731,7 @@ describe("OpenAIVoiceClient.createLiveCall", () => {
722
731
 
723
732
  await client.createLiveCall(credentials, {
724
733
  sdp: "v=0",
734
+ instructions: "Speak English.",
725
735
  history: [
726
736
  { role: "developer", text: "Stay in character as Kuma." },
727
737
  { role: "user", text: "My name is Dongseon." },
@@ -731,6 +741,8 @@ describe("OpenAIVoiceClient.createLiveCall", () => {
731
741
 
732
742
  const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
733
743
  expect(JSON.parse(String(init.body)).session.initial_items).toEqual([
744
+ // The instructions come first, then the caller's history in order
745
+ { type: "message", role: "developer", content: [{ type: "input_text", text: "Speak English." }] },
734
746
  { type: "message", role: "developer", content: [{ type: "input_text", text: "Stay in character as Kuma." }] },
735
747
  { type: "message", role: "user", content: [{ type: "input_text", text: "My name is Dongseon." }] },
736
748
  { type: "message", role: "assistant", content: [{ type: "output_text", text: "Nice to meet you!" }] },
@@ -789,3 +801,78 @@ describe("OpenAIVoiceClient.createLiveCall", () => {
789
801
  expect(fetchMock).not.toHaveBeenCalled();
790
802
  });
791
803
  });
804
+
805
+ describe("OpenAIVoiceClient.openTranscriptionStream", () => {
806
+ it("opens the direct socket with a manual-commit session and forwards stream events", async () => {
807
+ const ws = mockedWebSocket();
808
+ const client = new OpenAIVoiceClient({ webSocketFactory: ws.factory });
809
+ const events: unknown[] = [];
810
+
811
+ const opening = client.openTranscriptionStream(credentials, {
812
+ language: "ko",
813
+ onEvent: (event) => events.push(event),
814
+ });
815
+
816
+ await tick();
817
+ const socket = ws.sockets[0]!;
818
+ expect(ws.calls[0]!.url).toBe(`${OPENAI_REALTIME_WS_URL}?intent=transcription`);
819
+ expect(ws.calls[0]!.headers.originator).toBe(CODEX_CLI_ORIGINATOR);
820
+ socket.emit("open");
821
+ const stream = await opening;
822
+
823
+ expect(stream.model).toBe("gpt-live-transcribe");
824
+ expect(socket.sentEvents()[0]).toEqual({
825
+ type: "session.update",
826
+ session: buildTranscriptionSession({ model: "gpt-live-transcribe", language: "ko", manualCommit: true }),
827
+ });
828
+
829
+ await stream.append(new Uint8Array([1, 0, 2, 0]));
830
+ await stream.commit();
831
+ await stream.clear();
832
+ expect(socket.sentEvents().slice(1)).toEqual([
833
+ { type: "input_audio_buffer.append", audio: Buffer.from([1, 0, 2, 0]).toString("base64") },
834
+ { type: "input_audio_buffer.commit" },
835
+ { type: "input_audio_buffer.clear" },
836
+ ]);
837
+
838
+ socket.message({ type: "conversation.item.input_audio_transcription.delta", item_id: "i1", delta: "안녕" });
839
+ socket.message({ type: "input_audio_buffer.committed", item_id: "i1" });
840
+ socket.message({ type: "conversation.item.input_audio_transcription.completed", item_id: "i1", transcript: "안녕하세요." });
841
+ socket.message({ type: "error", error: { code: "input_audio_buffer_commit_empty", message: "empty" } });
842
+ socket.emit("close", 1000, Buffer.from("done"));
843
+ await tick();
844
+
845
+ expect(events).toEqual([
846
+ { type: "delta", itemId: "i1", text: "안녕" },
847
+ { type: "committed", itemId: "i1" },
848
+ { type: "completed", itemId: "i1", text: "안녕하세요." },
849
+ { type: "error", message: "empty", code: "input_audio_buffer_commit_empty" },
850
+ { type: "closed", error: undefined },
851
+ ]);
852
+ });
853
+
854
+ it("reports an abnormal close as the closing error", async () => {
855
+ const ws = mockedWebSocket();
856
+ const client = new OpenAIVoiceClient({ webSocketFactory: ws.factory });
857
+ const events: Array<{ type: string; error?: Error }> = [];
858
+ const opening = client.openTranscriptionStream(credentials, { onEvent: (e) => events.push(e) });
859
+ await tick();
860
+ ws.sockets[0]!.emit("open");
861
+ await opening;
862
+ ws.sockets[0]!.emit("close", 1006, Buffer.from(""));
863
+ await tick();
864
+
865
+ expect(events.at(-1)?.type).toBe("closed");
866
+ expect(events.at(-1)?.error?.message).toMatch(/1006/);
867
+ });
868
+
869
+ it("rejects an unknown model before opening a socket", async () => {
870
+ const ws = mockedWebSocket();
871
+ const client = new OpenAIVoiceClient({ webSocketFactory: ws.factory });
872
+
873
+ await expect(
874
+ client.openTranscriptionStream(credentials, { model: "gpt-nope", onEvent: () => {} }),
875
+ ).rejects.toBeInstanceOf(OpenAIVoiceInputError);
876
+ expect(ws.sockets).toHaveLength(0);
877
+ });
878
+ });
@@ -33,11 +33,16 @@ import {
33
33
  OPENAI_REALTIME_SAMPLE_RATE,
34
34
  OPENAI_REALTIME_SYNTHETIC_SDP,
35
35
  OPENAI_REALTIME_WS_URL,
36
+ OPENAI_TRANSCRIPTION_MODELS,
36
37
  OPENAI_TRANSCRIPTION_MODELS_WITHOUT_PROMPT,
37
38
  type OpenAIRealtimeCredentials,
38
39
  type OpenAIRealtimeHeaders,
40
+ audioBufferCommittedEvent,
39
41
  outputAudioDeltaEvent,
40
42
  outputAudioTranscriptDoneEvent,
43
+ transcriptionCompletedItemEvent,
44
+ transcriptionDeltaEvent,
45
+ transcriptionFailedItemEvent,
41
46
  prepareRealtimeInput,
42
47
  realtimeErrorEvent,
43
48
  realtimeServerEvent,
@@ -101,6 +106,43 @@ export interface OpenAIVoiceClientOptions {
101
106
  liveWatchLimitMs?: number;
102
107
  }
103
108
 
109
+ /** Model for streaming transcription when the caller names none: the only one that streams text. */
110
+ export const OPENAI_STREAM_DEFAULT_TRANSCRIPTION_MODEL = "gpt-live-transcribe";
111
+
112
+ /** Bounds the socket handshake and session.update of a streaming transcription. */
113
+ export const OPENAI_STREAM_OPEN_TIMEOUT_MS = 15_000;
114
+
115
+ export type OpenAITranscriptionStreamEvent =
116
+ | { type: "delta"; itemId: string; text: string }
117
+ /** The commit that ended item `itemId` was accepted; commits are acknowledged in order. */
118
+ | { type: "committed"; itemId: string }
119
+ | { type: "completed"; itemId: string; text: string }
120
+ | { type: "failed"; itemId: string; message: string }
121
+ /** A server error event; the socket stays open (e.g. committing an empty buffer). */
122
+ | { type: "error"; message: string; code?: string }
123
+ /** The socket ended. `error` is set unless it closed normally. Always the last event. */
124
+ | { type: "closed"; error?: Error };
125
+
126
+ export interface OpenAITranscriptionStreamRequest {
127
+ model?: string;
128
+ language?: string;
129
+ prompt?: string;
130
+ onEvent: (event: OpenAITranscriptionStreamEvent) => void;
131
+ /** Bounds the handshake and, once open, closes the stream when aborted. */
132
+ signal?: AbortSignal;
133
+ }
134
+
135
+ export interface OpenAITranscriptionStream {
136
+ readonly model: string;
137
+ /** Mono PCM16 at 24 kHz. */
138
+ append(pcm: Uint8Array): Promise<void>;
139
+ /** Ends the current item; its completed transcript follows. */
140
+ commit(): Promise<void>;
141
+ /** Drops the uncommitted buffer without transcribing it. */
142
+ clear(): Promise<void>;
143
+ close(): void;
144
+ }
145
+
104
146
  export interface OpenAITranscribeRequest {
105
147
  audio: Uint8Array;
106
148
  mediaType: string;
@@ -574,6 +616,75 @@ export class OpenAIVoiceClient {
574
616
  }
575
617
  }
576
618
 
619
+ /**
620
+ * A long-lived transcription session on the direct socket. The /calls path cannot host one: a
621
+ * call with no RTP peer is torn down about 30 s after creation. The direct socket stayed open for
622
+ * a 6 min 40 s stream with 20 commits (subscription probe 2026-11-18). Commits are manual
623
+ * because gpt-live-transcribe rejects server VAD and transcribes only about the first 30 s of a
624
+ * single committed buffer.
625
+ */
626
+ async openTranscriptionStream(
627
+ credentials: OpenAIRealtimeCredentials,
628
+ request: OpenAITranscriptionStreamRequest,
629
+ ): Promise<OpenAITranscriptionStream> {
630
+ const model = request.model ?? OPENAI_STREAM_DEFAULT_TRANSCRIPTION_MODEL;
631
+
632
+ if (!OPENAI_TRANSCRIPTION_MODELS.some((known) => known === model))
633
+ throw new OpenAIVoiceInputError(`unsupported transcription model "${model}"`);
634
+
635
+ if (request.prompt !== undefined && OPENAI_TRANSCRIPTION_MODELS_WITHOUT_PROMPT.has(model))
636
+ throw new OpenAIVoiceInputError(`${model} does not accept a prompt`);
637
+ const correlation = { threadId: crypto.randomUUID(), sessionId: crypto.randomUUID() };
638
+ const headers = buildOpenAIRealtimeHeaders(credentials, correlation);
639
+
640
+ const session = buildTranscriptionSession({
641
+ model,
642
+ language: request.language,
643
+ prompt: request.prompt,
644
+ manualCommit: true,
645
+ });
646
+
647
+ const lifetime = new AbortController();
648
+ const onCallerAbort = () => lifetime.abort(request.signal?.reason);
649
+
650
+ if (request.signal?.aborted) throw abortError(request.signal);
651
+ request.signal?.addEventListener("abort", onCallerAbort, { once: true });
652
+ const socket = this.webSocketFactory(`${this.realtimeWsUrl}?intent=transcription`, { headers });
653
+ const records = socketRecords(socket, lifetime.signal);
654
+ let openTimer: NodeJS.Timeout | undefined;
655
+
656
+ try {
657
+ const timedOut = new Promise<never>((_, reject) => {
658
+ openTimer = setTimeout(() => {
659
+ socket.terminate();
660
+ reject(new OpenAIProtocolError("realtime socket open timed out", "realtime_timeout"));
661
+ }, OPENAI_STREAM_OPEN_TIMEOUT_MS);
662
+ });
663
+
664
+ await Promise.race([this.awaitOpen(records.next), timedOut]);
665
+ await sendJson(socket, sessionUpdateEvent(session));
666
+ } catch (error) {
667
+ socket.terminate();
668
+ records.cleanup();
669
+ request.signal?.removeEventListener("abort", onCallerAbort);
670
+ throw error;
671
+ } finally {
672
+ clearTimeout(openTimer);
673
+ }
674
+
675
+ void pumpTranscriptionStream(records, request.onEvent).finally(() =>
676
+ request.signal?.removeEventListener("abort", onCallerAbort),
677
+ );
678
+
679
+ return {
680
+ model,
681
+ append: (pcm) => sendJson(socket, audioAppendEvent(Buffer.from(pcm).toString("base64"))),
682
+ commit: () => sendJson(socket, audioCommitEvent()),
683
+ clear: () => sendJson(socket, { type: "input_audio_buffer.clear" }),
684
+ close: () => socket.close(1000, "done"),
685
+ };
686
+ }
687
+
577
688
  /** session.update → append PCM → commit → await the completed transcript. */
578
689
  private async runTranscriptionSocket(
579
690
  url: string,
@@ -1016,3 +1127,80 @@ export function isSidebandTeardownError(error: Error): boolean {
1016
1127
 
1017
1128
  /** Event schema export for tests that replay captured server traffic. */
1018
1129
  export { realtimeServerEvent };
1130
+
1131
+ /** Forwards stream events until the socket ends, then reports `closed` exactly once. */
1132
+ async function pumpTranscriptionStream(
1133
+ records: ReturnType<typeof socketRecords>,
1134
+ onEvent: (event: OpenAITranscriptionStreamEvent) => void,
1135
+ ): Promise<void> {
1136
+ let error: Error | undefined;
1137
+
1138
+ try {
1139
+ for (;;) {
1140
+ const record = await records.next();
1141
+
1142
+ if (record.kind === "error") {
1143
+ error = record.error;
1144
+ break;
1145
+ }
1146
+
1147
+ if (record.kind === "close") {
1148
+ if (record.code !== 1000)
1149
+ error = new OpenAIProtocolError(
1150
+ `realtime socket closed (${record.code}${record.reason ? `: ${record.reason}` : ""})`,
1151
+ );
1152
+ break;
1153
+ }
1154
+
1155
+ if (record.kind === "rejected") {
1156
+ error = new OpenAIProtocolError("realtime socket rejected", undefined, record.status);
1157
+ break;
1158
+ }
1159
+
1160
+ if (record.kind !== "event") continue;
1161
+ const serverError = serverErrorFromEvent(record.event);
1162
+
1163
+ if (serverError) {
1164
+ onEvent({ type: "error", message: serverError.message, code: serverError.code });
1165
+ continue;
1166
+ }
1167
+
1168
+ const delta = transcriptionDeltaEvent.safeParse(record.event);
1169
+
1170
+ if (delta.success) {
1171
+ onEvent({ type: "delta", itemId: delta.data.item_id, text: delta.data.delta });
1172
+ continue;
1173
+ }
1174
+
1175
+ const committed = audioBufferCommittedEvent.safeParse(record.event);
1176
+
1177
+ if (committed.success) {
1178
+ onEvent({ type: "committed", itemId: committed.data.item_id });
1179
+ continue;
1180
+ }
1181
+
1182
+ const completed = transcriptionCompletedItemEvent.safeParse(record.event);
1183
+
1184
+ if (completed.success) {
1185
+ onEvent({
1186
+ type: "completed",
1187
+ itemId: completed.data.item_id,
1188
+ text: completed.data.transcript,
1189
+ });
1190
+ continue;
1191
+ }
1192
+
1193
+ const failed = transcriptionFailedItemEvent.safeParse(record.event);
1194
+
1195
+ if (failed.success)
1196
+ onEvent({
1197
+ type: "failed",
1198
+ itemId: failed.data.item_id,
1199
+ message: failed.data.error?.message ?? "transcription failed",
1200
+ });
1201
+ }
1202
+ } finally {
1203
+ records.cleanup();
1204
+ onEvent({ type: "closed", error });
1205
+ }
1206
+ }