@cartanova/qgrid-cli 2.19.0 → 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 (74) hide show
  1. package/bundle/dist/application/qgrid/qgrid-response-format.js +14 -5
  2. package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +12 -4
  3. package/bundle/dist/application/qgrid/qgrid.dispatcher.js +3 -1
  4. package/bundle/dist/application/qgrid/qgrid.frame.js +215 -6
  5. package/bundle/dist/application/qgrid/qgrid.types.js +65 -2
  6. package/bundle/dist/application/request-log/request-log.model.js +11 -1
  7. package/bundle/dist/application/sonamu.generated.js +5 -3
  8. package/bundle/dist/i18n/sd.generated.js +3 -2
  9. package/bundle/dist/utils/providers/common/model-cost.js +8 -2
  10. package/bundle/dist/utils/providers/openai/openai-dispatcher.js +18 -1
  11. package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +112 -2
  12. package/bundle/dist/utils/providers/openai/openai-voice-client.js +183 -6
  13. package/bundle/src/application/qgrid/qgrid-response-format.test.ts +14 -4
  14. package/bundle/src/application/qgrid/qgrid-response-format.ts +18 -2
  15. package/bundle/src/application/qgrid/qgrid-run-lifecycle.test.ts +36 -1
  16. package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +25 -3
  17. package/bundle/src/application/qgrid/qgrid.dispatcher.test.ts +17 -0
  18. package/bundle/src/application/qgrid/qgrid.dispatcher.ts +8 -0
  19. package/bundle/src/application/qgrid/qgrid.frame.test.ts +187 -0
  20. package/bundle/src/application/qgrid/qgrid.frame.ts +287 -3
  21. package/bundle/src/application/qgrid/qgrid.types.ts +103 -0
  22. package/bundle/src/application/request-log/request-log.entity.json +3 -2
  23. package/bundle/src/application/request-log/request-log.model.test.ts +19 -0
  24. package/bundle/src/application/request-log/request-log.model.ts +20 -1
  25. package/bundle/src/application/sonamu.generated.http +22 -0
  26. package/bundle/src/application/sonamu.generated.ts +2 -1
  27. package/bundle/src/i18n/sd.generated.ts +2 -1
  28. package/bundle/src/utils/providers/common/model-cost.ts +15 -0
  29. package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +16 -0
  30. package/bundle/src/utils/providers/openai/openai-dispatcher.ts +26 -0
  31. package/bundle/src/utils/providers/openai/openai-realtime-protocol.ts +125 -0
  32. package/bundle/src/utils/providers/openai/openai-voice-client.test.ts +184 -0
  33. package/bundle/src/utils/providers/openai/openai-voice-client.ts +277 -5
  34. package/bundle/web-dist/client/assets/index-BeceW0U9.js +104 -0
  35. package/bundle/web-dist/client/assets/index-hUNCpC11.css +1 -0
  36. package/bundle/web-dist/client/assets/logs-jMJnTwZn.js +1 -0
  37. package/bundle/web-dist/client/assets/monit-B1xRKwua.js +1 -0
  38. package/bundle/web-dist/client/assets/{routes-Dw227enb.js → routes-fsiyivXx.js} +2 -2
  39. package/bundle/web-dist/client/assets/{settings-BXmAToY1.js → settings-CHX44roa.js} +1 -1
  40. package/bundle/web-dist/client/assets/show-BDMwKfEY.js +2 -0
  41. package/bundle/web-dist/client/assets/{tokens-D8L8AC4v.js → tokens-zGl36OfE.js} +1 -1
  42. package/bundle/web-dist/client/assets/{use-oauth-login-flow-BcEUkszt.js → use-oauth-login-flow-DYWj4645.js} +1 -1
  43. package/bundle/web-dist/client/assets/use-update-token-mutation-BRXXrEf5.js +1 -0
  44. package/bundle/web-dist/client/assets/{vendor-tanstack-6B86itGS.js → vendor-tanstack-DMgmqjm4.js} +1 -1
  45. package/bundle/web-dist/client/assets/voice-Bwcp-KAu.js +1 -0
  46. package/bundle/web-dist/client/index.html +3 -3
  47. package/bundle/web-dist/server/assets/{TimedPlayer-DAwjkP4z.js → TimedPlayer-COqaTQSl.js} +1 -1
  48. package/bundle/web-dist/server/assets/{logs-BmBpBe-j.js → logs-HPho1SkC.js} +5 -6
  49. package/bundle/web-dist/server/assets/{monit-Db1WrIls.js → monit-Bl2kSkSF.js} +3 -3
  50. package/bundle/web-dist/server/assets/{plus-CW9y_K7l.js → plus-CQ8AHpih.js} +1 -1
  51. package/bundle/web-dist/server/assets/{refresh-cw-CRgcH5bT.js → refresh-cw-pYSuvt4c.js} +1 -1
  52. package/bundle/web-dist/server/assets/{request-model-DRF7hmJC.js → request-model-ZulJMbGm.js} +1 -1
  53. package/bundle/web-dist/server/assets/{routes-CARZj7or.js → routes-BNHCX4VI.js} +4 -4
  54. package/bundle/web-dist/server/assets/{services.generated-B6QpnL_N.js → services.generated-C3b31_vt.js} +23209 -22930
  55. package/bundle/web-dist/server/assets/{settings-B4jdpP5N.js → settings-NJUyaSrJ.js} +4 -4
  56. package/bundle/web-dist/server/assets/{show-CnLDFCtW.js → show-Dz5QGL7l.js} +8 -9
  57. package/bundle/web-dist/server/assets/{tokens-TDQguTdh.js → tokens-BPQvjIGq.js} +5 -5
  58. package/bundle/web-dist/server/assets/{use-oauth-login-flow-du7pOh_H.js → use-oauth-login-flow-CCc8LEmn.js} +1 -1
  59. package/bundle/web-dist/server/assets/{use-update-token-mutation-DA6HiiWS.js → use-update-token-mutation-Ba-sEhq1.js} +1 -1
  60. package/bundle/web-dist/server/assets/{voice-BvAl-vTr.js → voice-V-E3tRqD.js} +289 -22
  61. package/bundle/web-dist/server/entry-server.generated.js +5581 -71
  62. package/package.json +1 -1
  63. package/skills/qgrid/references/decision-rationale.md +5 -1
  64. package/skills/qgrid/references/openai-codex-runtime.md +15 -0
  65. package/skills/qgrid/references/request-log-run-lifecycle.md +3 -2
  66. package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
  67. package/bundle/web-dist/client/assets/index-Co8uAhSV.css +0 -1
  68. package/bundle/web-dist/client/assets/index-DYYtV8Qx.js +0 -104
  69. package/bundle/web-dist/client/assets/logs-CbDtQif1.js +0 -1
  70. package/bundle/web-dist/client/assets/monit-DtW8o_yF.js +0 -1
  71. package/bundle/web-dist/client/assets/show-5qj6wFgp.js +0 -2
  72. package/bundle/web-dist/client/assets/use-update-token-mutation-Ca0n_WnM.js +0 -1
  73. package/bundle/web-dist/client/assets/voice-D-c1Eyp3.js +0 -1
  74. package/bundle/web-dist/server/assets/link-DrdV092C.js +0 -4919
