cloud / internal-packages / cloud-ai / src / openai-voice.tsmain at aacbc74
import { waitUntil } from "cloudflare:workers";
import { z } from "zod";
import { type AuthenticatedMind, jsonError } from "./auth.ts";
import {
costOfLiveVoiceSeconds,
costOfRealtimeResponse,
costOfTranscription,
GPT_LIVE_TRANSCRIBE_USD_PER_SECOND,
type OpenAiUsageStore,
roundUsd,
} from "./ledger.ts";
const OPENAI_ORIGIN = "https://api.openai.com";
const MAX_TRANSCRIPTION_BYTES = 25 * 1024 * 1024;
const MAX_JSON_BODY_BYTES = 512 * 1024;
const LIVE_SESSION_HANGUP_PATTERN = /^v1\/live\/sessions\/([A-Za-z0-9_-]{4,120})\/hangup$/;
const TranscriptionJsonResponse = z.looseObject({
usage: z
.looseObject({
type: z.string().optional(),
seconds: z.number().optional(),
input_tokens: z.number().optional(),
output_tokens: z.number().optional(),
input_token_details: z
.looseObject({
text_tokens: z.number().optional(),
audio_tokens: z.number().optional(),
})
.optional(),
})
.optional(),
});
const LiveSessionAnswer = z.looseObject({
session: z.looseObject({ id: z.string().optional() }).optional(),
});
const OpenAiSessionBody = z.looseObject({
type: z.string().optional(),
store: z.boolean().optional(),
audio: z.string().optional(),
response: z.looseObject({ store: z.boolean().optional() }).optional(),
session: z
.looseObject({
store: z.boolean().optional(),
model: z.string().optional(),
audio: z
.looseObject({
format: z.looseObject({ rate: z.number().optional() }).optional(),
input: z
.looseObject({
format: z.looseObject({ rate: z.number().optional() }).optional(),
transcription: z.looseObject({ model: z.string().optional() }).optional(),
})
.optional(),
})
.optional(),
})
.optional(),
});
const RealtimeTokenDetails = z.looseObject({
text_tokens: z.number().optional(),
audio_tokens: z.number().optional(),
cached_tokens: z.number().optional(),
});
const RealtimeServerFrame = z.looseObject({
type: z.string().optional(),
response: z
.looseObject({
model: z.string().optional(),
usage: z
.looseObject({
input_token_details: RealtimeTokenDetails.optional(),
output_token_details: RealtimeTokenDetails.optional(),
})
.optional(),
})
.optional(),
usage: z
.looseObject({
seconds: z.number().optional(),
input_tokens: z.number().optional(),
output_tokens: z.number().optional(),
input_token_details: RealtimeTokenDetails.optional(),
})
.optional(),
});
/** Pluggable WebSocket pair factory so Node Vitest tests can exercise the full frame-level
* WebSocket relay and metering logic without requiring `workerd`'s global `WebSocketPair`. */
export type RelaySocketLike = {
accept?(): void;
send(data: string | ArrayBuffer | Uint8Array): void;
close(code?: number, reason?: string): void;
addEventListener(
type: "message" | "close" | "error",
listener: (event: { data?: unknown; code?: number; reason?: string }) => void,
): void;
};
export type OpenAiVoiceRelayDeps = {
fetcher?: (request: Request) => Promise<Response>;
createSocketPair?: () => { client: WebSocket; server: RelaySocketLike };
now?: () => number;
};
/** Extracts the `api.openai.com` subpath (`v1/audio/transcriptions`, `v1/live/sessions`,
* `v1/realtime`, etc.) when routed through `SecretProxy` (`/capnweb/api.openai.com/<subpath>`)
* or direct `/openai-voice/<subpath>`. */
export function openAiProxySubpathOf(pathname: string): string | null {
const proxyMatch = /^\/capnweb\/api\.openai\.com\/(.+)$/.exec(pathname);
if (proxyMatch?.[1]) return proxyMatch[1];
if (pathname.startsWith("/openai-voice/")) return pathname.slice("/openai-voice/".length);
return null;
}
/** Handles authenticated OpenAI Realtime Voice & Transcription requests lent via Iterate Cloud's
* `OPENAI_API_KEY` (`/secrets/openai` `SecretProxy` -> `/capnweb/api.openai.com/...`), enforcing
* zero-retention (`store !== true`) and recording exact per-mind USD usage in `usageStore`. */
export async function handleOpenAiVoiceOrTranscribe(input: {
request: Request;
url: URL;
subpath: string;
caller: AuthenticatedMind;
openAiApiKey: string | undefined;
usageStore: OpenAiUsageStore;
deps?: OpenAiVoiceRelayDeps;
}): Promise<Response> {
const { request, url, subpath, caller, openAiApiKey, usageStore, deps } = input;
if (!openAiApiKey) {
return jsonError(503, "Iterate Cloud OpenAI voice/transcription key is not configured", {
"retry-after": "5",
});
}
const fetcher = deps?.fetcher || ((req: Request) => fetch(req));
const now = deps?.now || (() => Date.now());
const isUpgrade = request.headers.get("upgrade")?.toLowerCase() === "websocket";
// 1. Batch HTTP transcription (`POST /v1/audio/transcriptions`)
if (request.method === "POST" && subpath === "v1/audio/transcriptions" && !isUpgrade) {
return handleAudioTranscription({ request, caller, openAiApiKey, usageStore, fetcher, now });
}
// 2. WebRTC GPT-Live session creation (`POST /v1/live/sessions`, `core/configs/default/call/outbound.ts`)
if (request.method === "POST" && subpath === "v1/live/sessions" && !isUpgrade) {
return handleWebRtcLiveSessionStart({
request,
caller,
openAiApiKey,
usageStore,
fetcher,
now,
});
}
// 3. WebRTC GPT-Live session hangup (`POST /v1/live/sessions/<id>/hangup`)
const hangupMatch = request.method === "POST" ? LIVE_SESSION_HANGUP_PATTERN.exec(subpath) : null;
if (hangupMatch && !isUpgrade) {
return handleWebRtcLiveSessionHangup({
sessionId: hangupMatch[1]!,
caller,
openAiApiKey,
usageStore,
fetcher,
now,
});
}
// 4. Short-lived Realtime transcription client secret (`POST /v1/realtime/client_secrets`)
if (request.method === "POST" && subpath === "v1/realtime/client_secrets" && !isUpgrade) {
return handleRealtimeClientSecret({
request,
caller,
openAiApiKey,
usageStore,
fetcher,
now,
});
}
// 5. Server/DO WebSocket relays (`GET /v1/live/sessions` and `GET /v1/realtime?...`)
if (
request.method === "GET" &&
isUpgrade &&
(subpath === "v1/live/sessions" || subpath === "v1/realtime")
) {
return handleOpenAiRealtimeWebSocket({
request,
url,
subpath,
caller,
openAiApiKey,
usageStore,
fetcher,
createSocketPair: deps?.createSocketPair,
now,
});
}
return jsonError(
404,
`Unsupported OpenAI voice/transcription route: ${request.method} /${subpath}`,
);
}
async function handleAudioTranscription(input: {
request: Request;
caller: AuthenticatedMind;
openAiApiKey: string;
usageStore: OpenAiUsageStore;
fetcher: (request: Request) => Promise<Response>;
now: () => number;
}): Promise<Response> {
const contentType = input.request.headers.get("content-type") || "";
if (!contentType.toLowerCase().includes("multipart/form-data")) {
return jsonError(400, "v1/audio/transcriptions requires multipart/form-data");
}
const rawBytes = new Uint8Array(await input.request.arrayBuffer());
if (rawBytes.byteLength > MAX_TRANSCRIPTION_BYTES) {
return jsonError(413, "Audio upload exceeds 25 MiB transcription limit");
}
// Parse form fields on a synthetic Request copy so we know `model` and WAV duration fallback
// while forwarding the exact original multipart bytes untouched.
let model = "gpt-4o-mini-transcribe";
let fallbackDurationSeconds = 0;
try {
const form = await new Request("https://api.openai.com/v1/audio/transcriptions", {
method: "POST",
headers: { "content-type": contentType },
body: rawBytes,
}).formData();
const askedModel = form.get("model");
if (typeof askedModel === "string" && askedModel.trim()) model = askedModel.trim();
const fileEntry = form.get("file");
if (fileEntry instanceof Blob) {
const fileBytes = new Uint8Array(await fileEntry.arrayBuffer());
fallbackDurationSeconds = estimateAudioDurationSeconds(fileBytes);
}
} catch {
return jsonError(400, "Invalid multipart/form-data body for v1/audio/transcriptions");
}
const headers = new Headers({
authorization: `Bearer ${input.openAiApiKey}`,
"content-type": contentType,
});
const accept = input.request.headers.get("accept");
if (accept) headers.set("accept", accept);
const upstream = await input.fetcher(
new Request(`${OPENAI_ORIGIN}/v1/audio/transcriptions`, {
method: "POST",
headers,
body: rawBytes,
}),
);
const responseBytes = new Uint8Array(await upstream.arrayBuffer());
if (upstream.ok) {
let textTokensIn: number | undefined;
let audioTokensIn: number | undefined;
let tokensIn: number | undefined;
let tokensOut: number | undefined;
let durationSeconds: number | undefined = fallbackDurationSeconds;
try {
const json = JSON.parse(new TextDecoder().decode(responseBytes)) as unknown;
const parsed = TranscriptionJsonResponse.safeParse(json);
if (parsed.success && parsed.data.usage) {
const u = parsed.data.usage;
tokensIn = u.input_tokens;
tokensOut = u.output_tokens;
textTokensIn = u.input_token_details?.text_tokens;
audioTokensIn = u.input_token_details?.audio_tokens;
if (typeof u.seconds === "number") durationSeconds = u.seconds;
}
} catch {
// Plain-text response formats (`text`, `srt`, `vtt`) carry no JSON `usage`; use WAV/byte duration.
}
const priced = costOfTranscription({
model,
textTokensIn,
audioTokensIn,
tokensIn,
tokensOut,
durationSeconds,
});
waitUntil(
input.usageStore.recordUsage({
mindId: input.caller.mindId,
mindSlug: input.caller.mindSlug,
createdAtMs: input.now(),
kind: "transcription",
route: "POST /v1/audio/transcriptions",
model,
costUsd: priced.costUsd,
audioSeconds: priced.audioSeconds,
tokensIn: priced.tokensIn,
tokensOut: priced.tokensOut,
}),
);
}
return new Response(responseBytes, {
status: upstream.status,
headers: cleanUpstreamHeaders(upstream.headers),
});
}
async function handleWebRtcLiveSessionStart(input: {
request: Request;
caller: AuthenticatedMind;
openAiApiKey: string;
usageStore: OpenAiUsageStore;
fetcher: (request: Request) => Promise<Response>;
now: () => number;
}): Promise<Response> {
const bodyResult = await readBoundedJson(input.request);
if ("error" in bodyResult) return bodyResult.error;
if (hasStorageEnabled(bodyResult.body)) {
return jsonError(400, "OpenAI session storage (`store: true`) is not permitted on lent keys");
}
const sessionModel = bodyResult.body.session?.model?.trim();
const model = sessionModel || "gpt-live-1";
const upstream = await input.fetcher(
new Request(`${OPENAI_ORIGIN}/v1/live/sessions`, {
method: "POST",
headers: {
authorization: `Bearer ${input.openAiApiKey}`,
"content-type": "application/json",
},
body: bodyResult.rawText,
}),
);
const answerText = await upstream.text();
if (upstream.ok) {
try {
const parsed = LiveSessionAnswer.safeParse(JSON.parse(answerText));
const sessionId = parsed.success ? parsed.data.session?.id : undefined;
if (sessionId) {
await input.usageStore.openWebRtcSession({
sessionId,
mindId: input.caller.mindId,
mindSlug: input.caller.mindSlug,
model,
startedAtMs: input.now(),
});
}
} catch {
// Upstream returned non-JSON despite 2xx; forward as-is.
}
}
return new Response(answerText, {
status: upstream.status,
headers: cleanUpstreamHeaders(upstream.headers),
});
}
async function handleWebRtcLiveSessionHangup(input: {
sessionId: string;
caller: AuthenticatedMind;
openAiApiKey: string;
usageStore: OpenAiUsageStore;
fetcher: (request: Request) => Promise<Response>;
now: () => number;
}): Promise<Response> {
const closed = await input.usageStore.closeWebRtcSession({
sessionId: input.sessionId,
mindId: input.caller.mindId,
endedAtMs: input.now(),
});
if (closed.status === "forbidden") {
return jsonError(403, "Live session belongs to another mind");
}
const upstream = await input.fetcher(
new Request(`${OPENAI_ORIGIN}/v1/live/sessions/${input.sessionId}/hangup`, {
method: "POST",
headers: { authorization: `Bearer ${input.openAiApiKey}` },
}),
);
const body = await upstream.text();
return new Response(body, {
status: upstream.status,
headers: cleanUpstreamHeaders(upstream.headers),
});
}
async function handleRealtimeClientSecret(input: {
request: Request;
caller: AuthenticatedMind;
openAiApiKey: string;
usageStore: OpenAiUsageStore;
fetcher: (request: Request) => Promise<Response>;
now: () => number;
}): Promise<Response> {
const bodyResult = await readBoundedJson(input.request);
if ("error" in bodyResult) return bodyResult.error;
if (hasStorageEnabled(bodyResult.body)) {
return jsonError(400, "OpenAI session storage (`store: true`) is not permitted on lent keys");
}
const transcriptionModel = bodyResult.body.session?.audio?.input?.transcription?.model?.trim();
const sessionModel = bodyResult.body.session?.model?.trim();
const model = transcriptionModel || sessionModel || "gpt-live-transcribe";
const upstream = await input.fetcher(
new Request(`${OPENAI_ORIGIN}/v1/realtime/client_secrets`, {
method: "POST",
headers: {
authorization: `Bearer ${input.openAiApiKey}`,
"content-type": "application/json",
},
body: bodyResult.rawText,
}),
);
const answerText = await upstream.text();
if (upstream.ok) {
waitUntil(
input.usageStore.recordUsage({
mindId: input.caller.mindId,
mindSlug: input.caller.mindSlug,
createdAtMs: input.now(),
kind: "transcription",
route: "POST /v1/realtime/client_secrets",
model,
costUsd: 0,
isClientSecretGrant: true,
}),
);
}
return new Response(answerText, {
status: upstream.status,
headers: cleanUpstreamHeaders(upstream.headers),
});
}
async function handleOpenAiRealtimeWebSocket(input: {
request: Request;
url: URL;
subpath: "v1/live/sessions" | "v1/realtime";
caller: AuthenticatedMind;
openAiApiKey: string;
usageStore: OpenAiUsageStore;
fetcher: (request: Request) => Promise<Response>;
createSocketPair?: () => { client: WebSocket; server: RelaySocketLike };
now: () => number;
}): Promise<Response> {
const headers = new Headers({
upgrade: "websocket",
connection: "Upgrade",
authorization: `Bearer ${input.openAiApiKey}`,
});
const openAiBeta = input.request.headers.get("openai-beta");
if (openAiBeta) headers.set("openai-beta", openAiBeta);
const upstreamRes = await input.fetcher(
new Request(`${OPENAI_ORIGIN}/${input.subpath}${input.url.search}`, {
method: "GET",
headers,
}),
);
// Cloudflare Workers attaches `.webSocket` on `101 Switching Protocols` responses (Node's
// `Response` constructor forbids status 101, so `createSocketPair` unit tests attach `.webSocket` on 200).
const upstreamWs = (upstreamRes as Response & { webSocket?: RelaySocketLike }).webSocket;
const upgraded =
Boolean(upstreamWs) &&
(upstreamRes.status === 101 || Boolean(input.createSocketPair && upstreamRes.ok));
if (!upgraded || !upstreamWs) {
return new Response(await upstreamRes.text(), {
status: upstreamRes.status === 101 ? 502 : upstreamRes.status,
headers: cleanUpstreamHeaders(upstreamRes.headers),
});
}
const pair = input.createSocketPair ? input.createSocketPair() : makeWorkersSocketPair();
upstreamWs.accept?.();
pair.server.accept?.();
const isTranscriptionIntent = input.url.searchParams.get("intent") === "transcription";
const isLiveSession = input.subpath === "v1/live/sessions";
let model =
input.url.searchParams.get("model") ||
(isLiveSession ? "gpt-live-1" : isTranscriptionIntent ? "gpt-live-transcribe" : "gpt-realtime");
let activeStartedAtMs: number | null = null;
let appendedPcmBytes = 0;
let sampleRateHz = isLiveSession ? 16_000 : 24_000;
let meteredCostUsd = 0;
let meteredTokensIn = 0;
let meteredTokensOut = 0;
let meteredAudioSeconds = 0;
let settled = false;
const finalize = (closePeer?: () => void) => {
closePeer?.();
if (settled) return;
settled = true;
let costUsd = meteredCostUsd;
let audioSeconds = meteredAudioSeconds;
const kind = isTranscriptionIntent || model.includes("transcribe") ? "transcription" : "voice";
if (isLiveSession && activeStartedAtMs !== null) {
const elapsedSecs = Math.max(0, (input.now() - activeStartedAtMs) / 1000);
audioSeconds = elapsedSecs;
costUsd = costOfLiveVoiceSeconds(elapsedSecs);
} else if (kind === "transcription" && costUsd === 0 && appendedPcmBytes > 0) {
const pcmSecs = appendedPcmBytes / (sampleRateHz * 2);
audioSeconds = pcmSecs;
costUsd = model.includes("gpt-live-transcribe")
? roundUsd(pcmSecs * GPT_LIVE_TRANSCRIBE_USD_PER_SECOND)
: costOfTranscription({ model, durationSeconds: pcmSecs }).costUsd;
}
if (activeStartedAtMs !== null || appendedPcmBytes > 0 || costUsd > 0) {
waitUntil(
input.usageStore.recordUsage({
mindId: input.caller.mindId,
mindSlug: input.caller.mindSlug,
createdAtMs: activeStartedAtMs ?? input.now(),
kind,
route: `GET /${input.subpath}`,
model,
costUsd,
audioSeconds,
tokensIn: meteredTokensIn,
tokensOut: meteredTokensOut,
}),
);
}
};
pair.server.addEventListener("message", (event) => {
const data = event.data;
if (typeof data === "string") {
const inspected = inspectClientSocketFrame(data);
if (inspected.storeEnabled) {
pair.server.close(1008, "store: true is not permitted on lent keys");
upstreamWs.close(1000, "closed");
finalize();
return;
}
if (inspected.model) model = inspected.model;
if (inspected.sampleRateHz) sampleRateHz = inspected.sampleRateHz;
if (inspected.pcmBytes > 0) appendedPcmBytes += inspected.pcmBytes;
if (activeStartedAtMs === null) activeStartedAtMs = input.now();
upstreamWs.send(data);
return;
}
if (data instanceof ArrayBuffer || data instanceof Uint8Array) {
if (activeStartedAtMs === null) activeStartedAtMs = input.now();
upstreamWs.send(data);
}
});
upstreamWs.addEventListener("message", (event) => {
const data = event.data;
if (typeof data === "string") {
pair.server.send(data);
const usageDelta = inspectServerSocketFrame(data, model);
if (usageDelta) {
meteredCostUsd = roundUsd(meteredCostUsd + usageDelta.costUsd);
meteredTokensIn += usageDelta.tokensIn;
meteredTokensOut += usageDelta.tokensOut;
meteredAudioSeconds += usageDelta.audioSeconds;
}
return;
}
if (data instanceof ArrayBuffer || data instanceof Uint8Array) {
pair.server.send(data);
}
});
pair.server.addEventListener("close", (event) => {
finalize(() => safeClose(upstreamWs, event.code, event.reason));
});
pair.server.addEventListener("error", () => {
finalize(() => safeClose(upstreamWs, 1011, "client error"));
});
upstreamWs.addEventListener("close", (event) => {
finalize(() => safeClose(pair.server, event.code, event.reason));
});
upstreamWs.addEventListener("error", () => {
finalize(() => safeClose(pair.server, 1011, "upstream error"));
});
// In Cloudflare Workers, `new Response(null, { status: 101, webSocket })` completes the upgrade;
// in Node tests (`createSocketPair`), `Response` rejects status 101 so return 200 with `.webSocket`.
if (input.createSocketPair) {
const testRes = new Response(null, { status: 200 });
Object.defineProperty(testRes, "webSocket", { value: pair.client });
return testRes;
}
return new Response(null, { status: 101, webSocket: pair.client });
}
function makeWorkersSocketPair(): { client: WebSocket; server: RelaySocketLike } {
const pair = new WebSocketPair();
// `WebSocket` in `workerd` implements `accept`, `send`, `close`, and `addEventListener`, matching
// `RelaySocketLike`, while `@cloudflare/workers-types` overloads `addEventListener` with stricter event classes.
return { client: pair[0], server: pair[1] as unknown as RelaySocketLike };
}
function safeClose(socket: RelaySocketLike, code?: number, reason?: string) {
try {
const safeCode = code && code >= 1000 && code < 5000 ? code : 1000;
socket.close(safeCode, reason ? reason.slice(0, 120) : undefined);
} catch {
// Socket may already be closing.
}
}
function inspectClientSocketFrame(text: string): {
storeEnabled: boolean;
model?: string;
sampleRateHz?: number;
pcmBytes: number;
} {
try {
const parsed = OpenAiSessionBody.safeParse(JSON.parse(text));
if (!parsed.success) return { storeEnabled: false, pcmBytes: 0 };
const frame = parsed.data;
if (hasStorageEnabled(frame)) return { storeEnabled: true, pcmBytes: 0 };
const transcriptionModel = frame.session?.audio?.input?.transcription?.model?.trim();
const sessionModel = frame.session?.model?.trim();
const model = transcriptionModel || sessionModel || undefined;
const rate = frame.session?.audio?.format?.rate ?? frame.session?.audio?.input?.format?.rate;
const sampleRateHz = rate !== undefined && rate >= 8_000 ? rate : undefined;
const pcmBytes =
frame.type === "input_audio_buffer.append" && frame.audio
? Math.floor((frame.audio.length * 3) / 4)
: 0;
return { storeEnabled: false, model, sampleRateHz, pcmBytes };
} catch {
return { storeEnabled: false, pcmBytes: 0 };
}
}
function inspectServerSocketFrame(
text: string,
fallbackModel: string,
): { costUsd: number; tokensIn: number; tokensOut: number; audioSeconds: number } | null {
try {
const parsed = RealtimeServerFrame.safeParse(JSON.parse(text));
if (!parsed.success) return null;
const frame = parsed.data;
if (frame.type === "response.done" && frame.response?.usage) {
const usage = frame.response.usage;
const inDetails = usage.input_token_details;
const outDetails = usage.output_token_details;
const model = frame.response.model || fallbackModel;
return costOfRealtimeResponse({
model,
textTokensIn: nonNegativeNumber(inDetails?.text_tokens),
audioTokensIn: nonNegativeNumber(inDetails?.audio_tokens),
cachedTokensIn: nonNegativeNumber(inDetails?.cached_tokens),
textTokensOut: nonNegativeNumber(outDetails?.text_tokens),
audioTokensOut: nonNegativeNumber(outDetails?.audio_tokens),
});
}
if (frame.type === "conversation.item.input_audio_transcription.completed" && frame.usage) {
const u = frame.usage;
return costOfTranscription({
model: fallbackModel,
textTokensIn: u.input_token_details?.text_tokens,
audioTokensIn: u.input_token_details?.audio_tokens,
tokensIn: u.input_tokens,
tokensOut: u.output_tokens,
durationSeconds: u.seconds,
});
}
return null;
} catch {
return null;
}
}
function nonNegativeNumber(value: number | undefined): number {
return value !== undefined && Number.isFinite(value) && value >= 0 ? value : 0;
}
function hasStorageEnabled(body: z.infer<typeof OpenAiSessionBody>): boolean {
return body.store === true || body.session?.store === true || body.response?.store === true;
}
async function readBoundedJson(
request: Request,
): Promise<{ rawText: string; body: z.infer<typeof OpenAiSessionBody> } | { error: Response }> {
const bytes = new Uint8Array(await request.arrayBuffer());
if (bytes.byteLength > MAX_JSON_BODY_BYTES) {
return { error: jsonError(413, "Request JSON body exceeds size limit") };
}
const rawText = new TextDecoder().decode(bytes);
try {
const parsed = OpenAiSessionBody.safeParse(JSON.parse(rawText));
if (!parsed.success) {
return { error: jsonError(400, "Request body must be a JSON object") };
}
return { rawText, body: parsed.data };
} catch {
return { error: jsonError(400, "Request body must be valid JSON") };
}
}
function cleanUpstreamHeaders(headers: Headers): Headers {
const out = new Headers({ "cache-control": "no-store" });
const contentType = headers.get("content-type");
if (contentType) out.set("content-type", contentType);
const requestId = headers.get("x-request-id");
if (requestId) out.set("x-request-id", requestId);
return out;
}
/** Reads exact PCM WAV header byte-rate (`RIFF....WAVEfmt `) when present, else estimates ~16 KB/s. */
function estimateAudioDurationSeconds(bytes: Uint8Array): number {
if (
bytes.byteLength >= 44 &&
bytes[0] === 0x52 &&
bytes[1] === 0x49 &&
bytes[2] === 0x46 &&
bytes[3] === 0x46 &&
bytes[8] === 0x57 &&
bytes[9] === 0x41 &&
bytes[10] === 0x56 &&
bytes[11] === 0x45
) {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const byteRate = view.getUint32(28, true);
if (byteRate > 0) return Math.max(0, (bytes.byteLength - 44) / byteRate);
}
return bytes.byteLength / 16_000;
}