@urun-sh/openai 0.6.50 → 0.6.51

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.
@@ -22,7 +22,7 @@ Content-Type: text/plain; charset=utf-8\r
22
22
  Content-Length: ${Buffer.byteLength(o)}\r
23
23
  \r
24
24
  ${o}`)}function is(t,e){let n=new bt.WebSocketServer({noServer:!0,maxPayload:Up}),r=new Ct,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,f)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{kr(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==os){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){kr(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(E){let A=e.statusOf?.(E)??null;kr(c,A?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(m=!0,n.handleUpgrade(d,c,f,E=>{s.delete(c),o.add(E),E.on("close",()=>o.delete(E));try{new rs(E,w,r,e.statusOf,e.operatorLog??(A=>console.error(A)))}catch{o.delete(E),E.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&kr(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=ss();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of o)h.readyState!==bt.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}O();O();var gs=require("@urun-sh/core");O();var Qa=require("@urun-sh/core"),qp={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Gp={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function $n(t,e){let n=Gp[t.code];return e?`${n} (${e})`:n}function Rr(t){if(t==null)return null;let e=qp[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Er(t){if(t.kind==="create-failed")return Rr(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Qa.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Rr(e?"cold_start_exceeded":"queue_timeout")}var Dn=require("ws");O();var nl=require("@urun-sh/core");O();var el=require("crypto");function G(t){return`${t}_${(0,el.randomUUID)().replace(/-/g,"").slice(0,24)}`}var xr=4*1024*1024,as=8*1024*1024,ls=512,Ar=20*1024*1024;function fe(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function dt(t,e){return{type:"server_error",code:t,message:e}}function le(t){return{type:"error",event_id:G("event"),error:t}}function us(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var z=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Wp={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Jp={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Vp={format:!0,voice:!0,speed:!0};function Kp(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function on(t,e){if(!Array.isArray(t)||t.length===0)throw new z(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new z(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function Za(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new z(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var zp=10;function ds(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:zp})}function Nn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new z("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Wp));if(s.length>0)throw new z(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=on(o.modalities,"modalities"),l=on(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new z("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[a,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new z(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new z(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(l==="transcription"&&!n.turns)throw new z('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new z(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=on(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new z('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");i.outputModalities=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Kp(l))throw new z(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(l!==null&&typeof l!="string")throw new z("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new z("instructions must be a string or null","instructions");i.instructions=ds(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new z("voice must be a string or null","voice");if(!n.voice)throw new z("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new z(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new z("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new z(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new z("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new z("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new z("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new z(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[f,h]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new z(`turn_detection.${f} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${f}`,"unsupported_field");if(h!=null&&h!==c[f])throw new z(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new z("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!l||typeof l!="object"||Array.isArray(l))throw new z("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new z(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new z(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(l!==null)throw new z("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new z("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Jp))throw new z(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Za(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Nn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Nn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new z("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new z("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Vp))throw new z(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Za(d.format,"audio.output.format"),d.speed!==void 0)throw new z("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete i.voice;else{if(typeof d.voice!="string")throw new z("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new z("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function Ir(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function cs(t,e){let n=t;if(!n||typeof n!="object")throw new z("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new z("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:G("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new z('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new z("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new z("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new z(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new z("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new z("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new z("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new z("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new z("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let l=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...l!==void 0?{detail:l}:{}});continue}throw new z(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:G("item"),type:"message",role:r,content:o}}throw new z(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Or(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Yp=1001,Xp=1011,Qp=6e4,Zp=3e5;var Tr=class extends Error{},Pr=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ut=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},ps=t=>t.slice(0,120),ef=/^[A-Za-z0-9+/=]*$/,tf=2;function nf(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>tf)return!1;return!0}var Un=class{id=G("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=us();sessionId=G("sess");conversationId=G("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??Qp,this.responseDeadlineMs=e.responseDeadlineMs??Zp,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(n=>{n.reason===Co&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:G("event"),session:Ir(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:G("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof te&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(le(dt("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:G("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:G("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:G("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:G("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:G("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:G("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:G("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:G("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=G("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:G("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:G("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:G("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:G("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(fe("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>xr){this.fail(fe("frame_too_large",`frame exceeds the ${xr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(fe("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(fe("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(le({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof Tr){this.fail(dt(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
25
- ${o?.stack??je(o)}`),this.send(le(dt(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Nn(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(le(fe("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:G("event"),session:Ir(this.config,this.sessionId)});return}case"conversation.item.create":{let n=cs(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:G("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:G("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:G("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(le(fe("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:G("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(le(fe("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ef.test(e.audio)){this.send(le(fe("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Ar){this.send(le(fe("buffer_full",`uncommitted input audio exceeds the ${Ar}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:G("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(le(fe("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=G("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:G("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:G("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:G("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:G("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(le(fe("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(le(fe("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,ps("session ended by client"))}catch{}});return}case"ping":return;default:this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(fe("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Tr("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(le({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0){o=!1;let i=n.next();i.catch(()=>{}),s=r?await Promise.race([i,r]):await i}else{let i,a=new Promise((d,c)=>{i=setTimeout(()=>c(new Pr),this.turnStallMs)}),l=n.next();l.catch(()=>{}),s=await(r?Promise.race([l,a,r]):Promise.race([l,a])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(le(fe("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?on(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?on(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new z("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(le(fe("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1;let i=()=>{},a=new Promise((v,x)=>{i=()=>x(new Ut)});this.turnCancelled=a,this.wakeTurnCancelled=()=>i(),a.catch(()=>{});let l=()=>{},u=new Promise((v,x)=>{l=()=>x(new Ut)});this.turnDialGate=u,this.wakeTurnDialGate=()=>l(),u.catch(()=>{});let d=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let c=G("req"),f=`resp_${c}`;this.activeResponseId=f,this.activeRequestId=c;let h=this.binding.composite===!0,m=h?0:this.items.length,w=h?null:Or(this.items),E=ds(typeof n.instructions=="string"?n.instructions:this.config.instructions),A=typeof n.temperature=="number"?n.temperature:this.config.temperature,b=n.max_output_tokens??this.config.maxOutputTokens,S=b==="inf"||b===void 0?void 0:b,p=n.tools!==void 0?n.tools:this.config.tools,g=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,y={stream:!0,...this.config.model?{model:this.config.model}:{},...E!==void 0?{instructions:E}:{},...A!==void 0?{temperature:A}:{},...S!==void 0?{max_output_tokens:S}:{},...p!==void 0?{tools:p}:{},...g!==void 0?{tool_choice:g}:{}};if(!(h&&!this.ensureVoice())){for(let{audio:v,captureWallMs:x}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(v,x);this.inFlight=(async()=>{let v=[],x=T=>{this.responseFlushed?this.send(T):v.push(T)},P=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:G("event"),response:this.responseObject(f,"in_progress")}),this.send({type:"response.in_progress",event_id:G("event"),response:this.responseObject(f,"in_progress")});for(let T of v)this.send(T);v.length=0,this.responseFlushed=!0}},k={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},L=null,_=()=>{this.closeOpenItems(f,k,m),P(),this.send({type:"response.done",event_id:G("event"),response:this.responseObject(f,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(h){if(this.pendingTranscriptItemId!==null&&(await new Promise(F=>{this.pendingTranscriptSettled=F}),this.cancelled||this.closed))throw new Ut;m=this.items.length,w=Or(this.items)}let{input:T,sawAudioOnlyItem:N}=w??{input:[],sawAudioOnlyItem:!1},M={...y,input:T,...h?this.compositeTurnAsk(n):{}};N&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let D;try{let F=this.upstreamStream(M,c);Promise.resolve(F).catch(K=>{K instanceof te&&this.failSessionGone(K)}),D=await Promise.race([F,u])}catch(F){if(F instanceof Ut){this.deadlineFired&&!this.closed&&_();return}this.upstreamTurnFault(F,f);return}P();try{for await(let F of this.stallBoundedTurn(D)){if(this.cancelled)break;let K=F;if(K.type==="error"){let X=this.upstreamErrorBody(K);k.contentFlowed?this.send(le(X)):this.send({type:"response.failed",event_id:G("event"),response:this.failedResponse(f,X)});return}if(K.type==="response.output_text.delta"&&typeof K.delta=="string"){P(),k.contentFlowed=!0,k.messageOpen||(this.beginMessageItem(f,k.nextOutputIndex++),k.messageOpen=!0),this.config.outputModalities.includes("text")&&x({type:"response.output_text.delta",event_id:G("event"),item_id:`${f}_msg_0`,response_id:f,output_index:0,content_index:0,delta:K.delta}),this.turnOutputIsAudio()&&(k.transcriptDelta=!0,x({type:"response.output_audio_transcript.delta",event_id:G("event"),item_id:`${f}_msg_0`,response_id:f,output_index:0,content_index:0,delta:K.delta})),k.messageText+=K.delta;continue}if(K.type==="response.function_call_arguments.delta"){P(),k.contentFlowed=!0;let X=typeof K.delta=="string"?K.delta:"",ne=typeof K.call_id=="string"&&K.call_id.length>0?K.call_id:`${f}_fc_${k.nextOutputIndex}`,J=k.tools.get(ne);if(!J){let $=typeof K.name=="string"&&K.name.length>0?K.name:void 0;J={outputIndex:k.nextOutputIndex++,name:$,args:""},k.tools.set(ne,J);let ee={id:ne,object:"realtime.item",type:"function_call",call_id:ne,name:$??"",arguments:"",status:"in_progress"};x({type:"response.output_item.added",event_id:G("event"),response_id:f,output_index:J.outputIndex,item:ee}),this.emitAssistantItemAdded(ee)}typeof K.name=="string"&&K.name.length>0&&(J.name=K.name),J.args+=X,x({type:"response.function_call_arguments.delta",event_id:G("event"),item_id:ne,response_id:f,output_index:J.outputIndex,call_id:ne,name:J.name??"",delta:X});continue}if(K.type==="response.completed"){L=K.response??null;continue}}}catch(F){if(this.closed)return;if(F instanceof Ut){this.deadlineFired&&_();return}if(this.cancelled)return;if(F instanceof Pr)this.operatorLog(`[realtime] turn ${f} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(F,f);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&_();return}this.closeOpenItems(f,k,m),P(),this.send({type:"response.done",event_id:G("event"),response:this.doneResponse(f,m,L)})}finally{clearTimeout(d),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(nf(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(le({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:G("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:G("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:G("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:G("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:G("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:G("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:G("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:G("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:G("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:G("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:G("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:G("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:G("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:G("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:G("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:G("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=nt(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??ze(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(dt(Lo,"the organization is out of credits \u2014 top up to continue"),Lo))}failSessionGone(e){if(e instanceof te&&e.reason===Co){this.failInsufficientCredits();return}let n=e instanceof Error&&Ke(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${je(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(dt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof te){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof nl.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=dt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(le(r)):this.send({type:"response.failed",event_id:G("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(fe("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:G("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>ls&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(le(fe("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>On){this.send(le(fe("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${On}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(le(fe("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(le(dt(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>as){this.ws.close(Yp,ps("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=Ue(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${je(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(Xp,ps(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>tl(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),tl(this.id,e)}},fs=[];function tl(t,e){fs.push({id:t,reason:e}),fs.length>256&&fs.shift()}var Fn="/v1/realtime",rl="urun.admission",ol=t=>t.slice(0,120);function rf(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
25
+ ${o?.stack??je(o)}`),this.send(le(dt(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Nn(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(le(fe("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:G("event"),session:Ir(this.config,this.sessionId)});return}case"conversation.item.create":{let n=cs(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:G("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:G("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:G("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(le(fe("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:G("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(le(fe("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ef.test(e.audio)){this.send(le(fe("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Ar){this.send(le(fe("buffer_full",`uncommitted input audio exceeds the ${Ar}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:G("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(le(fe("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=G("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:G("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:G("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:G("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:G("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(le(fe("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(le(fe("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,ps("session ended by client"))}catch{}});return}case"ping":return;default:this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(fe("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Tr("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(le({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0){o=!1;let i=n.next();i.catch(()=>{}),s=r?await Promise.race([i,r]):await i}else{let i,a=new Promise((d,c)=>{i=setTimeout(()=>c(new Pr),this.turnStallMs)}),l=n.next();l.catch(()=>{}),s=await(r?Promise.race([l,a,r]):Promise.race([l,a])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return this.config.model&&s.model===void 0&&(s.model=this.config.model),r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(le(fe("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?on(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?on(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new z("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(le(fe("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1;let i=()=>{},a=new Promise((v,x)=>{i=()=>x(new Ut)});this.turnCancelled=a,this.wakeTurnCancelled=()=>i(),a.catch(()=>{});let l=()=>{},u=new Promise((v,x)=>{l=()=>x(new Ut)});this.turnDialGate=u,this.wakeTurnDialGate=()=>l(),u.catch(()=>{});let d=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let c=G("req"),f=`resp_${c}`;this.activeResponseId=f,this.activeRequestId=c;let h=this.binding.composite===!0,m=h?0:this.items.length,w=h?null:Or(this.items),E=ds(typeof n.instructions=="string"?n.instructions:this.config.instructions),A=typeof n.temperature=="number"?n.temperature:this.config.temperature,b=n.max_output_tokens??this.config.maxOutputTokens,S=b==="inf"||b===void 0?void 0:b,p=n.tools!==void 0?n.tools:this.config.tools,g=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,y={stream:!0,...this.config.model?{model:this.config.model}:{},...E!==void 0?{instructions:E}:{},...A!==void 0?{temperature:A}:{},...S!==void 0?{max_output_tokens:S}:{},...p!==void 0?{tools:p}:{},...g!==void 0?{tool_choice:g}:{}};if(!(h&&!this.ensureVoice())){for(let{audio:v,captureWallMs:x}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(v,x);this.inFlight=(async()=>{let v=[],x=T=>{this.responseFlushed?this.send(T):v.push(T)},P=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:G("event"),response:this.responseObject(f,"in_progress")}),this.send({type:"response.in_progress",event_id:G("event"),response:this.responseObject(f,"in_progress")});for(let T of v)this.send(T);v.length=0,this.responseFlushed=!0}},k={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},L=null,_=()=>{this.closeOpenItems(f,k,m),P(),this.send({type:"response.done",event_id:G("event"),response:this.responseObject(f,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(h){if(this.pendingTranscriptItemId!==null&&(await new Promise(F=>{this.pendingTranscriptSettled=F}),this.cancelled||this.closed))throw new Ut;m=this.items.length,w=Or(this.items)}let{input:T,sawAudioOnlyItem:N}=w??{input:[],sawAudioOnlyItem:!1},M={...y,input:T,...h?this.compositeTurnAsk(n):{}};N&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let D;try{let F=this.upstreamStream(M,c);Promise.resolve(F).catch(K=>{K instanceof te&&this.failSessionGone(K)}),D=await Promise.race([F,u])}catch(F){if(F instanceof Ut){this.deadlineFired&&!this.closed&&_();return}this.upstreamTurnFault(F,f);return}P();try{for await(let F of this.stallBoundedTurn(D)){if(this.cancelled)break;let K=F;if(K.type==="error"){let X=this.upstreamErrorBody(K);k.contentFlowed?this.send(le(X)):this.send({type:"response.failed",event_id:G("event"),response:this.failedResponse(f,X)});return}if(K.type==="response.output_text.delta"&&typeof K.delta=="string"){P(),k.contentFlowed=!0,k.messageOpen||(this.beginMessageItem(f,k.nextOutputIndex++),k.messageOpen=!0),this.config.outputModalities.includes("text")&&x({type:"response.output_text.delta",event_id:G("event"),item_id:`${f}_msg_0`,response_id:f,output_index:0,content_index:0,delta:K.delta}),this.turnOutputIsAudio()&&(k.transcriptDelta=!0,x({type:"response.output_audio_transcript.delta",event_id:G("event"),item_id:`${f}_msg_0`,response_id:f,output_index:0,content_index:0,delta:K.delta})),k.messageText+=K.delta;continue}if(K.type==="response.function_call_arguments.delta"){P(),k.contentFlowed=!0;let X=typeof K.delta=="string"?K.delta:"",ne=typeof K.call_id=="string"&&K.call_id.length>0?K.call_id:`${f}_fc_${k.nextOutputIndex}`,J=k.tools.get(ne);if(!J){let $=typeof K.name=="string"&&K.name.length>0?K.name:void 0;J={outputIndex:k.nextOutputIndex++,name:$,args:""},k.tools.set(ne,J);let ee={id:ne,object:"realtime.item",type:"function_call",call_id:ne,name:$??"",arguments:"",status:"in_progress"};x({type:"response.output_item.added",event_id:G("event"),response_id:f,output_index:J.outputIndex,item:ee}),this.emitAssistantItemAdded(ee)}typeof K.name=="string"&&K.name.length>0&&(J.name=K.name),J.args+=X,x({type:"response.function_call_arguments.delta",event_id:G("event"),item_id:ne,response_id:f,output_index:J.outputIndex,call_id:ne,name:J.name??"",delta:X});continue}if(K.type==="response.completed"){L=K.response??null;continue}}}catch(F){if(this.closed)return;if(F instanceof Ut){this.deadlineFired&&_();return}if(this.cancelled)return;if(F instanceof Pr)this.operatorLog(`[realtime] turn ${f} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(F,f);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&_();return}this.closeOpenItems(f,k,m),P(),this.send({type:"response.done",event_id:G("event"),response:this.doneResponse(f,m,L)})}finally{clearTimeout(d),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(nf(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(le({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:G("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:G("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:G("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:G("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:G("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:G("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:G("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:G("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:G("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:G("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:G("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:G("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:G("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:G("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:G("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:G("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=nt(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??ze(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(dt(Lo,"the organization is out of credits \u2014 top up to continue"),Lo))}failSessionGone(e){if(e instanceof te&&e.reason===Co){this.failInsufficientCredits();return}let n=e instanceof Error&&Ke(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${je(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(dt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof te){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof nl.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=dt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(le(r)):this.send({type:"response.failed",event_id:G("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(fe("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:G("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>ls&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(le(fe("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>On){this.send(le(fe("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${On}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(le(fe("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(le(dt(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>as){this.ws.close(Yp,ps("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=Ue(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${je(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(Xp,ps(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>tl(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),tl(this.id,e)}},fs=[];function tl(t,e){fs.push({id:t,reason:e}),fs.length>256&&fs.shift()}var Fn="/v1/realtime",rl="urun.admission",ol=t=>t.slice(0,120);function rf(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
26
26
  Connection: close\r
27
27
  Content-Type: text/plain\r
28
28
  \r
@@ -73,7 +73,7 @@ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:y.message}}
73
73
 
74
74
  `):c.write(`data: ${JSON.stringify({error:{message:y.message,type:"upstream_error",code:g}})}
75
75
 
76
- `)),c.end()})}}O();var ct=(t,e)=>Object.assign(new Error(e),{status:t}),ym='"transcription" (a transcription session), or no intent at all (the realtime voice session)',As=(t,e,n)=>new te(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),xs=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof ie?ct(404,n.message):n}};async function eu(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw ct(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${ym}`);if(o==="transcription")throw ct(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw ct(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw ct(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let f;try{f=await t.supportsTranscription(n.stt)}catch(h){throw h instanceof ie?ct(404,h.message):h}if(!f)throw ct(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let f;try{f=await t.transcriptStreamFor(n.stt)}catch(h){throw h instanceof ie?ct(404,h.message):h}if(f!=="stt")throw ct(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await xs(t,n.stt),i=await xs(t,e),a=await xs(t,n.tts),l=await t.openAudioOn(s,r),u=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:f=>{let h=new AbortController;return d=h,wm({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},f,h.signal,()=>{d===h&&(d=null)})}},cancelActiveTurn:()=>{let f=d;d=null,f?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:f=>{l.appendInputAudio(f)},onOutputAudio:f=>u.onOutputAudio(f),sessionId:u.sessionId}},turns:async function*(f){try{yield*t.openTurnsOn(s,f)}catch(h){throw h instanceof te?As("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function Is(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Wn=class extends Error{};async function*wm(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:l}=t;if(n?.aborted){r?.();return}let{output_modalities:u,...d}=e,c=e.output_modalities,f=!Array.isArray(c)||c.includes("audio"),h=!1,m=null,w=null,E=[],A=null,b=new Promise((L,_)=>{n&&n.addEventListener("abort",()=>_(new Wn),{once:!0})}),S=()=>h||n?.aborted===!0,p=async L=>{if(S())return;let _;try{_=await o.createResponseOn(i,{model:l.tts,input:[{role:"user",content:[{type:"input_text",text:L}]}],stream:!1,...l.voice!==void 0?{voice:l.voice}:{}})}catch(N){throw N instanceof te?As("tts",l.tts,N):N}let T=_[Symbol.asyncIterator]();w=T;try{for(;;){let N=T.next(),M;try{M=await Promise.race([N,b])}catch(F){if(N.catch(()=>{}),F instanceof Wn)return;throw F}if(M.done)return;let D=M.value;if(D.type==="error"){let F=D.error&&typeof D.error.message=="string"?D.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(l.tts)}) errored: ${F}`)}if(D.type==="response.completed")return}}finally{w===T&&(w=null)}},g=async()=>{for(;E.length>0&&!S();){let L=E.shift();await p(L)}},y=L=>{if(L===""||S()||(E.push(L),A!==null))return;let _=g();A=_,_.then(()=>{A===_&&(A=null)},T=>{A===_&&(A=null),m??=T})},v=()=>{h=!0,E.length=0;let L=w;if(w=null,L){let _=L.return?.();_&&_.catch(()=>{})}},x=async()=>{for(;E.length>0||A!==null;){let L=A;if(L===null){await p(E.shift());continue}await L}},P=f?new ln({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},L=>y(L)):null,k=null;try{let L;try{L=await o.createResponseOn(s,d)}catch(T){throw T instanceof te?As("chat",a,T):T}let _=L[Symbol.asyncIterator]();try{for(;;){let T=_.next(),N;try{N=await Promise.race([T,b])}catch(F){if(T.catch(()=>{}),F instanceof Wn)break;throw F}if(N.done)break;let M=N.value;if(S())return;let D=M;if(D.type==="error"){yield M;return}if(D.type==="response.output_text.delta"&&typeof D.delta=="string"){yield M,P?.push(D.delta);continue}if(D.type==="response.function_call_arguments.delta"){P?.flush(),yield M;continue}if(D.type==="response.completed"){k=M.response;continue}}}finally{Promise.resolve(_.return?.()).catch(()=>{})}P?.flush(),P?.dispose(),f&&await x(),k!==null&&(yield{type:"response.completed",response:k})}finally{P?.dispose(),v();try{if(m instanceof te)throw m}finally{r?.()}}}var Ge=(t,e)=>Object.assign(new Error(e),{status:t});function nu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ru(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}function ou(t){let e=new URL(t.url??"/","http://localhost").searchParams.get("session"),n=t.headers?.["x-urun-session"],r=(e??(typeof n=="string"?n:n?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var _m='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function su(t,e,n,r,o){if(!t.supportsAudio)throw Ge(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await t.supportsAudio(e)}catch(h){throw h instanceof ie?Ge(404,h.message):h}if(!s){let h=null;if(t.realtimeCompanionsFor)try{h=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof ie?Ge(404,m.message):m}if(h!==null)return await eu(t,e,h,n,r);throw Ge(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw Ge(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(h){throw h instanceof ie?Ge(404,h.message):h}if(i&&!t.openTurnsOn)throw Ge(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let h;try{h=await t.transcriptStreamFor(e)}catch(m){throw m instanceof ie?Ge(404,m.message):m}if(h!=="stt")throw Ge(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(h)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw Ge(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${_m}`);if(r==="transcription"&&!i)throw Ge(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(h){throw h instanceof xe?Ge(503,h.message):h}let l=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,u=`conn_${(0,tu.randomUUID)()}`,c={audio:await t.openAudioOn(a,n,u,o).catch(h=>{throw t.releaseSessionHandle?.(a),h})},f={clients:{createResponse:async h=>await t.createResponseOn(a,h,u)},voice:s,audioSession:c};return t.openVideoOn&&(f.video=()=>t.openVideoOn(a,n)),i&&(f.turns=h=>t.openTurnsOn(a,h)),r==="transcription"&&(f.intent="transcription"),t.releaseSessionHandle&&(f.release=()=>t.releaseSessionHandle(a)),(t.touchSessionPresence||t.detachSessionPresence)&&(f.presence={touch:h=>t.touchSessionPresence?.(a,h),detach:h=>t.detachSessionPresence?.(a,h)}),t.endDedicatedSession&&(f.endSession=()=>t.endDedicatedSession(a)),t.onSessionEnd&&(f.onSessionEnd=h=>t.onSessionEnd(a,h)),e!==void 0&&(f.model=e),l!==null&&(f.catalog=l),f}O();var Tu=require("@urun-sh/core"),Pu=require("@urun-sh/core/internal"),Cu=Re(require("ws"),1);O();var hu=require("http");O();var du=require("http");O();function iu(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function Kr(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}O();O();function au(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var lu=require("@urun-sh/core/internal");O();var vm="llm-resp";async function*zr(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let a=typeof i.index=="number"?i.index:0,l=r.get(a)??{};i.id&&(l.id=i.id),i.function?.name&&(l.name=i.function.name),r.set(a,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:l.id,name:l.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield au(s);return}}}async function*Os(t,e){let n=`${vm}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*zr(e,t.stream(n).messages())}finally{try{(0,lu.gcRequest)(t.doc("llm"),e)}catch{}}}var bm="/pooler/v1/inference",Qe=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Sm=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},km=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},cu=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),Rm=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await cu(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new Qe(t.status,e,n,t.retryAfterSeconds)};async function Em(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${bm}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Sm(e),firstMessage:km(e)}});return new Promise((a,l)=>{let u=(0,du.request)({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let c=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(c)?c:void 0,body:d})});u.on("error",d=>l(new Qe(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var uu=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*xm(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
76
+ `)),c.end()})}}O();var ct=(t,e)=>Object.assign(new Error(e),{status:t}),ym='"transcription" (a transcription session), or no intent at all (the realtime voice session)',As=(t,e,n)=>new te(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),xs=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof ie?ct(404,n.message):n}};async function eu(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw ct(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${ym}`);if(o==="transcription")throw ct(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw ct(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw ct(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let f;try{f=await t.supportsTranscription(n.stt)}catch(h){throw h instanceof ie?ct(404,h.message):h}if(!f)throw ct(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let f;try{f=await t.transcriptStreamFor(n.stt)}catch(h){throw h instanceof ie?ct(404,h.message):h}if(f!=="stt")throw ct(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await xs(t,n.stt),i=await xs(t,e),a=await xs(t,n.tts),l=await t.openAudioOn(s,r),u=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:f=>{let h=new AbortController;return d=h,wm({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},f,h.signal,()=>{d===h&&(d=null)})}},cancelActiveTurn:()=>{let f=d;d=null,f?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:f=>{l.appendInputAudio(f)},onOutputAudio:f=>u.onOutputAudio(f),sessionId:u.sessionId}},turns:async function*(f){try{yield*t.openTurnsOn(s,f)}catch(h){throw h instanceof te?As("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function Is(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Wn=class extends Error{};async function*wm(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:l}=t;if(n?.aborted){r?.();return}let{output_modalities:u,...d}=e,c=e.output_modalities,f=!Array.isArray(c)||c.includes("audio"),h=!1,m=null,w=null,E=[],A=null,b=new Promise((L,_)=>{n&&n.addEventListener("abort",()=>_(new Wn),{once:!0})}),S=()=>h||n?.aborted===!0,p=async L=>{if(S())return;let _;try{_=await o.createResponseOn(i,{model:l.tts,input:[{role:"user",content:[{type:"input_text",text:L}]}],stream:!1,...l.voice!==void 0?{voice:l.voice}:{}})}catch(N){throw N instanceof te?As("tts",l.tts,N):N}let T=_[Symbol.asyncIterator]();w=T;try{for(;;){let N=T.next(),M;try{M=await Promise.race([N,b])}catch(F){if(N.catch(()=>{}),F instanceof Wn)return;throw F}if(M.done)return;let D=M.value;if(D.type==="error"){let F=D.error&&typeof D.error.message=="string"?D.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(l.tts)}) errored: ${F}`)}if(D.type==="response.completed")return}}finally{w===T&&(w=null)}},g=async()=>{for(;E.length>0&&!S();){let L=E.shift();await p(L)}},y=L=>{if(L===""||S()||(E.push(L),A!==null))return;let _=g();A=_,_.then(()=>{A===_&&(A=null)},T=>{A===_&&(A=null),m??=T})},v=()=>{h=!0,E.length=0;let L=w;if(w=null,L){let _=L.return?.();_&&_.catch(()=>{})}},x=async()=>{for(;E.length>0||A!==null;){let L=A;if(L===null){await p(E.shift());continue}await L}},P=f?new ln({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},L=>y(L)):null,k=null;try{let L;try{L=await o.createResponseOn(s,d)}catch(T){throw T instanceof te?As("chat",a,T):T}let _=L[Symbol.asyncIterator]();try{for(;;){let T=_.next(),N;try{N=await Promise.race([T,b])}catch(F){if(T.catch(()=>{}),F instanceof Wn)break;throw F}if(N.done)break;let M=N.value;if(S())return;let D=M;if(D.type==="error"){yield M;return}if(D.type==="response.output_text.delta"&&typeof D.delta=="string"){yield M,P?.push(D.delta);continue}if(D.type==="response.function_call_arguments.delta"){P?.flush(),yield M;continue}if(D.type==="response.completed"){k=M.response;continue}}}finally{Promise.resolve(_.return?.()).catch(()=>{})}P?.flush(),P?.dispose(),f&&await x(),k!==null&&(yield{type:"response.completed",response:k})}finally{P?.dispose(),v();try{if(m instanceof te)throw m}finally{r?.()}}}var Ge=(t,e)=>Object.assign(new Error(e),{status:t});function nu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ru(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}function ou(t){let e=new URL(t.url??"/","http://localhost").searchParams.get("session"),n=t.headers?.["x-urun-session"],r=(e??(typeof n=="string"?n:n?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var _m='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function su(t,e,n,r,o){if(!t.supportsAudio)throw Ge(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await t.supportsAudio(e)}catch(h){throw h instanceof ie?Ge(404,h.message):h}if(!s){let h=null;if(t.realtimeCompanionsFor)try{h=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof ie?Ge(404,m.message):m}if(h!==null)return await eu(t,e,h,n,r);throw Ge(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw Ge(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(h){throw h instanceof ie?Ge(404,h.message):h}if(i&&!t.openTurnsOn)throw Ge(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let h;try{h=await t.transcriptStreamFor(e)}catch(m){throw m instanceof ie?Ge(404,m.message):m}if(h!=="stt")throw Ge(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(h)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw Ge(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${_m}`);if(r==="transcription"&&!i)throw Ge(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(h){throw h instanceof xe?Ge(503,h.message):h}let l=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,u=`conn_${(0,tu.randomUUID)()}`,c={audio:await t.openAudioOn(a,n,u,o).catch(h=>{throw t.releaseSessionHandle?.(a),h})},f={clients:{createResponse:async h=>await t.createResponseOn(a,h,u)},voice:s,audioSession:c};return t.openVideoOn&&(f.video=()=>t.openVideoOn(a,n)),i&&(f.turns=h=>t.openTurnsOn(a,h)),r==="transcription"&&(f.intent="transcription"),t.releaseSessionHandle&&(f.release=()=>t.releaseSessionHandle(a)),(t.touchSessionPresence||t.detachSessionPresence)&&(f.presence={touch:h=>t.touchSessionPresence?.(a,h),detach:h=>t.detachSessionPresence?.(a,h)}),t.endDedicatedSession&&(f.endSession=()=>t.endDedicatedSession(a)),t.onSessionEnd&&(f.onSessionEnd=h=>t.onSessionEnd(a,h)),e!==void 0&&(f.model=e),l!==null&&(f.catalog=l),f}O();var Tu=require("@urun-sh/core"),Pu=require("@urun-sh/core/internal"),Cu=Re(require("ws"),1);O();var hu=require("http");O();var du=require("http");O();function iu(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),typeof o.model=="string"&&o.model&&(s.model=o.model),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function Kr(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}O();O();function au(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var lu=require("@urun-sh/core/internal");O();var vm="llm-resp";async function*zr(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let a=typeof i.index=="number"?i.index:0,l=r.get(a)??{};i.id&&(l.id=i.id),i.function?.name&&(l.name=i.function.name),r.set(a,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:l.id,name:l.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield au(s);return}}}async function*Os(t,e){let n=`${vm}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*zr(e,t.stream(n).messages())}finally{try{(0,lu.gcRequest)(t.doc("llm"),e)}catch{}}}var bm="/pooler/v1/inference",Qe=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Sm=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},km=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},cu=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),Rm=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await cu(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new Qe(t.status,e,n,t.retryAfterSeconds)};async function Em(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${bm}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Sm(e),firstMessage:km(e)}});return new Promise((a,l)=>{let u=(0,du.request)({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let c=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(c)?c:void 0,body:d})});u.on("error",d=>l(new Qe(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var uu=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*xm(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
77
77
 
78
78
  `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=uu(s);i!==null&&(yield i)}let n=uu(e);n!==null&&(yield n)}async function pu(t,e,n,r){let o=Kr(e,n,r),s=o.model??"";if(s==="")throw new Qe(400,"missing_model","the pooler submit requires a model");let i=await Em(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Rm(i);let a=e.stream===!0?zr(n,xm(i)):await Am(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Am(t,e){let n=await cu(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new Qe(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return zr(e,(async function*(){yield o})())}O();var Im=require("@urun-sh/core"),Om=require("bullmq"),Tm=require("crypto");var fu=12e4;var Pm="/pooler/v1/lanes/pick",Cm="/pooler/v1/lanes/status",Lm=1e4,Vn=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function mu(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),u=(0,hu.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:o},d=>{let c=[];d.on("data",f=>c.push(f)),d.on("end",()=>{let f=Buffer.concat(c).toString("utf8"),h=null;try{h=f===""?null:JSON.parse(f)}catch{h=null}s({status:d.statusCode??0,json:h})}),d.on("error",f=>i(new Qe(502,"pooler_unreachable",`the pooler channel failed: ${f.message}`)))});u.on("timeout",()=>{u.destroy(new Vn(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),u.on("error",d=>i(new Qe(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(l)})}function gu(t,e,n,r){if(t===400&&Mm(e)?.code==="lane_target")return new Nt(n,r);if(t===503)return new xe(n);let o=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${o}`)}function Mm(t){if(t===null||typeof t!="object")return null;let e=t.error;return e!==null&&typeof e=="object"?e:null}function yu(t){return{async pick({pool:e,app:n,fn:r,sharedApp:o,model:s,holdMs:i=0}){let a=Math.min(Math.max(Math.trunc(i),0),fu),l=await mu(t,"POST",Pm,{pool:e,app:n,fn:r,model:s,hold_ms:a,...o?{shared_app:!0}:{}},a+Lm);if(l.status!==200)throw gu(l.status,l.json,e,s);return(l.json?.lanes??[]).filter(d=>typeof d.lane_id=="string"&&d.lane_id!==""&&typeof d.host=="string"&&d.host!=="").map(d=>({laneId:d.lane_id,host:d.host}))},async status(){let e=await mu(t,"GET",Cm,void 0,5e3);if(e.status!==200)throw gu(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}O();O();O();async function wu(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}var _u=require("@urun-sh/core/internal");var Yr=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=Kr(e,n,this.consumerId);return this.write(r),Os(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=iu(e,n,r,this.consumerId);return this.write(o),Os(this.session,r)})}cancelTurn(e){try{(0,_u.gcRequest)(this.session.doc("llm"),e)}catch{}}async writeGated(e,n){try{await wu(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var vu=0;function Nm(){return vu+=1,`req_${Date.now().toString(36)}_${vu.toString(36)}`}var Ht=class{transport;constructor(e,n){this.transport=new Yr(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Nm(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};O();var dn=Re(require("yjs"),1),bu=require("@urun-sh/core/internal"),Um=3e4;function Dm(t){return(e,n,r)=>{let o=t(e);dn.applyUpdate(n,dn.encodeStateAsUpdate(o));let s=a=>dn.applyUpdate(o,a),i=a=>dn.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}function Ts(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Dm(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=r.get(d);return c||(c=new bu.SessionDocumentImpl(d,e,n),r.set(d,c)),c},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=i.get(d);if(!c){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);c=t.streamEndpoint(d),i.set(d,c)}return c},l=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);async function*f(){let h=a(d);try{yield*h.messages()}finally{i.delete(d),await h.close()}}return{messages:()=>f(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:l,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let f=d?.timeout??t.whenLiveTimeoutMs??Um;await new Promise((h,m)=>{let w=setTimeout(()=>{E(),m(new Error(`lane ${e} llm doc never synced within ${f}ms`))},f),E=c.onSynced(()=>{clearTimeout(w),d?.signal?.removeEventListener("abort",A),h()}),A=()=>{clearTimeout(w),E(),m(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",A,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,c]of i)i.delete(d),c.close()}}}O();var jt=Re(require("ws"),1),qt=require("@urun-sh/core"),Su="/stream/";function ku(t){if(!t.startsWith(Su))return null;let e=t.slice(Su.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function Zr(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Xr(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>qt.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Qr=class{reassembler=new qt.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===qt.STREAM_END&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},Cs=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;a.bytes+o.byteLength>Ru&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Ru} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,l)=>a+l.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},Ru=8*1024*1024,rt=new Cs;function Eu(t,e){let n=new Qr,r={send(o){rt.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Xr(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),rt.detach(t,e,r)}};return rt.attach(t,e,r),r}function Fm(t,e){return{deliver(n){e?.();try{t.send(n,{binary:!0})}catch(r){console.warn(`[lane-stream] socket send failed: ${String(r)}`)}},close(n,r){try{t.close(n,r)}catch{}}}}function xu(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new jt.default(r,Zr(e)),s=new Qr;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Xr(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Xr(i),o.readyState!==jt.default.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function Ps(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
79
79
  `;t.end(`HTTP/1.1 ${e} ${r}\r
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{D as i,E as w,U as v,V as g,a as d,b as f,l as c}from"../chunk-PL4MNBET.js";import"../chunk-OZVX4WPP.js";import"../chunk-CAR4AEQJ.js";import"../chunk-V6WQRPUO.js";import"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import{a as S}from"../chunk-LM4E5YM2.js";import"../chunk-XKKQ2NEZ.js";import"../chunk-XGAF2NDT.js";import{v as m,w as p}from"../chunk-6WTMEJZS.js";import"../chunk-XNRPTMSL.js";import"../chunk-Q3AIBMET.js";import"../chunk-PXV7QBSD.js";import"../chunk-7KRHHEKZ.js";import"../chunk-C452ZIU5.js";import{b as E,c as l}from"../chunk-YSFSRI3D.js";l();var O=E(S(),1);import o from"process";function T(){let r=null;return r=p({streams:o,note:n=>{r?.isDead("stderr")!==!0&&m(o.stderr,n)}}),r}async function $(){T();let r=w(o.env),{server:n,metricsServer:s,edgeIdentityServer:a,closeAll:P,closeWebSockets:I}=v(r);await new Promise((e,t)=>{n.once("error",t),n.listen(r.port,i,e)}),await new Promise((e,t)=>{s.once("error",t),s.listen(d,i,e)}),await new Promise((e,t)=>{a.once("error",t),a.listen(c,i,e)}),o.stdout.write(`inference-proxy listening on http://${i}:${r.port}/v1 (metrics http://${i}:${d}${f}, edge identity http://${i}:${c}, control plane ${r.baseUrl}, org API ${r.apiUrl}, catalog oracle ${r.catalog?"on":"off"})
2
+ import{D as i,E as w,U as v,V as g,a as d,b as f,l as c}from"../chunk-USE56WRQ.js";import"../chunk-5L7LOBL7.js";import"../chunk-CAR4AEQJ.js";import"../chunk-AW5X2PRN.js";import"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import{a as S}from"../chunk-LM4E5YM2.js";import"../chunk-7OUSAG7O.js";import"../chunk-XGAF2NDT.js";import{v as m,w as p}from"../chunk-H4KFMIEV.js";import"../chunk-XNRPTMSL.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-C452ZIU5.js";import{b as E,c as l}from"../chunk-YSFSRI3D.js";l();var O=E(S(),1);import o from"process";function T(){let r=null;return r=p({streams:o,note:n=>{r?.isDead("stderr")!==!0&&m(o.stderr,n)}}),r}async function $(){T();let r=w(o.env),{server:n,metricsServer:s,edgeIdentityServer:a,closeAll:P,closeWebSockets:I}=v(r);await new Promise((e,t)=>{n.once("error",t),n.listen(r.port,i,e)}),await new Promise((e,t)=>{s.once("error",t),s.listen(d,i,e)}),await new Promise((e,t)=>{a.once("error",t),a.listen(c,i,e)}),o.stdout.write(`inference-proxy listening on http://${i}:${r.port}/v1 (metrics http://${i}:${d}${f}, edge identity http://${i}:${c}, control plane ${r.baseUrl}, org API ${r.apiUrl}, catalog oracle ${r.catalog?"on":"off"})
3
3
  `);let u=async e=>{o.stdout.write(`inference-proxy: ${e} \u2014 draining
4
4
  `),await g(n,P,I),await new Promise(t=>s.close(()=>t())),await new Promise(t=>a.close(()=>t()))};await new Promise(e=>{o.once("SIGINT",()=>{u("SIGINT").finally(e)}),o.once("SIGTERM",()=>{u("SIGTERM").finally(e)})})}$().then(()=>o.exit(0),r=>{o.stderr.write(`inference-proxy: ${String(r instanceof Error?r.stack??r.message:r)}
5
5
  `),o.exit(1)});