@@ -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 {
@@ -116,6 +124,7 @@ import {
116
124
  RefreshFailedError,
117
125
  } from "./oauth";
118
126
  import { CODEX_IMAGE_GENERATION_MODEL } from "./qgrid-image-generation";
127
+ import { imagePlaceholderForLog } from "./qgrid-response-format";
119
128
  import {
120
129
  afterQuery,
121
130
  beforeQuery,
@@ -136,6 +145,8 @@ import {
136
145
  type FinishRunInput,
137
146
  GenerateImagesInput,
138
147
  type GenerateImagesOutput,
148
+ LiveCallInput,
149
+ type LiveCallOutput,
139
150
  SpeakInput,
140
151
  type SpeakOutput,
141
152
  TranscribeInput,
@@ -514,13 +525,14 @@ const inflightAnthropicRefresh = new Map<number, Promise<string>>();
514
525
 
515
526
  const mediaLogger = getLogger(["qgrid", "media"]);
516
527
 
517
- type MediaKind = "image" | "video" | "stt" | "tts";
528
+ type MediaKind = "image" | "video" | "stt" | "tts" | "live";
518
529
 
519
530
  const MEDIA_TOOL_NAMES: Record<MediaKind, string> = {
520
531
  image: "image_generation",
521
532
  video: "video_generation",
522
533
  stt: "transcription",
523
534
  tts: "speech",
535
+ live: "live_session",
524
536
  };
525
537
 
526
538
  function grokNotReady(): Error {
@@ -1309,6 +1321,177 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
1309
1321
  });
1310
1322
  }
1311
1323
 
1324
+ const OPENAI_LIVE_ROUTE = `openai/${OPENAI_LIVE_MODEL}`;
1325
+
1326
+ /** Session time as m:ss. */
1327
+ function sessionClock(ms: number): string {
1328
+ const seconds = Math.floor(ms / 1000);
1329
+
1330
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
1331
+ }
1332
+
1333
+ /** The conversation as the run's response: each finished turn with its session time. */
1334
+ function liveTranscript(turns: readonly OpenAILiveTurn[]): string {
1335
+ return turns
1336
+ .map((turn) => `**${turn.role}** ${sessionClock(turn.startMs)} \n${turn.transcript.trim()}`)
1337
+ .join("\n\n");
1338
+ }
1339
+
1340
+ /** Rewrites the running row's conversation after each turn, in order, so the log fills live. */
1341
+ function liveProgressRecorder(requestLogId: number): (turns: readonly OpenAILiveTurn[]) => void {
1342
+ let pending = Promise.resolve();
1343
+
1344
+ return (turns) => {
1345
+ const response = liveTranscript(turns);
1346
+
1347
+ pending = pending.then(async () => {
1348
+ try {
1349
+ await RequestLogModel.recordRunProgress(requestLogId, { response });
1350
+ } catch (e) {
1351
+ mediaLogger.warn(`live progress failed: ${e instanceof Error ? e.message : String(e)}`);
1352
+ }
1353
+ });
1354
+ };
1355
+ }
1356
+
1357
+ const LIVE_DELEGATION_DEFAULTS = { model: "openai/gpt-6-luna", effort: "low" } as const;
1358
+
1359
+ // The voice keeps talking while it waits; a stuck backend still has to end.
1360
+ const LIVE_DELEGATION_TIMEOUT_MS = 90_000;
1361
+
1362
+ const LIVE_DELEGATION_SYSTEM =
1363
+ "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.";
1364
+
1365
+ type LiveDelegationOptions = { model: string; effort: string; webSearch: boolean };
1366
+
1367
+ /** The backend sees the conversation so far, as Codex's agent has it in its own thread. */
1368
+ function delegationPrompt(turns: readonly OpenAILiveTurn[], request: string): string {
1369
+ const conversation = turns.map((turn) => `${turn.role}: ${turn.transcript.trim()}`).join("\n");
1370
+
1371
+ return [
1372
+ conversation && `Conversation so far:\n${conversation}`,
1373
+ `Request from the voice assistant:\n${request}`,
1374
+ ]
1375
+ .filter(Boolean)
1376
+ .join("\n\n");
1377
+ }
1378
+
1379
+ /**
1380
+ * Answers the voice model's delegations with a qgrid query on the chosen model and, when the run
1381
+ * is logged, records each as a `delegation` tool step beside the session step.
1382
+ */
1383
+ function liveDelegationHandler(
1384
+ options: LiveDelegationOptions,
1385
+ instructions: string | undefined,
1386
+ turnsSoFar: () => readonly OpenAILiveTurn[],
1387
+ log: { requestLogId: number; costs: { delegationUsd: number } } | undefined,
1388
+ ): (delegation: OpenAILiveDelegation) => Promise<string> {
1389
+ let callIndex = 0;
1390
+
1391
+ return async ({ itemId, text }) => {
1392
+ const startedAt = Date.now();
1393
+ let reply: string;
1394
+ let outcome: Pick<RequestLogStepFields, "tool_result" | "error">;
1395
+
1396
+ try {
1397
+ const result = await QgridDispatcher.query({
1398
+ prompt: delegationPrompt(turnsSoFar(), text),
1399
+ system: [
1400
+ LIVE_DELEGATION_SYSTEM,
1401
+ instructions && `The voice assistant's instructions:\n${instructions}`,
1402
+ ]
1403
+ .filter(Boolean)
1404
+ .join("\n\n"),
1405
+ model: options.model,
1406
+ effort: options.effort,
1407
+ webSearch: options.webSearch,
1408
+ timeout: LIVE_DELEGATION_TIMEOUT_MS,
1409
+ });
1410
+
1411
+ reply = result.text;
1412
+
1413
+ if (log) log.costs.delegationUsd += result.costUsd;
1414
+
1415
+ outcome = {
1416
+ tool_result: JSON.stringify({
1417
+ answer: result.text,
1418
+ model: result.model,
1419
+ tokenName: result.tokenName,
1420
+ usage: result.usage,
1421
+ costUsd: result.costUsd,
1422
+ }),
1423
+ };
1424
+ } catch (e) {
1425
+ const message = e instanceof Error ? e.message : String(e);
1426
+ // The voice adapts this to the conversation instead of stalling on an unanswered request.
1427
+ reply = `The backend could not answer (${message}). Tell the user briefly that you could not get it.`;
1428
+ outcome = { error: message };
1429
+ }
1430
+
1431
+ if (log) {
1432
+ callIndex += 1;
1433
+
1434
+ const step: RequestLogStepFields = {
1435
+ step_index: 0,
1436
+ type: "tool_call",
1437
+ tool_call_index: callIndex,
1438
+ tool_call_id: `delegation:${itemId}`,
1439
+ tool_name: "delegation",
1440
+ tool_args: JSON.stringify({ request: text, ...options }),
1441
+ tool_duration_ms: Date.now() - startedAt,
1442
+ ...outcome,
1443
+ };
1444
+
1445
+ void RequestLogModel.appendStep(log.requestLogId, step).catch((e: Error) =>
1446
+ mediaLogger.error(`live delegation log failed: ${e.message}`),
1447
+ );
1448
+ }
1449
+
1450
+ return reply;
1451
+ };
1452
+ }
1453
+
1454
+ type LiveRun = {
1455
+ requestLogId: number;
1456
+ toolCallId: string;
1457
+ tokenName: string;
1458
+ startedAt: number;
1459
+ costs: { delegationUsd: number };
1460
+ };
1461
+
1462
+ // Replaces the session step's result with the summary and finishes the run when the session ends.
1463
+ // Best-effort, as for video: the session already happened, so a failure only loses the record.
1464
+ async function finishLiveRun(run: LiveRun, summary: OpenAILiveSummary): Promise<void> {
1465
+ try {
1466
+ await RequestLogModel.continueToolRun(run.requestLogId, [
1467
+ { toolCallId: run.toolCallId, output: JSON.stringify(summary), isError: false },
1468
+ ]);
1469
+
1470
+ // The session's audio time plus every delegation's backend call.
1471
+ const audio = liveCost(OPENAI_LIVE_ROUTE, summary.audioDurationMs);
1472
+ const costUsd = (audio?.costUsd ?? 0) + run.costs.delegationUsd;
1473
+
1474
+ const fields = mediaFinishFields({
1475
+ kind: "live",
1476
+ model: OPENAI_LIVE_ROUTE,
1477
+ tokenName: run.tokenName,
1478
+ durationMs: Date.now() - run.startedAt,
1479
+ response: liveTranscript(summary.turns),
1480
+ cost: audio || costUsd ? { costUsd, costSource: "pricing_table" } : undefined,
1481
+ });
1482
+
1483
+ // A sideband that failed before any turn says nothing about the session; record why.
1484
+ await RequestLogModel.finishRun(
1485
+ run.requestLogId,
1486
+ summary.error !== undefined && summary.turns.length === 0
1487
+ ? { ...fields, status: "error", error_message: summary.error }
1488
+ : fields,
1489
+ );
1490
+ } catch (e) {
1491
+ mediaLogger.error(`live request log failed: ${e instanceof Error ? e.message : String(e)}`);
1492
+ }
1493
+ }
1494
+
1312
1495
  class QgridFrameClass extends BaseFrameClass {
1313
1496
  constructor() {
1314
1497
  super("Qgrid");
@@ -2091,7 +2274,8 @@ class QgridFrameClass extends BaseFrameClass {
2091
2274
  return {
2092
2275
  toolCallId: `image_generation:0:${index}`,
2093
2276
  args,
2094
- result: imageTagForLog(image.b64, image.mimeType, image.revisedPrompt),
2277
+ // The run's response already holds this image.
2278
+ result: imagePlaceholderForLog(image.mimeType, image.b64),
2095
2279
  };
2096
2280
  }),
2097
2281
  };
@@ -2409,6 +2593,106 @@ class QgridFrameClass extends BaseFrameClass {
2409
2593
  });
