@cartanova/qgrid-cli 2.15.3 → 2.15.4
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.frame.js +154 -8
- package/bundle/dist/application/qgrid/qgrid.types.js +6 -3
- package/bundle/dist/i18n/en.js +2 -1
- package/bundle/dist/i18n/ko.js +2 -1
- package/bundle/dist/utils/providers/openai/openai-backend-protocol.js +6 -54
- package/bundle/dist/utils/providers/openai/openai-direct-client.js +2 -2
- package/bundle/dist/utils/providers/openai/openai-dispatcher.js +47 -19
- package/bundle/dist/utils/providers/openai/openai-image-generation.js +1 -2
- package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +389 -0
- package/bundle/dist/utils/providers/openai/openai-voice-client.js +456 -0
- package/bundle/src/application/qgrid/qgrid.frame.test.ts +6 -6
- package/bundle/src/application/qgrid/qgrid.frame.ts +213 -9
- package/bundle/src/application/qgrid/qgrid.types.ts +14 -2
- package/bundle/src/application/sonamu.generated.http +2 -0
- package/bundle/src/i18n/en.ts +1 -0
- package/bundle/src/i18n/ko.ts +1 -0
- package/bundle/src/utils/providers/openai/openai-backend-protocol.test.ts +8 -69
- package/bundle/src/utils/providers/openai/openai-backend-protocol.ts +7 -86
- package/bundle/src/utils/providers/openai/openai-direct-client.test.ts +0 -15
- package/bundle/src/utils/providers/openai/openai-direct-client.ts +3 -1
- package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +19 -93
- package/bundle/src/utils/providers/openai/openai-dispatcher.ts +98 -47
- package/bundle/src/utils/providers/openai/openai-image-generation.test.ts +6 -4
- package/bundle/src/utils/providers/openai/openai-image-generation.ts +0 -6
- package/bundle/src/utils/providers/openai/openai-realtime-protocol.ts +550 -0
- package/bundle/src/utils/providers/openai/openai-voice-client.test.ts +576 -0
- package/bundle/src/utils/providers/openai/openai-voice-client.ts +738 -0
- package/bundle/web-dist/client/assets/{index-BakMhnHZ.js → index-CRdZwZsw.js} +3 -3
- package/bundle/web-dist/client/assets/{logs-Dw-GrMuH.js → logs-DyLC_2Rf.js} +1 -1
- package/bundle/web-dist/client/assets/{monit-BaFFiVKs.js → monit-C0hO3Fy6.js} +1 -1
- package/bundle/web-dist/client/assets/{routes-R1xBZYVT.js → routes-DTw4jsHI.js} +1 -1
- package/bundle/web-dist/client/assets/{settings-Bw_NXAx8.js → settings-Dg-1zSMq.js} +1 -1
- package/bundle/web-dist/client/assets/{show-BH7nfFtF.js → show-BmqUEs1O.js} +1 -1
- package/bundle/web-dist/client/assets/{tokens-BPmRr7mD.js → tokens-FQ82u55y.js} +1 -1
- package/bundle/web-dist/client/assets/{use-oauth-login-flow-B_MGbC3a.js → use-oauth-login-flow-BXmbUSjc.js} +1 -1
- package/bundle/web-dist/client/assets/{use-update-token-mutation-Dcq7Yv2R.js → use-update-token-mutation-BWlMl3qg.js} +1 -1
- package/bundle/web-dist/client/index.html +1 -1
- package/bundle/web-dist/server/assets/{logs-6289J29J.js → logs-WZMx5ErO.js} +3 -3
- package/bundle/web-dist/server/assets/{monit-YVvwJuAF.js → monit-Bf6U1Xp5.js} +2 -2
- package/bundle/web-dist/server/assets/{plus-z5Hy__3C.js → plus-BwpfWi3W.js} +1 -1
- package/bundle/web-dist/server/assets/{refresh-cw-CNm0CERy.js → refresh-cw-Xk9nLu8E.js} +1 -1
- package/bundle/web-dist/server/assets/{request-model-DIuPZZwu.js → request-model-ByadPBS5.js} +1 -1
- package/bundle/web-dist/server/assets/{routes-DVWRvqn0.js → routes-WFysbWfc.js} +3 -3
- package/bundle/web-dist/server/assets/{services.generated-CqS8DCjT.js → services.generated-Bej_fJ74.js} +2 -0
- package/bundle/web-dist/server/assets/{settings-CXwnKiMG.js → settings-DnAbfheS.js} +3 -3
- package/bundle/web-dist/server/assets/{show-G1t8dOEh.js → show-DvpdOIGn.js} +2 -2
- package/bundle/web-dist/server/assets/{tokens-Di1vDwm5.js → tokens-CAc4t_kZ.js} +4 -4
- package/bundle/web-dist/server/assets/{use-oauth-login-flow-BUAcW_pK.js → use-oauth-login-flow-Cxm_7Qg6.js} +1 -1
- package/bundle/web-dist/server/assets/{use-update-token-mutation-oH0O0n-g.js → use-update-token-mutation-DnxqIThp.js} +1 -1
- package/bundle/web-dist/server/entry-server.generated.js +8 -8
- package/package.json +1 -1
- package/skills/qgrid/SKILL.md +5 -5
- package/skills/qgrid/references/ai-sdk-provider-contract.md +4 -0
- package/skills/qgrid/references/decision-rationale.md +13 -3
- package/skills/qgrid/references/openai-codex-runtime.md +17 -5
- package/skills/qgrid/references/request-log-run-lifecycle.md +2 -2
- package/skills/qgrid/references/sonamu-api-web-flow.md +1 -1
- package/skills/qgrid/references/verification-and-debugging.md +3 -3
|
@@ -0,0 +1,738 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import { type ClientRequest } from "node:http";
|
|
3
|
+
|
|
4
|
+
import WsClient, { type RawData } from "ws";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
import { type JsonValue, OpenAIProtocolError } from "./openai-backend-protocol";
|
|
8
|
+
import { type OpenAIWebSocketFactory, type OpenAIWebSocketLike } from "./openai-direct-client";
|
|
9
|
+
import {
|
|
10
|
+
audioAppendEvent,
|
|
11
|
+
audioCommitEvent,
|
|
12
|
+
buildOpenAIRealtimeHeaders,
|
|
13
|
+
buildSpeechInstructions,
|
|
14
|
+
buildSpeechSession,
|
|
15
|
+
buildTranscriptionSession,
|
|
16
|
+
isOpenAIRealtimeVoice,
|
|
17
|
+
OPENAI_REALTIME_CALLS_URL,
|
|
18
|
+
OPENAI_REALTIME_DEFAULT_SPEECH_MODEL,
|
|
19
|
+
OPENAI_REALTIME_DEFAULT_TRANSCRIPTION_MODEL,
|
|
20
|
+
OPENAI_REALTIME_DEFAULT_VOICE,
|
|
21
|
+
OPENAI_REALTIME_SAMPLE_RATE,
|
|
22
|
+
OPENAI_REALTIME_SYNTHETIC_SDP,
|
|
23
|
+
OPENAI_REALTIME_WS_URL,
|
|
24
|
+
OPENAI_TRANSCRIPTION_MODELS_WITHOUT_PROMPT,
|
|
25
|
+
type OpenAIRealtimeCredentials,
|
|
26
|
+
type OpenAIRealtimeHeaders,
|
|
27
|
+
outputAudioDeltaEvent,
|
|
28
|
+
outputAudioTranscriptDoneEvent,
|
|
29
|
+
prepareRealtimeInput,
|
|
30
|
+
realtimeErrorEvent,
|
|
31
|
+
realtimeServerEvent,
|
|
32
|
+
responseCreateEvent,
|
|
33
|
+
responseDoneEvent,
|
|
34
|
+
sessionUpdateEvent,
|
|
35
|
+
speechScriptItemEvent,
|
|
36
|
+
transcriptionCompletedEvent,
|
|
37
|
+
transcriptionFailedEvent,
|
|
38
|
+
UnsupportedAudioError,
|
|
39
|
+
wrapPcmAsWav,
|
|
40
|
+
} from "./openai-realtime-protocol";
|
|
41
|
+
|
|
42
|
+
// One-shot speech-to-text and text-to-speech over OpenAI realtime sessions with a ChatGPT
|
|
43
|
+
// subscription token. Transport shapes and their Codex sources are documented in
|
|
44
|
+
// openai-realtime-protocol.ts. Nothing here is retried: a realtime session that failed may
|
|
45
|
+
// already have consumed audio tokens.
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A /realtime/calls session with no ICE connection is torn down about 30 s after creation
|
|
49
|
+
* (observed 2026-10-17: 25 s idle fine, 31 s gone). The sideband must open, stream, and
|
|
50
|
+
* receive the transcript inside that window; 25 s leaves margin for the POST itself.
|
|
51
|
+
*/
|
|
52
|
+
export const OPENAI_STT_DEADLINE_MS = 25_000;
|
|
53
|
+
|
|
54
|
+
/** The direct transcription socket has no observed teardown; this bounds a hung fallback. */
|
|
55
|
+
export const OPENAI_STT_FALLBACK_TIMEOUT_MS = 60_000;
|
|
56
|
+
export const OPENAI_TTS_TIMEOUT_MS = 60_000;
|
|
57
|
+
|
|
58
|
+
/** One second of 24 kHz mono PCM16 per input_audio_buffer.append. */
|
|
59
|
+
const APPEND_CHUNK_BYTES = OPENAI_REALTIME_SAMPLE_RATE * 2;
|
|
60
|
+
const MAX_BUFFERED_EVENTS = 4096;
|
|
61
|
+
|
|
62
|
+
export interface OpenAIVoiceClientOptions {
|
|
63
|
+
fetch?: typeof fetch;
|
|
64
|
+
webSocketFactory?: OpenAIWebSocketFactory;
|
|
65
|
+
callsUrl?: string;
|
|
66
|
+
realtimeWsUrl?: string;
|
|
67
|
+
sttDeadlineMs?: number;
|
|
68
|
+
/** Retry once on the direct transcription socket when the /calls session is torn down. */
|
|
69
|
+
sttDirectFallback?: boolean;
|
|
70
|
+
sttFallbackTimeoutMs?: number;
|
|
71
|
+
ttsTimeoutMs?: number;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface OpenAITranscribeRequest {
|
|
75
|
+
audio: Uint8Array;
|
|
76
|
+
mediaType: string;
|
|
77
|
+
model?: string;
|
|
78
|
+
language?: string;
|
|
79
|
+
prompt?: string;
|
|
80
|
+
signal?: AbortSignal;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export type OpenAITranscriptionTransport = "realtime-calls" | "realtime-ws";
|
|
84
|
+
|
|
85
|
+
export interface OpenAITranscription {
|
|
86
|
+
text: string;
|
|
87
|
+
/** Computed from the PCM sent, not reported by the server. */
|
|
88
|
+
durationSec: number;
|
|
89
|
+
/** Set on the Codex /calls path; undefined after the direct-socket fallback. */
|
|
90
|
+
callId: string | undefined;
|
|
91
|
+
/** x-codex-* quota headers from the /calls response; empty after the fallback. */
|
|
92
|
+
quotaHeaders: CodexQuotaHeaders;
|
|
93
|
+
transport: OpenAITranscriptionTransport;
|
|
94
|
+
/** Why the /calls attempt was abandoned, when the fallback ran. */
|
|
95
|
+
fallbackReason: string | undefined;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export interface OpenAISpeakRequest {
|
|
99
|
+
text: string;
|
|
100
|
+
model?: string;
|
|
101
|
+
voice?: string;
|
|
102
|
+
instructions?: string;
|
|
103
|
+
format?: "wav" | "pcm";
|
|
104
|
+
signal?: AbortSignal;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface OpenAISpeechResult {
|
|
108
|
+
audio: Uint8Array;
|
|
109
|
+
mediaType: string;
|
|
110
|
+
/** What the model said, from response.output_audio_transcript.done; compare with the input. */
|
|
111
|
+
transcript: string;
|
|
112
|
+
usage: { textTokens: number; audioTokens: number; inputTokens: number; outputTokens: number };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export class OpenAIVoiceInputError extends Error {
|
|
116
|
+
constructor(message: string, options?: ErrorOptions) {
|
|
117
|
+
super(message, options);
|
|
118
|
+
this.name = "OpenAIVoiceInputError";
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
type SocketRecord =
|
|
123
|
+
| { kind: "open" }
|
|
124
|
+
| { kind: "event"; event: JsonValue }
|
|
125
|
+
| { kind: "close"; code: number; reason: string }
|
|
126
|
+
| { kind: "error"; error: Error }
|
|
127
|
+
| { kind: "rejected"; status?: number };
|
|
128
|
+
|
|
129
|
+
function rawDataText(data: RawData): string {
|
|
130
|
+
if (Array.isArray(data)) return Buffer.concat(data).toString();
|
|
131
|
+
|
|
132
|
+
if (data instanceof ArrayBuffer) return Buffer.from(new Uint8Array(data)).toString();
|
|
133
|
+
|
|
134
|
+
return Buffer.from(data).toString();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function abortError(signal: AbortSignal): Error {
|
|
138
|
+
return signal.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Buffers socket records so the caller can await them in order; cleanup drops the listeners. */
|
|
142
|
+
function socketRecords(socket: OpenAIWebSocketLike, signal: AbortSignal) {
|
|
143
|
+
const records: SocketRecord[] = [];
|
|
144
|
+
const waiters: Array<(record: SocketRecord) => void> = [];
|
|
145
|
+
let active = true;
|
|
146
|
+
|
|
147
|
+
const push = (record: SocketRecord) => {
|
|
148
|
+
if (!active) return;
|
|
149
|
+
const waiter = waiters.shift();
|
|
150
|
+
|
|
151
|
+
if (waiter) waiter(record);
|
|
152
|
+
else if (records.length < MAX_BUFFERED_EVENTS) records.push(record);
|
|
153
|
+
else {
|
|
154
|
+
active = false;
|
|
155
|
+
socket.terminate();
|
|
156
|
+
records.length = 0;
|
|
157
|
+
records.push({
|
|
158
|
+
kind: "error",
|
|
159
|
+
error: new OpenAIProtocolError("realtime socket exceeded the receive buffer"),
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const onOpen = () => push({ kind: "open" });
|
|
165
|
+
|
|
166
|
+
const onMessage = (data: RawData, isBinary: boolean) => {
|
|
167
|
+
if (isBinary) {
|
|
168
|
+
push({ kind: "error", error: new OpenAIProtocolError("realtime socket sent binary data") });
|
|
169
|
+
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
let parsed: unknown;
|
|
174
|
+
|
|
175
|
+
try {
|
|
176
|
+
parsed = JSON.parse(rawDataText(data));
|
|
177
|
+
} catch {
|
|
178
|
+
push({ kind: "error", error: new OpenAIProtocolError("realtime socket sent invalid JSON") });
|
|
179
|
+
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const event = jsonValueSchema.safeParse(parsed);
|
|
184
|
+
|
|
185
|
+
if (event.success) push({ kind: "event", event: event.data });
|
|
186
|
+
else push({ kind: "error", error: new OpenAIProtocolError("realtime event is not JSON") });
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
const onClose = (code: number, reason: Buffer) =>
|
|
190
|
+
push({ kind: "close", code, reason: reason.toString() });
|
|
191
|
+
|
|
192
|
+
const onError = (error: Error) => push({ kind: "error", error });
|
|
193
|
+
|
|
194
|
+
const onUnexpectedResponse = (_request: ClientRequest, response: { statusCode?: number }) =>
|
|
195
|
+
push({ kind: "rejected", status: response.statusCode });
|
|
196
|
+
|
|
197
|
+
const onAbort = () => {
|
|
198
|
+
socket.terminate();
|
|
199
|
+
push({ kind: "error", error: abortError(signal) });
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
socket.on("open", onOpen);
|
|
203
|
+
socket.on("message", onMessage);
|
|
204
|
+
socket.on("close", onClose);
|
|
205
|
+
socket.on("error", onError);
|
|
206
|
+
socket.on("unexpected-response", onUnexpectedResponse);
|
|
207
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
next: (): Promise<SocketRecord> => {
|
|
211
|
+
const buffered = records.shift();
|
|
212
|
+
|
|
213
|
+
return buffered
|
|
214
|
+
? Promise.resolve(buffered)
|
|
215
|
+
: new Promise<SocketRecord>((resolve) => waiters.push(resolve));
|
|
216
|
+
},
|
|
217
|
+
cleanup: () => {
|
|
218
|
+
active = false;
|
|
219
|
+
signal.removeEventListener("abort", onAbort);
|
|
220
|
+
socket.off("open", onOpen);
|
|
221
|
+
socket.off("message", onMessage);
|
|
222
|
+
socket.off("close", onClose);
|
|
223
|
+
// The error listener stays: terminate() on a connecting socket emits "error" next tick.
|
|
224
|
+
socket.off("unexpected-response", onUnexpectedResponse);
|
|
225
|
+
records.length = 0;
|
|
226
|
+
|
|
227
|
+
const closed: SocketRecord = {
|
|
228
|
+
kind: "error",
|
|
229
|
+
error: new OpenAIProtocolError("realtime socket record stream was closed"),
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
for (const waiter of waiters.splice(0)) waiter(closed);
|
|
233
|
+
},
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>
|
|
238
|
+
z.union([
|
|
239
|
+
z.string(),
|
|
240
|
+
z.number(),
|
|
241
|
+
z.boolean(),
|
|
242
|
+
z.null(),
|
|
243
|
+
z.array(jsonValueSchema),
|
|
244
|
+
z.record(z.string(), jsonValueSchema),
|
|
245
|
+
]),
|
|
246
|
+
);
|
|
247
|
+
|
|
248
|
+
function serverErrorFromEvent(event: JsonValue): OpenAIProtocolError | undefined {
|
|
249
|
+
const parsed = realtimeErrorEvent.safeParse(event);
|
|
250
|
+
|
|
251
|
+
if (!parsed.success) return undefined;
|
|
252
|
+
const detail = parsed.data.error;
|
|
253
|
+
|
|
254
|
+
return new OpenAIProtocolError(
|
|
255
|
+
detail?.message ?? "realtime server error",
|
|
256
|
+
detail?.code ?? detail?.type ?? undefined,
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function sendJson(socket: OpenAIWebSocketLike, event: JsonValue): Promise<void> {
|
|
261
|
+
return new Promise((resolve, reject) => {
|
|
262
|
+
socket.send(JSON.stringify(event), (error) => (error ? reject(error) : resolve()));
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** x-codex-* response headers, lower-cased, as the dispatcher's quota tracker reads them. */
|
|
267
|
+
export type CodexQuotaHeaders = ReadonlyMap<string, string>;
|
|
268
|
+
|
|
269
|
+
function codexQuotaHeaders(headers: Headers): CodexQuotaHeaders {
|
|
270
|
+
const out = new Map<string, string>();
|
|
271
|
+
|
|
272
|
+
headers.forEach((value, key) => {
|
|
273
|
+
if (key.toLowerCase().startsWith("x-codex-")) out.set(key.toLowerCase(), value);
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
return out;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// chatgpt.com answers errors as {"detail": "..."} or {"detail": {"message": "..."}}.
|
|
280
|
+
const callErrorBody = z.object({
|
|
281
|
+
detail: z.union([
|
|
282
|
+
z.string().transform((message) => ({ message })),
|
|
283
|
+
z.looseObject({ message: z.string().optional() }),
|
|
284
|
+
]),
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
function parseCallErrorMessage(text: string): string | undefined {
|
|
288
|
+
let json: JsonValue;
|
|
289
|
+
|
|
290
|
+
try {
|
|
291
|
+
json = jsonValueSchema.parse(JSON.parse(text));
|
|
292
|
+
} catch {
|
|
293
|
+
return undefined;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const parsed = callErrorBody.safeParse(json);
|
|
297
|
+
|
|
298
|
+
return parsed.success ? parsed.data.detail.message : undefined;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function callErrorFromResponse(response: Response): Promise<OpenAIProtocolError> {
|
|
302
|
+
const text = await response.text().catch(() => "");
|
|
303
|
+
|
|
304
|
+
const message =
|
|
305
|
+
parseCallErrorMessage(text) ?? text ?? response.statusText ?? `HTTP ${response.status}`;
|
|
306
|
+
|
|
307
|
+
return new OpenAIProtocolError(`realtime call rejected: ${message}`, undefined, response.status);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export class OpenAIVoiceClient {
|
|
311
|
+
private readonly fetchImpl: typeof fetch;
|
|
312
|
+
private readonly webSocketFactory: OpenAIWebSocketFactory;
|
|
313
|
+
private readonly callsUrl: string;
|
|
314
|
+
private readonly realtimeWsUrl: string;
|
|
315
|
+
private readonly sttDeadlineMs: number;
|
|
316
|
+
private readonly sttDirectFallback: boolean;
|
|
317
|
+
private readonly sttFallbackTimeoutMs: number;
|
|
318
|
+
private readonly ttsTimeoutMs: number;
|
|
319
|
+
|
|
320
|
+
constructor(options: OpenAIVoiceClientOptions = {}) {
|
|
321
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
322
|
+
this.webSocketFactory =
|
|
323
|
+
options.webSocketFactory ?? ((url, wsOptions) => new WsClient(url, wsOptions));
|
|
324
|
+
this.callsUrl = options.callsUrl ?? OPENAI_REALTIME_CALLS_URL;
|
|
325
|
+
this.realtimeWsUrl = options.realtimeWsUrl ?? OPENAI_REALTIME_WS_URL;
|
|
326
|
+
this.sttDeadlineMs = options.sttDeadlineMs ?? OPENAI_STT_DEADLINE_MS;
|
|
327
|
+
this.sttDirectFallback = options.sttDirectFallback ?? true;
|
|
328
|
+
this.sttFallbackTimeoutMs = options.sttFallbackTimeoutMs ?? OPENAI_STT_FALLBACK_TIMEOUT_MS;
|
|
329
|
+
this.ttsTimeoutMs = options.ttsTimeoutMs ?? OPENAI_TTS_TIMEOUT_MS;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* STT, Codex /calls shape: POST {sdp, session} → 201 + Location rtc_…, sideband WebSocket,
|
|
334
|
+
* session.update (language/prompt, manual commit), append PCM, commit, await the transcript.
|
|
335
|
+
*/
|
|
336
|
+
async transcribe(
|
|
337
|
+
credentials: OpenAIRealtimeCredentials,
|
|
338
|
+
request: OpenAITranscribeRequest,
|
|
339
|
+
): Promise<OpenAITranscription> {
|
|
340
|
+
if (request.audio.byteLength === 0) throw new OpenAIVoiceInputError("audio must not be empty");
|
|
341
|
+
let pcm: Uint8Array;
|
|
342
|
+
|
|
343
|
+
try {
|
|
344
|
+
pcm = prepareRealtimeInput(request.audio, request.mediaType);
|
|
345
|
+
} catch (error) {
|
|
346
|
+
if (error instanceof UnsupportedAudioError) throw new OpenAIVoiceInputError(error.message);
|
|
347
|
+
throw error;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
if (pcm.byteLength === 0) throw new OpenAIVoiceInputError("audio contains no samples");
|
|
351
|
+
const model = request.model ?? OPENAI_REALTIME_DEFAULT_TRANSCRIPTION_MODEL;
|
|
352
|
+
|
|
353
|
+
if (request.prompt !== undefined && OPENAI_TRANSCRIPTION_MODELS_WITHOUT_PROMPT.has(model))
|
|
354
|
+
throw new OpenAIVoiceInputError(`${model} does not accept a prompt`);
|
|
355
|
+
const correlation = { threadId: crypto.randomUUID(), sessionId: crypto.randomUUID() };
|
|
356
|
+
const headers = buildOpenAIRealtimeHeaders(credentials, correlation);
|
|
357
|
+
|
|
358
|
+
const session = buildTranscriptionSession({
|
|
359
|
+
model,
|
|
360
|
+
language: request.language,
|
|
361
|
+
prompt: request.prompt,
|
|
362
|
+
manualCommit: true,
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
const durationSec = pcm.byteLength / (OPENAI_REALTIME_SAMPLE_RATE * 2);
|
|
366
|
+
|
|
367
|
+
try {
|
|
368
|
+
const viaCalls = await this.transcribeViaCalls(headers, model, session, pcm, request.signal);
|
|
369
|
+
|
|
370
|
+
return { ...viaCalls, durationSec, transport: "realtime-calls", fallbackReason: undefined };
|
|
371
|
+
} catch (error) {
|
|
372
|
+
if (!(error instanceof Error) || !this.sttDirectFallback || !isSidebandTeardownError(error))
|
|
373
|
+
throw error;
|
|
374
|
+
// The /calls session was reclaimed before the transcript arrived (about 30 s after creation
|
|
375
|
+
// with no RTP). Retry once on the direct transcription socket, which has no such window.
|
|
376
|
+
const fallbackReason = error.message;
|
|
377
|
+
const viaDirect = await this.transcribeViaDirectSocket(headers, session, pcm, request.signal);
|
|
378
|
+
|
|
379
|
+
return {
|
|
380
|
+
...viaDirect,
|
|
381
|
+
durationSec,
|
|
382
|
+
callId: undefined,
|
|
383
|
+
quotaHeaders: new Map(),
|
|
384
|
+
transport: "realtime-ws",
|
|
385
|
+
fallbackReason,
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Codex subscription path: POST /realtime/calls, then the sideband socket for that call. */
|
|
391
|
+
private async transcribeViaCalls(
|
|
392
|
+
headers: OpenAIRealtimeHeaders,
|
|
393
|
+
model: string,
|
|
394
|
+
session: JsonValue,
|
|
395
|
+
pcm: Uint8Array,
|
|
396
|
+
callerSignal: AbortSignal | undefined,
|
|
397
|
+
): Promise<{ text: string; callId: string; quotaHeaders: CodexQuotaHeaders }> {
|
|
398
|
+
const { signal, dispose } = this.deadline(callerSignal, this.sttDeadlineMs);
|
|
399
|
+
|
|
400
|
+
try {
|
|
401
|
+
// The /calls body is Codex's exact transcription session; per-request fields follow on
|
|
402
|
+
// the sideband so the create request stays byte-compatible with Codex.
|
|
403
|
+
const callBody = {
|
|
404
|
+
sdp: OPENAI_REALTIME_SYNTHETIC_SDP,
|
|
405
|
+
session: buildTranscriptionSession({ model }),
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
const response = await this.fetchImpl(this.callsUrl, {
|
|
409
|
+
method: "POST",
|
|
410
|
+
headers: { ...headers, "Content-Type": "application/json" },
|
|
411
|
+
body: JSON.stringify(callBody),
|
|
412
|
+
signal,
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
if (response.status !== 201) {
|
|
416
|
+
if (response.ok) await response.body?.cancel();
|
|
417
|
+
throw await callErrorFromResponse(response);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const location = response.headers.get("location") ?? "";
|
|
421
|
+
const callId = location.split("/").pop() ?? "";
|
|
422
|
+
await response.body?.cancel();
|
|
423
|
+
|
|
424
|
+
if (!/^rtc_[A-Za-z0-9_-]+$/.test(callId))
|
|
425
|
+
throw new OpenAIProtocolError(`realtime call returned no call id (Location: ${location})`);
|
|
426
|
+
const quotaHeaders = codexQuotaHeaders(response.headers);
|
|
427
|
+
|
|
428
|
+
const text = await this.runTranscriptionSocket(
|
|
429
|
+
`${this.realtimeWsUrl}?call_id=${encodeURIComponent(callId)}`,
|
|
430
|
+
headers,
|
|
431
|
+
session,
|
|
432
|
+
pcm,
|
|
433
|
+
signal,
|
|
434
|
+
callerSignal,
|
|
435
|
+
);
|
|
436
|
+
|
|
437
|
+
return { text, callId, quotaHeaders };
|
|
438
|
+
} catch (error) {
|
|
439
|
+
throw signal.aborted ? this.abortReason(callerSignal, signal, error) : error;
|
|
440
|
+
} finally {
|
|
441
|
+
dispose();
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Direct transcription socket (wss://api.openai.com/v1/realtime?intent=transcription). Not a
|
|
447
|
+
* Codex path: Codex treats this socket as API-key-only, so it is used only as the fallback.
|
|
448
|
+
*/
|
|
449
|
+
private async transcribeViaDirectSocket(
|
|
450
|
+
headers: OpenAIRealtimeHeaders,
|
|
451
|
+
session: JsonValue,
|
|
452
|
+
pcm: Uint8Array,
|
|
453
|
+
callerSignal: AbortSignal | undefined,
|
|
454
|
+
): Promise<{ text: string }> {
|
|
455
|
+
const { signal, dispose } = this.deadline(callerSignal, this.sttFallbackTimeoutMs);
|
|
456
|
+
|
|
457
|
+
try {
|
|
458
|
+
const text = await this.runTranscriptionSocket(
|
|
459
|
+
`${this.realtimeWsUrl}?intent=transcription`,
|
|
460
|
+
headers,
|
|
461
|
+
session,
|
|
462
|
+
pcm,
|
|
463
|
+
signal,
|
|
464
|
+
callerSignal,
|
|
465
|
+
);
|
|
466
|
+
|
|
467
|
+
return { text };
|
|
468
|
+
} catch (error) {
|
|
469
|
+
throw signal.aborted ? this.abortReason(callerSignal, signal, error) : error;
|
|
470
|
+
} finally {
|
|
471
|
+
dispose();
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** session.update → append PCM → commit → await the completed transcript. */
|
|
476
|
+
private async runTranscriptionSocket(
|
|
477
|
+
url: string,
|
|
478
|
+
headers: OpenAIRealtimeHeaders,
|
|
479
|
+
session: JsonValue,
|
|
480
|
+
pcm: Uint8Array,
|
|
481
|
+
signal: AbortSignal,
|
|
482
|
+
callerSignal: AbortSignal | undefined,
|
|
483
|
+
): Promise<string> {
|
|
484
|
+
const socket = this.webSocketFactory(url, { headers });
|
|
485
|
+
const records = socketRecords(socket, signal);
|
|
486
|
+
|
|
487
|
+
try {
|
|
488
|
+
await this.awaitOpen(records.next);
|
|
489
|
+
await sendJson(socket, sessionUpdateEvent(session));
|
|
490
|
+
await this.streamPcm(socket, pcm);
|
|
491
|
+
await sendJson(socket, audioCommitEvent());
|
|
492
|
+
const text = await this.awaitTranscript(records.next);
|
|
493
|
+
socket.close(1000, "done");
|
|
494
|
+
|
|
495
|
+
return text;
|
|
496
|
+
} catch (error) {
|
|
497
|
+
socket.terminate();
|
|
498
|
+
throw signal.aborted ? this.abortReason(callerSignal, signal, error) : error;
|
|
499
|
+
} finally {
|
|
500
|
+
records.cleanup();
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* TTS over the direct realtime socket: Codex's conversational session (minus tools), one user
|
|
506
|
+
* text item, response.create, then the concatenated response.output_audio.delta payload.
|
|
507
|
+
*/
|
|
508
|
+
async speak(
|
|
509
|
+
credentials: OpenAIRealtimeCredentials,
|
|
510
|
+
request: OpenAISpeakRequest,
|
|
511
|
+
): Promise<OpenAISpeechResult> {
|
|
512
|
+
if (!request.text.trim()) throw new OpenAIVoiceInputError("text must not be empty");
|
|
513
|
+
const voice = request.voice ?? OPENAI_REALTIME_DEFAULT_VOICE;
|
|
514
|
+
|
|
515
|
+
if (!isOpenAIRealtimeVoice(voice))
|
|
516
|
+
throw new OpenAIVoiceInputError(`unsupported voice "${voice}"`);
|
|
517
|
+
const model = request.model ?? OPENAI_REALTIME_DEFAULT_SPEECH_MODEL;
|
|
518
|
+
const format = request.format ?? "wav";
|
|
519
|
+
const correlation = { threadId: crypto.randomUUID(), sessionId: crypto.randomUUID() };
|
|
520
|
+
const headers = buildOpenAIRealtimeHeaders(credentials, correlation);
|
|
521
|
+
const { signal, dispose } = this.deadline(request.signal, this.ttsTimeoutMs);
|
|
522
|
+
|
|
523
|
+
const socket = this.webSocketFactory(
|
|
524
|
+
`${this.realtimeWsUrl}?model=${encodeURIComponent(model)}`,
|
|
525
|
+
{ headers },
|
|
526
|
+
);
|
|
527
|
+
|
|
528
|
+
const records = socketRecords(socket, signal);
|
|
529
|
+
|
|
530
|
+
try {
|
|
531
|
+
await this.awaitOpen(records.next);
|
|
532
|
+
|
|
533
|
+
const session = buildSpeechSession({
|
|
534
|
+
instructions: buildSpeechInstructions(request.instructions),
|
|
535
|
+
voice,
|
|
536
|
+
});
|
|
537
|
+
|
|
538
|
+
await sendJson(socket, sessionUpdateEvent(session));
|
|
539
|
+
await sendJson(socket, speechScriptItemEvent(request.text));
|
|
540
|
+
await sendJson(socket, responseCreateEvent());
|
|
541
|
+
const result = await this.awaitSpeech(records.next);
|
|
542
|
+
socket.close(1000, "done");
|
|
543
|
+
|
|
544
|
+
const pcm = result.audio;
|
|
545
|
+
|
|
546
|
+
return {
|
|
547
|
+
audio: format === "wav" ? wrapPcmAsWav(pcm) : pcm,
|
|
548
|
+
mediaType: format === "wav" ? "audio/wav" : `audio/pcm;rate=${OPENAI_REALTIME_SAMPLE_RATE}`,
|
|
549
|
+
transcript: result.transcript,
|
|
550
|
+
usage: result.usage,
|
|
551
|
+
};
|
|
552
|
+
} catch (error) {
|
|
553
|
+
socket.terminate();
|
|
554
|
+
throw signal.aborted ? this.abortReason(request.signal, signal, error) : error;
|
|
555
|
+
} finally {
|
|
556
|
+
records.cleanup();
|
|
557
|
+
dispose();
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
private deadline(caller: AbortSignal | undefined, ms: number) {
|
|
562
|
+
const timeout = AbortSignal.timeout(ms);
|
|
563
|
+
const signal = caller ? AbortSignal.any([caller, timeout]) : timeout;
|
|
564
|
+
|
|
565
|
+
return { signal, dispose: () => undefined };
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
private abortReason(
|
|
569
|
+
caller: AbortSignal | undefined,
|
|
570
|
+
combined: AbortSignal,
|
|
571
|
+
cause: unknown,
|
|
572
|
+
): Error {
|
|
573
|
+
if (caller?.aborted) return abortError(caller);
|
|
574
|
+
|
|
575
|
+
if (combined.aborted)
|
|
576
|
+
return new OpenAIProtocolError(
|
|
577
|
+
"realtime session timed out",
|
|
578
|
+
"realtime_timeout",
|
|
579
|
+
undefined,
|
|
580
|
+
undefined,
|
|
581
|
+
);
|
|
582
|
+
|
|
583
|
+
return cause instanceof Error ? cause : new Error(String(cause));
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
private async awaitOpen(next: () => Promise<SocketRecord>): Promise<void> {
|
|
587
|
+
const record = await next();
|
|
588
|
+
|
|
589
|
+
switch (record.kind) {
|
|
590
|
+
case "open":
|
|
591
|
+
return;
|
|
592
|
+
case "rejected":
|
|
593
|
+
throw new OpenAIProtocolError(
|
|
594
|
+
`realtime socket handshake rejected${record.status ? ` with HTTP ${record.status}` : ""}`,
|
|
595
|
+
undefined,
|
|
596
|
+
record.status,
|
|
597
|
+
);
|
|
598
|
+
case "error":
|
|
599
|
+
throw record.error;
|
|
600
|
+
case "close":
|
|
601
|
+
throw new OpenAIProtocolError(
|
|
602
|
+
`realtime socket closed before open (${record.code}${record.reason ? `: ${record.reason}` : ""})`,
|
|
603
|
+
);
|
|
604
|
+
case "event":
|
|
605
|
+
throw new OpenAIProtocolError("realtime socket emitted an event before opening");
|
|
606
|
+
default:
|
|
607
|
+
throw new OpenAIProtocolError("realtime socket emitted an unknown record");
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
private async streamPcm(socket: OpenAIWebSocketLike, pcm: Uint8Array): Promise<void> {
|
|
612
|
+
for (let offset = 0; offset < pcm.byteLength; offset += APPEND_CHUNK_BYTES) {
|
|
613
|
+
const chunk = pcm.subarray(offset, Math.min(offset + APPEND_CHUNK_BYTES, pcm.byteLength));
|
|
614
|
+
await sendJson(socket, audioAppendEvent(Buffer.from(chunk).toString("base64")));
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
private async awaitTranscript(next: () => Promise<SocketRecord>): Promise<string> {
|
|
619
|
+
for (;;) {
|
|
620
|
+
const record = await next();
|
|
621
|
+
|
|
622
|
+
if (record.kind === "error") throw record.error;
|
|
623
|
+
|
|
624
|
+
if (record.kind === "rejected")
|
|
625
|
+
throw new OpenAIProtocolError("realtime socket rejected", undefined, record.status);
|
|
626
|
+
|
|
627
|
+
if (record.kind === "close")
|
|
628
|
+
throw new OpenAIProtocolError(
|
|
629
|
+
`realtime socket closed before the transcript (${record.code}${record.reason ? `: ${record.reason}` : ""})`,
|
|
630
|
+
);
|
|
631
|
+
|
|
632
|
+
if (record.kind !== "event") continue;
|
|
633
|
+
const serverError = serverErrorFromEvent(record.event);
|
|
634
|
+
|
|
635
|
+
if (serverError) throw serverError;
|
|
636
|
+
const completed = transcriptionCompletedEvent.safeParse(record.event);
|
|
637
|
+
|
|
638
|
+
if (completed.success) return completed.data.transcript;
|
|
639
|
+
const failed = transcriptionFailedEvent.safeParse(record.event);
|
|
640
|
+
|
|
641
|
+
if (failed.success)
|
|
642
|
+
throw new OpenAIProtocolError(
|
|
643
|
+
failed.data.error?.message ?? "transcription failed",
|
|
644
|
+
failed.data.error?.code ?? undefined,
|
|
645
|
+
);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
private async awaitSpeech(next: () => Promise<SocketRecord>) {
|
|
650
|
+
const chunks: Buffer[] = [];
|
|
651
|
+
let transcript = "";
|
|
652
|
+
|
|
653
|
+
for (;;) {
|
|
654
|
+
const record = await next();
|
|
655
|
+
|
|
656
|
+
if (record.kind === "error") throw record.error;
|
|
657
|
+
|
|
658
|
+
if (record.kind === "rejected")
|
|
659
|
+
throw new OpenAIProtocolError("realtime socket rejected", undefined, record.status);
|
|
660
|
+
|
|
661
|
+
if (record.kind === "close")
|
|
662
|
+
throw new OpenAIProtocolError(
|
|
663
|
+
`realtime socket closed before response.done (${record.code}${record.reason ? `: ${record.reason}` : ""})`,
|
|
664
|
+
);
|
|
665
|
+
|
|
666
|
+
if (record.kind !== "event") continue;
|
|
667
|
+
const serverError = serverErrorFromEvent(record.event);
|
|
668
|
+
|
|
669
|
+
if (serverError) throw serverError;
|
|
670
|
+
const delta = outputAudioDeltaEvent.safeParse(record.event);
|
|
671
|
+
|
|
672
|
+
if (delta.success) {
|
|
673
|
+
chunks.push(Buffer.from(delta.data.delta, "base64"));
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
const transcriptDone = outputAudioTranscriptDoneEvent.safeParse(record.event);
|
|
678
|
+
|
|
679
|
+
if (transcriptDone.success) {
|
|
680
|
+
transcript = transcriptDone.data.transcript;
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const done = responseDoneEvent.safeParse(record.event);
|
|
685
|
+
|
|
686
|
+
if (!done.success) continue;
|
|
687
|
+
const status = done.data.response?.status;
|
|
688
|
+
|
|
689
|
+
if (status !== undefined && status !== "completed")
|
|
690
|
+
throw new OpenAIProtocolError(
|
|
691
|
+
`realtime response ${status}: ${JSON.stringify(done.data.response?.status_details ?? null)}`,
|
|
692
|
+
`realtime_response_${status}`,
|
|
693
|
+
);
|
|
694
|
+
const audio = new Uint8Array(Buffer.concat(chunks));
|
|
695
|
+
|
|
696
|
+
if (audio.byteLength === 0)
|
|
697
|
+
throw new OpenAIProtocolError("realtime response carried no audio");
|
|
698
|
+
const usage = done.data.response?.usage;
|
|
699
|
+
|
|
700
|
+
return {
|
|
701
|
+
audio,
|
|
702
|
+
transcript,
|
|
703
|
+
usage: {
|
|
704
|
+
textTokens: usage?.output_token_details?.text_tokens ?? 0,
|
|
705
|
+
audioTokens: usage?.output_token_details?.audio_tokens ?? 0,
|
|
706
|
+
inputTokens: usage?.input_tokens ?? 0,
|
|
707
|
+
outputTokens: usage?.output_tokens ?? 0,
|
|
708
|
+
},
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* Failures that mean the /calls session was reclaimed (or never reachable) rather than that the
|
|
716
|
+
* request was wrong: the 25 s deadline, the sideband closing or erroring before the transcript, a
|
|
717
|
+
* rejected sideband handshake. Server `error` events and /calls 4xx are not teardown and never
|
|
718
|
+
* trigger the fallback.
|
|
719
|
+
*/
|
|
720
|
+
export function isSidebandTeardownError(error: Error): boolean {
|
|
721
|
+
if (!(error instanceof OpenAIProtocolError)) return false;
|
|
722
|
+
|
|
723
|
+
if (error.code === "realtime_timeout") return true;
|
|
724
|
+
|
|
725
|
+
if (error.code !== undefined) return false;
|
|
726
|
+
|
|
727
|
+
return /closed before|handshake rejected|closed before open|record stream was closed/.test(
|
|
728
|
+
error.message,
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/** Used by the dispatcher's single 401 → refresh → retry step. */
|
|
733
|
+
export function isUnauthorizedRealtimeError(error: Error): boolean {
|
|
734
|
+
return error instanceof OpenAIProtocolError && error.status === 401;
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/** Event schema export for tests that replay captured server traffic. */
|
|
738
|
+
export { realtimeServerEvent };
|