@urun-sh/openai 0.6.0 → 0.6.2

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,63 +1,63 @@
1
- "use strict";var vi=Object.create;var Ot=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var ki=Object.getOwnPropertyNames;var Si=Object.getPrototypeOf,Ri=Object.prototype.hasOwnProperty;var xi=(t,e)=>{for(var n in e)Ot(t,n,{get:e[n],enumerable:!0})},qr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ki(e))!Ri.call(t,o)&&o!==n&&Ot(t,o,{get:()=>e[o],enumerable:!(r=bi(e,o))||r.enumerable});return t};var tt=(t,e,n)=>(n=t!=null?vi(Si(t)):{},qr(e||!t||!t.__esModule?Ot(n,"default",{value:t,enumerable:!0}):n,t)),Ei=t=>qr(Ot({},"__esModule",{value:!0}),t);var Kd={};xi(Kd,{ANONYMOUS_KEY_ID:()=>gn,BIND_HOST:()=>ci,BUCKET_DOMAIN:()=>gr,BoundedLabel:()=>Ge,ControlPlaneUnavailableError:()=>ve,ConversationBackhauls:()=>Ye,ConversationCapacityError:()=>ze,DEFAULT_PORT:()=>Or,EDGE_IDENTITY_PORT:()=>Zs,EDGE_KEY_FINGERPRINT_HEADER:()=>mr,EDGE_KEY_ID_HEADER:()=>fr,InferenceMetrics:()=>Ve,LEDGER_FUNCTION_PATH:()=>Lr,LEDGER_WRITE_TIMEOUT_MS:()=>Nr,LedgerClient:()=>Ze,LedgerDuplicateError:()=>Qe,LedgerSurfaceError:()=>W,MAX_CACHED_KEYS:()=>br,MAX_CONVERSATIONS:()=>kn,MAX_CONVERSATION_HANDLES:()=>Tr,MAX_MODEL_LABELS:()=>ur,MAX_ORG_LABELS:()=>dr,MAX_TENANTS:()=>Ir,METRICS_PATH:()=>fn,METRICS_PORT:()=>Xs,NO_MODEL_LABEL:()=>ar,ORG_BINDING_TTL_MS:()=>vr,OTHER_LABEL:()=>je,OrgResolver:()=>We,ProxyAuthError:()=>Z,READINESS_TIMEOUT_MS:()=>Fr,READINESS_TTL_MS:()=>Dr,SERVE_FUNCTION:()=>Je,TIER_DOMAIN:()=>hr,TenantRegistry:()=>Ke,bearerFrom:()=>Ce,bearerTokenOf:()=>wr,createEdgeIdentityServer:()=>hn,createHostedProxy:()=>wi,createMetricsServer:()=>mn,edgeBucketId:()=>yr,edgeTierFingerprint:()=>_r,laneOf:()=>lr,parseLedgerRecorded:()=>Ur,resolveHostedConfig:()=>pi,statusClassOf:()=>cr,tenantSubject:()=>Xe});module.exports=Ei(Kd);var _i=require("http");var Gr="audio",xn=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(e,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let s=0;s<r;s++)o[s]=n.readInt16LE(s*2);this.source.onData(o)}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function Vr(t,e,n=1e4){let r=new xn(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Gr).attach(o);let s=await Ai(t,n);return await r.startInbound(s),r}function Ai(t,e){let n=t.stream(Gr);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=u=>{u!=null&&(clearTimeout(i),s?.(),r(u))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var Hr="rt-video-in",jr=256e3;function Wr(t){let e=t.stream(Hr),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${Hr}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async r=>{if(r.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(r.byteLength>jr)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${jr}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var Oi=24e3,nt=480,Ii=111;async function Ti(){let t=await import("opusscript"),e=t.default??t;return new e(Oi,1,2048)}async function Jr(){let t=await import("werift"),e=await Ti();return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let u=new Int16Array(i.length+a.length);u.set(i,0),u.set(a,i.length);let d=0;for(;u.length-d>=nt;){let c=u.subarray(d,d+nt);d+=nt;let l=Buffer.from(c.buffer,c.byteOffset,c.byteLength),p=e.encode(l,nt);o=o+1&65535,s=s+nt>>>0;let f=new t.RtpHeader({version:2,payloadType:Ii,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),_=new t.RtpPacket(f,p);n.writeRtp(_)}i=u.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let u=0;u<a.length;u++)a[u]=i.readInt16LE(u*2);r.onframe?.({samples:a})}),r}}}var It=require("@urun-sh/core"),En="rt-video-out";var Pi="h264";function Ci(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function $i(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;Ci(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var Kr="urun.videoOut.v2-ws";function zr(t){let e=t.stream(En);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${En}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=u=>{for(let d of r)d(u)},i=!1,a=async()=>{for await(let u of e.messages()){if(!(u instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${En}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=$i(u)}catch(c){s(c instanceof Error?c:new Error(String(c)));continue}for(let c of n)c(d)}for(let u of o)u()};return{codec:Pi,onOutputFrame:u=>(n.add(u),i||(i=!0,a().catch(d=>s(d instanceof Error?d:new Error(String(d))))),()=>n.delete(u)),onLaneError:u=>(r.add(u),()=>r.delete(u)),onEnd:u=>(o.add(u),()=>o.delete(u))}}var $t="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Li=1007,Xr=1008,ce=1011,Lt=1008,k=class extends Error{constructor(n,r=Li){super(n);this.closeCode=r}closeCode},F=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Tt=["setup","clientContent","realtimeInput","toolResponse"];function Qr(t){let e;try{e=JSON.parse(t)}catch{throw new k("client message is not valid JSON")}let n=F(e);if(!n)throw new k("client message must be a JSON object");let r=Tt.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Tt.includes(a));if(o.length>0)throw new k(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Tt.join(", ")}`);if(r.length!==1)throw new k(`client message must contain exactly one of ${Tt.join(", ")} (got ${r.length})`);let s=r[0],i=F(n[s]);if(!i)throw new k(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Zr(t,e){if(typeof t=="string")return t;let n=F(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new k(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=F(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new k(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new k(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new k(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
2
- `)}var Ni={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Se="urun.videoOut";function eo(t){return{framing:Kr,codec:t}}function to(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Se]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Ui={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Mi=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Se],Yr=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Di(t){let e=F(t);if(!e)throw new k("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new k(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=F(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new k("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new k(`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 k("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(!Yr.includes(e.activityHandling))throw new k(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Yr.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Fi=["temperature","maxOutputTokens","responseModalities"];function no(t){for(let[l,p]of Object.entries(Ui))if(t[l]!==void 0)throw new k(p);for(let l of Object.keys(t))if(!Mi.includes(l))throw new k(`unsupported setup field "${l}"`);if(typeof t.model!="string"||t.model.length===0)throw new k('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=F(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new k("setup.generationConfig must be an object");if(s){for(let l of Object.keys(s))if(!Fi.includes(l))throw new k(`unsupported generationConfig field "${l}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new k("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new k("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let l=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of l){let f=String(p).toUpperCase();if(f==="AUDIO"){o=!0;continue}if(f!=="TEXT")throw new k(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:Zr(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new k("setup.tools must be an array");a=[];for(let l of t.tools){let p=F(l);if(!p)throw new k("setup.tools entries must be objects");for(let f of Object.keys(p))if(f!=="functionDeclarations")throw new k(`unsupported tool "${f}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new k("tool.functionDeclarations must be an array");for(let f of p.functionDeclarations){let _=F(f);if(!_||typeof _.name!="string")throw new k("functionDeclarations entries require a string name");a.push({type:"function",name:_.name,description:_.description,parameters:_.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let l=F(t.sessionResumption);if(!l)throw new k("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(l))if(p!=="handle")throw new k(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(l.handle!==void 0&&(typeof l.handle!="string"||l.handle.length===0))throw new k("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof l.handle=="string"?l.handle:null}}let d=t.realtimeInputConfig===void 0?Ni:Di(t.realtimeInputConfig),c=!1;if(t[Se]!==void 0){if(!F(t[Se]))throw new k(`setup["${Se}"] must be an object (the v1 opt-in is {})`);c=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:d,sessionResumption:u,videoOut:c}}function ro(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function oo(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function so(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new k(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new k("clientContent.turns must be an array");let n=[];for(let r of e){let o=F(r);if(!o)throw new k("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new k(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Zr(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Pt=16e3,io=24e3,Bi=`audio/pcm;rate=${io}`,ao=Buffer.alloc(960).toString("base64");function qi(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let u=a*s,d=Math.floor(u);if(d>=i){o[a]=t[i];continue}let c=u-d;o[a]=Math.round(t[d]+(t[d+1]-t[d])*c)}return o}function Hi(t){let e=F(t);if(!e)throw new k("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new k(`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 k("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 k("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function ji(t){let e=F(t);if(!e)throw new k("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new k(`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])!==Pt)throw new k(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Pt} Hz (audio/pcm;rate=${Pt})`);if(typeof e.data!="string"||e.data.length===0)throw new k("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 k(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=qi(o,Pt,io);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function uo(t){if(t.mediaChunks!==void 0)throw new k('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 k("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=F(t[o]);if(!s||Object.keys(s).length!==0)throw new k(`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 k(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new k(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:ji(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Hi(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new k("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new k("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function lo(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new k(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new k("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=F(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new k("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 co(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function po(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Bi,data:t}}]}}}}function fo(t){let e=F(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let d of n){let c=F(d);if(!(c?.type!=="message"||!Array.isArray(c.content)))for(let l of c.content){let p=F(l);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let d of n){let c=F(d);if(c?.type!=="function_call")continue;if(typeof c.call_id!="string"||typeof c.name!="string")throw new k(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,ce);let l=typeof c.arguments=="string"&&c.arguments.length>0?c.arguments:"{}",p;try{p=JSON.parse(l)}catch{throw new k(`upstream function_call arguments are not valid JSON: ${l}`,ce)}r.push({id:c.call_id,name:c.name,args:p}),o.push({type:"function_call",call_id:c.call_id,name:c.name,arguments:l})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=F(e.usage),u={serverContent:{turnComplete:!0}};if(a){let d={};typeof a.input_tokens=="number"&&(d.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(d.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(d.totalTokenCount=a.total_tokens),Object.keys(d).length>0&&(u.usageMetadata=d)}return i.push(u),{messages:i,assistantItems:o}}var Mo=require("crypto"),Do=require("ws");var j=class extends Error{},Gi=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Vi(t){if(typeof t!="string")return!1;let e=Gi.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let u=new Date(Date.UTC(n,r-1,o,s,i,a));return u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===o&&u.getUTCHours()===s&&u.getUTCMinutes()===i&&u.getUTCSeconds()===a}function Wi(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new j(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new j(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new j(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,u)=>{if(a===null||typeof a!="object")throw new j(`catalog shared endpoints[${u}] is not an object: ${JSON.stringify(a)}`);let d=a;for(let l of["model_id","variant","app_slug","function"])if(typeof d[l]!="string"||d[l].length===0)throw new j(`catalog shared endpoints[${u}] (${JSON.stringify(d)}) has no valid "${l}"`);let c=(l,p)=>{if(d[l]!==void 0&&d[l]!==null&&!p)throw new j(`catalog shared endpoints[${u}] (${d.model_id}:${d.variant}) carries a malformed "${l}": ${JSON.stringify(d[l])}`)};c("ready",typeof d.ready=="boolean"),c("ready_runtimes",typeof d.ready_runtimes=="number"&&Number.isInteger(d.ready_runtimes)&&d.ready_runtimes>=0),c("ready_since",Vi(d.ready_since));for(let l of["model_id","variant"]){let p=d[l];if(p.includes(":"))throw new j(`catalog shared endpoints[${u}] has "${l}" containing ":" (${JSON.stringify(p)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return c("output_free",typeof d.output_free=="boolean"),d});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new j(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new j(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let u of Object.keys(a))if(u!=="zdr"&&u!=="hipaa")throw new j(`catalog "shared" block compliance carries "${u}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function rt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function mo(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(d=>d.model_id===o);if(a.length===0)return null;if(s!==void 0){let d=a.find(c=>c.variant===s);return d?{shared_org_id:t.shared_org_id,endpoint:d}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let u=a.filter(d=>d.compat_default===!0);if(u.length!==1)throw new j(`shared model "${o}" has ${u.length} compat_default rows (exactly one required) among variants ${a.map(d=>d.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:u[0]}}async function go(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new j(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Wi(await r.json())}function pe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var ne=class extends Error{name="ModelPriceError"},An="per_million_input_tokens",On="per_million_output_tokens",yo="model_id,variant,unit,price_usd,effective_at,expires_at",ho={per_request:!0,per_minute:!0,per_output_unit:!0},Ji=5e3;function Ki(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ne(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function _o(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ne(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function zi(t,e,n){return t===null?null:_o(t,e,n)}function Yi(t,e){if(t===An)return"input";if(t===On)return"output";if(typeof t=="string"&&Object.hasOwn(ho,t))return null;throw new ne(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${An} | ${On}) nor a known GPU-time unit (${Object.keys(ho).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function Xi(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:n}}function In(t,e){return`${t}\0${e}`}function Qi(t){if(!Array.isArray(t))throw new ne(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new ne(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let d of yo.split(","))if(!Object.hasOwn(s,d))throw new ne(`${o} has no "${d}" column: ${JSON.stringify(s)}`);let i=Yi(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new ne(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new ne(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:Ki(s.price_usd,o),effective_at:_o(s.effective_at,o,"effective_at"),expires_at:zi(s.expires_at,o,"expires_at")})}return e}function wo(t,e=Date.now(),n){let r=new Map,o=new Map;for(let u of t){if(u.effective_at>e||u.expires_at!==null&&u.expires_at<=e)continue;let d=r.get(u.model_id);d||(d=new Map,r.set(u.model_id,d),o.set(u.model_id,new Map));let c=u.variant??"",l=d.get(c);l||(l={input:[],output:[]},d.set(c,l),o.get(u.model_id).set(c,u.variant)),l[u.side].push({effective_at:u.effective_at,usd:u.usd})}let s=[],i=[];for(let[u,d]of r){let c=d.get(""),l=(p,f,_)=>{let S=p&&p.length>0?p:c?.[f];if(!S||S.length===0)return null;let h=Xi(S,f);return"reason"in h?h:h.rate.usd===0?f==="output"&&_!==null&&n?.has(In(u,_))?h.rate:{reason:`the ${f} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:h.rate};for(let[p,f]of o.get(u)){let _=d.get(p),S=l(_?.input,"input",f),h=l(_?.output,"output",f);if(S!==null&&"reason"in S){i.push({model_id:u,variant:f,reason:S.reason});continue}if(h!==null&&"reason"in h){i.push({model_id:u,variant:f,reason:h.reason});continue}S===null||h===null||s.push({model_id:u,variant:f,pricing:{input:S.usd,output:h.usd}})}}let a=(u,d)=>u.model_id.localeCompare(d.model_id)||(u.variant===null?1:0)-(d.variant===null?1:0)||(u.variant??"").localeCompare(d.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function ot(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var Nt={prices:[],refusals:[]};async function vo(t){let e=t.fetchImpl??fetch,n=`${An},${On}`,r=await e(`${t.catalogUrl}/model_prices?select=${yo}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Ji)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Qi(await r.json())}var Zi={chat:!0,code:!0,agent:!0,vl:!0},bo={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function ea(t){let e=t.toLowerCase();return Object.hasOwn(bo,e)?bo[e]:null}var ko={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function ta(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(ko,o)?ko[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var So={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Ro={2:"Llama2",3:"Llama3"};function na(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(So,s))return So[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Ro,i))return Ro[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var ra=["context_length","max_model_len"];function oa(t){let e=ra.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function Mt(t){let e=t.map(oa),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function sa(t,e){let n=e.filter(o=>pe(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return Ut(n);let r=e.filter(o=>pe(o.model_id)===t);return r.length>0?Ut(r):null}function Ut(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:ia(t),matches:t}:null}function ia(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}function Ao(t){let e=t.updated_at?Date.parse(t.updated_at):NaN;return Number.isFinite(e)?Math.floor(e/1e3):0}function Tn(t,e,n){let r=sa(t,e);if(!r)return{id:t,object:"model",created:0,owned_by:"urun"};let{row:o,matches:s}=r,i=Mt(s),a=ot(o.model_id,o.variant,n),u=Oo(o,s);return{id:t,object:"model",created:Ao(o),owned_by:"urun",name:`${o.model_id}:${o.variant}`,...o.description?{description:o.description}:{},...o.task?{task:o.task}:{},...o.engine?{engine:o.engine}:{},...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...u.published.length>0?{voices:[...u.published]}:{}}}var aa=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Oo(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...aa],defect:o}:{published:[],defect:o}}function Pn(t){let e=t.length>0?Ut(t):null;return e===null?{published:[],defect:null}:Oo(e.row,e.matches)}function xo(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Eo(t){return{input:[{type:"prompt",unit:"token",cost_usd:xo(t.input)}],output:[{type:"completion",unit:"token",cost_usd:xo(t.output)}]}}function ua(t,e,n,r){if(e.length===0)return null;let o=Ut(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Zi[s.task]!==!0)return null;let a=Mt(i),u=ot(s.model_id,s.variant,n),d=na(s.hf_repo),c={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(c.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Ao(s),quantization:ea(s.variant),...d!==null?{tokenizer:d}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&u!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...u?{pricing:Eo(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:c,...u?{pricing:Eo(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Io(t,e,n,r){let o=r??(d=>console.warn(d.trimEnd())),s=t?rt(t):[];if(s.length>0){let d=s.filter(c=>c.ready===void 0);if(d.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(d.length>0){let c=d.map(l=>`${l.model_id}:${l.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${c} carry no ready field and are declared not ready`)}}let i={datacenters:ta(t?.regions,o),compliance:t?.compliance??null},a=[],u=new Set;for(let d of s){let c=`${d.model_id}:${d.variant}`;if(u.has(c))continue;u.add(c);let l=ua(d,e.filter(p=>p.model_id===d.model_id&&p.variant===d.variant),n,i);l&&a.push(l)}return{data:a}}var N=class extends Error{},K=class extends Error{},Cn="urs1.";function To(t,e){return Cn+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function da(t){if(!t.startsWith(Cn))return null;try{let e=JSON.parse(Buffer.from(t.slice(Cn.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function No(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Po(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=ca(t);return e===null?[]:[e]}function Co(t,e,n,r,o){if(!o)throw new j(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new j(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new j(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function $o(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new j(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var Uo="shared:",Re="speech:";function it(t){return t.sharedApp?Uo+t.appSlug:t.appSlug}function at(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function st(t,e){let n=e.filter(s=>pe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>pe(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function la(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function ca(t){let e=t.map(la),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Lo={stt:"stt",tts:"tts"};function Dt(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||Lo[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?Lo[e]:null}var Ft=6e4,Bt=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;rowsCache=null;seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??Ft;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}async sharedBlock(){if(!this.opts.shared)return null;let e=this.opts.appsTtlMs??Ft;if(this.sharedCache&&Date.now()-this.sharedCache.at<e)return this.sharedCache.block;let n=await this.opts.shared();return this.sharedCache={at:Date.now(),block:n},n}sharedCache=null;async catalogRows(){if(!this.opts.listCatalog)return[];let e=this.opts.appsTtlMs??Ft;if(this.rowsCache&&Date.now()-this.rowsCache.at<e)return this.rowsCache.rows;let n=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:n},n}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Ft;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof ne)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
3
- `),Nt}let r=wo(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
4
- `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(In(r.model_id,r.variant));return n}warn(e){(this.opts.warn??(r=>console.warn(r.trimEnd())))(e)}servable(e){return e.filter(n=>n.serves==="openai"&&n.deployment_status==="active").map(n=>n.app_slug)}async availableIds(){let e=this.opts.defaultApp,n=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let o of this.servable(await this.deployedApps()))n.add(o);for(let o of this.pool.keys())o.startsWith(Uo)||o.startsWith(Re)||n.add(o);let r=[...n].filter(o=>o!==e).sort();return e===null?r:[e,...r]}async noDefaultApp(e){let n=await this.availableIds(),r=n.length>0?n.join(", "):"(none deployed)";throw new N(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${r}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${r}`)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};let o=pe(n);if(o===r)return{appSlug:r};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let s=await this.deployedApps(),i=this.servable(s);if(i.includes(o))return{appSlug:o};let a=i.filter(d=>d.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new N(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=s.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new N(`model "${n}" maps to app "${u.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.shared){let s=await this.sharedBlock();if(s){let i=mo(s,n);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant,sharedOrgId:s.shared_org_id}}}if(this.opts.listCatalog){let i=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===pe(a.model_id)||o===pe(`${a.model_id}-${a.variant}`));if(i)throw new N(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${i.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=at(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async targetFor(e){return this.resolveTarget(e)}async resolveApp(e){return it(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,it(n))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Re+it(n))}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:at(e)}}keyOf(e){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=n(e);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(e){let{app:n,entry:r}=await this.sessionFor(e);return{app:n,handle:To(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:To(n,this.keyOf(r))}}async sessionForHandle(e){let n=da(e);if(!n)throw new K(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,s=this.pool.get(r),i=s?await s.then(a=>a,()=>null):null;if(i===null)throw new K(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==o)throw new K(`the session behind this handle (app "${r}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:r,entry:i}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(s=>s,()=>null)!==n||this.pool.get(e)!==r||(this.pool.delete(e),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),n=await this.sharedBlock(),[r,o]=await Promise.all([this.catalogRows().then(d=>({ok:!0,rows:d}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:Nt;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
5
- `);let u=(n?rt(n):[]).map(d=>{let c={id:`${d.model_id}:${d.variant}`,object:"model",created:0,owned_by:"urun",name:`${d.model_id}:${d.variant}`};d.gpu_spec&&(c.gpu_spec=d.gpu_spec),typeof d.warm=="number"&&(c.warm=d.warm);let l=s.filter(S=>S.model_id===d.model_id&&S.variant===d.variant),p=Mt(l);p!==null&&(c.context_length=p);let f=ot(d.model_id,d.variant,i);f!==null&&(c.pricing=f);let _=Pn(l);return _.published.length>0&&(c.voices=[..._.published]),c});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(d=>Tn(d,s,i)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Io(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let s=Co(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return $o(`${r.modelId}:${r.variant}`,s).includes(n)}return Po(st(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Dt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Dt(st(n.appSlug,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Dt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Dt(st(n.appSlug,r))==="tts"}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):st(n.appSlug,r);return Pn(o)}async imageModelList(){let e=await this.catalogRows(),n=Nt,r=[];for(let s of await this.availableIds()){let i=Po(st(s,e));i.length!==0&&r.push({...Tn(s,e,n),image_modes:i})}let o=await this.sharedBlock();if(o)for(let s of rt(o)){let i=Co(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=$o(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let u={id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun",name:`${s.model_id}:${s.variant}`,image_modes:a};s.gpu_spec&&(u.gpu_spec=s.gpu_spec),typeof s.warm=="number"&&(u.warm=s.warm),r.push(u)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var pa=256,$n=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>pa;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},fa="local",ut=t=>t.slice(0,120),Ln=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(Xr,ut(e.message));return}if(e instanceof K){this.ws.close(Lt,ut(e.message));return}if(e instanceof k){this.ws.close(e.closeCode,ut(e.message));return}this.ws.close(ce,ut(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Qr(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 k(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=so(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=uo(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:ao);return}this.transcript.push(...lo(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new k("setup may only be sent once, as the first client message");let n=no(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new k("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",Lt);if(s.model!==n.model)throw new k(`sessionResumption.handle was issued for model "${s.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 k("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!==s.proxyHandle)throw new k(`sessionResumption.handle named pooled session "${s.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`,Lt);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(d=>this.send(to(d))),u=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{a(),u()},o[Se]=eo(i.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 k("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new k("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(po(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 k("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new k("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 k(`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 k("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 k("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,Mo.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(ro(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(oo(e.timeLeftMs)),this.ws.close(ce,ut(`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,s=!1;for await(let u of r){if(n.interrupted)break;let d=u;if(d.type==="error")throw new k(`upstream error: ${JSON.stringify(d)}`,ce);if(d.type==="response.completed"){o=d.response,s=!0;continue}let c=co(d);c&&this.send(c)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new k("upstream produced no response.completed event",ce);let{messages:i,assistantItems:a}=fo(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},xe=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function ma(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let d of u)d!==""&&r.add(d)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new xe(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&&i!==void 0&&i!=="")throw new xe(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 u of r)a=u;if(a===void 0&&n)throw new xe(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Nn(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 Do.WebSocketServer({noServer:!0}),o=new $n;t.on("upgrade",(i,a,u)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===$t&&(a.on("error",()=>{}),(async()=>{let c=ma(i,d,n),l;if(e.authenticate)l=await e.authenticate(c,i);else{if(e.apiKey!==void 0&&c!==e.apiKey)throw new xe(401,"invalid local proxy api key");l={clients:e.clients,scope:fa}}r.handleUpgrade(i,a,u,p=>{new Ln(p,l,o)})})().catch(c=>{let l=502;(c instanceof xe||typeof c=="object"&&c!==null&&"status"in c&&typeof c.status=="number")&&(l=c.status);let p=l===401?"Unauthorized":l===403?"Forbidden":l===502?"Bad Gateway":"Internal Server Error",f=c instanceof Error?c.message:String(c);a.destroyed||(a.write(`HTTP/1.1 ${l} ${p}\r
1
+ "use strict";var Ui=Object.create;var Lt=Object.defineProperty;var Mi=Object.getOwnPropertyDescriptor;var Di=Object.getOwnPropertyNames;var Fi=Object.getPrototypeOf,Bi=Object.prototype.hasOwnProperty;var qi=(t,e)=>{for(var n in e)Lt(t,n,{get:e[n],enumerable:!0})},Zr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Di(e))!Bi.call(t,o)&&o!==n&&Lt(t,o,{get:()=>e[o],enumerable:!(r=Mi(e,o))||r.enumerable});return t};var at=(t,e,n)=>(n=t!=null?Ui(Fi(t)):{},Zr(e||!t||!t.__esModule?Lt(n,"default",{value:t,enumerable:!0}):n,t)),ji=t=>Zr(Lt({},"__esModule",{value:!0}),t);var vl={};qi(vl,{ANONYMOUS_KEY_ID:()=>kn,BIND_HOST:()=>Ai,BUCKET_DOMAIN:()=>xr,BoundedLabel:()=>Xe,ControlPlaneUnavailableError:()=>Ee,ConversationBackhauls:()=>rt,ConversationCapacityError:()=>nt,DEFAULT_PORT:()=>Fr,EDGE_IDENTITY_PORT:()=>hi,EDGE_KEY_FINGERPRINT_HEADER:()=>Rr,EDGE_KEY_ID_HEADER:()=>Sr,InferenceMetrics:()=>Qe,LEDGER_FUNCTION_PATH:()=>Vr,LEDGER_WRITE_TIMEOUT_MS:()=>Wr,LedgerClient:()=>it,LedgerDuplicateError:()=>st,LedgerSurfaceError:()=>z,MAX_CACHED_KEYS:()=>Pr,MAX_CONVERSATIONS:()=>In,MAX_CONVERSATION_HANDLES:()=>qr,MAX_MODEL_LABELS:()=>wr,MAX_ORG_LABELS:()=>_r,MAX_TENANTS:()=>Br,METRICS_PATH:()=>vn,METRICS_PORT:()=>mi,NO_MODEL_LABEL:()=>yr,ORG_BINDING_TTL_MS:()=>Tr,OTHER_LABEL:()=>Ye,OrgResolver:()=>Ze,ProxyAuthError:()=>se,READINESS_TIMEOUT_MS:()=>Yr,READINESS_TTL_MS:()=>zr,SERVE_FUNCTION:()=>et,TIER_DOMAIN:()=>Er,TenantRegistry:()=>tt,bearerFrom:()=>Me,bearerTokenOf:()=>Ir,createEdgeIdentityServer:()=>Sn,createHostedProxy:()=>Ni,createMetricsServer:()=>bn,edgeBucketId:()=>Ar,edgeTierFingerprint:()=>Or,laneOf:()=>vr,parseLedgerRecorded:()=>Jr,resolveHostedConfig:()=>Oi,statusClassOf:()=>br,tenantSubject:()=>ot});module.exports=ji(vl);var Li=require("http");var no="audio",$n=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(e,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let s=0;s<r;s++)o[s]=n.readInt16LE(s*2);this.source.onData(o)}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function ro(t,e,n=1e4){let r=new $n(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(no).attach(o);let s=await Hi(t,n);return await r.startInbound(s),r}function Hi(t,e){let n=t.stream(no);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=u=>{u!=null&&(clearTimeout(i),s?.(),r(u))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var eo="rt-video-in",to=256e3;function oo(t){let e=t.stream(eo),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${eo}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async r=>{if(r.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(r.byteLength>to)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${to}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var Gi=24e3,ut=480,Vi=111;async function Wi(){let t=await import("opusscript"),e=t.default??t;return new e(Gi,1,2048)}async function so(){let t=await import("werift"),e=await Wi();return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let u=new Int16Array(i.length+a.length);u.set(i,0),u.set(a,i.length);let d=0;for(;u.length-d>=ut;){let l=u.subarray(d,d+ut);d+=ut;let p=Buffer.from(l.buffer,l.byteOffset,l.byteLength),g=e.encode(p,ut);o=o+1&65535,s=s+ut>>>0;let c=new t.RtpHeader({version:2,payloadType:Vi,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),f=new t.RtpPacket(c,g);n.writeRtp(f)}i=u.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let u=0;u<a.length;u++)a[u]=i.readInt16LE(u*2);r.onframe?.({samples:a})}),r}}}var Nt=require("@urun-sh/core"),Ln="rt-video-out";var Ji="h264";function Ki(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function zi(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;Ki(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var io="urun.videoOut.v2-ws";function ao(t){let e=t.stream(Ln);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Ln}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=u=>{for(let d of r)d(u)},i=!1,a=async()=>{for await(let u of e.messages()){if(!(u instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${Ln}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=zi(u)}catch(l){s(l instanceof Error?l:new Error(String(l)));continue}for(let l of n)l(d)}for(let u of o)u()};return{codec:Ji,onOutputFrame:u=>(n.add(u),i||(i=!0,a().catch(d=>s(d instanceof Error?d:new Error(String(d))))),()=>n.delete(u)),onLaneError:u=>(r.add(u),()=>r.delete(u)),onEnd:u=>(o.add(u),()=>o.delete(u))}}var Ft="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Yi=1007,lo=1008,he=1011,Bt=1008,S=class extends Error{constructor(n,r=Yi){super(n);this.closeCode=r}closeCode},q=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Ut=["setup","clientContent","realtimeInput","toolResponse"];function co(t){let e;try{e=JSON.parse(t)}catch{throw new S("client message is not valid JSON")}let n=q(e);if(!n)throw new S("client message must be a JSON object");let r=Ut.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Ut.includes(a));if(o.length>0)throw new S(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Ut.join(", ")}`);if(r.length!==1)throw new S(`client message must contain exactly one of ${Ut.join(", ")} (got ${r.length})`);let s=r[0],i=q(n[s]);if(!i)throw new S(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function po(t,e){if(typeof t=="string")return t;let n=q(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new S(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=q(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new S(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new S(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new S(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
2
+ `)}var Xi={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Ae="urun.videoOut";function fo(t){return{framing:io,codec:t}}function mo(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Ae]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Qi={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Zi=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Ae],uo=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function ea(t){let e=q(t);if(!e)throw new S("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new S(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 S("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new S(`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 S("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(!uo.includes(e.activityHandling))throw new S(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${uo.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var ta=["temperature","maxOutputTokens","responseModalities"];function go(t){for(let[p,g]of Object.entries(Qi))if(t[p]!==void 0)throw new S(g);for(let p of Object.keys(t))if(!Zi.includes(p))throw new S(`unsupported setup field "${p}"`);if(typeof t.model!="string"||t.model.length===0)throw new S('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=q(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new S("setup.generationConfig must be an object");if(s){for(let p of Object.keys(s))if(!ta.includes(p))throw new S(`unsupported generationConfig field "${p}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new S("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new S("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let p=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let g of p){let c=String(g).toUpperCase();if(c==="AUDIO"){o=!0;continue}if(c!=="TEXT")throw new S(`responseModalities ${JSON.stringify(g)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:po(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new S("setup.tools must be an array");a=[];for(let p of t.tools){let g=q(p);if(!g)throw new S("setup.tools entries must be objects");for(let c of Object.keys(g))if(c!=="functionDeclarations")throw new S(`unsupported tool "${c}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(g.functionDeclarations))throw new S("tool.functionDeclarations must be an array");for(let c of g.functionDeclarations){let f=q(c);if(!f||typeof f.name!="string")throw new S("functionDeclarations entries require a string name");a.push({type:"function",name:f.name,description:f.description,parameters:f.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let p=q(t.sessionResumption);if(!p)throw new S("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let g of Object.keys(p))if(g!=="handle")throw new S(`unsupported sessionResumption field "${g}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(p.handle!==void 0&&(typeof p.handle!="string"||p.handle.length===0))throw new S("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof p.handle=="string"?p.handle:null}}let d=t.realtimeInputConfig===void 0?Xi:ea(t.realtimeInputConfig),l=!1;if(t[Ae]!==void 0){if(!q(t[Ae]))throw new S(`setup["${Ae}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:d,sessionResumption:u,videoOut:l}}function ho(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function yo(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function wo(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new S(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new S("clientContent.turns must be an array");let n=[];for(let r of e){let o=q(r);if(!o)throw new S("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new S(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:po(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Mt=16e3,_o=24e3,na=`audio/pcm;rate=${_o}`,vo=Buffer.alloc(960).toString("base64");function ra(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let u=a*s,d=Math.floor(u);if(d>=i){o[a]=t[i];continue}let l=u-d;o[a]=Math.round(t[d]+(t[d+1]-t[d])*l)}return o}function oa(t){let e=q(t);if(!e)throw new S("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new S(`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 S("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 S("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function sa(t){let e=q(t);if(!e)throw new S("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new S(`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])!==Mt)throw new S(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Mt} Hz (audio/pcm;rate=${Mt})`);if(typeof e.data!="string"||e.data.length===0)throw new S("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 S(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=ra(o,Mt,_o);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function bo(t){if(t.mediaChunks!==void 0)throw new S('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 S("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=q(t[o]);if(!s||Object.keys(s).length!==0)throw new S(`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 S(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new S(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:sa(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:oa(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new S("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new S("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function ko(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new S(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new S("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 S("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 So(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Ro(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:na,data:t}}]}}}}function xo(t){let e=q(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let d of n){let l=q(d);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let p of l.content){let g=q(p);g?.type==="output_text"&&typeof g.text=="string"&&(s+=g.text)}}s&&o.push({role:"assistant",content:s});for(let d of n){let l=q(d);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new S(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,he);let p=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",g;try{g=JSON.parse(p)}catch{throw new S(`upstream function_call arguments are not valid JSON: ${p}`,he)}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:p})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=q(e.usage),u={serverContent:{turnComplete:!0}};if(a){let d={};typeof a.input_tokens=="number"&&(d.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(d.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(d.totalTokenCount=a.total_tokens),Object.keys(d).length>0&&(u.usageMetadata=d)}return i.push(u),{messages:i,assistantItems:o}}var Ko=require("crypto"),zo=require("ws");var V=class extends Error{},ia=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function aa(t){if(typeof t!="string")return!1;let e=ia.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let u=new Date(Date.UTC(n,r-1,o,s,i,a));return u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===o&&u.getUTCHours()===s&&u.getUTCMinutes()===i&&u.getUTCSeconds()===a}function ua(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new V(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new V(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new V(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,u)=>{if(a===null||typeof a!="object")throw new V(`catalog shared endpoints[${u}] is not an object: ${JSON.stringify(a)}`);let d=a;for(let p of["model_id","variant","app_slug","function"])if(typeof d[p]!="string"||d[p].length===0)throw new V(`catalog shared endpoints[${u}] (${JSON.stringify(d)}) has no valid "${p}"`);let l=(p,g)=>{if(d[p]!==void 0&&d[p]!==null&&!g)throw new V(`catalog shared endpoints[${u}] (${d.model_id}:${d.variant}) carries a malformed "${p}": ${JSON.stringify(d[p])}`)};l("ready",typeof d.ready=="boolean"),l("ready_runtimes",typeof d.ready_runtimes=="number"&&Number.isInteger(d.ready_runtimes)&&d.ready_runtimes>=0),l("ready_since",aa(d.ready_since));for(let p of["model_id","variant"]){let g=d[p];if(g.includes(":"))throw new V(`catalog shared endpoints[${u}] has "${p}" containing ":" (${JSON.stringify(g)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return l("output_free",typeof d.output_free=="boolean"),d});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new V(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new V(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let u of Object.keys(a))if(u!=="zdr"&&u!=="hipaa")throw new V(`catalog "shared" block compliance carries "${u}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function Fe(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Eo(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(d=>d.model_id===o);if(a.length===0)return null;if(s!==void 0){let d=a.find(l=>l.variant===s);return d?{shared_org_id:t.shared_org_id,endpoint:d}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let u=a.filter(d=>d.compat_default===!0);if(u.length!==1)throw new V(`shared model "${o}" has ${u.length} compat_default rows (exactly one required) among variants ${a.map(d=>d.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:u[0]}}async function Ao(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new V(`catalog read failed: GET ${n} \u2192 ${r.status}`);return ua(await r.json())}function ye(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var ie=class extends Error{name="ModelPriceError"},Nn="per_million_input_tokens",Un="per_million_output_tokens",Io="model_id,variant,unit,price_usd,effective_at,expires_at",Oo={per_request:!0,per_minute:!0,per_output_unit:!0},da=5e3;function la(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ie(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function To(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ie(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function ca(t,e,n){return t===null?null:To(t,e,n)}function pa(t,e){if(t===Nn)return"input";if(t===Un)return"output";if(typeof t=="string"&&Object.hasOwn(Oo,t))return null;throw new ie(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Nn} | ${Un}) nor a known GPU-time unit (${Object.keys(Oo).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function fa(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:n}}function Mn(t,e){return`${t}\0${e}`}function ma(t){if(!Array.isArray(t))throw new ie(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new ie(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let d of Io.split(","))if(!Object.hasOwn(s,d))throw new ie(`${o} has no "${d}" column: ${JSON.stringify(s)}`);let i=pa(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new ie(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new ie(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:la(s.price_usd,o),effective_at:To(s.effective_at,o,"effective_at"),expires_at:ca(s.expires_at,o,"expires_at")})}return e}function Po(t,e=Date.now(),n){let r=new Map,o=new Map;for(let u of t){if(u.effective_at>e||u.expires_at!==null&&u.expires_at<=e)continue;let d=r.get(u.model_id);d||(d=new Map,r.set(u.model_id,d),o.set(u.model_id,new Map));let l=u.variant??"",p=d.get(l);p||(p={input:[],output:[]},d.set(l,p),o.get(u.model_id).set(l,u.variant)),p[u.side].push({effective_at:u.effective_at,usd:u.usd})}let s=[],i=[];for(let[u,d]of r){let l=d.get(""),p=(g,c,f)=>{let h=g&&g.length>0?g:l?.[c];if(!h||h.length===0)return null;let b=fa(h,c);return"reason"in b?b:b.rate.usd===0?c==="output"&&f!==null&&n?.has(Mn(u,f))?b.rate:{reason:`the ${c} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:b.rate};for(let[g,c]of o.get(u)){let f=d.get(g),h=p(f?.input,"input",c),b=p(f?.output,"output",c);if(h!==null&&"reason"in h){i.push({model_id:u,variant:c,reason:h.reason});continue}if(b!==null&&"reason"in b){i.push({model_id:u,variant:c,reason:b.reason});continue}h===null||b===null||s.push({model_id:u,variant:c,pricing:{input:h.usd,output:b.usd}})}}let a=(u,d)=>u.model_id.localeCompare(d.model_id)||(u.variant===null?1:0)-(d.variant===null?1:0)||(u.variant??"").localeCompare(d.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function dt(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var lt={prices:[],refusals:[]};async function Co(t){let e=t.fetchImpl??fetch,n=`${Nn},${Un}`,r=await e(`${t.catalogUrl}/model_prices?select=${Io}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(da)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return ma(await r.json())}var ga={chat:!0,code:!0,agent:!0,vl:!0},$o={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function ha(t){let e=t.toLowerCase();return Object.hasOwn($o,e)?$o[e]:null}var Lo={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function ya(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Lo,o)?Lo[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var No={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Uo={2:"Llama2",3:"Llama3"};function wa(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(No,s))return No[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Uo,i))return Uo[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var _a=["context_length","max_model_len"];function va(t){let e=_a.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function jt(t){let e=t.map(va),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function ba(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function Dn(t){if(t.length===0)return null;let e=t.map(ba),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function ka(t,e){let n=e.filter(o=>ye(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return qt(n);let r=e.filter(o=>ye(o.model_id)===t);return r.length>0?qt(r):null}function qt(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:Sa(t),matches:t}:null}function Sa(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}function Fo(t){let e=t.updated_at?Date.parse(t.updated_at):NaN;return Number.isFinite(e)?Math.floor(e/1e3):0}function Ht(t,e,n){let r=ka(t,e);if(!r)return{id:t,object:"model",created:0,owned_by:"urun"};let{row:o,matches:s}=r,i=jt(s),a=dt(o.model_id,o.variant,n),u=Bo(o,s),d=Dn(s);return{id:t,object:"model",created:Fo(o),owned_by:"urun",name:`${o.model_id}:${o.variant}`,...o.description?{description:o.description}:{},...o.task?{task:o.task}:{},...o.engine?{engine:o.engine}:{},...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}}}var Ra=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Bo(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...Ra],defect:o}:{published:[],defect:o}}function Fn(t){let e=t.length>0?qt(t):null;return e===null?{published:[],defect:null}:Bo(e.row,e.matches)}function Mo(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Do(t){return{input:[{type:"prompt",unit:"token",cost_usd:Mo(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Mo(t.output)}]}}function xa(t,e,n,r){if(e.length===0)return null;let o=qt(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||ga[s.task]!==!0)return null;let a=jt(i),u=dt(s.model_id,s.variant,n),d=wa(s.hf_repo),l={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(l.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Fo(s),quantization:ha(s.variant),...d!==null?{tokenizer:d}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&u!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...u?{pricing:Do(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:l,...u?{pricing:Do(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function qo(t,e,n,r){let o=r??(d=>console.warn(d.trimEnd())),s=t?Fe(t):[];if(s.length>0){let d=s.filter(l=>l.ready===void 0);if(d.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(d.length>0){let l=d.map(p=>`${p.model_id}:${p.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${l} carry no ready field and are declared not ready`)}}let i={datacenters:ya(t?.regions,o),compliance:t?.compliance??null},a=[],u=new Set;for(let d of s){let l=`${d.model_id}:${d.variant}`;if(u.has(l))continue;u.add(l);let p=xa(d,e.filter(g=>g.model_id===d.model_id&&g.variant===d.variant),n,i);p&&a.push(p)}return{data:a}}var N=class extends Error{},W=class extends Error{},qn="urs1.";function jo(t,e){return qn+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Ea(t){if(!t.startsWith(qn))return null;try{let e=JSON.parse(Buffer.from(t.slice(qn.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function Wo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Ho(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Oa(t);return e===null?[]:[e]}function Bn(t,e,n,r,o){if(!o)throw new V(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new V(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new V(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function Go(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new V(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var Jo="shared:",Ie="speech:";function ct(t){return t.sharedApp?Jo+t.appSlug:t.appSlug}function pt(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function Oe(t,e){let n=e.filter(s=>ye(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>ye(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function Aa(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Oa(t){let e=t.map(Aa),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Vo={stt:"stt",tts:"tts"};function be(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||Vo[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?Vo[e]:null}var Gt=6e4,Vt=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;rowsCache=null;seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??Gt;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}async sharedBlock(){if(!this.opts.shared)return null;let e=this.opts.appsTtlMs??Gt;if(this.sharedCache&&Date.now()-this.sharedCache.at<e)return this.sharedCache.block;let n=await this.opts.shared();return this.sharedCache={at:Date.now(),block:n},n}sharedCache=null;async catalogRows(){if(!this.opts.listCatalog)return[];let e=this.opts.appsTtlMs??Gt;if(this.rowsCache&&Date.now()-this.rowsCache.at<e)return this.rowsCache.rows;let n=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:n},n}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Gt;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof ie)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
3
+ `),lt}let r=Po(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
4
+ `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(Mn(r.model_id,r.variant));return n}warn(e){(this.opts.warn??(r=>console.warn(r.trimEnd())))(e)}servable(e){return e.filter(n=>n.serves==="openai"&&n.deployment_status==="active").map(n=>n.app_slug)}async availableIds(){let e=this.opts.defaultApp,n=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let o of this.servable(await this.deployedApps()))n.add(o);for(let o of this.pool.keys())o.startsWith(Jo)||o.startsWith(Ie)||n.add(o);let r=[...n].filter(o=>o!==e).sort();return e===null?r:[e,...r]}async noDefaultApp(e){let n=await this.availableIds(),r=n.length>0?n.join(", "):"(none deployed)";throw new N(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${r}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${r}`)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};let o=ye(n);if(o===r)return{appSlug:r};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let s=await this.deployedApps(),i=this.servable(s);if(i.includes(o))return{appSlug:o};let a=i.filter(d=>d.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new N(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=s.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new N(`model "${n}" maps to app "${u.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.shared){let s=await this.sharedBlock();if(s){let i=Eo(s,n);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant,sharedOrgId:s.shared_org_id}}}if(this.opts.listCatalog){let i=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===ye(a.model_id)||o===ye(`${a.model_id}-${a.variant}`));if(i)throw new N(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${i.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=pt(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async targetFor(e){return this.resolveTarget(e)}async resolveApp(e){return ct(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,ct(n))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ie+ct(n))}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:pt(e)}}keyOf(e){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=n(e);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(e){let{app:n,entry:r}=await this.sessionFor(e);return{app:n,handle:jo(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:jo(n,this.keyOf(r))}}async sessionForHandle(e){let n=Ea(e);if(!n)throw new W(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,s=this.pool.get(r),i=s?await s.then(a=>a,()=>null):null;if(i===null)throw new W(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==o)throw new W(`the session behind this handle (app "${r}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:r,entry:i}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(s=>s,()=>null)!==n||this.pool.get(e)!==r||(this.pool.delete(e),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),n=await this.sharedBlock(),[r,o]=await Promise.all([this.catalogRows().then(d=>({ok:!0,rows:d}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:lt;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
5
+ `);let u=(n?Fe(n):[]).map(d=>{let l={id:`${d.model_id}:${d.variant}`,object:"model",created:0,owned_by:"urun",name:`${d.model_id}:${d.variant}`};d.gpu_spec&&(l.gpu_spec=d.gpu_spec),typeof d.warm=="number"&&(l.warm=d.warm);let p=s.filter(b=>b.model_id===d.model_id&&b.variant===d.variant),g=jt(p);g!==null&&(l.context_length=g);let c=Dn(p);c!==null&&(l.capabilities={reasoning:c});let f=dt(d.model_id,d.variant,i);f!==null&&(l.pricing=f);let h=Fn(p);return h.published.length>0&&(l.voices=[...h.published]),l});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(d=>Ht(d,s,i)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return qo(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let s=Bn(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Go(`${r.modelId}:${r.variant}`,s).includes(n)}return Ho(Oe(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?be(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:be(Oe(n.appSlug,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?be(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":be(Oe(n.appSlug,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?be(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":be(Oe(n.appSlug,r))==="stt"}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):Oe(n.appSlug,r);return Fn(o)}async imageModelList(){let e=await this.catalogRows(),n=lt,r=[];for(let s of await this.availableIds()){let i=Ho(Oe(s,e));i.length!==0&&r.push({...Ht(s,e,n),image_modes:i})}let o=await this.sharedBlock();if(o)for(let s of Fe(o)){let i=Bn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Go(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let u={id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun",name:`${s.model_id}:${s.variant}`,image_modes:a};s.gpu_spec&&(u.gpu_spec=s.gpu_spec),typeof s.warm=="number"&&(u.warm=s.warm),r.push(u)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=lt,r=[];for(let s of await this.availableIds())be(Oe(s,e))==="stt"&&r.push(Ht(s,e,n));let o=await this.sharedBlock();if(o)for(let s of Fe(o)){let i=Bn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(be(i)!=="stt")continue;let a={id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun",name:`${s.model_id}:${s.variant}`};s.gpu_spec&&(a.gpu_spec=s.gpu_spec),typeof s.warm=="number"&&(a.warm=s.warm),r.push(a)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var Ia=256,jn=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Ia;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Ta="local",ft=t=>t.slice(0,120),Hn=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(lo,ft(e.message));return}if(e instanceof W){this.ws.close(Bt,ft(e.message));return}if(e instanceof S){this.ws.close(e.closeCode,ft(e.message));return}this.ws.close(he,ft(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=co(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 S(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=wo(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=bo(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:vo);return}this.transcript.push(...ko(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new S("setup may only be sent once, as the first client message");let n=go(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new S("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",Bt);if(s.model!==n.model)throw new S(`sessionResumption.handle was issued for model "${s.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 S("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!==s.proxyHandle)throw new S(`sessionResumption.handle named pooled session "${s.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`,Bt);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(d=>this.send(mo(d))),u=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{a(),u()},o[Ae]=fo(i.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 S("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new S("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",he);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Ro(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 S("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new S("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",he);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 S(`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 S("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 S("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,Ko.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(ho(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(yo(e.timeLeftMs)),this.ws.close(he,ft(`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,s=!1;for await(let u of r){if(n.interrupted)break;let d=u;if(d.type==="error")throw new S(`upstream error: ${JSON.stringify(d)}`,he);if(d.type==="response.completed"){o=d.response,s=!0;continue}let l=So(d);l&&this.send(l)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new S("upstream produced no response.completed event",he);let{messages:i,assistantItems:a}=xo(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Te=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Pa(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let d of u)d!==""&&r.add(d)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Te(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&&i!==void 0&&i!=="")throw new Te(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 u of r)a=u;if(a===void 0&&n)throw new Te(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Gn(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 zo.WebSocketServer({noServer:!0}),o=new jn;t.on("upgrade",(i,a,u)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===Ft&&(a.on("error",()=>{}),(async()=>{let l=Pa(i,d,n),p;if(e.authenticate)p=await e.authenticate(l,i);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new Te(401,"invalid local proxy api key");p={clients:e.clients,scope:Ta}}r.handleUpgrade(i,a,u,g=>{new Hn(g,p,o)})})().catch(l=>{let p=502;(l instanceof Te||typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number")&&(p=l.status);let g=p===401?"Unauthorized":p===403?"Forbidden":p===502?"Bad Gateway":"Internal Server Error",c=l instanceof Error?l.message:String(l);a.destroyed||(a.write(`HTTP/1.1 ${p} ${g}\r
6
6
  Connection: close\r
7
7
  \r
8
- ${f}\r
9
- `),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}var ye=require("ws");var Fo=require("crypto"),Bo="Inference-Id";function dt(){return(0,Fo.randomUUID)()}function Un(t){return t==="/v1"||t.startsWith("/v1/")}function qo(t,e){if(!Un(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 lt(t){return`resp_${t}`}function Ho(t){return`chatcmpl-${t}`}function jo(t){return`msg_${t}`}function se(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Go(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,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 Vo(t){return`${JSON.stringify(t)}
10
- `}var ga=256,ha=128;function oe(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,ha)}var Ee=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>=ga?"(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,s=performance.now(),i=null,a=0;return(async function*(){for await(let d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=d.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield d;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),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}}}},ya=256;function _a(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 Ae=class extends Error{},Le=class{conversations=new Map;thread(e,n){let r=_a(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ae(`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 s of this.conversations.keys()){if(this.conversations.size<=ya)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Wo=new WeakMap;function ct(t){let e=Wo.get(t);return e||(e=new Le,Wo.set(t,e)),e}function Ne(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function ie(t){return t.find(e=>e.type==="response.completed")?.response??null}function Ue(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 he=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}))}},wa=["<tool_call>","<function="];function va(t){return wa.find(e=>t.includes(e))}function Oe(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 Ie(t,e,n){if(!(!t||e>0))return va(n)}function qt(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 ba(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 Mn(t,e){let n=ba(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var re=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Me(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ae?new re(n.message,"previous_response_not_found",400,"previous_response_id"):new re(String(n instanceof Error?n.message:n),"invalid_input")}}function Jo(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Dn(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new re("instructions must be a string","invalid_instructions");let s=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,...s!==void 0?{instructions:s}:{},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}:{},...Jo(e)!==void 0?{response_format:Jo(e)}:{}},o)}async function pt(t){let{body:e,clients:n,store:r,stats:o}=t,s=Me(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,d=oe(e);o.model(d);let c=Array.isArray(e.tools)&&e.tools.length>0,l=t.turn,p=await Dn(n,e,s,!0,l?se(l):void 0);return{responseId:i,events:ka({events:p,conversation:s,responseId:i,modelKey:d,requestHadTools:c,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}async function*ka(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:d}=t,c=[],l=P=>P.response&&typeof P.response=="object"?{...P,response:{...P.response,id:r}}:P,p=`item_${r.slice(5)}`,f=`rs_${r.slice(5)}`,_=!1,S=!1,h=0;function*m(){_||(_=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let y=!1,g=0,R="";function*v(){y&&(y=!1,yield{type:"response.reasoning_text.done",item_id:f,output_index:g,content_index:0,text:R},yield{type:"response.output_item.done",output_index:g,item:{id:f,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:R}],status:"completed"}})}let b=!1,w=0,x="";function*T(P){b&&(b=!1,yield{type:"response.output_text.done",item_id:p,output_index:w,content_index:0,text:x},yield{type:"response.content_part.done",item_id:p,output_index:w,content_index:0,part:{type:"output_text",text:x}},yield{type:"response.output_item.done",output_index:w,item:{id:p,type:"message",role:"assistant",status:P,content:[{type:"output_text",text:x}]}})}let L=new he,I=null,z=-1;function*X(P){if(!I)return;let M=I;I=null,yield{type:"response.function_call_arguments.done",item_id:M.fcId,output_index:M.outputIndex,arguments:M.args},yield{type:"response.output_item.done",output_index:M.outputIndex,item:{id:M.fcId,type:"function_call",call_id:M.callId??M.fcId,name:M.name??"",arguments:M.args,status:P}}}let J=!1;for await(let P of d.track(e,o,t.turn)){c.push(P);let M=String(P.type??"");if(M==="response.created"||M==="response.in_progress"){_=!0,yield l(P);continue}if(M==="response.output_item.added"){S=!0,yield l(P);continue}if(M==="response.reasoning_text.delta"&&!S){yield*m(),y||(y=!0,g=h++,yield{type:"response.output_item.added",output_index:g,item:{id:f,type:"reasoning",summary:[],content:[],status:"in_progress"}}),R+=String(P.delta??""),yield{type:"response.reasoning_text.delta",item_id:f,output_index:g,content_index:0,delta:P.delta};continue}if(M==="response.output_text.delta"&&!S){yield*m(),yield*v(),b||(b=!0,w=h++,yield{type:"response.output_item.added",output_index:w,item:{id:p,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:p,output_index:w,content_index:0,part:{type:"output_text",text:""}}),x+=String(P.delta??""),yield{type:M,item_id:p,output_index:w,content_index:0,delta:P.delta};continue}let H=S?null:Ue(P);if(H){if(yield*m(),yield*v(),yield*T("completed"),L.add(H),H.tool_index!==z){yield*X("completed"),z=H.tool_index;let te=h++;I={fcId:`fc_${r.slice(5)}_${H.tool_index}`,outputIndex:te,callId:H.call_id,name:H.name,args:""},yield{type:"response.output_item.added",output_index:te,item:{id:I.fcId,type:"function_call",call_id:I.callId??I.fcId,name:I.name??"",arguments:"",status:"in_progress"}}}I&&(H.call_id&&(I.callId=H.call_id),H.name&&(I.name=H.name),I.args+=H.delta,yield{type:"response.function_call_arguments.delta",item_id:I.fcId,output_index:I.outputIndex,delta:H.delta});continue}if(M==="response.completed"&&!S){let te=Ne(P.response),be=Ie(s,L.size+te.length,x);if(be){J=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Oe(o,be)}};break}if(yield*v(),yield*T("completed"),yield*X("completed"),L.size===0)for(let ke of te){let ge=h++,le=ke.id??ke.call_id??`fc_${ge}`,et=ke.arguments??"",$e={id:le,type:"function_call",call_id:ke.call_id??le,name:ke.name??""};yield{type:"response.output_item.added",output_index:ge,item:{...$e,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:le,output_index:ge,delta:et},yield{type:"response.function_call_arguments.done",item_id:le,output_index:ge,arguments:et},yield{type:"response.output_item.done",output_index:ge,item:{...$e,arguments:et,status:"completed"}}}yield l(P);continue}yield l(P)}if(yield*v(),yield*T("incomplete"),yield*X("incomplete"),i&&!J){let P=ie(c);u.remember(r,n,Mn(P,qt(c,P)),a)}}var qn="/v1/responses",Sa=64*1024*1024,Ra=8*1024*1024,xa=16,Ko=32,zo=3600*1e3,Ea=/^[A-Za-z0-9._-]{1,256}$/;function Q(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Aa=Q(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 Hn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Oa(t){for(;t.bufferedAmount>Ra&&t.readyState===ye.WebSocket.OPEN;){let{promise:e,resolve:n}=Hn();setTimeout(n,5),await e}}var Fn=class extends Le{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 Ae))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},Bn=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new Fn(ct(n)),e.on("message",(i,a)=>this.onMessage(i,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(Q(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${zo/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},zo).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(Q(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(Q(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(Q(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(Q(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(Q(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(Q(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Ea.test(o.stream_id)){this.sendFrame(Aa);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Ko){this.sendFrame(Q(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Ko}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).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 pt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:lt(dt())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let s=o.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==ye.WebSocket.OPEN)break;this.send(i,n),await Oa(this.ws)}}finally{this.activeTurns.delete(s)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=lt(dt());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 re)return Q(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 Q(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof K)return Q(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?Q(o.status,{type:o.openaiType,message:r},n):Q(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=xa;){let{promise:e,resolve:n}=Hn();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!==ye.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!==ye.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Ht(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
8
+ ${c}\r
9
+ `),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}var Se=require("ws");var Yo=require("crypto"),Xo="Inference-Id";function mt(){return(0,Yo.randomUUID)()}function Vn(t){return t==="/v1"||t.startsWith("/v1/")}function Qo(t,e){if(!Vn(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 gt(t){return`resp_${t}`}function Zo(t){return`chatcmpl-${t}`}function es(t){return`msg_${t}`}function ae(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function ts(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,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 ns(t){return`${JSON.stringify(t)}
10
+ `}var Ca=256,$a=128;function re(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,$a)}var Pe=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>=Ca?"(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,s=performance.now(),i=null,a=0;return(async function*(){for await(let d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=d.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield d;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),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}}}},La=256;function Na(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 Ce=class extends Error{},Be=class{conversations=new Map;thread(e,n){let r=Na(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ce(`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 s of this.conversations.keys()){if(this.conversations.size<=La)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},rs=new WeakMap;function ht(t){let e=rs.get(t);return e||(e=new Be,rs.set(t,e)),e}function qe(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function de(t){return t.find(e=>e.type==="response.completed")?.response??null}function je(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 ke=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}))}},Ua=["<tool_call>","<function="];function Ma(t){return Ua.find(e=>t.includes(e))}function $e(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 Le(t,e,n){if(!(!t||e>0))return Ma(n)}function He(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 Da(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 Wn(t,e){let n=Da(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ue=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Ge(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ce?new ue(n.message,"previous_response_not_found",400,"previous_response_id"):new ue(String(n instanceof Error?n.message:n),"invalid_input")}}function os(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Jn(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ue("instructions must be a string","invalid_instructions");let s=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,...s!==void 0?{instructions:s}:{},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}:{},...os(e)!==void 0?{response_format:os(e)}:{}},o)}async function yt(t){let{body:e,clients:n,store:r,stats:o}=t,s=Ge(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,d=re(e);o.model(d);let l=Array.isArray(e.tools)&&e.tools.length>0,p=t.turn,g=await Jn(n,e,s,!0,p?ae(p):void 0);return{responseId:i,events:ja({events:g,conversation:s,responseId:i,modelKey:d,requestHadTools:l,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function Fa(t,e){let n=[...t].sort((u,d)=>u.output_index-d.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),s=n.filter(u=>u.type==="message").length===o.length,i=0;return[...n.map(u=>u.type==="message"&&s?qa(o[i++],u):u),...Ba(r,n)]}function Ba(t,e){let n=e.some(d=>d.type==="message"),r=e.some(d=>d.type==="reasoning"),o=d=>String(d.call_id??d.id??""),s=e.filter(d=>d.type==="function_call"),i=t.filter(d=>d!==null&&typeof d=="object"&&d.type==="function_call").length,a=s.length===i,u=new Set(s.map(o));return t.filter(d=>{if(d===null||typeof d!="object")return!0;let l=d;return l.type==="message"?!n:l.type==="reasoning"?!r:l.type==="function_call"?!a&&!u.has(o(l)):!0})}function qa(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 s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*ja(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:d}=t,l=[],p=C=>C.response&&typeof C.response=="object"?{...C,response:{...C.response,id:r}}:C,g=`item_${r.slice(5)}`,c=!1,f=!1,h=0;function*b(){c||(c=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let m=[],y=(C,U)=>{m.push({output_index:C,item:U})},w=!1,R=0,_="",k=0,v="";function*x(){if(!w)return;w=!1,yield{type:"response.reasoning_text.done",item_id:_,output_index:R,content_index:0,text:v};let C={id:_,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:v}],status:"completed"};yield{type:"response.output_item.done",output_index:R,item:C},y(R,C),v=""}let I=!1,T=0,$="",Y=0,Z="",X="";function*ee(C){if(!I)return;I=!1,yield{type:"response.output_text.done",item_id:$,output_index:T,content_index:0,text:Z},yield{type:"response.content_part.done",item_id:$,output_index:T,content_index:0,part:{type:"output_text",text:Z}};let U={id:$,type:"message",role:"assistant",status:C,content:[{type:"output_text",text:Z}]};yield{type:"response.output_item.done",output_index:T,item:U},y(T,U),Z=""}let fe=new ke,j=null,me=-1;function*_e(C){if(!j)return;let U=j;j=null,yield{type:"response.function_call_arguments.done",item_id:U.fcId,output_index:U.outputIndex,arguments:U.args};let J={id:U.fcId,type:"function_call",call_id:U.callId??U.fcId,name:U.name??"",arguments:U.args,status:C};yield{type:"response.output_item.done",output_index:U.outputIndex,item:J},y(U.outputIndex,J)}let Ct=!1;for await(let C of d.track(e,o,t.turn)){l.push(C);let U=String(C.type??"");if(U==="response.created"||U==="response.in_progress"){c=!0,yield p(C);continue}if(U==="response.output_item.added"){f=!0,yield p(C);continue}if(U==="response.reasoning_text.delta"&&!f){yield*b(),w||(w=!0,R=h++,k+=1,_=k===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${k}`,yield{type:"response.output_item.added",output_index:R,item:{id:_,type:"reasoning",summary:[],content:[],status:"in_progress"}}),v+=String(C.delta??""),yield{type:"response.reasoning_text.delta",item_id:_,output_index:R,content_index:0,delta:C.delta};continue}if(U==="response.output_text.delta"&&!f){yield*b(),yield*x(),I||(I=!0,T=h++,Y+=1,$=Y===1?g:`${g}_${Y}`,yield{type:"response.output_item.added",output_index:T,item:{id:$,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:$,output_index:T,content_index:0,part:{type:"output_text",text:""}}),Z+=String(C.delta??""),X+=String(C.delta??""),yield{type:U,item_id:$,output_index:T,content_index:0,delta:C.delta};continue}let J=f?null:je(C);if(J){if(yield*b(),yield*x(),yield*ee("completed"),fe.add(J),J.tool_index!==me){yield*_e("completed"),me=J.tool_index;let ge=h++;j={fcId:`fc_${r.slice(5)}_${J.tool_index}`,outputIndex:ge,callId:J.call_id,name:J.name,args:""},yield{type:"response.output_item.added",output_index:ge,item:{id:j.fcId,type:"function_call",call_id:j.callId??j.fcId,name:j.name??"",arguments:"",status:"in_progress"}}}j&&(J.call_id&&(j.callId=J.call_id),J.name&&(j.name=J.name),j.args+=J.delta,yield{type:"response.function_call_arguments.delta",item_id:j.fcId,output_index:j.outputIndex,delta:J.delta});continue}if(U==="response.completed"&&!f){let ge=qe(C.response),D=Le(s,fe.size+ge.length,X);if(D){Ct=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:$e(o,D)}};break}if(yield*x(),yield*ee("completed"),yield*_e("completed"),fe.size===0)for(let ve of ge){let De=h++,$t=ve.id??ve.call_id??`fc_${De}`,Cn=ve.arguments??"",Xr={id:$t,type:"function_call",call_id:ve.call_id??$t,name:ve.name??""};yield{type:"response.output_item.added",output_index:De,item:{...Xr,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:$t,output_index:De,delta:Cn},yield{type:"response.function_call_arguments.done",item_id:$t,output_index:De,arguments:Cn};let Qr={...Xr,arguments:Cn,status:"completed"};yield{type:"response.output_item.done",output_index:De,item:Qr},y(De,Qr)}let te=Fa(m,C.response);yield te.length>0?p({...C,response:{...C.response,output:te}}):p(C);continue}yield p(C)}if(yield*x(),yield*ee("incomplete"),yield*_e("incomplete"),i&&!Ct){let C=de(l);u.remember(r,n,Wn(C,He(l,C)),a)}}var Yn="/v1/responses",Ha=64*1024*1024,Ga=8*1024*1024,Va=16,ss=32,is=3600*1e3,Wa=/^[A-Za-z0-9._-]{1,256}$/;function oe(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Ja=oe(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 Xn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Ka(t){for(;t.bufferedAmount>Ga&&t.readyState===Se.WebSocket.OPEN;){let{promise:e,resolve:n}=Xn();setTimeout(n,5),await e}}var Kn=class extends Be{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 Ce))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},zn=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new Kn(ht(n)),e.on("message",(i,a)=>this.onMessage(i,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(oe(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${is/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},is).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(oe(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(oe(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(oe(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(oe(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(oe(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(oe(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Wa.test(o.stream_id)){this.sendFrame(Ja);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=ss){this.sendFrame(oe(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${ss}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).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 yt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:gt(mt())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let s=o.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==Se.WebSocket.OPEN)break;this.send(i,n),await Ka(this.ws)}}finally{this.activeTurns.delete(s)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=gt(mt());try{let o=Ge(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 ue)return oe(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 oe(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof W)return oe(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?oe(o.status,{type:o.openaiType,message:r},n):oe(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Va;){let{promise:e,resolve:n}=Xn();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!==Se.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!==Se.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Wt(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
11
11
  `;t.end(`HTTP/1.1 ${e} ${r}\r
12
12
  Connection: close\r
13
13
  Content-Type: text/plain; charset=utf-8\r
14
14
  Content-Length: ${Buffer.byteLength(o)}\r
15
15
  \r
16
- ${o}`)}function jn(t,e){let n=new ye.WebSocketServer({noServer:!0,maxPayload:Sa}),r=new Ee,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(c,l,p)=>{let f;try{f=new URL(c.url??"/","http://localhost")}catch{Ht(l,400,"malformed upgrade URL");return}if(l.on("error",()=>l.destroy()),l.on("close",()=>i.delete(l)),f.pathname!==qn){i.add(l);return}s.add(l);let _=!1;(async()=>{if(e.apiKey&&(c.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ht(l,401,"invalid local proxy api key");return}let S;try{S=await a(c)}catch(h){let m=e.statusOf?.(h)??null;Ht(l,m?.status??500,"upstream resolver rejected the connection");return}u||l.destroyed||(_=!0,n.handleUpgrade(c,l,p,h=>{s.delete(l),o.add(h),h.on("close",()=>o.delete(h));try{new Bn(h,S,r,e.statusOf)}catch{o.delete(h),h.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!_&&!l.destroyed&&Ht(l,500,"responses websocket upgrade failed")}).finally(()=>s.delete(l))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:c,resolve:l}=Hn();if(u)return l(),c;u=!0,t.off("upgrade",d);for(let f of s)f.destroy();s.clear();for(let f of i)f.destroy();i.clear();for(let f of o)f.close(1001,"server shutting down");let p=setTimeout(()=>{for(let f of o)f.readyState!==ye.WebSocket.CLOSED&&f.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),l()}),c}}}var ns=require("@urun-sh/core");var Yo=require("@urun-sh/core"),Ia={no_capacity:429,queue_timeout:429,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Ta={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 Gn(t,e){let n=Ta[t.code];return e?`${n} (${e})`:n}function jt(t){if(t==null)return null;let e=Ia[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 Gt(t){if(t.kind==="create-failed")return jt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Yo.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return jt(e?"cold_start_exceeded":"queue_timeout")}var Pa=tt(require("os"),1),Ca=tt(require("path"),1),$a=require("url"),La=require("util");function Xo(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function Vt(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}var Na=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Ua(t){let e=t?.code;return typeof e=="string"&&Na.has(e)}function _e(t,e){try{return t.write(e),!0}catch(n){if(Ua(n))return!1;throw n}}var rs=require("ws");var Zo=require("crypto");function E(t){return`${t}_${(0,Zo.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Wt=4*1024*1024,Vn=8*1024*1024,Jt=512,Kt=20*1024*1024;function q(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function mt(t,e){return{type:"server_error",code:t,message:e}}function U(t){return{type:"error",event_id:E("event"),error:t}}function Wn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var O=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Ma={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},Da={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Fa={format:!0,voice:!0,speed:!0};function Qo(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new O(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function ft(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new O("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(i=>!(i in Ma));if(o.length>0)throw new O(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let s={...e,outputModalities:[...e.outputModalities]};for(let[i,a]of Object.entries(r))switch(i){case"model":if(a!==null&&typeof a!="string")throw new O("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new O("instructions must be a string or null","instructions");s.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new O("modalities must be a non-empty array","modalities");let u=[];for(let d of a){if(d!=="text"&&d!=="audio")throw new O(`modality ${JSON.stringify(d)} is not "text" or "audio"`,"modalities");if(d==="audio"&&!n.voice)throw new O('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");u.includes(d)||u.push(d)}s.outputModalities=u;break}case"voice":if(a===null){delete s.voice;break}if(typeof a!="string")throw new O("voice must be a string or null","voice");if(!n.voice)throw new O("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new O(`${i} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,i);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new O("temperature must be a finite number or null","temperature");s.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 O(`${i} must be a positive integer, "inf" or null`,i);s.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new O("tools must be an array","tools");s.tools=a;break;case"tool_choice":s.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new O("metadata must be an object or null","metadata");s.metadata=a??null;break;case"turn_detection":{if(a===null){s.turnDetection=null;break}if(!n.turns)throw new O("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new O("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new O(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");s.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new O("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 O("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 O(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new O("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 u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new O("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new O("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Da))throw new O(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Qo(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=ft({input_audio_transcription:d.transcription},s,n);s.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let c=ft({turn_detection:d.turn_detection},s,n);s.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new O("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new O("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Fa))throw new O(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Qo(d.format,"audio.output.format"),d.speed!==void 0)throw new O("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new O("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new O("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function zt(t,e){return{id:e,object:"realtime.session",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 Jn(t,e){let n=t;if(!n||typeof n!="object")throw new O("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 O("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:E("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 O('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new O("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new O("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new O(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new O("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new O("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new O(`content part type ${String(i.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:E("item"),type:"message",role:r,content:o}}throw new O(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Kn(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Ba=1001,qa=1011,es=t=>t.slice(0,120),Ha=/^[A-Za-z0-9+/=]*$/,ja=2;function Ga(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ja)return!1;return!0}var gt=class{id=E("conn");ws;binding;onClosed;config=Wn();sessionId=E("sess");conversationId=E("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;turnTranscript={open:!1,text:""};lastCommittedTranscript=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.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:E("event"),session:zt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:E("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;(async()=>{try{for await(let r of n()){if(this.closed||e.signal.aborted)return;this.onTurnEvent(r)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(U(mt("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}})()}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"";if(n.length===0)return;this.turnTranscript.open=!0,this.turnTranscript.text+=n,this.config.inputAudioTranscription&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:E("event"),item_id:"input_audio_turn",content_index:0,delta:n});return}case"turn_start":{this.turnTranscript={open:!0,text:this.turnTranscript.text},this.send({type:"input_audio_buffer.speech_started",event_id:E("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.turnTranscript.text.trim(),r=n.length>0?n:null;this.turnTranscript={open:!1,text:""},this.lastCommittedTranscript=r,this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let o=E("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...r!==null?{transcript:r}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:E("event"),previous_item_id:s,item_id:o}),this.send({type:"conversation.item.created",event_id:E("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:o,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.inputAudioTranscription&&r!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:o,content_index:0,transcript:r}),this.config.turnDetection?.createResponse&&!this.inFlight&&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(q("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Wt){this.fail(q("frame_too_large",`frame exceeds the ${Wt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(q("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(q("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(U({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(mt(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=ft(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0}),this.send({type:"session.updated",event_id:E("event"),session:zt(this.config,this.sessionId)});return;case"conversation.item.create":{let n=Jn(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:E("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(q("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:E("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(q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:E("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(q("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:E("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(q("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Ha.test(e.audio)){this.send(U(q("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioBytes.length+n>Kt){this.send(U(q("buffer_full",`uncommitted input audio exceeds the ${Kt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);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.send({type:"input_audio_buffer.cleared",event_id:E("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(U(q("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=E("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;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:E("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:E("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])});return}case"output_audio_buffer.clear":{this.send(U(q("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":this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(U(q("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(U(q("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 s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(U(q("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(S=>S!=="text"&&S!=="audio")){this.send(U(q("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(q("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=E("req"),o=`resp_${r}`;this.activeResponseId=o;let s=this.items.length,{input:i,sawAudioOnlyItem:a}=Kn(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,d=typeof n.temperature=="number"?n.temperature:this.config.temperature,c=n.max_output_tokens??this.config.maxOutputTokens,l=c==="inf"||c===void 0?void 0:c,p=n.tools!==void 0?n.tools:this.config.tools,f=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,_={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...d!==void 0?{temperature:d}:{},...l!==void 0?{max_output_tokens:l}:{},...p!==void 0?{tools:p}:{},...f!==void 0?{tool_choice:f}:{}};for(let S of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(S);this.inFlight=(async()=>{let S=[],h=R=>{this.responseFlushed?this.send(R):S.push(R)},m=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:E("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:E("event"),response:this.responseObject(o,"in_progress")});for(let R of S)this.send(R);S.length=0,this.responseFlushed=!0}},y={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},g=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let R;try{R=await this.upstreamStream(_,r)}catch(v){this.emitUpstreamFault(v,o);return}try{for await(let v of R){if(this.cancelled)break;let b=v;if(b.type==="error"){let w=this.upstreamErrorBody(b);this.responseFlushed?this.send(U(w)):this.send({type:"response.failed",event_id:E("event"),response:this.failedResponse(o,w)});return}if(b.type==="response.output_text.delta"&&typeof b.delta=="string"){m(),y.messageOpen||(this.beginMessageItem(o,y.nextOutputIndex++),y.messageOpen=!0),h({type:"response.output_text.delta",event_id:E("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:b.delta}),y.messageText+=b.delta;continue}if(b.type==="response.function_call_arguments.delta"){m();let w=typeof b.delta=="string"?b.delta:"",x=typeof b.call_id=="string"&&b.call_id.length>0?b.call_id:`${o}_fc_${y.nextOutputIndex}`,T=y.tools.get(x);if(!T){let L=typeof b.name=="string"&&b.name.length>0?b.name:void 0;T={outputIndex:y.nextOutputIndex++,name:L,args:""},y.tools.set(x,T),h({type:"response.output_item.added",event_id:E("event"),response_id:o,output_index:T.outputIndex,item:{id:x,object:"realtime.item",type:"function_call",call_id:x,name:L??"",arguments:"",status:"in_progress"}})}typeof b.name=="string"&&b.name.length>0&&(T.name=b.name),T.args+=w,h({type:"response.function_call_arguments.delta",event_id:E("event"),item_id:x,response_id:o,output_index:T.outputIndex,call_id:x,name:T.name??"",delta:w});continue}if(b.type==="response.completed"){g=b.response??null;continue}}}catch(v){this.emitUpstreamFault(v,o);return}if(this.cancelled)return;this.closeOpenItems(o,y,s),m(),this.send({type:"response.done",event_id:E("event"),response:this.doneResponse(o,s,g)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Ga(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:E("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:E("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:E("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:E("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:E("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:E("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:E("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio;s&&this.send({type:"response.output_audio.done",event_id:E("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:E("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:E("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let i=[];s&&i.push({type:"output_audio"}),n.messageText.length>0&&i.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:E("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:E("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:E("event"),response_id:e,output_index:s.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,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=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}}emitUpstreamFault(e,n){if(this.cancelled)return;let r=mt(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(U(r)):this.send({type:"response.failed",event_id:E("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(U(q("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:E("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Jt&&(this.items.shift(),this.send(U({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Jt} 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>Vn){this.ws.close(Ba,es("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(qa,es(n)),this.teardown(n)}teardown(e){if(!this.closed){this.closed=!0,this.turnLaneAbort?.abort(),this.turnLaneAbort=null,this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(n=>ts(this.id,`binding release failed: ${n instanceof Error?n.message:String(n)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ts(this.id,e)}}},zn=[];function ts(t,e){zn.push({id:t,reason:e}),zn.length>256&&zn.shift()}var ht="/v1/realtime",Va=t=>t.slice(0,120);function Wa(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
16
+ ${o}`)}function Qn(t,e){let n=new Se.WebSocketServer({noServer:!0,maxPayload:Ha}),r=new Pe,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(l,p,g)=>{let c;try{c=new URL(l.url??"/","http://localhost")}catch{Wt(p,400,"malformed upgrade URL");return}if(p.on("error",()=>p.destroy()),p.on("close",()=>i.delete(p)),c.pathname!==Yn){i.add(p);return}s.add(p);let f=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){Wt(p,401,"invalid local proxy api key");return}let h;try{h=await a(l)}catch(b){let m=e.statusOf?.(b)??null;Wt(p,m?.status??500,"upstream resolver rejected the connection");return}u||p.destroyed||(f=!0,n.handleUpgrade(l,p,g,b=>{s.delete(p),o.add(b),b.on("close",()=>o.delete(b));try{new zn(b,h,r,e.statusOf)}catch{o.delete(b),b.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!f&&!p.destroyed&&Wt(p,500,"responses websocket upgrade failed")}).finally(()=>s.delete(p))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:p}=Xn();if(u)return p(),l;u=!0,t.off("upgrade",d);for(let c of s)c.destroy();s.clear();for(let c of i)c.destroy();i.clear();for(let c of o)c.close(1001,"server shutting down");let g=setTimeout(()=>{for(let c of o)c.readyState!==Se.WebSocket.CLOSED&&c.terminate()},2e3);return g.unref?.(),n.close(()=>{clearTimeout(g),p()}),l}}}var ms=require("@urun-sh/core");var as=require("@urun-sh/core"),za={no_capacity:429,queue_timeout:429,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Ya={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 Zn(t,e){let n=Ya[t.code];return e?`${n} (${e})`:n}function Jt(t){if(t==null)return null;let e=za[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 Kt(t){if(t.kind==="create-failed")return Jt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=as.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Jt(e?"cold_start_exceeded":"queue_timeout")}var Xa=at(require("os"),1),Qa=at(require("path"),1),Za=require("url"),eu=require("util");function us(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function zt(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}var tu=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function nu(t){let e=t?.code;return typeof e=="string"&&tu.has(e)}function Re(t,e){try{return t.write(e),!0}catch(n){if(nu(n))return!1;throw n}}var gs=require("ws");var fs=require("@urun-sh/core");var ls=require("crypto");function E(t){return`${t}_${(0,ls.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Yt=4*1024*1024,er=8*1024*1024,Xt=512,Qt=20*1024*1024;function H(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Ve(t,e){return{type:"server_error",code:t,message:e}}function M(t){return{type:"error",event_id:E("event"),error:t}}function tr(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var O=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},ru={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},ou={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},su={format:!0,voice:!0,speed:!0};function ds(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new O(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function wt(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new O("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(i=>!(i in ru));if(o.length>0)throw new O(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let s={...e,outputModalities:[...e.outputModalities]};for(let[i,a]of Object.entries(r))switch(i){case"model":if(a!==null&&typeof a!="string")throw new O("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new O("instructions must be a string or null","instructions");s.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new O("modalities must be a non-empty array","modalities");let u=[];for(let d of a){if(d!=="text"&&d!=="audio")throw new O(`modality ${JSON.stringify(d)} is not "text" or "audio"`,"modalities");if(d==="audio"&&!n.voice)throw new O('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");u.includes(d)||u.push(d)}s.outputModalities=u;break}case"voice":if(a===null){delete s.voice;break}if(typeof a!="string")throw new O("voice must be a string or null","voice");if(!n.voice)throw new O("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new O(`${i} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,i);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new O("temperature must be a finite number or null","temperature");s.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 O(`${i} must be a positive integer, "inf" or null`,i);s.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new O("tools must be an array","tools");s.tools=a;break;case"tool_choice":s.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new O("metadata must be an object or null","metadata");s.metadata=a??null;break;case"turn_detection":{if(a===null){s.turnDetection=null;break}if(!n.turns)throw new O("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new O("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new O(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");s.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new O("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 O("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 O(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new O("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 u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new O("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new O("audio.input must be an object","audio.input");for(let l of Object.keys(d))if(!(l in ou))throw new O(`audio.input field not supported by this backend: ${l}`,`audio.input.${l}`,"unsupported_field");if(d.format!==void 0&&ds(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let l=wt({input_audio_transcription:d.transcription},s,n);s.inputAudioTranscription=l.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let l=wt({turn_detection:d.turn_detection},s,n);s.turnDetection=l.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new O("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new O("audio.output must be an object","audio.output");for(let l of Object.keys(d))if(!(l in su))throw new O(`audio.output field not supported by this backend: ${l}`,`audio.output.${l}`,"unsupported_field");if(d.format!==void 0&&ds(d.format,"audio.output.format"),d.speed!==void 0)throw new O("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new O("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new O("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function Zt(t,e){return{id:e,object:"realtime.session",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 nr(t,e){let n=t;if(!n||typeof n!="object")throw new O("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 O("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:E("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 O('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new O("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new O("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new O(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new O("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new O("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new O(`content part type ${String(i.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:E("item"),type:"message",role:r,content:o}}throw new O(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function rr(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var iu=1001,au=1011,cs=t=>t.slice(0,120),uu=/^[A-Za-z0-9+/=]*$/,du=2;function lu(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>du)return!1;return!0}var _t=class{id=E("conn");ws;binding;onClosed;config=tr();sessionId=E("sess");conversationId=E("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;turnTranscript={open:!1,text:""};lastCommittedTranscript=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.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:E("event"),session:Zt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:E("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;(async()=>{try{for await(let r of n()){if(this.closed||e.signal.aborted)return;this.onTurnEvent(r)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(M(Ve("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}})()}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"";if(n.length===0)return;this.turnTranscript.open=!0,this.turnTranscript.text+=n,this.config.inputAudioTranscription&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:E("event"),item_id:"input_audio_turn",content_index:0,delta:n});return}case"turn_start":{this.turnTranscript={open:!0,text:this.turnTranscript.text},this.send({type:"input_audio_buffer.speech_started",event_id:E("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.turnTranscript.text.trim(),r=n.length>0?n:null;this.turnTranscript={open:!1,text:""},this.lastCommittedTranscript=r,this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let o=E("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...r!==null?{transcript:r}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:E("event"),previous_item_id:s,item_id:o}),this.send({type:"conversation.item.created",event_id:E("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:E("event"),item_id:o,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.inputAudioTranscription&&r!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:o,content_index:0,transcript:r}),this.config.turnDetection?.createResponse&&!this.inFlight&&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(H("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Yt){this.fail(H("frame_too_large",`frame exceeds the ${Yt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(H("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(H("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(M({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Ve(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=wt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0}),this.send({type:"session.updated",event_id:E("event"),session:Zt(this.config,this.sessionId)});return;case"conversation.item.create":{let n=nr(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:E("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(M(H("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:E("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(M(H("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:E("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(M(H("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:E("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(M(H("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!uu.test(e.audio)){this.send(M(H("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioBytes.length+n>Qt){this.send(M(H("buffer_full",`uncommitted input audio exceeds the ${Qt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);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.send({type:"input_audio_buffer.cleared",event_id:E("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(M(H("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=E("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;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:E("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:E("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])});return}case"output_audio_buffer.clear":{this.send(M(H("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":this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(M(H("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(M(H("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(M({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 s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(M(H("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(h=>h!=="text"&&h!=="audio")){this.send(M(H("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(M(H("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=E("req"),o=`resp_${r}`;this.activeResponseId=o;let s=this.items.length,{input:i,sawAudioOnlyItem:a}=rr(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,d=typeof n.temperature=="number"?n.temperature:this.config.temperature,l=n.max_output_tokens??this.config.maxOutputTokens,p=l==="inf"||l===void 0?void 0:l,g=n.tools!==void 0?n.tools:this.config.tools,c=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,f={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...d!==void 0?{temperature:d}:{},...p!==void 0?{max_output_tokens:p}:{},...g!==void 0?{tools:g}:{},...c!==void 0?{tool_choice:c}:{}};for(let h of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(h);this.inFlight=(async()=>{let h=[],b=R=>{this.responseFlushed?this.send(R):h.push(R)},m=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:E("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:E("event"),response:this.responseObject(o,"in_progress")});for(let R of h)this.send(R);h.length=0,this.responseFlushed=!0}},y={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},w=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let R;try{R=await this.upstreamStream(f,r)}catch(_){this.upstreamTurnFault(_,o);return}try{for await(let _ of R){if(this.cancelled)break;let k=_;if(k.type==="error"){let v=this.upstreamErrorBody(k);this.responseFlushed?this.send(M(v)):this.send({type:"response.failed",event_id:E("event"),response:this.failedResponse(o,v)});return}if(k.type==="response.output_text.delta"&&typeof k.delta=="string"){m(),y.messageOpen||(this.beginMessageItem(o,y.nextOutputIndex++),y.messageOpen=!0),b({type:"response.output_text.delta",event_id:E("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:k.delta}),y.messageText+=k.delta;continue}if(k.type==="response.function_call_arguments.delta"){m();let v=typeof k.delta=="string"?k.delta:"",x=typeof k.call_id=="string"&&k.call_id.length>0?k.call_id:`${o}_fc_${y.nextOutputIndex}`,I=y.tools.get(x);if(!I){let T=typeof k.name=="string"&&k.name.length>0?k.name:void 0;I={outputIndex:y.nextOutputIndex++,name:T,args:""},y.tools.set(x,I),b({type:"response.output_item.added",event_id:E("event"),response_id:o,output_index:I.outputIndex,item:{id:x,object:"realtime.item",type:"function_call",call_id:x,name:T??"",arguments:"",status:"in_progress"}})}typeof k.name=="string"&&k.name.length>0&&(I.name=k.name),I.args+=v,b({type:"response.function_call_arguments.delta",event_id:E("event"),item_id:x,response_id:o,output_index:I.outputIndex,call_id:x,name:I.name??"",delta:v});continue}if(k.type==="response.completed"){w=k.response??null;continue}}}catch(_){this.upstreamTurnFault(_,o);return}if(this.cancelled)return;this.closeOpenItems(o,y,s),m(),this.send({type:"response.done",event_id:E("event"),response:this.doneResponse(o,s,w)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(lu(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(M({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:E("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:E("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:E("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:E("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:E("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:E("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:E("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio;s&&this.send({type:"response.output_audio.done",event_id:E("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:E("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:E("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let i=[];s&&i.push({type:"output_audio"}),n.messageText.length>0&&i.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:E("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:E("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:E("event"),response_id:e,output_index:s.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,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=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(Ve("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 W){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof fs.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Ve(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(M(r)):this.send({type:"response.failed",event_id:E("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(M(H("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:E("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Xt&&(this.items.shift(),this.send(M({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Xt} 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>er){this.ws.close(iu,cs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(M(e)),this.ws.close(au,cs(n)),this.teardown(n)}teardown(e){if(!this.closed){this.closed=!0,this.turnLaneAbort?.abort(),this.turnLaneAbort=null,this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(n=>ps(this.id,`binding release failed: ${n instanceof Error?n.message:String(n)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ps(this.id,e)}}},or=[];function ps(t,e){or.push({id:t,reason:e}),or.length>256&&or.shift()}var vt="/v1/realtime",cu=t=>t.slice(0,120);function pu(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
17
17
  Connection: close\r
18
18
  Content-Type: text/plain\r
19
19
  \r
20
- ${Va(n)}\r
21
- `),t.destroy()}function Ja(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
22
- `}function Ka(t){_e(process.stdout,t)}function za(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Yn(t){return t.audioSession?.audio.sessionId??void 0}function Yt(t,e){let n=new rs.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==ht)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=E("rtup"),d=za(o),c=v=>{(e.log??Ka)(Ja(v))};c({stage:"accept",conn:u,model:d}),s.resume();let l=new AbortController,p=null,f=v=>{p??=v,l.abort(new Error(p))},_=()=>f("client socket closed"),S=()=>f("client socket closed (half-close)"),h=v=>f(`client socket error: ${v.message}`);s.once("close",_),s.once("end",S),s.once("error",h);let m=()=>{s.removeListener("close",_),s.removeListener("end",S),s.removeListener("error",h)},y=v=>{c({stage:"close",conn:u,model:d,...v})},g=v=>{let b=v,w=b.session!=null&&typeof b.session.sendResponseCreate=="function",x=b.clients!=null&&typeof b.clients.createResponse=="function";if(!w&&!x)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((T,L)=>{n.handleUpgrade(o,s,i,I=>{try{new gt({ws:I,binding:v,onClosed:(z,X)=>{y({while:"live",reason:X.reason})}}),c({stage:"admit",conn:u,model:d,...Yn(v)===void 0?{}:{session:Yn(v)}}),T()}catch(z){L(z)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,l.signal).then(async v=>{if(l.signal.aborted){m();let b=Yn(v);try{await v.release?.()}catch(w){y({while:"queued",...b===void 0?{}:{session:b},reason:p??"client socket closed",release_failed:w instanceof Error?w.message:String(w)});return}y({while:"queued",...b===void 0?{}:{session:b},reason:p??"client socket closed",released:!0}),s.destroy();return}m(),await g(v)}).catch(v=>{let b=v instanceof ns.SessionFailedError?Gt(v):null,w=null;if(v!==null&&typeof v=="object"&&"status"in v){let L=v.status;typeof L=="number"&&(w=L)}let x=w??b?.status??502,T=v instanceof Error?v.message:String(v);y({while:"queued",...l.signal.aborted?{reason:p??"client socket closed"}:{reason:T,status:x}}),s.destroyed||Wa(s,x,T)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}var rd=require("http");var os="/v1/images/generations",Xt="/v1/images/edits";function ss(t){return t===os||t===Xt}var is="/v1/images/models";async function as(t,e,n){if(t){if(t.model=oe({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}},Ya=16*1024*1024,us=64*1024*1024;function ds(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 yt(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}:{}}}))}var fe=class extends Error{};async function Xa(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new fe(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new fe(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function ls(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let l of o){if(l.type==="error"){let p=l.error??{};throw new $(502,`image upstream error: ${String(p.message??"upstream reported an error")}`)}if(l.type==="response.completed"){s=l.response??null;break}}if(s===null)throw new $(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=s.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new $(502,`image upstream returned ${Array.isArray(i)?i.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=[],u=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(u,"base64");if(ds(d)===null)throw new $(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function cs(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 ps(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 yt(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 fs(t,e){t&&(t.outputUnits=e.images.length)}function ms(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 Qa={model:!0,prompt:!0,response_format:!0,n:!0};async function gs(t,e,n){let r=n.maxBodyBytes??us;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${os}`);let o;try{o=JSON.parse((await Xa(t,r)).toString("utf8")||"{}")}catch(l){throw l instanceof fe?new $(413,l.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 s=o;for(let l of Object.keys(s))if(!Qa[l])throw new $(400,`request field "${l}" 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.`,l);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string","prompt");let a=s.model===void 0?void 0:s.model;if(a!==void 0&&typeof a!="string")throw new $(400,"model must be a string","model");await as(n.turn,n.clients,a);let u=s.n??1;if(u!==1)throw new $(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new $(400,`response_format ${JSON.stringify(d)} 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",i.length,i.length),!await ps(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:i}];try{let l=await ls(n.clients,a,c,n.turn?se(n.turn):void 0);fs(n.turn,l),ms(e,l)}catch(l){throw cs(l)}}catch(o){if(o instanceof fe){yt(e,new $(413,o.message));return}if(o instanceof $){yt(e,o);return}throw o}}var Za={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function hs(t,e,n){let r=n.maxBodyBytes??us,o=n.maxImagePartBytes??Ya;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${Xt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new $(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i=t[Symbol.asyncIterator](),a=0,u=new ReadableStream({async pull(h){try{let m=await i.next();if(m.done){h.close();return}if(a+=m.value.length,a>r){h.error(new fe(`request body exceeds the ${r}-byte limit`));return}h.enqueue(m.value)}catch(m){h.error(m)}},cancel(){i.return?.()}}),d;try{let h=new Headers;for(let[g,R]of Object.entries(t.headers))if(typeof R=="string")h.set(g,R);else if(Array.isArray(R))for(let v of R)h.append(g,v);let m={method:"POST",headers:h,body:u,duplex:"half"};d=await new Request(`https://proxy.internal${t.url??"/"}`,m).formData()}catch(h){throw h instanceof fe?new $(413,h.message):new $(400,`malformed multipart body: ${String(h instanceof Error?h.message:h)}`)}let c=d.get("prompt");if(typeof c!="string"||c.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string field","prompt");let l=d.get("model");if(l!==null&&typeof l!="string")throw new $(400,"model must be a string field","model");let p=l===null?void 0:l;await as(n.turn,n.clients,p);let f=d.get("response_format")??"b64_json";if(f!=="b64_json")throw new $(400,`response_format ${JSON.stringify(f)} 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 h of d.keys())if(!Za[h])throw new $(400,`form field "${h}" 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[]).`,h);let _=[];for(let h of["image","image[]"])for(let m of d.getAll(h)){if(!(m 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",h);if(m.size>o)throw new $(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,h);let y=new Uint8Array(await m.arrayBuffer()),g=ds(y);if(g===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)",h);_.push({bytes:y,mime:g})}if(_.length===0)throw new $(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",c.length,c.length),!await ps(n.imageModels,p,"edit",e))return;let S=[{type:"input_text",text:c}];for(let{bytes:h,mime:m}of _)S.push({type:"input_image",image_url:`data:${m};base64,${Buffer.from(h).toString("base64")}`});try{let h=await ls(n.clients,p,S,n.turn?se(n.turn):void 0);fs(n.turn,h),ms(e,h)}catch(h){throw cs(h)}}catch(s){if(s instanceof fe){yt(e,new $(413,s.message));return}if(s instanceof $){yt(e,s);return}throw s}}var wt="/v1/audio/speech";function bs(t){return t===wt}var ys=4096,eu=18e4,tu=5e3,nu=64*1024*1024,_s=8,ws=5,Zt="voice_applied",ru="X-Urun-Voice-Applied",C=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Xn(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 De=class extends Error{},en=class extends C{constructor(e){super(502,e)}};async function ou(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new De(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new De(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function su(t,e,n){if(t){if(t.model=oe({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 iu(t,e){t&&(t.outputUnits=e/(24e3*2))}var au=2;function uu(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>au)return!1;return!0}function du(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 vs=new WeakMap,Qt=new WeakMap;function lu(t,e){let n=Qt.get(t)??0;if(n>=_s)throw new C(503,`this model's speech queue is full \u2014 ${_s} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${ws}s`,void 0,ws);Qt.set(t,n+1);let r=vs.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return vs.set(t,s),(async()=>{await r;try{return await e()}finally{Qt.set(t,(Qt.get(t)??1)-1),o()}})()}async function cu(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new C(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(i){if(!(i instanceof K))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function _t(t){return t instanceof C?t:t instanceof N?new C(404,t.message):new C(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function pu(t,e,n,r,o,s,i){return lu(e,async()=>{if(i?.()===!0)return null;let a=[],u=!1,d=0,c=!1,l=!1,p,f=new Promise(R=>{p=R}),_=()=>{c&&!l&&d>=o.quietRunFrames&&(l=!0,p())},S=e.onOutputAudio(R=>{let v=Buffer.from(R,"base64");if(v.byteLength===0)return;let b=uu(v);if(!u){if(b)return;u=!0}a.push(v),d=b?d+1:0,_()}),h=null,m,y,g;try{g=(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 v=new Promise(T=>{y=setTimeout(T,s.capMs)}),b=!1;for(;;){let T=g.next(),L=await Promise.race([T,v]);if(L===void 0){b=!0,T.catch(()=>{});break}if(L.done)break;let I=L.value;if(I.type==="error"){let z=I.error??{};throw await g.return?.(),new C(502,`speech upstream error: ${String(z.message??"upstream reported an error")}`)}if(I.type==="response.completed"){h=I.response??null,c=!0,_(),await g.return?.();break}}if(clearTimeout(y),b)throw new C(504,`the speech turn produced no terminal event within ${s.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(h===null)throw new C(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let w=!1;if(await Promise.race([f,new Promise(T=>{m=setTimeout(()=>{w=!0,T()},o.capMs)})]),m!==void 0&&clearTimeout(m),r.voice!==void 0){let T=h[Zt];if(typeof T!="string"||T!==r.voice){let L=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof T=="string"?`${Zt} ${JSON.stringify(T)}`:`no ${Zt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw l?new en(L):new C(502,L)}}if(!u)throw new C(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(w&&!l&&d<1)throw new C(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`);let x=d>0?a.slice(0,a.length-d):a;return{pcm:Buffer.concat(x),completed:h}}catch(R){throw R instanceof en||await cu(t,n,g,s.returnBoundMs),R}finally{m!==void 0&&clearTimeout(m),y!==void 0&&clearTimeout(y),S()}})}async function fu(t,e,n){let r;try{r=await t(e)}catch(o){throw _t(o)}return r?!0:(Xn(n,new C(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 mu={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},gu="wav, pcm";async function ks(t,e,n){let r=n.maxBodyBytes??nu,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new C(405,`${String(t.method)} is not supported on ${wt}`);let i;try{i=JSON.parse((await ou(t,r)).toString("utf8")||"{}")}catch(g){throw g instanceof De?new C(413,g.message):new C(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new C(400,"request body must be a JSON object");let a=i;for(let g of Object.keys(a))if(!mu[g])throw new C(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 u=a.input;if(typeof u!="string"||u.trim().length===0)throw new C(400,"input is required and must be a non-empty string","input");if(u.length>ys)throw new C(400,`input is ${u.length} chars \u2014 over the ${ys}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new C(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new C(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new C(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 ${wt} against a stale copy of the list`);let l;try{l=await n.clients.speechVoices(d)}catch(g){throw _t(g)}if(l.defect!==null)throw new C(500,`the voice set for this model cannot be resolved: ${l.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let p=typeof c=="string"?c:void 0;if(p!==void 0&&l.published.length>0&&!l.published.includes(p))throw new C(400,`voice ${JSON.stringify(p)} is not one of the voices this model publishes \u2014 accepted voices: ${l.published.join(", ")}`,"voice");let f=a.response_format??"wav";if(f!=="wav"&&f!=="pcm")throw new C(400,`response_format ${JSON.stringify(f)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${gu} \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 C(400,"stream_format, when present, must be a string","stream_format");let _=a.speed;if(_!==void 0){if(typeof _!="number"||!Number.isFinite(_))throw new C(400,"speed, when present, must be a number","speed");if(_!==1)throw new C(400,`speed=${JSON.stringify(_)} 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 S=a.instructions;if(S!==void 0){if(typeof S!="string")throw new C(400,"instructions, when present, must be a string","instructions");if(S.trim().length>0)throw new C(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 su(n.turn,n.clients,d);let h=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",h,h),!await fu(n.speechModels,d,e))return;if(typeof n.clients.openAudioOn!="function")throw new C(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 C(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 C(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(s())return;let m;try{m=await n.clients.speechSessionHandle(d)}catch(g){throw _t(g)}let y;try{y=await n.clients.openAudioOn(m)}catch(g){throw _t(g)}n.turn&&(n.turn.sessionId=y.sessionId);try{let g=await pu(n.clients,y,m,{model:d,text:u,...p!==void 0?{voice:p}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??eu,returnBoundMs:n.turnReturnBoundMs??tu},s);if(g===null||s())return;if(iu(n.turn,g.pcm.byteLength),e.statusCode=200,p===void 0){let R=g.completed[Zt];typeof R=="string"&&e.setHeader(ru,R)}f==="wav"?(e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([du(g.pcm.byteLength),g.pcm]))):(e.setHeader("content-type","audio/pcm"),e.end(g.pcm))}catch(g){throw _t(g)}}catch(i){if(i instanceof De){Xn(e,new C(413,i.message));return}if(i instanceof C){Xn(e,i);return}throw i}}var nn="/v1/usage/requests",Ss=1e4,hu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,we=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},D=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},tn=class extends D{constructor(e){super(e),this.name="UsageWithholdingError"}},As=1024*1024;function er(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new we(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new we(`"${e}" must be an array of uuid strings`);if(n.length>Ss)throw new we(`"${e}" carries ${n.length} ids; at most ${Ss} 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 s of n){if(typeof s!="string"||!hu.test(s))throw new we(`"${e}" contains ${JSON.stringify(s)}, 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(s)||(o.add(s),r.push(s))}return r}function Os(t){return er(t,"inference_ids")}var yu=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","cost_nano_usd","price_version","priced_at"];function Fe(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new D(`${n}: ${e} is not a non-empty string (got ${Be(r)})`);return r}function Qn(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new D(`${n}: ${e} is neither null nor a non-empty string (got ${Be(r)})`);return r}function vt(t,e,n,r){let o=t[e];if(o===null)return null;let s=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(s))throw new D(`${n}: ${e} is not a number (got ${Be(o)})`);if(r&&!Number.isSafeInteger(s))throw new D(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(s<0)throw new D(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var _u=40,Rs=64,xs=600;function Is(t){let e=Object.keys(t).sort(),r=e.slice(0,_u).map(o=>o.length>Rs?`${o.slice(0,Rs)}\u2026`:o).join(", ");return r.length>xs&&(r=`${r.slice(0,xs)}\u2026`),`${e.length} keys present: [${r}]`}function Be(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function Zn(t){_e(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
23
- `)}function wu(t,e){let n;try{n=t(e)}catch{Es(t,e);return}vu(n)&&Promise.resolve(n).catch(()=>{Es(t,e)})}function vu(t){return typeof t?.then=="function"}function Es(t,e){if(t!==Zn)try{Zn(e)}catch{}}function Ts(t,e=Zn){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?Is(t):Be(t);throw new D(`the usage surface answered without a "requests" array: got ${Be(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(bu(n[o],s))}catch(i){if(i instanceof tn||!(i instanceof D))throw i;wu(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new D(`the usage surface returned ${n.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function bu(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new D(`${e} is not an object: got ${Be(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new tn(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let o of yu)if(!Object.hasOwn(n,o))throw new D(`${e} has no "${o}" column (${Is(n)})`);let r=vt(n,"http_status",e,!0);if(r===null)throw new D(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Fe(n,"inference_id",e),model_id:Fe(n,"model_id",e),identity_kind:Fe(n,"identity_kind",e),variant:Qn(n,"variant",e),task:Fe(n,"task",e),http_status:r,started_at:Fe(n,"started_at",e),completed_at:Fe(n,"completed_at",e),prompt_tokens:vt(n,"prompt_tokens",e,!0),completion_tokens:vt(n,"completion_tokens",e,!0),output_units:vt(n,"output_units",e,!1),cost_nano_usd:vt(n,"cost_nano_usd",e,!0),price_version:Qn(n,"price_version",e),priced_at:Qn(n,"priced_at",e)}}function rn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new D(`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(s.inference_id))throw new D(`the usage surface returned ${s.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(s.inference_id)}}var ln=require("@urun-sh/core");var bt="/partners/huggingface/v1/billing/requests";function ku(t){return er(t,"requestIds")}function Su(t){return t>=200&&t<=399}function Ru(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Su(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Ps(t,e){let n=ku(t),r=await e(n);return rn(r,n),Ru(r)}var xu={"/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"};function Eu(t){return xu[t]??null}var Ns=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function Au(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Ou(t){return t==="surface"}function Iu(t){let e=t?.ledgerFailureReason;return Ns.includes(e)?e:"unknown"}var Tu=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Cs=["priced","unpriced"],Pu={written:Cs,already_written:Cs,skipped:Tu,failed:Ns},Us=Object.entries(Pu).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Cu(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function $u(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 Lu=256,$s=4096,St=12e4,Nu=250,Uu=8e3,Te=[],Ls=new Set,Rt=0,kt=!1;function Ms(){return Te.length}function Ds(t=Date.now()){let e=Te[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var Mu=new Set;function Du(){return Rt===0&&Te.length===0}function Fu(){if(Du()){kt=!1;for(let t of[...Mu])t()}}function Fs(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
24
- `}function Bu(t){_e(process.stdout,t)}function Bs(t,e){try{t(e)}catch{}}function qs(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Bu,o=Eu(e.path);if(o===null)return;let s=c=>{try{n.observe(c)}catch{}},i=(c,l)=>{s({outcome:"skipped",reason:c}),Bs(r,Fs("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:c,detail:l}))};if(e.status===null){i("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){i("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"){i("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("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}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let d={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:$u(e),completed_at:e.ts,billable_outcome:Cu(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,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(Te.length>=$s){i("queue_full",`${Te.length} ledger writes are already waiting (capacity ${$s}, ${Rt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Te.push({entry:d,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Rt<Lu&&(Rt+=1,qu())}async function qu(){try{for(;;){let t=Hu();if(t===void 0)return;Ls.add(t);try{await ju(t)}finally{Ls.delete(t)}}}finally{Rt-=1,Fu()}}function Hu(){let t=Date.now();for(;;){let e=Te.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<St)return e;qe(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 ${St}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 ju(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);qe(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 s=Au(o);if(s!==null){qe(t,{outcome:"already_written",reason:s.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:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=Iu(o),a=Date.now()-t.queuedAt;if(kt){qe(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(Ou(i)&&a<St){if(await Vu(Gu(t.attempts)),kt||Date.now()-t.queuedAt>=St){let u=Date.now()-t.queuedAt;qe(t,{outcome:"failed",reason:kt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:kt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${St}ms dwell bound (waited ${u}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}qe(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Gu(t){return Math.min(Uu,Nu*2**Math.max(0,t-1))}function Vu(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function qe(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Bs(t.report,Fs(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var tr=tt(require("crypto"),1),Wu="urun-runtime-key-v1";function Ju(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return tr.createHmac("sha256",t).update(`${Wu}|${e}`,"ascii").digest("base64url")}var Ku="decision-intake",on=6e4,zu=on/1e3+5,Hs=3,nr=15;function Yu(t,e,n=60,r=Math.floor(Date.now()/1e3)){if(!t)throw new Error("cannot mint a decision token without a secret");let o=d=>Buffer.from(d).toString("base64url"),s=o(JSON.stringify({alg:"HS256",typ:"JWT"})),i={tenant:e.tenant,app:e.app,fn:e.fn,...e.provider?{provider:e.provider}:{},session_id:"decision-intake",sub:`machine:${e.tenant}/${e.app}/${e.fn}`,aud:Ku,iat:r,exp:r+Math.max(1,n)},a=o(JSON.stringify(i)),u=tr.createHmac("sha256",t).update(`${s}.${a}`,"ascii").digest("base64url");return`${s}.${a}.${u}`}function Xu(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.runtime_id=="string"&&e.runtime_id!==""&&typeof e.ready=="boolean"&&typeof e.address=="string"&&e.address!==""&&typeof e.last_seen=="string"&&!Number.isNaN(Date.parse(e.last_seen))}async function Qu(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/runtimes?app=${encodeURIComponent(t.app)}&fn=${encodeURIComponent(t.fn)}`,r;try{r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"},signal:AbortSignal.timeout(on)})}catch(u){throw(u instanceof Error?u.name:void 0)==="TimeoutError"?new ae(`runtime presence read for (app=${t.app} fn=${t.fn}) timed out after ${on}ms \u2014 the control plane is not answering; no replica can be discovered`):u}if(!r.ok)throw new Error(`runtime presence read failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.runtimes))throw new Error(`runtime presence read returned no "runtimes" array (GET ${n})`);let s=[],i=[];for(let u of o.runtimes){if(!Xu(u)){s.push(JSON.stringify(u));continue}i.push(u)}if(s.length>0)throw new Error(`runtime presence read for (app=${t.app} fn=${t.fn}) returned ${s.length} malformed presence row(s) \u2014 the control plane's runtimes schema drifted (runtime_id/address/ready/last_seen are all required): ${s.slice(0,3).join("; ")}`);let a=(t.nowMs??Date.now())/1e3;return i.filter(u=>u.ready===!0&&a-Date.parse(u.last_seen)/1e3<=nr)}var Zu=nr*1e3,ed=nr*500,td=256,sn=class{constructor(e){this.opts=e;this.nowMs=e.nowMs??Date.now}opts;replicas=new Map;nowMs;presenceCache=new Map;get enabled(){return this.opts.secret!==""}async targetFor(e){let n=await this.opts.targetFor(e);return n.sharedApp===!0&&this.opts.shared===void 0?null:n}async decide(e,n){let r=await this.targetFor(n);if(r===null)throw new ae("the shared-endpoint lane keeps the session dial \u2014 the stateless direct path serves caller-org functions");let o=r.appSlug,s=r.fnName??this.opts.fnName,i=r.sharedApp===!0,a=i?this.opts.shared.apiKey:this.opts.apiKey,u=`${a}\0${o}\0${s}`,d=await this.ensureRows(u,a,o,s);if(d.length===0)throw new ae(`no ready runtime for (org app=${o} fn=${s}) \u2014 nothing is serving decisions right now`);let c=null;for(let l=0;l<Hs;l++){let p=this.pick(d);if(p===null)throw new ae(`every discovered runtime for app=${o} failed at the transport layer \u2014 no replica took the decision`);let f=i&&r.sharedOrgId?r.sharedOrgId:this.opts.orgId,_=Yu(Ju(this.opts.secret,f),{tenant:this.opts.orgId,app:o,fn:s,...i&&r.sharedOrgId?{provider:r.sharedOrgId}:{}},zu);try{return{...await this.post(p,e,_),target:{...r,fnName:s}}}catch(S){if(S instanceof Pe)throw S;c=S;let h=this.replicas.get(p)??{outstanding:0,cooldownUntil:0};h.cooldownUntil=this.nowMs()+5e3,this.replicas.set(p,h);let m=this.presenceCache.get(u);m&&(m.rows=m.rows.filter(y=>y.address!==p),m.rows.length===0&&this.presenceCache.delete(u))}}throw new ae(`no runtime for app=${o} answered within ${Hs} attempts: ${String(c instanceof Error?c.message:c)}`)}async ensureRows(e,n,r,o){let s=this.presenceCache.get(e);if(s)if(this.nowMs()-s.fetchedAtMs>Zu)this.presenceCache.delete(e);else return this.nowMs()-s.fetchedAtMs>ed&&!s.refreshing&&(s.refreshing=!0,this.readPresence(n,r,o).then(a=>{this.presenceCache.set(e,{rows:a,fetchedAtMs:this.nowMs(),refreshing:!1})}).catch(()=>{s.refreshing=!1})),s.rows;let i=await this.readPresence(n,r,o);for(;this.presenceCache.size>=td;){let a=this.presenceCache.keys().next();if(a.done)break;this.presenceCache.delete(a.value)}return this.presenceCache.set(e,{rows:i,fetchedAtMs:this.nowMs(),refreshing:!1}),i}readPresence(e,n,r){return Qu({apiUrl:this.opts.apiUrl,apiKey:e,app:n,fn:r,fetchImpl:this.opts.fetchImpl,nowMs:this.nowMs()})}pick(e){let n=this.nowMs(),r=null,o=1/0;for(let s of e){let i=this.replicas.get(s.address);if(i!==void 0&&i.cooldownUntil>n)continue;let a=i?.outstanding??0;a<o&&(r=s.address,o=a)}return r}async post(e,n,r){let o=this.replicas.get(e)??{outstanding:0,cooldownUntil:0};o.outstanding+=1,this.replicas.set(e,o);try{let s=await fetch(`${e.replace(/\/+$/,"")}/v1/decision`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.opts.timeoutMs??on)}),i=null;try{i=await s.json()}catch{i={error:{message:`runtime answered ${s.status} with a non-JSON body`,type:"upstream_error"}}}if(s.status>=500)throw new Error(`runtime ${e} answered ${s.status}`);if(s.status>=400)throw new Pe(s.status,i);return{status:s.status,body:i,completed:nd(i)}}finally{o.outstanding-=1}}};function nd(t){if(t===null||typeof t!="object")return null;let e=t,n=e.usage;if(n===null||typeof n!="object")return e;let r=n;return{...e,usage:{input_tokens:r.prompt_tokens??r.input_tokens,output_tokens:r.completion_tokens??r.output_tokens}}}var Pe=class extends Error{constructor(n,r){super(`runtime answered ${n}`);this.status=n;this.body=r}status;body},ae=class extends Error{};function sr(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function G(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function V(t,e,n,r="invalid_request_error",o){G(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function ir(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);G(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function ue(t,e,n,r){G(t,e,{type:"error",error:{type:n,message:r}})}function de(t,e,n){if(e==="anthropic"){G(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}G(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var od=64*1024*1024,xt=class extends Error{};async function js(t,e=od){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new xt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function He(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 Vs(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function an(t){let e=Vs(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Gs(t){let e=an(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 sd(t,e){let n=Vs(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function id(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let d=n[u];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function ad(t,e){let n=id(e);n&&(t.timing=n)}function me(t,e){sd(t,e),ad(t,e)}async function cn(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 Ws(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 ud(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 un=class extends Error{};function dd(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 un(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function ld(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:dd(n.role,n.content)})}return e}function rr(t){return Ne(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 cd(t,e,n,r,o,s){let i=lt(s.id),a=t.stream===!0;if(s.model=oe(t),s.stream=a,await cn(s,e,typeof t.model=="string"?t.model:void 0),a){let m;try{m=await pt({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(y){if(y instanceof N){de(r,"openai",y);return}if(y instanceof re){V(r,y.status,y.message);return}throw y}sr(r);for await(let y of m.events)y.type==="error"&&(s.streamError=!0),y.type==="response.completed"&&me(s,y.response),r.write(`event: ${String(y.type??"message")}
20
+ ${cu(n)}\r
21
+ `),t.destroy()}function fu(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
22
+ `}function mu(t){Re(process.stdout,t)}function gu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function sr(t){return t.audioSession?.audio.sessionId??void 0}function en(t,e){let n=new gs.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==vt)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=E("rtup"),d=gu(o),l=_=>{(e.log??mu)(fu(_))};l({stage:"accept",conn:u,model:d}),s.resume();let p=new AbortController,g=null,c=_=>{g??=_,p.abort(new Error(g))},f=()=>c("client socket closed"),h=()=>c("client socket closed (half-close)"),b=_=>c(`client socket error: ${_.message}`);s.once("close",f),s.once("end",h),s.once("error",b);let m=()=>{s.removeListener("close",f),s.removeListener("end",h),s.removeListener("error",b)},y=_=>{l({stage:"close",conn:u,model:d,..._})},w=_=>{let k=_,v=k.session!=null&&typeof k.session.sendResponseCreate=="function",x=k.clients!=null&&typeof k.clients.createResponse=="function";if(!v&&!x)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((I,T)=>{n.handleUpgrade(o,s,i,$=>{try{new _t({ws:$,binding:_,onClosed:(Y,Z)=>{y({while:"live",reason:Z.reason})}}),l({stage:"admit",conn:u,model:d,...sr(_)===void 0?{}:{session:sr(_)}}),I()}catch(Y){T(Y)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,p.signal).then(async _=>{if(p.signal.aborted){m();let k=sr(_);try{await _.release?.()}catch(v){y({while:"queued",...k===void 0?{}:{session:k},reason:g??"client socket closed",release_failed:v instanceof Error?v.message:String(v)});return}y({while:"queued",...k===void 0?{}:{session:k},reason:g??"client socket closed",released:!0}),s.destroy();return}m(),await w(_)}).catch(_=>{let k=_ instanceof ms.SessionFailedError?Kt(_):null,v=null;if(_!==null&&typeof _=="object"&&"status"in _){let T=_.status;typeof T=="number"&&(v=T)}let x=v??k?.status??502,I=_ instanceof Error?_.message:String(_);y({while:"queued",...p.signal.aborted?{reason:g??"client socket closed"}:{reason:I,status:x}}),s.destroyed||pu(s,x,I)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}var Id=require("http");var Q=class extends Error{};async function tn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Q(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new Q(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function nn(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new Q(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[d,l]of Object.entries(t.headers))if(typeof l=="string")i.set(d,l);else if(Array.isArray(l))for(let p of l)i.append(d,p);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof Q?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var hs="/v1/images/generations",rn="/v1/images/edits";function ys(t){return t===hs||t===rn}var ws="/v1/images/models";async function _s(t,e,n){if(t){if(t.model=re({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 L=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},hu=16*1024*1024,vs=64*1024*1024;function bs(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 bt(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 ks(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let p of o){if(p.type==="error"){let g=p.error??{};throw new L(502,`image upstream error: ${String(g.message??"upstream reported an error")}`)}if(p.type==="response.completed"){s=p.response??null;break}}if(s===null)throw new L(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=s.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new L(502,`image upstream returned ${Array.isArray(i)?i.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=[],u=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(u,"base64");if(bs(d)===null)throw new L(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function Ss(t){return t instanceof L?t:t instanceof N?new L(404,t.message):new L(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Rs(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 bt(r,new L(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 xs(t,e){t&&(t.outputUnits=e.images.length)}function Es(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 yu={model:!0,prompt:!0,response_format:!0,n:!0};async function As(t,e,n){let r=n.maxBodyBytes??vs;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${hs}`);let o;try{o=JSON.parse((await tn(t,r)).toString("utf8")||"{}")}catch(p){throw p instanceof Q?new L(413,p.message):new L(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new L(400,"request body must be a JSON object");let s=o;for(let p of Object.keys(s))if(!yu[p])throw new L(400,`request field "${p}" 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.`,p);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new L(400,"prompt is required and must be a non-empty string","prompt");let a=s.model===void 0?void 0:s.model;if(a!==void 0&&typeof a!="string")throw new L(400,"model must be a string","model");await _s(n.turn,n.clients,a);let u=s.n??1;if(u!==1)throw new L(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new L(400,`response_format ${JSON.stringify(d)} 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",i.length,i.length),!await Rs(n.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:i}];try{let p=await ks(n.clients,a,l,n.turn?ae(n.turn):void 0);xs(n.turn,p),Es(e,p)}catch(p){throw Ss(p)}}catch(o){if(o instanceof Q){bt(e,new L(413,o.message));return}if(o instanceof L){bt(e,o);return}throw o}}var wu={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Os(t,e,n){let r=n.maxBodyBytes??vs,o=n.maxImagePartBytes??hu;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${rn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new L(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await nn(t,r)}catch(c){throw c instanceof Q?new L(413,c.message):new L(400,String(c instanceof Error?c.message:c))}let a=i.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new L(400,"prompt is required and must be a non-empty string field","prompt");let u=i.get("model");if(u!==null&&typeof u!="string")throw new L(400,"model must be a string field","model");let d=u===null?void 0:u;await _s(n.turn,n.clients,d);let l=i.get("response_format")??"b64_json";if(l!=="b64_json")throw new L(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 c of i.keys())if(!wu[c])throw new L(400,`form field "${c}" 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[]).`,c);let p=[];for(let c of["image","image[]"])for(let f of i.getAll(c)){if(!(f instanceof File))throw new L(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",c);if(f.size>o)throw new L(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,c);let h=new Uint8Array(await f.arrayBuffer()),b=bs(h);if(b===null)throw new L(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",c);p.push({bytes:h,mime:b})}if(p.length===0)throw new L(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await Rs(n.imageModels,d,"edit",e))return;let g=[{type:"input_text",text:a}];for(let{bytes:c,mime:f}of p)g.push({type:"input_image",image_url:`data:${f};base64,${Buffer.from(c).toString("base64")}`});try{let c=await ks(n.clients,d,g,n.turn?ae(n.turn):void 0);xs(n.turn,c),Es(e,c)}catch(c){throw Ss(c)}}catch(s){if(s instanceof Q){bt(e,new L(413,s.message));return}if(s instanceof L){bt(e,s);return}throw s}}var St="/v1/audio/speech";function $s(t){return t===St}var Is=4096,_u=18e4,vu=5e3,bu=64*1024*1024,Ts=8,Ps=5,sn="voice_applied",ku="X-Urun-Voice-Applied",P=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function ir(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 an=class extends P{constructor(e){super(502,e)}};async function Su(t,e,n){if(t){if(t.model=re({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 Ru(t,e){t&&(t.outputUnits=e/(24e3*2))}var xu=2;function Eu(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>xu)return!1;return!0}function Au(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 Cs=new WeakMap,on=new WeakMap;function Ou(t,e){let n=on.get(t)??0;if(n>=Ts)throw new P(503,`this model's speech queue is full \u2014 ${Ts} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Ps}s`,void 0,Ps);on.set(t,n+1);let r=Cs.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Cs.set(t,s),(async()=>{await r;try{return await e()}finally{on.set(t,(on.get(t)??1)-1),o()}})()}async function Iu(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new P(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(i){if(!(i instanceof W))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function kt(t){return t instanceof P?t:t instanceof N?new P(404,t.message):new P(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Tu(t,e,n,r,o,s,i){return Ou(e,async()=>{if(i?.()===!0)return null;let a=[],u=!1,d=0,l=!1,p=!1,g,c=new Promise(R=>{g=R}),f=()=>{l&&!p&&d>=o.quietRunFrames&&(p=!0,g())},h=e.onOutputAudio(R=>{let _=Buffer.from(R,"base64");if(_.byteLength===0)return;let k=Eu(_);if(!u){if(k)return;u=!0}a.push(_),d=k?d+1:0,f()}),b=null,m,y,w;try{w=(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 _=new Promise(I=>{y=setTimeout(I,s.capMs)}),k=!1;for(;;){let I=w.next(),T=await Promise.race([I,_]);if(T===void 0){k=!0,I.catch(()=>{});break}if(T.done)break;let $=T.value;if($.type==="error"){let Y=$.error??{};throw await w.return?.(),new P(502,`speech upstream error: ${String(Y.message??"upstream reported an error")}`)}if($.type==="response.completed"){b=$.response??null,l=!0,f(),await w.return?.();break}}if(clearTimeout(y),k)throw new P(504,`the speech turn produced no terminal event within ${s.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(b===null)throw new P(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let v=!1;if(await Promise.race([c,new Promise(I=>{m=setTimeout(()=>{v=!0,I()},o.capMs)})]),m!==void 0&&clearTimeout(m),r.voice!==void 0){let I=b[sn];if(typeof I!="string"||I!==r.voice){let T=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof I=="string"?`${sn} ${JSON.stringify(I)}`:`no ${sn} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw p?new an(T):new P(502,T)}}if(!u)throw new P(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(v&&!p&&d<1)throw new P(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`);let x=d>0?a.slice(0,a.length-d):a;return{pcm:Buffer.concat(x),completed:b}}catch(R){throw R instanceof an||await Iu(t,n,w,s.returnBoundMs),R}finally{m!==void 0&&clearTimeout(m),y!==void 0&&clearTimeout(y),h()}})}async function Pu(t,e,n){let r;try{r=await t(e)}catch(o){throw kt(o)}return r?!0:(ir(n,new P(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 Cu={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},$u="wav, pcm";async function Ls(t,e,n){let r=n.maxBodyBytes??bu,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new P(405,`${String(t.method)} is not supported on ${St}`);let i;try{i=JSON.parse((await tn(t,r)).toString("utf8")||"{}")}catch(w){throw w instanceof Q?new P(413,w.message):new P(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new P(400,"request body must be a JSON object");let a=i;for(let w of Object.keys(a))if(!Cu[w])throw new P(400,`request field "${w}" 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.`,w);let u=a.input;if(typeof u!="string"||u.trim().length===0)throw new P(400,"input is required and must be a non-empty string","input");if(u.length>Is)throw new P(400,`input is ${u.length} chars \u2014 over the ${Is}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new P(400,"model must be a string","model");let l=a.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new P(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new P(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 ${St} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(w){throw kt(w)}if(p.defect!==null)throw new P(500,`the voice set for this model cannot be resolved: ${p.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&&p.published.length>0&&!p.published.includes(g))throw new P(400,`voice ${JSON.stringify(g)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let c=a.response_format??"wav";if(c!=="wav"&&c!=="pcm")throw new P(400,`response_format ${JSON.stringify(c)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${$u} \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 P(400,"stream_format, when present, must be a string","stream_format");let f=a.speed;if(f!==void 0){if(typeof f!="number"||!Number.isFinite(f))throw new P(400,"speed, when present, must be a number","speed");if(f!==1)throw new P(400,`speed=${JSON.stringify(f)} 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 h=a.instructions;if(h!==void 0){if(typeof h!="string")throw new P(400,"instructions, when present, must be a string","instructions");if(h.trim().length>0)throw new P(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 Su(n.turn,n.clients,d);let b=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",b,b),!await Pu(n.speechModels,d,e))return;if(typeof n.clients.openAudioOn!="function")throw new P(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 P(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 P(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(s())return;let m;try{m=await n.clients.speechSessionHandle(d)}catch(w){throw kt(w)}let y;try{y=await n.clients.openAudioOn(m)}catch(w){throw kt(w)}n.turn&&(n.turn.sessionId=y.sessionId);try{let w=await Tu(n.clients,y,m,{model:d,text:u,...g!==void 0?{voice:g}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??_u,returnBoundMs:n.turnReturnBoundMs??vu},s);if(w===null||s())return;if(Ru(n.turn,w.pcm.byteLength),e.statusCode=200,g===void 0){let R=w.completed[sn];typeof R=="string"&&e.setHeader(ku,R)}c==="wav"?(e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Au(w.pcm.byteLength),w.pcm]))):(e.setHeader("content-type","audio/pcm"),e.end(w.pcm))}catch(w){throw kt(w)}}catch(i){if(i instanceof Q){ir(e,new P(413,i.message));return}if(i instanceof P){ir(e,i);return}throw i}}var un="/v1/audio/transcriptions";function Ns(t){return t===un}var Us="/v1/audio/models",Lu=16*1024*1024,Nu=64*1024*1024,F=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function ar(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 Ms(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 Uu(t){if(!Ms(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(s==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,d=(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:d,channels:u,bitsPerSample:l}}else if(s==="data"){let u=t.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%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 Mu(t,e,n){if(t){if(t.model=re({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 Du(t,e){t&&(t.outputUnits=e.seconds)}async function Fu(t,e,n,r,o){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),i=[],a=null;for await(let u of s){if(i.push(u),u.type==="error"){let d=u.error??{},l=typeof d.type=="string"?d.type:"upstream_error",p=String(d.message??"upstream reported an error");throw new F(l==="invalid_request_error"?400:502,`transcription upstream error: ${p}`)}if(u.type==="response.completed"){a=u.response??null;break}}if(a===null)throw new F(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return He(i,a)}function Ds(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 Bu(t,e,n){let r;try{r=await t(e)}catch(o){throw Ds(o)}return r?!0:(ar(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 qu=new Set(["file","model","language","response_format"]);async function Fs(t,e,n){let r=n.maxBodyBytes??Nu,o=n.maxAudioPartBytes??Lu;try{if(t.method!=="POST")throw new F(405,`${String(t.method)} is not supported on ${un}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new F(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await nn(t,r)}catch(m){throw m instanceof Q?new F(413,m.message):new F(400,String(m instanceof Error?m.message:m))}let a=new Map;for(let m of i.keys()){if(!qu.has(m))throw new F(400,`form field "${m}" 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.`,m);a.set(m,(a.get(m)??0)+1)}for(let[m,y]of a)if(y>1)throw new F(400,`form field "${m}" appears ${y} 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`,m);let u=i.get("model");if(u!==null&&typeof u!="string")throw new F(400,"model must be a string field","model");let d=u===null?void 0:u,l=i.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 p=l===null?void 0:l,g=i.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 c=i.get("file");if(!(c 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(c.size>o)throw new F(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let f=new Uint8Array(await c.arrayBuffer());if(!Ms(f))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 h=Uu(f);if(h===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 Mu(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",f.length,f.length),!await Bu(n.transcriptionModels,d,e))return;let b=[{type:"input_audio",input_audio:{data:Buffer.from(f).toString("base64"),format:"wav"}}];try{let m=await Fu(n.clients,d,b,p,n.turn?ae(n.turn):void 0);Du(n.turn,h),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:m}))}catch(m){throw Ds(m)}}catch(s){if(s instanceof Q){ar(e,new F(413,s.message));return}if(s instanceof F){ar(e,s);return}throw s}}var ln="/v1/usage/requests",Bs=1e4,ju=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,xe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},B=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},dn=class extends B{constructor(e){super(e),this.name="UsageWithholdingError"}},Gs=1024*1024;function lr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new xe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new xe(`"${e}" must be an array of uuid strings`);if(n.length>Bs)throw new xe(`"${e}" carries ${n.length} ids; at most ${Bs} 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 s of n){if(typeof s!="string"||!ju.test(s))throw new xe(`"${e}" contains ${JSON.stringify(s)}, 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(s)||(o.add(s),r.push(s))}return r}function Vs(t){return lr(t,"inference_ids")}var Hu=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","cost_nano_usd","price_version","priced_at"];function We(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new B(`${n}: ${e} is not a non-empty string (got ${Je(r)})`);return r}function ur(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new B(`${n}: ${e} is neither null nor a non-empty string (got ${Je(r)})`);return r}function Rt(t,e,n,r){let o=t[e];if(o===null)return null;let s=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(s))throw new B(`${n}: ${e} is not a number (got ${Je(o)})`);if(r&&!Number.isSafeInteger(s))throw new B(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(s<0)throw new B(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Gu=40,qs=64,js=600;function Ws(t){let e=Object.keys(t).sort(),r=e.slice(0,Gu).map(o=>o.length>qs?`${o.slice(0,qs)}\u2026`:o).join(", ");return r.length>js&&(r=`${r.slice(0,js)}\u2026`),`${e.length} keys present: [${r}]`}function Je(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function dr(t){Re(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
23
+ `)}function Vu(t,e){let n;try{n=t(e)}catch{Hs(t,e);return}Wu(n)&&Promise.resolve(n).catch(()=>{Hs(t,e)})}function Wu(t){return typeof t?.then=="function"}function Hs(t,e){if(t!==dr)try{dr(e)}catch{}}function Js(t,e=dr){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?Ws(t):Je(t);throw new B(`the usage surface answered without a "requests" array: got ${Je(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Ju(n[o],s))}catch(i){if(i instanceof dn||!(i instanceof B))throw i;Vu(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new B(`the usage surface returned ${n.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function Ju(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new B(`${e} is not an object: got ${Je(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new dn(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let o of Hu)if(!Object.hasOwn(n,o))throw new B(`${e} has no "${o}" column (${Ws(n)})`);let r=Rt(n,"http_status",e,!0);if(r===null)throw new B(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:We(n,"inference_id",e),model_id:We(n,"model_id",e),identity_kind:We(n,"identity_kind",e),variant:ur(n,"variant",e),task:We(n,"task",e),http_status:r,started_at:We(n,"started_at",e),completed_at:We(n,"completed_at",e),prompt_tokens:Rt(n,"prompt_tokens",e,!0),completion_tokens:Rt(n,"completion_tokens",e,!0),output_units:Rt(n,"output_units",e,!1),cost_nano_usd:Rt(n,"cost_nano_usd",e,!0),price_version:ur(n,"price_version",e),priced_at:ur(n,"priced_at",e)}}function cn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new B(`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(s.inference_id))throw new B(`the usage surface returned ${s.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(s.inference_id)}}var yn=require("@urun-sh/core");var xt="/partners/huggingface/v1/billing/requests";function Ku(t){return lr(t,"requestIds")}function zu(t){return t>=200&&t<=399}function Yu(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&zu(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Ks(t,e){let n=Ku(t),r=await e(n);return cn(r,n),Yu(r)}var Xu={"/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 Qu(t){return Xu[t]??null}var Qs=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function Zu(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function ed(t){return t==="surface"}function td(t){let e=t?.ledgerFailureReason;return Qs.includes(e)?e:"unknown"}var nd=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],zs=["priced","unpriced"],rd={written:zs,already_written:zs,skipped:nd,failed:Qs},Zs=Object.entries(rd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function od(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function sd(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 id=256,Ys=4096,At=12e4,ad=250,ud=8e3,Ne=[],Xs=new Set,Ot=0,Et=!1;function ei(){return Ne.length}function ti(t=Date.now()){let e=Ne[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var dd=new Set;function ld(){return Ot===0&&Ne.length===0}function cd(){if(ld()){Et=!1;for(let t of[...dd])t()}}function ni(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
24
+ `}function pd(t){Re(process.stdout,t)}function ri(t,e){try{t(e)}catch{}}function oi(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??pd,o=Qu(e.path);if(o===null)return;let s=l=>{try{n.observe(l)}catch{}},i=(l,p)=>{s({outcome:"skipped",reason:l}),ri(r,ni("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:l,detail:p}))};if(e.status===null){i("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){i("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"){i("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("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}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let d={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:sd(e),completed_at:e.ts,billable_outcome:od(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,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(Ne.length>=Ys){i("queue_full",`${Ne.length} ledger writes are already waiting (capacity ${Ys}, ${Ot} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Ne.push({entry:d,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Ot<id&&(Ot+=1,fd())}async function fd(){try{for(;;){let t=md();if(t===void 0)return;Xs.add(t);try{await gd(t)}finally{Xs.delete(t)}}}finally{Ot-=1,cd()}}function md(){let t=Date.now();for(;;){let e=Ne.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<At)return e;Ke(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 ${At}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 gd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Ke(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 s=Zu(o);if(s!==null){Ke(t,{outcome:"already_written",reason:s.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:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=td(o),a=Date.now()-t.queuedAt;if(Et){Ke(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(ed(i)&&a<At){if(await yd(hd(t.attempts)),Et||Date.now()-t.queuedAt>=At){let u=Date.now()-t.queuedAt;Ke(t,{outcome:"failed",reason:Et?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Et?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${At}ms dwell bound (waited ${u}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}Ke(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function hd(t){return Math.min(ud,ad*2**Math.max(0,t-1))}function yd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Ke(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;ri(t.report,ni(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var cr=at(require("crypto"),1),wd="urun-runtime-key-v1";function _d(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return cr.createHmac("sha256",t).update(`${wd}|${e}`,"ascii").digest("base64url")}var vd="decision-intake",pn=6e4,bd=pn/1e3+5,si=3,pr=15;function kd(t,e,n=60,r=Math.floor(Date.now()/1e3)){if(!t)throw new Error("cannot mint a decision token without a secret");let o=d=>Buffer.from(d).toString("base64url"),s=o(JSON.stringify({alg:"HS256",typ:"JWT"})),i={tenant:e.tenant,app:e.app,fn:e.fn,...e.provider?{provider:e.provider}:{},session_id:"decision-intake",sub:`machine:${e.tenant}/${e.app}/${e.fn}`,aud:vd,iat:r,exp:r+Math.max(1,n)},a=o(JSON.stringify(i)),u=cr.createHmac("sha256",t).update(`${s}.${a}`,"ascii").digest("base64url");return`${s}.${a}.${u}`}function Sd(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.runtime_id=="string"&&e.runtime_id!==""&&typeof e.ready=="boolean"&&typeof e.address=="string"&&e.address!==""&&typeof e.last_seen=="string"&&!Number.isNaN(Date.parse(e.last_seen))}async function Rd(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/runtimes?app=${encodeURIComponent(t.app)}&fn=${encodeURIComponent(t.fn)}`,r;try{r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"},signal:AbortSignal.timeout(pn)})}catch(u){throw(u instanceof Error?u.name:void 0)==="TimeoutError"?new le(`runtime presence read for (app=${t.app} fn=${t.fn}) timed out after ${pn}ms \u2014 the control plane is not answering; no replica can be discovered`):u}if(!r.ok)throw new Error(`runtime presence read failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.runtimes))throw new Error(`runtime presence read returned no "runtimes" array (GET ${n})`);let s=[],i=[];for(let u of o.runtimes){if(!Sd(u)){s.push(JSON.stringify(u));continue}i.push(u)}if(s.length>0)throw new Error(`runtime presence read for (app=${t.app} fn=${t.fn}) returned ${s.length} malformed presence row(s) \u2014 the control plane's runtimes schema drifted (runtime_id/address/ready/last_seen are all required): ${s.slice(0,3).join("; ")}`);let a=(t.nowMs??Date.now())/1e3;return i.filter(u=>u.ready===!0&&a-Date.parse(u.last_seen)/1e3<=pr)}var xd=pr*1e3,Ed=pr*500,Ad=256,fn=class{constructor(e){this.opts=e;this.nowMs=e.nowMs??Date.now}opts;replicas=new Map;nowMs;presenceCache=new Map;get enabled(){return this.opts.secret!==""}async targetFor(e){let n=await this.opts.targetFor(e);return n.sharedApp===!0&&this.opts.shared===void 0?null:n}async decide(e,n){let r=await this.targetFor(n);if(r===null)throw new le("the shared-endpoint lane keeps the session dial \u2014 the stateless direct path serves caller-org functions");let o=r.appSlug,s=r.fnName??this.opts.fnName,i=r.sharedApp===!0,a=i?this.opts.shared.apiKey:this.opts.apiKey,u=`${a}\0${o}\0${s}`,d=await this.ensureRows(u,a,o,s);if(d.length===0)throw new le(`no ready runtime for (org app=${o} fn=${s}) \u2014 nothing is serving decisions right now`);let l=null;for(let p=0;p<si;p++){let g=this.pick(d);if(g===null)throw new le(`every discovered runtime for app=${o} failed at the transport layer \u2014 no replica took the decision`);let c=i&&r.sharedOrgId?r.sharedOrgId:this.opts.orgId,f=kd(_d(this.opts.secret,c),{tenant:this.opts.orgId,app:o,fn:s,...i&&r.sharedOrgId?{provider:r.sharedOrgId}:{}},bd);try{return{...await this.post(g,e,f),target:{...r,fnName:s}}}catch(h){if(h instanceof Ue)throw h;l=h;let b=this.replicas.get(g)??{outstanding:0,cooldownUntil:0};b.cooldownUntil=this.nowMs()+5e3,this.replicas.set(g,b);let m=this.presenceCache.get(u);m&&(m.rows=m.rows.filter(y=>y.address!==g),m.rows.length===0&&this.presenceCache.delete(u))}}throw new le(`no runtime for app=${o} answered within ${si} attempts: ${String(l instanceof Error?l.message:l)}`)}async ensureRows(e,n,r,o){let s=this.presenceCache.get(e);if(s)if(this.nowMs()-s.fetchedAtMs>xd)this.presenceCache.delete(e);else return this.nowMs()-s.fetchedAtMs>Ed&&!s.refreshing&&(s.refreshing=!0,this.readPresence(n,r,o).then(a=>{this.presenceCache.set(e,{rows:a,fetchedAtMs:this.nowMs(),refreshing:!1})}).catch(()=>{s.refreshing=!1})),s.rows;let i=await this.readPresence(n,r,o);for(;this.presenceCache.size>=Ad;){let a=this.presenceCache.keys().next();if(a.done)break;this.presenceCache.delete(a.value)}return this.presenceCache.set(e,{rows:i,fetchedAtMs:this.nowMs(),refreshing:!1}),i}readPresence(e,n,r){return Rd({apiUrl:this.opts.apiUrl,apiKey:e,app:n,fn:r,fetchImpl:this.opts.fetchImpl,nowMs:this.nowMs()})}pick(e){let n=this.nowMs(),r=null,o=1/0;for(let s of e){let i=this.replicas.get(s.address);if(i!==void 0&&i.cooldownUntil>n)continue;let a=i?.outstanding??0;a<o&&(r=s.address,o=a)}return r}async post(e,n,r){let o=this.replicas.get(e)??{outstanding:0,cooldownUntil:0};o.outstanding+=1,this.replicas.set(e,o);try{let s=await fetch(`${e.replace(/\/+$/,"")}/v1/decision`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.opts.timeoutMs??pn)}),i=null;try{i=await s.json()}catch{i={error:{message:`runtime answered ${s.status} with a non-JSON body`,type:"upstream_error"}}}if(s.status>=500)throw new Error(`runtime ${e} answered ${s.status}`);if(s.status>=400)throw new Ue(s.status,i);return{status:s.status,body:i,completed:Od(i)}}finally{o.outstanding-=1}}};function Od(t){if(t===null||typeof t!="object")return null;let e=t,n=e.usage;if(n===null||typeof n!="object")return e;let r=n;return{...e,usage:{input_tokens:r.prompt_tokens??r.input_tokens,output_tokens:r.completion_tokens??r.output_tokens}}}var Ue=class extends Error{constructor(n,r){super(`runtime answered ${n}`);this.status=n;this.body=r}status;body},le=class extends Error{};function gr(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function G(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){G(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function hr(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);G(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function ce(t,e,n,r){G(t,e,{type:"error",error:{type:n,message:r}})}function pe(t,e,n){if(e==="anthropic"){G(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}G(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Td=64*1024*1024,It=class extends Error{};async function ii(t,e=Td){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new It(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function ze(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 ui(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function mn(t){let e=ui(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function ai(t){let e=mn(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 Pd(t,e){let n=ui(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Cd(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let d=n[u];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function $d(t,e){let n=Cd(e);n&&(t.timing=n)}function we(t,e){Pd(t,e),$d(t,e)}async function wn(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 di(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 Ld(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 gn=class extends Error{};function Nd(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 gn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Ud(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:Nd(n.role,n.content)})}return e}function fr(t){return qe(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 Md(t,e,n,r,o,s){let i=gt(s.id),a=t.stream===!0;if(s.model=re(t),s.stream=a,await wn(s,e,typeof t.model=="string"?t.model:void 0),a){let m;try{m=await yt({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(y){if(y instanceof N){pe(r,"openai",y);return}if(y instanceof ue){K(r,y.status,y.message);return}throw y}gr(r);for await(let y of m.events)y.type==="error"&&(s.streamError=!0),y.type==="response.completed"&&we(s,y.response),r.write(`event: ${String(y.type??"message")}
25
25
  data: ${JSON.stringify(y)}
26
26
 
27
27
  `);r.write(`data: [DONE]
28
28
 
29
- `),r.end();return}let u;try{u=Me(n,t)}catch(m){if(m instanceof re){V(r,m.status,m.message);return}throw m}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=oe(t);o.model(c);let l=Array.isArray(t.tools)&&t.tools.length>0,p;try{p=await Dn(e,t,u,!1,se(s))}catch(m){if(m instanceof N){de(r,"openai",m);return}if(m instanceof re){V(r,m.status,m.message);return}throw m}let f=[],_=null;for await(let m of o.track(p,c,s)){if(f.push(m),m.type==="error"){ir(r,m);return}m.type==="response.completed"&&(_=m.response)}if(_==null){V(r,502,"upstream produced no response.completed event","upstream_error");return}me(s,_);let S=qt(f,_),h=Ie(l,Ne(_).length,S);if(h){V(r,502,Oe(c,h),"upstream_error");return}d&&n.remember(i,u,Mn(_,S),d),G(r,200,{..._,id:i})}async function pd(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){V(n,400,"chat/completions requires a messages array");return}let i=String(t.model??"urun"),a=Ho(o.id),u;try{u=ld(s)}catch(w){if(w instanceof un){V(n,400,w.message);return}throw w}let d=oe(t);r.model(d),o.model=d,o.stream=t.stream===!0,await cn(o,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0;if(t.stream!==!0&&e.stateless?.enabled){let w;try{w=await e.stateless.targetFor(typeof t.model=="string"?t.model:void 0)}catch(x){if(x instanceof N){de(n,"openai",x);return}throw x}if(w!==null){try{let x=await e.stateless.decide(t,typeof t.model=="string"?t.model:void 0);o.catalog=at(x.target),me(o,x.completed),G(n,200,{...x.body,id:a})}catch(x){if(x instanceof N){de(n,"openai",x);return}if(x instanceof Pe){G(n,x.status,x.body);return}if(x instanceof ae){V(n,503,x.message,"upstream_error");return}throw x}return}}let l;try{l=await e.createResponse({model:t.model,input:u,stream:!0,tools:ud(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}:{}},se(o))}catch(w){if(w instanceof N){de(n,"openai",w);return}throw w}if(t.stream===!0){sr(n);let w=[],x=new he,T="";n.write(`data: ${JSON.stringify(He(a,i,{role:"assistant"},null))}
29
+ `),r.end();return}let u;try{u=Ge(n,t)}catch(m){if(m instanceof ue){K(r,m.status,m.message);return}throw m}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,l=re(t);o.model(l);let p=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await Jn(e,t,u,!1,ae(s))}catch(m){if(m instanceof N){pe(r,"openai",m);return}if(m instanceof ue){K(r,m.status,m.message);return}throw m}let c=[],f=null;for await(let m of o.track(g,l,s)){if(c.push(m),m.type==="error"){hr(r,m);return}m.type==="response.completed"&&(f=m.response)}if(f==null){K(r,502,"upstream produced no response.completed event","upstream_error");return}we(s,f);let h=He(c,f),b=Le(p,qe(f).length,h);if(b){K(r,502,$e(l,b),"upstream_error");return}d&&n.remember(i,u,Wn(f,h),d),G(r,200,{...f,id:i})}async function Dd(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){K(n,400,"chat/completions requires a messages array");return}let i=String(t.model??"urun"),a=Zo(o.id),u;try{u=Ud(s)}catch(v){if(v instanceof gn){K(n,400,v.message);return}throw v}let d=re(t);r.model(d),o.model=d,o.stream=t.stream===!0,await wn(o,e,typeof t.model=="string"?t.model:void 0);let l=Array.isArray(t.tools)&&t.tools.length>0;if(t.stream!==!0&&e.stateless?.enabled){let v;try{v=await e.stateless.targetFor(typeof t.model=="string"?t.model:void 0)}catch(x){if(x instanceof N){pe(n,"openai",x);return}throw x}if(v!==null){try{let x=await e.stateless.decide(t,typeof t.model=="string"?t.model:void 0);o.catalog=pt(x.target),we(o,x.completed),G(n,200,{...x.body,id:a})}catch(x){if(x instanceof N){pe(n,"openai",x);return}if(x instanceof Ue){G(n,x.status,x.body);return}if(x instanceof le){K(n,503,x.message,"upstream_error");return}throw x}return}}let p;try{p=await e.createResponse({model:t.model,input:u,stream:!0,tools:Ld(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}:{}},ae(o))}catch(v){if(v instanceof N){pe(n,"openai",v);return}throw v}if(t.stream===!0){gr(n);let v=[],x=new ke,I="";n.write(`data: ${JSON.stringify(ze(a,i,{role:"assistant"},null))}
30
30
 
31
- `);for await(let J of r.track(l,d,o)){w.push(J);let P=Ue(J);if(J.type==="response.output_text.delta"&&typeof J.delta=="string")T+=J.delta,n.write(`data: ${JSON.stringify(He(a,i,{content:J.delta},null))}
31
+ `);for await(let X of r.track(p,d,o)){v.push(X);let ee=je(X);if(X.type==="response.output_text.delta"&&typeof X.delta=="string")I+=X.delta,n.write(`data: ${JSON.stringify(ze(a,i,{content:X.delta},null))}
32
32
 
33
- `);else if(J.type==="response.reasoning_text.delta"&&typeof J.delta=="string")n.write(`data: ${JSON.stringify(He(a,i,{reasoning_content:J.delta},null))}
33
+ `);else if(X.type==="response.reasoning_text.delta"&&typeof X.delta=="string")n.write(`data: ${JSON.stringify(ze(a,i,{reasoning_content:X.delta},null))}
34
34
 
35
- `);else if(P){let{call:M,isNew:H}=x.add(P),te=H?{index:P.tool_index,id:M.id??`call_${P.tool_index}`,type:"function",function:{name:M.name??"",arguments:P.delta}}:{index:P.tool_index,function:{arguments:P.delta}};n.write(`data: ${JSON.stringify(He(a,i,{tool_calls:[te]},null))}
35
+ `);else if(ee){let{call:fe,isNew:j}=x.add(ee),me=j?{index:ee.tool_index,id:fe.id??`call_${ee.tool_index}`,type:"function",function:{name:fe.name??"",arguments:ee.delta}}:{index:ee.tool_index,function:{arguments:ee.delta}};n.write(`data: ${JSON.stringify(ze(a,i,{tool_calls:[me]},null))}
36
36
 
37
- `)}else if(J.type==="error"){o.streamError=!0,n.write(`data: ${JSON.stringify({error:J})}
37
+ `)}else if(X.type==="error"){o.streamError=!0,n.write(`data: ${JSON.stringify({error:X})}
38
38
 
39
- `),n.end();return}}let L=rr(ie(w)),I=Ie(c,x.size+L.length,T);if(I){o.streamError=!0,n.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Oe(d,I)}})}
39
+ `),n.end();return}}let T=fr(de(v)),$=Le(l,x.size+T.length,I);if($){o.streamError=!0,n.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:$e(d,$)}})}
40
40
 
41
- `),n.end();return}x.size===0&&L.length>0&&n.write(`data: ${JSON.stringify(He(a,i,{tool_calls:L},null))}
41
+ `),n.end();return}x.size===0&&T.length>0&&n.write(`data: ${JSON.stringify(ze(a,i,{tool_calls:T},null))}
42
42
 
43
- `);let z=x.size>0||L.length>0;n.write(`data: ${JSON.stringify(He(a,i,{},z?"tool_calls":"stop"))}
43
+ `);let Y=x.size>0||T.length>0;n.write(`data: ${JSON.stringify(ze(a,i,{},Y?"tool_calls":"stop"))}
44
44
 
45
- `);let X=an(ie(w));me(o,ie(w)),X&&n.write(`data: ${JSON.stringify({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:i,choices:[],usage:Gs(ie(w))})}
45
+ `);let Z=mn(de(v));we(o,de(v)),Z&&n.write(`data: ${JSON.stringify({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:i,choices:[],usage:ai(de(v))})}
46
46
 
47
47
  `),n.write(`data: [DONE]
48
48
 
49
- `),n.end();return}let p="",f="",_=[],S=new he;for await(let w of r.track(l,d,o)){_.push(w),w.type==="response.output_text.delta"&&typeof w.delta=="string"&&(p+=w.delta),w.type==="response.reasoning_text.delta"&&typeof w.delta=="string"&&(f+=w.delta);let x=Ue(w);if(x&&S.add(x),w.type==="error"){ir(n,w);return}}let h=ie(_);me(o,h);let m=rr(h),y=m.length>0?m:rr({output:S.items()}),g=Ie(c,y.length,p);if(g){V(n,502,Oe(d,g),"upstream_error");return}let R=y.map(({index:w,...x})=>x),v={role:"assistant",content:p||null},b=f||Ws(h);b&&(v.reasoning_content=b),R.length>0&&(v.tool_calls=R),G(n,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:i,choices:[{index:0,message:v,finish_reason:R.length>0?"tool_calls":"stop"}],usage:Gs(h)})}var fd="reflex-latest";async function md(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){V(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:fd,i=oe({model:s});if(o.model=i,o.stream=!1,t.state===void 0||t.state===null){V(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){V(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){V(n,400,"systemone media, when present, must be an array");return}if(r.model(i),await cn(o,e,s),e.stateless?.enabled){let f;try{f=await e.stateless.targetFor(s)}catch(_){if(_ instanceof N){de(n,"openai",_);return}throw _}if(f!==null){try{let _=await e.stateless.decide(t,s);o.catalog=at(_.target),me(o,_.completed),G(n,200,_.body)}catch(_){if(_ instanceof N){de(n,"openai",_);return}if(_ instanceof Pe){G(n,_.status,_.body);return}if(_ instanceof ae){V(n,503,_.message,"upstream_error");return}throw _}return}}let u;try{u=await e.createResponse({model:s,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},se(o))}catch(f){if(f instanceof N){de(n,"openai",f);return}throw f}let d=[];try{for await(let f of r.track(u,i,o))if(d.push(f),f.type==="error"){ir(n,f);return}}catch(f){if(f instanceof N){de(n,"openai",f);return}throw f}let c=ie(d);if(c==null){V(n,502,"upstream produced no response.completed event","upstream_error");return}me(o,c);let l=qt(d,c),p;try{p=JSON.parse(l)}catch{V(n,502,"systemone answer was not valid JSON","upstream_error");return}if(p===null||typeof p!="object"||Array.isArray(p)){V(n,502,"systemone answer was not a JSON object","upstream_error");return}G(n,200,p)}function gd(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Et=class extends Error{};function dn(t){return new Et(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function hd(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 yd(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 Et(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function _d(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw dn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw dn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function wd(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 dn(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:_d(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw dn(a)}}return s(),r}function or(t){return Ne(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 vd(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){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(w=>typeof w!="string"))){ue(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(t.model??"urun"),a=jo(o.id),u=[],d;try{t.system&&u.push({role:"system",content:gd(t.system)});for(let w of s)u.push(...wd(w));d=yd(t.tool_choice)}catch(w){if(w instanceof Et){ue(n,400,"invalid_request_error",w.message);return}throw w}let c=oe(t);r.model(c),o.model=c,o.stream=t.stream===!0,await cn(o,e,typeof t.model=="string"?t.model:void 0);let l=Array.isArray(t.tools)&&t.tools.length>0,p;try{p=await e.createResponse({model:t.model,input:u,stream:!0,tools:hd(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},se(o))}catch(w){if(w instanceof N){de(n,"anthropic",w);return}throw w}let f=(w,x)=>{n.destroyed||n.write(`event: ${w}
50
- data: ${JSON.stringify({type:w,...x})}
49
+ `),n.end();return}let g="",c="",f=[],h=new ke;for await(let v of r.track(p,d,o)){f.push(v),v.type==="response.output_text.delta"&&typeof v.delta=="string"&&(g+=v.delta),v.type==="response.reasoning_text.delta"&&typeof v.delta=="string"&&(c+=v.delta);let x=je(v);if(x&&h.add(x),v.type==="error"){hr(n,v);return}}let b=de(f);we(o,b);let m=fr(b),y=m.length>0?m:fr({output:h.items()}),w=Le(l,y.length,g);if(w){K(n,502,$e(d,w),"upstream_error");return}let R=y.map(({index:v,...x})=>x),_={role:"assistant",content:g||null},k=c||di(b);k&&(_.reasoning_content=k),R.length>0&&(_.tool_calls=R),G(n,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:i,choices:[{index:0,message:_,finish_reason:R.length>0?"tool_calls":"stop"}],usage:ai(b)})}var Fd="reflex-latest";async function Bd(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 s=typeof t.model=="string"&&t.model?t.model:Fd,i=re({model:s});if(o.model=i,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}if(r.model(i),await wn(o,e,s),e.stateless?.enabled){let c;try{c=await e.stateless.targetFor(s)}catch(f){if(f instanceof N){pe(n,"openai",f);return}throw f}if(c!==null){try{let f=await e.stateless.decide(t,s);o.catalog=pt(f.target),we(o,f.completed),G(n,200,f.body)}catch(f){if(f instanceof N){pe(n,"openai",f);return}if(f instanceof Ue){G(n,f.status,f.body);return}if(f instanceof le){K(n,503,f.message,"upstream_error");return}throw f}return}}let u;try{u=await e.createResponse({model:s,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},ae(o))}catch(c){if(c instanceof N){pe(n,"openai",c);return}throw c}let d=[];try{for await(let c of r.track(u,i,o))if(d.push(c),c.type==="error"){hr(n,c);return}}catch(c){if(c instanceof N){pe(n,"openai",c);return}throw c}let l=de(d);if(l==null){K(n,502,"upstream produced no response.completed event","upstream_error");return}we(o,l);let p=He(d,l),g;try{g=JSON.parse(p)}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}G(n,200,g)}function qd(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Tt=class extends Error{};function hn(t){return new Tt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function jd(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 Hd(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 Tt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Gd(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw hn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw hn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Vd(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 hn(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:Gd(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw hn(a)}}return s(),r}function mr(t){return qe(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 Wd(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){ce(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){ce(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){ce(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"))){ce(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(t.model??"urun"),a=es(o.id),u=[],d;try{t.system&&u.push({role:"system",content:qd(t.system)});for(let v of s)u.push(...Vd(v));d=Hd(t.tool_choice)}catch(v){if(v instanceof Tt){ce(n,400,"invalid_request_error",v.message);return}throw v}let l=re(t);r.model(l),o.model=l,o.stream=t.stream===!0,await wn(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await e.createResponse({model:t.model,input:u,stream:!0,tools:jd(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},ae(o))}catch(v){if(v instanceof N){pe(n,"anthropic",v);return}throw v}let c=(v,x)=>{n.destroyed||n.write(`event: ${v}
50
+ data: ${JSON.stringify({type:v,...x})}
51
51
 
52
- `)};if(t.stream===!0){let w=r.track(p,c,o);sr(n),f("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let x=0,T="",L=0,I="none",z=()=>I,X=-1,J=-1,P=new he,M=[],H=()=>{I!=="none"&&(I="none",f("content_block_stop",{index:X}))},te=(B,ee)=>{H(),I=B,X=L++,f("content_block_start",{index:X,content_block:ee})};for await(let B of w){if(n.destroyed)break;M.push(B);let ee=Ue(B);if(B.type==="response.reasoning_text.delta"&&typeof B.delta=="string")z()!=="thinking"&&te("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:X,delta:{type:"thinking_delta",thinking:B.delta}});else if(B.type==="response.output_text.delta"&&typeof B.delta=="string")z()!=="text"&&te("text",{type:"text",text:""}),x+=1,T+=B.delta,f("content_block_delta",{index:X,delta:{type:"text_delta",text:B.delta}});else if(ee){let{call:Br}=P.add(ee);(z()!=="tool"||ee.tool_index!==J)&&(J=ee.tool_index,te("tool",{type:"tool_use",id:Br.id??`call_${ee.tool_index}`,name:Br.name??"",input:{}})),ee.delta&&f("content_block_delta",{index:X,delta:{type:"input_json_delta",partial_json:ee.delta}})}else if(B.type==="error"){o.streamError=!0,f("error",{error:{type:"api_error",message:JSON.stringify(B)}}),n.end();return}}if(n.destroyed)return;let be=ie(M),ke=Ne(be),ge=Ie(l,P.size+ke.length,T);if(ge){o.streamError=!0,f("error",{error:{type:"api_error",message:Oe(c,ge)}}),n.end();return}H();let le=[];if(P.size===0)try{le=or(be)}catch(B){o.streamError=!0,f("error",{error:{type:"api_error",message:String(B instanceof Error?B.message:B)}}),n.end();return}L===0&&le.length===0&&(te("text",{type:"text",text:""}),H()),le.forEach(B=>{let ee=L++;f("content_block_start",{index:ee,content_block:{...B,input:{}}}),f("content_block_delta",{index:ee,delta:{type:"input_json_delta",partial_json:JSON.stringify(B.input??{})}}),f("content_block_stop",{index:ee})});let et=P.size>0||le.length>0,$e=an(be);me(o,be),f("message_delta",{delta:{stop_reason:et?"tool_use":"end_turn"},usage:$e?{input_tokens:$e.input_tokens,output_tokens:$e.output_tokens}:{output_tokens:x}}),f("message_stop",{}),n.end();return}let _="",S="",h=[],m=new he;for await(let w of r.track(p,c,o)){h.push(w),w.type==="response.output_text.delta"&&typeof w.delta=="string"&&(_+=w.delta),w.type==="response.reasoning_text.delta"&&typeof w.delta=="string"&&(S+=w.delta);let x=Ue(w);if(x&&m.add(x),w.type==="error"){let T=w.error,L=T?.type==="invalid_request_error";ue(n,L?400:502,L?"invalid_request_error":"api_error",T?.message??JSON.stringify(w));return}if(n.destroyed)break}if(n.destroyed)return;let y=ie(h);me(o,y);let g;try{g=or(y),g.length===0&&m.size>0&&(g=or({output:m.items()}))}catch(w){ue(n,502,"api_error",String(w instanceof Error?w.message:w));return}let R=Ie(l,g.length,_);if(R){ue(n,502,"api_error",Oe(c,R));return}let v=[],b=S||Ws(y);b&&v.push({type:"thinking",thinking:b}),(_||g.length===0)&&v.push({type:"text",text:_}),v.push(...g),G(n,200,{id:a,type:"message",role:"assistant",content:v,model:i,stop_reason:g.length>0?"tool_use":"end_turn",usage:an(y)??{input_tokens:0,output_tokens:0}})}function bd(t){_e(process.stdout,t)}function Js(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??bd,a=t.observe,u=new Ee;return(d,c)=>{let l=new URL(d.url??"/","http://localhost"),p=l.pathname==="/v1/messages"||l.pathname.startsWith("/v1/messages/"),f=(y,g,R,v,b)=>p?ue(c,y,v,g):V(c,y,g,R,b),_=Un(l.pathname),S=l.pathname.startsWith("/partners/"),h=_||S?{id:dt(),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,sessionId:null,timing:null}:null;h&&(c.setHeader(Bo,h.id),c.once("close",()=>{let y=Go({turn:h,method:d.method??"",path:l.pathname,res:c});i(Vo(y)),a?.(y),qs({record:y,ledger:t.ledger??null,req:d})}));let m=()=>qo(l.pathname,h);(async()=>{if(d.method==="GET"&&l.pathname==="/healthz"){G(c,200,{ok:!0});return}if(d.method==="GET"&&l.pathname==="/stats"){G(c,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){f(401,"invalid local proxy api key","authentication_error","authentication_error");return}let y=l.pathname===nn?"canonical":l.pathname===bt?"huggingface":null;if(y){if(d.method!=="POST"){f(405,`${l.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let b=t.usage;if(!b){f(501,`${l.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 w=b.authorize(d),x;try{x=await js(d,As)}catch(I){if(I instanceof xt){f(413,I.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let T=I=>b.lookup(w,I),L;try{if(y==="canonical"){let I=Os(x),z=await T(I);rn(z,I),L={requests:z}}else L=await Ps(x,T)}catch(I){if(I instanceof we){f(I.status,I.message,"invalid_request_error","invalid_request_error");return}throw I}G(c,200,L);return}if(l.pathname.startsWith("/partners/")){f(404,`no partner adapter for ${d.method} ${l.pathname} \u2014 the partner surface currently carries ${bt}`,"invalid_request_error","not_found_error");return}let g=await s(d);if(h&&(h.org=g.tenant??null),d.method==="GET"&&l.pathname==="/v1/models"){if(l.searchParams.get("format")==="openrouter"){if(!g.openRouterModels){f(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}G(c,200,await g.openRouterModels());return}G(c,200,await g.listModels());return}if(d.method==="GET"&&l.pathname===is){if(!g.listImageModels){f(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}G(c,200,await g.listImageModels());return}if(ss(l.pathname)){if(!g.supportsImages){f(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${l.pathname}`,"not_implemented","not_implemented_error");return}let b={clients:g,imageModels:g.supportsImages,stats:u,turn:m()};l.pathname===Xt?await hs(d,c,b):await gs(d,c,b);return}if(bs(l.pathname)){if(!g.supportsSpeech){f(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${wt}`,"not_implemented","not_implemented_error");return}let b={clients:g,speechModels:g.supportsSpeech,stats:u,turn:m()};await ks(d,c,b);return}if(d.method!=="POST"){f(404,`no route for ${d.method} ${l.pathname}`,"invalid_request_error","not_found_error");return}let R;try{R=await js(d)}catch(b){if(b instanceof xt){f(413,b.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let v=Buffer.byteLength(JSON.stringify(R));if(l.pathname==="/v1/responses"){u.request("responses",v,v),await cd(R,g,ct(g),c,u,m());return}if(l.pathname==="/v1/chat/completions"){u.request("chat_completions",v,v),await pd(R,g,c,u,m());return}if(l.pathname==="/v1/systemone"){u.request("systemone",v,v),await md(R,g,c,u,m());return}if(l.pathname==="/v1/messages"){u.request("messages",v,v),await vd(R,g,c,u,m());return}if(l.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",v,v),ue(c,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}f(404,`no route for POST ${l.pathname}`,"invalid_request_error","not_found_error")})().catch(y=>{let g=String(y instanceof Error?y.message:y);if(!c.headersSent){let R=o?.(y)??null;if(R){f(R.status,g,R.openaiType,R.anthropicType);return}if(y instanceof ln.SessionAllocationError){let v=jt(y.code);if(v){let b=y.retryAfterSeconds??(v.status===429?30:void 0);b!==void 0&&c.setHeader("Retry-After",String(b)),f(v.status,Gn(v,y.code??void 0),v.openaiType,v.anthropicType,v.code);return}}if(y instanceof ln.SessionFailedError){let v=Gt(y);if(v){let b=v.status===429?30:void 0;b!==void 0&&c.setHeader("Retry-After",String(b)),f(v.status,Gn(v,y.status.sessionId?`session ${y.status.sessionId}`:void 0),v.openaiType,v.anthropicType,v.code);return}}if(y instanceof D){f(502,g,"upstream_error","api_error");return}f(500,g,"proxy_error","api_error","proxy_error");return}h&&(h.streamError=!0),c.destroyed||(p?c.write(`event: error
53
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:g}})}
52
+ `)};if(t.stream===!0){let v=r.track(g,l,o);gr(n),c("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let x=0,I="",T=0,$="none",Y=()=>$,Z=-1,X=-1,ee=new ke,fe=[],j=()=>{$!=="none"&&($="none",c("content_block_stop",{index:Z}))},me=(D,te)=>{j(),$=D,Z=T++,c("content_block_start",{index:Z,content_block:te})};for await(let D of v){if(n.destroyed)break;fe.push(D);let te=je(D);if(D.type==="response.reasoning_text.delta"&&typeof D.delta=="string")Y()!=="thinking"&&me("thinking",{type:"thinking",thinking:""}),c("content_block_delta",{index:Z,delta:{type:"thinking_delta",thinking:D.delta}});else if(D.type==="response.output_text.delta"&&typeof D.delta=="string")Y()!=="text"&&me("text",{type:"text",text:""}),x+=1,I+=D.delta,c("content_block_delta",{index:Z,delta:{type:"text_delta",text:D.delta}});else if(te){let{call:ve}=ee.add(te);(Y()!=="tool"||te.tool_index!==X)&&(X=te.tool_index,me("tool",{type:"tool_use",id:ve.id??`call_${te.tool_index}`,name:ve.name??"",input:{}})),te.delta&&c("content_block_delta",{index:Z,delta:{type:"input_json_delta",partial_json:te.delta}})}else if(D.type==="error"){o.streamError=!0,c("error",{error:{type:"api_error",message:JSON.stringify(D)}}),n.end();return}}if(n.destroyed)return;let _e=de(fe),Ct=qe(_e),C=Le(p,ee.size+Ct.length,I);if(C){o.streamError=!0,c("error",{error:{type:"api_error",message:$e(l,C)}}),n.end();return}j();let U=[];if(ee.size===0)try{U=mr(_e)}catch(D){o.streamError=!0,c("error",{error:{type:"api_error",message:String(D instanceof Error?D.message:D)}}),n.end();return}T===0&&U.length===0&&(me("text",{type:"text",text:""}),j()),U.forEach(D=>{let te=T++;c("content_block_start",{index:te,content_block:{...D,input:{}}}),c("content_block_delta",{index:te,delta:{type:"input_json_delta",partial_json:JSON.stringify(D.input??{})}}),c("content_block_stop",{index:te})});let J=ee.size>0||U.length>0,ge=mn(_e);we(o,_e),c("message_delta",{delta:{stop_reason:J?"tool_use":"end_turn"},usage:ge?{input_tokens:ge.input_tokens,output_tokens:ge.output_tokens}:{output_tokens:x}}),c("message_stop",{}),n.end();return}let f="",h="",b=[],m=new ke;for await(let v of r.track(g,l,o)){b.push(v),v.type==="response.output_text.delta"&&typeof v.delta=="string"&&(f+=v.delta),v.type==="response.reasoning_text.delta"&&typeof v.delta=="string"&&(h+=v.delta);let x=je(v);if(x&&m.add(x),v.type==="error"){let I=v.error,T=I?.type==="invalid_request_error";ce(n,T?400:502,T?"invalid_request_error":"api_error",I?.message??JSON.stringify(v));return}if(n.destroyed)break}if(n.destroyed)return;let y=de(b);we(o,y);let w;try{w=mr(y),w.length===0&&m.size>0&&(w=mr({output:m.items()}))}catch(v){ce(n,502,"api_error",String(v instanceof Error?v.message:v));return}let R=Le(p,w.length,f);if(R){ce(n,502,"api_error",$e(l,R));return}let _=[],k=h||di(y);k&&_.push({type:"thinking",thinking:k}),(f||w.length===0)&&_.push({type:"text",text:f}),_.push(...w),G(n,200,{id:a,type:"message",role:"assistant",content:_,model:i,stop_reason:w.length>0?"tool_use":"end_turn",usage:mn(y)??{input_tokens:0,output_tokens:0}})}function Jd(t){Re(process.stdout,t)}function li(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Jd,a=t.observe,u=new Pe;return(d,l)=>{let p=new URL(d.url??"/","http://localhost"),g=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),c=(y,w,R,_,k)=>g?ce(l,y,_,w):K(l,y,w,R,k),f=Vn(p.pathname),h=p.pathname.startsWith("/partners/"),b=f||h?{id:mt(),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,sessionId:null,timing:null}:null;b&&(l.setHeader(Xo,b.id),l.once("close",()=>{let y=ts({turn:b,method:d.method??"",path:p.pathname,res:l});i(ns(y)),a?.(y),oi({record:y,ledger:t.ledger??null,req:d})}));let m=()=>Qo(p.pathname,b);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){G(l,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){G(l,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){c(401,"invalid local proxy api key","authentication_error","authentication_error");return}let y=p.pathname===ln?"canonical":p.pathname===xt?"huggingface":null;if(y){if(d.method!=="POST"){c(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let k=t.usage;if(!k){c(501,`${p.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=k.authorize(d),x;try{x=await ii(d,Gs)}catch($){if($ instanceof It){c(413,$.message,"request_too_large","request_too_large");return}c(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let I=$=>k.lookup(v,$),T;try{if(y==="canonical"){let $=Vs(x),Y=await I($);cn(Y,$),T={requests:Y}}else T=await Ks(x,I)}catch($){if($ instanceof xe){c($.status,$.message,"invalid_request_error","invalid_request_error");return}throw $}G(l,200,T);return}if(p.pathname.startsWith("/partners/")){c(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${xt}`,"invalid_request_error","not_found_error");return}let w=await s(d);if(b&&(b.org=w.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){if(!w.openRouterModels){c(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}G(l,200,await w.openRouterModels());return}G(l,200,await w.listModels());return}if(d.method==="GET"&&p.pathname===ws){if(!w.listImageModels){c(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}G(l,200,await w.listImageModels());return}if(ys(p.pathname)){if(!w.supportsImages){c(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let k={clients:w,imageModels:w.supportsImages,stats:u,turn:m()};p.pathname===rn?await Os(d,l,k):await As(d,l,k);return}if(d.method==="GET"&&p.pathname===Us){if(!w.listSpeechToTextModels){c(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}G(l,200,await w.listSpeechToTextModels());return}if(Ns(p.pathname)){if(!w.supportsTranscription){c(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${un}`,"not_implemented","not_implemented_error");return}let k={clients:w,transcriptionModels:w.supportsTranscription,stats:u,turn:m()};await Fs(d,l,k);return}if($s(p.pathname)){if(!w.supportsSpeech){c(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${St}`,"not_implemented","not_implemented_error");return}let k={clients:w,speechModels:w.supportsSpeech,stats:u,turn:m()};await Ls(d,l,k);return}if(d.method!=="POST"){c(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let R;try{R=await ii(d)}catch(k){if(k instanceof It){c(413,k.message,"request_too_large","request_too_large");return}c(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let _=Buffer.byteLength(JSON.stringify(R));if(p.pathname==="/v1/responses"){u.request("responses",_,_),await Md(R,w,ht(w),l,u,m());return}if(p.pathname==="/v1/chat/completions"){u.request("chat_completions",_,_),await Dd(R,w,l,u,m());return}if(p.pathname==="/v1/systemone"){u.request("systemone",_,_),await Bd(R,w,l,u,m());return}if(p.pathname==="/v1/messages"){u.request("messages",_,_),await Wd(R,w,l,u,m());return}if(p.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",_,_),ce(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}c(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(y=>{let w=String(y instanceof Error?y.message:y);if(!l.headersSent){let R=o?.(y)??null;if(R){c(R.status,w,R.openaiType,R.anthropicType);return}if(y instanceof yn.SessionAllocationError){let _=Jt(y.code);if(_){let k=y.retryAfterSeconds??(_.status===429?30:void 0);k!==void 0&&l.setHeader("Retry-After",String(k)),c(_.status,Zn(_,y.code??void 0),_.openaiType,_.anthropicType,_.code);return}}if(y instanceof yn.SessionFailedError){let _=Kt(y);if(_){let k=_.status===429?30:void 0;k!==void 0&&l.setHeader("Retry-After",String(k)),c(_.status,Zn(_,y.status.sessionId?`session ${y.status.sessionId}`:void 0),_.openaiType,_.anthropicType,_.code);return}}if(y instanceof B){c(502,w,"upstream_error","api_error");return}c(500,w,"proxy_error","api_error","proxy_error");return}b&&(b.streamError=!0),l.destroyed||(g?l.write(`event: error
53
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:w}})}
54
54
 
55
- `):c.write(`data: ${JSON.stringify({error:{message:g,type:"upstream_error"}})}
55
+ `):l.write(`data: ${JSON.stringify({error:{message:w,type:"upstream_error"}})}
56
56
 
57
- `)),c.end()})}}var pn=(t,e)=>Object.assign(new Error(e),{status:t});function Ks(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}async function zs(t,e,n){if(!t.supportsAudio)throw pn(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 r;try{r=await t.supportsAudio(e)}catch(i){throw i instanceof N?pn(404,i.message):i}if(!r)throw pn(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.openAudio)throw pn(501,"an audio-capable model needs a router-backed client (openAudio) to open its native session audio bridge \u2014 refusing loudly rather than binding a voiceless session");let o={audio:await t.openAudio(e,n)},s={clients:t,voice:r,audioSession:o};return e!==void 0&&(s.model=e),s}var Y=require("@prometheus-io/client"),Ys=require("http");var Xs=9464,fn="/metrics",je="(other)",ar="(none)",ur=64,dr=128,kd=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech",nn,bt],Sd=new Set(kd);function lr(t){return Sd.has(t)?t:je}function cr(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var Ge=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?ar:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,je):(this.admitted.add(e),e):je}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},Ve=class{registry=new Y.Registry;modelLabel=new Ge(ur);orgLabel=new Ge(dr);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new Y.Counter({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new Y.Histogram({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new Y.Histogram({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new Y.Counter({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new Y.Counter({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new Y.Counter({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of Us)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new Y.Gauge({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},Ms()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Ds()/1e3)}}),this.labelCardinality=new Y.Gauge({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new Y.Counter({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),e.defaultMetrics!==!1&&(0,Y.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=lr(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(e.model,r),i=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?je:e.method,status_class:cr(e.status),stream:u,model:s,org:i}),this.duration.observe({lane:n,stream:u,model:s,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:s}),e.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function mn(t){return(0,Ys.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==fn){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${fn}
57
+ `)),l.end()})}}var _n=(t,e)=>Object.assign(new Error(e),{status:t});function ci(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}async function pi(t,e,n){if(!t.supportsAudio)throw _n(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 r;try{r=await t.supportsAudio(e)}catch(a){throw a instanceof N?_n(404,a.message):a}if(!r)throw _n(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 _n(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 o=await t.sessionHandle(e),s={audio:await t.openAudioOn(o,n)},i={clients:{createResponse:async a=>await t.createResponseOn(o,a)},voice:r,audioSession:s};return e!==void 0&&(i.model=e),i}var ne=require("@prometheus-io/client"),fi=require("http");var mi=9464,vn="/metrics",Ye="(other)",yr="(none)",wr=64,_r=128,Kd=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",ln,xt],zd=new Set(Kd);function vr(t){return zd.has(t)?t:Ye}function br(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var Xe=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?yr:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,Ye):(this.admitted.add(e),e):Ye}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},Qe=class{registry=new ne.Registry;modelLabel=new Xe(wr);orgLabel=new Xe(_r);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new ne.Counter({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new ne.Histogram({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new ne.Histogram({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new ne.Counter({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new ne.Counter({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new ne.Counter({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of Zs)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ne.Gauge({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},ei()),this.ledgerQueue.set({measure:"oldest_age_seconds"},ti()/1e3)}}),this.labelCardinality=new ne.Gauge({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new ne.Counter({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),e.defaultMetrics!==!1&&(0,ne.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=vr(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(e.model,r),i=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?Ye:e.method,status_class:br(e.status),stream:u,model:s,org:i}),this.duration.observe({lane:n,stream:u,model:s,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:s}),e.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function bn(t){return(0,fi.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==vn){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${vn}
58
58
  `);return}let o=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(o)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
59
- `);return}n.end()})})}var pr=require("crypto"),Qs=require("http"),Zs=9465,fr="x-urun-key-id",mr="x-urun-key-fingerprint",gr="urun-ratelimit-bucket:",hr="urun-ratelimit-tier:",gn="anonymous",Rd=/^urun_sk_[A-Za-z0-9_-]{43}$/;function yr(t){return(0,pr.createHash)("sha256").update(`${gr}${t}`).digest("hex")}function _r(t){return(0,pr.createHash)("sha256").update(`${hr}${t}`).digest("hex")}function wr(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Rd.test(n)?n:null}function hn(){return(0,Qs.createServer)((t,e)=>{let n=wr(t.headers.authorization);e.setHeader(fr,n===null?gn:yr(n)),e.setHeader(mr,n===null?gn:_r(n)),e.writeHead(200),e.end()})}var yn=require("@urun-sh/core"),Z=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},ve=class extends Error{constructor(e){super(e),this.name="ControlPlaneUnavailableError"}};function Ce(t){let e=(t??"").trim();if(e==="")throw new Z("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new Z("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var xd=60,vr=6e4,br=4096;function Ed(t){return t===401||t===403}var We=class{constructor(e){this.opts=e;this.mint=e.mint??yn.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new Z("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<vr)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:xd})).orgId}catch(o){throw o instanceof yn.ClientTokenError&&Ed(o.status)?(this.cache.delete(e),new Z("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new ve(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new ve("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=br){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};var bn=require("crypto");var At=require("@urun-sh/core");function ei(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function ti(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),r}function ni(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var Ad="llm-resp";async function*kr(t,e){let n=`${Ad}:${e}`,r=`resp_${e}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;try{for await(let s of t.stream(n).messages()){let i=s;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let u=typeof a.index=="number"?a.index:0,d=o.get(u)??{};a.id&&(d.id=a.id),a.function?.name&&(d.name=a.function.name),o.set(u,d),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:d.id,name:d.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...i.body}};return}else if(i.t==="error"){yield ni(i);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var wn=class t{constructor(e,n=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((o,s)=>{let i=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(e){e.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=ti(e,n,this.consumerId);return this.write(r),kr(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=ei(e,n,r,this.consumerId);return this.write(o),kr(this.session,r)})}async writeGated(e,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var ri=0;function Od(){return ri+=1,`req_${Date.now().toString(36)}_${ri.toString(36)}`}var vn=class{transport;constructor(e){this.transport=new wn(e)}responses={create:async e=>{let n=Od(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};async function oi(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}var si=require("@urun-sh/core"),Sr=2;function Id(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Td(t){let e=t?.type;return e==="response.completed"||e==="error"}function ii(t){return async function(n,r){return(async function*(){for(let s=1;s<=Sr;s++){let{app:i,entry:a,identity:u}=await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:u});let d=!1,c=!1;try{let l=await t.createStream(a,n);for await(let p of l){if(Td(p)&&(d=!0),Id(p)){if(s>1)continue}else c=!0;yield p}}catch(l){if(l instanceof si.SessionFailedError&&(l.kind==="never-live"||l.kind==="create-failed")){try{t.onAdmissionVerdict?.(i,a,l)}catch{}throw l}if(s<Sr&&!c){await t.evict(i,a);continue}throw l}if(d)return;if(s<Sr&&!c){await t.evict(i,a);continue}return}})()}}var Pd=3,Cd="llm",$d=new Set(["paused","error"]);function ai(t,e){let n=t.doc(Cd),r=typeof n.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let s=null,i=!1,a=new Set,u=[],d=c=>{if(!s){s=c;for(let l of[...a])l(c);a.clear()}};return r&&u.push(n.onConnectionState(c=>{i&&(c.consecutiveFailures<Pd||d(new K(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),o&&u.push(t.onPhase(c=>{if(c.name==="live"){i=!0;return}i&&$d.has(c.name)&&d(new K(`the pooled session for app "${e}" lost its compute binding (phase "${c.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>s,onGone(c){return s?(c(s),()=>{}):(a.add(c),()=>a.delete(c))},dispose(){a.clear();for(let c of u.splice(0))c()}}}async function*Rr(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(u=>a(u))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}function ui(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function Ld(t,e,n){let{baseUrl:r,orgId:o,auth:s}=t,i=typeof t.subject=="function"?t.subject():t.subject,a=n.startsWith(Re)&&i!==void 0?`${i}:speech`:i,u=e.fnName??t.fnName,d=t.sessionStartOptions?.(n),c=e.sharedApp?{sharedApp:!0,...d}:d,l=S=>({session:S,responses:new vn(S),gone:ai(S,n)});if(s.lane==="jwt"){let S=(0,At.App)(e.appSlug,{baseUrl:r,orgId:o,jwt:s.jwt});return l(ui(S,e.appSlug,u,c))}let{apiKey:p,gatewayUrl:f}=s,_=(0,At.App)(e.appSlug,{baseUrl:r,orgId:o,getAccessToken:async()=>(await(0,At.createClientToken)(p,{baseUrl:f,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],...a===void 0?{}:{subject:a},...e.sharedApp?{sharedApp:!0}:{}})).token});return l(ui(_,e.appSlug,u,c))}function Nd(t){let e=t.session.id;if(typeof e!="string"||e.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return e}function Ud(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var Md=new Set(["error","paused"]);function Er(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=Ld(t,i,a);return t.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&t.onSessionOpen(a,u.session.id),u.gone.onGone(()=>{r?.evict(a,u)}),u},s=new Bt({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>No({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>oi(n):null,listPrices:n?()=>vo(n):null,shared:e.lane==="api-key"?()=>go({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:Nd});return r=s,t.defaultApp!==null&&t.statelessDirect!==!0&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},it({appSlug:t.defaultApp}))),s}async function xr(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,e===void 0?void 0:{signal:e})}async function di(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}function li(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Ar(t,e=Jr,n,r){let o=new WeakMap,s=new WeakMap,i=new WeakMap,a=new WeakMap,u=l=>{let p=l.session.id;return typeof p=="string"&&p.length>0?p:null},d=(l,p)=>{let f=o.get(l);return f||(f=(async()=>{await xr(l.session,p);let _=await Vr(l.session,await e());return Object.assign(_,{sessionId:l.session.id})})(),o.set(l,f),f.catch(()=>o.delete(l))),f},c=l=>{let p=a.get(l);return p||(p=(async()=>{let f=await d(l);return{appendInputAudio:_=>f.appendInputAudio(_),onOutputAudio:_=>f.onOutputAudio(_),sessionId:u(l)}})(),a.set(l,p),p.catch(()=>a.delete(l))),p};return{createResponse:ii({sessionFor:l=>t.sessionFor(l),sessionIdOf:l=>u(l),evict:(l,p)=>t.evict(l,p),onAdmissionVerdict:(l,p,f)=>{Ud(f)&&(t.evict(l,p),n?.(l,f.kind==="never-live"?"never-live":"create-failed"))},createStream:async(l,p)=>(await xr(l.session),Rr(await l.responses.responses.create(p),l.gone))}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(l,p)=>t.supportsImages(l,p),listImageModels:()=>t.imageModelList(),catalogIdentity:l=>t.catalogIdentityFor(l),servingAppSlug:async l=>await t.servingAppSlugFor(l),supportsAudio:l=>t.supportsAudio(l),supportsSpeech:l=>t.supportsSpeech(l),speechVoices:l=>t.speechVoices(l),openAudio:async(l,p)=>{let{entry:f}=await t.sessionFor(l);if(p?.aborted)throw await di(f.session),li(p);let _=d(f,p);return p===void 0?_:new Promise((S,h)=>{let m=()=>{di(f.session).catch(()=>{}),h(li(p))};p.addEventListener("abort",m,{once:!0});let y=()=>p.removeEventListener("abort",m);_.then(g=>{y(),S(g)},g=>{y(),h(g)})})},openAudioOn:async l=>c((await t.sessionForHandle(l)).entry),openVideo:async l=>{let{entry:p}=await t.sessionFor(l),f=s.get(p);return f||(f=Wr(p.session),s.set(p,f)),f},openVideoOut:async l=>{let{entry:p}=await t.sessionFor(l),f=i.get(p);return f||(f=zr(p.session),i.set(p,f)),f},sessionHandle:async l=>(await t.handleFor(l)).handle,speechSessionHandle:async l=>(await t.speechHandleFor(l)).handle,evictSpeechSession:async l=>{let{app:p,entry:f}=await t.sessionForHandle(l);await t.evict(p,f)},createResponseOn:async(l,p)=>{let{entry:f}=await t.sessionForHandle(l);return await xr(f.session),Rr(await f.responses.responses.create(p),f.gone)},onSessionEnd:async(l,p)=>{let{entry:f}=await t.sessionForHandle(l),_=f.session;if(typeof _.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let S=!1;return _.onPhase(h=>{if(S||!Md.has(h.name))return;S=!0;let m=_.endsAt??null;p({timeLeftMs:m?Math.max(0,m.getTime()-Date.now()):null,reason:h.reason??`session ${h.name}`})})},...r?{stateless:r}:{}}}var Or=8080,Je="serve",ci="0.0.0.0";function Dd(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function pi(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Or:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=Xo(Vt(Dd(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),s=o?Vt(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let u=i?{catalogUrl:Vt(i,"URUN_CATALOG_URL"),anonKey:a}:null,d=(t.URUN_SESSION_TOKEN_SECRET??"").trim(),c=(t.URUN_SHARED_ORG_API_KEY??"").trim(),l=(t.URUN_SHARED_ORG_ID??"").trim();if(!!c!=!!l)throw new Error("URUN_SHARED_ORG_API_KEY and URUN_SHARED_ORG_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would silently leave the shared endpoints on the session lane");return{port:n,baseUrl:r,apiUrl:s,catalog:u,decisionSecret:d,sharedOrgKey:c,sharedOrgId:l}}var Ir=512;function Xe(t){return`urun-inference-proxy-${(0,bn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Ke=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){return Object.assign(Object.create(e),{tenant:n.orgId})}build(e){if(this.opts.build){let a=this.opts.build(e);return{router:a.router,clients:this.label(a.clients,e)}}let n=0,r=Xe(e.apiKey),o=()=>{n+=1},s=Er({baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Je,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,subject:()=>n===0?r:`${r}#${n}`,onPoolWedged:o,release:"end"}),i=this.opts.decisionIntake?new sn({targetFor:a=>s.targetFor(a),apiUrl:this.opts.apiUrl,apiKey:e.apiKey,orgId:e.orgId,fnName:Je,secret:this.opts.decisionIntake.secret,...this.opts.decisionIntake.shared?{shared:this.opts.decisionIntake.shared}:{}}):void 0;return{router:s,clients:this.label(Ar(s,void 0,o,i),e)}}clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=Ir;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}async closeAll(){let e=[...this.tenants.values()].map(r=>r.router);this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r.closeAll()}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},kn=512,Tr=1024,ze=class extends Error{constructor(){super(`conversation capacity reached (${kn} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Fd(t){return{sessionStartOptions:e=>{if(e.startsWith(Re))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(Re)||t.set(e,n)}}}function Bd(t,e,n,r){let o=Er({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Je,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalog,subject:n.subject,release:"detach",...Fd(r)});return{clients:Ar(o),release:async()=>{await o.closeAll()}}}var Ye=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${Xe(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):Bd(this.opts,e,r,o);return{id:n,backhaul:s,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let s=this.build(e,n);return s.attachments=1,r.set(n,s),s}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=kn;){let e=this.byCaller.keys().next();if(e.done)throw new ze;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[s,i]of r)if(!(i.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),i.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new ze;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,(0,bn.randomUUID)())),n),s={createResponse:(i,a)=>o().backhaul.clients.createResponse(i,a),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),createResponseOn:(i,a)=>o().backhaul.clients.createResponseOn(i,a),onSessionEnd:(i,a)=>o().backhaul.clients.onSessionEnd(i,a)};return s.openAudio=async(i,a)=>{let u=o().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(i,a)},s.openVideo=async i=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(i)},s.openVideoOut=async i=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(i)},s.supportsAudio=async i=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(i)},s.supportsSpeech=async i=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(i)},s.speechVoices=async i=>{let a=o().backhaul.clients.speechVoices;if(a===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return a(i)},s.speechSessionHandle=async i=>{let a=o().backhaul.clients.speechSessionHandle;if(a===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return a(i)},s.openAudioOn=async i=>{let a=o().backhaul.clients.openAudioOn;if(a===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech lane cannot open its pinned native session audio on this deployment");return a(i)},s.evictSpeechSession=async i=>{let a=o().backhaul.clients.evictSpeechSession;if(a===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return a(i)},{clients:s,bindResumeHandle:i=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Tr;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async i=>{let a=this.byHandle.get(i),u=a===void 0?void 0:this.byCaller.get(a.apiKey),d=a===void 0||u===void 0?void 0:u.get(a.conversationId);if(a===void 0||d===void 0||a.apiKey!==e.apiKey)throw new K("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(r)return;r=!0;let i=n;n=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};var Sn="/inference-usage",fi=25e3;var qd=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function mi(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=qd.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var Rn=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Sn}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(fi)})}catch(i){throw new D(`the uRun usage surface (POST ${Sn}) could not be reached within ${fi}ms: ${mi(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new Z("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new D(`the uRun usage surface (POST ${Sn}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new D(`the uRun usage surface (POST ${Sn}) answered HTTP ${o.status} with a body that is not JSON: ${mi(i)}`)}return Ts(s,this.opts.onRejectedRow)}};var Lr="/inference-ledger",Nr=1e4,Qe=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Cr=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},W=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},$r=class extends Z{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Hd=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",gi],["cost_nano_usd",gi],["price_version",t=>t===null||typeof t=="string"]];function jd(t){for(let[e,n]of Hd){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Gd(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:jd(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function gi(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Pr(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function hi(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Vd(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&hi(t.started_at,n.started_at)&&hi(t.completed_at,n.completed_at)&&Pr(t.prompt_tokens,n.prompt_tokens)&&Pr(t.completion_tokens,n.completion_tokens)&&Pr(t.output_units,n.output_units)}function Ur(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new W(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new W(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new W(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new W(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=d=>{if(!(d in n))throw new W(`${e} answered a row with no ${d} field: ${JSON.stringify(t)}`);let c=n[d];if(c===null)return null;if(typeof c!="string")throw new W(`${e} answered a non-string ${d}: ${JSON.stringify(c)}`);if(!/[^\s]/.test(c))throw new W(`${e} answered a BLANK ${d} (${JSON.stringify(c)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return c},i=s("price_version"),a=s("unpriced_reason"),u=o!=null;if(u&&(i===null||a!==null))throw new W(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(i!==null||a===null))throw new W(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var Ze=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Lr}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(n),signal:AbortSignal.timeout(Nr)})}catch(u){throw new W(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(o.status===409){let u=await o.text().catch(()=>""),d=Gd(u);throw d.status==="found"&&Vd(n,d.row)?new Cr(d.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):d.status==="not_in_this_org"?new Qe(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new Qe(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${u.slice(0,400)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new $r("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!o.ok){let u=await o.text().catch(d=>`<body unreadable: ${d instanceof Error?d.message:String(d)}>`);throw new W(`the uRun ledger surface at ${r} answered HTTP ${o.status}: ${u.slice(0,400)}`)}let s;try{s=await o.json()}catch(u){throw new W(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let i=s?.recorded;if(i===void 0)throw new W(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let a=Ur(i,`the uRun ledger surface at ${r}`);if(a.inference_id!==n.inference_id)throw new W(`the uRun ledger surface at ${r} answered for inference_id ${a.inference_id} when asked about ${n.inference_id}`);return a}};var Dr=5e3,Fr=3e3,Wd="/api/client-tokens";function Mr(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function yi(t,e,n,r){Mr(t,e,{error:{message:n,type:r}})}async function Jd(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Wd}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Fr)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function wi(t){let e=t.resolver??new We({gatewayUrl:t.baseUrl}),n=t.decisionSecret??"",r=t.sharedOrgKey&&t.sharedOrgId?{apiKey:t.sharedOrgKey}:void 0,o=t.registry??new Ke({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog,...n!==""?{decisionIntake:{secret:n,...r?{shared:r}:{}}}:{}});n!==""&&process.stderr.write(`inference-proxy: stateless direct path ENABLED \u2014 caller-org decisions dial ready runtimes directly (no session mint)
60
- `);let s=t.probeControlPlane??(()=>Jd(t.baseUrl)),i=t.usageClient??new Rn({apiUrl:t.apiUrl}),a=t.ledgerClient??new Ze({apiUrl:t.apiUrl}),u=new Ve(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),d=async m=>e.resolve(Ce(m.headers.authorization)),c=m=>m instanceof Z?{status:m.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:m instanceof ve?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null,l=Js({clients:async m=>o.clientsFor(await d(m)),usage:{authorize:m=>Ce(m.headers.authorization),lookup:(m,y)=>i.lookup(m,y)},statusOf:c,...t.requestLog?{requestLog:t.requestLog}:{},observe:m=>u.observe(m),ledger:{write:(m,y)=>a.write(Ce(m.headers.authorization),y),observe:m=>u.observeLedger(m),...t.ledgerLog?{report:t.ledgerLog}:{}}}),p=null,f=(0,_i.createServer)((m,y)=>{let g=new URL(m.url??"/","http://localhost");(async()=>{if(m.method==="GET"&&g.pathname==="/healthz"){Mr(y,200,{ok:!0});return}if(m.method==="GET"&&g.pathname==="/readyz"){let b=Date.now();if(!p||b-p.at>=Dr){let w=await s();p={at:b,...w}}Mr(y,p.ready?200:503,{ok:p.ready,control_plane:p.detail});return}let R=g.pathname==="/v1"||g.pathname.startsWith("/v1/"),v=g.pathname.startsWith("/partners/");if(!R&&!v){yi(y,404,`no route for ${m.method} ${g.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz and /readyz`,"invalid_request_error");return}l(m,y)})().catch(R=>{if(!y.headersSent){yi(y,500,String(R instanceof Error?R.message:R),"proxy_error");return}y.end()})}),_=t.conversations??new Ye({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),S=[Nn(f,{authenticate:async m=>{let y=await e.resolve(m),g=_.connectionFor(y);return{clients:g.clients,scope:Xe(y.apiKey),onBindResumeHandle:g.bindResumeHandle,clientsForResume:g.clientsForResume,release:g.release}}}),jn(f,{clients:async m=>o.clientsFor(await d(m)),statusOf:c}).close,Yt(f,{resolver:{resolve:async(m,y)=>{let g=await e.resolve(Ce(m.headers.authorization)),R=_.connectionFor(g),v;try{v=await zs(R.clients,Ks(m),y)}catch(b){throw R.release().catch(()=>{}),b}return{...v,release:R.release}}}})];f.on("upgrade",(m,y)=>{let g=new URL(m.url??"/","http://localhost");g.pathname===$t||g.pathname===qn||g.pathname===ht||y.destroyed||(y.write(`HTTP/1.1 404 Not Found\r
59
+ `);return}n.end()})})}var kr=require("crypto"),gi=require("http"),hi=9465,Sr="x-urun-key-id",Rr="x-urun-key-fingerprint",xr="urun-ratelimit-bucket:",Er="urun-ratelimit-tier:",kn="anonymous",Yd=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Ar(t){return(0,kr.createHash)("sha256").update(`${xr}${t}`).digest("hex")}function Or(t){return(0,kr.createHash)("sha256").update(`${Er}${t}`).digest("hex")}function Ir(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Yd.test(n)?n:null}function Sn(){return(0,gi.createServer)((t,e)=>{let n=Ir(t.headers.authorization);e.setHeader(Sr,n===null?kn:Ar(n)),e.setHeader(Rr,n===null?kn:Or(n)),e.writeHead(200),e.end()})}var Rn=require("@urun-sh/core"),se=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Ee=class extends Error{constructor(e){super(e),this.name="ControlPlaneUnavailableError"}};function Me(t){let e=(t??"").trim();if(e==="")throw new se("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new se("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var Xd=60,Tr=6e4,Pr=4096;function Qd(t){return t===401||t===403}var Ze=class{constructor(e){this.opts=e;this.mint=e.mint??Rn.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new se("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<Tr)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:Xd})).orgId}catch(o){throw o instanceof Rn.ClientTokenError&&Qd(o.status)?(this.cache.delete(e),new se("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Ee(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new Ee("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=Pr){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};var On=require("crypto");var Pt=require("@urun-sh/core");function yi(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function wi(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}function _i(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var Zd="llm-resp";async function*Cr(t,e){let n=`${Zd}:${e}`,r=`resp_${e}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;try{for await(let s of t.stream(n).messages()){let i=s;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let u=typeof a.index=="number"?a.index:0,d=o.get(u)??{};a.id&&(d.id=a.id),a.function?.name&&(d.name=a.function.name),o.set(u,d),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:d.id,name:d.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...i.body}};return}else if(i.t==="error"){yield _i(i);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var En=class t{constructor(e,n=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((o,s)=>{let i=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(e){e.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=wi(e,n,this.consumerId);return this.write(r),Cr(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=yi(e,n,r,this.consumerId);return this.write(o),Cr(this.session,r)})}async writeGated(e,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var vi=0;function el(){return vi+=1,`req_${Date.now().toString(36)}_${vi.toString(36)}`}var An=class{transport;constructor(e){this.transport=new En(e)}responses={create:async e=>{let n=el(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};async function bi(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}var ki=require("@urun-sh/core"),$r=2;function tl(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function nl(t){let e=t?.type;return e==="response.completed"||e==="error"}function Si(t){return async function(n,r){return(async function*(){for(let s=1;s<=$r;s++){let{app:i,entry:a,identity:u}=await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:u});let d=!1,l=!1;try{let p=await t.createStream(a,n);for await(let g of p){if(nl(g)&&(d=!0),tl(g)){if(s>1)continue}else l=!0;yield g}}catch(p){if(p instanceof ki.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(i,a,p)}catch{}throw p}if(s<$r&&!l){await t.evict(i,a);continue}throw p}if(d)return;if(s<$r&&!l){await t.evict(i,a);continue}return}})()}}var rl=3,ol="llm",sl=new Set(["paused","error"]);function Ri(t,e){let n=t.doc(ol),r=typeof n.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let s=null,i=!1,a=new Set,u=[],d=l=>{if(!s){s=l;for(let p of[...a])p(l);a.clear()}};return r&&u.push(n.onConnectionState(l=>{i&&(l.consecutiveFailures<rl||d(new W(`the pooled session for app "${e}" is gone: its doc backhaul failed ${l.consecutiveFailures} consecutive times (last close ${l.lastCloseCode===null?"by provider liveness reap":`code ${l.lastCloseCode}`}${l.lastCloseReason?`, reason ${JSON.stringify(l.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),o&&u.push(t.onPhase(l=>{if(l.name==="live"){i=!0;return}i&&sl.has(l.name)&&d(new W(`the pooled session for app "${e}" lost its compute binding (phase "${l.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>s,onGone(l){return s?(l(s),()=>{}):(a.add(l),()=>a.delete(l))},dispose(){a.clear();for(let l of u.splice(0))l()}}}async function*Lr(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(u=>a(u))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}function xi(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function il(t,e,n){let{baseUrl:r,orgId:o,auth:s}=t,i=typeof t.subject=="function"?t.subject():t.subject,a=n.startsWith(Ie)&&i!==void 0?`${i}:speech`:i,u=e.fnName??t.fnName,d=t.sessionStartOptions?.(n),l=e.sharedApp?{sharedApp:!0,...d}:d,p=h=>({session:h,responses:new An(h),gone:Ri(h,n)});if(s.lane==="jwt"){let h=(0,Pt.App)(e.appSlug,{baseUrl:r,orgId:o,jwt:s.jwt});return p(xi(h,e.appSlug,u,l))}let{apiKey:g,gatewayUrl:c}=s,f=(0,Pt.App)(e.appSlug,{baseUrl:r,orgId:o,getAccessToken:async()=>(await(0,Pt.createClientToken)(g,{baseUrl:c,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],...a===void 0?{}:{subject:a},...e.sharedApp?{sharedApp:!0}:{}})).token});return p(xi(f,e.appSlug,u,l))}function al(t){let e=t.session.id;if(typeof e!="string"||e.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return e}function ul(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var dl=new Set(["error","paused"]);function Mr(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=il(t,i,a);return t.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&t.onSessionOpen(a,u.session.id),u.gone.onGone(()=>{r?.evict(a,u)}),u},s=new Vt({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>Wo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>bi(n):null,listPrices:n?()=>Co(n):null,shared:e.lane==="api-key"?()=>Ao({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:al});return r=s,t.defaultApp!==null&&t.statelessDirect!==!0&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},ct({appSlug:t.defaultApp}))),s}async function Nr(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,e===void 0?void 0:{signal:e})}async function Ei(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}function Ur(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Dr(t,e=so,n,r){let o=new WeakMap,s=new WeakMap,i=new WeakMap,a=new WeakMap,u=new WeakMap,d=c=>{let f=c.session.id;return typeof f=="string"&&f.length>0?f:null},l=c=>{let f=o.get(c);if(!f){let h={waiting:0,gone:new AbortController};u.set(c,h),f=(async()=>{if(await Nr(c.session,h.gone.signal),h.gone.signal.aborted)throw Ur(h.gone.signal);u.get(c)===h&&u.delete(c);let b=await ro(c.session,await e());return Object.assign(b,{sessionId:c.session.id})})(),o.set(c,f),f.catch(()=>{o.get(c)===f&&o.delete(c)}),f.then(()=>{u.get(c)===h&&u.delete(c)},()=>{u.get(c)===h&&u.delete(c)})}return f},p=c=>{let f=a.get(c);return f||(f=(async()=>{let h=await l(c);return{appendInputAudio:b=>h.appendInputAudio(b),onOutputAudio:b=>h.onOutputAudio(b),sessionId:d(c)}})(),a.set(c,f),f.catch(()=>{a.get(c)===f&&a.delete(c)})),f},g=async(c,f,h)=>{if(h?.aborted){let y=u.get(c);throw(o.get(c)===void 0||y!==void 0&&y.waiting===0)&&await Ei(c.session),Ur(h)}let b=f(c),m=u.get(c);return m!==void 0&&m.waiting++,h===void 0?b:new Promise((y,w)=>{let R=()=>{m!==void 0&&--m.waiting===0&&u.get(c)===m&&(m.gone.abort(),u.delete(c),o.delete(c),a.delete(c),Ei(c.session).catch(()=>{})),w(Ur(h))};h.addEventListener("abort",R,{once:!0});let _=()=>h.removeEventListener("abort",R);b.then(k=>{_(),y(k)},k=>{_(),w(k)})})};return{createResponse:Si({sessionFor:c=>t.sessionFor(c),sessionIdOf:c=>d(c),evict:(c,f)=>t.evict(c,f),onAdmissionVerdict:(c,f,h)=>{ul(h)&&(t.evict(c,f),n?.(c,h.kind==="never-live"?"never-live":"create-failed"))},createStream:async(c,f)=>(await Nr(c.session),Lr(await c.responses.responses.create(f),c.gone))}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(c,f)=>t.supportsImages(c,f),listImageModels:()=>t.imageModelList(),catalogIdentity:c=>t.catalogIdentityFor(c),servingAppSlug:async c=>await t.servingAppSlugFor(c),supportsAudio:c=>t.supportsAudio(c),supportsSpeech:c=>t.supportsSpeech(c),speechVoices:c=>t.speechVoices(c),supportsTranscription:c=>t.supportsTranscription(c),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(c,f)=>{let{entry:h}=await t.sessionFor(c);return await g(h,l,f)},openAudioOn:async(c,f)=>{let{entry:h}=await t.sessionForHandle(c);return await g(h,p,f)},openVideo:async c=>{let{entry:f}=await t.sessionFor(c),h=s.get(f);return h||(h=oo(f.session),s.set(f,h)),h},openVideoOut:async c=>{let{entry:f}=await t.sessionFor(c),h=i.get(f);return h||(h=ao(f.session),i.set(f,h)),h},sessionHandle:async c=>(await t.handleFor(c)).handle,speechSessionHandle:async c=>(await t.speechHandleFor(c)).handle,evictSpeechSession:async c=>{let{app:f,entry:h}=await t.sessionForHandle(c);await t.evict(f,h)},createResponseOn:async(c,f)=>{let{entry:h}=await t.sessionForHandle(c);return await Nr(h.session),Lr(await h.responses.responses.create(f),h.gone)},onSessionEnd:async(c,f)=>{let{entry:h}=await t.sessionForHandle(c),b=h.session;if(typeof b.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let m=!1;return b.onPhase(y=>{if(m||!dl.has(y.name))return;m=!0;let w=b.endsAt??null;f({timeLeftMs:w?Math.max(0,w.getTime()-Date.now()):null,reason:y.reason??`session ${y.name}`})})},...r?{stateless:r}:{}}}var Fr=8080,et="serve",Ai="0.0.0.0";function ll(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Oi(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Fr:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=us(zt(ll(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),s=o?zt(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let u=i?{catalogUrl:zt(i,"URUN_CATALOG_URL"),anonKey:a}:null,d=(t.URUN_SESSION_TOKEN_SECRET??"").trim(),l=(t.URUN_SHARED_ORG_API_KEY??"").trim(),p=(t.URUN_SHARED_ORG_ID??"").trim();if(!!l!=!!p)throw new Error("URUN_SHARED_ORG_API_KEY and URUN_SHARED_ORG_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would silently leave the shared endpoints on the session lane");return{port:n,baseUrl:r,apiUrl:s,catalog:u,decisionSecret:d,sharedOrgKey:l,sharedOrgId:p}}var Br=512;function ot(t){return`urun-inference-proxy-${(0,On.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var tt=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){return Object.assign(Object.create(e),{tenant:n.orgId})}build(e){if(this.opts.build){let a=this.opts.build(e);return{router:a.router,clients:this.label(a.clients,e)}}let n=0,r=ot(e.apiKey),o=()=>{n+=1},s=Mr({baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:et,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,subject:()=>n===0?r:`${r}#${n}`,onPoolWedged:o,release:"end"}),i=this.opts.decisionIntake?new fn({targetFor:a=>s.targetFor(a),apiUrl:this.opts.apiUrl,apiKey:e.apiKey,orgId:e.orgId,fnName:et,secret:this.opts.decisionIntake.secret,...this.opts.decisionIntake.shared?{shared:this.opts.decisionIntake.shared}:{}}):void 0;return{router:s,clients:this.label(Dr(s,void 0,o,i),e)}}clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=Br;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}async closeAll(){let e=[...this.tenants.values()].map(r=>r.router);this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r.closeAll()}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},In=512,qr=1024,nt=class extends Error{constructor(){super(`conversation capacity reached (${In} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function cl(t){return{sessionStartOptions:e=>{if(e.startsWith(Ie))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(Ie)||t.set(e,n)}}}function pl(t,e,n,r){let o=Mr({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:et,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalog,subject:n.subject,release:"detach",...cl(r)});return{clients:Dr(o),release:async()=>{await o.closeAll()}}}var rt=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${ot(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):pl(this.opts,e,r,o);return{id:n,backhaul:s,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let s=this.build(e,n);return s.attachments=1,r.set(n,s),s}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=In;){let e=this.byCaller.keys().next();if(e.done)throw new nt;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[s,i]of r)if(!(i.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),i.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new nt;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,(0,On.randomUUID)())),n),s={createResponse:(i,a)=>o().backhaul.clients.createResponse(i,a),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),createResponseOn:(i,a)=>o().backhaul.clients.createResponseOn(i,a),onSessionEnd:(i,a)=>o().backhaul.clients.onSessionEnd(i,a)};return s.openAudio=async(i,a)=>{let u=o().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(i,a)},s.openVideo=async i=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(i)},s.openVideoOut=async i=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(i)},s.supportsAudio=async i=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(i)},s.supportsSpeech=async i=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(i)},s.speechVoices=async i=>{let a=o().backhaul.clients.speechVoices;if(a===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return a(i)},s.speechSessionHandle=async i=>{let a=o().backhaul.clients.speechSessionHandle;if(a===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return a(i)},s.openAudioOn=async(i,a)=>{let u=o().backhaul.clients.openAudioOn;if(u===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return u(i,a)},s.evictSpeechSession=async i=>{let a=o().backhaul.clients.evictSpeechSession;if(a===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return a(i)},s.supportsTranscription=async i=>{let a=o().backhaul.clients.supportsTranscription;if(a===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return a(i)},s.listSpeechToTextModels=async()=>{let i=o().backhaul.clients.listSpeechToTextModels;if(i===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return i()},{clients:s,bindResumeHandle:i=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=qr;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async i=>{let a=this.byHandle.get(i),u=a===void 0?void 0:this.byCaller.get(a.apiKey),d=a===void 0||u===void 0?void 0:u.get(a.conversationId);if(a===void 0||d===void 0||a.apiKey!==e.apiKey)throw new W("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(r)return;r=!0;let i=n;n=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};var Tn="/inference-usage",Ii=25e3;var fl=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Ti(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=fl.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var Pn=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Tn}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(Ii)})}catch(i){throw new B(`the uRun usage surface (POST ${Tn}) could not be reached within ${Ii}ms: ${Ti(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new se("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new B(`the uRun usage surface (POST ${Tn}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new B(`the uRun usage surface (POST ${Tn}) answered HTTP ${o.status} with a body that is not JSON: ${Ti(i)}`)}return Js(s,this.opts.onRejectedRow)}};var Vr="/inference-ledger",Wr=1e4,st=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Hr=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},z=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Gr=class extends se{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ml=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",Pi],["cost_nano_usd",Pi],["price_version",t=>t===null||typeof t=="string"]];function gl(t){for(let[e,n]of ml){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function hl(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:gl(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Pi(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function jr(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Ci(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function yl(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&Ci(t.started_at,n.started_at)&&Ci(t.completed_at,n.completed_at)&&jr(t.prompt_tokens,n.prompt_tokens)&&jr(t.completion_tokens,n.completion_tokens)&&jr(t.output_units,n.output_units)}function Jr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new z(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new z(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new z(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new z(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=d=>{if(!(d in n))throw new z(`${e} answered a row with no ${d} field: ${JSON.stringify(t)}`);let l=n[d];if(l===null)return null;if(typeof l!="string")throw new z(`${e} answered a non-string ${d}: ${JSON.stringify(l)}`);if(!/[^\s]/.test(l))throw new z(`${e} answered a BLANK ${d} (${JSON.stringify(l)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return l},i=s("price_version"),a=s("unpriced_reason"),u=o!=null;if(u&&(i===null||a!==null))throw new z(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(i!==null||a===null))throw new z(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var it=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Vr}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(n),signal:AbortSignal.timeout(Wr)})}catch(u){throw new z(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(o.status===409){let u=await o.text().catch(()=>""),d=hl(u);throw d.status==="found"&&yl(n,d.row)?new Hr(d.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):d.status==="not_in_this_org"?new st(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new st(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${u.slice(0,400)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new Gr("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!o.ok){let u=await o.text().catch(d=>`<body unreadable: ${d instanceof Error?d.message:String(d)}>`);throw new z(`the uRun ledger surface at ${r} answered HTTP ${o.status}: ${u.slice(0,400)}`)}let s;try{s=await o.json()}catch(u){throw new z(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let i=s?.recorded;if(i===void 0)throw new z(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let a=Jr(i,`the uRun ledger surface at ${r}`);if(a.inference_id!==n.inference_id)throw new z(`the uRun ledger surface at ${r} answered for inference_id ${a.inference_id} when asked about ${n.inference_id}`);return a}};var zr=5e3,Yr=3e3,wl="/api/client-tokens";function Kr(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function $i(t,e,n,r){Kr(t,e,{error:{message:n,type:r}})}async function _l(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${wl}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Yr)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function Ni(t){let e=t.resolver??new Ze({gatewayUrl:t.baseUrl}),n=t.decisionSecret??"",r=t.sharedOrgKey&&t.sharedOrgId?{apiKey:t.sharedOrgKey}:void 0,o=t.registry??new tt({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog,...n!==""?{decisionIntake:{secret:n,...r?{shared:r}:{}}}:{}});n!==""&&process.stderr.write(`inference-proxy: stateless direct path ENABLED \u2014 caller-org decisions dial ready runtimes directly (no session mint)
60
+ `);let s=t.probeControlPlane??(()=>_l(t.baseUrl)),i=t.usageClient??new Pn({apiUrl:t.apiUrl}),a=t.ledgerClient??new it({apiUrl:t.apiUrl}),u=new Qe(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),d=async m=>e.resolve(Me(m.headers.authorization)),l=m=>m instanceof se?{status:m.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:m instanceof Ee?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null,p=li({clients:async m=>o.clientsFor(await d(m)),usage:{authorize:m=>Me(m.headers.authorization),lookup:(m,y)=>i.lookup(m,y)},statusOf:l,...t.requestLog?{requestLog:t.requestLog}:{},observe:m=>u.observe(m),ledger:{write:(m,y)=>a.write(Me(m.headers.authorization),y),observe:m=>u.observeLedger(m),...t.ledgerLog?{report:t.ledgerLog}:{}}}),g=null,c=(0,Li.createServer)((m,y)=>{let w=new URL(m.url??"/","http://localhost");(async()=>{if(m.method==="GET"&&w.pathname==="/healthz"){Kr(y,200,{ok:!0});return}if(m.method==="GET"&&w.pathname==="/readyz"){let k=Date.now();if(!g||k-g.at>=zr){let v=await s();g={at:k,...v}}Kr(y,g.ready?200:503,{ok:g.ready,control_plane:g.detail});return}let R=w.pathname==="/v1"||w.pathname.startsWith("/v1/"),_=w.pathname.startsWith("/partners/");if(!R&&!_){$i(y,404,`no route for ${m.method} ${w.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz and /readyz`,"invalid_request_error");return}p(m,y)})().catch(R=>{if(!y.headersSent){$i(y,500,String(R instanceof Error?R.message:R),"proxy_error");return}y.end()})}),f=t.conversations??new rt({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),h=[Gn(c,{authenticate:async m=>{let y=await e.resolve(m),w=f.connectionFor(y);return{clients:w.clients,scope:ot(y.apiKey),onBindResumeHandle:w.bindResumeHandle,clientsForResume:w.clientsForResume,release:w.release}}}),Qn(c,{clients:async m=>o.clientsFor(await d(m)),statusOf:l}).close,en(c,{resolver:{resolve:async(m,y)=>{let w=await e.resolve(Me(m.headers.authorization)),R=f.connectionFor(w),_;try{_=await pi(R.clients,ci(m),y)}catch(k){throw R.release().catch(()=>{}),k}return{..._,release:R.release}}}})];c.on("upgrade",(m,y)=>{let w=new URL(m.url??"/","http://localhost");w.pathname===Ft||w.pathname===Yn||w.pathname===vt||y.destroyed||(y.write(`HTTP/1.1 404 Not Found\r
61
61
  Connection: close\r
62
62
  \r
63
- no WS route for ${g.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),y.destroy())});let h=async()=>{for(let m of S)await m();await _.detachAll()};return{server:f,metricsServer:mn(u),metrics:u,edgeIdentityServer:hn(),registry:o,closeAll:()=>o.closeAll(),closeWebSockets:h}}0&&(module.exports={ANONYMOUS_KEY_ID,BIND_HOST,BUCKET_DOMAIN,BoundedLabel,ControlPlaneUnavailableError,ConversationBackhauls,ConversationCapacityError,DEFAULT_PORT,EDGE_IDENTITY_PORT,EDGE_KEY_FINGERPRINT_HEADER,EDGE_KEY_ID_HEADER,InferenceMetrics,LEDGER_FUNCTION_PATH,LEDGER_WRITE_TIMEOUT_MS,LedgerClient,LedgerDuplicateError,LedgerSurfaceError,MAX_CACHED_KEYS,MAX_CONVERSATIONS,MAX_CONVERSATION_HANDLES,MAX_MODEL_LABELS,MAX_ORG_LABELS,MAX_TENANTS,METRICS_PATH,METRICS_PORT,NO_MODEL_LABEL,ORG_BINDING_TTL_MS,OTHER_LABEL,OrgResolver,ProxyAuthError,READINESS_TIMEOUT_MS,READINESS_TTL_MS,SERVE_FUNCTION,TIER_DOMAIN,TenantRegistry,bearerFrom,bearerTokenOf,createEdgeIdentityServer,createHostedProxy,createMetricsServer,edgeBucketId,edgeTierFingerprint,laneOf,parseLedgerRecorded,resolveHostedConfig,statusClassOf,tenantSubject});
63
+ no WS route for ${w.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),y.destroy())});let b=async()=>{for(let m of h)await m();await f.detachAll()};return{server:c,metricsServer:bn(u),metrics:u,edgeIdentityServer:Sn(),registry:o,closeAll:()=>o.closeAll(),closeWebSockets:b}}0&&(module.exports={ANONYMOUS_KEY_ID,BIND_HOST,BUCKET_DOMAIN,BoundedLabel,ControlPlaneUnavailableError,ConversationBackhauls,ConversationCapacityError,DEFAULT_PORT,EDGE_IDENTITY_PORT,EDGE_KEY_FINGERPRINT_HEADER,EDGE_KEY_ID_HEADER,InferenceMetrics,LEDGER_FUNCTION_PATH,LEDGER_WRITE_TIMEOUT_MS,LedgerClient,LedgerDuplicateError,LedgerSurfaceError,MAX_CACHED_KEYS,MAX_CONVERSATIONS,MAX_CONVERSATION_HANDLES,MAX_MODEL_LABELS,MAX_ORG_LABELS,MAX_TENANTS,METRICS_PATH,METRICS_PORT,NO_MODEL_LABEL,ORG_BINDING_TTL_MS,OTHER_LABEL,OrgResolver,ProxyAuthError,READINESS_TIMEOUT_MS,READINESS_TTL_MS,SERVE_FUNCTION,TIER_DOMAIN,TenantRegistry,bearerFrom,bearerTokenOf,createEdgeIdentityServer,createHostedProxy,createMetricsServer,edgeBucketId,edgeTierFingerprint,laneOf,parseLedgerRecorded,resolveHostedConfig,statusClassOf,tenantSubject});