2410
2594
  }
2411
2595
 
2596
+ // GPT-Live: exchanges the caller's WebRTC offer and returns the answer at once. The run stays
2597
+ // running for the whole session (up to two hours), its conversation rewritten after each turn;
2598
+ // a run left behind by a server restart is closed by the live stale sweep.
2599
+ @api({ httpMethod: "POST", clients: ["axios", "tanstack-mutation"] })
2600
+ async liveCall(params: LiveCallInput): Promise<LiveCallOutput> {
2601
+ const input = parseMediaInput(LiveCallInput, params);
2602
+ const dispatcher = openaiVoice();
2603
+ const selection = await resolveMediaTokenSelection("openai", input.tokenName);
2604
+ const voice = input.voice ?? OPENAI_LIVE_DEFAULT_VOICE;
2605
+
2606
+ const delegation: LiveDelegationOptions = {
2607
+ model: input.delegation?.model ?? LIVE_DELEGATION_DEFAULTS.model,
2608
+ effort: input.delegation?.effort ?? LIVE_DELEGATION_DEFAULTS.effort,
2609
+ webSearch: input.delegation?.webSearch ?? false,
2610
+ };
2611
+
2612
+ if (delegation.webSearch && delegation.model.startsWith("anthropic/")) {
2613
+ throw new BadRequestException(
2614
+ SD("qgrid.invalidInput")("delegation.webSearch is available on openai/ and grok/ models"),
2615
+ );
2616
+ }
2617
+
2618
+ const requestLogId = await startMediaRun(input.logger, {
2619
+ kind: "live",
2620
+ model: OPENAI_LIVE_ROUTE,
2621
+ prompt: "",
2622
+ systemPrompt: input.instructions,
2623
+ projectName: input.projectName,
2624
+ });
2625
+
2626
+ const startedAt = Date.now();
2627
+ const costs = { delegationUsd: 0 };
2628
+ const progress = requestLogId === undefined ? undefined : liveProgressRecorder(requestLogId);
2629
+ let turnsSoFar: readonly OpenAILiveTurn[] = [];
2630
+
2631
+ const started = await dispatchMediaCall(requestLogId, (signal) =>
2632
+ dispatcher.startLive({
2633
+ sdp: input.sdp,
2634
+ voice,
2635
+ instructions: input.instructions,
2636
+ onTurn: (turns) => {
2637
+ turnsSoFar = turns;
2638
+ progress?.(turns);
2639
+ },
2640
+ onDelegation: liveDelegationHandler(
2641
+ delegation,
2642
+ input.instructions,
2643
+ () => turnsSoFar,
2644
+ requestLogId === undefined ? undefined : { requestLogId, costs },
2645
+ ),
2646
+ signal,
2647
+ ...selection,
2648
+ }),
2649
+ );
2650
+
2651
+ const { sdp, callId, ended } = started.result;
2652
+
2653
+ if (requestLogId !== undefined) {
2654
+ const toolCallId = `live_session:${callId}`;
2655
+
2656
+ const args = {
2657
+ kind: "live",
2658
+ model: OPENAI_LIVE_ROUTE,
2659
+ voice,
2660
+ instructions: input.instructions,
2661
+ delegation,
2662
+ transport: "webrtc",
2663
+ callId,
2664
+ };
2665
+
2666
+ // Not a pending step (that would fall to the 30-minute tool-wait cleanup): the result says
2667
+ // the session is live until the summary replaces it.
2668
+ const result = JSON.stringify({ status: "live", callId });
2669
+
2670
+ const [step] = mediaToolSteps("live", [{ toolCallId, args, result }], Date.now() - startedAt);
2671
+
2672
+ try {
2673
+ await RequestLogModel.appendStep(requestLogId, step!);
2674
+ await RequestLogModel.recordRunProgress(requestLogId, { token_name: started.tokenName });
2675
+ } catch (e) {
2676
+ mediaLogger.error(`live request log failed: ${e instanceof Error ? e.message : String(e)}`);
2677
+ }
2678
+
2679
+ const run = { requestLogId, toolCallId, tokenName: started.tokenName, startedAt, costs };
2680
+ void ended.then((summary) => finishLiveRun(run, summary));
2681
+ }
2682
+
2683
+ const output: LiveCallOutput = {
2684
+ sdp,
2685
+ callId,
2686
+ model: OPENAI_LIVE_ROUTE,
2687
+ voice,
2688
+ tokenName: started.tokenName,
2689
+ };
2690
+
2691
+ if (requestLogId !== undefined) output.requestLogId = requestLogId;
2692
+
2693
+ return output;
2694
+ }
2695
+
2412
2696
  @api({ httpMethod: "GET", clients: ["axios", "tanstack-query"] })
