UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 26.4 kB
import{l as normalizeOptionalString}from"../../string-coerce-CpTFcSwY.mjs";import{m as asSafeIntegerInRange,s as asFiniteNumber}from"../../number-coercion-B3CfI447.mjs";import{a as asOptionalRecord,l as isRecord}from"../../record-coerce-BTbqdJ3-.mjs";import{t as asBoolean}from"../../boolean-Dt_JCqyW.mjs";import{f as normalizeResolvedSecretInputString}from"../../types.secrets-UWdyCdE6.mjs";import{n as materializeErrorStack}from"../../error-graph-internal-Bt2pFJBM.mjs";import{t as createDeferredCore}from"../../deferred-QsZCoVH-.mjs";import{o as warn}from"../../globals-l9I53ZKA.mjs";import"../../string-coerce-runtime-BYDH9Quw.mjs";import"../../error-runtime-DW-sj0iq.mjs";import"../../concurrency-runtime-A2TPGCdf.mjs";import{n as createRealtimeVoiceAudioQueue}from"../../realtime-session-lifecycle-t7GHCthe.mjs";import{i as realtimeVoiceAudioDurationMs,n as REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,t as REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ}from"../../provider-types-BnuLI0aS.mjs";import{n as REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME}from"../../agent-consult-tool-CCU5qa7O.mjs";import"../../realtime-voice-provider-CxjeBzmy.mjs";import"../../runtime-env-Qb8DG6sI.mjs";import"../../secret-input-FyvkT2mt.mjs";import{n as resolveGoogleEnvApiKey}from"../../gemini-auth-C-j7V5ap.mjs";import{n as GOOGLE_REALTIME_VOICE_METADATA,t as GOOGLE_REALTIME_DEFAULT_MODEL}from"../../realtime-voice-metadata-CTySkhn7.mjs";import{t as canonicalizeGoogleProviderBase64}from"../../base64-BGWO1SMP.mjs";import{t as createGoogleGenAI}from"../../google-genai-runtime-BTTtt5w-.mjs";import{n as GoogleLiveInputAudio,t as GOOGLE_REALTIME_INPUT_SAMPLE_RATE}from"../../realtime-voice-input-audio-B9vMpoVD.mjs";import{t as buildGoogleRealtimeSystemInstruction}from"../../realtime-voice-language-YuNKuxRq.mjs";import{a as isGemini31LiveModel,c as supportsAsyncFunctionCalling,i as endsTurnOnAudioStreamEnd,l as supportsClientContentInterrupt,n as buildThinkingConfig,o as isResponseDone,r as emitsCompleteInputTranscripts,s as modelSupportsToolResultContinuation,t as buildGoogleLiveInterruptTurn}from"../../realtime-voice-model-contract-BCMSXDTN.mjs";import{t as GoogleLiveOutputAudio}from"../../realtime-voice-output-audio-D0fm9H2y.mjs";import{randomUUID}from"node:crypto";import{ActivityHandling,Behavior,EndSensitivity,FunctionResponseScheduling,Modality,StartSensitivity,TurnCoverage}from"@google/genai"; //!extensions/google/realtime-voice-provider.ts const GOOGLE_REALTIME_DEFAULT_VOICE=`Kore`;const GOOGLE_REALTIME_DEFAULT_API_VERSION=`v1beta`;const GOOGLE_REALTIME_BROWSER_API_VERSION=`v1alpha`;const GOOGLE_REALTIME_BROWSER_WEBSOCKET_URL=`wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained`;const DEFAULT_AUDIO_STREAM_END_SILENCE_MS=500;const GOOGLE_REALTIME_BROWSER_SESSION_TTL_MS=18e5;const GOOGLE_REALTIME_BROWSER_NEW_SESSION_TTL_MS=6e4;const GOOGLE_REALTIME_RECONNECT_MAX_ATTEMPTS=3;const GOOGLE_REALTIME_RECONNECT_BASE_DELAY_MS=250;const GOOGLE_REALTIME_RECONNECT_MAX_DELAY_MS=2e3;const GOOGLE_REALTIME_MAX_TOOL_CALL_IDS=1024;const GOOGLE_REALTIME_MAX_PENDING_TOOL_RESPONSES=1024;const GOOGLE_REALTIME_MAX_PENDING_TOOL_RESPONSE_BYTES=1048576;const GOOGLE_REALTIME_MAX_PENDING_TRANSCRIPT_BYTES=262144;const GOOGLE_REALTIME_TRANSCRIPT_OVERFLOW_MESSAGE=`Google Live transcript exceeded the 256 KiB UTF-8 pending buffer limit`;const GOOGLE_REALTIME_TOOL_NAME_RE=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/;const START_SENSITIVITY={high:StartSensitivity.START_SENSITIVITY_HIGH,low:StartSensitivity.START_SENSITIVITY_LOW};const END_SENSITIVITY={high:EndSensitivity.END_SENSITIVITY_HIGH,low:EndSensitivity.END_SENSITIVITY_LOW};const ACTIVITY_HANDLING={"start-of-activity-interrupts":ActivityHandling.START_OF_ACTIVITY_INTERRUPTS,"no-interruption":ActivityHandling.NO_INTERRUPTION};const TURN_COVERAGE={"only-activity":TurnCoverage.TURN_INCLUDES_ONLY_ACTIVITY,"all-input":TurnCoverage.TURN_INCLUDES_ALL_INPUT,"audio-activity-and-all-video":TurnCoverage.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO};function asSensitivity(e){const t=normalizeOptionalString(e)?.toLowerCase();return t===`low`||t===`high`?t:void 0}function asThinkingLevel(e){const t=normalizeOptionalString(e)?.toLowerCase();return t===`minimal`||t===`low`||t===`medium`||t===`high`?t:void 0}function asActivityHandling(e){switch(normalizeOptionalString(e)?.toLowerCase().replaceAll(`_`,`-`)){case`start-of-activity-interrupts`:case`start-of-activity-interrupt`:case`interrupt`:case`interrupts`:return`start-of-activity-interrupts`;case`no-interruption`:case`no-interruptions`:case`none`:return`no-interruption`;default:return}}function asTurnCoverage(e){switch(normalizeOptionalString(e)?.toLowerCase().replaceAll(`_`,`-`)){case`only-activity`:case`turn-includes-only-activity`:return`only-activity`;case`all-input`:case`turn-includes-all-input`:return`all-input`;case`audio-activity-and-all-video`:case`turn-includes-audio-activity-and-all-video`:return`audio-activity-and-all-video`;default:return}}function normalizeProviderConfig(e,t){const n=asOptionalRecord(e.providers);const r=asOptionalRecord(n?.google)??asOptionalRecord(e.google)??e;return{apiKey:normalizeResolvedSecretInputString({value:r.apiKey??t?.models?.providers?.google?.apiKey,path:`plugins.entries.voice-call.config.realtime.providers.google.apiKey`}),model:normalizeOptionalString(r.model),voice:normalizeOptionalString(r.speakerVoice)??normalizeOptionalString(r.voice),temperature:asFiniteNumber(r.temperature),apiVersion:normalizeOptionalString(r.apiVersion),prefixPaddingMs:asSafeIntegerInRange(r.prefixPaddingMs,{min:0}),silenceDurationMs:asSafeIntegerInRange(r.silenceDurationMs,{min:0}),startSensitivity:asSensitivity(r.startSensitivity),endSensitivity:asSensitivity(r.endSensitivity),activityHandling:asActivityHandling(r.activityHandling),turnCoverage:asTurnCoverage(r.turnCoverage),automaticActivityDetectionDisabled:asBoolean(r.automaticActivityDetectionDisabled),enableAffectiveDialog:asBoolean(r.enableAffectiveDialog),sessionResumption:asBoolean(r.sessionResumption),contextWindowCompression:asBoolean(r.contextWindowCompression),thinkingLevel:asThinkingLevel(r.thinkingLevel),thinkingBudget:asSafeIntegerInRange(r.thinkingBudget,{min:-1,max:24576})}}function buildRealtimeInputConfig(e){const t=e.startSensitivity?START_SENSITIVITY[e.startSensitivity]:void 0;const n=e.endSensitivity?END_SENSITIVITY[e.endSensitivity]:void 0;const r=e.activityHandling?ACTIVITY_HANDLING[e.activityHandling]:void 0;const i=e.turnCoverage?TURN_COVERAGE[e.turnCoverage]:void 0;const a={...e.automaticActivityDetectionDisabled!==void 0?{disabled:e.automaticActivityDetectionDisabled}:{},...t?{startOfSpeechSensitivity:t}:{},...n?{endOfSpeechSensitivity:n}:{},...e.prefixPaddingMs!==void 0?{prefixPaddingMs:e.prefixPaddingMs}:{},...e.silenceDurationMs!==void 0?{silenceDurationMs:e.silenceDurationMs}:{}};const o={...Object.keys(a).length>0?{automaticActivityDetection:a}:{},...r?{activityHandling:r}:{},...i?{turnCoverage:i}:{}};return Object.keys(o).length>0?o:void 0}function buildFunctionDeclarations(e,t){const n=[];let r=0;for(const i of e??[])try{const e=i.name;if(typeof e!==`string`||!GOOGLE_REALTIME_TOOL_NAME_RE.test(e)){r+=1;continue}const a={name:e,description:i.description,parameters:i.parameters};if(t&&e===`openclaw_agent_consult`)a.behavior=Behavior.NON_BLOCKING;n.push(a)}catch{r+=1}if(r>0)warn(`google realtime: omitted ${r} tool definition(s) with unsupported names`);return n}function buildGoogleLiveConnectConfig(e,t){const n=supportsAsyncFunctionCalling(t);const r=buildFunctionDeclarations(e.tools,n);const i=buildRealtimeInputConfig(e);const a=buildThinkingConfig(e,t);return{responseModalities:[Modality.AUDIO],...e.temperature!==void 0&&e.temperature>0?{temperature:e.temperature}:{},speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:e.voice??GOOGLE_REALTIME_DEFAULT_VOICE}}},systemInstruction:buildGoogleRealtimeSystemInstruction(e.instructions,e.language),...r.length>0?{tools:[{functionDeclarations:r}]}:{},...i?{realtimeInputConfig:i}:{},inputAudioTranscription:{},outputAudioTranscription:{},...!isGemini31LiveModel(t)&&e.enableAffectiveDialog!==void 0?{enableAffectiveDialog:e.enableAffectiveDialog}:{},...a?{thinkingConfig:a}:{}}}function isMulawSilence(e){return e.length>0&&e.every(e=>e===255||e===127)}function isPcm16Silence(e){const t=Math.floor(e.length/2);if(t===0)return false;for(let n=0;n<t;n+=1)if(e.readInt16LE(n*2)!==0)return false;return true}function formatGoogleLiveCloseEvent(e){if(!e)return`code=unknown reason=unknown`;return`code=${e.code??`unknown`} reason=${e.reason?.trim()||`none`}${e.wasClean!==void 0?` clean=${e.wasClean}`:``}`}var GoogleRealtimeVoiceBridge=class{constructor(e){this.config=e;this.supportsToolResultSuppression=false;this.session=null;this.connected=false;this.setupCompleteReceived=false;this.sessionConfigured=false;this.intentionallyClosed=false;this.pendingAudio=createRealtimeVoiceAudioQueue(`reject-newest`);this.consecutiveSilenceBytes=0;this.audioStreamEnded=false;this.responseInterrupted=false;this.pendingFunctionNames=/* @__PURE__ */ new Map;this.seenFunctionCallIds=/* @__PURE__ */ new Set;this.pendingToolResponses=[];this.pendingToolResponseBytes=0;this.resumingSession=false;this.reconnectAttempts=0;this.hasConnectedSession=false;this.continuityResetEmitted=false;this.closeNotified=false;this.pendingTranscripts={user:{text:``,byteCount:0},assistant:{text:``,byteCount:0}};this.audioFormat=e.audioFormat??REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ;this.inputAudio=new GoogleLiveInputAudio(this.audioFormat);this.outputAudio=new GoogleLiveOutputAudio(this.audioFormat,e);this.model=e.model??`gemini-3.1-flash-live-preview`;this.supportsToolResultContinuation=modelSupportsToolResultContinuation(this.model)}async connect(){if(this.terminalError)throw this.terminalError;if(this.session)return;if(this.connectAttempt)return this.connectAttempt.promise;const e=createDeferredCore();const t={promise:e.promise,cancel:e.resolve};this.connectionOwner=t;this.connectAttempt=t;const n=this.connectOwned(t);t.promise=Promise.race([n,e.promise]).finally(()=>{if(this.connectAttempt===t)this.connectAttempt=void 0});return t.promise}async connectOwned(e){this.intentionallyClosed=false;this.closeNotified=false;this.setupCompleteReceived=false;this.sessionConfigured=false;this.consecutiveSilenceBytes=0;this.audioStreamEnded=false;const t=this.config.sessionResumption!==false&&Boolean(this.resumptionHandle);this.resumingSession=t;if(!t){this.inputAudio.reset();this.outputAudio.reset();this.responseInterrupted=false;this.resetToolCallOwnership()}const n=createGoogleGenAI({apiKey:this.config.apiKey,httpOptions:{apiVersion:this.config.apiVersion??GOOGLE_REALTIME_DEFAULT_API_VERSION}});try{const t=await n.live.connect({model:this.model,config:{...buildGoogleLiveConnectConfig(this.config,this.model),...this.config.sessionResumption===false?{}:{sessionResumption:this.resumptionHandle?{handle:this.resumptionHandle}:{}},...this.config.contextWindowCompression===false?{}:{contextWindowCompression:{slidingWindow:{}}}},callbacks:{onopen:()=>{if(this.connectionOwner!==e)return;this.connected=true;this.maybeActivateSession()},onmessage:t=>{if(this.connectionOwner!==e)return;this.handleMessage(t)},onerror:t=>{if(this.connectionOwner!==e)return;const n=t.error instanceof Error?t.error:new Error(typeof t.message===`string`?t.message:`Google Live API error`);this.config.onError?.(n)},onclose:t=>{if(this.connectionOwner!==e)return;this.connectionOwner=void 0;this.cancelConnectAttempt(e);this.connected=false;this.setupCompleteReceived=false;this.sessionConfigured=false;this.session=null;if(this.terminalError){this.notifyClose(`error`);return}if(this.intentionallyClosed){this.notifyClose(`completed`);return}const n=formatGoogleLiveCloseEvent(t);if(this.scheduleReconnect(n))return;this.resetToolCallOwnership();this.flushPendingTranscripts();this.config.onError?.(/* @__PURE__ */ new Error(`Google Live session closed after reconnect attempts: ${n}`));this.notifyClose(`error`)}}});if(this.connectionOwner!==e){t.close();return}this.session=t;this.hasConnectedSession=true;this.maybeActivateSession()}catch(t){if(this.connectionOwner===e){this.connectionOwner=void 0;this.connected=false;this.setupCompleteReceived=false;this.sessionConfigured=false;const e=this.session;this.session=null;e?.close()}throw t}}sendAudio(e){if(this.terminalError||this.intentionallyClosed||this.closeNotified)return;if(!this.session||!this.connected||!this.sessionConfigured){this.pendingAudio.enqueue(e);return}const t=endsTurnOnAudioStreamEnd(this.model)&&this.isSilence(e);if(t&&this.audioStreamEnded)return;this.inputAudio.send(this.session,e);if(!t){this.consecutiveSilenceBytes=0;this.audioStreamEnded=false;return}this.consecutiveSilenceBytes+=e.length;const n=realtimeVoiceAudioDurationMs(this.audioFormat,this.consecutiveSilenceBytes);const r=this.config.silenceDurationMs??DEFAULT_AUDIO_STREAM_END_SILENCE_MS;if(!this.audioStreamEnded&&n>=r){this.inputAudio.flush(this.session);this.session.sendRealtimeInput({audioStreamEnd:true});this.audioStreamEnded=true}}setMediaTimestamp(e){}handleBargeIn(e){if(!supportsClientContentInterrupt(this.model))return;if(!this.session||!this.connected||!this.sessionConfigured)return;if(e?.audioPlaybackActive!==true&&e?.force!==true)return;try{this.session.sendClientContent(buildGoogleLiveInterruptTurn())}catch(e){this.config.onError?.(e instanceof Error?e:/* @__PURE__ */ new Error(`Google Live barge-in interrupt failed`))}}sendUserMessage(e){const t=e.trim();if(!t||!this.session||!this.connected||!this.sessionConfigured)return;if(isGemini31LiveModel(this.model)){this.session.sendRealtimeInput({text:t});return}this.session.sendClientContent({turns:[{role:`user`,parts:[{text:t}]}],turnComplete:true})}triggerGreeting(e){const t=e?.trim()||`Start the call now. Greet the caller naturally and keep it brief.`;this.sendUserMessage(t)}rejectToolResult(e){this.config.onError?.(e);throw e}submitToolResult(e,t,n){const r=this.pendingFunctionNames.get(e);if(!r){if(this.seenFunctionCallIds.has(e))return;this.rejectToolResult(/* @__PURE__ */ new Error(`Google Live function response is missing a matching function call for ${e}`))}const i=r===REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME;if(n?.willContinue===true&&!this.supportsToolResultContinuation)this.rejectToolResult(/* @__PURE__ */ new Error(`Google Live model ${this.model} does not support continuing tool responses`));const a=!t||typeof t!==`object`||Array.isArray(t);const o={id:e,name:r,response:a?{output:t}:t};if(i&&this.supportsToolResultContinuation){o.scheduling=FunctionResponseScheduling.WHEN_IDLE;if(n?.willContinue===true)o.willContinue=true}else if(n?.willContinue===true)this.rejectToolResult(/* @__PURE__ */ new Error(`Google Live continuation is only supported for ${REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME}`));let s;let c;try{s=JSON.stringify(o);c=JSON.parse(s);if(!isRecord(c.response)||a&&!Object.hasOwn(c.response,`output`))throw new Error(`Google Live function response is missing required JSON output`)}catch(e){this.rejectToolResult(new Error(`Google Live function response result is not JSON-serializable`,{cause:e}))}try{const t=this.session;if(t&&(!this.resumingSession||this.sessionConfigured))t.sendToolResponse({functionResponses:[c]});else this.queueToolResponseForReconnect(c,s);if(n?.willContinue!==true)this.pendingFunctionNames.delete(e)}catch(e){const t=e instanceof Error?e:/* @__PURE__ */ new Error(`Failed to send Google Live function response`);if(this.session&&(!this.resumingSession||this.sessionConfigured))this.config.onError?.(t);else this.failConnection(t);throw t}}acknowledgeMark(e){}close(){const e=Boolean(this.connectionOwner||this.connectAttempt||this.session||this.reconnectTimer);try{if(this.session&&this.isConnected())this.inputAudio.flush(this.session)}finally{this.detachSession({clearInputAudio:true})?.close();if(e)this.notifyClose(`completed`)}}detachSession({clearInputAudio:e}){this.intentionallyClosed=true;this.connected=false;this.setupCompleteReceived=false;this.sessionConfigured=false;if(this.reconnectTimer){clearTimeout(this.reconnectTimer);this.reconnectTimer=void 0}if(e){this.pendingAudio.clear();this.consecutiveSilenceBytes=0;this.audioStreamEnded=false}this.resetToolCallOwnership();this.flushPendingTranscripts();const t=this.connectionOwner;this.connectionOwner=void 0;this.cancelConnectAttempt(t);const n=this.session;this.session=null;return n}isConnected(){return this.connected&&this.sessionConfigured}isSilence(e){return this.audioFormat.encoding===`pcm16`?isPcm16Silence(e):isMulawSilence(e)}handleMessage(e){this.captureSessionLifecycle(e);if(e.setupComplete)this.handleSetupComplete();if(e.serverContent)this.handleServerContent(e.serverContent);if(e.toolCall)this.handleToolCall(e.toolCall);if(e.toolCallCancellation)this.handleToolCallCancellation(e.toolCallCancellation.ids);if(e.setupComplete)this.maybeActivateSession()}captureSessionLifecycle(e){const t=e.sessionResumptionUpdate;if(t?.resumable===false)this.resumptionHandle=void 0;else if(t?.resumable&&t.newHandle)this.resumptionHandle=t.newHandle;if(e.goAway?.timeLeft)this.config.onError?.(/* @__PURE__ */ new Error(`Google Live session goAway: ${e.goAway.timeLeft}`))}handleSetupComplete(){if(!this.setupCompleteReceived){if(this.continuityResetEmitted)this.config.onEvent?.({direction:`server`,type:`session.created`});this.continuityResetEmitted=false}this.setupCompleteReceived=true}maybeActivateSession(){if(this.sessionConfigured||!this.connected||!this.setupCompleteReceived||!this.session)return;this.sessionConfigured=true;this.reconnectAttempts=0;if(!this.flushPendingToolResponses())return;this.resumingSession=false;for(const e of this.pendingAudio.drain())this.sendAudio(e);this.config.onReady?.()}handleServerContent(e){if(e.interrupted){this.responseInterrupted=true;this.outputAudio.reset();this.config.onClearAudio(`barge-in`)}if(e.inputTranscription){if(!this.appendTranscript(`user`,e.inputTranscription))return}if(e.outputTranscription){if(!this.appendTranscript(`assistant`,e.outputTranscription))return}for(const t of e.modelTurn?.parts??[])if(t.inlineData?.data){const e=canonicalizeGoogleProviderBase64(t.inlineData.data);if(!e){this.failConnection(/* @__PURE__ */ new Error(`Google Live stream returned malformed base64 audio data`));return}this.outputAudio.play(Buffer.from(e,`base64`),t.inlineData.mimeType)}if(e.generationComplete||e.interrupted||e.turnComplete){if(this.responseInterrupted)this.outputAudio.reset();else this.outputAudio.flush();this.flushPendingTranscript(`assistant`)}const t=isResponseDone(this.model,e.interactionStatus,this.responseInterrupted);if(e.turnComplete&&t){const e=this.responseInterrupted?`cancelled`:`completed`;this.responseInterrupted=false;this.config.onResponseDone?.({status:e})}}appendTranscript(e,t){const n=e===`user`&&emitsCompleteInputTranscripts(this.model);if(t.text){const r=this.pendingTranscripts[e],i=Buffer.byteLength(t.text,`utf8`);if(r.byteCount+i>GOOGLE_REALTIME_MAX_PENDING_TRANSCRIPT_BYTES){this.resetPendingTranscripts();this.failConnection(/* @__PURE__ */ new Error(GOOGLE_REALTIME_TRANSCRIPT_OVERFLOW_MESSAGE));return false}r.text+=t.text;r.byteCount+=i;if(!n)this.emitTranscript(e,t.text,false)}if(t.finished||n)this.flushPendingTranscript(e);return true}flushPendingTranscript(e){const t=this.pendingTranscripts[e].text.trim();this.pendingTranscripts[e]={text:``,byteCount:0};if(t)this.emitTranscript(e,t,true)}emitTranscript(e,t,n){try{this.config.onTranscript?.(e,t,n)}catch(e){try{this.config.onError?.(e instanceof Error?e:/* @__PURE__ */ new Error(`Google Live transcript callback failed`))}catch{}}}flushPendingTranscripts(){this.flushPendingTranscript(`user`);this.flushPendingTranscript(`assistant`)}resetPendingTranscripts(){this.responseInterrupted=false;this.pendingTranscripts.user={text:``,byteCount:0};this.pendingTranscripts.assistant={text:``,byteCount:0}}failConnection(e){if(this.terminalError)return;materializeErrorStack(e);this.terminalError=e;const t=this.detachSession({clearInputAudio:false});try{this.config.onError?.(e)}finally{try{t?.close()}finally{this.notifyClose(`error`)}}}notifyClose(e){if(this.closeNotified)return;this.pendingAudio.clear();this.inputAudio.reset();this.outputAudio.reset();this.responseInterrupted=false;this.closeNotified=true;this.config.onClose?.(e)}cancelConnectAttempt(e){if(!e)return;if(this.connectAttempt===e)this.connectAttempt=void 0;e.cancel()}handleToolCall(e){for(const t of e.functionCalls??[]){const e=t.name?.trim();if(!e)continue;const n=t.id?.trim()||`google-live-${randomUUID()}`;if(this.seenFunctionCallIds.has(n))continue;if(this.seenFunctionCallIds.size>=GOOGLE_REALTIME_MAX_TOOL_CALL_IDS){this.failConnection(/* @__PURE__ */ new Error(`Google Live tool-call session limit exceeded`));return}this.seenFunctionCallIds.add(n);this.pendingFunctionNames.set(n,e);this.config.onToolCall?.({itemId:n,callId:n,name:e,args:t.args??{}})}}handleToolCallCancellation(e){for(const t of e??[]){const e=t.trim();if(!e)continue;const n=this.pendingFunctionNames.delete(e);const r=this.removePendingToolResponses(e);if(!n&&!r)continue;this.config.onEvent?.({direction:`server`,type:`tool.call.cancelled`,itemId:e})}}resetToolCallOwnership(){this.pendingFunctionNames.clear();this.seenFunctionCallIds.clear();this.pendingToolResponses=[];this.pendingToolResponseBytes=0}queueToolResponseForReconnect(e,t){const n=Buffer.byteLength(t,`utf8`);if(this.pendingToolResponses.length>=GOOGLE_REALTIME_MAX_PENDING_TOOL_RESPONSES||this.pendingToolResponseBytes+n>GOOGLE_REALTIME_MAX_PENDING_TOOL_RESPONSE_BYTES)throw new Error(`Google Live reconnect tool-response buffer limit exceeded`);this.pendingToolResponses.push({payload:e,byteLength:n});this.pendingToolResponseBytes+=n}removePendingToolResponses(e){const t=[];let n=false;for(const r of this.pendingToolResponses)if(r.payload.id===e){this.pendingToolResponseBytes-=r.byteLength;n=true}else t.push(r);this.pendingToolResponses=t;return n}flushPendingToolResponses(){const e=this.session;if(!e)return false;try{while(this.pendingToolResponses.length>0){const t=this.pendingToolResponses[0];if(!t)break;e.sendToolResponse({functionResponses:[t.payload]});this.pendingToolResponses.shift();this.pendingToolResponseBytes-=t.byteLength}return true}catch(e){this.failConnection(e instanceof Error?e:/* @__PURE__ */ new Error(`Failed to flush Google Live function responses`));return false}}scheduleReconnect(e){if(this.reconnectAttempts>=GOOGLE_REALTIME_RECONNECT_MAX_ATTEMPTS)return false;const t=this.config.sessionResumption!==false&&Boolean(this.resumptionHandle);if(this.hasConnectedSession&&!t&&!this.continuityResetEmitted){this.continuityResetEmitted=true;this.resetPendingTranscripts();this.resetToolCallOwnership();this.config.onEvent?.({direction:`client`,type:`session.continuity.reset`})}const n=++this.reconnectAttempts;const r=Math.min(GOOGLE_REALTIME_RECONNECT_MAX_DELAY_MS,GOOGLE_REALTIME_RECONNECT_BASE_DELAY_MS*2**(n-1));this.config.onError?.(/* @__PURE__ */ new Error(`Google Live session closed unexpectedly (${e}); reconnecting ${n}/${GOOGLE_REALTIME_RECONNECT_MAX_ATTEMPTS} in ${r}ms`));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0;if(this.intentionallyClosed)return;this.connect().catch(e=>{const t=e instanceof Error?e.message:String(e);this.config.onError?.(e instanceof Error?e:new Error(t));if(!this.scheduleReconnect(`connect failed: ${t}`)){this.resetToolCallOwnership();this.flushPendingTranscripts();this.notifyClose(`error`)}})},r);return true}};async function createGoogleRealtimeBrowserSession(e){const t=normalizeProviderConfig(e.providerConfig);const n=asSafeIntegerInRange(e.prefixPaddingMs,{min:0});const r=asSafeIntegerInRange(e.silenceDurationMs,{min:0});const i={...t,...n!==void 0?{prefixPaddingMs:n}:{},...r!==void 0?{silenceDurationMs:r}:{}};const a=i.apiKey||resolveGoogleEnvApiKey();if(!a)throw new Error(`Google Gemini API key missing`);const o=e.model??i.model??`gemini-3.1-flash-live-preview`;const s=e.voice??i.voice??GOOGLE_REALTIME_DEFAULT_VOICE;const c=Date.now();const l=new Date(c+GOOGLE_REALTIME_BROWSER_SESSION_TTL_MS).toISOString();const u=c+GOOGLE_REALTIME_BROWSER_NEW_SESSION_TTL_MS;const d=new Date(u).toISOString();const f=(await createGoogleGenAI({apiKey:a,httpOptions:{apiVersion:GOOGLE_REALTIME_BROWSER_API_VERSION,timeout:3e4}}).authTokens.create({config:{uses:1,expireTime:l,newSessionExpireTime:d,liveConnectConstraints:{model:o,config:buildGoogleLiveConnectConfig({...i,apiKey:a,model:o,voice:s,instructions:e.instructions,tools:e.tools},o)}}})).name?.trim();if(!f)throw new Error(`Google Live browser session did not return an ephemeral token`);return{provider:`google`,transport:`provider-websocket`,protocol:`google-live-bidi`,clientSecret:f,websocketUrl:GOOGLE_REALTIME_BROWSER_WEBSOCKET_URL,audio:{inputEncoding:`pcm16`,inputSampleRateHz:GOOGLE_REALTIME_INPUT_SAMPLE_RATE,outputEncoding:`pcm16`,outputSampleRateHz:24e3},initialMessage:{setup:{model:o.startsWith(`models/`)?o:`models/${o}`,generationConfig:{responseModalities:[Modality.AUDIO]},inputAudioTranscription:{},outputAudioTranscription:{}}},model:o,voice:s,expiresAt:u}}function buildGoogleRealtimeVoiceProvider(){const resolveConfig=({cfg:e,rawConfig:t})=>normalizeProviderConfig(t,e);const isConfigured=({providerConfig:e})=>Boolean(normalizeProviderConfig(e).apiKey||resolveGoogleEnvApiKey());return{...GOOGLE_REALTIME_VOICE_METADATA,capabilities:{transports:[`provider-websocket`,`gateway-relay`],inputAudioFormats:[REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ,REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ],outputAudioFormats:[REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ,REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ],supportsBrowserSession:true,supportsBargeIn:true,handlesInputAudioBargeIn:true,supportsToolCalls:true,supportsVideoFrames:true,supportsSessionResumption:true},resolveConfig,isConfigured,resolveConfigAsync:async e=>resolveConfig(e),isConfiguredAsync:async e=>isConfigured(e),createBridge:e=>{const t=normalizeProviderConfig(e.providerConfig);const n=t.apiKey||resolveGoogleEnvApiKey();if(!n)throw new Error(`Google Gemini API key missing`);return new GoogleRealtimeVoiceBridge({...e,...t,apiKey:n})},createBrowserSession:createGoogleRealtimeBrowserSession}}export{buildGoogleRealtimeVoiceProvider};