@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
@@ -12,8 +12,19 @@ import {
12
12
  buildOpenAIRealtimeHeaders,
13
13
  buildSpeechInstructions,
14
14
  buildSpeechSession,
15
+ buildLiveSession,
15
16
  buildTranscriptionSession,
17
+ isOpenAILiveVoice,
16
18
  isOpenAIRealtimeVoice,
19
+ liveDelegationAnswerEvent,
20
+ liveDelegationCreatedEvent,
21
+ liveSessionClosedEvent,
22
+ liveTurnDoneEvent,
23
+ liveUsageUpdatedEvent,
24
+ OPENAI_LIVE_ALPHA_HEADER,
25
+ OPENAI_LIVE_CALLS_QUERY,
26
+ OPENAI_LIVE_DEFAULT_VOICE,
27
+ OPENAI_LIVE_WS_URL,
17
28
  OPENAI_REALTIME_CALLS_URL,
18
29
  OPENAI_REALTIME_DEFAULT_SPEECH_MODEL,
19
30
  OPENAI_REALTIME_DEFAULT_TRANSCRIPTION_MODEL,
@@ -54,6 +65,22 @@ export const OPENAI_STT_DEADLINE_MS = 25_000;
54
65
  /** The direct transcription socket has no observed teardown; this bounds a hung fallback. */
55
66
  export const OPENAI_STT_FALLBACK_TIMEOUT_MS = 60_000;
56
67
  export const OPENAI_TTS_TIMEOUT_MS = 60_000;
68
+ export const OPENAI_LIVE_CALL_TIMEOUT_MS = 15_000;
69
+
70
+ /**
71
+ * A live session expires two hours after creation (session.started expires_at, observed
72
+ * 2026-11-10); this bounds a sideband that never closes.
73
+ */
74
+ export const OPENAI_LIVE_WATCH_LIMIT_MS = (2 * 60 + 5) * 60_000;
75
+
76
+ /** Live events too frequent or bulky for the request log: audio copies and word-level text. */
77
+ const LIVE_UNLOGGED_EVENTS: ReadonlySet<string> = new Set([
78
+ "session.input_audio.append",
79
+ "session.output_audio.delta",
80
+ "input_transcript.added",
81
+ "output_transcript.added",
82
+ "turn.delta",
83
+ ]);
57
84
 
58
85
  /** One second of 24 kHz mono PCM16 per input_audio_buffer.append. */
59
86
  const APPEND_CHUNK_BYTES = OPENAI_REALTIME_SAMPLE_RATE * 2;
@@ -69,6 +96,8 @@ export interface OpenAIVoiceClientOptions {
69
96
  sttDirectFallback?: boolean;
70
97
  sttFallbackTimeoutMs?: number;
71
98
  ttsTimeoutMs?: number;
99
+ liveWsUrl?: string;
100
+ liveWatchLimitMs?: number;
72
101
  }
73
102
 
74
103
  export interface OpenAITranscribeRequest {
@@ -114,6 +143,62 @@ export interface OpenAISpeechResult {
114
143
  firstAudioAt: number;
115
144
  }
116
145
 
146
+ export interface OpenAILiveCallRequest {
147
+ /** The caller's WebRTC SDP offer. */
148
+ sdp: string;
149
+ voice?: string;
150
+ instructions?: string;
151
+ signal?: AbortSignal;
152
+ /** Called with the conversation so far after each finished turn; must not throw. */
153
+ onTurn?: (turns: readonly OpenAILiveTurn[]) => void;
154
+ /**
155
+ * Answers a delegation (work the voice model hands to the client); the resolved text goes back
156
+ * to the session and the voice speaks it. Without it delegations go unanswered.
157
+ */
158
+ onDelegation?: (delegation: OpenAILiveDelegation) => Promise<string>;
159
+ }
160
+
161
+ export interface OpenAILiveDelegation {
162
+ itemId: string;
163
+ /** What the voice model asks for, usually the user's request in its own words. */
164
+ text: string;
165
+ }
166
+
167
+ /** A session event kept for the request log; audio copies and word-level text are skipped. */
168
+ export interface OpenAILiveEvent {
169
+ /** Milliseconds since qgrid joined the sideband. */
170
+ atMs: number;
171
+ event: JsonValue;
172
+ }
173
+
174
+ export interface OpenAILiveTurn {
175
+ role: string;
176
+ transcript: string;
177
+ /** Session time, from the session's own clock. */
178
+ startMs: number;
179
+ endMs: number;
180
+ }
181
+
182
+ export interface OpenAILiveSummary {
183
+ turns: OpenAILiveTurn[];
184
+ events: OpenAILiveEvent[];
185
+ /** From session.closed, or the last usage update when the session ended without one. */
186
+ audioDurationMs: number | undefined;
187
+ /** The session.closed reason, or how the sideband ended without one. */
188
+ endReason: string;
189
+ /** Set when the sideband failed; the caller's session may still have run. */
190
+ error?: string;
191
+ }
192
+
193
+ export interface OpenAILiveCall {
194
+ /** The SDP answer for the caller's peer connection. */
195
+ sdp: string;
196
+ callId: string;
197
+ quotaHeaders: CodexQuotaHeaders;
198
+ /** Settles when the session ends; never rejects. */
199
+ ended: Promise<OpenAILiveSummary>;
200
+ }
201
+
117
202
  export class OpenAIVoiceInputError extends Error {
118
203
  constructor(message: string, options?: ErrorOptions) {
119
204
  super(message, options);
@@ -309,6 +394,16 @@ async function callErrorFromResponse(response: Response): Promise<OpenAIProtocol
309
394
  return new OpenAIProtocolError(`realtime call rejected: ${message}`, undefined, response.status);
310
395
  }
311
396
 
397
+ /** The rtc_… id at the end of a 201's Location (/v1/realtime/calls/rtc_…). */
398
+ function callIdFromLocation(location: string | null): string {
399
+ const callId = location?.split("/").pop() ?? "";
400
+
401
+ if (!/^rtc_[A-Za-z0-9_-]+$/.test(callId))
402
+ throw new OpenAIProtocolError(`realtime call returned no call id (Location: ${location})`);
403
+
404
+ return callId;
405
+ }
406
+
312
407
  export class OpenAIVoiceClient {
313
408
  private readonly fetchImpl: typeof fetch;
314
409
  private readonly webSocketFactory: OpenAIWebSocketFactory;
@@ -318,6 +413,10 @@ export class OpenAIVoiceClient {
318
413
  private readonly sttDirectFallback: boolean;
319
414
  private readonly sttFallbackTimeoutMs: number;
320
415
  private readonly ttsTimeoutMs: number;
416
+ private readonly liveWsUrl: string;
417
+ private readonly liveWatchLimitMs: number;
418
+ /** Open live sidebands, terminated on shutdown so they do not hold the process. */
419
+ private readonly liveSockets = new Set<OpenAIWebSocketLike>();
321
420
 
322
421
  constructor(options: OpenAIVoiceClientOptions = {}) {
323
422
  this.fetchImpl = options.fetch ?? fetch;
@@ -329,6 +428,8 @@ export class OpenAIVoiceClient {
329
428
  this.sttDirectFallback = options.sttDirectFallback ?? true;
330
429
  this.sttFallbackTimeoutMs = options.sttFallbackTimeoutMs ?? OPENAI_STT_FALLBACK_TIMEOUT_MS;
331
430
  this.ttsTimeoutMs = options.ttsTimeoutMs ?? OPENAI_TTS_TIMEOUT_MS;
431
+ this.liveWsUrl = options.liveWsUrl ?? OPENAI_LIVE_WS_URL;
432
+ this.liveWatchLimitMs = options.liveWatchLimitMs ?? OPENAI_LIVE_WATCH_LIMIT_MS;
332
433
  }
333
434
 
334
435
  /**
@@ -419,12 +520,8 @@ export class OpenAIVoiceClient {
419
520
  throw await callErrorFromResponse(response);
420
521
  }
421
522
 
422
- const location = response.headers.get("location") ?? "";
423
- const callId = location.split("/").pop() ?? "";
424
523
  await response.body?.cancel();
425
-
426
- if (!/^rtc_[A-Za-z0-9_-]+$/.test(callId))
427
- throw new OpenAIProtocolError(`realtime call returned no call id (Location: ${location})`);
524
+ const callId = callIdFromLocation(response.headers.get("location"));
428
525
  const quotaHeaders = codexQuotaHeaders(response.headers);
429
526
 
430
527
  const text = await this.runTranscriptionSocket(
@@ -561,6 +658,181 @@ export class OpenAIVoiceClient {
561
658
  }
562
659
  }
563
660
 
661
+ /**
662
+ * GPT-Live: exchanges the caller's SDP offer through /realtime/calls and starts watching the
663
+ * call's sideband. Audio flows between the caller's peer and OpenAI; the caller ends the session
664
+ * with {"type":"session.close"} on its data channel.
665
+ */
666
+ async createLiveCall(
667
+ credentials: OpenAIRealtimeCredentials,
668
+ request: OpenAILiveCallRequest,
669
+ ): Promise<OpenAILiveCall> {
670
+ const voice = request.voice ?? OPENAI_LIVE_DEFAULT_VOICE;
671
+
672
+ if (!isOpenAILiveVoice(voice))
673
+ throw new OpenAIVoiceInputError(`unsupported live voice "${voice}"`);
674
+ const correlation = { threadId: crypto.randomUUID(), sessionId: crypto.randomUUID() };
675
+
676
+ const headers = {
677
+ ...buildOpenAIRealtimeHeaders(credentials, correlation),
678
+ ...OPENAI_LIVE_ALPHA_HEADER,
679
+ };
680
+
681
+ // The caller's signal (its HTTP request) bounds only the exchange, never the session.
682
+ const { signal, dispose } = this.deadline(request.signal, OPENAI_LIVE_CALL_TIMEOUT_MS);
683
+
684
+ try {
685
+ const response = await this.fetchImpl(`${this.callsUrl}?${OPENAI_LIVE_CALLS_QUERY}`, {
686
+ method: "POST",
687
+ headers: { ...headers, "Content-Type": "application/json" },
688
+ body: JSON.stringify({
689
+ sdp: request.sdp,
690
+ session: buildLiveSession({ voice, instructions: request.instructions }),
691
+ }),
692
+ signal,
693
+ });
694
+
695
+ if (response.status !== 201) {
696
+ if (response.ok) await response.body?.cancel();
697
+ throw await callErrorFromResponse(response);
698
+ }
699
+
700
+ const callId = callIdFromLocation(response.headers.get("location"));
701
+ const sdp = await response.text();
702
+
703
+ return {
704
+ sdp,
705
+ callId,
706
+ quotaHeaders: codexQuotaHeaders(response.headers),
707
+ ended: this.watchLiveSession(`${this.liveWsUrl}/${callId}`, headers, request),
708
+ };
709
+ } catch (error) {
710
+ throw signal.aborted ? this.abortReason(request.signal, signal, error) : error;
711
+ } finally {
712
+ dispose();
713
+ }
714
+ }
715
+
716
+ /**
717
+ * Follows a live call's sideband until the session ends. It carries the same events as the
718
+ * caller's data channel plus a copy of both audio streams. Finished turns, usage and the other
719
+ * events are kept (audio copies and word-level text are skipped), and delegations are answered
720
+ * through `onDelegation`. Never rejects.
721
+ */
722
+ private async watchLiveSession(
723
+ url: string,
724
+ headers: Record<string, string>,
725
+ { onTurn, onDelegation }: Pick<OpenAILiveCallRequest, "onTurn" | "onDelegation">,
726
+ ): Promise<OpenAILiveSummary> {
727
+ const signal = AbortSignal.timeout(this.liveWatchLimitMs);
728
+ const socket = this.webSocketFactory(url, { headers });
729
+ const records = socketRecords(socket, signal);
730
+ const startedAt = Date.now();
731
+ const turns: OpenAILiveTurn[] = [];
732
+ const events: OpenAILiveEvent[] = [];
733
+ let audioDurationMs: number | undefined;
734
+ let serverError: string | undefined;
735
+ this.liveSockets.add(socket);
736
+ const keep = (event: JsonValue) => events.push({ atMs: Date.now() - startedAt, event });
737
+
738
+ const ended = (endReason: string, error = serverError): OpenAILiveSummary =>
739
+ error === undefined
740
+ ? { turns, events, audioDurationMs, endReason }
741
+ : { turns, events, audioDurationMs, endReason, error };
742
+
743
+ // Runs beside the event loop, which must keep draining the sideband meanwhile.
744
+ const answer = (delegation: OpenAILiveDelegation) => {
745
+ if (!onDelegation) return;
746
+ const asked = Date.now();
747
+
748
+ void onDelegation(delegation)
749
+ .then(async (reply) => {
750
+ await sendJson(socket, liveDelegationAnswerEvent(delegation.itemId, reply));
751
+ // qgrid's own message, logged beside the server's events.
752
+ keep({
753
+ type: "delegation.context.append",
754
+ delegation_item_id: delegation.itemId,
755
+ ms: Date.now() - asked,
756
+ text: reply,
757
+ });
758
+ })
759
+ .catch((error: Error) =>
760
+ keep({
761
+ type: "qgrid.delegation_failed",
762
+ delegation_item_id: delegation.itemId,
763
+ error: error.message,
764
+ }),
765
+ );
766
+ };
767
+
768
+ try {
769
+ await this.awaitOpen(records.next);
770
+
771
+ for (;;) {
772
+ const next = await records.next();
773
+
774
+ if (next.kind === "error") {
775
+ return ended(
776
+ signal.aborted ? "watch limit reached" : "sideband error",
777
+ next.error.message,
778
+ );
779
+ }
780
+
781
+ // Without session.closed: the caller dropped its peer (OpenAI ends it about 30 s later).
782
+ if (next.kind === "close") return ended(`sideband closed (${next.code})`);
783
+
784
+ if (next.kind !== "event") continue;
785
+ const type = realtimeServerEvent.safeParse(next.event).data?.type ?? "";
786
+
787
+ if (!LIVE_UNLOGGED_EVENTS.has(type)) keep(next.event);
788
+ const delegation = liveDelegationCreatedEvent.safeParse(next.event);
789
+
790
+ if (delegation.success) {
791
+ const { id, content } = delegation.data.item;
792
+ answer({ itemId: id, text: content.flatMap((part) => part.text ?? []).join("") });
793
+ continue;
794
+ }
795
+
796
+ const turn = liveTurnDoneEvent.safeParse(next.event);
797
+
798
+ if (turn.success) {
799
+ const { role, transcript, start_ms, end_ms } = turn.data.turn;
800
+ turns.push({ role, transcript, startMs: start_ms, endMs: end_ms });
801
+ onTurn?.(turns);
802
+ continue;
803
+ }
804
+
805
+ const usage = liveUsageUpdatedEvent.safeParse(next.event);
806
+
807
+ if (usage.success) {
808
+ audioDurationMs = usage.data.usage.audio_duration_ms;
809
+ continue;
810
+ }
811
+
812
+ const closed = liveSessionClosedEvent.safeParse(next.event);
813
+
814
+ if (closed.success) {
815
+ audioDurationMs = closed.data.usage?.audio_duration_ms ?? audioDurationMs;
816
+ socket.close(1000, "done");
817
+
818
+ return ended(closed.data.reason ?? "closed");
819
+ }
820
+
821
+ serverError = serverErrorFromEvent(next.event)?.message ?? serverError;
822
+ }
823
+ } catch (error) {
824
+ return ended("sideband error", error instanceof Error ? error.message : String(error));
825
+ } finally {
826
+ records.cleanup();
827
+ this.liveSockets.delete(socket);
828
+ }
829
+ }
830
+
831
+ /** Shutdown: ends every live watcher (each run is then logged with what it saw). */
832
+ closeLiveSessions(): void {
833
+ this.liveSockets.forEach((socket) => socket.terminate());
834
+ }
835
+
564
836
  private deadline(caller: AbortSignal | undefined, ms: number) {
565
837
  const timeout = AbortSignal.timeout(ms);
566
838
  const signal = caller ? AbortSignal.any([caller, timeout]) : timeout;