@urun-sh/openai 0.6.21 → 0.6.22

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,57 +1,57 @@
1
- "use strict";var Qr=Object.create;var it=Object.defineProperty;var Zr=Object.getOwnPropertyDescriptor;var eo=Object.getOwnPropertyNames;var to=Object.getPrototypeOf,no=Object.prototype.hasOwnProperty;var ro=(t,e)=>{for(var n in e)it(t,n,{get:e[n],enumerable:!0})},pn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of eo(e))!no.call(t,o)&&o!==n&&it(t,o,{get:()=>e[o],enumerable:!(r=Zr(e,o))||r.enumerable});return t};var fn=(t,e,n)=>(n=t!=null?Qr(to(t)):{},pn(e||!t||!t.__esModule?it(n,"default",{value:t,enumerable:!0}):n,t)),oo=t=>pn(it({},"__esModule",{value:!0}),t);var xs={};ro(xs,{GEMINI_LIVE_PATH:()=>lt,OPENAI_REALTIME_PATH:()=>We,OpenAIRealtimeConnection:()=>Se,ResumptionRegistry:()=>Oe,SessionGoneError:()=>ne,UnknownModelError:()=>N,VIDEO_OUT_SETUP_KEY:()=>le,attachGeminiLive:()=>ft,attachOpenAIRealtime:()=>Ke,createOpenAIProxy:()=>Xr,fixedClientsResolver:()=>bt,realtimeBindingFor:()=>Qt,realtimeModelOf:()=>Xt,serveGeminiLiveSocket:()=>Mn});module.exports=oo(xs);var Kr=require("http");var Cn=require("crypto"),$n=require("ws");var Fe="/partners/openrouter/models";var N=class extends Error{},ne=class extends Error{};var st=require("@urun-sh/core");var mn="urun.videoOut.v2-ws";var lt="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",uo=1007,hn=1008,ce=1011,ct=1008,w=class extends Error{constructor(n,r=uo){super(n);this.closeCode=r}closeCode},q=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,at=["setup","clientContent","realtimeInput","toolResponse"];function yn(t){let e;try{e=JSON.parse(t)}catch{throw new w("client message is not valid JSON")}let n=q(e);if(!n)throw new w("client message must be a JSON object");let r=at.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!at.includes(a));if(o.length>0)throw new w(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${at.join(", ")}`);if(r.length!==1)throw new w(`client message must contain exactly one of ${at.join(", ")} (got ${r.length})`);let i=r[0],s=q(n[i]);if(!s)throw new w(`"${i}" must be a JSON object`);return{kind:i,[i]:s}}function _n(t,e){if(typeof t=="string")return t;let n=q(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new w(`${e}: expected a Content with a parts array`);let o=[];for(let i of r){let s=q(i);if(s&&typeof s.text=="string"){o.push(s.text);continue}throw s&&(s.inlineData!==void 0||s.fileData!==void 0)?new w(`${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`):s&&(s.functionCall!==void 0||s.functionResponse!==void 0)?new w(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new w(`${e}: unsupported part ${JSON.stringify(i)}`)}return o.join(`
2
- `)}var lo={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},le="urun.videoOut";function wn(t){return{framing:mn,codec:t}}function vn(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[le]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var co={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},po=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",le],gn=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function fo(t){let e=q(t);if(!e)throw new w("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new w(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=q(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new w("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new w(`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 w("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(!gn.includes(e.activityHandling))throw new w(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${gn.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var mo=["temperature","maxOutputTokens","responseModalities"];function bn(t){for(let[c,g]of Object.entries(co))if(t[c]!==void 0)throw new w(g);for(let c of Object.keys(t))if(!po.includes(c))throw new w(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new w('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,i=q(t.generationConfig);if(t.generationConfig!==void 0&&!i)throw new w("setup.generationConfig must be an object");if(i){for(let c of Object.keys(i))if(!mo.includes(c))throw new w(`unsupported generationConfig field "${c}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new w("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new w("generationConfig.maxOutputTokens must be a number");r=i.maxOutputTokens}if(i.responseModalities!==void 0){let c=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let g of c){let p=String(g).toUpperCase();if(p==="AUDIO"){o=!0;continue}if(p!=="TEXT")throw new w(`responseModalities ${JSON.stringify(g)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let s=[];t.systemInstruction!==void 0&&s.push({role:"system",content:_n(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new w("setup.tools must be an array");a=[];for(let c of t.tools){let g=q(c);if(!g)throw new w("setup.tools entries must be objects");for(let p of Object.keys(g))if(p!=="functionDeclarations")throw new w(`unsupported tool "${p}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(g.functionDeclarations))throw new w("tool.functionDeclarations must be an array");for(let p of g.functionDeclarations){let k=q(p);if(!k||typeof k.name!="string")throw new w("functionDeclarations entries require a string name");a.push({type:"function",name:k.name,description:k.description,parameters:k.parameters})}}a.length===0&&(a=void 0)}let d={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=q(t.sessionResumption);if(!c)throw new w("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let g of Object.keys(c))if(g!=="handle")throw new w(`unsupported sessionResumption field "${g}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new w("sessionResumption.handle must be a non-empty string when present");d={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?lo:fo(t.realtimeInputConfig),l=!1;if(t[le]!==void 0){if(!q(t[le]))throw new w(`setup["${le}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:e,systemItems:s,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:u,sessionResumption:d,videoOut:l}}function kn(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Rn(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Sn(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new w(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new w("clientContent.turns must be an array");let n=[];for(let r of e){let o=q(r);if(!o)throw new w("clientContent.turns entries must be Content objects");let i=o.role===void 0?"user":String(o.role).toLowerCase();if(i!=="user"&&i!=="model")throw new w(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:i==="model"?"assistant":"user",content:_n(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var ut=16e3,xn=24e3,go=`audio/pcm;rate=${xn}`,An=Buffer.alloc(960).toString("base64");function ho(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),i=e/n,s=t.length-1;for(let a=0;a<r;a++){let d=a*i,u=Math.floor(d);if(u>=s){o[a]=t[s];continue}let l=d-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*l)}return o}function yo(t){let e=q(t);if(!e)throw new w("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new w(`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 w("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 w("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function _o(t){let e=q(t);if(!e)throw new w("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new w(`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])!==ut)throw new w(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${ut} Hz (audio/pcm;rate=${ut})`);if(typeof e.data!="string"||e.data.length===0)throw new w("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 w(`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 s=0;s<o.length;s++)o[s]=r.readInt16LE(s*2);let i=ho(o,ut,xn);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function En(t){if(t.mediaChunks!==void 0)throw new w('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 w("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",i=q(t[o]);if(!i||Object.keys(i).length!==0)throw new w(`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 w(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new w(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:_o(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:yo(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new w("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new w("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function In(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new w(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new w("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=q(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new w("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 On(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Tn(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:go,data:t}}]}}}}function Pn(t){let e=q(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],i=typeof e.output_text=="string"?e.output_text:"";if(!i)for(let u of n){let l=q(u);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let c of l.content){let g=q(c);g?.type==="output_text"&&typeof g.text=="string"&&(i+=g.text)}}i&&o.push({role:"assistant",content:i});for(let u of n){let l=q(u);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new w(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,ce);let c=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",g;try{g=JSON.parse(c)}catch{throw new w(`upstream function_call arguments are not valid JSON: ${c}`,ce)}r.push({id:l.call_id,name:l.name,args:g}),o.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:c})}let s=[];r.length>0&&s.push({toolCall:{functionCalls:r}}),s.push({serverContent:{generationComplete:!0}});let a=q(e.usage),d={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&&(d.usageMetadata=u)}return s.push(d),{messages:s,assistantItems:o}}var wo=256,Oe=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>wo;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},vo="local",qe=t=>t.slice(0,120),pt=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof N){this.ws.close(hn,qe(e.message));return}if(e instanceof ne){this.ws.close(ct,qe(e.message));return}if(e instanceof w){this.ws.close(e.closeCode,qe(e.message));return}this.ws.close(ce,qe(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=yn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new w(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:i}=Sn(n.clientContent);this.transcript.push(...o),i&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=En(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:An);return}this.transcript.push(...In(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new w("setup may only be sent once, as the first client message");let n=bn(e),r=n.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new w("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",ct);if(i.model!==n.model)throw new w(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new w("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==i.proxyHandle)throw new w(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,ct);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let i=this.clients.openVideoOut;if(i){let s=await i.call(this.clients,n.model),a=s.onOutputFrame(u=>this.send(vn(u))),d=s.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),d()},o[le]=wn(s.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new w("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new w("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",ce);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Tn(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new w("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new w("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",ce);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new w(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new w("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new w("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,Cn.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(kn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Rn(e.timeLeftMs)),this.ws.close(ce,qe(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,i=!1;for await(let d of r){if(n.interrupted)break;let u=d;if(u.type==="error")throw new w(`upstream error: ${JSON.stringify(u)}`,ce);if(u.type==="response.completed"){o=u.response,i=!0;continue}let l=On(u);l&&this.send(l)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new w("upstream produced no response.completed event",ce);let{messages:s,assistantItems:a}=Pn(o);this.transcript.push(...a);for(let d of s)this.send(d);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},_e=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function bo(t,e,n){let r=new Set;(d=>{if(typeof d=="string")d!==""&&r.add(d);else if(Array.isArray(d))for(let u of d)u!==""&&r.add(u)})(t.headers["x-goog-api-key"]);let i=t.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let s=e.searchParams.get("key")??void 0;if(s!==void 0&&s!==""&&r.add(s),r.size>1)throw new _e(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&s!==void 0&&s!=="")throw new _e(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let d of r)a=d;if(a===void 0&&n)throw new _e(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ft(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new $n.WebSocketServer({noServer:!0}),o=new Oe;t.on("upgrade",(s,a,d)=>{let u=new URL(s.url??"/","http://localhost");u.pathname===lt&&(a.on("error",()=>{}),(async()=>{let l=bo(s,u,n),c;if(e.authenticate)c=await e.authenticate(l,s);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new _e(401,"invalid local proxy api key");c={clients:e.clients,scope:vo}}r.handleUpgrade(s,a,d,g=>{new pt(g,c,o)})})().catch(l=>{let c=502;(l instanceof _e||typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number")&&(c=l.status);let g=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",p=l instanceof Error?l.message:String(l);a.destroyed||(a.write(`HTTP/1.1 ${c} ${g}\r
1
+ "use strict";var to=Object.create;var at=Object.defineProperty;var no=Object.getOwnPropertyDescriptor;var ro=Object.getOwnPropertyNames;var oo=Object.getPrototypeOf,io=Object.prototype.hasOwnProperty;var so=(t,e)=>{for(var n in e)at(t,n,{get:e[n],enumerable:!0})},hn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ro(e))!io.call(t,o)&&o!==n&&at(t,o,{get:()=>e[o],enumerable:!(r=no(e,o))||r.enumerable});return t};var gn=(t,e,n)=>(n=t!=null?to(oo(t)):{},hn(e||!t||!t.__esModule?at(n,"default",{value:t,enumerable:!0}):n,t)),ao=t=>hn(at({},"__esModule",{value:!0}),t);var Os={};so(Os,{GEMINI_LIVE_PATH:()=>pt,OPENAI_REALTIME_PATH:()=>We,OpenAIRealtimeConnection:()=>xe,ResumptionRegistry:()=>Oe,SessionGoneError:()=>Z,UnknownModelError:()=>N,VIDEO_OUT_SETUP_KEY:()=>le,attachGeminiLive:()=>ht,attachOpenAIRealtime:()=>Ke,createOpenAIProxy:()=>eo,fixedClientsResolver:()=>St,realtimeBindingFor:()=>tn,realtimeModelOf:()=>en,serveGeminiLiveSocket:()=>Un});module.exports=ao(Os);var Xr=require("http");var Ln=require("crypto"),Nn=require("ws");var Be="/partners/openrouter/models";var N=class extends Error{},Z=class extends Error{};var ut=require("@urun-sh/core");var yn="urun.videoOut.v2-ws";var pt="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",po=1007,wn=1008,ce=1011,ft=1008,w=class extends Error{constructor(n,r=po){super(n);this.closeCode=r}closeCode},q=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,dt=["setup","clientContent","realtimeInput","toolResponse"];function vn(t){let e;try{e=JSON.parse(t)}catch{throw new w("client message is not valid JSON")}let n=q(e);if(!n)throw new w("client message must be a JSON object");let r=dt.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!dt.includes(a));if(o.length>0)throw new w(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${dt.join(", ")}`);if(r.length!==1)throw new w(`client message must contain exactly one of ${dt.join(", ")} (got ${r.length})`);let i=r[0],s=q(n[i]);if(!s)throw new w(`"${i}" must be a JSON object`);return{kind:i,[i]:s}}function bn(t,e){if(typeof t=="string")return t;let n=q(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new w(`${e}: expected a Content with a parts array`);let o=[];for(let i of r){let s=q(i);if(s&&typeof s.text=="string"){o.push(s.text);continue}throw s&&(s.inlineData!==void 0||s.fileData!==void 0)?new w(`${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`):s&&(s.functionCall!==void 0||s.functionResponse!==void 0)?new w(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new w(`${e}: unsupported part ${JSON.stringify(i)}`)}return o.join(`
2
+ `)}var fo={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},le="urun.videoOut";function kn(t){return{framing:yn,codec:t}}function Sn(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[le]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var mo={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},ho=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",le],_n=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function go(t){let e=q(t);if(!e)throw new w("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new w(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=q(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new w("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new w(`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 w("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(!_n.includes(e.activityHandling))throw new w(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${_n.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var yo=["temperature","maxOutputTokens","responseModalities"];function xn(t){for(let[c,y]of Object.entries(mo))if(t[c]!==void 0)throw new w(y);for(let c of Object.keys(t))if(!ho.includes(c))throw new w(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new w('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,i=q(t.generationConfig);if(t.generationConfig!==void 0&&!i)throw new w("setup.generationConfig must be an object");if(i){for(let c of Object.keys(i))if(!yo.includes(c))throw new w(`unsupported generationConfig field "${c}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new w("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new w("generationConfig.maxOutputTokens must be a number");r=i.maxOutputTokens}if(i.responseModalities!==void 0){let c=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let y of c){let p=String(y).toUpperCase();if(p==="AUDIO"){o=!0;continue}if(p!=="TEXT")throw new w(`responseModalities ${JSON.stringify(y)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let s=[];t.systemInstruction!==void 0&&s.push({role:"system",content:bn(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new w("setup.tools must be an array");a=[];for(let c of t.tools){let y=q(c);if(!y)throw new w("setup.tools entries must be objects");for(let p of Object.keys(y))if(p!=="functionDeclarations")throw new w(`unsupported tool "${p}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(y.functionDeclarations))throw new w("tool.functionDeclarations must be an array");for(let p of y.functionDeclarations){let k=q(p);if(!k||typeof k.name!="string")throw new w("functionDeclarations entries require a string name");a.push({type:"function",name:k.name,description:k.description,parameters:k.parameters})}}a.length===0&&(a=void 0)}let d={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=q(t.sessionResumption);if(!c)throw new w("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let y of Object.keys(c))if(y!=="handle")throw new w(`unsupported sessionResumption field "${y}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new w("sessionResumption.handle must be a non-empty string when present");d={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?fo:go(t.realtimeInputConfig),l=!1;if(t[le]!==void 0){if(!q(t[le]))throw new w(`setup["${le}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:e,systemItems:s,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:u,sessionResumption:d,videoOut:l}}function Rn(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function En(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function An(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new w(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new w("clientContent.turns must be an array");let n=[];for(let r of e){let o=q(r);if(!o)throw new w("clientContent.turns entries must be Content objects");let i=o.role===void 0?"user":String(o.role).toLowerCase();if(i!=="user"&&i!=="model")throw new w(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:i==="model"?"assistant":"user",content:bn(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var lt=16e3,In=24e3,_o=`audio/pcm;rate=${In}`,On=Buffer.alloc(960).toString("base64");function wo(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),i=e/n,s=t.length-1;for(let a=0;a<r;a++){let d=a*i,u=Math.floor(d);if(u>=s){o[a]=t[s];continue}let l=d-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*l)}return o}function vo(t){let e=q(t);if(!e)throw new w("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new w(`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 w("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 w("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function bo(t){let e=q(t);if(!e)throw new w("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new w(`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])!==lt)throw new w(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${lt} Hz (audio/pcm;rate=${lt})`);if(typeof e.data!="string"||e.data.length===0)throw new w("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 w(`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 s=0;s<o.length;s++)o[s]=r.readInt16LE(s*2);let i=wo(o,lt,In);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function Tn(t){if(t.mediaChunks!==void 0)throw new w('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 w("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",i=q(t[o]);if(!i||Object.keys(i).length!==0)throw new w(`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 w(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new w(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:bo(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:vo(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new w("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new w("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Pn(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new w(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new w("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=q(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new w("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 Cn(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Mn(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:_o,data:t}}]}}}}function $n(t){let e=q(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],i=typeof e.output_text=="string"?e.output_text:"";if(!i)for(let u of n){let l=q(u);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let c of l.content){let y=q(c);y?.type==="output_text"&&typeof y.text=="string"&&(i+=y.text)}}i&&o.push({role:"assistant",content:i});for(let u of n){let l=q(u);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new w(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,ce);let c=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",y;try{y=JSON.parse(c)}catch{throw new w(`upstream function_call arguments are not valid JSON: ${c}`,ce)}r.push({id:l.call_id,name:l.name,args:y}),o.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:c})}let s=[];r.length>0&&s.push({toolCall:{functionCalls:r}}),s.push({serverContent:{generationComplete:!0}});let a=q(e.usage),d={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&&(d.usageMetadata=u)}return s.push(d),{messages:s,assistantItems:o}}var ko=256,Oe=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>ko;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},So="local",qe=t=>t.slice(0,120),mt=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof N){this.ws.close(wn,qe(e.message));return}if(e instanceof Z){this.ws.close(ft,qe(e.message));return}if(e instanceof w){this.ws.close(e.closeCode,qe(e.message));return}this.ws.close(ce,qe(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=vn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new w(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:i}=An(n.clientContent);this.transcript.push(...o),i&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Tn(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:On);return}this.transcript.push(...Pn(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new w("setup may only be sent once, as the first client message");let n=xn(e),r=n.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new w("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",ft);if(i.model!==n.model)throw new w(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new w("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==i.proxyHandle)throw new w(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,ft);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let i=this.clients.openVideoOut;if(i){let s=await i.call(this.clients,n.model),a=s.onOutputFrame(u=>this.send(Sn(u))),d=s.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),d()},o[le]=kn(s.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new w("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new w("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",ce);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Mn(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new w("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new w("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",ce);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new w(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new w("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new w("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,Ln.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Rn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(En(e.timeLeftMs)),this.ws.close(ce,qe(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,i=!1;for await(let d of r){if(n.interrupted)break;let u=d;if(u.type==="error")throw new w(`upstream error: ${JSON.stringify(u)}`,ce);if(u.type==="response.completed"){o=u.response,i=!0;continue}let l=Cn(u);l&&this.send(l)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new w("upstream produced no response.completed event",ce);let{messages:s,assistantItems:a}=$n(o);this.transcript.push(...a);for(let d of s)this.send(d);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},_e=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function xo(t,e,n){let r=new Set;(d=>{if(typeof d=="string")d!==""&&r.add(d);else if(Array.isArray(d))for(let u of d)u!==""&&r.add(u)})(t.headers["x-goog-api-key"]);let i=t.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let s=e.searchParams.get("key")??void 0;if(s!==void 0&&s!==""&&r.add(s),r.size>1)throw new _e(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&s!==void 0&&s!=="")throw new _e(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let d of r)a=d;if(a===void 0&&n)throw new _e(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ht(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Nn.WebSocketServer({noServer:!0}),o=new Oe;t.on("upgrade",(s,a,d)=>{let u=new URL(s.url??"/","http://localhost");u.pathname===pt&&(a.on("error",()=>{}),(async()=>{let l=xo(s,u,n),c;if(e.authenticate)c=await e.authenticate(l,s);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new _e(401,"invalid local proxy api key");c={clients:e.clients,scope:So}}r.handleUpgrade(s,a,d,y=>{new mt(y,c,o)})})().catch(l=>{let c=502;(l instanceof _e||typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number")&&(c=l.status);let y=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",p=l instanceof Error?l.message:String(l);a.destroyed||(a.write(`HTTP/1.1 ${c} ${y}\r
3
3
  Connection: close\r
4
4
  \r
5
5
  ${p}\r
6
- `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let s of r.clients)s.close(1001,"server closing");await new Promise((s,a)=>r.close(d=>d===void 0?s():a(d)))})(),i)}function Mn(t,e,n=new Oe){new pt(t,e,n)}var ge=require("ws");var Ln=require("crypto"),Nn="Inference-Id";function je(){return(0,Ln.randomUUID)()}function Dt(t){return t==="/v1"||t.startsWith("/v1/")}function Un(t,e){if(!Dt(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function He(t){return`resp_${t}`}function Dn(t){return`chatcmpl-${t}`}function Bn(t){return`msg_${t}`}function re(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Fn(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,catalog:t.turn.catalog}}function qn(t){return`${JSON.stringify(t)}
7
- `}var ko=256,Ro=128;function Z(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Ro)}var we=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=ko?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,i=performance.now(),s=null,a=0;return(async function*(){for await(let u of e)u.type==="response.output_text.delta"&&typeof u.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-i),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=s-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=u.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield u;let d=(performance.now()-(s??i))/1e3;a>0&&d>0&&(o.tokRates.push(a/d),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},So=256;function xo(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var ve=class extends Error{},Te=class{conversations=new Map;thread(e,n){let r=xo(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new ve(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let i of this.conversations.keys()){if(this.conversations.size<=So)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},jn=new WeakMap;function Ve(t){let e=jn.get(t);return e||(e=new Te,jn.set(t,e)),e}function Pe(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function ae(t){return t.find(e=>e.type==="response.completed")?.response??null}function Ce(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var me=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},Ao=["<tool_call>","<function="];function Eo(t){return Ao.find(e=>t.includes(e))}function be(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function ke(t,e,n){if(!(!t||e>0))return Eo(n)}function $e(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Io(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function Bt(t,e){let n=Io(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var oe=class extends Error{constructor(n,r,o=400,i){super(n);this.code=r;this.status=o;this.param=i}code;status;param};function Me(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof ve?new oe(n.message,"previous_response_not_found",400,"previous_response_id"):new oe(String(n instanceof Error?n.message:n),"invalid_input")}}function Hn(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Ft(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new oe("instructions must be a string","invalid_instructions");let i=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...i!==void 0?{instructions:i}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...Hn(e)!==void 0?{response_format:Hn(e)}:{}},o)}async function Ge(t){let{body:e,clients:n,store:r,stats:o}=t,i=Me(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let s=t.responseId,a=t.remember??e.store!==!1,d=e.store!==!1,u=Z(e);o.model(u);let l=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,g=await Ft(n,e,i,!0,c?re(c):void 0);return{responseId:s,events:Co({events:g,conversation:i,responseId:s,modelKey:u,requestHadTools:l,remember:a,persist:d,store:r,stats:o,turn:t.turn})}}function Oo(t,e){let n=[...t].sort((d,u)=>d.output_index-u.output_index).map(({item:d})=>d),r=Array.isArray(e?.output)?e.output:[],o=r.filter(d=>d!==null&&typeof d=="object"&&d.type==="message"),i=n.filter(d=>d.type==="message").length===o.length,s=0;return[...n.map(d=>d.type==="message"&&i?Po(o[s++],d):d),...To(r,n)]}function To(t,e){let n=e.some(u=>u.type==="message"),r=e.some(u=>u.type==="reasoning"),o=u=>String(u.call_id??u.id??""),i=e.filter(u=>u.type==="function_call"),s=t.filter(u=>u!==null&&typeof u=="object"&&u.type==="function_call").length,a=i.length===s,d=new Set(i.map(o));return t.filter(u=>{if(u===null||typeof u!="object")return!0;let l=u;return l.type==="message"?!n:l.type==="reasoning"?!r:l.type==="function_call"?!a&&!d.has(o(l)):!0})}function Po(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(n);if(i===void 0)return e;let s={...t};return s.id=e.id,t.role===void 0&&(s.role=e.role),t.status===void 0&&(s.status=e.status),s.content=r.map(a=>n(a)?{...a,text:i.text}:a),s}async function*Co(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:i,remember:s,persist:a,store:d,stats:u}=t,l=[],c=O=>O.response&&typeof O.response=="object"?{...O,response:{...O.response,id:r}}:O,g=`item_${r.slice(5)}`,p=!1,k=!1,E=0;function*S(){p||(p=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let _=[],h=(O,M)=>{_.push({output_index:O,item:M})},y=!1,x=0,f="",m=0,b="";function*P(){if(!y)return;y=!1,yield{type:"response.reasoning_text.done",item_id:f,output_index:x,content_index:0,text:b};let O={id:f,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:b}],status:"completed"};yield{type:"response.output_item.done",output_index:x,item:O},h(x,O),b=""}let v=!1,I=0,C="",D=0,J="",Q="";function*ie(O){if(!v)return;v=!1,yield{type:"response.output_text.done",item_id:C,output_index:I,content_index:0,text:J},yield{type:"response.content_part.done",item_id:C,output_index:I,content_index:0,part:{type:"output_text",text:J}};let M={id:C,type:"message",role:"assistant",status:O,content:[{type:"output_text",text:J}]};yield{type:"response.output_item.done",output_index:I,item:M},h(I,M),J=""}let pe=new me,H=null,V=-1;function*z(O){if(!H)return;let M=H;H=null,yield{type:"response.function_call_arguments.done",item_id:M.fcId,output_index:M.outputIndex,arguments:M.args};let G={id:M.fcId,type:"function_call",call_id:M.callId??M.fcId,name:M.name??"",arguments:M.args,status:O};yield{type:"response.output_item.done",output_index:M.outputIndex,item:G},h(M.outputIndex,G)}let ye=!1;for await(let O of u.track(e,o,t.turn)){l.push(O);let M=String(O.type??"");if(M==="response.created"||M==="response.in_progress"){p=!0,yield c(O);continue}if(M==="response.output_item.added"){k=!0,yield c(O);continue}if(M==="response.reasoning_text.delta"&&!k){yield*S(),y||(y=!0,x=E++,m+=1,f=m===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${m}`,yield{type:"response.output_item.added",output_index:x,item:{id:f,type:"reasoning",summary:[],content:[],status:"in_progress"}}),b+=String(O.delta??""),yield{type:"response.reasoning_text.delta",item_id:f,output_index:x,content_index:0,delta:O.delta};continue}if(M==="response.output_text.delta"&&!k){yield*S(),yield*P(),v||(v=!0,I=E++,D+=1,C=D===1?g:`${g}_${D}`,yield{type:"response.output_item.added",output_index:I,item:{id:C,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:C,output_index:I,content_index:0,part:{type:"output_text",text:""}}),J+=String(O.delta??""),Q+=String(O.delta??""),yield{type:M,item_id:C,output_index:I,content_index:0,delta:O.delta};continue}let G=k?null:Ce(O);if(G){if(yield*S(),yield*P(),yield*ie("completed"),pe.add(G),G.tool_index!==V){yield*z("completed"),V=G.tool_index;let de=E++;H={fcId:`fc_${r.slice(5)}_${G.tool_index}`,outputIndex:de,callId:G.call_id,name:G.name,args:""},yield{type:"response.output_item.added",output_index:de,item:{id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:"",status:"in_progress"}}}H&&(G.call_id&&(H.callId=G.call_id),G.name&&(H.name=G.name),H.args+=G.delta,yield{type:"response.function_call_arguments.delta",item_id:H.fcId,output_index:H.outputIndex,delta:G.delta});continue}if(M==="response.completed"&&!k){let de=Pe(O.response),B=ke(i,pe.size+de.length,Q);if(B){ye=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:be(o,B)}};break}if(yield*P(),yield*ie("completed"),yield*z("completed"),pe.size===0)for(let fe of de){let Ie=E++,ot=fe.id??fe.call_id??`fc_${Ie}`,Nt=fe.arguments??"",ln={id:ot,type:"function_call",call_id:fe.call_id??ot,name:fe.name??""};yield{type:"response.output_item.added",output_index:Ie,item:{...ln,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:ot,output_index:Ie,delta:Nt},yield{type:"response.function_call_arguments.done",item_id:ot,output_index:Ie,arguments:Nt};let cn={...ln,arguments:Nt,status:"completed"};yield{type:"response.output_item.done",output_index:Ie,item:cn},h(Ie,cn)}let Y=Oo(_,O.response);yield Y.length>0?c({...O,response:{...O.response,output:Y}}):c(O);continue}yield c(O)}if(yield*P(),yield*ie("incomplete"),yield*z("incomplete"),s&&!ye){let O=ae(l);d.remember(r,n,Bt(O,$e(l,O)),a)}}var $o="/v1/responses",Mo=64*1024*1024,Lo=8*1024*1024,No=16,Vn=32,Gn=3600*1e3,Uo=/^[A-Za-z0-9._-]{1,256}$/;function ee(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Do=ee(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function Ht(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Bo(t){for(;t.bufferedAmount>Lo&&t.readyState===ge.WebSocket.OPEN;){let{promise:e,resolve:n}=Ht();setTimeout(n,5),await e}}var qt=class extends Te{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof ve))throw o;return this.shared.thread(n,r)}}remember(n,r,o,i=!0){i?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},jt=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new qt(Ve(n)),e.on("message",(s,a)=>this.onMessage(s,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ee(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Gn/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Gn).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(ee(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(ee(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(ee(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(ee(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(ee(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(ee(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Uo.test(o.stream_id)){this.sendFrame(Do);return}if(i=o.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=Vn){this.sendFrame(ee(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Vn}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let s=o.generate===!1?()=>this.runWarmup(o,i):()=>this.runTurn(o,i),a=i??"",d=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,d.then(s).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(!this.closed){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await Ge({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:He(je())})}catch(s){this.failTurn(s,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let i=o.events;this.activeTurns.add(i);try{for await(let s of i){if(this.closed||this.ws.readyState!==ge.WebSocket.OPEN)break;this.send(s,n),await Bo(this.ws)}}finally{this.activeTurns.delete(i)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=He(je());try{let o=Me(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof oe)return ee(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof N)return ee(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof ne)return ee(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?ee(o.status,{type:o.openaiType,message:r},n):ee(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=No;){let{promise:e,resolve:n}=Ht();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==ge.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==ge.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function mt(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
6
+ `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let s of r.clients)s.close(1001,"server closing");await new Promise((s,a)=>r.close(d=>d===void 0?s():a(d)))})(),i)}function Un(t,e,n=new Oe){new mt(t,e,n)}var he=require("ws");var Dn=require("crypto"),Fn="Inference-Id";function je(){return(0,Dn.randomUUID)()}function qt(t){return t==="/v1"||t.startsWith("/v1/")}function Bn(t,e){if(!qt(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function He(t){return`resp_${t}`}function qn(t){return`chatcmpl-${t}`}function jn(t){return`msg_${t}`}function re(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Hn(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function Vn(t){return`${JSON.stringify(t)}
7
+ `}var Ro=256,Eo=128;function ee(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Eo)}var we=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=Ro?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,i=performance.now(),s=null,a=0;return(async function*(){for await(let u of e)u.type==="response.output_text.delta"&&typeof u.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-i),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=s-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=u.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield u;let d=(performance.now()-(s??i))/1e3;a>0&&d>0&&(o.tokRates.push(a/d),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Ao=256;function Io(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var ve=class extends Error{},Te=class{conversations=new Map;thread(e,n){let r=Io(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new ve(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let i of this.conversations.keys()){if(this.conversations.size<=Ao)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},Gn=new WeakMap;function Ve(t){let e=Gn.get(t);return e||(e=new Te,Gn.set(t,e)),e}function Pe(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function ae(t){return t.find(e=>e.type==="response.completed")?.response??null}function Ce(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var me=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},Oo=["<tool_call>","<function="];function To(t){return Oo.find(e=>t.includes(e))}function be(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function ke(t,e,n){if(!(!t||e>0))return To(n)}function Me(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Po(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function jt(t,e){let n=Po(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var oe=class extends Error{constructor(n,r,o=400,i){super(n);this.code=r;this.status=o;this.param=i}code;status;param};function $e(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof ve?new oe(n.message,"previous_response_not_found",400,"previous_response_id"):new oe(String(n instanceof Error?n.message:n),"invalid_input")}}function Jn(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Ht(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new oe("instructions must be a string","invalid_instructions");let i=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...i!==void 0?{instructions:i}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...Jn(e)!==void 0?{response_format:Jn(e)}:{}},o)}async function Ge(t){let{body:e,clients:n,store:r,stats:o}=t,i=$e(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let s=t.responseId,a=t.remember??e.store!==!1,d=e.store!==!1,u=ee(e);o.model(u);let l=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,y=await Ht(n,e,i,!0,c?re(c):void 0);return{responseId:s,events:Lo({events:y,conversation:i,responseId:s,modelKey:u,requestHadTools:l,remember:a,persist:d,store:r,stats:o,turn:t.turn})}}function Co(t,e){let n=[...t].sort((d,u)=>d.output_index-u.output_index).map(({item:d})=>d),r=Array.isArray(e?.output)?e.output:[],o=r.filter(d=>d!==null&&typeof d=="object"&&d.type==="message"),i=n.filter(d=>d.type==="message").length===o.length,s=0;return[...n.map(d=>d.type==="message"&&i?$o(o[s++],d):d),...Mo(r,n)]}function Mo(t,e){let n=e.some(u=>u.type==="message"),r=e.some(u=>u.type==="reasoning"),o=u=>String(u.call_id??u.id??""),i=e.filter(u=>u.type==="function_call"),s=t.filter(u=>u!==null&&typeof u=="object"&&u.type==="function_call").length,a=i.length===s,d=new Set(i.map(o));return t.filter(u=>{if(u===null||typeof u!="object")return!0;let l=u;return l.type==="message"?!n:l.type==="reasoning"?!r:l.type==="function_call"?!a&&!d.has(o(l)):!0})}function $o(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(n);if(i===void 0)return e;let s={...t};return s.id=e.id,t.role===void 0&&(s.role=e.role),t.status===void 0&&(s.status=e.status),s.content=r.map(a=>n(a)?{...a,text:i.text}:a),s}async function*Lo(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:i,remember:s,persist:a,store:d,stats:u}=t,l=[],c=O=>O.response&&typeof O.response=="object"?{...O,response:{...O.response,id:r}}:O,y=`item_${r.slice(5)}`,p=!1,k=!1,E=0;function*S(){p||(p=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let f=[],h=(O,L)=>{f.push({output_index:O,item:L})},g=!1,A=0,_="",m=0,v="";function*P(){if(!g)return;g=!1,yield{type:"response.reasoning_text.done",item_id:_,output_index:A,content_index:0,text:v};let O={id:_,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:v}],status:"completed"};yield{type:"response.output_item.done",output_index:A,item:O},h(A,O),v=""}let b=!1,I=0,C="",D=0,W="",Q="";function*ie(O){if(!b)return;b=!1,yield{type:"response.output_text.done",item_id:C,output_index:I,content_index:0,text:W},yield{type:"response.content_part.done",item_id:C,output_index:I,content_index:0,part:{type:"output_text",text:W}};let L={id:C,type:"message",role:"assistant",status:O,content:[{type:"output_text",text:W}]};yield{type:"response.output_item.done",output_index:I,item:L},h(I,L),W=""}let pe=new me,H=null,V=-1;function*z(O){if(!H)return;let L=H;H=null,yield{type:"response.function_call_arguments.done",item_id:L.fcId,output_index:L.outputIndex,arguments:L.args};let J={id:L.fcId,type:"function_call",call_id:L.callId??L.fcId,name:L.name??"",arguments:L.args,status:O};yield{type:"response.output_item.done",output_index:L.outputIndex,item:J},h(L.outputIndex,J)}let ye=!1;for await(let O of u.track(e,o,t.turn)){l.push(O);let L=String(O.type??"");if(L==="response.created"||L==="response.in_progress"){p=!0,yield c(O);continue}if(L==="response.output_item.added"){k=!0,yield c(O);continue}if(L==="response.reasoning_text.delta"&&!k){yield*S(),g||(g=!0,A=E++,m+=1,_=m===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${m}`,yield{type:"response.output_item.added",output_index:A,item:{id:_,type:"reasoning",summary:[],content:[],status:"in_progress"}}),v+=String(O.delta??""),yield{type:"response.reasoning_text.delta",item_id:_,output_index:A,content_index:0,delta:O.delta};continue}if(L==="response.output_text.delta"&&!k){yield*S(),yield*P(),b||(b=!0,I=E++,D+=1,C=D===1?y:`${y}_${D}`,yield{type:"response.output_item.added",output_index:I,item:{id:C,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:C,output_index:I,content_index:0,part:{type:"output_text",text:""}}),W+=String(O.delta??""),Q+=String(O.delta??""),yield{type:L,item_id:C,output_index:I,content_index:0,delta:O.delta};continue}let J=k?null:Ce(O);if(J){if(yield*S(),yield*P(),yield*ie("completed"),pe.add(J),J.tool_index!==V){yield*z("completed"),V=J.tool_index;let de=E++;H={fcId:`fc_${r.slice(5)}_${J.tool_index}`,outputIndex:de,callId:J.call_id,name:J.name,args:""},yield{type:"response.output_item.added",output_index:de,item:{id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:"",status:"in_progress"}}}H&&(J.call_id&&(H.callId=J.call_id),J.name&&(H.name=J.name),H.args+=J.delta,yield{type:"response.function_call_arguments.delta",item_id:H.fcId,output_index:H.outputIndex,delta:J.delta});continue}if(L==="response.completed"&&!k){let de=Pe(O.response),F=ke(i,pe.size+de.length,Q);if(F){ye=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:be(o,F)}};break}if(yield*P(),yield*ie("completed"),yield*z("completed"),pe.size===0)for(let fe of de){let Ie=E++,st=fe.id??fe.call_id??`fc_${Ie}`,Ft=fe.arguments??"",fn={id:st,type:"function_call",call_id:fe.call_id??st,name:fe.name??""};yield{type:"response.output_item.added",output_index:Ie,item:{...fn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:st,output_index:Ie,delta:Ft},yield{type:"response.function_call_arguments.done",item_id:st,output_index:Ie,arguments:Ft};let mn={...fn,arguments:Ft,status:"completed"};yield{type:"response.output_item.done",output_index:Ie,item:mn},h(Ie,mn)}let Y=Co(f,O.response);yield Y.length>0?c({...O,response:{...O.response,output:Y}}):c(O);continue}yield c(O)}if(yield*P(),yield*ie("incomplete"),yield*z("incomplete"),s&&!ye){let O=ae(l);d.remember(r,n,jt(O,Me(l,O)),a)}}var No="/v1/responses",Uo=64*1024*1024,Do=8*1024*1024,Fo=16,Wn=32,Kn=3600*1e3,Bo=/^[A-Za-z0-9._-]{1,256}$/;function te(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var qo=te(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function Jt(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function jo(t){for(;t.bufferedAmount>Do&&t.readyState===he.WebSocket.OPEN;){let{promise:e,resolve:n}=Jt();setTimeout(n,5),await e}}var Vt=class extends Te{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof ve))throw o;return this.shared.thread(n,r)}}remember(n,r,o,i=!0){i?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},Gt=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new Vt(Ve(n)),e.on("message",(s,a)=>this.onMessage(s,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(te(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Kn/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Kn).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(te(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(te(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(te(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(te(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(te(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(te(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Bo.test(o.stream_id)){this.sendFrame(qo);return}if(i=o.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=Wn){this.sendFrame(te(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Wn}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let s=o.generate===!1?()=>this.runWarmup(o,i):()=>this.runTurn(o,i),a=i??"",d=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,d.then(s).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(!this.closed){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await Ge({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:He(je())})}catch(s){this.failTurn(s,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let i=o.events;this.activeTurns.add(i);try{for await(let s of i){if(this.closed||this.ws.readyState!==he.WebSocket.OPEN)break;this.send(s,n),await jo(this.ws)}}finally{this.activeTurns.delete(i)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=He(je());try{let o=$e(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof oe)return te(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof N)return te(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof Z)return te(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?te(o.status,{type:o.openaiType,message:r},n):te(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Fo;){let{promise:e,resolve:n}=Jt();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==he.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==he.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function gt(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
8
8
  `;t.end(`HTTP/1.1 ${e} ${r}\r
9
9
  Connection: close\r
10
10
  Content-Type: text/plain; charset=utf-8\r
11
11
  Content-Length: ${Buffer.byteLength(o)}\r
12
12
  \r
13
- ${o}`)}function Jn(t,e){let n=new ge.WebSocketServer({noServer:!0,maxPayload:Mo}),r=new we,o=new Set,i=new Set,s=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,d=!1,u=(l,c,g)=>{let p;try{p=new URL(l.url??"/","http://localhost")}catch{mt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>s.delete(c)),p.pathname!==$o){s.add(c);return}i.add(c);let k=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){mt(c,401,"invalid local proxy api key");return}let E;try{E=await a(l)}catch(S){let _=e.statusOf?.(S)??null;mt(c,_?.status??500,"upstream resolver rejected the connection");return}d||c.destroyed||(k=!0,n.handleUpgrade(l,c,g,S=>{i.delete(c),o.add(S),S.on("close",()=>o.delete(S));try{new jt(S,E,r,e.statusOf)}catch{o.delete(S),S.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!k&&!c.destroyed&&mt(c,500,"responses websocket upgrade failed")}).finally(()=>i.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:l,resolve:c}=Ht();if(d)return c(),l;d=!0,t.off("upgrade",u);for(let p of i)p.destroy();i.clear();for(let p of s)p.destroy();s.clear();for(let p of o)p.close(1001,"server shutting down");let g=setTimeout(()=>{for(let p of o)p.readyState!==ge.WebSocket.CLOSED&&p.terminate()},2e3);return g.unref?.(),n.close(()=>{clearTimeout(g),c()}),l}}}var Zn=require("@urun-sh/core");var Wn=require("@urun-sh/core"),Fo={no_capacity:429,queue_timeout:429,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},qo={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; 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:"admission is momentarily contended (lock convoy) \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session"};function Vt(t,e){let n=qo[t.code];return e?`${n} (${e})`:n}function gt(t){if(t==null)return null;let e=Fo[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:e===429?"capacity_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function ht(t){if(t.kind==="create-failed")return gt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Wn.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return gt(e?"cold_start_exceeded":"queue_timeout")}var jo=fn(require("os"),1),Ho=fn(require("path"),1),Vo=require("url"),Go=require("util");var Jo=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Wo(t){let e=t?.code;return typeof e=="string"&&Jo.has(e)}function Re(t,e){try{return t.write(e),!0}catch(n){if(Wo(n))return!1;throw n}}var er=require("ws");var Qn=require("@urun-sh/core");var zn=require("crypto");function R(t){return`${t}_${(0,zn.randomUUID)().replace(/-/g,"").slice(0,24)}`}var yt=4*1024*1024,Gt=8*1024*1024,_t=512,wt=20*1024*1024;function j(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Le(t,e){return{type:"server_error",code:t,message:e}}function U(t){return{type:"error",event_id:R("event"),error:t}}function Jt(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var A=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Ko={type:!0,model:!0,instructions:!0,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,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},zo={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Yo={format:!0,voice:!0,speed:!0};function Kn(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new A(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function Je(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new A("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(s=>!(s in Ko));if(o.length>0)throw new A(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let i={...e,outputModalities:[...e.outputModalities]};for(let[s,a]of Object.entries(r))switch(s){case"type":{if(a!=="realtime"&&a!=="transcription")throw new A(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new A(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: 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(a==="transcription"&&!n.turns)throw new A('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=a;break}case"model":if(a!==null&&typeof a!="string")throw new A("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new A("instructions must be a string or null","instructions");i.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new A("modalities must be a non-empty array","modalities");let d=[];for(let u of a){if(u!=="text"&&u!=="audio")throw new A(`modality ${JSON.stringify(u)} is not "text" or "audio"`,"modalities");if(u==="audio"&&!n.voice)throw new A('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");d.includes(u)||d.push(u)}i.outputModalities=d;break}case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new A("voice must be a string or null","voice");if(!n.voice)throw new A("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new A(`${s} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,s);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new A("temperature must be a finite number or null","temperature");i.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new A(`${s} must be a positive integer, "inf" or null`,s);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new A("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new A("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new A("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 d=a;if(!d||typeof d!="object"||Array.isArray(d))throw new A("turn_detection must be an object or null","turn_detection");let u=String(d.type??"");if(u!=="server_vad"&&u!=="semantic_vad")throw new A(`turn_detection.type ${JSON.stringify(d.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");i.turnDetection={createResponse:d.create_response!==!1,interruptResponse:d.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new A("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(!a||typeof a!="object"||Array.isArray(a))throw new A("input_audio_transcription must be an object or null","input_audio_transcription");for(let u of Object.keys(a))if(!["model","language","languages","prompt"].includes(u))throw new A(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");let d=a.model;if(d!=null){let u=typeof d=="string"?d:JSON.stringify(d);if(typeof d!="string"||d!==n.model)throw new A(`input_audio_transcription.model ${JSON.stringify(u)} 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(a!==null)throw new A("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(a===null)break;let d=a;if(!d||typeof d!="object"||Array.isArray(d))throw new A("audio must be an object or null","audio");if(d.input!==void 0&&d.input!==null){let u=d.input;if(!u||typeof u!="object"||Array.isArray(u))throw new A("audio.input must be an object","audio.input");for(let l of Object.keys(u))if(!(l in zo))throw new A(`audio.input field not supported by this backend: ${l}`,`audio.input.${l}`,"unsupported_field");if(u.format!==void 0&&Kn(u.format,"audio.input.format"),u.transcription!==null&&u.transcription!==void 0){let l=Je({input_audio_transcription:u.transcription},i,n);i.inputAudioTranscription=l.inputAudioTranscription}if(u.turn_detection!==null&&u.turn_detection!==void 0){let l=Je({turn_detection:u.turn_detection},i,n);i.turnDetection=l.turnDetection}if(u.noise_reduction!==null&&u.noise_reduction!==void 0)throw new A("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(d.output!==void 0&&d.output!==null){let u=d.output;if(!u||typeof u!="object"||Array.isArray(u))throw new A("audio.output must be an object","audio.output");for(let l of Object.keys(u))if(!(l in Yo))throw new A(`audio.output field not supported by this backend: ${l}`,`audio.output.${l}`,"unsupported_field");if(u.format!==void 0&&Kn(u.format,"audio.output.format"),u.speed!==void 0)throw new A("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(u.voice!==void 0)if(u.voice===null)delete i.voice;else{if(typeof u.voice!="string")throw new A("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new A("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=u.voice}u.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function vt(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 Wt(t,e){let n=t;if(!n||typeof n!="object")throw new A("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 A("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:R("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 A('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new A("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new A("content part must be an object","item.content","invalid_request");if(s.type==="input_text"||r==="assistant"&&s.type==="output_text"){if(typeof s.text!="string")throw new A(`${String(s.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){if(!e)throw new A("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof s.audio!="string")throw new A("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}throw new A(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:R("item"),type:"message",role:r,content:o}}throw new A(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Kt(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 i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let s=i.transcript;if(typeof s=="string"&&s.trim().length>0){o.push({type:"input_text",text:s});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Xo=1001,Qo=1011,Yn=t=>t.slice(0,120),Zo=/^[A-Za-z0-9+/=]*$/,ei=2;function ti(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ei)return!1;return!0}var Se=class{id=R("conn");ws;binding;onClosed;config=Jt();sessionId=R("sess");conversationId=R("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),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.send({type:"session.created",event_id:R("event"),session:vt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:R("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}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){!this.closed&&!e.signal.aborted&&this.send(U(Le("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.isTranscriptionSession()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:e,content_index:0,transcript: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:R("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:R("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:R("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:R("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),i=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.isTranscriptionSession()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:R("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 s=R("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:R("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:R("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:s,content_index:0,transcript:i}),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(j("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>yt){this.fail(j("frame_too_large",`frame exceeds the ${yt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(j("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(j("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let i=o;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(U({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}this.fail(Le(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=Je(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model}),this.send({type:"session.updated",event_id:R("event"),session:vt(this.config,this.sessionId)});return;case"conversation.item.create":{let n=Wt(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(U(j("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:R("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(U(j("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:R("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(U(j("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:R("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(U(j("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Zo.test(e.audio)){this.send(U(j("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>wt){this.send(U(j("buffer_full",`uncommitted input audio exceeds the ${wt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.isTranscriptionSession()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;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:R("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(U(j("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.isTranscriptionSession()&&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=R("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:R("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.isTranscriptionSession())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:r,content_index:0,transcript:n});else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:r,content_index:0,transcript:i}),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;return}case"output_audio_buffer.clear":{this.send(U(j("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(U(j("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(U(j("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(U(j("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 Error("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(U({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 upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:i,input:s,...a}=e;return await o.createResponse({...a,input:s})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(U(j("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(E=>E!=="text"&&E!=="audio")){this.send(U(j("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(U(j("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.responseFlushed=!1,this.messageItemAdded=!1;let r=R("req"),o=`resp_${r}`;this.activeResponseId=o;let i=this.items.length,{input:s,sawAudioOnlyItem:a}=Kt(this.items),d=typeof n.instructions=="string"?n.instructions:this.config.instructions,u=typeof n.temperature=="number"?n.temperature:this.config.temperature,l=n.max_output_tokens??this.config.maxOutputTokens,c=l==="inf"||l===void 0?void 0:l,g=n.tools!==void 0?n.tools:this.config.tools,p=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,k={input:s,stream:!0,...this.config.model?{model:this.config.model}:{},...d!==void 0?{instructions:d}:{},...u!==void 0?{temperature:u}:{},...c!==void 0?{max_output_tokens:c}:{},...g!==void 0?{tools:g}:{},...p!==void 0?{tool_choice:p}:{}};for(let E of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(E);this.inFlight=(async()=>{let E=[],S=x=>{this.responseFlushed?this.send(x):E.push(x)},_=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:R("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(o,"in_progress")});for(let x of E)this.send(x);E.length=0,this.responseFlushed=!0}},h={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},y=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let x;try{x=await this.upstreamStream(k,r)}catch(f){this.upstreamTurnFault(f,o);return}try{for await(let f of x){if(this.cancelled)break;let m=f;if(m.type==="error"){let b=this.upstreamErrorBody(m);this.responseFlushed?this.send(U(b)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(o,b)});return}if(m.type==="response.output_text.delta"&&typeof m.delta=="string"){_(),h.messageOpen||(this.beginMessageItem(o,h.nextOutputIndex++),h.messageOpen=!0),S({type:"response.output_text.delta",event_id:R("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:m.delta}),h.messageText+=m.delta;continue}if(m.type==="response.function_call_arguments.delta"){_();let b=typeof m.delta=="string"?m.delta:"",P=typeof m.call_id=="string"&&m.call_id.length>0?m.call_id:`${o}_fc_${h.nextOutputIndex}`,v=h.tools.get(P);if(!v){let I=typeof m.name=="string"&&m.name.length>0?m.name:void 0;v={outputIndex:h.nextOutputIndex++,name:I,args:""},h.tools.set(P,v),S({type:"response.output_item.added",event_id:R("event"),response_id:o,output_index:v.outputIndex,item:{id:P,object:"realtime.item",type:"function_call",call_id:P,name:I??"",arguments:"",status:"in_progress"}})}typeof m.name=="string"&&m.name.length>0&&(v.name=m.name),v.args+=b,S({type:"response.function_call_arguments.delta",event_id:R("event"),item_id:P,response_id:o,output_index:v.outputIndex,call_id:P,name:v.name??"",delta:b});continue}if(m.type==="response.completed"){y=m.response??null;continue}}}catch(f){this.upstreamTurnFault(f,o);return}if(this.cancelled)return;this.closeOpenItems(o,h,i),_(),this.send({type:"response.done",event_id:R("event"),response:this.doneResponse(o,i,y)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(ti(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(U({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:R("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:R("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:R("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:R("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`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:R("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:R("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`,i=this.messageItemOpenForAudio;i&&this.send({type:"response.output_audio.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:R("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:R("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let s=[];i&&s.push({type:"output_audio"}),n.messageText.length>0&&s.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,i]of n.tools){let s=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:R("event"),item_id:o,response_id:e,output_index:i.outputIndex,call_id:o,name:i.name??"",arguments:s});let a={id:o,type:"function_call",callId:o,name:i.name,arguments:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)})}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,i=[];for(let s=n;s<this.items.length;s++)i.push(this.itemToProtocol(this.items[s]));return this.responseObject(e,"completed",{output:i,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=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(Le("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof ne){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Qn.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Le(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(U(r)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(U(j("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:R("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>_t&&(this.items.shift(),this.send(U({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${_t} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}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}:{}}:{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>Gt){this.ws.close(Xo,Yn("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(U(e)),this.ws.close(Qo,Yn(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;let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>Xn(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Xn(this.id,e)}},zt=[];function Xn(t,e){zt.push({id:t,reason:e}),zt.length>256&&zt.shift()}var We="/v1/realtime",ni=t=>t.slice(0,120);function ri(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
13
+ ${o}`)}function zn(t,e){let n=new he.WebSocketServer({noServer:!0,maxPayload:Uo}),r=new we,o=new Set,i=new Set,s=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,d=!1,u=(l,c,y)=>{let p;try{p=new URL(l.url??"/","http://localhost")}catch{gt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>s.delete(c)),p.pathname!==No){s.add(c);return}i.add(c);let k=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){gt(c,401,"invalid local proxy api key");return}let E;try{E=await a(l)}catch(S){let f=e.statusOf?.(S)??null;gt(c,f?.status??500,"upstream resolver rejected the connection");return}d||c.destroyed||(k=!0,n.handleUpgrade(l,c,y,S=>{i.delete(c),o.add(S),S.on("close",()=>o.delete(S));try{new Gt(S,E,r,e.statusOf)}catch{o.delete(S),S.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!k&&!c.destroyed&&gt(c,500,"responses websocket upgrade failed")}).finally(()=>i.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:l,resolve:c}=Jt();if(d)return c(),l;d=!0,t.off("upgrade",u);for(let p of i)p.destroy();i.clear();for(let p of s)p.destroy();s.clear();for(let p of o)p.close(1001,"server shutting down");let y=setTimeout(()=>{for(let p of o)p.readyState!==he.WebSocket.CLOSED&&p.terminate()},2e3);return y.unref?.(),n.close(()=>{clearTimeout(y),c()}),l}}}var nr=require("@urun-sh/core");var Yn=require("@urun-sh/core"),Ho={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},Vo={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; 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:"admission is momentarily contended (lock convoy) \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 Wt(t,e){let n=Vo[t.code];return e?`${n} (${e})`:n}function yt(t){if(t==null)return null;let e=Ho[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 _t(t){if(t.kind==="create-failed")return yt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Yn.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return yt(e?"cold_start_exceeded":"queue_timeout")}var Go=gn(require("os"),1),Jo=gn(require("path"),1),Wo=require("url"),Ko=require("util");var zo=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Yo(t){let e=t?.code;return typeof e=="string"&&zo.has(e)}function Se(t,e){try{return t.write(e),!0}catch(n){if(Yo(n))return!1;throw n}}var rr=require("ws");var tr=require("@urun-sh/core");var Qn=require("crypto");function x(t){return`${t}_${(0,Qn.randomUUID)().replace(/-/g,"").slice(0,24)}`}var wt=4*1024*1024,Kt=8*1024*1024,vt=512,bt=20*1024*1024;function j(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Le(t,e){return{type:"server_error",code:t,message:e}}function U(t){return{type:"error",event_id:x("event"),error:t}}function zt(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var R=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Xo={type:!0,model:!0,instructions:!0,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,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Qo={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Zo={format:!0,voice:!0,speed:!0};function Xn(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new R(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function Je(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new R("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(s=>!(s in Xo));if(o.length>0)throw new R(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let i={...e,outputModalities:[...e.outputModalities]};for(let[s,a]of Object.entries(r))switch(s){case"type":{if(a!=="realtime"&&a!=="transcription")throw new R(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new R(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: 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(a==="transcription"&&!n.turns)throw new R('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=a;break}case"model":if(a!==null&&typeof a!="string")throw new R("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new R("instructions must be a string or null","instructions");i.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new R("modalities must be a non-empty array","modalities");let d=[];for(let u of a){if(u!=="text"&&u!=="audio")throw new R(`modality ${JSON.stringify(u)} is not "text" or "audio"`,"modalities");if(u==="audio"&&!n.voice)throw new R('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");d.includes(u)||d.push(u)}i.outputModalities=d;break}case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new R("voice must be a string or null","voice");if(!n.voice)throw new R("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new R(`${s} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,s);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new R("temperature must be a finite number or null","temperature");i.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new R(`${s} must be a positive integer, "inf" or null`,s);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new R("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new R("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new R("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 d=a;if(!d||typeof d!="object"||Array.isArray(d))throw new R("turn_detection must be an object or null","turn_detection");let u=String(d.type??"");if(u!=="server_vad"&&u!=="semantic_vad")throw new R(`turn_detection.type ${JSON.stringify(d.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");i.turnDetection={createResponse:d.create_response!==!1,interruptResponse:d.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new R("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(!a||typeof a!="object"||Array.isArray(a))throw new R("input_audio_transcription must be an object or null","input_audio_transcription");for(let u of Object.keys(a))if(!["model","language","languages","prompt"].includes(u))throw new R(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");let d=a.model;if(d!=null){let u=typeof d=="string"?d:JSON.stringify(d);if(typeof d!="string"||d!==n.model)throw new R(`input_audio_transcription.model ${JSON.stringify(u)} 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(a!==null)throw new R("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(a===null)break;let d=a;if(!d||typeof d!="object"||Array.isArray(d))throw new R("audio must be an object or null","audio");if(d.input!==void 0&&d.input!==null){let u=d.input;if(!u||typeof u!="object"||Array.isArray(u))throw new R("audio.input must be an object","audio.input");for(let l of Object.keys(u))if(!(l in Qo))throw new R(`audio.input field not supported by this backend: ${l}`,`audio.input.${l}`,"unsupported_field");if(u.format!==void 0&&Xn(u.format,"audio.input.format"),u.transcription!==null&&u.transcription!==void 0){let l=Je({input_audio_transcription:u.transcription},i,n);i.inputAudioTranscription=l.inputAudioTranscription}if(u.turn_detection!==null&&u.turn_detection!==void 0){let l=Je({turn_detection:u.turn_detection},i,n);i.turnDetection=l.turnDetection}if(u.noise_reduction!==null&&u.noise_reduction!==void 0)throw new R("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(d.output!==void 0&&d.output!==null){let u=d.output;if(!u||typeof u!="object"||Array.isArray(u))throw new R("audio.output must be an object","audio.output");for(let l of Object.keys(u))if(!(l in Zo))throw new R(`audio.output field not supported by this backend: ${l}`,`audio.output.${l}`,"unsupported_field");if(u.format!==void 0&&Xn(u.format,"audio.output.format"),u.speed!==void 0)throw new R("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(u.voice!==void 0)if(u.voice===null)delete i.voice;else{if(typeof u.voice!="string")throw new R("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new R("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=u.voice}u.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function kt(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 Yt(t,e){let n=t;if(!n||typeof n!="object")throw new R("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 R("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:x("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 R('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new R("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new R("content part must be an object","item.content","invalid_request");if(s.type==="input_text"||r==="assistant"&&s.type==="output_text"){if(typeof s.text!="string")throw new R(`${String(s.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){if(!e)throw new R("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof s.audio!="string")throw new R("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}throw new R(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:x("item"),type:"message",role:r,content:o}}throw new R(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Xt(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 i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let s=i.transcript;if(typeof s=="string"&&s.trim().length>0){o.push({type:"input_text",text:s});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var ei=1001,ti=1011,Zn=t=>t.slice(0,120),ni=/^[A-Za-z0-9+/=]*$/,ri=2;function oi(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ri)return!1;return!0}var xe=class{id=x("conn");ws;binding;onClosed;config=zt();sessionId=x("sess");conversationId=x("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),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.send({type:"session.created",event_id:x("event"),session:kt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:x("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}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){!this.closed&&!e.signal.aborted&&this.send(U(Le("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.isTranscriptionSession()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:x("event"),item_id:e,content_index:0,transcript: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:x("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:x("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:x("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:x("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),i=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.isTranscriptionSession()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:x("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 s=x("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:x("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.created",event_id:x("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:x("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:x("event"),item_id:s,content_index:0,transcript:i}),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(j("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>wt){this.fail(j("frame_too_large",`frame exceeds the ${wt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(j("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(j("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let i=o;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(U({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}this.fail(Le(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=Je(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model}),this.send({type:"session.updated",event_id:x("event"),session:kt(this.config,this.sessionId)});return;case"conversation.item.create":{let n=Yt(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:x("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(U(j("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:x("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(U(j("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:x("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(U(j("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:x("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(U(j("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ni.test(e.audio)){this.send(U(j("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>bt){this.send(U(j("buffer_full",`uncommitted input audio exceeds the ${bt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.isTranscriptionSession()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;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:x("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(U(j("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.isTranscriptionSession()&&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=x("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:x("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:x("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.isTranscriptionSession())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:x("event"),item_id:r,content_index:0,transcript:n});else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:x("event"),item_id:r,content_index:0,transcript:i}),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;return}case"output_audio_buffer.clear":{this.send(U(j("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(U(j("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(U(j("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(U(j("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 Error("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(U({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 upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:i,input:s,...a}=e;return await o.createResponse({...a,input:s})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(U(j("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(E=>E!=="text"&&E!=="audio")){this.send(U(j("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(U(j("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.responseFlushed=!1,this.messageItemAdded=!1;let r=x("req"),o=`resp_${r}`;this.activeResponseId=o;let i=this.items.length,{input:s,sawAudioOnlyItem:a}=Xt(this.items),d=typeof n.instructions=="string"?n.instructions:this.config.instructions,u=typeof n.temperature=="number"?n.temperature:this.config.temperature,l=n.max_output_tokens??this.config.maxOutputTokens,c=l==="inf"||l===void 0?void 0:l,y=n.tools!==void 0?n.tools:this.config.tools,p=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,k={input:s,stream:!0,...this.config.model?{model:this.config.model}:{},...d!==void 0?{instructions:d}:{},...u!==void 0?{temperature:u}:{},...c!==void 0?{max_output_tokens:c}:{},...y!==void 0?{tools:y}:{},...p!==void 0?{tool_choice:p}:{}};for(let E of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(E);this.inFlight=(async()=>{let E=[],S=A=>{this.responseFlushed?this.send(A):E.push(A)},f=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:x("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:x("event"),response:this.responseObject(o,"in_progress")});for(let A of E)this.send(A);E.length=0,this.responseFlushed=!0}},h={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},g=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let A;try{A=await this.upstreamStream(k,r)}catch(_){this.upstreamTurnFault(_,o);return}try{for await(let _ of A){if(this.cancelled)break;let m=_;if(m.type==="error"){let v=this.upstreamErrorBody(m);this.responseFlushed?this.send(U(v)):this.send({type:"response.failed",event_id:x("event"),response:this.failedResponse(o,v)});return}if(m.type==="response.output_text.delta"&&typeof m.delta=="string"){f(),h.messageOpen||(this.beginMessageItem(o,h.nextOutputIndex++),h.messageOpen=!0),S({type:"response.output_text.delta",event_id:x("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:m.delta}),h.messageText+=m.delta;continue}if(m.type==="response.function_call_arguments.delta"){f();let v=typeof m.delta=="string"?m.delta:"",P=typeof m.call_id=="string"&&m.call_id.length>0?m.call_id:`${o}_fc_${h.nextOutputIndex}`,b=h.tools.get(P);if(!b){let I=typeof m.name=="string"&&m.name.length>0?m.name:void 0;b={outputIndex:h.nextOutputIndex++,name:I,args:""},h.tools.set(P,b),S({type:"response.output_item.added",event_id:x("event"),response_id:o,output_index:b.outputIndex,item:{id:P,object:"realtime.item",type:"function_call",call_id:P,name:I??"",arguments:"",status:"in_progress"}})}typeof m.name=="string"&&m.name.length>0&&(b.name=m.name),b.args+=v,S({type:"response.function_call_arguments.delta",event_id:x("event"),item_id:P,response_id:o,output_index:b.outputIndex,call_id:P,name:b.name??"",delta:v});continue}if(m.type==="response.completed"){g=m.response??null;continue}}}catch(_){this.upstreamTurnFault(_,o);return}if(this.cancelled)return;this.closeOpenItems(o,h,i),f(),this.send({type:"response.done",event_id:x("event"),response:this.doneResponse(o,i,g)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(oi(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(U({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:x("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:x("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:x("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:x("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:x("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`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:x("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:x("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`,i=this.messageItemOpenForAudio;i&&this.send({type:"response.output_audio.done",event_id:x("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:x("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:x("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let s=[];i&&s.push({type:"output_audio"}),n.messageText.length>0&&s.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:x("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,i]of n.tools){let s=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:x("event"),item_id:o,response_id:e,output_index:i.outputIndex,call_id:o,name:i.name??"",arguments:s});let a={id:o,type:"function_call",callId:o,name:i.name,arguments:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:x("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)})}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,i=[];for(let s=n;s<this.items.length;s++)i.push(this.itemToProtocol(this.items[s]));return this.responseObject(e,"completed",{output:i,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=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(Le("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof Z){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof tr.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Le(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(U(r)):this.send({type:"response.failed",event_id:x("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(U(j("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:x("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>vt&&(this.items.shift(),this.send(U({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${vt} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}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}:{}}:{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>Kt){this.ws.close(ei,Zn("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(U(e)),this.ws.close(ti,Zn(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;let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>er(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),er(this.id,e)}},Qt=[];function er(t,e){Qt.push({id:t,reason:e}),Qt.length>256&&Qt.shift()}var We="/v1/realtime",ii=t=>t.slice(0,120);function si(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
14
14
  Connection: close\r
15
15
  Content-Type: text/plain\r
16
16
  \r
17
- ${ni(n)}\r
18
- `),t.destroy()}function oi(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
19
- `}function ii(t){Re(process.stdout,t)}function si(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Yt(t){return t.audioSession?.audio.sessionId??void 0}function Ke(t,e){let n=new er.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==We)return;r.add(i),i.on("close",()=>{r.delete(i)});let d=R("rtup"),u=si(o),l=f=>{(e.log??ii)(oi(f))};l({stage:"accept",conn:d,model:u}),i.resume();let c=new AbortController,g=null,p=f=>{g??=f,c.abort(new Error(g))},k=()=>p("client socket closed"),E=()=>p("client socket closed (half-close)"),S=f=>p(`client socket error: ${f.message}`);i.once("close",k),i.once("end",E),i.once("error",S);let _=()=>{i.removeListener("close",k),i.removeListener("end",E),i.removeListener("error",S)},h=f=>{l({stage:"close",conn:d,model:u,...f})},y=f=>{let m=f,b=m.session!=null&&typeof m.session.sendResponseCreate=="function",P=m.clients!=null&&typeof m.clients.createResponse=="function";if(!b&&!P)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((v,I)=>{n.handleUpgrade(o,i,s,C=>{try{new Se({ws:C,binding:f,onClosed:(D,J)=>{h({while:"live",reason:J.reason})}}),l({stage:"admit",conn:d,model:u,...Yt(f)===void 0?{}:{session:Yt(f)}}),v()}catch(D){I(D)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async f=>{if(c.signal.aborted){_();let m=Yt(f);try{await f.release?.()}catch(b){h({while:"queued",...m===void 0?{}:{session:m},reason:g??"client socket closed",release_failed:b instanceof Error?b.message:String(b)});return}h({while:"queued",...m===void 0?{}:{session:m},reason:g??"client socket closed",released:!0}),i.destroy();return}_(),await y(f)}).catch(f=>{let m=f instanceof Zn.SessionFailedError?ht(f):null,b=null;if(f!==null&&typeof f=="object"&&"status"in f){let I=f.status;typeof I=="number"&&(b=I)}let P=b??m?.status??502,v=f instanceof Error?f.message:String(f);h({while:"queued",...c.signal.aborted?{reason:g??"client socket closed"}:{reason:v,status:P}}),i.destroyed||ri(i,P,v)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}var se=(t,e)=>Object.assign(new Error(e),{status:t});function Xt(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ai(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var ui='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Qt(t,e,n,r){if(!t.supportsAudio)throw se(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(u){throw u instanceof N?se(404,u.message):u}if(!o)throw se(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw se(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(u){throw u instanceof N?se(404,u.message):u}if(i&&!t.openTurnsOn)throw se(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let u;try{u=await t.transcriptStreamFor(e)}catch(l){throw l instanceof N?se(404,l.message):l}if(u!=="stt")throw se(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(u)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw se(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ui}`);if(r==="transcription"&&!i)throw se(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let s=await t.sessionHandle(e),a={audio:await t.openAudioOn(s,n)},d={clients:{createResponse:async u=>await t.createResponseOn(s,u)},voice:o,audioSession:a};return i&&(d.turns=u=>t.openTurnsOn(s,u)),r==="transcription"&&(d.intent="transcription"),e!==void 0&&(d.model=e),d}function bt(t,e){return{resolve:async(n,r)=>{if(e!==void 0){let o=n.headers.authorization,i=typeof o=="string"?o.trim():"",s=i.startsWith("Bearer ")?i.slice(7).trim():"";if(s===""||s!==e)throw se(401,"invalid local proxy api key")}return Qt(t,Xt(n),r,ai(n))}}}var W=class extends Error{};async function kt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new W(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let i of t){let s=i;if(o+=s.length,o>e)throw new W(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function Rt(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(s){try{let a=await n.next();if(a.done){s.close();return}if(r+=a.value.length,r>e){s.error(new W(`request body exceeds the ${e}-byte limit`));return}s.enqueue(a.value)}catch(a){s.error(a)}},cancel(){n.return?.()}}),i;try{let s=new Headers;for(let[u,l]of Object.entries(t.headers))if(typeof l=="string")s.set(u,l);else if(Array.isArray(l))for(let c of l)s.append(u,c);let a={method:"POST",headers:s,body:o,duplex:"half"};i=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(s){throw s instanceof W?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var tr="/v1/images/generations",St="/v1/images/edits";function nr(t){return t===tr||t===St}var rr="/v1/images/models";async function or(t,e,n){if(t){if(t.model=Z({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var $=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},di=16*1024*1024,ir=64*1024*1024;function sr(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function ze(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function ar(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),i=null;for await(let c of o){if(c.type==="error"){let g=c.error??{};throw new $(502,`image upstream error: ${String(g.message??"upstream reported an error")}`)}if(c.type==="response.completed"){i=c.response??null;break}}if(i===null)throw new $(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let s=i.images;if(!Array.isArray(s)||s.length!==1||typeof s[0]!="string"||s[0].length===0)throw new $(502,`image upstream returned ${Array.isArray(s)?s.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],d=s[0].startsWith("data:")?s[0].slice(s[0].indexOf(";base64,")+8):s[0],u=Buffer.from(d,"base64");if(sr(u)===null)throw new $(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${u.length} bytes) \u2014 refusing to pass it through`);return a.push(d),{images:a}}function ur(t){return t instanceof $?t:t instanceof N?new $(404,t.message):new $(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function dr(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return ze(r,new $(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function lr(t,e){t&&(t.outputUnits=e.images.length)}function cr(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var li={model:!0,prompt:!0,response_format:!0,n:!0};async function pr(t,e,n){let r=n.maxBodyBytes??ir;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${tr}`);let o;try{o=JSON.parse((await kt(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof W?new $(413,c.message):new $(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new $(400,"request body must be a JSON object");let i=o;for(let c of Object.keys(i))if(!li[c])throw new $(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let s=i.prompt;if(typeof s!="string"||s.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new $(400,"model must be a string","model");await or(n.turn,n.clients,a);let d=i.n??1;if(d!==1)throw new $(400,`n=${JSON.stringify(d)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let u=i.response_format??"b64_json";if(u!=="b64_json")throw new $(400,`response_format ${JSON.stringify(u)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",s.length,s.length),!await dr(n.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:s}];try{let c=await ar(n.clients,a,l,n.turn?re(n.turn):void 0);lr(n.turn,c),cr(e,c)}catch(c){throw ur(c)}}catch(o){if(o instanceof W){ze(e,new $(413,o.message));return}if(o instanceof $){ze(e,o);return}throw o}}var ci={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function fr(t,e,n){let r=n.maxBodyBytes??ir,o=n.maxImagePartBytes??di;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${St}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new $(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Rt(t,r)}catch(p){throw p instanceof W?new $(413,p.message):new $(400,String(p instanceof Error?p.message:p))}let a=s.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string field","prompt");let d=s.get("model");if(d!==null&&typeof d!="string")throw new $(400,"model must be a string field","model");let u=d===null?void 0:d;await or(n.turn,n.clients,u);let l=s.get("response_format")??"b64_json";if(l!=="b64_json")throw new $(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let p of s.keys())if(!ci[p])throw new $(400,`form field "${p}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,p);let c=[];for(let p of["image","image[]"])for(let k of s.getAll(p)){if(!(k instanceof File))throw new $(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",p);if(k.size>o)throw new $(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,p);let E=new Uint8Array(await k.arrayBuffer()),S=sr(E);if(S===null)throw new $(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",p);c.push({bytes:E,mime:S})}if(c.length===0)throw new $(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await dr(n.imageModels,u,"edit",e))return;let g=[{type:"input_text",text:a}];for(let{bytes:p,mime:k}of c)g.push({type:"input_image",image_url:`data:${k};base64,${Buffer.from(p).toString("base64")}`});try{let p=await ar(n.clients,u,g,n.turn?re(n.turn):void 0);lr(n.turn,p),cr(e,p)}catch(p){throw ur(p)}}catch(i){if(i instanceof W){ze(e,new $(413,i.message));return}if(i instanceof $){ze(e,i);return}throw i}}var Ye="/v1/audio/speech";function kr(t){return t===Ye}var mr=4096,gr=18e4,hr=5e3,pi=64*1024*1024,yr=8,_r=5,wr=1024*1024,Ne="voice_applied",At="X-Urun-Voice-Applied",T=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Zt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Et=class extends T{constructor(e){super(502,e)}};function Rr(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Sr(t){return new T(502,`the runtime's ${Ne} receipt ${JSON.stringify(t)} cannot be relayed as the ${At} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function fi(t,e,n){if(t){if(t.model=Z({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function xr(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var mi=2;function gi(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>mi)return!1;return!0}function hi(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var vr=new WeakMap,xt=new WeakMap;function yi(t,e){let n=xt.get(t)??0;if(n>=yr)throw new T(503,`this model's speech queue is full \u2014 ${yr} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${_r}s`,void 0,_r);xt.set(t,n+1);let r=vr.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return vr.set(t,i),(async()=>{await r;try{return await e()}finally{xt.set(t,(xt.get(t)??1)-1),o()}})()}async function _i(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new T(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(s){if(!(s instanceof ne))throw s}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),i;await Promise.race([o,new Promise(s=>{i=setTimeout(s,r)})]).finally(()=>{i!==void 0&&clearTimeout(i)})}function xe(t){return t instanceof T?t:t instanceof N?new T(404,t.message):new T(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function br(t,e,n,r,o,i,s,a){let d=a??(()=>{});return yi(e,async()=>{if(s?.()===!0)return null;let u=!1,l=!1,c=!1,g,p=new Promise(f=>{g=f}),k=[],E=()=>{l&&!c&&k.length>=o.quietRunFrames&&(c=!0,g())},S=e.onOutputAudio(f=>{let m=Buffer.from(f,"base64");if(m.byteLength===0)return;let b=gi(m);if(!u){if(b)return;u=!0}if(b){k.push(m),E();return}for(let P of k)d(P);k.length=0,d(m),E()}),_=null,h,y,x;try{x=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let m=new Promise(v=>{y=setTimeout(v,i.capMs)}),b=!1;for(;;){let v=x.next(),I=await Promise.race([v,m]);if(I===void 0){b=!0,v.catch(()=>{});break}if(I.done)break;let C=I.value;if(C.type==="error"){let D=C.error??{};throw await x.return?.(),new T(502,`speech upstream error: ${String(D.message??"upstream reported an error")}`)}if(C.type==="response.completed"){_=C.response??null,l=!0,E(),await x.return?.();break}}if(clearTimeout(y),b)throw new T(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(_===null)throw new T(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let P=!1;if(await Promise.race([p,new Promise(v=>{h=setTimeout(()=>{P=!0,v()},o.capMs)})]),h!==void 0&&clearTimeout(h),r.voice!==void 0){let v=_[Ne];if(typeof v!="string"||v!==r.voice){let I=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof v=="string"?`${Ne} ${JSON.stringify(v)}`:`no ${Ne} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new Et(I):new T(502,I)}}if(!u)throw new T(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(P&&!c&&k.length<1)throw new T(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return _}catch(f){throw f instanceof Et||await _i(t,n,x,i.returnBoundMs),f}finally{h!==void 0&&clearTimeout(h),y!==void 0&&clearTimeout(y),S()}})}function wi(t,e,n,r){let o=!1,i=0,s=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",At)),t.write(a,d=>{d||(i+=a.byteLength,xr(e,i))}),t.writableLength>wr&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${wr} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let d=a[Ne];if(typeof d=="string"){if(!Rr(d))throw Sr(d);t.addTrailers({[At]:d})}}await new Promise(d=>{t.end(()=>d())})}},fail:s}}async function vi(t,e,n){let r;try{r=await t(e)}catch(o){throw xe(o)}return r?!0:(Zt(n,new T(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var bi={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},ki="wav, pcm";async function Ar(t,e,n){let r=n.maxBodyBytes??pi,o=!1;e.once("close",()=>{o=!0});let i=()=>o||e.destroyed;try{if(t.method!=="POST")throw new T(405,`${String(t.method)} is not supported on ${Ye}`);let s;try{s=JSON.parse((await kt(t,r)).toString("utf8")||"{}")}catch(y){throw y instanceof W?new T(413,y.message):new T(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new T(400,"request body must be a JSON object");let a=s;for(let y of Object.keys(a))if(!bi[y])throw new T(400,`request field "${y}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,y);let d=a.input;if(typeof d!="string"||d.trim().length===0)throw new T(400,"input is required and must be a non-empty string","input");if(d.length>mr)throw new T(400,`input is ${d.length} chars \u2014 over the ${mr}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let u=a.model===void 0?void 0:a.model;if(u!==void 0&&typeof u!="string")throw new T(400,"model must be a string","model");let l=a.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new T(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new T(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Ye} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(u)}catch(y){throw xe(y)}if(c.defect!==null)throw new T(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let g=typeof l=="string"?l:void 0;if(g!==void 0&&c.published.length>0&&!c.published.includes(g))throw new T(400,`voice ${JSON.stringify(g)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let p=a.response_format??"wav";if(p!=="wav"&&p!=="pcm")throw new T(400,`response_format ${JSON.stringify(p)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${ki} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new T(400,"stream_format, when present, must be a string","stream_format");let k=a.speed;if(k!==void 0){if(typeof k!="number"||!Number.isFinite(k))throw new T(400,"speed, when present, must be a number","speed");if(k!==1)throw new T(400,`speed=${JSON.stringify(k)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let E=a.instructions;if(E!==void 0){if(typeof E!="string")throw new T(400,"instructions, when present, must be a string","instructions");if(E.trim().length>0)throw new T(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await fi(n.turn,n.clients,u);let S=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",S,S),!await vi(n.speechModels,u,e))return;if(typeof n.clients.openAudioOn!="function")throw new T(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new T(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new T(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let _;try{_=await n.clients.speechSessionHandle(u)}catch(y){throw xe(y)}let h;try{h=await n.clients.openAudioOn(_)}catch(y){throw xe(y)}n.turn&&(n.turn.sessionId=h.sessionId);try{if(p==="wav"){let y=[],x=await br(n.clients,h,_,{model:u,text:d,...g!==void 0?{voice:g}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??gr,returnBoundMs:n.turnReturnBoundMs??hr},i,m=>y.push(m));if(x===null||i())return;let f=Buffer.concat(y);if(g===void 0){let m=x[Ne];if(typeof m=="string"){if(!Rr(m))throw Sr(m);e.setHeader(At,m)}}xr(n.turn,f.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([hi(f.byteLength),f]))}else{let y=wi(e,n.turn,i,g===void 0),x;try{x=await br(n.clients,h,_,{model:u,text:d,...g!==void 0?{voice:g}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??gr,returnBoundMs:n.turnReturnBoundMs??hr},i,y.sink)}catch(f){let m=xe(f);if(!y.started())throw m;n.turn&&(n.turn.streamError=!0),y.fail(m);return}if(x===null)return;try{await y.finish(x)}catch(f){let m=xe(f);n.turn&&(n.turn.streamError=!0),y.fail(m);return}}}catch(y){throw xe(y)}}catch(s){if(s instanceof W){Zt(e,new T(413,s.message));return}if(s instanceof T){Zt(e,s);return}throw s}}var It="/v1/audio/transcriptions";function Er(t){return t===It}var Ir="/v1/audio/models",Ri=16*1024*1024,Si=64*1024*1024,F=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function en(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Or(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function xi(t){if(!Or(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),s=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=t.length){let d=t[a+2]|t[a+3]<<8,u=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,l=t[a+14]|t[a+15]<<8;n={sampleRate:u,channels:d,bitsPerSample:l}}else if(i==="data"){let d=t.length-a;r=Math.min(s===0||s===4294967295?d:s,d)}e=a+s+s%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Ai(t,e,n){if(t){if(t.model=Z({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Ei(t,e){t&&(t.outputUnits=e.seconds)}async function Ii(t,e,n,r,o){let i=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),s=[],a=null;for await(let d of i){if(s.push(d),d.type==="error"){let u=d.error??{},l=typeof u.type=="string"?u.type:"upstream_error",c=String(u.message??"upstream reported an error");throw new F(l==="invalid_request_error"?400:502,`transcription upstream error: ${c}`)}if(d.type==="response.completed"){a=d.response??null;break}}if(a===null)throw new F(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return $e(s,a)}function Tr(t){return t instanceof F?t:t instanceof N?new F(404,t.message):new F(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Oi(t,e,n){let r;try{r=await t(e)}catch(o){throw Tr(o)}return r?!0:(en(n,new F(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Ti=new Set(["file","model","language","response_format"]);async function Pr(t,e,n){let r=n.maxBodyBytes??Si,o=n.maxAudioPartBytes??Ri;try{if(t.method!=="POST")throw new F(405,`${String(t.method)} is not supported on ${It}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new F(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Rt(t,r)}catch(_){throw _ instanceof W?new F(413,_.message):new F(400,String(_ instanceof Error?_.message:_))}let a=new Map;for(let _ of s.keys()){if(!Ti.has(_))throw new F(400,`form field "${_}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,_);a.set(_,(a.get(_)??0)+1)}for(let[_,h]of a)if(h>1)throw new F(400,`form field "${_}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,_);let d=s.get("model");if(d!==null&&typeof d!="string")throw new F(400,"model must be a string field","model");let u=d===null?void 0:d,l=s.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new F(400,"language, when present, must be a non-empty string","language");let c=l===null?void 0:l,g=s.get("response_format")??"json";if(g!=="json")throw new F(400,`response_format ${JSON.stringify(g)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let p=s.get("file");if(!(p instanceof File))throw new F(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(p.size>o)throw new F(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let k=new Uint8Array(await p.arrayBuffer());if(!Or(k))throw new F(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let E=xi(k);if(E===null)throw new F(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Ai(n.turn,n.clients,u),n.stats?.request("audio_transcriptions",k.length,k.length),!await Oi(n.transcriptionModels,u,e))return;let S=[{type:"input_audio",input_audio:{data:Buffer.from(k).toString("base64"),format:"wav"}}];try{let _=await Ii(n.clients,u,S,c,n.turn?re(n.turn):void 0);Ei(n.turn,E),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:_}))}catch(_){throw Tr(_)}}catch(i){if(i instanceof W){en(e,new F(413,i.message));return}if(i instanceof F){en(e,i);return}throw i}}var $r="/v1/usage/requests",Cr=1e4,Pi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,he=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},Ue=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var Mr=1024*1024;function tn(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new he(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new he(`"${e}" must be an array of uuid strings`);if(n.length>Cr)throw new he(`"${e}" carries ${n.length} ids; at most ${Cr} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let i of n){if(typeof i!="string"||!Pi.test(i))throw new he(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(i)||(o.add(i),r.push(i))}return r}function Lr(t){return tn(t,"inference_ids")}function Ot(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let i=t[o];if(!n.has(i.inference_id))throw new Ue(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(i.inference_id))throw new Ue(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(i.inference_id)}}var Mt=require("@urun-sh/core");var nn="/partners/huggingface/v1/billing/requests";function Ci(t){return tn(t,"requestIds")}function $i(t){return t>=200&&t<=399}function Mi(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&$i(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Nr(t,e){let n=Ci(t),r=await e(n);return Ot(r,n),Mi(r)}var Li={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Ni(t){return Li[t]??null}var Fr=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function Ui(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Di(t){return t==="surface"}function Bi(t){let e=t?.ledgerFailureReason;return Fr.includes(e)?e:"unknown"}var Fi=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Ur=["priced","unpriced"],qi={written:Ur,already_written:Ur,skipped:Fi,failed:Fr},Pu=Object.entries(qi).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function ji(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Hi(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var Vi=256,Dr=4096,Qe=12e4,Gi=250,Ji=8e3,Ze=[],Br=new Set,et=0,Xe=!1;var Wi=new Set;function Ki(){return et===0&&Ze.length===0}function zi(){if(Ki()){Xe=!1;for(let t of[...Wi])t()}}function qr(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
20
- `}function Yi(t){Re(process.stdout,t)}function jr(t,e){try{t(e)}catch{}}function Hr(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Yi,o=Ni(e.path);if(o===null)return;let i=l=>{try{n.observe(l)}catch{}},s=(l,c)=>{i({outcome:"skipped",reason:l}),jr(r,qr("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:l,detail:c}))};if(e.status===null){s("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){s("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){s("model_unresolved",a.reason);return}let d;if(a.kind==="catalog")d={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){s("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}d={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let u={inference_id:e.inference_id,...d,task:o,http_status:e.status,started_at:Hi(e),completed_at:e.ts,billable_outcome:ji(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(Ze.length>=Dr){s("queue_full",`${Ze.length} ledger writes are already waiting (capacity ${Dr}, ${et} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Ze.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),et<Vi&&(et+=1,Xi())}async function Xi(){try{for(;;){let t=Qi();if(t===void 0)return;Br.add(t);try{await Zi(t)}finally{Br.delete(t)}}}finally{et-=1,zi()}}function Qi(){let t=Date.now();for(;;){let e=Ze.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Qe)return e;De(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${Qe}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function Zi(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);De(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let i=Ui(o);if(i!==null){De(t,{outcome:"already_written",reason:i.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:i.cost_nano_usd,price_version:i.price_version,attempts:t.attempts});return}let s=Bi(o),a=Date.now()-t.queuedAt;if(Xe){De(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Di(s)&&a<Qe){if(await ts(es(t.attempts)),Xe||Date.now()-t.queuedAt>=Qe){let d=Date.now()-t.queuedAt;De(t,{outcome:"failed",reason:Xe?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Xe?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:d,error:`this row's backoff outlived the ${Qe}ms dwell bound (waited ${d}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}De(t,{outcome:"failed",reason:s},{event:"inference_ledger_write_failed",reason:s,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function es(t){return Math.min(Ji,Gi*2**Math.max(0,t-1))}function ts(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function De(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;jr(t.report,qr(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var on="x-urun-profile",tt="voice";var te=class extends Error{status=400},ns=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,rs=/\s/;function os(t){return ns.test(t)}function rn(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new te(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Vr(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new te(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new te(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new te(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function Gr(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new te(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let u=n.trim();if(u==="")throw new te(`the ${on} header is empty \u2014 the only profile this lane accepts is "${tt}" (omit the header for the ordinary lane)`);if(u!==tt)throw new te(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${tt}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==tt)throw new te(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${tt}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new te("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new te("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let d=a??{};return{flushMaxChars:Vr(d,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Vr(d,"flush_max_ms",250,{max:2147483647}),sentenceFlush:rn(d,"sentence_flush",!0),includeReasoning:rn(d,"include_reasoning",!1),metadata:rn(d,"metadata",!1)}}var Tt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&os(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(rs.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function un(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function is(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function X(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function K(t,e,n,r="invalid_request_error",o){X(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function dn(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);X(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function ue(t,e,n,r){X(t,e,{type:"error",error:{type:n,message:r}})}function Be(t,e,n){if(e==="anthropic"){X(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}X(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var ss=64*1024*1024,nt=class extends Error{};async function Jr(t,e=ss){let n=[],r=0;for await(let i of t){if(r+=i.length,r>e)throw new nt(`request body exceeds ${e} bytes`);n.push(i)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ae(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function zr(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=d=>typeof d=="number"&&Number.isFinite(d)&&d>=0?d:null,o=r(n.input_tokens),i=r(n.output_tokens),s=d=>d??0,a=r(n.total_tokens)??s(o)+s(i);if(s(o)>0||s(i)>0){let d={input_tokens:s(o),output_tokens:s(i),total_tokens:a};return o===null||i===null?{kind:"partial",usage:d}:{kind:"counts",usage:d}}return o===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function Pt(t){let e=zr(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Wr(t){let e=Pt(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function as(t,e){let n=zr(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function us(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=d=>{let u=n[d];return typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u:null},o=r("queue_ms"),i=r("prefill_ms"),s=r("decode_ms"),a=r("total_ms");return o===null||i===null||s===null||a===null?null:{queue_ms:o,prefill_ms:i,decode_ms:s,total_ms:a}}function ds(t,e){let n=us(e);n&&(t.timing=n)}function Ee(t,e){as(t,e),ds(t,e)}async function Lt(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function Yr(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function ls(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var Ct=class extends Error{};function cs(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new Ct(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function ps(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:cs(n.role,n.content)})}return e}function sn(t){return Pe(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function fs(t,e,n,r,o,i){let s=He(i.id),a=t.stream===!0;if(i.model=Z(t),i.stream=a,await Lt(i,e,typeof t.model=="string"?t.model:void 0),a){let _;try{_=await Ge({body:t,clients:e,store:n,stats:o,responseId:s,turn:i})}catch(h){if(h instanceof N){Be(r,"openai",h);return}if(h instanceof oe){K(r,h.status,h.message);return}throw h}un(r);for await(let h of _.events)h.type==="error"&&(i.streamError=!0),h.type==="response.completed"&&Ee(i,h.response),r.write(`event: ${String(h.type??"message")}
17
+ ${ii(n)}\r
18
+ `),t.destroy()}function ai(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
19
+ `}function ui(t){Se(process.stdout,t)}function di(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Zt(t){return t.audioSession?.audio.sessionId??void 0}function Ke(t,e){let n=new rr.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==We)return;r.add(i),i.on("close",()=>{r.delete(i)});let d=x("rtup"),u=di(o),l=_=>{(e.log??ui)(ai(_))};l({stage:"accept",conn:d,model:u}),i.resume();let c=new AbortController,y=null,p=_=>{y??=_,c.abort(new Error(y))},k=()=>p("client socket closed"),E=()=>p("client socket closed (half-close)"),S=_=>p(`client socket error: ${_.message}`);i.once("close",k),i.once("end",E),i.once("error",S);let f=()=>{i.removeListener("close",k),i.removeListener("end",E),i.removeListener("error",S)},h=_=>{l({stage:"close",conn:d,model:u,..._})},g=_=>{let m=_,v=m.session!=null&&typeof m.session.sendResponseCreate=="function",P=m.clients!=null&&typeof m.clients.createResponse=="function";if(!v&&!P)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((b,I)=>{n.handleUpgrade(o,i,s,C=>{try{new xe({ws:C,binding:_,onClosed:(D,W)=>{h({while:"live",reason:W.reason})}}),l({stage:"admit",conn:d,model:u,...Zt(_)===void 0?{}:{session:Zt(_)}}),b()}catch(D){I(D)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async _=>{if(c.signal.aborted){f();let m=Zt(_);try{await _.release?.()}catch(v){h({while:"queued",...m===void 0?{}:{session:m},reason:y??"client socket closed",release_failed:v instanceof Error?v.message:String(v)});return}h({while:"queued",...m===void 0?{}:{session:m},reason:y??"client socket closed",released:!0}),i.destroy();return}f(),await g(_)}).catch(_=>{let m=_ instanceof nr.SessionFailedError?_t(_):null,v=null;if(_!==null&&typeof _=="object"&&"status"in _){let I=_.status;typeof I=="number"&&(v=I)}let P=v??m?.status??502,b=_ instanceof Error?_.message:String(_);h({while:"queued",...c.signal.aborted?{reason:y??"client socket closed"}:{reason:b,status:P}}),i.destroyed||si(i,P,b)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}var se=(t,e)=>Object.assign(new Error(e),{status:t});function en(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function li(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var ci='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function tn(t,e,n,r){if(!t.supportsAudio)throw se(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(u){throw u instanceof N?se(404,u.message):u}if(!o)throw se(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw se(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(u){throw u instanceof N?se(404,u.message):u}if(i&&!t.openTurnsOn)throw se(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let u;try{u=await t.transcriptStreamFor(e)}catch(l){throw l instanceof N?se(404,l.message):l}if(u!=="stt")throw se(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(u)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw se(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ci}`);if(r==="transcription"&&!i)throw se(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let s=await t.sessionHandle(e),a={audio:await t.openAudioOn(s,n)},d={clients:{createResponse:async u=>await t.createResponseOn(s,u)},voice:o,audioSession:a};return i&&(d.turns=u=>t.openTurnsOn(s,u)),r==="transcription"&&(d.intent="transcription"),e!==void 0&&(d.model=e),d}function St(t,e){return{resolve:async(n,r)=>{if(e!==void 0){let o=n.headers.authorization,i=typeof o=="string"?o.trim():"",s=i.startsWith("Bearer ")?i.slice(7).trim():"";if(s===""||s!==e)throw se(401,"invalid local proxy api key")}return tn(t,en(n),r,li(n))}}}var xt=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}};var ze=class extends Error{constructor(){super("no ready decision slot on this proxy \u2014 the request was refused fast, not fenced; retry shortly (an out-of-band slot add was submitted)"),this.name="DecisionCapacityError"}};var K=class extends Error{};async function Rt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new K(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let i of t){let s=i;if(o+=s.length,o>e)throw new K(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function Et(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(s){try{let a=await n.next();if(a.done){s.close();return}if(r+=a.value.length,r>e){s.error(new K(`request body exceeds the ${e}-byte limit`));return}s.enqueue(a.value)}catch(a){s.error(a)}},cancel(){n.return?.()}}),i;try{let s=new Headers;for(let[u,l]of Object.entries(t.headers))if(typeof l=="string")s.set(u,l);else if(Array.isArray(l))for(let c of l)s.append(u,c);let a={method:"POST",headers:s,body:o,duplex:"half"};i=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(s){throw s instanceof K?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var or="/v1/images/generations",At="/v1/images/edits";function ir(t){return t===or||t===At}var sr="/v1/images/models";async function ar(t,e,n){if(t){if(t.model=ee({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var M=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},pi=16*1024*1024,ur=64*1024*1024;function dr(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function Ye(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function lr(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),i=null;for await(let c of o){if(c.type==="error"){let y=c.error??{};throw new M(502,`image upstream error: ${String(y.message??"upstream reported an error")}`)}if(c.type==="response.completed"){i=c.response??null;break}}if(i===null)throw new M(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let s=i.images;if(!Array.isArray(s)||s.length!==1||typeof s[0]!="string"||s[0].length===0)throw new M(502,`image upstream returned ${Array.isArray(s)?s.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],d=s[0].startsWith("data:")?s[0].slice(s[0].indexOf(";base64,")+8):s[0],u=Buffer.from(d,"base64");if(dr(u)===null)throw new M(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${u.length} bytes) \u2014 refusing to pass it through`);return a.push(d),{images:a}}function cr(t){return t instanceof M?t:t instanceof N?new M(404,t.message):new M(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function pr(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return Ye(r,new M(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function fr(t,e){t&&(t.outputUnits=e.images.length)}function mr(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var fi={model:!0,prompt:!0,response_format:!0,n:!0};async function hr(t,e,n){let r=n.maxBodyBytes??ur;try{if(t.method!=="POST")throw new M(405,`${String(t.method)} is not supported on ${or}`);let o;try{o=JSON.parse((await Rt(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof K?new M(413,c.message):new M(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new M(400,"request body must be a JSON object");let i=o;for(let c of Object.keys(i))if(!fi[c])throw new M(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let s=i.prompt;if(typeof s!="string"||s.trim().length===0)throw new M(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new M(400,"model must be a string","model");await ar(n.turn,n.clients,a);let d=i.n??1;if(d!==1)throw new M(400,`n=${JSON.stringify(d)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let u=i.response_format??"b64_json";if(u!=="b64_json")throw new M(400,`response_format ${JSON.stringify(u)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",s.length,s.length),!await pr(n.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:s}];try{let c=await lr(n.clients,a,l,n.turn?re(n.turn):void 0);fr(n.turn,c),mr(e,c)}catch(c){throw cr(c)}}catch(o){if(o instanceof K){Ye(e,new M(413,o.message));return}if(o instanceof M){Ye(e,o);return}throw o}}var mi={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function gr(t,e,n){let r=n.maxBodyBytes??ur,o=n.maxImagePartBytes??pi;try{if(t.method!=="POST")throw new M(405,`${String(t.method)} is not supported on ${At}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new M(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Et(t,r)}catch(p){throw p instanceof K?new M(413,p.message):new M(400,String(p instanceof Error?p.message:p))}let a=s.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new M(400,"prompt is required and must be a non-empty string field","prompt");let d=s.get("model");if(d!==null&&typeof d!="string")throw new M(400,"model must be a string field","model");let u=d===null?void 0:d;await ar(n.turn,n.clients,u);let l=s.get("response_format")??"b64_json";if(l!=="b64_json")throw new M(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let p of s.keys())if(!mi[p])throw new M(400,`form field "${p}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,p);let c=[];for(let p of["image","image[]"])for(let k of s.getAll(p)){if(!(k instanceof File))throw new M(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",p);if(k.size>o)throw new M(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,p);let E=new Uint8Array(await k.arrayBuffer()),S=dr(E);if(S===null)throw new M(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",p);c.push({bytes:E,mime:S})}if(c.length===0)throw new M(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await pr(n.imageModels,u,"edit",e))return;let y=[{type:"input_text",text:a}];for(let{bytes:p,mime:k}of c)y.push({type:"input_image",image_url:`data:${k};base64,${Buffer.from(p).toString("base64")}`});try{let p=await lr(n.clients,u,y,n.turn?re(n.turn):void 0);fr(n.turn,p),mr(e,p)}catch(p){throw cr(p)}}catch(i){if(i instanceof K){Ye(e,new M(413,i.message));return}if(i instanceof M){Ye(e,i);return}throw i}}var Xe="/v1/audio/speech";function Rr(t){return t===Xe}var yr=4096,_r=18e4,wr=5e3,hi=64*1024*1024,vr=8,br=5,kr=1024*1024,Ne="voice_applied",Ot="X-Urun-Voice-Applied",T=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function nn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Tt=class extends T{constructor(e){super(502,e)}};function Er(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Ar(t){return new T(502,`the runtime's ${Ne} receipt ${JSON.stringify(t)} cannot be relayed as the ${Ot} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function gi(t,e,n){if(t){if(t.model=ee({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Ir(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var yi=2;function _i(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>yi)return!1;return!0}function wi(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var Sr=new WeakMap,It=new WeakMap;function vi(t,e){let n=It.get(t)??0;if(n>=vr)throw new T(503,`this model's speech queue is full \u2014 ${vr} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${br}s`,void 0,br);It.set(t,n+1);let r=Sr.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return Sr.set(t,i),(async()=>{await r;try{return await e()}finally{It.set(t,(It.get(t)??1)-1),o()}})()}async function bi(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new T(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(s){if(!(s instanceof Z))throw s}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),i;await Promise.race([o,new Promise(s=>{i=setTimeout(s,r)})]).finally(()=>{i!==void 0&&clearTimeout(i)})}function Re(t){return t instanceof T?t:t instanceof N?new T(404,t.message):new T(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function xr(t,e,n,r,o,i,s,a){let d=a??(()=>{});return vi(e,async()=>{if(s?.()===!0)return null;let u=!1,l=!1,c=!1,y,p=new Promise(_=>{y=_}),k=[],E=()=>{l&&!c&&k.length>=o.quietRunFrames&&(c=!0,y())},S=e.onOutputAudio(_=>{let m=Buffer.from(_,"base64");if(m.byteLength===0)return;let v=_i(m);if(!u){if(v)return;u=!0}if(v){k.push(m),E();return}for(let P of k)d(P);k.length=0,d(m),E()}),f=null,h,g,A;try{A=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let m=new Promise(b=>{g=setTimeout(b,i.capMs)}),v=!1;for(;;){let b=A.next(),I=await Promise.race([b,m]);if(I===void 0){v=!0,b.catch(()=>{});break}if(I.done)break;let C=I.value;if(C.type==="error"){let D=C.error??{};throw await A.return?.(),new T(502,`speech upstream error: ${String(D.message??"upstream reported an error")}`)}if(C.type==="response.completed"){f=C.response??null,l=!0,E(),await A.return?.();break}}if(clearTimeout(g),v)throw new T(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(f===null)throw new T(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let P=!1;if(await Promise.race([p,new Promise(b=>{h=setTimeout(()=>{P=!0,b()},o.capMs)})]),h!==void 0&&clearTimeout(h),r.voice!==void 0){let b=f[Ne];if(typeof b!="string"||b!==r.voice){let I=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof b=="string"?`${Ne} ${JSON.stringify(b)}`:`no ${Ne} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new Tt(I):new T(502,I)}}if(!u)throw new T(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(P&&!c&&k.length<1)throw new T(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return f}catch(_){throw _ instanceof Tt||await bi(t,n,A,i.returnBoundMs),_}finally{h!==void 0&&clearTimeout(h),g!==void 0&&clearTimeout(g),S()}})}function ki(t,e,n,r){let o=!1,i=0,s=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Ot)),t.write(a,d=>{d||(i+=a.byteLength,Ir(e,i))}),t.writableLength>kr&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${kr} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let d=a[Ne];if(typeof d=="string"){if(!Er(d))throw Ar(d);t.addTrailers({[Ot]:d})}}await new Promise(d=>{t.end(()=>d())})}},fail:s}}async function Si(t,e,n){let r;try{r=await t(e)}catch(o){throw Re(o)}return r?!0:(nn(n,new T(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var xi={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Ri="wav, pcm";async function Or(t,e,n){let r=n.maxBodyBytes??hi,o=!1;e.once("close",()=>{o=!0});let i=()=>o||e.destroyed;try{if(t.method!=="POST")throw new T(405,`${String(t.method)} is not supported on ${Xe}`);let s;try{s=JSON.parse((await Rt(t,r)).toString("utf8")||"{}")}catch(g){throw g instanceof K?new T(413,g.message):new T(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new T(400,"request body must be a JSON object");let a=s;for(let g of Object.keys(a))if(!xi[g])throw new T(400,`request field "${g}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,g);let d=a.input;if(typeof d!="string"||d.trim().length===0)throw new T(400,"input is required and must be a non-empty string","input");if(d.length>yr)throw new T(400,`input is ${d.length} chars \u2014 over the ${yr}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let u=a.model===void 0?void 0:a.model;if(u!==void 0&&typeof u!="string")throw new T(400,"model must be a string","model");let l=a.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new T(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new T(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Xe} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(u)}catch(g){throw Re(g)}if(c.defect!==null)throw new T(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let y=typeof l=="string"?l:void 0;if(y!==void 0&&c.published.length>0&&!c.published.includes(y))throw new T(400,`voice ${JSON.stringify(y)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let p=a.response_format??"wav";if(p!=="wav"&&p!=="pcm")throw new T(400,`response_format ${JSON.stringify(p)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Ri} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new T(400,"stream_format, when present, must be a string","stream_format");let k=a.speed;if(k!==void 0){if(typeof k!="number"||!Number.isFinite(k))throw new T(400,"speed, when present, must be a number","speed");if(k!==1)throw new T(400,`speed=${JSON.stringify(k)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let E=a.instructions;if(E!==void 0){if(typeof E!="string")throw new T(400,"instructions, when present, must be a string","instructions");if(E.trim().length>0)throw new T(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await gi(n.turn,n.clients,u);let S=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",S,S),!await Si(n.speechModels,u,e))return;if(typeof n.clients.openAudioOn!="function")throw new T(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new T(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new T(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let f;try{f=await n.clients.speechSessionHandle(u)}catch(g){throw Re(g)}let h;try{h=await n.clients.openAudioOn(f)}catch(g){throw Re(g)}n.turn&&(n.turn.sessionId=h.sessionId);try{if(p==="wav"){let g=[],A=await xr(n.clients,h,f,{model:u,text:d,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??_r,returnBoundMs:n.turnReturnBoundMs??wr},i,m=>g.push(m));if(A===null||i())return;let _=Buffer.concat(g);if(y===void 0){let m=A[Ne];if(typeof m=="string"){if(!Er(m))throw Ar(m);e.setHeader(Ot,m)}}Ir(n.turn,_.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([wi(_.byteLength),_]))}else{let g=ki(e,n.turn,i,y===void 0),A;try{A=await xr(n.clients,h,f,{model:u,text:d,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??_r,returnBoundMs:n.turnReturnBoundMs??wr},i,g.sink)}catch(_){let m=Re(_);if(!g.started())throw m;n.turn&&(n.turn.streamError=!0),g.fail(m);return}if(A===null)return;try{await g.finish(A)}catch(_){let m=Re(_);n.turn&&(n.turn.streamError=!0),g.fail(m);return}}}catch(g){throw Re(g)}}catch(s){if(s instanceof K){nn(e,new T(413,s.message));return}if(s instanceof T){nn(e,s);return}throw s}}var Pt="/v1/audio/transcriptions";function Tr(t){return t===Pt}var Pr="/v1/audio/models",Ei=16*1024*1024,Ai=64*1024*1024,B=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function rn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Cr(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function Ii(t){if(!Cr(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),s=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=t.length){let d=t[a+2]|t[a+3]<<8,u=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,l=t[a+14]|t[a+15]<<8;n={sampleRate:u,channels:d,bitsPerSample:l}}else if(i==="data"){let d=t.length-a;r=Math.min(s===0||s===4294967295?d:s,d)}e=a+s+s%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Oi(t,e,n){if(t){if(t.model=ee({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Ti(t,e){t&&(t.outputUnits=e.seconds)}async function Pi(t,e,n,r,o){let i=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),s=[],a=null;for await(let d of i){if(s.push(d),d.type==="error"){let u=d.error??{},l=typeof u.type=="string"?u.type:"upstream_error",c=String(u.message??"upstream reported an error");throw new B(l==="invalid_request_error"?400:502,`transcription upstream error: ${c}`)}if(d.type==="response.completed"){a=d.response??null;break}}if(a===null)throw new B(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return Me(s,a)}function Mr(t){return t instanceof B?t:t instanceof N?new B(404,t.message):new B(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Ci(t,e,n){let r;try{r=await t(e)}catch(o){throw Mr(o)}return r?!0:(rn(n,new B(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Mi=new Set(["file","model","language","response_format"]);async function $r(t,e,n){let r=n.maxBodyBytes??Ai,o=n.maxAudioPartBytes??Ei;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${Pt}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new B(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Et(t,r)}catch(f){throw f instanceof K?new B(413,f.message):new B(400,String(f instanceof Error?f.message:f))}let a=new Map;for(let f of s.keys()){if(!Mi.has(f))throw new B(400,`form field "${f}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,f);a.set(f,(a.get(f)??0)+1)}for(let[f,h]of a)if(h>1)throw new B(400,`form field "${f}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,f);let d=s.get("model");if(d!==null&&typeof d!="string")throw new B(400,"model must be a string field","model");let u=d===null?void 0:d,l=s.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new B(400,"language, when present, must be a non-empty string","language");let c=l===null?void 0:l,y=s.get("response_format")??"json";if(y!=="json")throw new B(400,`response_format ${JSON.stringify(y)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let p=s.get("file");if(!(p instanceof File))throw new B(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(p.size>o)throw new B(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let k=new Uint8Array(await p.arrayBuffer());if(!Cr(k))throw new B(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let E=Ii(k);if(E===null)throw new B(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Oi(n.turn,n.clients,u),n.stats?.request("audio_transcriptions",k.length,k.length),!await Ci(n.transcriptionModels,u,e))return;let S=[{type:"input_audio",input_audio:{data:Buffer.from(k).toString("base64"),format:"wav"}}];try{let f=await Pi(n.clients,u,S,c,n.turn?re(n.turn):void 0);Ti(n.turn,E),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:f}))}catch(f){throw Mr(f)}}catch(i){if(i instanceof K){rn(e,new B(413,i.message));return}if(i instanceof B){rn(e,i);return}throw i}}var Nr="/v1/usage/requests",Lr=1e4,$i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ge=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},Ue=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var Ur=1024*1024;function on(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ge(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new ge(`"${e}" must be an array of uuid strings`);if(n.length>Lr)throw new ge(`"${e}" carries ${n.length} ids; at most ${Lr} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let i of n){if(typeof i!="string"||!$i.test(i))throw new ge(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(i)||(o.add(i),r.push(i))}return r}function Dr(t){return on(t,"inference_ids")}function Ct(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let i=t[o];if(!n.has(i.inference_id))throw new Ue(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(i.inference_id))throw new Ue(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(i.inference_id)}}var Ut=require("@urun-sh/core");var Li=require("@urun-sh/core"),Qe=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}};var sn="/partners/huggingface/v1/billing/requests";function Ni(t){return on(t,"requestIds")}function Ui(t){return t>=200&&t<=399}function Di(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Ui(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Fr(t,e){let n=Ni(t),r=await e(n);return Ct(r,n),Di(r)}var Fi={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Bi(t){return Fi[t]??null}var Hr=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function qi(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function ji(t){return t==="surface"}function Hi(t){let e=t?.ledgerFailureReason;return Hr.includes(e)?e:"unknown"}var Vi=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Br=["priced","unpriced"],Gi={written:Br,already_written:Br,skipped:Vi,failed:Hr},Bu=Object.entries(Gi).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Ji(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Wi(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var Ki=256,qr=4096,et=12e4,zi=250,Yi=8e3,tt=[],jr=new Set,nt=0,Ze=!1;var Xi=new Set;function Qi(){return nt===0&&tt.length===0}function Zi(){if(Qi()){Ze=!1;for(let t of[...Xi])t()}}function Vr(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
20
+ `}function es(t){Se(process.stdout,t)}function Gr(t,e){try{t(e)}catch{}}function Jr(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??es,o=Bi(e.path);if(o===null)return;let i=l=>{try{n.observe(l)}catch{}},s=(l,c)=>{i({outcome:"skipped",reason:l}),Gr(r,Vr("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:l,detail:c}))};if(e.status===null){s("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){s("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){s("model_unresolved",a.reason);return}let d;if(a.kind==="catalog")d={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){s("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}d={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let u={inference_id:e.inference_id,...d,task:o,http_status:e.status,started_at:Wi(e),completed_at:e.ts,billable_outcome:Ji(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(tt.length>=qr){s("queue_full",`${tt.length} ledger writes are already waiting (capacity ${qr}, ${nt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}tt.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),nt<Ki&&(nt+=1,ts())}async function ts(){try{for(;;){let t=ns();if(t===void 0)return;jr.add(t);try{await rs(t)}finally{jr.delete(t)}}}finally{nt-=1,Zi()}}function ns(){let t=Date.now();for(;;){let e=tt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<et)return e;De(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${et}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function rs(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);De(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let i=qi(o);if(i!==null){De(t,{outcome:"already_written",reason:i.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:i.cost_nano_usd,price_version:i.price_version,attempts:t.attempts});return}let s=Hi(o),a=Date.now()-t.queuedAt;if(Ze){De(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(ji(s)&&a<et){if(await is(os(t.attempts)),Ze||Date.now()-t.queuedAt>=et){let d=Date.now()-t.queuedAt;De(t,{outcome:"failed",reason:Ze?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Ze?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:d,error:`this row's backoff outlived the ${et}ms dwell bound (waited ${d}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}De(t,{outcome:"failed",reason:s},{event:"inference_ledger_write_failed",reason:s,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function os(t){return Math.min(Yi,zi*2**Math.max(0,t-1))}function is(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function De(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Gr(t.report,Vr(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var un="x-urun-profile",rt="voice";var ne=class extends Error{status=400},ss=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,as=/\s/;function us(t){return ss.test(t)}function an(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ne(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Wr(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new ne(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new ne(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new ne(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function Kr(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new ne(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let u=n.trim();if(u==="")throw new ne(`the ${un} header is empty \u2014 the only profile this lane accepts is "${rt}" (omit the header for the ordinary lane)`);if(u!==rt)throw new ne(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${rt}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==rt)throw new ne(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${rt}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new ne("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new ne("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let d=a??{};return{flushMaxChars:Wr(d,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Wr(d,"flush_max_ms",250,{max:2147483647}),sentenceFlush:an(d,"sentence_flush",!0),includeReasoning:an(d,"include_reasoning",!1),metadata:an(d,"metadata",!1)}}var Mt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&us(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(as.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function cn(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function ds(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function X(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function G(t,e,n,r="invalid_request_error",o){X(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function pn(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);X(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function ue(t,e,n,r){X(t,e,{type:"error",error:{type:n,message:r}})}function Fe(t,e,n){if(e==="anthropic"){X(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}X(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var ls=64*1024*1024,ot=class extends Error{};async function zr(t,e=ls){let n=[],r=0;for await(let i of t){if(r+=i.length,r>e)throw new ot(`request body exceeds ${e} bytes`);n.push(i)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ee(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function Qr(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=d=>typeof d=="number"&&Number.isFinite(d)&&d>=0?d:null,o=r(n.input_tokens),i=r(n.output_tokens),s=d=>d??0,a=r(n.total_tokens)??s(o)+s(i);if(s(o)>0||s(i)>0){let d={input_tokens:s(o),output_tokens:s(i),total_tokens:a};return o===null||i===null?{kind:"partial",usage:d}:{kind:"counts",usage:d}}return o===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function $t(t){let e=Qr(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Yr(t){let e=$t(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function cs(t,e){let n=Qr(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function ps(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=d=>{let u=n[d];return typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u:null},o=r("queue_ms"),i=r("prefill_ms"),s=r("decode_ms"),a=r("total_ms");return o===null||i===null||s===null||a===null?null:{queue_ms:o,prefill_ms:i,decode_ms:s,total_ms:a}}function fs(t,e){let n=ps(e);n&&(t.timing=n)}function Ae(t,e){cs(t,e),fs(t,e)}async function Dt(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function Zr(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function ms(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var Lt=class extends Error{};function hs(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new Lt(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function gs(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:hs(n.role,n.content)})}return e}function dn(t){return Pe(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function ys(t,e,n,r,o,i){let s=He(i.id),a=t.stream===!0;if(i.model=ee(t),i.stream=a,await Dt(i,e,typeof t.model=="string"?t.model:void 0),a){let f;try{f=await Ge({body:t,clients:e,store:n,stats:o,responseId:s,turn:i})}catch(h){if(h instanceof N){Fe(r,"openai",h);return}if(h instanceof oe){G(r,h.status,h.message);return}throw h}cn(r);for await(let h of f.events)h.type==="error"&&(i.streamError=!0),h.type==="response.completed"&&Ae(i,h.response),r.write(`event: ${String(h.type??"message")}
21
21
  data: ${JSON.stringify(h)}
22
22
 
23
23
  `);r.write(`data: [DONE]
24
24
 
25
- `),r.end();return}let d;try{d=Me(n,t)}catch(_){if(_ instanceof oe){K(r,_.status,_.message);return}throw _}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(d))-Buffer.byteLength(JSON.stringify(t.input)));let u=t.store!==!1,l=Z(t);o.model(l);let c=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await Ft(e,t,d,!1,re(i))}catch(_){if(_ instanceof N){Be(r,"openai",_);return}if(_ instanceof oe){K(r,_.status,_.message);return}throw _}let p=[],k=null;for await(let _ of o.track(g,l,i)){if(p.push(_),_.type==="error"){dn(r,_);return}_.type==="response.completed"&&(k=_.response)}if(k==null){K(r,502,"upstream produced no response.completed event","upstream_error");return}Ee(i,k);let E=$e(p,k),S=ke(c,Pe(k).length,E);if(S){K(r,502,be(l,S),"upstream_error");return}u&&n.remember(s,d,Bt(k,E),u),X(r,200,{...k,id:s})}async function ms(t,e,n,r,o,i){let s=t.messages;if(!Array.isArray(s)){K(n,400,"chat/completions requires a messages array");return}let a;try{a=Gr(i,t)}catch(v){if(v instanceof te){K(n,v.status,v.message);return}throw v}let d=String(t.model??"urun"),u=Dn(o.id),l;try{l=ps(s)}catch(v){if(v instanceof Ct){K(n,400,v.message);return}throw v}let c=Z(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Lt(o,e,typeof t.model=="string"?t.model:void 0);let g=Array.isArray(t.tools)&&t.tools.length>0,p;try{p=await e.createResponse({model:t.model,input:l,stream:!0,tools:ls(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},re(o))}catch(v){if(v instanceof N){Be(n,"openai",v);return}throw v}if(t.stream===!0){a?is(n):un(n);let v=[],I=new me,C="",D=a?new Tt(a,Q=>{n.write(`data: ${JSON.stringify(Ae(u,d,{content:Q},null))}
25
+ `),r.end();return}let d;try{d=$e(n,t)}catch(f){if(f instanceof oe){G(r,f.status,f.message);return}throw f}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(d))-Buffer.byteLength(JSON.stringify(t.input)));let u=t.store!==!1,l=ee(t);o.model(l);let c=Array.isArray(t.tools)&&t.tools.length>0,y;try{y=await Ht(e,t,d,!1,re(i))}catch(f){if(f instanceof N){Fe(r,"openai",f);return}if(f instanceof oe){G(r,f.status,f.message);return}throw f}let p=[],k=null;for await(let f of o.track(y,l,i)){if(p.push(f),f.type==="error"){pn(r,f);return}f.type==="response.completed"&&(k=f.response)}if(k==null){G(r,502,"upstream produced no response.completed event","upstream_error");return}Ae(i,k);let E=Me(p,k),S=ke(c,Pe(k).length,E);if(S){G(r,502,be(l,S),"upstream_error");return}u&&n.remember(s,d,jt(k,E),u),X(r,200,{...k,id:s})}async function _s(t,e,n,r,o,i){let s=t.messages;if(!Array.isArray(s)){G(n,400,"chat/completions requires a messages array");return}let a;try{a=Kr(i,t)}catch(b){if(b instanceof ne){G(n,b.status,b.message);return}throw b}let d=String(t.model??"urun"),u=qn(o.id),l;try{l=gs(s)}catch(b){if(b instanceof Lt){G(n,400,b.message);return}throw b}let c=ee(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Dt(o,e,typeof t.model=="string"?t.model:void 0);let y=Array.isArray(t.tools)&&t.tools.length>0,p;try{p=await e.createResponse({model:t.model,input:l,stream:!0,tools:ms(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},re(o))}catch(b){if(b instanceof N){Fe(n,"openai",b);return}throw b}if(t.stream===!0){a?ds(n):cn(n);let b=[],I=new me,C="",D=a?new Mt(a,Q=>{n.write(`data: ${JSON.stringify(Ee(u,d,{content:Q},null))}
26
26
 
27
- `)}):null,J=Q=>{D?.flush(),n.write(Q),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:u,model:d,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
27
+ `)}):null,W=Q=>{D?.flush(),n.write(Q),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:u,model:d,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
28
28
 
29
- `),n.write(`data: ${JSON.stringify(Ae(u,d,{role:"assistant"},null))}
29
+ `),n.write(`data: ${JSON.stringify(Ee(u,d,{role:"assistant"},null))}
30
30
 
31
- `);for await(let V of r.track(p,c,o)){v.push(V);let z=Ce(V);if(V.type==="response.output_text.delta"&&typeof V.delta=="string")C+=V.delta,D?D.push(V.delta):n.write(`data: ${JSON.stringify(Ae(u,d,{content:V.delta},null))}
31
+ `);for await(let V of r.track(p,c,o)){b.push(V);let z=Ce(V);if(V.type==="response.output_text.delta"&&typeof V.delta=="string")C+=V.delta,D?D.push(V.delta):n.write(`data: ${JSON.stringify(Ee(u,d,{content:V.delta},null))}
32
32
 
33
- `);else if(V.type==="response.reasoning_text.delta"&&typeof V.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(Ae(u,d,{reasoning_content:V.delta},null))}
33
+ `);else if(V.type==="response.reasoning_text.delta"&&typeof V.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(Ee(u,d,{reasoning_content:V.delta},null))}
34
34
 
35
- `);else if(z){D?.flush();let{call:ye,isNew:O}=I.add(z),M=O?{index:z.tool_index,id:ye.id??`call_${z.tool_index}`,type:"function",function:{name:ye.name??"",arguments:z.delta}}:{index:z.tool_index,function:{arguments:z.delta}};n.write(`data: ${JSON.stringify(Ae(u,d,{tool_calls:[M]},null))}
35
+ `);else if(z){D?.flush();let{call:ye,isNew:O}=I.add(z),L=O?{index:z.tool_index,id:ye.id??`call_${z.tool_index}`,type:"function",function:{name:ye.name??"",arguments:z.delta}}:{index:z.tool_index,function:{arguments:z.delta}};n.write(`data: ${JSON.stringify(Ee(u,d,{tool_calls:[L]},null))}
36
36
 
37
- `)}else if(V.type==="error"){o.streamError=!0,J(`data: ${JSON.stringify({error:V})}
37
+ `)}else if(V.type==="error"){o.streamError=!0,W(`data: ${JSON.stringify({error:V})}
38
38
 
39
- `);return}}let Q=sn(ae(v)),ie=ke(g,I.size+Q.length,C);if(ie){o.streamError=!0,J(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:be(c,ie)}})}
39
+ `);return}}let Q=dn(ae(b)),ie=ke(y,I.size+Q.length,C);if(ie){o.streamError=!0,W(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:be(c,ie)}})}
40
40
 
41
- `);return}D?.flush(),I.size===0&&Q.length>0&&n.write(`data: ${JSON.stringify(Ae(u,d,{tool_calls:Q},null))}
41
+ `);return}D?.flush(),I.size===0&&Q.length>0&&n.write(`data: ${JSON.stringify(Ee(u,d,{tool_calls:Q},null))}
42
42
 
43
- `);let pe=I.size>0||Q.length>0;n.write(`data: ${JSON.stringify(Ae(u,d,{},pe?"tool_calls":"stop"))}
43
+ `);let pe=I.size>0||Q.length>0;n.write(`data: ${JSON.stringify(Ee(u,d,{},pe?"tool_calls":"stop"))}
44
44
 
45
- `);let H=Pt(ae(v));Ee(o,ae(v)),H&&n.write(`data: ${JSON.stringify({id:u,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:d,choices:[],usage:Wr(ae(v))})}
45
+ `);let H=$t(ae(b));Ae(o,ae(b)),H&&n.write(`data: ${JSON.stringify({id:u,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:d,choices:[],usage:Yr(ae(b))})}
46
46
 
47
47
  `),n.write(`data: [DONE]
48
48
 
49
- `),n.end();return}finally{D?.flush(),D?.dispose()}}let k="",E="",S=[],_=new me;for await(let v of r.track(p,c,o)){S.push(v),v.type==="response.output_text.delta"&&typeof v.delta=="string"&&(k+=v.delta),v.type==="response.reasoning_text.delta"&&typeof v.delta=="string"&&(E+=v.delta);let I=Ce(v);if(I&&_.add(I),v.type==="error"){dn(n,v);return}}let h=ae(S);Ee(o,h);let y=sn(h),x=y.length>0?y:sn({output:_.items()}),f=ke(g,x.length,k);if(f){K(n,502,be(c,f),"upstream_error");return}let m=x.map(({index:v,...I})=>I),b={role:"assistant",content:k||null},P=E||Yr(h);P&&(b.reasoning_content=P),m.length>0&&(b.tool_calls=m),X(n,200,{id:u,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:d,choices:[{index:0,message:b,finish_reason:m.length>0?"tool_calls":"stop"}],usage:Wr(h)})}var gs="reflex-latest";async function hs(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){K(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:gs,s=Z({model:i});if(o.model=s,o.stream=!1,t.state===void 0||t.state===null){K(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){K(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){K(n,400,"systemone media, when present, must be an array");return}r.model(s),await Lt(o,e,i);let d;try{d=await e.createResponse({model:i,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},re(o))}catch(p){if(p instanceof N){Be(n,"openai",p);return}throw p}let u=[];try{for await(let p of r.track(d,s,o))if(u.push(p),p.type==="error"){dn(n,p);return}}catch(p){if(p instanceof N){Be(n,"openai",p);return}throw p}let l=ae(u);if(l==null){K(n,502,"upstream produced no response.completed event","upstream_error");return}Ee(o,l);let c=$e(u,l),g;try{g=JSON.parse(c)}catch{K(n,502,"systemone answer was not valid JSON","upstream_error");return}if(g===null||typeof g!="object"||Array.isArray(g)){K(n,502,"systemone answer was not a JSON object","upstream_error");return}X(n,200,g)}function ys(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var rt=class extends Error{};function $t(t){return new rt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function _s(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function ws(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new rt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function vs(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw $t(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw $t(`tool_result > ${r}`);e+=String(n.text??"")}return e}function bs(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw $t(typeof n);let r=[],o="",i=()=>{o&&(r.push({role:e,content:o}),o="")};for(let s of n){let a=String(s.type??"");if(a==="text")o+=String(s.text??"");else if(a==="tool_use")i(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});else if(a==="tool_result")i(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:vs(s.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw $t(a)}}return i(),r}function an(t){return Pe(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function ks(t,e,n,r,o){let i=t.messages;if(!Array.isArray(i)){ue(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){ue(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){ue(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(b=>typeof b!="string"))){ue(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let s=String(t.model??"urun"),a=Bn(o.id),d=[],u;try{t.system&&d.push({role:"system",content:ys(t.system)});for(let b of i)d.push(...bs(b));u=ws(t.tool_choice)}catch(b){if(b instanceof rt){ue(n,400,"invalid_request_error",b.message);return}throw b}let l=Z(t);r.model(l),o.model=l,o.stream=t.stream===!0,await Lt(o,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await e.createResponse({model:t.model,input:d,stream:!0,tools:_s(t.tools),tool_choice:u,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},re(o))}catch(b){if(b instanceof N){Be(n,"anthropic",b);return}throw b}let p=(b,P)=>{n.destroyed||n.write(`event: ${b}
50
- data: ${JSON.stringify({type:b,...P})}
49
+ `),n.end();return}finally{D?.flush(),D?.dispose()}}let k="",E="",S=[],f=new me;for await(let b of r.track(p,c,o)){S.push(b),b.type==="response.output_text.delta"&&typeof b.delta=="string"&&(k+=b.delta),b.type==="response.reasoning_text.delta"&&typeof b.delta=="string"&&(E+=b.delta);let I=Ce(b);if(I&&f.add(I),b.type==="error"){pn(n,b);return}}let h=ae(S);Ae(o,h);let g=dn(h),A=g.length>0?g:dn({output:f.items()}),_=ke(y,A.length,k);if(_){G(n,502,be(c,_),"upstream_error");return}let m=A.map(({index:b,...I})=>I),v={role:"assistant",content:k||null},P=E||Zr(h);P&&(v.reasoning_content=P),m.length>0&&(v.tool_calls=m),X(n,200,{id:u,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:d,choices:[{index:0,message:v,finish_reason:m.length>0?"tool_calls":"stop"}],usage:Yr(h)})}var ws="sense-latest";async function vs(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){G(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:ws,s=ee({model:i});if(o.model=s,o.stream=!1,t.state===void 0||t.state===null){G(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){G(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){G(n,400,"systemone media, when present, must be an array");return}let d={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=d;let u=performance.now();r.model(s),await Dt(o,e,i),d.resolve_ms=Math.round(performance.now()-u);let l,c=performance.now();try{l=await e.createResponse({model:i,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},re(o))}catch(f){if(f instanceof N){Fe(n,"openai",f);return}if(f instanceof ze){n.setHeader("retry-after","2"),G(n,503,f.message,"capacity_error");return}throw f}d.dial_ms=Math.round(performance.now()-c);let y=[],p=null;try{for await(let f of r.track(l,s,o))if(p===null&&(p=performance.now(),d.first_event_ms=Math.round(p-c)),y.push(f),f.type==="error"){pn(n,f);return}}catch(f){if(f instanceof N){p!==null&&(d.stream_ms=Math.round(performance.now()-p)),Fe(n,"openai",f);return}if(f instanceof ze){p!==null&&(d.stream_ms=Math.round(performance.now()-p)),n.setHeader("retry-after","2"),G(n,503,f.message,"capacity_error");return}throw p!==null&&(d.stream_ms=Math.round(performance.now()-p)),f}p!==null&&(d.stream_ms=Math.round(performance.now()-p));let k=ae(y);if(k==null){G(n,502,"upstream produced no response.completed event","upstream_error");return}Ae(o,k);let E=Me(y,k),S;try{S=JSON.parse(E)}catch{G(n,502,"systemone answer was not valid JSON","upstream_error");return}if(S===null||typeof S!="object"||Array.isArray(S)){G(n,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof S=="object"&&S!==null&&!Array.isArray(S)&&"timing"in S){let f=S.timing;if(typeof f=="object"&&f!==null&&!Array.isArray(f)&&"question_fwd_ms"in f&&"head_ms"in f){let h=g=>typeof g=="number"&&Number.isFinite(g)&&g>=0?Math.round(g):null;d.question_fwd_ms=h(f.question_fwd_ms),d.head_ms=h(f.head_ms)}}X(n,200,S)}function bs(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var it=class extends Error{};function Nt(t){return new it(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function ks(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function Ss(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new it(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function xs(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Nt(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Nt(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Rs(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw Nt(typeof n);let r=[],o="",i=()=>{o&&(r.push({role:e,content:o}),o="")};for(let s of n){let a=String(s.type??"");if(a==="text")o+=String(s.text??"");else if(a==="tool_use")i(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});else if(a==="tool_result")i(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:xs(s.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Nt(a)}}return i(),r}function ln(t){return Pe(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function Es(t,e,n,r,o){let i=t.messages;if(!Array.isArray(i)){ue(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){ue(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){ue(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(v=>typeof v!="string"))){ue(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let s=String(t.model??"urun"),a=jn(o.id),d=[],u;try{t.system&&d.push({role:"system",content:bs(t.system)});for(let v of i)d.push(...Rs(v));u=Ss(t.tool_choice)}catch(v){if(v instanceof it){ue(n,400,"invalid_request_error",v.message);return}throw v}let l=ee(t);r.model(l),o.model=l,o.stream=t.stream===!0,await Dt(o,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0,y;try{y=await e.createResponse({model:t.model,input:d,stream:!0,tools:ks(t.tools),tool_choice:u,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},re(o))}catch(v){if(v instanceof N){Fe(n,"anthropic",v);return}throw v}let p=(v,P)=>{n.destroyed||n.write(`event: ${v}
50
+ data: ${JSON.stringify({type:v,...P})}
51
51
 
52
- `)};if(t.stream===!0){let b=r.track(g,l,o);un(n),p("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:s,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let P=0,v="",I=0,C="none",D=()=>C,J=-1,Q=-1,ie=new me,pe=[],H=()=>{C!=="none"&&(C="none",p("content_block_stop",{index:J}))},V=(B,Y)=>{H(),C=B,J=I++,p("content_block_start",{index:J,content_block:Y})};for await(let B of b){if(n.destroyed)break;pe.push(B);let Y=Ce(B);if(B.type==="response.reasoning_text.delta"&&typeof B.delta=="string")D()!=="thinking"&&V("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:J,delta:{type:"thinking_delta",thinking:B.delta}});else if(B.type==="response.output_text.delta"&&typeof B.delta=="string")D()!=="text"&&V("text",{type:"text",text:""}),P+=1,v+=B.delta,p("content_block_delta",{index:J,delta:{type:"text_delta",text:B.delta}});else if(Y){let{call:fe}=ie.add(Y);(D()!=="tool"||Y.tool_index!==Q)&&(Q=Y.tool_index,V("tool",{type:"tool_use",id:fe.id??`call_${Y.tool_index}`,name:fe.name??"",input:{}})),Y.delta&&p("content_block_delta",{index:J,delta:{type:"input_json_delta",partial_json:Y.delta}})}else if(B.type==="error"){o.streamError=!0,p("error",{error:{type:"api_error",message:JSON.stringify(B)}}),n.end();return}}if(n.destroyed)return;let z=ae(pe),ye=Pe(z),O=ke(c,ie.size+ye.length,v);if(O){o.streamError=!0,p("error",{error:{type:"api_error",message:be(l,O)}}),n.end();return}H();let M=[];if(ie.size===0)try{M=an(z)}catch(B){o.streamError=!0,p("error",{error:{type:"api_error",message:String(B instanceof Error?B.message:B)}}),n.end();return}I===0&&M.length===0&&(V("text",{type:"text",text:""}),H()),M.forEach(B=>{let Y=I++;p("content_block_start",{index:Y,content_block:{...B,input:{}}}),p("content_block_delta",{index:Y,delta:{type:"input_json_delta",partial_json:JSON.stringify(B.input??{})}}),p("content_block_stop",{index:Y})});let G=ie.size>0||M.length>0,de=Pt(z);Ee(o,z),p("message_delta",{delta:{stop_reason:G?"tool_use":"end_turn"},usage:de?{input_tokens:de.input_tokens,output_tokens:de.output_tokens}:{output_tokens:P}}),p("message_stop",{}),n.end();return}let k="",E="",S=[],_=new me;for await(let b of r.track(g,l,o)){S.push(b),b.type==="response.output_text.delta"&&typeof b.delta=="string"&&(k+=b.delta),b.type==="response.reasoning_text.delta"&&typeof b.delta=="string"&&(E+=b.delta);let P=Ce(b);if(P&&_.add(P),b.type==="error"){let v=b.error,I=v?.type==="invalid_request_error";ue(n,I?400:502,I?"invalid_request_error":"api_error",v?.message??JSON.stringify(b));return}if(n.destroyed)break}if(n.destroyed)return;let h=ae(S);Ee(o,h);let y;try{y=an(h),y.length===0&&_.size>0&&(y=an({output:_.items()}))}catch(b){ue(n,502,"api_error",String(b instanceof Error?b.message:b));return}let x=ke(c,y.length,k);if(x){ue(n,502,"api_error",be(l,x));return}let f=[],m=E||Yr(h);m&&f.push({type:"thinking",thinking:m}),(k||y.length===0)&&f.push({type:"text",text:k}),f.push(...y),X(n,200,{id:a,type:"message",role:"assistant",content:f,model:s,stop_reason:y.length>0?"tool_use":"end_turn",usage:Pt(h)??{input_tokens:0,output_tokens:0}})}function Rs(t){Re(process.stdout,t)}function Ss(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,i=typeof e=="function"?e:()=>e,s=t.requestLog??Rs,a=t.observe,d=new we;return(u,l)=>{let c=new URL(u.url??"/","http://localhost"),g=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),p=(h,y,x,f,m)=>g?ue(l,h,f,y):K(l,h,y,x,m),k=Dt(c.pathname),E=c.pathname.startsWith("/partners/"),S=k||E?{id:je(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,sessionId:null,timing:null}:null;S&&(l.setHeader(Nn,S.id),l.once("close",()=>{let h=Fn({turn:S,method:u.method??"",path:c.pathname,res:l});s(qn(h)),a?.(h),Hr({record:h,ledger:t.ledger??null,req:u})}));let _=()=>Un(c.pathname,S);(async()=>{if(u.method==="GET"&&c.pathname==="/healthz"){X(l,200,{ok:!0});return}if(u.method==="GET"&&c.pathname==="/stats"){X(l,200,r?{identity:r,...d.snapshot()}:d.snapshot());return}if(n&&(u.headers.authorization??"")!==`Bearer ${n}`){p(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=c.pathname===$r?"canonical":c.pathname===nn?"huggingface":null;if(h){if(u.method!=="POST"){p(405,`${c.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let m=t.usage;if(!m){p(501,`${c.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let b=m.authorize(u),P;try{P=await Jr(u,Mr)}catch(C){if(C instanceof nt){p(413,C.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let v=C=>m.lookup(b,C),I;try{if(h==="canonical"){let C=Lr(P),D=await v(C);Ot(D,C),I={requests:D}}else I=await Nr(P,v)}catch(C){if(C instanceof he){p(C.status,C.message,"invalid_request_error","invalid_request_error");return}throw C}X(l,200,I);return}if(u.method==="GET"&&c.pathname===Fe){let m=await i(u);if(S&&(S.org=m.tenant??null),!m.openRouterModels){p(501,`GET ${Fe} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}X(l,200,await m.openRouterModels());return}if(c.pathname.startsWith("/partners/")){p(404,`no partner adapter for ${u.method} ${c.pathname} \u2014 the partner surface currently carries ${nn} and GET ${Fe}`,"invalid_request_error","not_found_error");return}let y=await i(u);if(S&&(S.org=y.tenant??null),u.method==="GET"&&c.pathname==="/v1/models"){if(c.searchParams.get("format")==="openrouter"){l.writeHead(308,{location:Fe}),l.end();return}X(l,200,await y.listModels());return}if(u.method==="GET"&&c.pathname===rr){if(!y.listImageModels){p(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}X(l,200,await y.listImageModels());return}if(nr(c.pathname)){if(!y.supportsImages){p(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${c.pathname}`,"not_implemented","not_implemented_error");return}let m={clients:y,imageModels:y.supportsImages,stats:d,turn:_()};c.pathname===St?await fr(u,l,m):await pr(u,l,m);return}if(u.method==="GET"&&c.pathname===Ir){if(!y.listSpeechToTextModels){p(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}X(l,200,await y.listSpeechToTextModels());return}if(Er(c.pathname)){if(!y.supportsTranscription){p(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${It}`,"not_implemented","not_implemented_error");return}let m={clients:y,transcriptionModels:y.supportsTranscription,stats:d,turn:_()};await Pr(u,l,m);return}if(kr(c.pathname)){if(!y.supportsSpeech){p(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Ye}`,"not_implemented","not_implemented_error");return}let m={clients:y,speechModels:y.supportsSpeech,stats:d,turn:_()};await Ar(u,l,m);return}if(u.method!=="POST"){p(404,`no route for ${u.method} ${c.pathname}`,"invalid_request_error","not_found_error");return}let x;try{x=await Jr(u)}catch(m){if(m instanceof nt){p(413,m.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let f=Buffer.byteLength(JSON.stringify(x));if(c.pathname==="/v1/responses"){d.request("responses",f,f),await fs(x,y,Ve(y),l,d,_());return}if(c.pathname==="/v1/chat/completions"){d.request("chat_completions",f,f),await ms(x,y,l,d,_(),u.headers[on]);return}if(c.pathname==="/v1/systemone"){d.request("systemone",f,f),await hs(x,y,l,d,_());return}if(c.pathname==="/v1/messages"){d.request("messages",f,f),await ks(x,y,l,d,_());return}if(c.pathname==="/v1/messages/count_tokens"){d.request("count_tokens",f,f),ue(l,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}p(404,`no route for POST ${c.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let y=String(h instanceof Error?h.message:h);if(!l.headersSent){let x=o?.(h)??null;if(x){p(x.status,y,x.openaiType,x.anthropicType);return}if(h instanceof Mt.SessionAllocationError){let f=gt(h.code);if(f){let m=h.retryAfterSeconds??(f.status===429?30:void 0);m!==void 0&&l.setHeader("Retry-After",String(m)),p(f.status,Vt(f,h.code??void 0),f.openaiType,f.anthropicType,f.code);return}}if(h instanceof Mt.SessionFailedError){let f=ht(h);if(f){let m=f.status===429?30:void 0;m!==void 0&&l.setHeader("Retry-After",String(m)),p(f.status,Vt(f,h.status.sessionId?`session ${h.status.sessionId}`:void 0),f.openaiType,f.anthropicType,f.code);return}}if(h instanceof Ue){p(502,y,"upstream_error","api_error");return}p(500,y,"proxy_error","api_error","proxy_error");return}S&&(S.streamError=!0),l.destroyed||(g?l.write(`event: error
53
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:y}})}
52
+ `)};if(t.stream===!0){let v=r.track(y,l,o);cn(n),p("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:s,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let P=0,b="",I=0,C="none",D=()=>C,W=-1,Q=-1,ie=new me,pe=[],H=()=>{C!=="none"&&(C="none",p("content_block_stop",{index:W}))},V=(F,Y)=>{H(),C=F,W=I++,p("content_block_start",{index:W,content_block:Y})};for await(let F of v){if(n.destroyed)break;pe.push(F);let Y=Ce(F);if(F.type==="response.reasoning_text.delta"&&typeof F.delta=="string")D()!=="thinking"&&V("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:W,delta:{type:"thinking_delta",thinking:F.delta}});else if(F.type==="response.output_text.delta"&&typeof F.delta=="string")D()!=="text"&&V("text",{type:"text",text:""}),P+=1,b+=F.delta,p("content_block_delta",{index:W,delta:{type:"text_delta",text:F.delta}});else if(Y){let{call:fe}=ie.add(Y);(D()!=="tool"||Y.tool_index!==Q)&&(Q=Y.tool_index,V("tool",{type:"tool_use",id:fe.id??`call_${Y.tool_index}`,name:fe.name??"",input:{}})),Y.delta&&p("content_block_delta",{index:W,delta:{type:"input_json_delta",partial_json:Y.delta}})}else if(F.type==="error"){o.streamError=!0,p("error",{error:{type:"api_error",message:JSON.stringify(F)}}),n.end();return}}if(n.destroyed)return;let z=ae(pe),ye=Pe(z),O=ke(c,ie.size+ye.length,b);if(O){o.streamError=!0,p("error",{error:{type:"api_error",message:be(l,O)}}),n.end();return}H();let L=[];if(ie.size===0)try{L=ln(z)}catch(F){o.streamError=!0,p("error",{error:{type:"api_error",message:String(F instanceof Error?F.message:F)}}),n.end();return}I===0&&L.length===0&&(V("text",{type:"text",text:""}),H()),L.forEach(F=>{let Y=I++;p("content_block_start",{index:Y,content_block:{...F,input:{}}}),p("content_block_delta",{index:Y,delta:{type:"input_json_delta",partial_json:JSON.stringify(F.input??{})}}),p("content_block_stop",{index:Y})});let J=ie.size>0||L.length>0,de=$t(z);Ae(o,z),p("message_delta",{delta:{stop_reason:J?"tool_use":"end_turn"},usage:de?{input_tokens:de.input_tokens,output_tokens:de.output_tokens}:{output_tokens:P}}),p("message_stop",{}),n.end();return}let k="",E="",S=[],f=new me;for await(let v of r.track(y,l,o)){S.push(v),v.type==="response.output_text.delta"&&typeof v.delta=="string"&&(k+=v.delta),v.type==="response.reasoning_text.delta"&&typeof v.delta=="string"&&(E+=v.delta);let P=Ce(v);if(P&&f.add(P),v.type==="error"){let b=v.error,I=b?.type==="invalid_request_error";ue(n,I?400:502,I?"invalid_request_error":"api_error",b?.message??JSON.stringify(v));return}if(n.destroyed)break}if(n.destroyed)return;let h=ae(S);Ae(o,h);let g;try{g=ln(h),g.length===0&&f.size>0&&(g=ln({output:f.items()}))}catch(v){ue(n,502,"api_error",String(v instanceof Error?v.message:v));return}let A=ke(c,g.length,k);if(A){ue(n,502,"api_error",be(l,A));return}let _=[],m=E||Zr(h);m&&_.push({type:"thinking",thinking:m}),(k||g.length===0)&&_.push({type:"text",text:k}),_.push(...g),X(n,200,{id:a,type:"message",role:"assistant",content:_,model:s,stop_reason:g.length>0?"tool_use":"end_turn",usage:$t(h)??{input_tokens:0,output_tokens:0}})}function As(t){Se(process.stdout,t)}function Is(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,i=typeof e=="function"?e:()=>e,s=t.requestLog??As,a=t.observe,d=new we;return(u,l)=>{let c=new URL(u.url??"/","http://localhost"),y=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),p=(h,g,A,_,m)=>y?ue(l,h,_,g):G(l,h,g,A,m),k=qt(c.pathname),E=c.pathname.startsWith("/partners/"),S=k||E?{id:je(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,sessionId:null,timing:null}:null;S&&(l.setHeader(Fn,S.id),l.once("close",()=>{let h=Hn({turn:S,method:u.method??"",path:c.pathname,res:l});s(Vn(h)),a?.(h),Jr({record:h,ledger:t.ledger??null,req:u})}));let f=()=>Bn(c.pathname,S);(async()=>{if(u.method==="GET"&&c.pathname==="/healthz"){X(l,200,{ok:!0});return}if(u.method==="GET"&&c.pathname==="/stats"){X(l,200,r?{identity:r,...d.snapshot()}:d.snapshot());return}if(n&&(u.headers.authorization??"")!==`Bearer ${n}`){p(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=c.pathname===Nr?"canonical":c.pathname===sn?"huggingface":null;if(h){if(u.method!=="POST"){p(405,`${c.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let m=t.usage;if(!m){p(501,`${c.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let v=m.authorize(u),P;try{P=await zr(u,Ur)}catch(C){if(C instanceof ot){p(413,C.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let b=C=>m.lookup(v,C),I;try{if(h==="canonical"){let C=Dr(P),D=await b(C);Ct(D,C),I={requests:D}}else I=await Fr(P,b)}catch(C){if(C instanceof ge){p(C.status,C.message,"invalid_request_error","invalid_request_error");return}throw C}X(l,200,I);return}if(u.method==="GET"&&c.pathname===Be){let m=await i(u);if(S&&(S.org=m.tenant??null),!m.openRouterModels){p(501,`GET ${Be} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}X(l,200,await m.openRouterModels());return}if(c.pathname.startsWith("/partners/")){p(404,`no partner adapter for ${u.method} ${c.pathname} \u2014 the partner surface currently carries ${sn} and GET ${Be}`,"invalid_request_error","not_found_error");return}let g=await i(u);if(S&&(S.org=g.tenant??null),u.method==="GET"&&c.pathname==="/v1/models"){if(c.searchParams.get("format")==="openrouter"){l.writeHead(308,{location:Be}),l.end();return}X(l,200,await g.listModels());return}if(u.method==="GET"&&c.pathname===sr){if(!g.listImageModels){p(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}X(l,200,await g.listImageModels());return}if(ir(c.pathname)){if(!g.supportsImages){p(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${c.pathname}`,"not_implemented","not_implemented_error");return}let m={clients:g,imageModels:g.supportsImages,stats:d,turn:f()};c.pathname===At?await gr(u,l,m):await hr(u,l,m);return}if(u.method==="GET"&&c.pathname===Pr){if(!g.listSpeechToTextModels){p(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}X(l,200,await g.listSpeechToTextModels());return}if(Tr(c.pathname)){if(!g.supportsTranscription){p(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Pt}`,"not_implemented","not_implemented_error");return}let m={clients:g,transcriptionModels:g.supportsTranscription,stats:d,turn:f()};await $r(u,l,m);return}if(Rr(c.pathname)){if(!g.supportsSpeech){p(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Xe}`,"not_implemented","not_implemented_error");return}let m={clients:g,speechModels:g.supportsSpeech,stats:d,turn:f()};await Or(u,l,m);return}if(u.method!=="POST"){p(404,`no route for ${u.method} ${c.pathname}`,"invalid_request_error","not_found_error");return}let A;try{A=await zr(u)}catch(m){if(m instanceof ot){p(413,m.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let _=Buffer.byteLength(JSON.stringify(A));if(c.pathname==="/v1/responses"){d.request("responses",_,_),await ys(A,g,Ve(g),l,d,f());return}if(c.pathname==="/v1/chat/completions"){d.request("chat_completions",_,_),await _s(A,g,l,d,f(),u.headers[un]);return}if(c.pathname==="/v1/systemone"){d.request("systemone",_,_),await vs(A,g,l,d,f());return}if(c.pathname==="/v1/messages"){d.request("messages",_,_),await Es(A,g,l,d,f());return}if(c.pathname==="/v1/messages/count_tokens"){d.request("count_tokens",_,_),ue(l,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}p(404,`no route for POST ${c.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let g=String(h instanceof Error?h.message:h);if(!l.headersSent){let _=o?.(h)??null;if(_){p(_.status,g,_.openaiType,_.anthropicType);return}if(h instanceof Ut.SessionAllocationError){let m=yt(h.code);if(m){let v=h.retryAfterSeconds??(m.status===429?30:void 0);v!==void 0&&l.setHeader("Retry-After",String(v)),p(m.status,Wt(m,h.code??void 0),m.openaiType,m.anthropicType,m.code);return}}if(h instanceof Ut.SessionFailedError){let m=_t(h);if(m){let v=m.status===429?30:void 0;v!==void 0&&l.setHeader("Retry-After",String(v)),p(m.status,Wt(m,h.status.sessionId?`session ${h.status.sessionId}`:void 0),m.openaiType,m.anthropicType,m.code);return}}if(h instanceof Ue){p(502,g,"upstream_error","api_error");return}if(h instanceof Qe){h.retryable&&l.setHeader("Retry-After","1"),p(502,g,"upstream_error","api_error",h.code);return}if(h instanceof xt){l.setHeader("Retry-After",String(h.retryAfterSeconds)),p(h.status,g,h.status===429?"capacity_error":"upstream_error",h.status===429?"rate_limit_error":"overloaded_error",h.code);return}p(500,g,"proxy_error","api_error","proxy_error");return}S&&(S.streamError=!0);let A=h instanceof Qe?h.code:null;l.destroyed||(y?l.write(`event: error
53
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:g}})}
54
54
 
55
- `):l.write(`data: ${JSON.stringify({error:{message:y,type:"upstream_error"}})}
55
+ `):l.write(`data: ${JSON.stringify({error:{message:g,type:"upstream_error",code:A}})}
56
56
 
57
- `)),l.end()})}}function Xr(t){let{clients:e,apiKey:n}=t,r=(0,Kr.createServer)(Ss(t)),o=Jn(r,{clients:e,apiKey:n,statusOf:t.statusOf}),i=Ke(r,{resolver:bt(e,n)}),s=r.close.bind(r);return r.close=(a=>(o.close(),i(),s(a))),ft(r,{clients:e,apiKey:n}),r}0&&(module.exports={GEMINI_LIVE_PATH,OPENAI_REALTIME_PATH,OpenAIRealtimeConnection,ResumptionRegistry,SessionGoneError,UnknownModelError,VIDEO_OUT_SETUP_KEY,attachGeminiLive,attachOpenAIRealtime,createOpenAIProxy,fixedClientsResolver,realtimeBindingFor,realtimeModelOf,serveGeminiLiveSocket});
57
+ `)),l.end()})}}function eo(t){let{clients:e,apiKey:n}=t,r=(0,Xr.createServer)(Is(t)),o=zn(r,{clients:e,apiKey:n,statusOf:t.statusOf}),i=Ke(r,{resolver:St(e,n)}),s=r.close.bind(r);return r.close=(a=>(o.close(),i(),s(a))),ht(r,{clients:e,apiKey:n}),r}0&&(module.exports={GEMINI_LIVE_PATH,OPENAI_REALTIME_PATH,OpenAIRealtimeConnection,ResumptionRegistry,SessionGoneError,UnknownModelError,VIDEO_OUT_SETUP_KEY,attachGeminiLive,attachOpenAIRealtime,createOpenAIProxy,fixedClientsResolver,realtimeBindingFor,realtimeModelOf,serveGeminiLiveSocket});