@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.
- package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +5 -2
- package/bundle/dist/application/qgrid/qgrid.dispatcher.js +3 -1
- package/bundle/dist/application/qgrid/qgrid.frame.js +225 -6
- package/bundle/dist/application/qgrid/qgrid.types.js +74 -2
- package/bundle/dist/application/request-log/request-log.model.js +11 -1
- package/bundle/dist/application/sonamu.generated.js +5 -3
- package/bundle/dist/i18n/sd.generated.js +3 -2
- package/bundle/dist/utils/providers/common/model-cost.js +8 -2
- package/bundle/dist/utils/providers/openai/openai-dispatcher.js +18 -1
- package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +120 -2
- package/bundle/dist/utils/providers/openai/openai-voice-client.js +184 -6
- package/bundle/src/application/qgrid/qgrid-run-lifecycle.test.ts +13 -0
- package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +11 -1
- package/bundle/src/application/qgrid/qgrid.dispatcher.test.ts +17 -0
- package/bundle/src/application/qgrid/qgrid.dispatcher.ts +8 -0
- package/bundle/src/application/qgrid/qgrid.frame.test.ts +223 -0
- package/bundle/src/application/qgrid/qgrid.frame.ts +304 -3
- package/bundle/src/application/qgrid/qgrid.types.ts +121 -0
- package/bundle/src/application/request-log/request-log.entity.json +3 -2
- package/bundle/src/application/request-log/request-log.model.test.ts +19 -0
- package/bundle/src/application/request-log/request-log.model.ts +20 -1
- package/bundle/src/application/sonamu.generated.http +28 -0
- package/bundle/src/application/sonamu.generated.ts +2 -1
- package/bundle/src/i18n/sd.generated.ts +2 -1
- package/bundle/src/utils/providers/common/model-cost.ts +15 -0
- package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +16 -0
- package/bundle/src/utils/providers/openai/openai-dispatcher.ts +26 -0
- package/bundle/src/utils/providers/openai/openai-realtime-protocol.ts +160 -0
- package/bundle/src/utils/providers/openai/openai-voice-client.test.ts +205 -0
- package/bundle/src/utils/providers/openai/openai-voice-client.ts +284 -5
- package/bundle/web-dist/client/assets/index-B5yorZqv.js +104 -0
- package/bundle/web-dist/client/assets/index-CpOwNalw.css +1 -0
- package/bundle/web-dist/client/assets/logs-Bx_jXEDZ.js +1 -0
- package/bundle/web-dist/client/assets/monit-CPQ18s_m.js +1 -0
- package/bundle/web-dist/client/assets/{routes--6kS1pgJ.js → routes-S4D5Ld4L.js} +2 -2
- package/bundle/web-dist/client/assets/{settings-Dah87LB2.js → settings-M4h_UV87.js} +1 -1
- package/bundle/web-dist/client/assets/show-BchF-T1a.js +2 -0
- package/bundle/web-dist/client/assets/{tokens-CIHja806.js → tokens-BgBD07ru.js} +1 -1
- package/bundle/web-dist/client/assets/{use-oauth-login-flow-DeJCqHDJ.js → use-oauth-login-flow-D_wI9MzM.js} +1 -1
- package/bundle/web-dist/client/assets/use-update-token-mutation-IvuH3Qje.js +1 -0
- package/bundle/web-dist/client/assets/{vendor-tanstack-6B86itGS.js → vendor-tanstack-DMgmqjm4.js} +1 -1
- package/bundle/web-dist/client/assets/voice-CnIiQMbo.js +1 -0
- package/bundle/web-dist/client/index.html +3 -3
- package/bundle/web-dist/server/assets/{TimedPlayer-DAwjkP4z.js → TimedPlayer-COqaTQSl.js} +1 -1
- package/bundle/web-dist/server/assets/{logs-BmBpBe-j.js → logs-HPho1SkC.js} +5 -6
- package/bundle/web-dist/server/assets/{monit-Db1WrIls.js → monit-Bl2kSkSF.js} +3 -3
- package/bundle/web-dist/server/assets/{plus-CW9y_K7l.js → plus-CQ8AHpih.js} +1 -1
- package/bundle/web-dist/server/assets/{refresh-cw-CRgcH5bT.js → refresh-cw-pYSuvt4c.js} +1 -1
- package/bundle/web-dist/server/assets/{request-model-DRF7hmJC.js → request-model-ZulJMbGm.js} +1 -1
- package/bundle/web-dist/server/assets/{routes-CARZj7or.js → routes-BNHCX4VI.js} +4 -4
- package/bundle/web-dist/server/assets/{services.generated-B6QpnL_N.js → services.generated-C3b31_vt.js} +23209 -22930
- package/bundle/web-dist/server/assets/{settings-B4jdpP5N.js → settings-NJUyaSrJ.js} +4 -4
- package/bundle/web-dist/server/assets/{show-CnLDFCtW.js → show-Dz5QGL7l.js} +8 -9
- package/bundle/web-dist/server/assets/{tokens-TDQguTdh.js → tokens-BPQvjIGq.js} +5 -5
- package/bundle/web-dist/server/assets/{use-oauth-login-flow-du7pOh_H.js → use-oauth-login-flow-CCc8LEmn.js} +1 -1
- package/bundle/web-dist/server/assets/{use-update-token-mutation-DA6HiiWS.js → use-update-token-mutation-Ba-sEhq1.js} +1 -1
- package/bundle/web-dist/server/assets/{voice-BvAl-vTr.js → voice-xFFT4zqK.js} +307 -22
- package/bundle/web-dist/server/entry-server.generated.js +5590 -71
- package/package.json +1 -1
- package/skills/qgrid/references/decision-rationale.md +4 -0
- package/skills/qgrid/references/openai-codex-runtime.md +16 -0
- package/skills/qgrid/references/request-log-run-lifecycle.md +2 -1
- package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
- package/bundle/web-dist/client/assets/index-Co8uAhSV.css +0 -1
- package/bundle/web-dist/client/assets/index-DvW4Yb82.js +0 -104
- package/bundle/web-dist/client/assets/logs-DAif2re1.js +0 -1
- package/bundle/web-dist/client/assets/monit-DYczkiu0.js +0 -1
- package/bundle/web-dist/client/assets/show-DQWFaVDW.js +0 -2
- package/bundle/web-dist/client/assets/use-update-token-mutation-Cn_Po_rH.js +0 -1
- package/bundle/web-dist/client/assets/voice-6i785ieC.js +0 -1
- package/bundle/web-dist/server/assets/link-DrdV092C.js +0 -4919
|
@@ -3,10 +3,12 @@ import { describe, expect, it, vi } from "vitest";
|
|
|
3
3
|
import { CODEX_CLI_ORIGINATOR } from "./openai-backend-protocol";
|
|
4
4
|
import type { OpenAIWebSocketFactory, OpenAIWebSocketLike } from "./openai-direct-client";
|
|
5
5
|
import {
|
|
6
|
+
buildLiveSession,
|
|
6
7
|
buildOpenAIRealtimeHeaders,
|
|
7
8
|
buildSpeechSession,
|
|
8
9
|
buildTranscriptionSession,
|
|
9
10
|
decodeWav,
|
|
11
|
+
OPENAI_LIVE_WS_URL,
|
|
10
12
|
OPENAI_REALTIME_CALLS_URL,
|
|
11
13
|
OPENAI_REALTIME_WS_URL,
|
|
12
14
|
prepareRealtimeInput,
|
|
@@ -580,3 +582,206 @@ describe("OpenAIVoiceClient.speak", () => {
|
|
|
580
582
|
});
|
|
581
583
|
});
|
|
582
584
|
|
|
585
|
+
describe("OpenAIVoiceClient.createLiveCall", () => {
|
|
586
|
+
// Shapes observed live on 2026-11-10 (SON-592): a browser peer in conversation with gpt-live-1.
|
|
587
|
+
const userTurn = {
|
|
588
|
+
type: "turn.done",
|
|
589
|
+
turn: { id: "turn_u", role: "user", start_ms: 600, end_ms: 5800, transcript: "Hi there?" },
|
|
590
|
+
};
|
|
591
|
+
|
|
592
|
+
const assistantTurn = {
|
|
593
|
+
type: "turn.done",
|
|
594
|
+
turn: { id: "turn_a", role: "assistant", start_ms: 5600, end_ms: 9400, transcript: "Hello!" },
|
|
595
|
+
};
|
|
596
|
+
|
|
597
|
+
it("exchanges the offer through /calls with the alpha header and summarizes the sideband", async () => {
|
|
598
|
+
const fetchMock = vi.fn(async () => callsResponse("rtc_live"));
|
|
599
|
+
const ws = mockedWebSocket();
|
|
600
|
+
|
|
601
|
+
const client = new OpenAIVoiceClient({
|
|
602
|
+
fetch: fetchMock as unknown as typeof fetch,
|
|
603
|
+
webSocketFactory: ws.factory,
|
|
604
|
+
});
|
|
605
|
+
|
|
606
|
+
const progress: number[] = [];
|
|
607
|
+
|
|
608
|
+
const call = await client.createLiveCall(credentials, {
|
|
609
|
+
sdp: "v=0\r\noffer",
|
|
610
|
+
voice: "hanul",
|
|
611
|
+
instructions: "Be brief.",
|
|
612
|
+
onTurn: (turns) => progress.push(turns.length),
|
|
613
|
+
});
|
|
614
|
+
|
|
615
|
+
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
|
|
616
|
+
expect(url).toBe(`${OPENAI_REALTIME_CALLS_URL}?intent=quicksilver&architecture=avas`);
|
|
617
|
+
const headers = init.headers as Record<string, string>;
|
|
618
|
+
expect(headers["OpenAI-Alpha"]).toBe("quicksilver=v2");
|
|
619
|
+
expect(headers.Authorization).toBe("Bearer access");
|
|
620
|
+
|
|
621
|
+
expect(JSON.parse(String(init.body))).toEqual({
|
|
622
|
+
sdp: "v=0\r\noffer",
|
|
623
|
+
session: {
|
|
624
|
+
model: "gpt-live-1-codex",
|
|
625
|
+
instructions: "Be brief.",
|
|
626
|
+
audio: { output: { voice: "hanul" } },
|
|
627
|
+
delegation: { type: "client" },
|
|
628
|
+
},
|
|
629
|
+
});
|
|
630
|
+
|
|
631
|
+
expect(buildLiveSession({ voice: "cove" })).toMatchObject({ instructions: "" });
|
|
632
|
+
expect(call).toMatchObject({ sdp: "v=0", callId: "rtc_live" });
|
|
633
|
+
expect(call.quotaHeaders.get("x-codex-primary-used-percent")).toBe("88");
|
|
634
|
+
expect(ws.calls[0]?.url).toBe(`${OPENAI_LIVE_WS_URL}/rtc_live`);
|
|
635
|
+
expect(ws.calls[0]?.headers["OpenAI-Alpha"]).toBe("quicksilver=v2");
|
|
636
|
+
|
|
637
|
+
const socket = ws.sockets[0]!;
|
|
638
|
+
socket.emit("open");
|
|
639
|
+
socket.message({ type: "session.started", session: { id: "rtc_live", expires_at: 1 } });
|
|
640
|
+
socket.message({ type: "session.input_audio.append", audio: "AAAA" });
|
|
641
|
+
socket.message(userTurn);
|
|
642
|
+
socket.message({ type: "session.output_audio.delta", delta: "AAAA" });
|
|
643
|
+
socket.message(assistantTurn);
|
|
644
|
+
socket.message({ type: "session.usage.updated", usage: { audio_duration_ms: 5000 } });
|
|
645
|
+
|
|
646
|
+
socket.message({
|
|
647
|
+
type: "session.closed",
|
|
648
|
+
reason: "client_request",
|
|
649
|
+
usage: { audio_duration_ms: 9400 },
|
|
650
|
+
});
|
|
651
|
+
|
|
652
|
+
await expect(call.ended).resolves.toMatchObject({
|
|
653
|
+
turns: [
|
|
654
|
+
{ role: "user", transcript: "Hi there?", startMs: 600, endMs: 5800 },
|
|
655
|
+
{ role: "assistant", transcript: "Hello!", startMs: 5600, endMs: 9400 },
|
|
656
|
+
],
|
|
657
|
+
audioDurationMs: 9400,
|
|
658
|
+
endReason: "client_request",
|
|
659
|
+
});
|
|
660
|
+
expect(progress).toEqual([1, 2]);
|
|
661
|
+
// The session belongs to the caller's peer: qgrid sends nothing on the sideband.
|
|
662
|
+
expect(socket.sent).toHaveLength(0);
|
|
663
|
+
expect(socket.closed?.code).toBe(1000);
|
|
664
|
+
});
|
|
665
|
+
|
|
666
|
+
it("answers a delegation on the sideband and keeps the session's events", async () => {
|
|
667
|
+
const ws = mockedWebSocket();
|
|
668
|
+
|
|
669
|
+
const client = new OpenAIVoiceClient({
|
|
670
|
+
fetch: (async () => callsResponse("rtc_live")) as unknown as typeof fetch,
|
|
671
|
+
webSocketFactory: ws.factory,
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
const onDelegation = vi.fn(async () => "Nvidia is in today's top story.");
|
|
675
|
+
const call = await client.createLiveCall(credentials, { sdp: "v=0", onDelegation });
|
|
676
|
+
const socket = ws.sockets[0]!;
|
|
677
|
+
socket.emit("open");
|
|
678
|
+
socket.message({ type: "session.input_audio.append", audio: "AAAA" });
|
|
679
|
+
socket.message({ type: "turn.delta", delta: " news", turn_id: "turn_u" });
|
|
680
|
+
|
|
681
|
+
socket.message({
|
|
682
|
+
type: "delegation.created",
|
|
683
|
+
item: {
|
|
684
|
+
id: "item_d",
|
|
685
|
+
type: "delegation",
|
|
686
|
+
target: "client",
|
|
687
|
+
handoff_id: "handoff_1",
|
|
688
|
+
content: [{ type: "input_text", text: "Look up today's top tech news" }],
|
|
689
|
+
},
|
|
690
|
+
});
|
|
691
|
+
|
|
692
|
+
await tick();
|
|
693
|
+
await tick();
|
|
694
|
+
|
|
695
|
+
expect(onDelegation).toHaveBeenCalledWith({ itemId: "item_d", text: "Look up today's top tech news" });
|
|
696
|
+
expect(socket.sentEvents()).toEqual([
|
|
697
|
+
{
|
|
698
|
+
type: "delegation.context.append",
|
|
699
|
+
delegation_item_id: "item_d",
|
|
700
|
+
content: [{ type: "input_text", text: "Nvidia is in today's top story." }],
|
|
701
|
+
},
|
|
702
|
+
]);
|
|
703
|
+
|
|
704
|
+
socket.message({ type: "session.closed", reason: "client_request", usage: { audio_duration_ms: 1 } });
|
|
705
|
+
const summary = await call.ended;
|
|
706
|
+
|
|
707
|
+
// Audio copies and word-level text are skipped; qgrid's own answer is logged with them.
|
|
708
|
+
expect(summary.events.map(({ event }) => (event as { type: string }).type)).toEqual([
|
|
709
|
+
"delegation.created",
|
|
710
|
+
"delegation.context.append",
|
|
711
|
+
"session.closed",
|
|
712
|
+
]);
|
|
713
|
+
});
|
|
714
|
+
|
|
715
|
+
it("seeds the session with history as Codex's initial_items", async () => {
|
|
716
|
+
const fetchMock = vi.fn(async () => callsResponse("rtc_live"));
|
|
717
|
+
const client = new OpenAIVoiceClient({ fetch: fetchMock as unknown as typeof fetch });
|
|
718
|
+
|
|
719
|
+
await client.createLiveCall(credentials, {
|
|
720
|
+
sdp: "v=0",
|
|
721
|
+
history: [
|
|
722
|
+
{ role: "developer", text: "Stay in character as Kuma." },
|
|
723
|
+
{ role: "user", text: "My name is Dongseon." },
|
|
724
|
+
{ role: "assistant", text: "Nice to meet you!" },
|
|
725
|
+
],
|
|
726
|
+
});
|
|
727
|
+
|
|
728
|
+
const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
|
|
729
|
+
expect(JSON.parse(String(init.body)).session.initial_items).toEqual([
|
|
730
|
+
{ type: "message", role: "developer", content: [{ type: "input_text", text: "Stay in character as Kuma." }] },
|
|
731
|
+
{ type: "message", role: "user", content: [{ type: "input_text", text: "My name is Dongseon." }] },
|
|
732
|
+
{ type: "message", role: "assistant", content: [{ type: "output_text", text: "Nice to meet you!" }] },
|
|
733
|
+
]);
|
|
734
|
+
});
|
|
735
|
+
|
|
736
|
+
it("ends at a bare sideband close with the last reported usage", async () => {
|
|
737
|
+
const ws = mockedWebSocket();
|
|
738
|
+
|
|
739
|
+
const client = new OpenAIVoiceClient({
|
|
740
|
+
fetch: (async () => callsResponse("rtc_live")) as unknown as typeof fetch,
|
|
741
|
+
webSocketFactory: ws.factory,
|
|
742
|
+
});
|
|
743
|
+
|
|
744
|
+
const call = await client.createLiveCall(credentials, { sdp: "v=0" });
|
|
745
|
+
const socket = ws.sockets[0]!;
|
|
746
|
+
socket.emit("open");
|
|
747
|
+
socket.message(userTurn);
|
|
748
|
+
socket.message({ type: "session.usage.updated", usage: { audio_duration_ms: 27_400 } });
|
|
749
|
+
socket.emit("close", 1006, Buffer.from(""));
|
|
750
|
+
|
|
751
|
+
await expect(call.ended).resolves.toMatchObject({
|
|
752
|
+
turns: [{ role: "user" }],
|
|
753
|
+
audioDurationMs: 27_400,
|
|
754
|
+
endReason: "sideband closed (1006)",
|
|
755
|
+
});
|
|
756
|
+
});
|
|
757
|
+
|
|
758
|
+
it("resolves, never rejects, when the sideband handshake fails", async () => {
|
|
759
|
+
const ws = mockedWebSocket();
|
|
760
|
+
|
|
761
|
+
const client = new OpenAIVoiceClient({
|
|
762
|
+
fetch: (async () => callsResponse("rtc_live")) as unknown as typeof fetch,
|
|
763
|
+
webSocketFactory: ws.factory,
|
|
764
|
+
});
|
|
765
|
+
|
|
766
|
+
const call = await client.createLiveCall(credentials, { sdp: "v=0" });
|
|
767
|
+
ws.sockets[0]!.emit("unexpected-response", {}, { statusCode: 404 });
|
|
768
|
+
|
|
769
|
+
await expect(call.ended).resolves.toEqual({
|
|
770
|
+
turns: [],
|
|
771
|
+
events: [],
|
|
772
|
+
audioDurationMs: undefined,
|
|
773
|
+
endReason: "sideband error",
|
|
774
|
+
error: "realtime socket handshake rejected with HTTP 404",
|
|
775
|
+
});
|
|
776
|
+
});
|
|
777
|
+
|
|
778
|
+
it("rejects voices outside the live list before any network call", async () => {
|
|
779
|
+
const fetchMock = vi.fn();
|
|
780
|
+
const client = new OpenAIVoiceClient({ fetch: fetchMock as unknown as typeof fetch });
|
|
781
|
+
|
|
782
|
+
await expect(
|
|
783
|
+
client.createLiveCall(credentials, { sdp: "v=0", voice: "marin" }),
|
|
784
|
+
).rejects.toBeInstanceOf(OpenAIVoiceInputError);
|
|
785
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
786
|
+
});
|
|
787
|
+
});
|
|
@@ -12,8 +12,20 @@ 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
|
+
type LiveHistoryMessage,
|
|
24
|
+
liveUsageUpdatedEvent,
|
|
25
|
+
OPENAI_LIVE_ALPHA_HEADER,
|
|
26
|
+
OPENAI_LIVE_CALLS_QUERY,
|
|
27
|
+
OPENAI_LIVE_DEFAULT_VOICE,
|
|
28
|
+
OPENAI_LIVE_WS_URL,
|
|
17
29
|
OPENAI_REALTIME_CALLS_URL,
|
|
18
30
|
OPENAI_REALTIME_DEFAULT_SPEECH_MODEL,
|
|
19
31
|
OPENAI_REALTIME_DEFAULT_TRANSCRIPTION_MODEL,
|
|
@@ -54,6 +66,22 @@ export const OPENAI_STT_DEADLINE_MS = 25_000;
|
|
|
54
66
|
/** The direct transcription socket has no observed teardown; this bounds a hung fallback. */
|
|
55
67
|
export const OPENAI_STT_FALLBACK_TIMEOUT_MS = 60_000;
|
|
56
68
|
export const OPENAI_TTS_TIMEOUT_MS = 60_000;
|
|
69
|
+
export const OPENAI_LIVE_CALL_TIMEOUT_MS = 15_000;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* A live session expires two hours after creation (session.started expires_at, observed
|
|
73
|
+
* 2026-11-10); this bounds a sideband that never closes.
|
|
74
|
+
*/
|
|
75
|
+
export const OPENAI_LIVE_WATCH_LIMIT_MS = (2 * 60 + 5) * 60_000;
|
|
76
|
+
|
|
77
|
+
/** Live events too frequent or bulky for the request log: audio copies and word-level text. */
|
|
78
|
+
const LIVE_UNLOGGED_EVENTS: ReadonlySet<string> = new Set([
|
|
79
|
+
"session.input_audio.append",
|
|
80
|
+
"session.output_audio.delta",
|
|
81
|
+
"input_transcript.added",
|
|
82
|
+
"output_transcript.added",
|
|
83
|
+
"turn.delta",
|
|
84
|
+
]);
|
|
57
85
|
|
|
58
86
|
/** One second of 24 kHz mono PCM16 per input_audio_buffer.append. */
|
|
59
87
|
const APPEND_CHUNK_BYTES = OPENAI_REALTIME_SAMPLE_RATE * 2;
|
|
@@ -69,6 +97,8 @@ export interface OpenAIVoiceClientOptions {
|
|
|
69
97
|
sttDirectFallback?: boolean;
|
|
70
98
|
sttFallbackTimeoutMs?: number;
|
|
71
99
|
ttsTimeoutMs?: number;
|
|
100
|
+
liveWsUrl?: string;
|
|
101
|
+
liveWatchLimitMs?: number;
|
|
72
102
|
}
|
|
73
103
|
|
|
74
104
|
export interface OpenAITranscribeRequest {
|
|
@@ -114,6 +144,64 @@ export interface OpenAISpeechResult {
|
|
|
114
144
|
firstAudioAt: number;
|
|
115
145
|
}
|
|
116
146
|
|
|
147
|
+
export interface OpenAILiveCallRequest {
|
|
148
|
+
/** The caller's WebRTC SDP offer. */
|
|
149
|
+
sdp: string;
|
|
150
|
+
voice?: string;
|
|
151
|
+
instructions?: string;
|
|
152
|
+
/** An earlier conversation the session starts from. */
|
|
153
|
+
history?: readonly LiveHistoryMessage[];
|
|
154
|
+
signal?: AbortSignal;
|
|
155
|
+
/** Called with the conversation so far after each finished turn; must not throw. */
|
|
156
|
+
onTurn?: (turns: readonly OpenAILiveTurn[]) => void;
|
|
157
|
+
/**
|
|
158
|
+
* Answers a delegation (work the voice model hands to the client); the resolved text goes back
|
|
159
|
+
* to the session and the voice speaks it. Without it delegations go unanswered.
|
|
160
|
+
*/
|
|
161
|
+
onDelegation?: (delegation: OpenAILiveDelegation) => Promise<string>;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export interface OpenAILiveDelegation {
|
|
165
|
+
itemId: string;
|
|
166
|
+
/** What the voice model asks for, usually the user's request in its own words. */
|
|
167
|
+
text: string;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** A session event kept for the request log; audio copies and word-level text are skipped. */
|
|
171
|
+
export interface OpenAILiveEvent {
|
|
172
|
+
/** Milliseconds since qgrid joined the sideband. */
|
|
173
|
+
atMs: number;
|
|
174
|
+
event: JsonValue;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export interface OpenAILiveTurn {
|
|
178
|
+
role: string;
|
|
179
|
+
transcript: string;
|
|
180
|
+
/** Session time, from the session's own clock. */
|
|
181
|
+
startMs: number;
|
|
182
|
+
endMs: number;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export interface OpenAILiveSummary {
|
|
186
|
+
turns: OpenAILiveTurn[];
|
|
187
|
+
events: OpenAILiveEvent[];
|
|
188
|
+
/** From session.closed, or the last usage update when the session ended without one. */
|
|
189
|
+
audioDurationMs: number | undefined;
|
|
190
|
+
/** The session.closed reason, or how the sideband ended without one. */
|
|
191
|
+
endReason: string;
|
|
192
|
+
/** Set when the sideband failed; the caller's session may still have run. */
|
|
193
|
+
error?: string;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export interface OpenAILiveCall {
|
|
197
|
+
/** The SDP answer for the caller's peer connection. */
|
|
198
|
+
sdp: string;
|
|
199
|
+
callId: string;
|
|
200
|
+
quotaHeaders: CodexQuotaHeaders;
|
|
201
|
+
/** Settles when the session ends; never rejects. */
|
|
202
|
+
ended: Promise<OpenAILiveSummary>;
|
|
203
|
+
}
|
|
204
|
+
|
|
117
205
|
export class OpenAIVoiceInputError extends Error {
|
|
118
206
|
constructor(message: string, options?: ErrorOptions) {
|
|
119
207
|
super(message, options);
|
|
@@ -309,6 +397,16 @@ async function callErrorFromResponse(response: Response): Promise<OpenAIProtocol
|
|
|
309
397
|
return new OpenAIProtocolError(`realtime call rejected: ${message}`, undefined, response.status);
|
|
310
398
|
}
|
|
311
399
|
|
|
400
|
+
/** The rtc_… id at the end of a 201's Location (/v1/realtime/calls/rtc_…). */
|
|
401
|
+
function callIdFromLocation(location: string | null): string {
|
|
402
|
+
const callId = location?.split("/").pop() ?? "";
|
|
403
|
+
|
|
404
|
+
if (!/^rtc_[A-Za-z0-9_-]+$/.test(callId))
|
|
405
|
+
throw new OpenAIProtocolError(`realtime call returned no call id (Location: ${location})`);
|
|
406
|
+
|
|
407
|
+
return callId;
|
|
408
|
+
}
|
|
409
|
+
|
|
312
410
|
export class OpenAIVoiceClient {
|
|
313
411
|
private readonly fetchImpl: typeof fetch;
|
|
314
412
|
private readonly webSocketFactory: OpenAIWebSocketFactory;
|
|
@@ -318,6 +416,10 @@ export class OpenAIVoiceClient {
|
|
|
318
416
|
private readonly sttDirectFallback: boolean;
|
|
319
417
|
private readonly sttFallbackTimeoutMs: number;
|
|
320
418
|
private readonly ttsTimeoutMs: number;
|
|
419
|
+
private readonly liveWsUrl: string;
|
|
420
|
+
private readonly liveWatchLimitMs: number;
|
|
421
|
+
/** Open live sidebands, terminated on shutdown so they do not hold the process. */
|
|
422
|
+
private readonly liveSockets = new Set<OpenAIWebSocketLike>();
|
|
321
423
|
|
|
322
424
|
constructor(options: OpenAIVoiceClientOptions = {}) {
|
|
323
425
|
this.fetchImpl = options.fetch ?? fetch;
|
|
@@ -329,6 +431,8 @@ export class OpenAIVoiceClient {
|
|
|
329
431
|
this.sttDirectFallback = options.sttDirectFallback ?? true;
|
|
330
432
|
this.sttFallbackTimeoutMs = options.sttFallbackTimeoutMs ?? OPENAI_STT_FALLBACK_TIMEOUT_MS;
|
|
331
433
|
this.ttsTimeoutMs = options.ttsTimeoutMs ?? OPENAI_TTS_TIMEOUT_MS;
|
|
434
|
+
this.liveWsUrl = options.liveWsUrl ?? OPENAI_LIVE_WS_URL;
|
|
435
|
+
this.liveWatchLimitMs = options.liveWatchLimitMs ?? OPENAI_LIVE_WATCH_LIMIT_MS;
|
|
332
436
|
}
|
|
333
437
|
|
|
334
438
|
/**
|
|
@@ -419,12 +523,8 @@ export class OpenAIVoiceClient {
|
|
|
419
523
|
throw await callErrorFromResponse(response);
|
|
420
524
|
}
|
|
421
525
|
|
|
422
|
-
const location = response.headers.get("location") ?? "";
|
|
423
|
-
const callId = location.split("/").pop() ?? "";
|
|
424
526
|
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})`);
|
|
527
|
+
const callId = callIdFromLocation(response.headers.get("location"));
|
|
428
528
|
const quotaHeaders = codexQuotaHeaders(response.headers);
|
|
429
529
|
|
|
430
530
|
const text = await this.runTranscriptionSocket(
|
|
@@ -561,6 +661,185 @@ export class OpenAIVoiceClient {
|
|
|
561
661
|
}
|
|
562
662
|
}
|
|
563
663
|
|
|
664
|
+
/**
|
|
665
|
+
* GPT-Live: exchanges the caller's SDP offer through /realtime/calls and starts watching the
|
|
666
|
+
* call's sideband. Audio flows between the caller's peer and OpenAI; the caller ends the session
|
|
667
|
+
* with {"type":"session.close"} on its data channel.
|
|
668
|
+
*/
|
|
669
|
+
async createLiveCall(
|
|
670
|
+
credentials: OpenAIRealtimeCredentials,
|
|
671
|
+
request: OpenAILiveCallRequest,
|
|
672
|
+
): Promise<OpenAILiveCall> {
|
|
673
|
+
const voice = request.voice ?? OPENAI_LIVE_DEFAULT_VOICE;
|
|
674
|
+
|
|
675
|
+
if (!isOpenAILiveVoice(voice))
|
|
676
|
+
throw new OpenAIVoiceInputError(`unsupported live voice "${voice}"`);
|
|
677
|
+
const correlation = { threadId: crypto.randomUUID(), sessionId: crypto.randomUUID() };
|
|
678
|
+
|
|
679
|
+
const headers = {
|
|
680
|
+
...buildOpenAIRealtimeHeaders(credentials, correlation),
|
|
681
|
+
...OPENAI_LIVE_ALPHA_HEADER,
|
|
682
|
+
};
|
|
683
|
+
|
|
684
|
+
// The caller's signal (its HTTP request) bounds only the exchange, never the session.
|
|
685
|
+
const { signal, dispose } = this.deadline(request.signal, OPENAI_LIVE_CALL_TIMEOUT_MS);
|
|
686
|
+
|
|
687
|
+
try {
|
|
688
|
+
const response = await this.fetchImpl(`${this.callsUrl}?${OPENAI_LIVE_CALLS_QUERY}`, {
|
|
689
|
+
method: "POST",
|
|
690
|
+
headers: { ...headers, "Content-Type": "application/json" },
|
|
691
|
+
body: JSON.stringify({
|
|
692
|
+
sdp: request.sdp,
|
|
693
|
+
session: buildLiveSession({
|
|
694
|
+
voice,
|
|
695
|
+
instructions: request.instructions,
|
|
696
|
+
history: request.history,
|
|
697
|
+
}),
|
|
698
|
+
}),
|
|
699
|
+
signal,
|
|
700
|
+
});
|
|
701
|
+
|
|
702
|
+
if (response.status !== 201) {
|
|
703
|
+
if (response.ok) await response.body?.cancel();
|
|
704
|
+
throw await callErrorFromResponse(response);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
const callId = callIdFromLocation(response.headers.get("location"));
|
|
708
|
+
const sdp = await response.text();
|
|
709
|
+
|
|
710
|
+
return {
|
|
711
|
+
sdp,
|
|
712
|
+
callId,
|
|
713
|
+
quotaHeaders: codexQuotaHeaders(response.headers),
|
|
714
|
+
ended: this.watchLiveSession(`${this.liveWsUrl}/${callId}`, headers, request),
|
|
715
|
+
};
|
|
716
|
+
} catch (error) {
|
|
717
|
+
throw signal.aborted ? this.abortReason(request.signal, signal, error) : error;
|
|
718
|
+
} finally {
|
|
719
|
+
dispose();
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* Follows a live call's sideband until the session ends. It carries the same events as the
|
|
725
|
+
* caller's data channel plus a copy of both audio streams. Finished turns, usage and the other
|
|
726
|
+
* events are kept (audio copies and word-level text are skipped), and delegations are answered
|
|
727
|
+
* through `onDelegation`. Never rejects.
|
|
728
|
+
*/
|
|
729
|
+
private async watchLiveSession(
|
|
730
|
+
url: string,
|
|
731
|
+
headers: Record<string, string>,
|
|
732
|
+
{ onTurn, onDelegation }: Pick<OpenAILiveCallRequest, "onTurn" | "onDelegation">,
|
|
733
|
+
): Promise<OpenAILiveSummary> {
|
|
734
|
+
const signal = AbortSignal.timeout(this.liveWatchLimitMs);
|
|
735
|
+
const socket = this.webSocketFactory(url, { headers });
|
|
736
|
+
const records = socketRecords(socket, signal);
|
|
737
|
+
const startedAt = Date.now();
|
|
738
|
+
const turns: OpenAILiveTurn[] = [];
|
|
739
|
+
const events: OpenAILiveEvent[] = [];
|
|
740
|
+
let audioDurationMs: number | undefined;
|
|
741
|
+
let serverError: string | undefined;
|
|
742
|
+
this.liveSockets.add(socket);
|
|
743
|
+
const keep = (event: JsonValue) => events.push({ atMs: Date.now() - startedAt, event });
|
|
744
|
+
|
|
745
|
+
const ended = (endReason: string, error = serverError): OpenAILiveSummary =>
|
|
746
|
+
error === undefined
|
|
747
|
+
? { turns, events, audioDurationMs, endReason }
|
|
748
|
+
: { turns, events, audioDurationMs, endReason, error };
|
|
749
|
+
|
|
750
|
+
// Runs beside the event loop, which must keep draining the sideband meanwhile.
|
|
751
|
+
const answer = (delegation: OpenAILiveDelegation) => {
|
|
752
|
+
if (!onDelegation) return;
|
|
753
|
+
const asked = Date.now();
|
|
754
|
+
|
|
755
|
+
void onDelegation(delegation)
|
|
756
|
+
.then(async (reply) => {
|
|
757
|
+
await sendJson(socket, liveDelegationAnswerEvent(delegation.itemId, reply));
|
|
758
|
+
// qgrid's own message, logged beside the server's events.
|
|
759
|
+
keep({
|
|
760
|
+
type: "delegation.context.append",
|
|
761
|
+
delegation_item_id: delegation.itemId,
|
|
762
|
+
ms: Date.now() - asked,
|
|
763
|
+
text: reply,
|
|
764
|
+
});
|
|
765
|
+
})
|
|
766
|
+
.catch((error: Error) =>
|
|
767
|
+
keep({
|
|
768
|
+
type: "qgrid.delegation_failed",
|
|
769
|
+
delegation_item_id: delegation.itemId,
|
|
770
|
+
error: error.message,
|
|
771
|
+
}),
|
|
772
|
+
);
|
|
773
|
+
};
|
|
774
|
+
|
|
775
|
+
try {
|
|
776
|
+
await this.awaitOpen(records.next);
|
|
777
|
+
|
|
778
|
+
for (;;) {
|
|
779
|
+
const next = await records.next();
|
|
780
|
+
|
|
781
|
+
if (next.kind === "error") {
|
|
782
|
+
return ended(
|
|
783
|
+
signal.aborted ? "watch limit reached" : "sideband error",
|
|
784
|
+
next.error.message,
|
|
785
|
+
);
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// Without session.closed: the caller dropped its peer (OpenAI ends it about 30 s later).
|
|
789
|
+
if (next.kind === "close") return ended(`sideband closed (${next.code})`);
|
|
790
|
+
|
|
791
|
+
if (next.kind !== "event") continue;
|
|
792
|
+
const type = realtimeServerEvent.safeParse(next.event).data?.type ?? "";
|
|
793
|
+
|
|
794
|
+
if (!LIVE_UNLOGGED_EVENTS.has(type)) keep(next.event);
|
|
795
|
+
const delegation = liveDelegationCreatedEvent.safeParse(next.event);
|
|
796
|
+
|
|
797
|
+
if (delegation.success) {
|
|
798
|
+
const { id, content } = delegation.data.item;
|
|
799
|
+
answer({ itemId: id, text: content.flatMap((part) => part.text ?? []).join("") });
|
|
800
|
+
continue;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
const turn = liveTurnDoneEvent.safeParse(next.event);
|
|
804
|
+
|
|
805
|
+
if (turn.success) {
|
|
806
|
+
const { role, transcript, start_ms, end_ms } = turn.data.turn;
|
|
807
|
+
turns.push({ role, transcript, startMs: start_ms, endMs: end_ms });
|
|
808
|
+
onTurn?.(turns);
|
|
809
|
+
continue;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
const usage = liveUsageUpdatedEvent.safeParse(next.event);
|
|
813
|
+
|
|
814
|
+
if (usage.success) {
|
|
815
|
+
audioDurationMs = usage.data.usage.audio_duration_ms;
|
|
816
|
+
continue;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
const closed = liveSessionClosedEvent.safeParse(next.event);
|
|
820
|
+
|
|
821
|
+
if (closed.success) {
|
|
822
|
+
audioDurationMs = closed.data.usage?.audio_duration_ms ?? audioDurationMs;
|
|
823
|
+
socket.close(1000, "done");
|
|
824
|
+
|
|
825
|
+
return ended(closed.data.reason ?? "closed");
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
serverError = serverErrorFromEvent(next.event)?.message ?? serverError;
|
|
829
|
+
}
|
|
830
|
+
} catch (error) {
|
|
831
|
+
return ended("sideband error", error instanceof Error ? error.message : String(error));
|
|
832
|
+
} finally {
|
|
833
|
+
records.cleanup();
|
|
834
|
+
this.liveSockets.delete(socket);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/** Shutdown: ends every live watcher (each run is then logged with what it saw). */
|
|
839
|
+
closeLiveSessions(): void {
|
|
840
|
+
this.liveSockets.forEach((socket) => socket.terminate());
|
|
841
|
+
}
|
|
842
|
+
|
|
564
843
|
private deadline(caller: AbortSignal | undefined, ms: number) {
|
|
565
844
|
const timeout = AbortSignal.timeout(ms);
|
|
566
845
|
const signal = caller ? AbortSignal.any([caller, timeout]) : timeout;
|