@urun-sh/openai 0.6.55 → 0.6.57

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.
@@ -1,5 +1,5 @@
1
1
  "use strict";var dd=Object.create;var Vn=Object.defineProperty;var cd=Object.getOwnPropertyDescriptor;var pd=Object.getOwnPropertyNames;var fd=Object.getPrototypeOf,md=Object.prototype.hasOwnProperty;var gd=(t,e)=>{for(var n in e)Vn(t,n,{get:e[n],enumerable:!0})},di=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pd(e))!md.call(t,o)&&o!==n&&Vn(t,o,{get:()=>e[o],enumerable:!(r=cd(e,o))||r.enumerable});return t};var fe=(t,e,n)=>(n=t!=null?dd(fd(t)):{},di(e||!t||!t.__esModule?Vn(n,"default",{value:t,enumerable:!0}):n,t)),hd=t=>di(Vn({},"__esModule",{value:!0}),t);var hg={};gd(hg,{ANONYMOUS_KEY_ID:()=>Vr,BIND_HOST:()=>ed,BUCKET_DOMAIN:()=>Os,BoundedLabel:()=>Qt,ControlPlaneUnavailableError:()=>$e,ConversationBackhauls:()=>on,ConversationCapacityError:()=>Wn,DEFAULT_PORT:()=>zs,EDGE_IDENTITY_PORT:()=>Uu,EDGE_KEY_FINGERPRINT_HEADER:()=>Ts,EDGE_KEY_ID_HEADER:()=>Is,InferenceMetrics:()=>Zt,LEDGER_FUNCTION_PATH:()=>ri,LEDGER_WRITE_TIMEOUT_MS:()=>oi,LedgerClient:()=>an,LedgerDuplicateError:()=>sn,LedgerSurfaceError:()=>le,MAX_CACHED_KEYS:()=>Us,MAX_CACHED_MEMBERSHIPS:()=>Bs,MAX_CONVERSATIONS:()=>to,MAX_CONVERSATION_HANDLES:()=>Xs,MAX_MODEL_LABELS:()=>ks,MAX_ORG_LABELS:()=>Rs,MAX_TENANTS:()=>Ys,MEMBERSHIP_CHECK_TIMEOUT_MS:()=>Fs,MEMBERSHIP_VERDICT_TTL_MS:()=>Ds,METRICS_PATH:()=>Wr,METRICS_PORT:()=>Mu,MembershipGate:()=>qn,MembershipRefusalError:()=>Ge,NO_MODEL_LABEL:()=>Ss,ORG_BINDING_TTL_MS:()=>Ns,OTHER_LABEL:()=>Xt,OrgResolver:()=>St,ProxyAuthError:()=>V,READINESS_TIMEOUT_MS:()=>ai,READINESS_TTL_MS:()=>ii,SERVE_FUNCTION:()=>Gn,TIER_DOMAIN:()=>Ps,TenantRegistry:()=>rn,bearerFrom:()=>tn,bearerTokenOf:()=>$s,createEdgeIdentityServer:()=>Kr,createHostedProxy:()=>ud,createMetricsServer:()=>Jr,edgeBucketId:()=>Cs,edgeTierFingerprint:()=>Ls,laneOf:()=>Es,parseLedgerRecorded:()=>si,resolveHostedConfig:()=>td,statusClassOf:()=>xs,tenantSubject:()=>nn});module.exports=hd(hg);var id=require("http");function zn(t){let e=t.byteLength>>1,n=0;for(let r=0;r<e;r++){let o=t.readInt16LE(r*2);if(o>16||o<-16)return!1;n+=o*o}return n<=64*e}var pi="audio",io=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(e,"base64"),o=Math.floor(r.byteLength/2),s=new Int16Array(o);for(let i=0;i<o;i++)s[i]=r.readInt16LE(i*2);this.source.onData(s),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(i=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(i instanceof Error?i.message:String(i)))}))}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function fi(t,e,n=1e4){try{return await yd(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function yd(t,e,n){let r=new io(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(pi);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(a=>s.emit(a));let i=await wd(t,n);return await r.startInbound(i),r}function wd(t,e){let n=t.stream(pi);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=l=>{l!=null&&(clearTimeout(i),s?.(),r(l))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var ci="rt-video-in",un=256e3;function lo(t){let e=t.stream(ci),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${ci}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async r=>{if(r.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(r.byteLength>un)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${un}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var _d=24e3,ln=480,vd=111,bd=50,Kn=null;async function Sd(){if(Kn)return;let t=await import("opusscript");Kn=t.default??t}function kd(){if(!Kn)throw new Error("[opus-guard] opusscript module not loaded");return new Kn(_d,1,2048)}var ao=class{constructor(e=kd){this.build=e;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let e=this.build();return this.inner=e,e}get wedged(){return this._wedged||this.consecutiveFailures>=bd}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let o=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,o}catch(o){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${o instanceof Error?o.message:String(o)}`);return null}}decode(e){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(e);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let e=this.inner;this.inner=null;try{e?.delete?.()}catch{}}};async function mi(){let t=await import("werift");await Sd();let e=new ao;return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let l=new Int16Array(i.length+a.length);l.set(i,0),l.set(a,i.length);let u=0;for(;l.length-u>=ln;){let d=l.subarray(u,u+ln);u+=ln;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),f=e.encode(c,ln);if(f===null){i=l.slice(u);break}o=o+1&65535,s=s+ln>>>0;let g=new t.RtpHeader({version:2,payloadType:vd,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),m=new t.RtpPacket(g,f);n.writeRtp(m)}i=l.slice(u)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{if(s.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${s.payload.length} B > 3828 B max`);return}let i;try{i=e.decode(s.payload)}catch(l){if(e.wedged)throw l;return}let a=new Int16Array(i.length/2);for(let l=0;l<a.length;l++)a[l]=i.readInt16LE(l*2);r.onframe?.({samples:a})}),r},dispose:()=>e.dispose()}}var Yn=require("@urun-sh/core"),uo="rt-video-out";var Rd="h264";function Ed(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function xd(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;Ed(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var gi="urun.videoOut.v2-ws";function hi(t){let e=t.stream(uo);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${uo}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=l=>{for(let u of r)u(l)},i=!1,a=async()=>{for await(let l of e.messages()){if(!(l instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${uo}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=xd(l)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(u)}for(let l of o)l()};return{codec:Rd,onOutputFrame:l=>(n.add(l),i||(i=!0,a().catch(u=>s(u instanceof Error?u:new Error(String(u))))),()=>n.delete(l)),onLaneError:l=>(r.add(l),()=>r.delete(l)),onEnd:l=>(o.add(l),()=>o.delete(l))}}var er="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Ad=1007,wi=1008,Be=1011,tr=1008,L=class extends Error{constructor(n,r=Ad){super(n);this.closeCode=r}closeCode},ie=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Xn=["setup","clientContent","realtimeInput","toolResponse"];function _i(t){let e;try{e=JSON.parse(t)}catch{throw new L("client message is not valid JSON")}let n=ie(e);if(!n)throw new L("client message must be a JSON object");let r=Xn.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Xn.includes(a));if(o.length>0)throw new L(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Xn.join(", ")}`);if(r.length!==1)throw new L(`client message must contain exactly one of ${Xn.join(", ")} (got ${r.length})`);let s=r[0],i=ie(n[s]);if(!i)throw new L(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function vi(t,e){if(typeof t=="string")return t;let n=ie(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new L(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=ie(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new L(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new L(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new L(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
2
- `)}var Id={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},nt="urun.videoOut";function bi(t){return{framing:gi,codec:t}}function Si(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[nt]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Td={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Od=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",nt],yi=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Pd(t){let e=ie(t);if(!e)throw new L("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new L(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ie(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new L("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new L(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new L("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!yi.includes(e.activityHandling))throw new L(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${yi.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Cd=["temperature","maxOutputTokens","responseModalities"];function ki(t){for(let[c,f]of Object.entries(Td))if(t[c]!==void 0)throw new L(f);for(let c of Object.keys(t))if(!Od.includes(c))throw new L(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new L('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=ie(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new L("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Cd.includes(c))throw new L(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new L("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new L("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let f of c){let g=String(f).toUpperCase();if(g==="AUDIO"){o=!0;continue}if(g!=="TEXT")throw new L(`responseModalities ${JSON.stringify(f)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:vi(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new L("setup.tools must be an array");a=[];for(let c of t.tools){let f=ie(c);if(!f)throw new L("setup.tools entries must be objects");for(let g of Object.keys(f))if(g!=="functionDeclarations")throw new L(`unsupported tool "${g}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new L("tool.functionDeclarations must be an array");for(let g of f.functionDeclarations){let m=ie(g);if(!m||typeof m.name!="string")throw new L("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ie(t.sessionResumption);if(!c)throw new L("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(c))if(f!=="handle")throw new L(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new L("sessionResumption.handle must be a non-empty string when present");l={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?Id:Pd(t.realtimeInputConfig),d=!1;if(t[nt]!==void 0){if(!ie(t[nt]))throw new L(`setup["${nt}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:u,sessionResumption:l,videoOut:d}}function Ri(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Ei(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function xi(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new L(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new L("clientContent.turns must be an array");let n=[];for(let r of e){let o=ie(r);if(!o)throw new L("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new L(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:vi(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Qn=16e3,Ai=24e3,Ld=`audio/pcm;rate=${Ai}`,Ii=Buffer.alloc(960).toString("base64");function $d(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let l=a*s,u=Math.floor(l);if(u>=i){o[a]=t[i];continue}let d=l-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*d)}return o}function Md(t){let e=ie(t);if(!e)throw new L("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new L(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new L("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new L("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Nd(t){let e=ie(t);if(!e)throw new L("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new L(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==Qn)throw new L(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Qn} Hz (audio/pcm;rate=${Qn})`);if(typeof e.data!="string"||e.data.length===0)throw new L("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new L(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=$d(o,Qn,Ai);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Ti(t){if(t.mediaChunks!==void 0)throw new L('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new L("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=ie(t[o]);if(!s||Object.keys(s).length!==0)throw new L(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new L(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new L(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Nd(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Md(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new L("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new L("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Oi(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new L(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new L("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ie(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new L("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Pi(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Ci(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Ld,data:t}}]}}}}function Li(t){let e=ie(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let u of n){let d=ie(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let f=ie(c);f?.type==="output_text"&&typeof f.text=="string"&&(s+=f.text)}}s&&o.push({role:"assistant",content:s});for(let u of n){let d=ie(u);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new L(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,Be);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",f;try{f=JSON.parse(c)}catch{throw new L(`upstream function_call arguments are not valid JSON: ${c}`,Be)}r.push({id:d.call_id,name:d.name,args:f}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=ie(e.usage),l={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(l.usageMetadata=u)}return i.push(l),{messages:i,assistantItems:o}}var sa=require("crypto"),ia=require("ws");var ta=require("crypto");var ee=class extends Error{},Ud=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Dd(t){if(typeof t!="string")return!1;let e=Ud.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Fd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new ee(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new ee(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new ee(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new ee(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new ee(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new ee(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new ee(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",Dd(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new ee(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new ee(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new ee(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new ee(`catalog "shared" block compliance carries "${l}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function Rt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function $i(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new ee(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function co(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new ee(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function Mi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new ee(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Fd(await r.json())}function we(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var ve=class extends Error{name="ModelPriceError"},po="per_million_input_tokens",fo="per_million_output_tokens",Ui="model_id,variant,unit,price_usd,effective_at,expires_at",Ni={per_request:!0,per_minute:!0,per_output_unit:!0},Bd=5e3;function Hd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ve(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Di(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ve(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function jd(t,e,n){return t===null?null:Di(t,e,n)}function qd(t,e){if(t===po)return"input";if(t===fo)return"output";if(typeof t=="string"&&Object.hasOwn(Ni,t))return null;throw new ve(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${po} | ${fo}) nor a known GPU-time unit (${Object.keys(Ni).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function Gd(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:n}}function mo(t,e){return`${t}\0${e}`}function Wd(t){if(!Array.isArray(t))throw new ve(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new ve(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of Ui.split(","))if(!Object.hasOwn(s,u))throw new ve(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=qd(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new ve(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new ve(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Hd(s.price_usd,o),effective_at:Di(s.effective_at,o,"effective_at"),expires_at:jd(s.expires_at,o,"expires_at")})}return e}function Fi(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,g,m)=>{let w=f&&f.length>0?f:d?.[g];if(!w||w.length===0)return null;let E=Gd(w,g);return"reason"in E?E:E.rate.usd===0?g==="output"&&m!==null&&n?.has(mo(l,m))?E.rate:{reason:`the ${g} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:E.rate};for(let[f,g]of o.get(l)){let m=u.get(f),w=c(m?.input,"input",g),E=c(m?.output,"output",g);if(w!==null&&"reason"in w){i.push({model_id:l,variant:g,reason:w.reason});continue}if(E!==null&&"reason"in E){i.push({model_id:l,variant:g,reason:E.reason});continue}w===null||E===null||s.push({model_id:l,variant:g,pricing:{input:w.usd,output:E.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function dn(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var cn={prices:[],refusals:[]};async function Bi(t){let e=t.fetchImpl??fetch,n=`${po},${fo}`,r=await e(`${t.catalogUrl}/model_prices?select=${Ui}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Bd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Wd(await r.json())}var ot="/partners/openrouter/models",Jd={chat:!0,code:!0,agent:!0,vl:!0},Hi={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Vd(t){let e=t.toLowerCase();return Object.hasOwn(Hi,e)?Hi[e]:null}var ji={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function Kd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(ji,o)?ji[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var qi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Gi={2:"Llama2",3:"Llama3"};function zd(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(qi,s))return qi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Gi,i))return Gi[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Yd=["context_length","max_model_len"];function Xd(t){let e=Yd.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function nr(t){let e=t.map(Xd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Qd(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function go(t){if(t.length===0)return null;let e=t.map(Qd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function ho(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function Zd(t,e){let n=e.filter(s=>we(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return pn(n);let r=e.filter(s=>we(s.model_id)===t);if(r.length>0)return pn(r);let o=ho(t,e);return o.length>0?pn(o):null}function pn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:ec(t),matches:t}:null}function ec(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var We=class extends Error{name="ModelCreatedError"};function Et(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new We(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new We(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new We(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new We(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function rt(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function rr(t,e,n){let r=Zd(t,e);if(!r)return rt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=nr(s),a=Et(s),l=dn(o.model_id,o.variant,n),u=Vi(o,s),d=go(s);return rt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var tc=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Vi(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...tc],defect:o}:{published:[],defect:o}}function yo(t){let e=t.length>0?pn(t):null;return e===null?{published:[],defect:null}:Vi(e.row,e.matches)}function Wi(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Ji(t){return{input:[{type:"prompt",unit:"token",cost_usd:Wi(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Wi(t.output)}]}}function nc(t,e,n,r){if(e.length===0)return null;let o=pn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Jd[s.task]!==!0)return null;let a=nr(i),l=dn(s.model_id,s.variant,n),u=zd(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Et(i),quantization:Vd(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:Ji(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:Ji(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Ki(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?Rt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:Kd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=nc(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}var zi={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},xt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Yi(t){let e=t.t;if(typeof e!="string"||!(e in zi))throw new xt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(zi).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function rc(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new xt(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new xt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Yi(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new xt(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return Yi(t)}function Xi(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function oc(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function Qi(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Xi(e);let s=o.next();if(e!==void 0&&await oc(s,e)==="aborted")throw s.catch(()=>{}),Xi(e);let i=await s;if(i.done)return;yield rc(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var J=class extends Error{},G=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},bo="credits_exhausted",So="insufficient_credits",_o="urs1.";function gn(t,e){return _o+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function st(t){if(!t.startsWith(_o))return null;try{let e=JSON.parse(Buffer.from(t.slice(_o.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function na(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Zi(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=ac(t);return e===null?[]:[e]}function sc(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
2
+ `)}var Id={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},nt="urun.videoOut";function bi(t){return{framing:gi,codec:t}}function Si(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[nt]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Td={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Od=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",nt],yi=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Pd(t){let e=ie(t);if(!e)throw new L("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new L(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ie(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new L("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new L(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new L("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!yi.includes(e.activityHandling))throw new L(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${yi.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Cd=["temperature","maxOutputTokens","responseModalities"];function ki(t){for(let[c,f]of Object.entries(Td))if(t[c]!==void 0)throw new L(f);for(let c of Object.keys(t))if(!Od.includes(c))throw new L(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new L('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=ie(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new L("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Cd.includes(c))throw new L(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new L("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new L("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let f of c){let g=String(f).toUpperCase();if(g==="AUDIO"){o=!0;continue}if(g!=="TEXT")throw new L(`responseModalities ${JSON.stringify(f)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:vi(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new L("setup.tools must be an array");a=[];for(let c of t.tools){let f=ie(c);if(!f)throw new L("setup.tools entries must be objects");for(let g of Object.keys(f))if(g!=="functionDeclarations")throw new L(`unsupported tool "${g}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new L("tool.functionDeclarations must be an array");for(let g of f.functionDeclarations){let m=ie(g);if(!m||typeof m.name!="string")throw new L("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ie(t.sessionResumption);if(!c)throw new L("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(c))if(f!=="handle")throw new L(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new L("sessionResumption.handle must be a non-empty string when present");l={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?Id:Pd(t.realtimeInputConfig),d=!1;if(t[nt]!==void 0){if(!ie(t[nt]))throw new L(`setup["${nt}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:u,sessionResumption:l,videoOut:d}}function Ri(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Ei(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function xi(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new L(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new L("clientContent.turns must be an array");let n=[];for(let r of e){let o=ie(r);if(!o)throw new L("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new L(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:vi(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Qn=16e3,Ai=24e3,Ld=`audio/pcm;rate=${Ai}`,Ii=Buffer.alloc(960).toString("base64");function $d(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let l=a*s,u=Math.floor(l);if(u>=i){o[a]=t[i];continue}let d=l-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*d)}return o}function Md(t){let e=ie(t);if(!e)throw new L("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new L(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new L("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new L("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Nd(t){let e=ie(t);if(!e)throw new L("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new L(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==Qn)throw new L(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Qn} Hz (audio/pcm;rate=${Qn})`);if(typeof e.data!="string"||e.data.length===0)throw new L("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new L(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=$d(o,Qn,Ai);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Ti(t){if(t.mediaChunks!==void 0)throw new L('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new L("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=ie(t[o]);if(!s||Object.keys(s).length!==0)throw new L(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new L(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new L(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Nd(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Md(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new L("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new L("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Oi(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new L(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new L("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ie(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new L("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Pi(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Ci(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Ld,data:t}}]}}}}function Li(t){let e=ie(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let u of n){let d=ie(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let f=ie(c);f?.type==="output_text"&&typeof f.text=="string"&&(s+=f.text)}}s&&o.push({role:"assistant",content:s});for(let u of n){let d=ie(u);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new L(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,Be);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",f;try{f=JSON.parse(c)}catch{throw new L(`upstream function_call arguments are not valid JSON: ${c}`,Be)}r.push({id:d.call_id,name:d.name,args:f}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=ie(e.usage),l={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(l.usageMetadata=u)}return i.push(l),{messages:i,assistantItems:o}}var sa=require("crypto"),ia=require("ws");var ta=require("crypto");var ee=class extends Error{},Ud=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Dd(t){if(typeof t!="string")return!1;let e=Ud.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Fd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new ee(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new ee(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new ee(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new ee(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new ee(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new ee(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new ee(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",Dd(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new ee(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new ee(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new ee(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new ee(`catalog "shared" block compliance carries "${l}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function Rt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function $i(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new ee(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function co(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new ee(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function Mi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new ee(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Fd(await r.json())}function we(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var ve=class extends Error{name="ModelPriceError"},po="per_million_input_tokens",fo="per_million_output_tokens",Ui="model_id,variant,unit,price_usd,effective_at,expires_at",Ni={per_request:!0,per_minute:!0,per_output_unit:!0},Bd=5e3;function Hd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ve(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Di(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ve(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function jd(t,e,n){return t===null?null:Di(t,e,n)}function qd(t,e){if(t===po)return"input";if(t===fo)return"output";if(typeof t=="string"&&Object.hasOwn(Ni,t))return null;throw new ve(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${po} | ${fo}) nor a known GPU-time unit (${Object.keys(Ni).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function Gd(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:n}}function mo(t,e){return`${t}\0${e}`}function Wd(t){if(!Array.isArray(t))throw new ve(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new ve(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of Ui.split(","))if(!Object.hasOwn(s,u))throw new ve(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=qd(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new ve(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new ve(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Hd(s.price_usd,o),effective_at:Di(s.effective_at,o,"effective_at"),expires_at:jd(s.expires_at,o,"expires_at")})}return e}function Fi(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,g,m)=>{let w=f&&f.length>0?f:d?.[g];if(!w||w.length===0)return null;let E=Gd(w,g);return"reason"in E?E:E.rate.usd===0?g==="output"&&m!==null&&n?.has(mo(l,m))?E.rate:{reason:`the ${g} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:E.rate};for(let[f,g]of o.get(l)){let m=u.get(f),w=c(m?.input,"input",g),E=c(m?.output,"output",g);if(w!==null&&"reason"in w){i.push({model_id:l,variant:g,reason:w.reason});continue}if(E!==null&&"reason"in E){i.push({model_id:l,variant:g,reason:E.reason});continue}w===null||E===null||s.push({model_id:l,variant:g,pricing:{input:w.usd,output:E.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function dn(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var cn={prices:[],refusals:[]};async function Bi(t){let e=t.fetchImpl??fetch,n=`${po},${fo}`,r=await e(`${t.catalogUrl}/model_prices?select=${Ui}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Bd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Wd(await r.json())}var ot="/partners/openrouter/models",Jd={chat:!0,code:!0,agent:!0,vl:!0},Hi={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Vd(t){let e=t.toLowerCase();return Object.hasOwn(Hi,e)?Hi[e]:null}var ji={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function Kd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(ji,o)?ji[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var qi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Gi={2:"Llama2",3:"Llama3"};function zd(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(qi,s))return qi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Gi,i))return Gi[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Yd=["context_length","max_model_len"];function Xd(t){let e=Yd.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function nr(t){let e=t.map(Xd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Qd(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function go(t){if(t.length===0)return null;let e=t.map(Qd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function ho(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function Zd(t,e){let n=e.filter(s=>we(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return pn(n);let r=e.filter(s=>we(s.model_id)===t);if(r.length>0)return pn(r);let o=ho(t,e);return o.length>0?pn(o):null}function pn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:ec(t),matches:t}:null}function ec(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var We=class extends Error{name="ModelCreatedError"};function Et(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new We(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new We(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new We(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new We(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function rt(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function rr(t,e,n){let r=Zd(t,e);if(!r)return rt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=nr(s),a=Et(s),l=dn(o.model_id,o.variant,n),u=Vi(o,s),d=go(s);return rt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var tc=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Vi(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...tc],defect:o}:{published:[],defect:o}}function yo(t){let e=t.length>0?pn(t):null;return e===null?{published:[],defect:null}:Vi(e.row,e.matches)}function Wi(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Ji(t){return{input:[{type:"prompt",unit:"token",cost_usd:Wi(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Wi(t.output)}]}}function nc(t,e,n,r){if(e.length===0)return null;let o=pn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Jd[s.task]!==!0)return null;let a=nr(i),l=dn(s.model_id,s.variant,n),u=zd(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Et(i),quantization:Vd(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:Ji(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:Ji(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Ki(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?Rt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:Kd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=nc(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}var zi={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_dropped:!0,turn_eager_end:!0,turn_resumed:!0},xt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Yi(t){let e=t.t;if(typeof e!="string"||!(e in zi))throw new xt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(zi).join(", ")}`);let n={kind:e};return e!=="turn_dropped"&&typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function rc(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new xt(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new xt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Yi(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new xt(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return Yi(t)}function Xi(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function oc(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function Qi(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Xi(e);let s=o.next();if(e!==void 0&&await oc(s,e)==="aborted")throw s.catch(()=>{}),Xi(e);let i=await s;if(i.done)return;yield rc(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var J=class extends Error{},G=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},bo="credits_exhausted",So="insufficient_credits",_o="urs1.";function gn(t,e){return _o+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function st(t){if(!t.startsWith(_o))return null;try{let e=JSON.parse(Buffer.from(t.slice(_o.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function na(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Zi(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=ac(t);return e===null?[]:[e]}function sc(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
3
3
  `),null;let e={},n=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],r=!1;for(let[o,s]of n){let i=t[o];if(i==null)continue;let a=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(a)||a<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
4
4
  `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function ko(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||we(`${r.model_id}-${r.variant}`)===e.appSlug||we(r.model_id)===e.appSlug)),n?sc(n.engine_args?.pool):null}function wo(t,e,n,r,o){if(!o)throw new ee(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new ee(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new ee(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function ea(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new ee(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var ra="shared:",At="speech:",Ke="realtime:";function Ve(t){return t.sharedApp?ra+t.appSlug:t.appSlug}function mn(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function vo(t,e){let n=e.filter(s=>we(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>we(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function ic(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function ac(t){let e=t.map(ic),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var lc={stt:"stt",tts:"tts"};function Je(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:lc[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function oa(t,e){let n=vo(t,e);return n.length>0?n:ho(t,e)}function fn(t,e){return oa(t.appSlug,e)}function uc(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new ee(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var or=6e4,sr=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??or):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??or):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??or):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??or;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof ve)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
5
5
  `),cn}let r=Fi(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
@@ -15,8 +15,8 @@ Connection: close\r
15
15
  Content-Type: text/plain; charset=utf-8\r
16
16
  Content-Length: ${Buffer.byteLength(o)}\r
17
17
  \r
18
- ${o}`)}function Uo(t,e){let n=new Xe.WebSocketServer({noServer:!0,maxPayload:Ec}),r=new ut,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 g;try{g=new URL(d.url??"/","http://localhost")}catch{lr(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),g.pathname!==Mo){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){lr(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(E){let R=e.statusOf?.(E)??null;lr(c,R?.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 $o(E,w,r,e.statusOf,e.operatorLog??(R=>console.error(R)))}catch{o.delete(E),E.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&lr(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=No();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let g of s)g.destroy();s.clear();for(let g of i)g.destroy();i.clear();for(let g of o)g.close(1001,"server shutting down");let f=setTimeout(()=>{for(let g of o)g.readyState!==Xe.WebSocket.CLOSED&&g.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}var Ko=require("@urun-sh/core");var ba=require("@urun-sh/core"),Pc={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},Cc={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 bn(t,e){let n=Cc[t.code];return e?`${n} (${e})`:n}function ur(t){if(t==null)return null;let e=Pc[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 dr(t){if(t.kind==="create-failed")return ur(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ba.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return ur(e?"cold_start_exceeded":"queue_timeout")}var Lc=fe(require("os"),1),$c=fe(require("path"),1),Mc=require("url"),Nc=require("util");function Sa(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function cr(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}var Uc=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Dc(t){let e=t?.code;return typeof e=="string"&&Uc.has(e)}function Qe(t,e){try{return t.write(e),!0}catch(n){if(Dc(n))return!1;throw n}}var Rn=require("ws");var xa=require("@urun-sh/core");var Ra=require("crypto");function M(t){return`${t}_${(0,Ra.randomUUID)().replace(/-/g,"").slice(0,24)}`}var pr=4*1024*1024,Do=8*1024*1024,Fo=512,Mt=20*1024*1024;function Z(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function De(t,e){return{type:"server_error",code:t,message:e}}function Y(t){return{type:"error",event_id:M("event"),error:t}}function Bo(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var D=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Fc={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},Bc={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Hc={format:!0,voice:!0,speed:!0};function jc(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function $t(t,e){if(!Array.isArray(t)||t.length===0)throw new D(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new D(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function ka(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new D(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var qc=10;function Ho(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:qc})}function Sn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new D("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Fc));if(s.length>0)throw new D(`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=$t(o.modalities,"modalities"),l=$t(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new D("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 D(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new D(`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 D('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 D(`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=$t(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new D('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(!jc(l))throw new D(`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 D("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new D("instructions must be a string or null","instructions");i.instructions=Ho(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new D("voice must be a string or null","voice");if(!n.voice)throw new D("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 D(`${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 D("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 D(`${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 D("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 D("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 D("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 D("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new D(`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,g]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new D(`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(g!=null&&g!==c[f])throw new D(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(g)}, 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 D("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 D("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 D(`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 D(`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 D("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 D("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 D("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Bc))throw new D(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&ka(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Sn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Sn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new D("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 D("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Hc))throw new D(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&ka(d.format,"audio.output.format"),d.speed!==void 0)throw new D("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 D("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new D("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 fr(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 jo(t,e){let n=t;if(!n||typeof n!="object")throw new D("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 D("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:M("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 D('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new D("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 D("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 D(`${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 D("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 D("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 D("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 D("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new D("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 D(`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:M("item"),type:"message",role:r,content:o}}throw new D(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function mr(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 Gc=1001,Wc=1011,Jc=6e4,Vc=3e5,qo=3;var gr=class extends Error{},hr=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},mt=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},Go=t=>t.slice(0,120),Kc=/^[A-Za-z0-9+/=]*$/,zc=600;function Wo(t){return zn(Buffer.from(t,"base64"))}var kn=class{id=M("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=Bo();sessionId=M("sess");conversationId=M("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;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??Jc,this.responseDeadlineMs=e.responseDeadlineMs??Vc,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===bo&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:M("event"),session:fr(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:M("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane(),this.binding.duplex&&this.ensureVoice();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 G&&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(Y(De("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:M("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:M("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:M("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:M("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:M("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),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:M("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:M("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:M("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=M("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:M("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:M("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:M("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:M("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.binding.duplex&&!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(Z("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>pr){this.fail(Z("frame_too_large",`frame exceeds the ${pr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(Z("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Z("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(Y({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof gr){this.fail(De(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}):
19
- ${o?.stack??Re(o)}`),this.send(Y(De(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Sn(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(Y(Z("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:M("event"),session:fr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=jo(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:M("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(Y(Z("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:M("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(Y(Z("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:M("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(Y(Z("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:M("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(Y(Z("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Kc.test(e.audio)){this.send(Y(Z("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.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>Mt&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${Mt}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${Mt} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>Mt&&this.pendingAudioBytes.length>0;){let s=this.pendingAudioBytes.shift();o-=Buffer.byteLength(s.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;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:M("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(Y(Z("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=M("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:M("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:M("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:M("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:M("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(Y(Z("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(Y(Z("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}if(this.binding.duplex){this.send(Y(Z("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);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(Y(Z("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,Go("session ended by client"))}catch{}});return}case"ping":return;default:this.send(Y(Z("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(Y(Z("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 gr("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(Y({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 hr),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,n=!1){if(this.inFlight){this.send(Y(Z("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?$t(r.modalities,"response.modalities"):void 0,s=r.output_modalities!==void 0?$t(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&s!==void 0&&o.slice().sort().join(",")!==s.slice().sort().join(","))throw new D("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((s??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(Y(Z("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,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},l=new Promise((x,I)=>{a=()=>I(new mt)});this.turnCancelled=l,this.wakeTurnCancelled=()=>a(),l.catch(()=>{});let u=()=>{},d=new Promise((x,I)=>{u=()=>I(new mt)});this.turnDialGate=d,this.wakeTurnDialGate=()=>u(),d.catch(()=>{});let c=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 f=M("req"),g=`resp_${f}`;this.activeResponseId=g,this.activeRequestId=f;let m=this.binding.composite===!0,w=m?0:this.items.length,E=m?null:mr(this.items),R=Ho(typeof r.instructions=="string"?r.instructions:this.config.instructions),v=typeof r.temperature=="number"?r.temperature:this.config.temperature,_=r.max_output_tokens??this.config.maxOutputTokens,p=_==="inf"||_===void 0?void 0:_,h=r.tools!==void 0?r.tools:this.config.tools,y=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...R!==void 0?{instructions:R}:{},...v!==void 0?{temperature:v}:{},...p!==void 0?{max_output_tokens:p}:{},...h!==void 0?{tools:h}:{},...y!==void 0?{tool_choice:y}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:x,captureWallMs:I}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(x,I);this.inFlight=(async()=>{let x=[],I=P=>{this.responseFlushed?this.send(P):x.push(P)},k=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:M("event"),response:this.responseObject(g,"in_progress")}),this.send({type:"response.in_progress",event_id:M("event"),response:this.responseObject(g,"in_progress")});for(let P of x)this.send(P);x.length=0,this.responseFlushed=!0}},A={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},b=null,T=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(g,A,w),k(),this.send({type:"response.done",event_id:M("event"),response:this.responseObject(g,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(H=>{this.pendingTranscriptSettled=H}),this.cancelled||this.closed))throw new mt;w=this.items.length,E=mr(this.items)}let{input:P,sawAudioOnlyItem:O}=E??{input:[],sawAudioOnlyItem:!1},C={...S,input:P,...m?this.compositeTurnAsk(r):{}};O&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let N;try{let H=this.upstreamStream(C,f);Promise.resolve(H).catch(U=>{U instanceof G&&this.failSessionGone(U)}),N=await Promise.race([H,d])}catch(H){if(H instanceof mt){this.deadlineFired&&!this.closed&&T();return}this.upstreamTurnFault(H,g);return}k();try{for await(let H of this.stallBoundedTurn(N)){if(this.cancelled)break;let U=H;if(U.type==="error"){let K=this.upstreamErrorBody(U);A.contentFlowed?this.send(Y(K)):this.send({type:"response.failed",event_id:M("event"),response:this.failedResponse(g,K)});return}if(U.type==="response.output_text.delta"&&typeof U.delta=="string"){k(),A.contentFlowed=!0,A.messageOpen||(this.beginMessageItem(g,A.nextOutputIndex++),A.messageOpen=!0),this.config.outputModalities.includes("text")&&I({type:"response.output_text.delta",event_id:M("event"),item_id:`${g}_msg_0`,response_id:g,output_index:0,content_index:0,delta:U.delta}),this.turnOutputIsAudio()&&(A.transcriptDelta=!0,I({type:"response.output_audio_transcript.delta",event_id:M("event"),item_id:`${g}_msg_0`,response_id:g,output_index:0,content_index:0,delta:U.delta})),A.messageText+=U.delta;continue}if(U.type==="response.function_call_arguments.delta"){k(),A.contentFlowed=!0;let K=typeof U.delta=="string"?U.delta:"",F=typeof U.call_id=="string"&&U.call_id.length>0?U.call_id:`${g}_fc_${A.nextOutputIndex}`,B=A.tools.get(F);if(!B){let z=typeof U.name=="string"&&U.name.length>0?U.name:void 0;B={outputIndex:A.nextOutputIndex++,name:z,args:""},A.tools.set(F,B);let Me={id:F,object:"realtime.item",type:"function_call",call_id:F,name:z??"",arguments:"",status:"in_progress"};I({type:"response.output_item.added",event_id:M("event"),response_id:g,output_index:B.outputIndex,item:Me}),this.emitAssistantItemAdded(Me)}typeof U.name=="string"&&U.name.length>0&&(B.name=U.name),B.args+=K,I({type:"response.function_call_arguments.delta",event_id:M("event"),item_id:F,response_id:g,output_index:B.outputIndex,call_id:F,name:B.name??"",delta:K});continue}if(U.type==="response.completed"){b=U.response??null;continue}}}catch(H){if(this.closed)return;if(H instanceof mt){this.deadlineFired&&T();return}if(this.cancelled)return;if(H instanceof hr)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${g} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(H,g);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&T();return}this.closeOpenItems(g,A,w),k(),this.send({type:"response.done",event_id:M("event"),response:this.doneResponse(g,w,b)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(A.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=qo){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${qo} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(Y(De("member_unresponsive",`the member served no content for ${qo} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}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.binding.duplex){if(this.activeResponseId===null){if(Wo(n))return;this.openDuplexResponse()}else if(Wo(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=zc){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(Wo(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(Y({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:M("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:M("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.turnOutputFlowed=!0,this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:M("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${M("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:M("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}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:M("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:M("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:M("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:M("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:M("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:M("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:M("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:M("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:M("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:M("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:M("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:M("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:M("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=Ue(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??Oe(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(De(So,"the organization is out of credits \u2014 top up to continue"),So))}failSessionGone(e){if(e instanceof G&&e.reason===bo){this.failInsufficientCredits();return}let n=e instanceof Error&&Te(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: ${Re(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(De("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof G){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof xa.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=De(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(Y(r)):this.send({type:"response.failed",event_id:M("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(Y(Z("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:M("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Fo&&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(Y(Z("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>un){this.send(Y(Z("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${un}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(Y(Z("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(Y(De(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>Do){this.ws.close(Gc,Go("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=_e(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Re(e)}`),r.message}fail(e,n){this.send(Y(e)),this.ws.close(Wc,Go(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=>Ea(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Ea(this.id,e)}},Jo=[];function Ea(t,e){Jo.push({id:t,reason:e}),Jo.length>256&&Jo.shift()}var En="/v1/realtime",Aa="urun.admission",Ia=t=>t.slice(0,120);function Yc(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
18
+ ${o}`)}function Uo(t,e){let n=new Xe.WebSocketServer({noServer:!0,maxPayload:Ec}),r=new ut,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 g;try{g=new URL(d.url??"/","http://localhost")}catch{lr(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),g.pathname!==Mo){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){lr(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(E){let R=e.statusOf?.(E)??null;lr(c,R?.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 $o(E,w,r,e.statusOf,e.operatorLog??(R=>console.error(R)))}catch{o.delete(E),E.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&lr(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=No();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let g of s)g.destroy();s.clear();for(let g of i)g.destroy();i.clear();for(let g of o)g.close(1001,"server shutting down");let f=setTimeout(()=>{for(let g of o)g.readyState!==Xe.WebSocket.CLOSED&&g.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}var Ko=require("@urun-sh/core");var ba=require("@urun-sh/core"),Pc={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},Cc={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 bn(t,e){let n=Cc[t.code];return e?`${n} (${e})`:n}function ur(t){if(t==null)return null;let e=Pc[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 dr(t){if(t.kind==="create-failed")return ur(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ba.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return ur(e?"cold_start_exceeded":"queue_timeout")}var Lc=fe(require("os"),1),$c=fe(require("path"),1),Mc=require("url"),Nc=require("util");function Sa(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function cr(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}var Uc=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Dc(t){let e=t?.code;return typeof e=="string"&&Uc.has(e)}function Qe(t,e){try{return t.write(e),!0}catch(n){if(Dc(n))return!1;throw n}}var Rn=require("ws");var xa=require("@urun-sh/core");var Ra=require("crypto");function M(t){return`${t}_${(0,Ra.randomUUID)().replace(/-/g,"").slice(0,24)}`}var pr=4*1024*1024,Do=8*1024*1024,Fo=512,Mt=20*1024*1024;function Z(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function De(t,e){return{type:"server_error",code:t,message:e}}function Y(t){return{type:"error",event_id:M("event"),error:t}}function Bo(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var D=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Fc={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},Bc={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Hc={format:!0,voice:!0,speed:!0};function jc(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function $t(t,e){if(!Array.isArray(t)||t.length===0)throw new D(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new D(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function ka(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new D(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var qc=10;function Ho(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:qc})}function Sn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new D("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Fc));if(s.length>0)throw new D(`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=$t(o.modalities,"modalities"),l=$t(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new D("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 D(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new D(`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 D('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 D(`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=$t(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new D('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(!jc(l))throw new D(`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 D("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new D("instructions must be a string or null","instructions");i.instructions=Ho(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new D("voice must be a string or null","voice");if(!n.voice)throw new D("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 D(`${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 D("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 D(`${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 D("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 D("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 D("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 D("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new D(`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,g]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new D(`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(g!=null&&g!==c[f])throw new D(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(g)}, 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 D("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 D("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 D(`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 D(`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 D("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 D("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 D("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Bc))throw new D(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&ka(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Sn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Sn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new D("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 D("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Hc))throw new D(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&ka(d.format,"audio.output.format"),d.speed!==void 0)throw new D("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 D("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new D("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 fr(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 jo(t,e){let n=t;if(!n||typeof n!="object")throw new D("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 D("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:M("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 D('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new D("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 D("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 D(`${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 D("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 D("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 D("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 D("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new D("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 D(`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:M("item"),type:"message",role:r,content:o}}throw new D(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function mr(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 Gc=1001,Wc=1011,Jc=6e4,Vc=3e5,qo=3;var gr=class extends Error{},hr=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},mt=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},Go=t=>t.slice(0,120),Kc=/^[A-Za-z0-9+/=]*$/,zc=600;function Wo(t){return zn(Buffer.from(t,"base64"))}var kn=class{id=M("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=Bo();sessionId=M("sess");conversationId=M("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;userTurnOpen=!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??Jc,this.responseDeadlineMs=e.responseDeadlineMs??Vc,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===bo&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:M("event"),session:fr(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:M("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane(),this.binding.duplex&&this.ensureVoice();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 G&&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(Y(De("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:M("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:M("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:M("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:M("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:M("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.userTurnOpen=!0,this.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{this.userTurnOpen=!1;let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:M("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:M("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:M("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=M("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:M("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:M("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:M("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:M("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.binding.duplex&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_dropped":{this.userTurnOpen=!1,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:M("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});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(Z("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>pr){this.fail(Z("frame_too_large",`frame exceeds the ${pr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(Z("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Z("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(Y({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof gr){this.fail(De(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}):
19
+ ${o?.stack??Re(o)}`),this.send(Y(De(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Sn(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(Y(Z("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:M("event"),session:fr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=jo(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:M("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(Y(Z("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:M("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(Y(Z("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:M("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(Y(Z("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:M("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(Y(Z("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Kc.test(e.audio)){this.send(Y(Z("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.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>Mt&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${Mt}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${Mt} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>Mt&&this.pendingAudioBytes.length>0;){let s=this.pendingAudioBytes.shift();o-=Buffer.byteLength(s.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;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:M("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(Y(Z("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=M("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:M("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:M("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:M("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:M("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(Y(Z("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(Y(Z("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}if(this.binding.duplex){this.send(Y(Z("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);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(Y(Z("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,Go("session ended by client"))}catch{}});return}case"ping":return;default:this.send(Y(Z("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(Y(Z("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 gr("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(Y({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 hr),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,n=!1){if(this.inFlight){this.send(Y(Z("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?$t(r.modalities,"response.modalities"):void 0,s=r.output_modalities!==void 0?$t(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&s!==void 0&&o.slice().sort().join(",")!==s.slice().sort().join(","))throw new D("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((s??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(Y(Z("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,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},l=new Promise((x,I)=>{a=()=>I(new mt)});this.turnCancelled=l,this.wakeTurnCancelled=()=>a(),l.catch(()=>{});let u=()=>{},d=new Promise((x,I)=>{u=()=>I(new mt)});this.turnDialGate=d,this.wakeTurnDialGate=()=>u(),d.catch(()=>{});let c=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 f=M("req"),g=`resp_${f}`;this.activeResponseId=g,this.activeRequestId=f;let m=this.binding.composite===!0,w=m?0:this.items.length,E=m?null:mr(this.items),R=Ho(typeof r.instructions=="string"?r.instructions:this.config.instructions),v=typeof r.temperature=="number"?r.temperature:this.config.temperature,_=r.max_output_tokens??this.config.maxOutputTokens,p=_==="inf"||_===void 0?void 0:_,h=r.tools!==void 0?r.tools:this.config.tools,y=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...R!==void 0?{instructions:R}:{},...v!==void 0?{temperature:v}:{},...p!==void 0?{max_output_tokens:p}:{},...h!==void 0?{tools:h}:{},...y!==void 0?{tool_choice:y}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:x,captureWallMs:I}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(x,I);this.inFlight=(async()=>{let x=[],I=P=>{this.responseFlushed?this.send(P):x.push(P)},k=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:M("event"),response:this.responseObject(g,"in_progress")}),this.send({type:"response.in_progress",event_id:M("event"),response:this.responseObject(g,"in_progress")});for(let P of x)this.send(P);x.length=0,this.responseFlushed=!0}},A={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},b=null,T=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(g,A,w),k(),this.send({type:"response.done",event_id:M("event"),response:this.responseObject(g,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(H=>{this.pendingTranscriptSettled=H}),this.cancelled||this.closed))throw new mt;w=this.items.length,E=mr(this.items)}let{input:P,sawAudioOnlyItem:O}=E??{input:[],sawAudioOnlyItem:!1},C={...S,input:P,...m?this.compositeTurnAsk(r):{}};O&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let N;try{let H=this.upstreamStream(C,f);Promise.resolve(H).catch(U=>{U instanceof G&&this.failSessionGone(U)}),N=await Promise.race([H,d])}catch(H){if(H instanceof mt){this.deadlineFired&&!this.closed&&T();return}this.upstreamTurnFault(H,g);return}k();try{for await(let H of this.stallBoundedTurn(N)){if(this.cancelled)break;let U=H;if(U.type==="error"){let K=this.upstreamErrorBody(U);A.contentFlowed?this.send(Y(K)):this.send({type:"response.failed",event_id:M("event"),response:this.failedResponse(g,K)});return}if(U.type==="response.output_text.delta"&&typeof U.delta=="string"){k(),A.contentFlowed=!0,A.messageOpen||(this.beginMessageItem(g,A.nextOutputIndex++),A.messageOpen=!0),this.config.outputModalities.includes("text")&&I({type:"response.output_text.delta",event_id:M("event"),item_id:`${g}_msg_0`,response_id:g,output_index:0,content_index:0,delta:U.delta}),this.turnOutputIsAudio()&&(A.transcriptDelta=!0,I({type:"response.output_audio_transcript.delta",event_id:M("event"),item_id:`${g}_msg_0`,response_id:g,output_index:0,content_index:0,delta:U.delta})),A.messageText+=U.delta;continue}if(U.type==="response.function_call_arguments.delta"){k(),A.contentFlowed=!0;let K=typeof U.delta=="string"?U.delta:"",F=typeof U.call_id=="string"&&U.call_id.length>0?U.call_id:`${g}_fc_${A.nextOutputIndex}`,B=A.tools.get(F);if(!B){let z=typeof U.name=="string"&&U.name.length>0?U.name:void 0;B={outputIndex:A.nextOutputIndex++,name:z,args:""},A.tools.set(F,B);let Me={id:F,object:"realtime.item",type:"function_call",call_id:F,name:z??"",arguments:"",status:"in_progress"};I({type:"response.output_item.added",event_id:M("event"),response_id:g,output_index:B.outputIndex,item:Me}),this.emitAssistantItemAdded(Me)}typeof U.name=="string"&&U.name.length>0&&(B.name=U.name),B.args+=K,I({type:"response.function_call_arguments.delta",event_id:M("event"),item_id:F,response_id:g,output_index:B.outputIndex,call_id:F,name:B.name??"",delta:K});continue}if(U.type==="response.completed"){b=U.response??null;continue}}}catch(H){if(this.closed)return;if(H instanceof mt){this.deadlineFired&&T();return}if(this.cancelled)return;if(H instanceof hr)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${g} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(H,g);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&T();return}this.closeOpenItems(g,A,w),k(),this.send({type:"response.done",event_id:M("event"),response:this.doneResponse(g,w,b)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(A.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=qo){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${qo} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(Y(De("member_unresponsive",`the member served no content for ${qo} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}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.binding.duplex){if(this.activeResponseId===null){if(Wo(n)||this.userTurnOpen)return;this.openDuplexResponse()}else if(Wo(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=zc){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(Wo(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(Y({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:M("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:M("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.turnOutputFlowed=!0,this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:M("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${M("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:M("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}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:M("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:M("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:M("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:M("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:M("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:M("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:M("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:M("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:M("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:M("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:M("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:M("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:M("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=Ue(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??Oe(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(De(So,"the organization is out of credits \u2014 top up to continue"),So))}failSessionGone(e){if(e instanceof G&&e.reason===bo){this.failInsufficientCredits();return}let n=e instanceof Error&&Te(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: ${Re(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(De("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof G){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof xa.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=De(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(Y(r)):this.send({type:"response.failed",event_id:M("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(Y(Z("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:M("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Fo&&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(Y(Z("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>un){this.send(Y(Z("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${un}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(Y(Z("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(Y(De(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>Do){this.ws.close(Gc,Go("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=_e(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Re(e)}`),r.message}fail(e,n){this.send(Y(e)),this.ws.close(Wc,Go(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=>Ea(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Ea(this.id,e)}},Jo=[];function Ea(t,e){Jo.push({id:t,reason:e}),Jo.length>256&&Jo.shift()}var En="/v1/realtime",Aa="urun.admission",Ia=t=>t.slice(0,120);function Yc(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
20
20
  Connection: close\r
21
21
  Content-Type: text/plain\r
22
22
  \r
@@ -1,5 +1,5 @@
1
1
  import { Server } from 'node:http';
2
- import { c as LedgerOutcome, I as InferenceRecord, m as RouteTarget, S as SessionGoneError, p as billingIdentityOf, P as ProxyClients, M as ModelRouter, n as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, l as RealtimeCompanionsFor } from '../composite-C1oeSkNz.cjs';
2
+ import { c as LedgerOutcome, I as InferenceRecord, m as RouteTarget, S as SessionGoneError, p as billingIdentityOf, P as ProxyClients, M as ModelRouter, n as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, l as RealtimeCompanionsFor } from '../composite-4JhDPmCP.cjs';
3
3
  import * as _prometheus_io_client from '@prometheus-io/client';
4
4
  import { Registry } from '@prometheus-io/client';
5
5
  import { createClientToken, SessionPhaseName } from '@urun-sh/core';
@@ -1,5 +1,5 @@
1
1
  import { Server } from 'node:http';
2
- import { c as LedgerOutcome, I as InferenceRecord, m as RouteTarget, S as SessionGoneError, p as billingIdentityOf, P as ProxyClients, M as ModelRouter, n as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, l as RealtimeCompanionsFor } from '../composite-CmDZAzTq.js';
2
+ import { c as LedgerOutcome, I as InferenceRecord, m as RouteTarget, S as SessionGoneError, p as billingIdentityOf, P as ProxyClients, M as ModelRouter, n as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, l as RealtimeCompanionsFor } from '../composite-BjRgfMOX.js';
3
3
  import * as _prometheus_io_client from '@prometheus-io/client';
4
4
  import { Registry } from '@prometheus-io/client';
5
5
  import { createClientToken, SessionPhaseName } from '@urun-sh/core';
@@ -1 +1 @@
1
- import{A as g,B as x,C as H,D as B,E as P,F as v,G as y,H as u,I as G,J as h,K as U,L as b,M as X,N as F,O as K,P as Y,Q as k,R as V,S as j,T as W,U as q,V as w,W as z,X as J,Y as Q,Z,a as r,b as o,c as t,d as E,e as _,f as n,g as a,h as T,i,j as s,k as M,l as O,m as p,n as I,o as R,p as S,q as A,r as C,s as D,t as N,u as f,v as L,w as d,x as l,y as m,z as c}from"../chunk-4UE7XH7T.js";import"../chunk-HLSJAQHY.js";import"../chunk-CAR4AEQJ.js";import"../chunk-PPEND4SP.js";import"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import"../chunk-BVM4ZQ2Y.js";import"../chunk-KNWFUWXY.js";import"../chunk-Z74YK7AL.js";import"../chunk-XNRPTMSL.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-N3Y2GDQK.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{A as ANONYMOUS_KEY_ID,G as BIND_HOST,R as BUCKET_DOMAIN,i as BoundedLabel,d as ControlPlaneUnavailableError,k as ConversationBackhauls,Y as ConversationCapacityError,y as DEFAULT_PORT,O as EDGE_IDENTITY_PORT,I as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,s as InferenceMetrics,V as LEDGER_FUNCTION_PATH,j as LEDGER_WRITE_TIMEOUT_MS,z as LedgerClient,W as LedgerDuplicateError,q as LedgerSurfaceError,c as MAX_CACHED_KEYS,B as MAX_CACHED_MEMBERSHIPS,F as MAX_CONVERSATIONS,K as MAX_CONVERSATION_HANDLES,_ as MAX_MODEL_LABELS,n as MAX_ORG_LABELS,U as MAX_TENANTS,H as MEMBERSHIP_CHECK_TIMEOUT_MS,x as MEMBERSHIP_VERDICT_TTL_MS,o as METRICS_PATH,r as METRICS_PORT,v as MembershipGate,P as MembershipRefusalError,E as NO_MODEL_LABEL,m as ORG_BINDING_TTL_MS,t as OTHER_LABEL,g as OrgResolver,L as ProxyAuthError,Q as READINESS_TIMEOUT_MS,J as READINESS_TTL_MS,u as SERVE_FUNCTION,S as TIER_DOMAIN,X as TenantRegistry,l as bearerFrom,N as bearerTokenOf,f as createEdgeIdentityServer,Z as createHostedProxy,M as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,w as parseLedgerRecorded,h as resolveHostedConfig,T as statusClassOf,b as tenantSubject};
1
+ import{A as g,B as x,C as H,D as B,E as P,F as v,G as y,H as u,I as G,J as h,K as U,L as b,M as X,N as F,O as K,P as Y,Q as k,R as V,S as j,T as W,U as q,V as w,W as z,X as J,Y as Q,Z,a as r,b as o,c as t,d as E,e as _,f as n,g as a,h as T,i,j as s,k as M,l as O,m as p,n as I,o as R,p as S,q as A,r as C,s as D,t as N,u as f,v as L,w as d,x as l,y as m,z as c}from"../chunk-SNCDIY53.js";import"../chunk-HIM6EB3J.js";import"../chunk-CAR4AEQJ.js";import"../chunk-RONITPWW.js";import"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import"../chunk-2VZR5MAX.js";import"../chunk-EA3GQ2MM.js";import"../chunk-O3Z5AY5E.js";import"../chunk-XNRPTMSL.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-4GW343S5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{A as ANONYMOUS_KEY_ID,G as BIND_HOST,R as BUCKET_DOMAIN,i as BoundedLabel,d as ControlPlaneUnavailableError,k as ConversationBackhauls,Y as ConversationCapacityError,y as DEFAULT_PORT,O as EDGE_IDENTITY_PORT,I as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,s as InferenceMetrics,V as LEDGER_FUNCTION_PATH,j as LEDGER_WRITE_TIMEOUT_MS,z as LedgerClient,W as LedgerDuplicateError,q as LedgerSurfaceError,c as MAX_CACHED_KEYS,B as MAX_CACHED_MEMBERSHIPS,F as MAX_CONVERSATIONS,K as MAX_CONVERSATION_HANDLES,_ as MAX_MODEL_LABELS,n as MAX_ORG_LABELS,U as MAX_TENANTS,H as MEMBERSHIP_CHECK_TIMEOUT_MS,x as MEMBERSHIP_VERDICT_TTL_MS,o as METRICS_PATH,r as METRICS_PORT,v as MembershipGate,P as MembershipRefusalError,E as NO_MODEL_LABEL,m as ORG_BINDING_TTL_MS,t as OTHER_LABEL,g as OrgResolver,L as ProxyAuthError,Q as READINESS_TIMEOUT_MS,J as READINESS_TTL_MS,u as SERVE_FUNCTION,S as TIER_DOMAIN,X as TenantRegistry,l as bearerFrom,N as bearerTokenOf,f as createEdgeIdentityServer,Z as createHostedProxy,M as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,w as parseLedgerRecorded,h as resolveHostedConfig,T as statusClassOf,b as tenantSubject};
@@ -1,4 +1,4 @@
1
- import{a as z}from"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import{h as W,o as Q}from"../chunk-N3Y2GDQK.js";import{c as C}from"../chunk-YSFSRI3D.js";C();import{createAssistantMessageEventStream as he}from"@earendil-works/pi-ai";import{mkdirSync as we,openSync as _e,writeSync as ke}from"fs";import{dirname as ve}from"path";C();import{appendFileSync as de,mkdirSync as pe}from"fs";import fe from"os";import{dirname as ge,join as me}from"path";import{format as ye}from"util";function J(t=fe.homedir()){return me(t,".urun","logs","pi-extension.log")}var V=!1;function te(t,e){let n=J();try{pe(ge(n),{recursive:!0}),de(n,`${new Date().toISOString()} [console.${t}] [urun] ${ye(...e)}
1
+ import{a as z}from"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import{h as W,o as Q}from"../chunk-4GW343S5.js";import{c as C}from"../chunk-YSFSRI3D.js";C();import{createAssistantMessageEventStream as he}from"@earendil-works/pi-ai";import{mkdirSync as we,openSync as _e,writeSync as ke}from"fs";import{dirname as ve}from"path";C();import{appendFileSync as de,mkdirSync as pe}from"fs";import fe from"os";import{dirname as ge,join as me}from"path";import{format as ye}from"util";function J(t=fe.homedir()){return me(t,".urun","logs","pi-extension.log")}var V=!1;function te(t,e){let n=J();try{pe(ge(n),{recursive:!0}),de(n,`${new Date().toISOString()} [console.${t}] [urun] ${ye(...e)}
2
2
  `)}catch(o){if(!V){V=!0;try{process.stderr.write(`[urun] pi-extension quiet console: cannot write ${n} (${String(o)}); further urun-side console output will be dropped
3
3
  `)}catch{}}}}var f=t=>(...e)=>te(t,e),j={log:f("log"),info:f("info"),warn:f("warn"),error:f("error"),debug:f("debug"),trace:f("trace"),dir:f("dir"),table:f("table"),group:f("group"),groupCollapsed:f("groupCollapsed"),groupEnd:f("groupEnd"),count:f("count"),countReset:f("countReset"),time:f("time"),timeLog:f("timeLog"),timeEnd:f("timeEnd"),assert:(t,...e)=>{t||te("assert",e.length>0?e:["Assertion failed"])}};function q(t){try{process.stderr.write(t)}catch{}}C();async function ne(t){let e=await Q(t),n=e.filter(o=>o.function_name===t.fnName&&o.deployment_status==="active").map(o=>o.app_slug);if(n.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${t.fnName}" (GET ${t.apiUrl}/apps returned ${e.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return n.sort()}var ae="urun-serve",xe="serve",Re=131072,be=16384,oe=3,Te=42e4,Ee=6e4,re=2,Se=15e3;function Ae(t){let e=(t.URUN_API_KEY??"").trim();if(!e)throw new Error("urun pi extension: URUN_API_KEY is required \u2014 model discovery lists the org's deployed serve apps via the org API (URUN_JWT alone cannot list apps)");return{apiKey:e,apiUrl:(t.URUN_API_URL??"").trim()||W,fnName:(t.URUN_FUNCTION??"").trim()||xe}}function Ue(t){let e=(t.URUN_BASE_URL??"").trim(),n=(t.URUN_ORG_ID??"").trim();if(!e)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org API form (URUN_API_URL); session allocation 404s against it. Drop the /v1.`);if(!n)throw new Error("urun pi extension: URUN_ORG_ID is required to open a session");let o=(t.URUN_JWT??"").trim();if(o)return{baseUrl:e,orgId:n,auth:{lane:"jwt",jwt:o}};let s=(t.URUN_API_KEY??"").trim();if(!s)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let l=(t.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:e,orgId:n,auth:{lane:"api-key",apiKey:s,gatewayUrl:l}}}function Ie(t){let e=null;return n=>{e===null&&(we(ve(t),{recursive:!0}),e=_e(t,"a"));let o=n.detail?` ${JSON.stringify(n.detail)}`:"";ke(e,`${new Date().toISOString()} [${n.level}] [urun] ${n.message}${o}
4
4
  `)}}function Pe(t){let e=Ie(J());return async(n,o,s)=>{let{baseUrl:l,orgId:i,auth:p}=Ue(n),{App:k,createClientToken:a}=await t(),m=(p.lane==="jwt"?k(o,{baseUrl:l,orgId:i,jwt:p.jwt,diagnosticSink:e}):k(o,{baseUrl:l,orgId:i,diagnosticSink:e,getAccessToken:async()=>(await a(p.apiKey,{baseUrl:p.gatewayUrl,expiresIn:300,allowedFunctions:[`${o}/${s}`]})).token}))[s];if(typeof m!="function")throw new Error(`urun pi extension: app "${o}" has no function "${s}"`);let h=m();if(typeof h.end!="function")throw new Error(`urun pi extension: app "${o}" function "${s}" returned a session without end()`);let A=h.connect;return typeof A=="function"&&await A.call(h),h}}var Ce=Pe(async()=>{let{createRequire:t}=await import("module"),e=t(import.meta.url);if(typeof globalThis.RTCPeerConnection>"u")try{e.resolve("werift")}catch{throw new Error('urun pi extension: token streams require a WebRTC data channel, and this Node runtime has no RTCPeerConnection and no "werift" backend installed (@urun-sh/core\'s optional Node WebRTC backend \u2014 it was probably stripped by a --no-optional install). Install werift (`npm i werift`) and retry.')}return e("@urun-sh/core")});function Ne(t,e){try{return Promise.resolve(t.end()).then(()=>{},n=>e(n))}catch(n){return e(n),Promise.resolve()}}function $e(t){if(t?.hasUI===!1)return!0;if(t?.hasUI===!0)return!1;let e=process.argv.slice(2);if(e.includes("-p")||e.includes("--print"))return!0;let n=e.indexOf("--mode");return n!==-1&&(e[n+1]==="json"||e[n+1]==="rpc")?!0:!process.stdin.isTTY||!process.stdout.isTTY}function le(t,e){return`uRun: releasing the pooled "${t}" session failed \u2014 the backend session may stay allocated until the platform reclaims it: ${e instanceof Error?e.message:String(e)}`}var H=class{constructor(e,n,o,s=(l,i)=>j.warn(le(l,i))){this.open=e;this.env=n;this.fnName=o;this.onReleaseError=s}open;env;fnName;onReleaseError;pool=new Map;releasing=new Set;acquire(e){let n=this.pool.get(e);if(!n){let o=Promise.resolve(this.open(this.env,e,this.fnName)).then(s=>({session:s,responses:new z(s)}));n=o,this.pool.set(e,o),o.catch(()=>{this.pool.get(e)===o&&this.pool.delete(e)})}return n}evict(e){let n=this.pool.get(e);if(!n)return Promise.resolve();this.pool.delete(e);let o=n.then(s=>Ne(s.session,l=>this.onReleaseError(e,l)),()=>{});return this.releasing.add(o),o.then(()=>this.releasing.delete(o)),o}closeAll(){let e=[...this.pool.keys()].map(n=>this.evict(n));return Promise.all([...e,...this.releasing]).then(()=>{})}};function Le(t){let e=[];t.systemPrompt&&e.push({role:"system",content:t.systemPrompt});for(let n of t.messages){if(n.role==="toolResult"){e.push({type:"function_call_output",call_id:n.toolCallId,output:De(n.content)});continue}if(n.role==="assistant"&&Array.isArray(n.content)){let s="",l=()=>{s&&(e.push({role:"assistant",content:s}),s="")};for(let i of n.content)if(i.type==="text")s+=String(i.text??"");else if(i.type==="toolCall")l(),e.push({type:"function_call",call_id:String(i.id??""),name:String(i.name??""),arguments:JSON.stringify(i.arguments??{})});else{if(i.type==="thinking")continue;throw new Error(`urun pi extension: unsupported assistant content part "${String(i.type)}"`)}l();continue}let o=n.role==="assistant"?"assistant":"user";e.push({role:o,content:Me(n.content)})}return Oe(e)}function Oe(t){let e=[];for(let n of t){let o=e[e.length-1];o&&"role"in o&&"role"in n&&o.role===n.role?o.content=[o.content,n.content].filter(s=>s.length>0).join(`