openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
722 lines (721 loc) • 25.9 kB
JavaScript
import { C as XAI_REALTIME_WS_MAX_PAYLOAD_BYTES, D as serializeXaiRealtimeToolResult, E as readXaiRealtimeErrorDetail, O as toXaiRealtimeWsUrl, S as XAI_REALTIME_NO_ACTIVE_RESPONSE_CANCEL_ERROR, T as normalizeXaiRealtimeProviderConfig, _ as XAI_REALTIME_CONNECT_TIMEOUT_MS, b as XAI_REALTIME_INPUT_TRANSCRIPTION_MODEL, d as createXaiRealtimeVoiceProviderMetadata, g as XAI_REALTIME_BASE_RECONNECT_DELAY_MS, h as XAI_REALTIME_ACTIVE_RESPONSE_ERROR_PREFIX, s as assertXaiRealtimeVoiceRequestSupported, v as XAI_REALTIME_DEFAULT_MODEL, w as normalizeXaiRealtimeBaseUrl, x as XAI_REALTIME_MAX_PENDING_PLAYBACK_MARKS, y as XAI_REALTIME_DEFAULT_VAD_THRESHOLD } from "./capability-provider-metadata-factory-CKRz8kw4.mjs";
import { t as xaiUserAgentHeaderFor } from "./xai-user-agent-DETyZ1LS.mjs";
import { t as WebSocket } from "./ws-runtime-BC0VsR8N.mjs";
import { isRecord, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
import { REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ, RealtimeVoiceSessionLifecycle, RealtimeVoiceWebSocketTransport, canonicalizeBase64, normalizeRealtimeVoiceResponseOutcome, realtimeVoiceAudioDurationMs, toOpenAICompatibleRealtimeAudioFormat } from "openclaw/plugin-sdk/realtime-voice-provider";
import { resolveAgentDir } from "openclaw/plugin-sdk/agent-scope-runtime";
import { isProviderAuthProfileConfigured, isProviderAuthProfileConfiguredAsync } from "openclaw/plugin-sdk/provider-auth";
import { resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
import * as proxyCaptureSdk from "openclaw/plugin-sdk/proxy-capture";
import { randomUUID } from "node:crypto";
//#region extensions/xai/realtime-voice-auth.runtime.ts
async function resolveXaiRealtimeApiKey(e, t, n) {
const r = normalizeOptionalString(e) ?? normalizeOptionalString(process.env.XAI_API_KEY);
if (r) return r;
const i = await resolveApiKeyForProvider({
provider: "xai",
cfg: t,
...t && n ? { agentDir: resolveAgentDir(t, n) } : {}
});
const a = normalizeOptionalString(i?.apiKey);
if (a) return a;
throw new Error("xAI credentials missing for realtime voice. Sign in with `openclaw onboard --auth-choice xai-oauth`, run `openclaw onboard --auth-choice xai-api-key`, or set XAI_API_KEY.");
}
//#endregion
//#region extensions/xai/realtime-voice-protocol.ts
var XaiRealtimePlaybackMarkOverflowError = class extends Error {};
var XaiRealtimeVoiceProtocol = class {
constructor(e) {
this.config = e;
this.markQueue = [];
this.responseActive = false;
this.responseCreateInFlight = false;
this.responseCancelInFlight = false;
this.responseCreatePending = false;
this.pendingToolCallIds = /* @__PURE__ */ new Set();
this.latestMediaTimestamp = 0;
this.assistantAudioItem = null;
this.toolCallBuffers = /* @__PURE__ */ new Map();
this.deliveredToolCallKeys = /* @__PURE__ */ new Set();
this.pendingToolResultAcks = /* @__PURE__ */ new Set();
this.conversationId = null;
this.audioFormat = e.audioFormat ?? REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ;
}
sendUserMessageNow(e) {
this.sendEvent({
type: "conversation.item.create",
item: {
type: "message",
role: "user",
content: [{
type: "input_text",
text: e
}]
}
});
this.requestResponseCreate();
}
submitToolResultNow(e, t, n) {
this.sendEvent({
type: "conversation.item.create",
item: {
type: "function_call_output",
call_id: e,
output: t
}
});
this.pendingToolResultAcks.add(e);
this.pendingToolCallIds.delete(e);
if (n?.suppressResponse !== true) this.requestResponseCreate();
}
acknowledgeMark(e) {
if (this.markQueue.length === 0) return;
if (e) {
const t = this.markQueue.indexOf(e);
if (t < 0) return;
this.markQueue.splice(t, 1);
} else this.markQueue.shift();
if (this.markQueue.length === 0) this.flushPendingResponseCreate();
}
handleBargeIn(e) {
this.interruptPlayback("barge-in", e);
}
handleServerVadBargeIn() {
this.interruptPlayback("server-vad-barge-in");
}
audioEndMs(e) {
const t = Math.floor(realtimeVoiceAudioDurationMs(this.audioFormat, e.bytes));
const n = Math.max(0, this.latestMediaTimestamp - e.startTimestamp);
return Math.min(t, n);
}
interruptPlayback(e, t) {
const n = this.assistantAudioItem;
const r = this.markQueue.length > 0 || e === "barge-in" && (this.responseActive || t?.audioPlaybackActive === true);
const i = (this.config.getPlaybackState ? this.config.getPlaybackState() : n && r ? [{
itemId: n.itemId,
audioEndMs: this.audioEndMs(n)
}] : []).map(({ itemId: e, audioEndMs: t }) => ({
itemId: e,
audioEndMs: t
}));
const a = e === "barge-in" && (this.responseActive || this.responseCreateInFlight || i.length > 0) && !this.responseCancelInFlight;
this.markQueue = [];
this.assistantAudioItem = null;
if (this.responseActive || this.responseCreateInFlight) this.responseCancelInFlight = true;
if (a) this.sendEvent({ type: "response.cancel" }, `reason=${e}`);
for (const t of i) this.sendEvent({
type: "conversation.item.truncate",
item_id: t.itemId,
content_index: 0,
audio_end_ms: t.audioEndMs
}, `reason=${e} audioEndMs=${t.audioEndMs}`);
this.config.onClearAudio("barge-in");
if (e === "barge-in") this.flushPendingResponseCreate();
}
buildSessionUpdate() {
const e = this.config;
const t = toOpenAICompatibleRealtimeAudioFormat(this.audioFormat);
return {
type: "session.update",
session: {
instructions: e.instructions,
voice: e.voice ?? "eve",
output_modalities: ["audio"],
turn_detection: {
type: "server_vad",
threshold: e.vadThreshold ?? .85,
prefix_padding_ms: e.prefixPaddingMs ?? 333,
silence_duration_ms: e.silenceDurationMs ?? 500
},
audio: {
input: {
format: t,
transcription: { model: XAI_REALTIME_INPUT_TRANSCRIPTION_MODEL }
},
output: { format: t }
},
...e.sessionResumption === true ? { resumption: { enabled: true } } : {},
...e.reasoningEffort ? { reasoning: { effort: e.reasoningEffort } } : {},
...e.tools?.length ? {
tools: e.tools,
tool_choice: "auto"
} : {}
}
};
}
emitToolCallOnce(e) {
if (!this.config.onToolCall) return;
const t = e.itemId || e.callId || "unknown";
const n = e.callId || t;
const r = e.name || "";
const i = e.itemId || e.callId || `${r}:${e.rawArgs ?? ""}`;
if (this.deliveredToolCallKeys.has(i)) return;
let a;
try {
a = JSON.parse(e.rawArgs || "{}");
} catch {
this.rejectToolCallArguments({
itemId: t,
callId: n,
dedupeKey: i,
reason: "malformed-json"
});
return;
}
if (!isRecord(a)) {
this.rejectToolCallArguments({
itemId: t,
callId: n,
dedupeKey: i,
reason: "non-object-json"
});
return;
}
this.deliveredToolCallKeys.add(i);
this.pendingToolCallIds.add(n);
this.config.onToolCall({
itemId: t,
callId: n,
name: r,
args: a
});
}
rejectToolCallArguments(e) {
this.deliveredToolCallKeys.add(e.dedupeKey);
this.config.onEvent?.({
direction: "server",
type: "tool_call.arguments.rejected",
detail: `reason=${e.reason}`,
itemId: e.itemId
});
this.submitToolResultNow(e.callId, "{\"error\":\"Invalid tool arguments.\"}");
}
requestResponseCreate() {
if (this.responseActive || this.responseCreateInFlight || this.responseCancelInFlight || this.markQueue.length > 0 || this.pendingToolCallIds.size > 0) {
this.responseCreatePending = true;
return;
}
this.responseCreatePending = false;
this.responseCreateInFlight = true;
this.sendEvent({ type: "response.create" });
}
flushPendingResponseCreate() {
if (!this.responseCreatePending) return;
this.responseCreatePending = false;
this.requestResponseCreate();
}
resetRealtimeSessionState(e = {}) {
this.markQueue = [];
this.responseActive = false;
this.responseCreateInFlight = false;
this.responseCancelInFlight = false;
this.responseCreatePending = false;
this.assistantAudioItem = null;
this.resetInputTranscripts();
if (!e.preserveToolCallState) {
this.pendingToolCallIds.clear();
this.toolCallBuffers.clear();
this.deliveredToolCallKeys.clear();
this.pendingToolResultAcks.clear();
}
}
createPlaybackMark() {
if (this.markQueue.length >= 1024) throw new XaiRealtimePlaybackMarkOverflowError(`xAI realtime voice playback mark limit exceeded (${XAI_REALTIME_MAX_PENDING_PLAYBACK_MARKS})`);
const e = `audio-${randomUUID()}`;
this.markQueue.push(e);
return e;
}
};
//#endregion
//#region extensions/xai/realtime-voice-bridge.ts
var XaiRealtimeMalformedAudioError = class extends Error {};
const XAI_REALTIME_INPUT_SETTLE_MS = 1500;
var XaiRealtimeVoiceBridge = class extends XaiRealtimeVoiceProtocol {
constructor(e) {
super(e);
this.assistantTranscriptBuffer = "";
this.assistantTranscriptFinalized = false;
this.finalizedInputTranscriptKeys = /* @__PURE__ */ new Set();
this.inputSpeechSequence = 0;
this.inputResponseStarted = false;
this.inputResponseFinished = false;
this.finalizedToolCallItems = /* @__PURE__ */ new Set();
this.inputTranscriptReplacements = /* @__PURE__ */ new Map();
this.supportsToolResultContinuation = false;
this.pendingToolResults = [];
this.pendingUserMessages = [];
this.sessionReadyFired = false;
this.transport = new RealtimeVoiceWebSocketTransport({
providerId: "xai",
label: "xAI realtime voice",
callbacks: e,
lifecycle: new RealtimeVoiceSessionLifecycle("xAI"),
resolveConnection: () => this.resolveConnectionParams(),
createSocket: ({ url: e, headers: t }) => {
const n = proxyCaptureSdk.createDebugProxyWebSocketAgent(proxyCaptureSdk.resolveDebugProxySettings());
return new WebSocket(e, {
headers: t,
maxPayload: XAI_REALTIME_WS_MAX_PAYLOAD_BYTES,
...n ? { agent: n } : {}
});
},
capture: proxyCaptureSdk.captureWsEventAsync,
onOpen: () => {
this.resetRealtimeSessionState({ preserveToolCallState: e.sessionResumption === true && this.conversationId !== null });
this.sendEvent(this.buildSessionUpdate());
},
onEvent: (e, t) => this.handleEvent(e, t),
onReset: () => this.resetTerminalState(),
startupError: (e) => e instanceof Error ? e : new Error(readXaiRealtimeErrorDetail(e)),
fatalEventError: (e) => e instanceof XaiRealtimeMalformedAudioError ? {
code: 1002,
reason: "Malformed audio payload"
} : e instanceof XaiRealtimePlaybackMarkOverflowError ? {
code: 1002,
reason: "Playback mark overflow"
} : void 0,
reconnectBlocked: () => this.reconnectBlockReason(),
maxReconnectAttempts: 5,
reconnectDelayMs: XAI_REALTIME_BASE_RECONNECT_DELAY_MS,
connectTimeoutMs: XAI_REALTIME_CONNECT_TIMEOUT_MS
});
}
connect() {
return this.transport.connect();
}
sendAudio(e) {
if (this.transport.lifecycle.phase() === "terminal") return;
if (!this.isConnected()) {
this.transport.lifecycle.enqueuePendingAudio(e);
return;
}
this.sendEvent({
type: "input_audio_buffer.append",
audio: e.toString("base64")
});
}
setMediaTimestamp(e) {
this.latestMediaTimestamp = e;
}
sendUserMessage(e) {
if (this.transport.lifecycle.phase() === "terminal") return;
if (!this.isConnected()) {
if (this.pendingUserMessages.length < 128) this.pendingUserMessages.push(e);
else this.config.onError?.(/* @__PURE__ */ new Error("xAI realtime voice pending user message queue overflow during reconnect"));
return;
}
this.sendUserMessageNow(e);
}
triggerGreeting(e) {
if (this.isConnected() && this.transport.socket) this.sendUserMessage(e ?? this.config.instructions ?? "Greet the user.");
}
submitToolResult(e, t, n) {
if (this.transport.lifecycle.phase() === "terminal" || n?.willContinue === true) return;
const r = this.isConnected();
let i;
try {
i = serializeXaiRealtimeToolResult(t);
} catch (e) {
if (!r) this.config.onError?.(e);
throw e;
}
if (!r) {
if (this.pendingToolResults.length >= 128) {
const e = /* @__PURE__ */ new Error("xAI realtime voice pending tool result queue overflow during reconnect");
this.config.onError?.(e);
throw e;
}
this.pendingToolResults.push({
callId: e,
output: i,
...n ? { options: n } : {}
});
return;
}
this.submitToolResultNow(e, i, n);
}
close() {
this.transport.close();
}
isConnected() {
return this.transport.isConnected();
}
async resolveConnectionParams() {
const e = await this.config.resolveApiKey();
const t = this.config.model ?? "grok-voice-latest";
return {
url: toXaiRealtimeWsUrl(this.config.baseUrl, t, this.config.sessionResumption === true ? this.conversationId ?? void 0 : void 0),
headers: {
Authorization: `Bearer ${e}`,
...xaiUserAgentHeaderFor(this.config.baseUrl)
}
};
}
reconnectBlockReason() {
if (this.config.sessionResumption !== true) return "sessionResumption=false";
if (this.pendingToolResultAcks.size > 0) return `unacknowledgedToolResults=${this.pendingToolResultAcks.size}`;
if (!this.conversationId) return "missingConversationId=true";
}
acceptsEvent(e) {
return this.transport.lifecycle.acceptsEvents(e);
}
onSessionUpdated(e) {
if (!this.transport.lifecycle.ready(e)) return;
for (const e of this.transport.lifecycle.drainPendingAudio()) this.sendAudio(e);
for (const e of this.pendingToolResults.splice(0)) this.submitToolResultNow(e.callId, e.output, e.options);
for (const e of this.pendingUserMessages.splice(0)) this.sendUserMessageNow(e);
if (!this.sessionReadyFired) {
this.sessionReadyFired = true;
this.config.onReady?.();
}
}
sendEvent(e, t) {
this.transport.send(e, t);
}
resetTerminalState() {
this.pendingToolResults = [];
this.pendingUserMessages = [];
this.conversationId = null;
this.resetRealtimeSessionState();
}
handleEvent(e, t) {
const n = e.response_id ?? e.response?.id;
if (e.type.startsWith("response.") && e.type !== "response.created" && this.outputResponse && (this.outputResponse.ended || n && this.outputResponse.id && n !== this.outputResponse.id)) return;
if (e.type === "response.created" && this.acceptsEvent(t)) {
if (this.outputResponse?.id && !this.outputResponse.ended && n && n !== this.outputResponse.id) {
if (!this.inputResponseStarted) {
this.outputResponse.ended = true;
this.config.onResponseDone?.({
status: "cancelled",
responseId: this.outputResponse.id
});
if (!this.acceptsEvent(t)) return;
}
this.responseCancelInFlight = false;
}
this.inputResponseStarted = true;
this.inputResponseFinished = false;
this.outputResponse = {
id: n,
ended: false
};
this.toolCallBuffers.clear();
this.finalizedToolCallItems.clear();
this.responseActive = true;
this.responseCreateInFlight = false;
this.markQueue = [];
this.assistantAudioItem = null;
this.resetAssistantTranscript();
}
const r = {
direction: "server",
type: e.type,
detail: this.describeServerEvent(e),
...e.item_id ? { itemId: e.item_id } : {},
...n ? { responseId: n } : {}
};
const emitBridgeEvent = () => this.config.onEvent?.(r);
if (e.type !== "response.done" || !this.acceptsEvent(t)) emitBridgeEvent();
if (!this.acceptsEvent(t)) return;
switch (e.type) {
case "session.created": return;
case "conversation.created": {
const t = normalizeOptionalString(e.conversation?.id);
if (t) this.conversationId = t;
return;
}
case "conversation.item.created":
case "conversation.item.added": {
const t = e.item;
const n = normalizeOptionalString(t?.call_id);
if (t?.type === "function_call_output" && n) {
this.pendingToolResultAcks.delete(n);
return;
}
if (e.type === "conversation.item.created") this.emitCompletedToolCall(t, e);
return;
}
case "session.updated":
this.onSessionUpdated(t);
return;
case "response.output_audio.delta": {
const n = e.delta ?? e.data;
if (!n || this.responseCancelInFlight) return;
const r = canonicalizeBase64(n);
if (!r) throw new XaiRealtimeMalformedAudioError("xAI realtime voice stream returned malformed base64 audio data");
const i = Buffer.from(r, "base64");
if (e.item_id && e.item_id !== this.assistantAudioItem?.itemId) this.assistantAudioItem = {
itemId: e.item_id,
bytes: i.byteLength,
startTimestamp: this.latestMediaTimestamp
};
else if (this.assistantAudioItem) this.assistantAudioItem.bytes += i.byteLength;
this.responseActive = true;
const a = this.createPlaybackMark();
this.config.onAudio(i, e.item_id ? { itemId: e.item_id } : void 0);
if (this.acceptsEvent(t)) this.config.onMark?.(a, () => {
if (this.acceptsEvent(t)) this.acknowledgeMark(a);
});
return;
}
case "input_audio_buffer.speech_started":
this.flushPendingInputTranscript();
this.inputSpeechSequence += 1;
this.inputResponseStarted = false;
this.inputResponseFinished = false;
this.handleServerVadBargeIn();
return;
case "response.text.delta":
case "response.output_text.delta":
case "response.output_audio_transcript.delta":
if (e.delta) this.appendAssistantTranscriptDelta(e.delta);
return;
case "response.text.done":
case "response.output_text.done":
case "response.output_audio_transcript.done":
if (this.isCurrentInputResponse(e)) {
this.flushPendingInputTranscript();
if (!this.acceptsEvent(t)) return;
}
this.flushAssistantTranscript(e.transcript ?? e.text);
return;
case "conversation.item.input_audio_transcription.delta":
if (e.delta) this.config.onTranscript?.("user", e.delta, false);
return;
case "conversation.item.input_audio_transcription.updated":
if (e.transcript) this.inputTranscriptReplacements.set(this.inputTranscriptKey(e), e.transcript);
return;
case "conversation.item.input_audio_transcription.completed": {
const n = this.inputTranscriptKey(e);
const r = e.transcript ?? this.inputTranscriptReplacements.get(n);
this.inputTranscriptReplacements.delete(n);
if (!r || this.finalizedInputTranscriptKeys.has(n)) return;
if (this.pendingInputTranscript && this.pendingInputTranscript.key !== n) {
this.flushPendingInputTranscript();
if (!this.acceptsEvent(t)) return;
}
this.pendingInputTranscript = {
key: n,
text: r
};
this.config.onTranscript?.("user", r, false, { textMode: "snapshot" });
if (this.inputResponseFinished) this.armInputSettleTimer();
return;
}
case "conversation.item.input_audio_transcription.failed": {
const t = this.inputTranscriptKey(e);
if (this.pendingInputTranscript?.key === t) this.pendingInputTranscript = void 0;
this.inputTranscriptReplacements.delete(t);
this.config.onError?.(new Error(readXaiRealtimeErrorDetail(e.error)));
return;
}
case "response.done": {
if (this.isCurrentInputResponse(e)) {
this.inputResponseFinished = true;
this.flushPendingInputTranscript();
if (!this.acceptsEvent(t)) return;
}
const n = Array.isArray(e.response?.output) ? e.response.output.filter(isRecord) : [];
const r = normalizeRealtimeVoiceResponseOutcome({
providerLabel: "xAI realtime voice",
response: e.response,
responseId: e.response_id
});
if (r.status !== "completed") {
this.markQueue = [];
this.assistantAudioItem = null;
}
try {
if (r.status === "completed") {
for (const [e, n] of this.toolCallBuffers) {
if (!this.acceptsEvent(t)) break;
this.emitToolCallOnce({
itemId: e,
callId: n.callId,
name: n.name,
rawArgs: n.args
});
}
for (const r of n) {
if (!this.acceptsEvent(t)) break;
this.emitCompletedToolCall(r, e);
}
}
if (this.acceptsEvent(t)) {
const e = n.filter((e) => e.type === "message" && e.role === "assistant").flatMap((e) => Array.isArray(e.content) ? e.content.filter(isRecord) : []).map((e) => typeof e.transcript === "string" ? e.transcript : typeof e.text === "string" ? e.text : "").join("");
this.flushAssistantTranscript(e);
}
if (this.outputResponse) this.outputResponse.ended = true;
this.config.onResponseDone?.(r);
emitBridgeEvent();
} finally {
this.responseActive = false;
this.responseCreateInFlight = false;
this.responseCancelInFlight = false;
this.toolCallBuffers.clear();
this.finalizedToolCallItems.clear();
this.flushPendingResponseCreate();
}
return;
}
case "response.function_call_arguments.delta": {
const t = e.item_id ?? "unknown";
const n = this.toolCallBuffers.get(t);
if (n && e.delta) n.args += e.delta;
else if (e.item_id) this.toolCallBuffers.set(e.item_id, {
name: e.name ?? "",
callId: e.call_id ?? "",
args: e.delta ?? ""
});
return;
}
case "response.function_call_arguments.done": {
const t = e.item_id ?? "unknown";
if (this.finalizedToolCallItems.has(t)) return;
const n = this.toolCallBuffers.get(t);
if (e.item_id) {
this.finalizedToolCallItems.add(e.item_id);
this.toolCallBuffers.set(e.item_id, {
name: n?.name || e.name || "",
callId: n?.callId || e.call_id || "",
args: e.arguments ?? n?.args ?? ""
});
}
return;
}
case "response.output_item.done":
this.bufferCompletedToolCall(e.item, e);
return;
case "error": this.handleErrorEvent(e.error);
}
}
resetInputTranscripts() {
this.flushPendingInputTranscript();
this.inputTranscriptReplacements.clear();
this.finalizedInputTranscriptKeys.clear();
this.inputResponseStarted = false;
this.inputResponseFinished = false;
this.outputResponse = void 0;
this.finalizedToolCallItems.clear();
}
isCurrentInputResponse(e) {
const t = e.response_id ?? e.response?.id;
return this.inputResponseStarted && (!t || !this.outputResponse?.id || t === this.outputResponse.id);
}
armInputSettleTimer() {
clearTimeout(this.inputSettleTimer);
this.inputSettleTimer = setTimeout(() => {
this.inputSettleTimer = void 0;
this.flushPendingInputTranscript();
}, XAI_REALTIME_INPUT_SETTLE_MS);
this.inputSettleTimer.unref?.();
}
flushPendingInputTranscript() {
clearTimeout(this.inputSettleTimer);
this.inputSettleTimer = void 0;
const e = this.pendingInputTranscript;
this.pendingInputTranscript = void 0;
if (!e) return;
this.finalizedInputTranscriptKeys.add(e.key);
if (this.finalizedInputTranscriptKeys.size > 1024) {
const e = this.finalizedInputTranscriptKeys.values().next().value;
if (e !== void 0) this.finalizedInputTranscriptKeys.delete(e);
}
this.config.onTranscript?.("user", e.text, true, { textMode: "snapshot" });
}
emitCompletedToolCall(e, t) {
if (e?.type === "function_call" && (!e.status || e.status === "completed")) this.emitToolCallOnce({
itemId: e.id ?? t.item_id,
callId: e.call_id,
name: e.name,
rawArgs: e.arguments
});
}
bufferCompletedToolCall(e, t) {
if (e?.type !== "function_call" || e.status && e.status !== "completed") return;
const n = e.id ?? t.item_id;
if (!n) return;
this.toolCallBuffers.set(n, {
name: e.name ?? "",
callId: e.call_id ?? "",
args: e.arguments ?? ""
});
}
appendAssistantTranscriptDelta(e) {
if (this.assistantTranscriptFinalized) {
this.assistantTranscriptBuffer = "";
this.assistantTranscriptFinalized = false;
}
this.assistantTranscriptBuffer += e;
this.config.onTranscript?.("assistant", e, false);
}
flushAssistantTranscript(e) {
if (this.assistantTranscriptFinalized) return;
const t = e || this.assistantTranscriptBuffer;
if (t) {
this.config.onTranscript?.("assistant", t, true);
this.assistantTranscriptFinalized = true;
}
this.assistantTranscriptBuffer = "";
}
resetAssistantTranscript() {
this.assistantTranscriptBuffer = "";
this.assistantTranscriptFinalized = false;
}
inputTranscriptKey(e) {
return e.item_id ?? e.response_id ?? `speech-${this.inputSpeechSequence}`;
}
handleErrorEvent(e) {
const t = readXaiRealtimeErrorDetail(e);
if (t.startsWith("Conversation already has an active response in progress:")) {
this.responseActive = true;
this.responseCreateInFlight = false;
this.responseCreatePending = true;
return;
}
if (t === "Cancellation failed: no active response found") {
if (!this.responseCancelInFlight) return;
this.responseActive = false;
this.responseCancelInFlight = false;
this.flushPendingResponseCreate();
return;
}
this.config.onError?.(new Error(t));
}
describeServerEvent(e) {
if (e.type === "error" || e.type === "conversation.item.input_audio_transcription.failed") return readXaiRealtimeErrorDetail(e.error);
if (e.type !== "response.done") return;
const t = e.response?.status;
const n = e.response?.status_details === void 0 ? void 0 : JSON.stringify(e.response.status_details);
return [t ? `status=${t}` : void 0, n].filter(Boolean).join(" ") || void 0;
}
};
//#endregion
//#region extensions/xai/realtime-voice-provider.ts
function buildXaiRealtimeVoiceProvider() {
return {
...createXaiRealtimeVoiceProviderMetadata({
isProviderAuthProfileConfigured,
isProviderAuthProfileConfiguredAsync,
resolveAgentDir
}),
createBridge: (e) => {
const t = normalizeXaiRealtimeProviderConfig(e.providerConfig);
assertXaiRealtimeVoiceRequestSupported(e);
return new XaiRealtimeVoiceBridge({
...e,
baseUrl: normalizeXaiRealtimeBaseUrl(t.baseUrl),
model: t.model,
voice: t.voice,
vadThreshold: t.vadThreshold,
silenceDurationMs: t.silenceDurationMs,
prefixPaddingMs: t.prefixPaddingMs,
reasoningEffort: t.reasoningEffort,
sessionResumption: t.sessionResumption,
resolveApiKey: () => resolveXaiRealtimeApiKey(t.apiKey, e.cfg, e.agentId)
});
}
};
}
//#endregion
export { buildXaiRealtimeVoiceProvider };