2413
2697
  async usage(tokenId?: number): Promise<UsageResponse> {
2414
2698
  const { rows: allTokens } = await TokenModel.findMany("A");
@@ -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,50 @@ 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
+ export const LiveCallInput = z.object({
664
+ model: z.literal("openai/gpt-live-1").optional(),
665
+ sdp: z
666
+ .string()
667
+ .startsWith("v=0", "sdp must be an SDP offer")
668
+ .max(64 * 1024),
669
+ // One of the live voices (cove by default); the realtime TTS voices do not apply.
670
+ voice: z.string().min(1).max(64).optional(),
671
+ instructions: z.string().min(1).max(8_000).optional(),
672
+ // What the voice hands off (lookups, reasoning) runs as a qgrid query on this model, chosen per
673
+ // session: any served model in QGRID_MODELS (default openai/gpt-6-luna at low effort).
674
+ // webSearch turns on the provider's hosted web search (openai/ and grok/ only).
675
+ delegation: z
676
+ .object({
677
+ model: z
678
+ .string()
679
+ .refine((id) => QGRID_MODELS.includes(id), "model must be one of QGRID_MODELS")
680
+ .optional(),
681
+ effort: Effort.optional(),
682
+ webSearch: z.boolean().optional(),
683
+ })
684
+ .optional(),
685
+ ...MediaCallOptions,
686
+ });
687
+
688
+ export type LiveCallInput = z.infer<typeof LiveCallInput>;
689
+
690
+ export const LiveCallOutput = z.object({
691
+ // The SDP answer for the caller's peer connection.
692
+ sdp: z.string(),
693
+ callId: z.string(),
694
+ model: z.string(),
695
+ voice: z.string(),
696
+ tokenName: z.string(),
697
+ requestLogId: z.number().optional(),
698
+ });
699
+
700
+ export type LiveCallOutput = z.infer<typeof LiveCallOutput>;
701
+
599
702
  // ─── Run Lifecycle ───
600
703
 
601
704
  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,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) => {