@urun-sh/openai 0.6.38 → 0.6.40

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.
Files changed (44) hide show
  1. package/dist/{chunk-B26FENQ3.js → chunk-BWYY4IPR.js} +1 -1
  2. package/dist/chunk-G5VRFFBE.js +64 -0
  3. package/dist/chunk-G7CSAISC.js +1 -0
  4. package/dist/{chunk-7AI75MPZ.js → chunk-HPUX2H65.js} +6 -6
  5. package/dist/{chunk-5MH6NSR2.js → chunk-L4QBHSVY.js} +1 -1
  6. package/dist/chunk-L6CT7ZVO.js +23 -0
  7. package/dist/chunk-PT5N7AY7.js +2 -0
  8. package/dist/{chunk-3JWYIKHM.js → chunk-QTHFMDZY.js} +1 -1
  9. package/dist/chunk-Z3QCHKJB.js +1 -0
  10. package/dist/{composite-ClDE3ViI.d.ts → composite-B--rGI5m.d.ts} +8 -2
  11. package/dist/{composite-F94H40CD.d.cts → composite-B-F2J0NK.d.cts} +40 -2
  12. package/dist/gemini-live.cjs +2 -2
  13. package/dist/gemini-live.d.cts +2 -2
  14. package/dist/gemini-live.d.ts +2 -2
  15. package/dist/gemini-live.js +1 -1
  16. package/dist/hosted/bin.cjs +48 -48
  17. package/dist/hosted/bin.js +1 -1
  18. package/dist/hosted/index.cjs +46 -46
  19. package/dist/hosted/index.d.cts +3 -3
  20. package/dist/hosted/index.d.ts +3 -3
  21. package/dist/hosted/index.js +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.d.cts +2 -2
  24. package/dist/index.d.ts +2 -2
  25. package/dist/index.js +1 -1
  26. package/dist/pi-extension/index.js +1 -1
  27. package/dist/pi-extension/standalone.cjs +55 -55
  28. package/dist/pooler/bin.cjs +7 -7
  29. package/dist/pooler/bin.js +25 -25
  30. package/dist/proxy/cli.cjs +51 -51
  31. package/dist/proxy/cli.js +1 -1
  32. package/dist/proxy/index.cjs +26 -26
  33. package/dist/proxy/index.d.cts +35 -5
  34. package/dist/proxy/index.d.ts +11 -5
  35. package/dist/proxy/index.js +1 -1
  36. package/dist/{translator-Ddd65sXR.d.ts → translator-BqpmZ-vh.d.ts} +1 -1
  37. package/dist/{translator-CO8W_hmJ.d.cts → translator-Dox25ky9.d.cts} +1 -1
  38. package/dist/{video-out-BsuLqlID.d.cts → video-out-DnCKUUO2.d.cts} +13 -0
  39. package/dist/{video-out-Cawtm7SF.d.ts → video-out-REmiQMBJ.d.ts} +7 -0
  40. package/package.json +3 -3
  41. package/dist/chunk-6M5JK4YC.js +0 -1
  42. package/dist/chunk-UQV3ZXCW.js +0 -2
  43. package/dist/chunk-YOFTYCYH.js +0 -64
  44. package/dist/chunk-ZA2LMA3I.js +0 -23
@@ -1,93 +1,93 @@
1
- "use strict";var vu=Object.create;var Pn=Object.defineProperty;var bu=Object.getOwnPropertyDescriptor;var Su=Object.getOwnPropertyNames;var ku=Object.getPrototypeOf,Ru=Object.prototype.hasOwnProperty;var Eu=(t,e)=>{for(var n in e)Pn(t,n,{get:e[n],enumerable:!0})},Ls=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Su(e))!Ru.call(t,o)&&o!==n&&Pn(t,o,{get:()=>e[o],enumerable:!(r=bu(e,o))||r.enumerable});return t};var de=(t,e,n)=>(n=t!=null?vu(ku(t)):{},Ls(e||!t||!t.__esModule?Pn(n,"default",{value:t,enumerable:!0}):n,t)),xu=t=>Ls(Pn({},"__esModule",{value:!0}),t);var sm={};Eu(sm,{ANONYMOUS_KEY_ID:()=>Cr,BIND_HOST:()=>du,BUCKET_DOMAIN:()=>os,BoundedLabel:()=>Ht,ControlPlaneUnavailableError:()=>we,ConversationBackhauls:()=>Vt,ConversationCapacityError:()=>Jt,DEFAULT_PORT:()=>ws,EDGE_IDENTITY_PORT:()=>Vl,EDGE_KEY_FINGERPRINT_HEADER:()=>rs,EDGE_KEY_ID_HEADER:()=>ns,InferenceMetrics:()=>Bt,LEDGER_FUNCTION_PATH:()=>xs,LEDGER_WRITE_TIMEOUT_MS:()=>As,LedgerClient:()=>zt,LedgerDuplicateError:()=>Kt,LedgerSurfaceError:()=>ie,MAX_CACHED_KEYS:()=>ds,MAX_CONVERSATIONS:()=>Fr,MAX_CONVERSATION_HANDLES:()=>vs,MAX_MODEL_LABELS:()=>Xo,MAX_ORG_LABELS:()=>Qo,MAX_TENANTS:()=>_s,METRICS_PATH:()=>Tr,METRICS_PORT:()=>Wl,NO_MODEL_LABEL:()=>Yo,ORG_BINDING_TTL_MS:()=>us,OTHER_LABEL:()=>Ft,OrgResolver:()=>jt,ProxyAuthError:()=>Q,READINESS_TIMEOUT_MS:()=>Ts,READINESS_TTL_MS:()=>Os,SERVE_FUNCTION:()=>In,TIER_DOMAIN:()=>ss,TenantRegistry:()=>Wt,bearerFrom:()=>qt,bearerTokenOf:()=>ls,createEdgeIdentityServer:()=>Lr,createHostedProxy:()=>_u,createMetricsServer:()=>Pr,edgeBucketId:()=>is,edgeTierFingerprint:()=>as,laneOf:()=>Zo,parseLedgerRecorded:()=>Is,resolveHostedConfig:()=>cu,statusClassOf:()=>es,tenantSubject:()=>Tn});module.exports=xu(sm);var hu=require("http");var Ns="audio",Gr=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 Us(t,e,n=1e4){let r=new Gr(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Ns).attach(o);let s=await Au(t,n);return await r.startInbound(s),r}function Au(t,e){let n=t.stream(Ns);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=l=>{l!=null&&(clearTimeout(i),s?.(),r(l))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var $s="rt-video-in",Ms=256e3;function Ds(t){let e=t.stream($s),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${$s}') 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>Ms)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Ms}-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 Iu=24e3,Yt=480,Ou=111;async function Tu(){let t=await import("opusscript"),e=t.default??t;return new e(Iu,1,2048)}async function Fs(){let t=await import("werift"),e=await Tu();return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let l=new Int16Array(i.length+a.length);l.set(i,0),l.set(a,i.length);let u=0;for(;l.length-u>=Yt;){let d=l.subarray(u,u+Yt);u+=Yt;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,Yt);o=o+1&65535,s=s+Yt>>>0;let m=new t.RtpHeader({version:2,payloadType:Ou,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),h=new t.RtpPacket(m,p);n.writeRtp(h)}i=l.slice(u)}}},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 l=0;l<a.length;l++)a[l]=i.readInt16LE(l*2);r.onframe?.({samples:a})}),r}}}var Cn=require("@urun-sh/core"),Wr="rt-video-out";var Pu="h264";function Cu(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 Lu(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;Cu(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 Hs="urun.videoOut.v2-ws";function Bs(t){let e=t.stream(Wr);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Wr}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=l=>{for(let u of r)u(l)},i=!1,a=async()=>{for await(let l of e.messages()){if(!(l instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${Wr}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=Lu(l)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(u)}for(let l of o)l()};return{codec:Pu,onOutputFrame:l=>(n.add(l),i||(i=!0,a().catch(u=>s(u instanceof Error?u:new Error(String(u))))),()=>n.delete(l)),onLaneError:l=>(r.add(l),()=>r.delete(l)),onEnd:l=>(o.add(l),()=>o.delete(l))}}var Nn="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",$u=1007,qs=1008,Ne=1011,Un=1008,O=class extends Error{constructor(n,r=$u){super(n);this.closeCode=r}closeCode},re=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Ln=["setup","clientContent","realtimeInput","toolResponse"];function Gs(t){let e;try{e=JSON.parse(t)}catch{throw new O("client message is not valid JSON")}let n=re(e);if(!n)throw new O("client message must be a JSON object");let r=Ln.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Ln.includes(a));if(o.length>0)throw new O(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Ln.join(", ")}`);if(r.length!==1)throw new O(`client message must contain exactly one of ${Ln.join(", ")} (got ${r.length})`);let s=r[0],i=re(n[s]);if(!i)throw new O(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Ws(t,e){if(typeof t=="string")return t;let n=re(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new O(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=re(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new O(`${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 O(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new O(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
2
- `)}var Mu={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Xe="urun.videoOut";function Js(t){return{framing:Hs,codec:t}}function Vs(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Xe]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Nu={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Uu=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Xe],js=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Du(t){let e=re(t);if(!e)throw new O("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new O(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=re(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new O("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new O(`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 O("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(!js.includes(e.activityHandling))throw new O(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${js.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Fu=["temperature","maxOutputTokens","responseModalities"];function Ks(t){for(let[c,p]of Object.entries(Nu))if(t[c]!==void 0)throw new O(p);for(let c of Object.keys(t))if(!Uu.includes(c))throw new O(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new O('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=re(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new O("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Fu.includes(c))throw new O(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new O("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new O("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of c){let m=String(p).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="TEXT")throw new O(`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:Ws(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new O("setup.tools must be an array");a=[];for(let c of t.tools){let p=re(c);if(!p)throw new O("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new O(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new O("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let h=re(m);if(!h||typeof h.name!="string")throw new O("functionDeclarations entries require a string name");a.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=re(t.sessionResumption);if(!c)throw new O("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new O(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new O("sessionResumption.handle must be a non-empty string when present");l={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?Mu:Du(t.realtimeInputConfig),d=!1;if(t[Xe]!==void 0){if(!re(t[Xe]))throw new O(`setup["${Xe}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:u,sessionResumption:l,videoOut:d}}function zs(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Ys(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Xs(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new O(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new O("clientContent.turns must be an array");let n=[];for(let r of e){let o=re(r);if(!o)throw new O("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 O(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Ws(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var $n=16e3,Qs=24e3,Hu=`audio/pcm;rate=${Qs}`,Zs=Buffer.alloc(960).toString("base64");function Bu(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let l=a*s,u=Math.floor(l);if(u>=i){o[a]=t[i];continue}let d=l-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*d)}return o}function ju(t){let e=re(t);if(!e)throw new O("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new O(`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 O("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 O("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function qu(t){let e=re(t);if(!e)throw new O("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new O(`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])!==$n)throw new O(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${$n} Hz (audio/pcm;rate=${$n})`);if(typeof e.data!="string"||e.data.length===0)throw new O("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 O(`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=Bu(o,$n,Qs);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function ei(t){if(t.mediaChunks!==void 0)throw new O('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 O("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=re(t[o]);if(!s||Object.keys(s).length!==0)throw new O(`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 O(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new O(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:qu(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:ju(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new O("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new O("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function ti(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new O(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new O("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=re(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new O("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 ni(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function ri(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Hu,data:t}}]}}}}function oi(t){let e=re(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let u of n){let d=re(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=re(c);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let u of n){let d=re(u);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new O(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,Ne);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new O(`upstream function_call arguments are not valid JSON: ${c}`,Ne)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=re(e.usage),l={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(l.usageMetadata=u)}return i.push(l),{messages:i,assistantItems:o}}var Ti=require("crypto"),Pi=require("ws");var xi=require("crypto");var Y=class extends Error{},Gu=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Wu(t){if(typeof t!="string")return!1;let e=Gu.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Ju(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new Y(`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 Y(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new Y(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new Y(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new Y(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new Y(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,p)=>{if(u[c]!==void 0&&u[c]!==null&&!p)throw new Y(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",Wu(u.ready_since));for(let c of["model_id","variant"]){let p=u[c];if(p.includes(":"))throw new Y(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(p)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new Y(`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 Y(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new Y(`catalog "shared" block compliance carries "${l}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function mt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function si(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new Y(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function Jr(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new Y(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function ii(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 Y(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Ju(await r.json())}function he(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var _e=class extends Error{name="ModelPriceError"},Vr="per_million_input_tokens",Kr="per_million_output_tokens",li="model_id,variant,unit,price_usd,effective_at,expires_at",ai={per_request:!0,per_minute:!0,per_output_unit:!0},Vu=5e3;function Ku(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new _e(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function ui(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new _e(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function zu(t,e,n){return t===null?null:ui(t,e,n)}function Yu(t,e){if(t===Vr)return"input";if(t===Kr)return"output";if(typeof t=="string"&&Object.hasOwn(ai,t))return null;throw new _e(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Vr} | ${Kr}) nor a known GPU-time unit (${Object.keys(ai).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 Xu(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 zr(t,e){return`${t}\0${e}`}function Qu(t){if(!Array.isArray(t))throw new _e(`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 _e(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of li.split(","))if(!Object.hasOwn(s,u))throw new _e(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=Yu(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new _e(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new _e(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Ku(s.price_usd,o),effective_at:ui(s.effective_at,o,"effective_at"),expires_at:zu(s.expires_at,o,"expires_at")})}return e}function di(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(p,m,h)=>{let v=p&&p.length>0?p:d?.[m];if(!v||v.length===0)return null;let S=Xu(v,m);return"reason"in S?S:S.rate.usd===0?m==="output"&&h!==null&&n?.has(zr(l,h))?S.rate:{reason:`the ${m} 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`}:S.rate};for(let[p,m]of o.get(l)){let h=u.get(p),v=c(h?.input,"input",m),S=c(h?.output,"output",m);if(v!==null&&"reason"in v){i.push({model_id:l,variant:m,reason:v.reason});continue}if(S!==null&&"reason"in S){i.push({model_id:l,variant:m,reason:S.reason});continue}v===null||S===null||s.push({model_id:l,variant:m,pricing:{input:v.usd,output:S.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function Xt(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 Qt={prices:[],refusals:[]};async function ci(t){let e=t.fetchImpl??fetch,n=`${Vr},${Kr}`,r=await e(`${t.catalogUrl}/model_prices?select=${li}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Vu)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Qu(await r.json())}var Ze="/partners/openrouter/models",Zu={chat:!0,code:!0,agent:!0,vl:!0},pi={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function ed(t){let e=t.toLowerCase();return Object.hasOwn(pi,e)?pi[e]:null}var fi={"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 td(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(fi,o)?fi[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 mi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},gi={2:"Llama2",3:"Llama3"};function nd(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(mi,s))return mi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(gi,i))return gi[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var rd=["context_length","max_model_len"];function od(t){let e=rd.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 Dn(t){let e=t.map(od),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function sd(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function Yr(t){if(t.length===0)return null;let e=t.map(sd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Xr(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function id(t,e){let n=e.filter(s=>he(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Zt(n);let r=e.filter(s=>he(s.model_id)===t);if(r.length>0)return Zt(r);let o=Xr(t,e);return o.length>0?Zt(o):null}function Zt(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:ad(t),matches:t}:null}function ad(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var He=class extends Error{name="ModelCreatedError"};function gt(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new He(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new He(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new He(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new He(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function Qe(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function Fn(t,e,n){let r=id(t,e);if(!r)return Qe({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Dn(s),a=gt(s),l=Xt(o.model_id,o.variant,n),u=wi(o,s),d=Yr(s);return Qe({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var ld=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function wi(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:[...ld],defect:o}:{published:[],defect:o}}function Qr(t){let e=t.length>0?Zt(t):null;return e===null?{published:[],defect:null}:wi(e.row,e.matches)}function hi(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 yi(t){return{input:[{type:"prompt",unit:"token",cost_usd:hi(t.input)}],output:[{type:"completion",unit:"token",cost_usd:hi(t.output)}]}}function ud(t,e,n,r){if(e.length===0)return null;let o=Zt(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Zu[s.task]!==!0)return null;let a=Dn(i),l=Xt(s.model_id,s.variant,n),u=nd(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:gt(i),quantization:ed(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:yi(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:yi(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function _i(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?mt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:td(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=ud(u,e.filter(p=>p.model_id===u.model_id&&p.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}var vi={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},ht=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function bi(t){let e=t.t;if(typeof e!="string"||!(e in vi))throw new ht(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(vi).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function dd(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new ht(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new ht(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return bi(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new ht(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return bi(t)}function Si(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function cd(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function ki(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Si(e);let s=o.next();if(e!==void 0&&await cd(s,e)==="aborted")throw s.catch(()=>{}),Si(e);let i=await s;if(i.done)return;yield dd(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var B=class extends Error{},F=class extends Error{},eo="urs1.";function tn(t,e){return eo+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function nn(t){if(!t.startsWith(eo))return null;try{let e=JSON.parse(Buffer.from(t.slice(eo.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 Ai(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 Ri(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=md(t);return e===null?[]:[e]}function pd(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
1
+ "use strict";var Au=Object.create;var Ln=Object.defineProperty;var Iu=Object.getOwnPropertyDescriptor;var Ou=Object.getOwnPropertyNames;var Tu=Object.getPrototypeOf,Pu=Object.prototype.hasOwnProperty;var Cu=(t,e)=>{for(var n in e)Ln(t,n,{get:e[n],enumerable:!0})},Us=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ou(e))!Pu.call(t,o)&&o!==n&&Ln(t,o,{get:()=>e[o],enumerable:!(r=Iu(e,o))||r.enumerable});return t};var ce=(t,e,n)=>(n=t!=null?Au(Tu(t)):{},Us(e||!t||!t.__esModule?Ln(n,"default",{value:t,enumerable:!0}):n,t)),Lu=t=>Us(Ln({},"__esModule",{value:!0}),t);var ym={};Cu(ym,{ANONYMOUS_KEY_ID:()=>$r,BIND_HOST:()=>yu,BUCKET_DOMAIN:()=>as,BoundedLabel:()=>jt,ControlPlaneUnavailableError:()=>_e,ConversationBackhauls:()=>Yt,ConversationCapacityError:()=>zt,DEFAULT_PORT:()=>Ss,EDGE_IDENTITY_PORT:()=>Zl,EDGE_KEY_FINGERPRINT_HEADER:()=>is,EDGE_KEY_ID_HEADER:()=>ss,InferenceMetrics:()=>qt,LEDGER_FUNCTION_PATH:()=>Ts,LEDGER_WRITE_TIMEOUT_MS:()=>Ps,LedgerClient:()=>Qt,LedgerDuplicateError:()=>Xt,LedgerSurfaceError:()=>se,MAX_CACHED_KEYS:()=>fs,MAX_CONVERSATIONS:()=>Br,MAX_CONVERSATION_HANDLES:()=>Rs,MAX_MODEL_LABELS:()=>es,MAX_ORG_LABELS:()=>ts,MAX_TENANTS:()=>ks,METRICS_PATH:()=>Cr,METRICS_PORT:()=>Xl,NO_MODEL_LABEL:()=>Zo,ORG_BINDING_TTL_MS:()=>ps,OTHER_LABEL:()=>Bt,OrgResolver:()=>Gt,ProxyAuthError:()=>Z,READINESS_TIMEOUT_MS:()=>$s,READINESS_TTL_MS:()=>Ls,SERVE_FUNCTION:()=>Pn,TIER_DOMAIN:()=>ls,TenantRegistry:()=>Kt,bearerFrom:()=>Wt,bearerTokenOf:()=>cs,createEdgeIdentityServer:()=>Mr,createHostedProxy:()=>xu,createMetricsServer:()=>Lr,edgeBucketId:()=>us,edgeTierFingerprint:()=>ds,laneOf:()=>ns,parseLedgerRecorded:()=>Cs,resolveHostedConfig:()=>wu,statusClassOf:()=>rs,tenantSubject:()=>Jt});module.exports=Lu(ym);var ku=require("http");var Fs="audio",Vr=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e){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),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(n)).catch(s=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(s instanceof Error?s.message:String(s)))}))}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 Hs(t,e,n=1e4){let r=new Vr(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(Fs);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(a=>s.emit(a));let i=await $u(t,n);return await r.startInbound(i),r}function $u(t,e){let n=t.stream(Fs);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=l=>{l!=null&&(clearTimeout(i),s?.(),r(l))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var Ds="rt-video-in",en=256e3;function Jr(t){let e=t.stream(Ds),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${Ds}') 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>en)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${en}-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 Mu=24e3,Zt=480,Nu=111;async function Uu(){let t=await import("opusscript"),e=t.default??t;return new e(Mu,1,2048)}async function Bs(){let t=await import("werift"),e=await Uu();return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let l=new Int16Array(i.length+a.length);l.set(i,0),l.set(a,i.length);let u=0;for(;l.length-u>=Zt;){let d=l.subarray(u,u+Zt);u+=Zt;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,Zt);o=o+1&65535,s=s+Zt>>>0;let h=new t.RtpHeader({version:2,payloadType:Nu,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),m=new t.RtpPacket(h,p);n.writeRtp(m)}i=l.slice(u)}}},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 l=0;l<a.length;l++)a[l]=i.readInt16LE(l*2);r.onframe?.({samples:a})}),r}}}var $n=require("@urun-sh/core"),Kr="rt-video-out";var Du="h264";function Fu(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 Hu(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;Fu(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 js="urun.videoOut.v2-ws";function qs(t){let e=t.stream(Kr);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Kr}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=l=>{for(let u of r)u(l)},i=!1,a=async()=>{for await(let l of e.messages()){if(!(l instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${Kr}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=Hu(l)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(u)}for(let l of o)l()};return{codec:Du,onOutputFrame:l=>(n.add(l),i||(i=!0,a().catch(u=>s(u instanceof Error?u:new Error(String(u))))),()=>n.delete(l)),onLaneError:l=>(r.add(l),()=>r.delete(l)),onEnd:l=>(o.add(l),()=>o.delete(l))}}var Dn="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Bu=1007,Ws=1008,Ne=1011,Fn=1008,T=class extends Error{constructor(n,r=Bu){super(n);this.closeCode=r}closeCode},oe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Mn=["setup","clientContent","realtimeInput","toolResponse"];function Vs(t){let e;try{e=JSON.parse(t)}catch{throw new T("client message is not valid JSON")}let n=oe(e);if(!n)throw new T("client message must be a JSON object");let r=Mn.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Mn.includes(a));if(o.length>0)throw new T(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Mn.join(", ")}`);if(r.length!==1)throw new T(`client message must contain exactly one of ${Mn.join(", ")} (got ${r.length})`);let s=r[0],i=oe(n[s]);if(!i)throw new T(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Js(t,e){if(typeof t=="string")return t;let n=oe(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new T(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=oe(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new T(`${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 T(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new T(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
2
+ `)}var ju={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Xe="urun.videoOut";function Ks(t){return{framing:js,codec:t}}function zs(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Xe]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var qu={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Gu=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Xe],Gs=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Wu(t){let e=oe(t);if(!e)throw new T("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new T(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=oe(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new T("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new T(`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 T("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(!Gs.includes(e.activityHandling))throw new T(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Gs.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Vu=["temperature","maxOutputTokens","responseModalities"];function Ys(t){for(let[c,p]of Object.entries(qu))if(t[c]!==void 0)throw new T(p);for(let c of Object.keys(t))if(!Gu.includes(c))throw new T(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new T('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=oe(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new T("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Vu.includes(c))throw new T(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new T("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new T("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of c){let h=String(p).toUpperCase();if(h==="AUDIO"){o=!0;continue}if(h!=="TEXT")throw new T(`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:Js(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new T("setup.tools must be an array");a=[];for(let c of t.tools){let p=oe(c);if(!p)throw new T("setup.tools entries must be objects");for(let h of Object.keys(p))if(h!=="functionDeclarations")throw new T(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new T("tool.functionDeclarations must be an array");for(let h of p.functionDeclarations){let m=oe(h);if(!m||typeof m.name!="string")throw new T("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=oe(t.sessionResumption);if(!c)throw new T("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new T(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new T("sessionResumption.handle must be a non-empty string when present");l={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?ju:Wu(t.realtimeInputConfig),d=!1;if(t[Xe]!==void 0){if(!oe(t[Xe]))throw new T(`setup["${Xe}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:u,sessionResumption:l,videoOut:d}}function Xs(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Qs(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Zs(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new T(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new T("clientContent.turns must be an array");let n=[];for(let r of e){let o=oe(r);if(!o)throw new T("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 T(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Js(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Nn=16e3,ei=24e3,Ju=`audio/pcm;rate=${ei}`,ti=Buffer.alloc(960).toString("base64");function Ku(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let l=a*s,u=Math.floor(l);if(u>=i){o[a]=t[i];continue}let d=l-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*d)}return o}function zu(t){let e=oe(t);if(!e)throw new T("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new T(`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 T("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 T("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Yu(t){let e=oe(t);if(!e)throw new T("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new T(`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])!==Nn)throw new T(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Nn} Hz (audio/pcm;rate=${Nn})`);if(typeof e.data!="string"||e.data.length===0)throw new T("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 T(`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=Ku(o,Nn,ei);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function ni(t){if(t.mediaChunks!==void 0)throw new T('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 T("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=oe(t[o]);if(!s||Object.keys(s).length!==0)throw new T(`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 T(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new T(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Yu(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:zu(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new T("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new T("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function ri(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new T(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new T("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=oe(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new T("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 oi(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function si(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Ju,data:t}}]}}}}function ii(t){let e=oe(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let u of n){let d=oe(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=oe(c);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let u of n){let d=oe(u);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new T(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,Ne);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new T(`upstream function_call arguments are not valid JSON: ${c}`,Ne)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=oe(e.usage),l={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(l.usageMetadata=u)}return i.push(l),{messages:i,assistantItems:o}}var Ci=require("crypto"),Li=require("ws");var Ii=require("crypto");var Y=class extends Error{},Xu=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Qu(t){if(typeof t!="string")return!1;let e=Xu.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Zu(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new Y(`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 Y(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new Y(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new Y(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new Y(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new Y(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,p)=>{if(u[c]!==void 0&&u[c]!==null&&!p)throw new Y(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",Qu(u.ready_since));for(let c of["model_id","variant"]){let p=u[c];if(p.includes(":"))throw new Y(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(p)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new Y(`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 Y(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new Y(`catalog "shared" block compliance carries "${l}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function gt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function ai(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new Y(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function zr(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new Y(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function li(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 Y(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Zu(await r.json())}function ye(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var ve=class extends Error{name="ModelPriceError"},Yr="per_million_input_tokens",Xr="per_million_output_tokens",di="model_id,variant,unit,price_usd,effective_at,expires_at",ui={per_request:!0,per_minute:!0,per_output_unit:!0},ed=5e3;function td(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ve(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function ci(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ve(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function nd(t,e,n){return t===null?null:ci(t,e,n)}function rd(t,e){if(t===Yr)return"input";if(t===Xr)return"output";if(typeof t=="string"&&Object.hasOwn(ui,t))return null;throw new ve(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Yr} | ${Xr}) nor a known GPU-time unit (${Object.keys(ui).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 od(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 Qr(t,e){return`${t}\0${e}`}function sd(t){if(!Array.isArray(t))throw new ve(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new ve(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of di.split(","))if(!Object.hasOwn(s,u))throw new ve(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=rd(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new ve(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new ve(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:td(s.price_usd,o),effective_at:ci(s.effective_at,o,"effective_at"),expires_at:nd(s.expires_at,o,"expires_at")})}return e}function pi(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(p,h,m)=>{let _=p&&p.length>0?p:d?.[h];if(!_||_.length===0)return null;let b=od(_,h);return"reason"in b?b:b.rate.usd===0?h==="output"&&m!==null&&n?.has(Qr(l,m))?b.rate:{reason:`the ${h} 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[p,h]of o.get(l)){let m=u.get(p),_=c(m?.input,"input",h),b=c(m?.output,"output",h);if(_!==null&&"reason"in _){i.push({model_id:l,variant:h,reason:_.reason});continue}if(b!==null&&"reason"in b){i.push({model_id:l,variant:h,reason:b.reason});continue}_===null||b===null||s.push({model_id:l,variant:h,pricing:{input:_.usd,output:b.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function tn(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 nn={prices:[],refusals:[]};async function fi(t){let e=t.fetchImpl??fetch,n=`${Yr},${Xr}`,r=await e(`${t.catalogUrl}/model_prices?select=${di}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(ed)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return sd(await r.json())}var Ze="/partners/openrouter/models",id={chat:!0,code:!0,agent:!0,vl:!0},mi={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function ad(t){let e=t.toLowerCase();return Object.hasOwn(mi,e)?mi[e]:null}var gi={"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 ld(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(gi,o)?gi[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 hi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},yi={2:"Llama2",3:"Llama3"};function ud(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(hi,s))return hi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(yi,i))return yi[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var dd=["context_length","max_model_len"];function cd(t){let e=dd.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 Hn(t){let e=t.map(cd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function pd(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function Zr(t){if(t.length===0)return null;let e=t.map(pd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function eo(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function fd(t,e){let n=e.filter(s=>ye(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return rn(n);let r=e.filter(s=>ye(s.model_id)===t);if(r.length>0)return rn(r);let o=eo(t,e);return o.length>0?rn(o):null}function rn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:md(t),matches:t}:null}function md(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var He=class extends Error{name="ModelCreatedError"};function ht(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new He(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new He(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new He(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new He(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function Qe(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function Bn(t,e,n){let r=fd(t,e);if(!r)return Qe({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Hn(s),a=ht(s),l=tn(o.model_id,o.variant,n),u=vi(o,s),d=Zr(s);return Qe({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var gd=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function vi(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...gd],defect:o}:{published:[],defect:o}}function to(t){let e=t.length>0?rn(t):null;return e===null?{published:[],defect:null}:vi(e.row,e.matches)}function wi(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function _i(t){return{input:[{type:"prompt",unit:"token",cost_usd:wi(t.input)}],output:[{type:"completion",unit:"token",cost_usd:wi(t.output)}]}}function hd(t,e,n,r){if(e.length===0)return null;let o=rn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||id[s.task]!==!0)return null;let a=Hn(i),l=tn(s.model_id,s.variant,n),u=ud(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:ht(i),quantization:ad(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:_i(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:_i(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function bi(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?gt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:ld(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=hd(u,e.filter(p=>p.model_id===u.model_id&&p.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}var Si={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},yt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function ki(t){let e=t.t;if(typeof e!="string"||!(e in Si))throw new yt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Si).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function yd(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new yt(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new yt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return ki(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new yt(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return ki(t)}function Ri(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function wd(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function Ei(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Ri(e);let s=o.next();if(e!==void 0&&await wd(s,e)==="aborted")throw s.catch(()=>{}),Ri(e);let i=await s;if(i.done)return;yield yd(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var j=class extends Error{},F=class extends Error{},ro="urs1.";function sn(t,e){return ro+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function an(t){if(!t.startsWith(ro))return null;try{let e=JSON.parse(Buffer.from(t.slice(ro.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 Oi(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 xi(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=bd(t);return e===null?[]:[e]}function _d(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
3
3
  `),null;let e={},n=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],r=!1;for(let[o,s]of n){let i=t[o];if(i==null)continue;let a=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(a)||a<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
4
- `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function no(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||he(`${r.model_id}-${r.variant}`)===e.appSlug||he(r.model_id)===e.appSlug)),n?pd(n.engine_args?.pool):null}function Zr(t,e,n,r,o){if(!o)throw new Y(`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 Y(`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 Y(`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 Ei(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 Y(`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 Ii="shared:",rn="speech:",yt="realtime:";function je(t){return t.sharedApp?Ii+t.appSlug:t.appSlug}function Bn(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 to(t,e){let n=e.filter(s=>he(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>he(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function fd(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function md(t){let e=t.map(fd),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var gd={stt:"stt",tts:"tts"};function Be(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:gd[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Oi(t,e){let n=to(t,e);return n.length>0?n:Xr(t,e)}function en(t,e){return Oi(t.appSlug,e)}function hd(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new Y(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var Hn=6e4,jn=class{constructor(e){this.opts=e}opts;pool=new Map;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??Hn):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??Hn):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??Hn):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Hn;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 _e)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
5
- `),Qt}let r=di(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}
6
- `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(zr(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(Ii)||o.startsWith(rn)||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 B(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 sharedLane(e){if(!this.opts.shared)return null;let n=await this.sharedBlock();if(!n)return null;let r=Jr(n,e);if(r)return r;let o=e.lastIndexOf(":"),s=o>0?e.slice(0,o):e,i=o>0?e.slice(o+1):void 0,a=he(s),l=n.endpoints.filter(c=>he(c.model_id)===a&&(i===void 0||c.variant===i)),u=new Set(l.map(c=>c.model_id)),d=[...u][0];return d===void 0||u.size!==1?null:Jr(n,d,i)}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=he(n);if(o===r)return{appSlug:r};let s=await this.sharedLane(n);if(s)return{appSlug:s.endpoint.app_slug,fnName:s.endpoint.function,sharedApp:!0,modelId:s.endpoint.model_id,variant:s.endpoint.variant,sharedOrgId:s.shared_org_id,gpuSpec:s.endpoint.gpu_spec??void 0,appId:s.endpoint.app_id??void 0};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let i=await this.deployedApps(),a=this.servable(i);if(a.includes(o))return{appSlug:o};let l=a.filter(d=>d.startsWith(`${o}-`));if(l.length===1)return{appSlug:l[0]};if(l.length>1)throw new B(`model "${n}" is ambiguous across deployed apps ${l.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new B(`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.listCatalog){let a=(await this.opts.listCatalog()).find(l=>n===l.model_id||n===`${l.model_id}:${l.variant}`||o===he(l.model_id)||o===he(`${l.model_id}-${l.variant}`));if(a)throw new B(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${a.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=Bn(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return no(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return je(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,je(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,rn+je(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,yt+(0,xi.randomUUID)())}async evictHandle(e){let n=nn(e);if(!n)return;let r=this.pool.get(n.app);if(!r)return;let o=await r.then(s=>s,()=>null);o!==null&&await this.evict(n.app,o)}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:Bn(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:tn(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:tn(n,this.keyOf(r))}}async sessionForHandle(e){let n=nn(e);if(!n)throw new F(`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 F(`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 F(`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(u=>({ok:!0,rows:u}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:Qt;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)
7
- `);let l=(n?mt(n):[]).map(u=>{let d=s.filter(w=>w.model_id===u.model_id&&w.variant===u.variant),c=Dn(d),p=gt(d),m=Yr(d),h=Xt(u.model_id,u.variant,i),v=Qr(d);return Qe({id:`${u.model_id}:${u.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...h!==null?{pricing:h}:{},...v.published.length>0?{voices:[...v.published]}:{},...m!==null?{capabilities:{reasoning:m}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?l:[...e.map(u=>Fn(u,s,i)),...l]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return _i(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=Zr(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Ei(`${r.modelId}:${r.variant}`,s).includes(n)}return Ri(to(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(en(n,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(en(n,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(en(n,r))==="stt"}async transcriptStreamFor(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):en(n,r);return hd(o)}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):en(n,r);return Qr(o)}async imageModelList(){let e=await this.catalogRows(),n=Qt,r=[];for(let s of await this.availableIds()){let i=Ri(to(s,e));i.length!==0&&r.push(Qe({...Fn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of mt(o)){let i=Zr(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Ei(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let l=Qe({id:`${s.model_id}:${s.variant}`,object:"model",created:gt(i),owned_by:"urun",image_modes:a});r.push(l)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=Qt,r=[];for(let s of await this.availableIds())Be(Oi(s,e))==="stt"&&r.push(Fn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of mt(o)){let i=Zr(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Be(i)!=="stt")continue;let a=Qe({id:`${s.model_id}:${s.variant}`,object:"model",created:gt(i),owned_by:"urun"});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 yd=256,ro=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>yd;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},wd="local",on=t=>t.slice(0,120),oo=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 B){this.ws.close(qs,on(e.message));return}if(e instanceof F){this.ws.close(Un,on(e.message));return}if(e instanceof O){this.ws.close(e.closeCode,on(e.message));return}this.ws.close(Ne,on(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Gs(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 O(`"${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}=Xs(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=ei(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:Zs);return}this.transcript.push(...ti(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new O("setup may only be sent once, as the first client message");let n=Ks(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new O("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",Un);if(s.model!==n.model)throw new O(`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 O("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 O(`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`,Un);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(u=>this.send(Vs(u))),l=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),l()},o[Xe]=Js(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 O("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new O("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ne);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(ri(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 O("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new O("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ne);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 O(`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 O("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 O("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,Ti.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(zs(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(Ys(e.timeLeftMs)),this.ws.close(Ne,on(`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 l of r){if(n.interrupted)break;let u=l;if(u.type==="error")throw new O(`upstream error: ${JSON.stringify(u)}`,Ne);if(u.type==="response.completed"){o=u.response,s=!0;continue}let d=ni(u);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new O("upstream produced no response.completed event",Ne);let{messages:i,assistantItems:a}=oi(o);this.transcript.push(...a);for(let l of i)this.send(l);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},tt=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function _d(t,e,n){let r=new Set;(l=>{if(typeof l=="string")l!==""&&r.add(l);else if(Array.isArray(l))for(let u of l)u!==""&&r.add(u)})(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 tt(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 tt(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 l of r)a=l;if(a===void 0&&n)throw new tt(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function so(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 Pi.WebSocketServer({noServer:!0}),o=new ro;t.on("upgrade",(i,a,l)=>{let u=new URL(i.url??"/","http://localhost");u.pathname===Nn&&(a.on("error",()=>{}),(async()=>{let d=_d(i,u,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new tt(401,"invalid local proxy api key");c={clients:e.clients,scope:wd}}r.handleUpgrade(i,a,l,p=>{new oo(p,c,o)})})().catch(d=>{let c=502;(d instanceof tt||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
4
+ `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function so(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||ye(`${r.model_id}-${r.variant}`)===e.appSlug||ye(r.model_id)===e.appSlug)),n?_d(n.engine_args?.pool):null}function no(t,e,n,r,o){if(!o)throw new Y(`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 Y(`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 Y(`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 Ai(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 Y(`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 Ti="shared:",wt="speech:",_t="realtime:";function je(t){return t.sharedApp?Ti+t.appSlug:t.appSlug}function qn(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 oo(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 vd(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function bd(t){let e=t.map(vd),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Sd={stt:"stt",tts:"tts"};function Be(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:Sd[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Pi(t,e){let n=oo(t,e);return n.length>0?n:eo(t,e)}function on(t,e){return Pi(t.appSlug,e)}function kd(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new Y(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var jn=6e4,Gn=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??jn):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??jn):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??jn):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??jn;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof ve)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
5
+ `),nn}let r=pi(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}
6
+ `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(Qr(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(Ti)||o.startsWith(wt)||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 j(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 sharedLane(e){if(!this.opts.shared)return null;let n=await this.sharedBlock();if(!n)return null;let r=zr(n,e);if(r)return r;let o=e.lastIndexOf(":"),s=o>0?e.slice(0,o):e,i=o>0?e.slice(o+1):void 0,a=ye(s),l=n.endpoints.filter(c=>ye(c.model_id)===a&&(i===void 0||c.variant===i)),u=new Set(l.map(c=>c.model_id)),d=[...u][0];return d===void 0||u.size!==1?null:zr(n,d,i)}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};let s=await this.sharedLane(n);if(s)return{appSlug:s.endpoint.app_slug,fnName:s.endpoint.function,sharedApp:!0,modelId:s.endpoint.model_id,variant:s.endpoint.variant,sharedOrgId:s.shared_org_id,gpuSpec:s.endpoint.gpu_spec??void 0,appId:s.endpoint.app_id??void 0};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let i=await this.deployedApps(),a=this.servable(i);if(a.includes(o))return{appSlug:o};let l=a.filter(d=>d.startsWith(`${o}-`));if(l.length===1)return{appSlug:l[0]};if(l.length>1)throw new j(`model "${n}" is ambiguous across deployed apps ${l.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new j(`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.listCatalog){let a=(await this.opts.listCatalog()).find(l=>n===l.model_id||n===`${l.model_id}:${l.variant}`||o===ye(l.model_id)||o===ye(`${l.model_id}-${l.variant}`));if(a)throw new j(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${a.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=qn(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return so(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return je(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,je(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,wt+je(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,_t+(0,Ii.randomUUID)())}async evictHandle(e){let n=an(e);if(!n)return;let r=this.pool.get(n.app);if(!r)return;let o=await r.then(s=>s,()=>null);o!==null&&await this.evict(n.app,o)}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.then(o=>this.snapshotMintId(o),()=>{}),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:qn(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:sn(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:sn(n,this.keyOf(r))}}async sessionForHandle(e){let n=an(e);if(!n)throw new F(`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 F(`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&&this.mintedIds.get(i)!==o)throw new F(`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(u=>({ok:!0,rows:u}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:nn;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)
7
+ `);let l=(n?gt(n):[]).map(u=>{let d=s.filter(v=>v.model_id===u.model_id&&v.variant===u.variant),c=Hn(d),p=ht(d),h=Zr(d),m=tn(u.model_id,u.variant,i),_=to(d);return Qe({id:`${u.model_id}:${u.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...m!==null?{pricing:m}:{},..._.published.length>0?{voices:[..._.published]}:{},...h!==null?{capabilities:{reasoning:h}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?l:[...e.map(u=>Bn(u,s,i)),...l]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return bi(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=no(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Ai(`${r.modelId}:${r.variant}`,s).includes(n)}return xi(oo(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(on(n,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(on(n,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(on(n,r))==="stt"}async transcriptStreamFor(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):on(n,r);return kd(o)}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):on(n,r);return to(o)}async imageModelList(){let e=await this.catalogRows(),n=nn,r=[];for(let s of await this.availableIds()){let i=xi(oo(s,e));i.length!==0&&r.push(Qe({...Bn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of gt(o)){let i=no(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Ai(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let l=Qe({id:`${s.model_id}:${s.variant}`,object:"model",created:ht(i),owned_by:"urun",image_modes:a});r.push(l)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=nn,r=[];for(let s of await this.availableIds())Be(Pi(s,e))==="stt"&&r.push(Bn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of gt(o)){let i=no(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Be(i)!=="stt")continue;let a=Qe({id:`${s.model_id}:${s.variant}`,object:"model",created:ht(i),owned_by:"urun"});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 Rd=256,io=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Rd;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Ed="local",ln=t=>t.slice(0,120),ao=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 j){this.ws.close(Ws,ln(e.message));return}if(e instanceof F){this.ws.close(Fn,ln(e.message));return}if(e instanceof T){this.ws.close(e.closeCode,ln(e.message));return}this.ws.close(Ne,ln(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Vs(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 T(`"${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}=Zs(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=ni(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:ti);return}this.transcript.push(...ri(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new T("setup may only be sent once, as the first client message");let n=Ys(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new T("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",Fn);if(s.model!==n.model)throw new T(`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 T("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 T(`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`,Fn);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(u=>this.send(zs(u))),l=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),l()},o[Xe]=Ks(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 T("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new T("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ne);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(si(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 T("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new T("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ne);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 T(`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 T("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 T("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,Ci.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Xs(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(Qs(e.timeLeftMs)),this.ws.close(Ne,ln(`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 l of r){if(n.interrupted)break;let u=l;if(u.type==="error")throw new T(`upstream error: ${JSON.stringify(u)}`,Ne);if(u.type==="response.completed"){o=u.response,s=!0;continue}let d=oi(u);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new T("upstream produced no response.completed event",Ne);let{messages:i,assistantItems:a}=ii(o);this.transcript.push(...a);for(let l of i)this.send(l);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},tt=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function xd(t,e,n){let r=new Set;(l=>{if(typeof l=="string")l!==""&&r.add(l);else if(Array.isArray(l))for(let u of l)u!==""&&r.add(u)})(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 tt(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 tt(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 l of r)a=l;if(a===void 0&&n)throw new tt(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function lo(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 Li.WebSocketServer({noServer:!0}),o=new io;t.on("upgrade",(i,a,l)=>{let u=new URL(i.url??"/","http://localhost");u.pathname===Dn&&(a.on("error",()=>{}),(async()=>{let d=xd(i,u,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new tt(401,"invalid local proxy api key");c={clients:e.clients,scope:Ed}}r.handleUpgrade(i,a,l,p=>{new ao(p,c,o)})})().catch(d=>{let c=502;(d instanceof tt||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",h=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
8
8
  Connection: close\r
9
9
  \r
10
- ${m}\r
11
- `),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(l=>l===void 0?i():a(l)))})(),s)}var We=require("ws");var Ci=require("crypto"),Li="Inference-Id";function sn(){return(0,Ci.randomUUID)()}function io(t){return t==="/v1"||t.startsWith("/v1/")}function $i(t,e){if(!io(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 an(t){return`resp_${t}`}function Mi(t){return`chatcmpl-${t}`}function Ni(t){return`msg_${t}`}function ve(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Ui(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function Di(t){return`${JSON.stringify(t)}
12
- `}var vd=256,bd=128;function fe(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,bd)}var nt=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>=vd?"(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 u of e)u.type==="response.output_text.delta"&&typeof u.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+=u.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield u;let l=(performance.now()-(i??s))/1e3;a>0&&l>0&&(o.tokRates.push(a/l),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}}}},Sd=256;function kd(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 rt=class extends Error{},wt=class{conversations=new Map;thread(e,n){let r=kd(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new rt(`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<=Sd)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Fi=new WeakMap;function ln(t){let e=Fi.get(t);return e||(e=new wt,Fi.set(t,e)),e}function _t(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Le(t){return t.find(e=>e.type==="response.completed")?.response??null}function vt(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 qe=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}))}},Rd=["<tool_call>","<function="];function Ed(t){return Rd.find(e=>t.includes(e))}function ot(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 st(t,e,n){if(!(!t||e>0))return Ed(n)}function bt(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 Ue(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function xd(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 ao(t,e){let n=xd(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var be=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function St(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof rt?new be(n.message,"previous_response_not_found",400,"previous_response_id"):new be(String(n instanceof Error?n.message:n),"invalid_input")}}function Hi(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function lo(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new be("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}:{},...Hi(e)!==void 0?{response_format:Hi(e)}:{}},o)}async function un(t){let{body:e,clients:n,store:r,stats:o}=t,s=St(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,l=e.store!==!1,u=fe(e);o.model(u);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await lo(n,e,s,!0,c?ve(c):void 0);return{responseId:i,events:Td({events:p,conversation:s,responseId:i,modelKey:u,requestHadTools:d,remember:a,persist:l,store:r,stats:o,turn:t.turn})}}function Ad(t,e){let n=[...t].sort((l,u)=>l.output_index-u.output_index).map(({item:l})=>l),r=Array.isArray(e?.output)?e.output:[],o=r.filter(l=>l!==null&&typeof l=="object"&&l.type==="message"),s=n.filter(l=>l.type==="message").length===o.length,i=0;return[...n.map(l=>l.type==="message"&&s?Od(o[i++],l):l),...Id(r,n)]}function Id(t,e){let n=e.some(u=>u.type==="message"),r=e.some(u=>u.type==="reasoning"),o=u=>String(u.call_id??u.id??""),s=e.filter(u=>u.type==="function_call"),i=t.filter(u=>u!==null&&typeof u=="object"&&u.type==="function_call").length,a=s.length===i,l=new Set(s.map(o));return t.filter(u=>{if(u===null||typeof u!="object")return!0;let d=u;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!l.has(o(d)):!0})}function Od(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*Td(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:l,stats:u}=t,d=[],c=N=>N.response&&typeof N.response=="object"?{...N,response:{...N.response,id:r}}:N,p=`item_${r.slice(5)}`,m=!1,h=!1,v=0;function*S(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let w=[],f=(N,j)=>{w.push({output_index:N,item:j})},g=!1,y=0,_="",I=0,A="";function*b(){if(!g)return;g=!1,yield{type:"response.reasoning_text.done",item_id:_,output_index:y,content_index:0,text:A};let N={id:_,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:A}],status:"completed"};yield{type:"response.output_item.done",output_index:y,item:N},f(y,N),A=""}let R=!1,k=0,E="",x=0,T="",$="";function*D(N){if(!R)return;R=!1,yield{type:"response.output_text.done",item_id:E,output_index:k,content_index:0,text:T},yield{type:"response.content_part.done",item_id:E,output_index:k,content_index:0,part:{type:"output_text",text:T}};let j={id:E,type:"message",role:"assistant",status:N,content:[{type:"output_text",text:T}]};yield{type:"response.output_item.done",output_index:k,item:j},f(k,j),T=""}let q=new qe,G=null,Ce=-1;function*J(N){if(!G)return;let j=G;G=null,yield{type:"response.function_call_arguments.done",item_id:j.fcId,output_index:j.outputIndex,arguments:j.args};let V={id:j.fcId,type:"function_call",call_id:j.callId??j.fcId,name:j.name??"",arguments:j.args,status:N};yield{type:"response.output_item.done",output_index:j.outputIndex,item:V},f(j.outputIndex,V)}let pe=!1;for await(let N of u.track(e,o,t.turn)){d.push(N);let j=String(N.type??"");if(j==="response.created"||j==="response.in_progress"){m=!0,yield c(N);continue}if(j==="response.output_item.added"){h=!0,yield c(N);continue}if(j==="response.reasoning_text.delta"&&!h){yield*S(),g||(g=!0,y=v++,I+=1,_=I===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${I}`,yield{type:"response.output_item.added",output_index:y,item:{id:_,type:"reasoning",summary:[],content:[],status:"in_progress"}}),A+=String(N.delta??""),yield{type:"response.reasoning_text.delta",item_id:_,output_index:y,content_index:0,delta:N.delta};continue}if(j==="response.output_text.delta"&&!h){yield*S(),yield*b(),R||(R=!0,k=v++,x+=1,E=x===1?p:`${p}_${x}`,yield{type:"response.output_item.added",output_index:k,item:{id:E,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:E,output_index:k,content_index:0,part:{type:"output_text",text:""}}),T+=String(N.delta??""),$+=String(N.delta??""),yield{type:j,item_id:E,output_index:k,content_index:0,delta:N.delta};continue}let V=h?null:vt(N);if(V){if(yield*S(),yield*b(),yield*D("completed"),q.add(V),V.tool_index!==Ce){yield*J("completed"),Ce=V.tool_index;let ze=v++;G={fcId:`fc_${r.slice(5)}_${V.tool_index}`,outputIndex:ze,callId:V.call_id,name:V.name,args:""},yield{type:"response.output_item.added",output_index:ze,item:{id:G.fcId,type:"function_call",call_id:G.callId??G.fcId,name:G.name??"",arguments:"",status:"in_progress"}}}G&&(V.call_id&&(G.callId=V.call_id),V.name&&(G.name=V.name),G.args+=V.delta,yield{type:"response.function_call_arguments.delta",item_id:G.fcId,output_index:G.outputIndex,delta:V.delta});continue}if(j==="response.completed"&&!h){let ze=_t(N.response),ft=st(s,q.size+ze.length,$);if(ft){pe=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ot(o,ft)}};break}if(yield*b(),yield*D("completed"),yield*J("completed"),q.size===0)for(let ee of ze){let Ee=v++,Ye=ee.id??ee.call_id??`fc_${Ee}`,qr=ee.arguments??"",Ps={id:Ye,type:"function_call",call_id:ee.call_id??Ye,name:ee.name??""};yield{type:"response.output_item.added",output_index:Ee,item:{...Ps,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Ye,output_index:Ee,delta:qr},yield{type:"response.function_call_arguments.done",item_id:Ye,output_index:Ee,arguments:qr};let Cs={...Ps,arguments:qr,status:"completed"};yield{type:"response.output_item.done",output_index:Ee,item:Cs},f(Ee,Cs)}let K=Ad(w,N.response);yield K.length>0?c({...N,response:{...N.response,output:K}}):c(N);continue}yield c(N)}if(yield*b(),yield*D("incomplete"),yield*J("incomplete"),i&&!pe){let N=Le(d);l.remember(r,n,ao(N,bt(d,N)),a)}}var Se=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},se=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Ge=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},dn=class extends Ge{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},uo=class extends Ge{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},xe=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},qn=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(){let e=this.slots.filter(n=>n.state==="paused"&&!n.opening).sort((n,r)=>n.slot.index-r.slot.index);return e.length>0?(this.openRuntime(e[0]),e[0]):this.ensureSlot()}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new dn;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new dn;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening);if(!s&&(i||a)&&this.slots.length<this.opts.max){this.openForDemand();continue}let l=r+n-Date.now();if(l<=0)throw new uo(n,this.slots.some(c=>c.state==="queued"));let u,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{u=setTimeout(c,l)})])}finally{clearTimeout(u);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new dn}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening);(r||o)&&this.openForDemand()}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let a=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};var co=require("@urun-sh/core"),Ae=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},po=33e4;function Bi(t,e=po){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((u,d)=>{o=d}),i=setTimeout(()=>o(new Gn),e),a;try{a=await Promise.race([r.next(),s])}catch(u){throw u instanceof F||u instanceof co.SessionFailedError&&u.kind==="transport-failed"?u:u instanceof Gn?(await r.return?.(void 0),new Ae("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new Ae("upstream_threw",`decision stream failed: ${String(u instanceof Error?u.message:u)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let l=a.value;if(typeof l=="object"&&l!==null&&"type"in l&&l.type==="error")throw new Ae("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield l}})()}var Gn=class extends Error{constructor(){super("stream idle timeout")}};function ji(t){return t instanceof Ae?!1:t instanceof F?!0:t instanceof co.SessionFailedError?t.kind==="transport-failed":!1}var Pd=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function Oe(t){return!Pd.some(e=>e.test(t))}function Te(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function ye(t,e){if(t instanceof F)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=qi(t);return n||{message:Te(e?.inferenceId??null),redacted:!0}}function qi(t){return t instanceof He?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof Y?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof B?{message:t.message,redacted:!1}:t instanceof Se?{message:t.message,redacted:!1}:t instanceof Ge?{message:t.message,redacted:!1}:t instanceof Ae?Oe(t.message)?{message:t.message,redacted:!1}:null:t instanceof xe?{message:t.message,redacted:!1}:t instanceof se?{message:t.message,redacted:!1}:null}function kt(t,e,n){let r=n??(i=>console.error(i)),o=qi(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ie(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Oe(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ie(e)}`),`the ${t} upstream failed while serving this request`)}function $e(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Oe(e)?e:null}function Ie(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var go="/v1/responses",Cd=64*1024*1024,Ld=8*1024*1024,$d=16,Gi=32,Wi=3600*1e3,Md=/^[A-Za-z0-9._-]{1,256}$/;function me(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Nd=me(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 ho(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Ud(t){for(;t.bufferedAmount>Ld&&t.readyState===We.WebSocket.OPEN;){let{promise:e,resolve:n}=ho();setTimeout(n,5),await e}}var fo=class extends wt{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 rt))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)}},mo=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new fo(ln(n)),e.on("message",(a,l)=>this.onMessage(a,l)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(me(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Wi/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Wi).unref?.()}ws;clients;stats;statusOf;operatorLog;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(me(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(me(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(me(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(me(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(me(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(me(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"||!Md.test(o.stream_id)){this.sendFrame(Nd);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Gi){this.sendFrame(me(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Gi}). 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??"",l=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,l.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=sn();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await un({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:an(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let a of i){if(this.closed||this.ws.readyState!==We.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Ud(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=sn(),o=an(r);try{let s=St(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:Ie(e);if(e instanceof be)return me(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof B)return me(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof F){let a=ye(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),me(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),me(s.status,{type:s.openaiType,message:o},n);let i=ye(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),me(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=$e(o),a=i??Te(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),me(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=$d;){let{promise:e,resolve:n}=ho();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!==We.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!==We.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Wn(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
10
+ ${h}\r
11
+ `),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(l=>l===void 0?i():a(l)))})(),s)}var We=require("ws");var $i=require("crypto"),Mi="Inference-Id";function un(){return(0,$i.randomUUID)()}function uo(t){return t==="/v1"||t.startsWith("/v1/")}function Ni(t,e){if(!uo(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 dn(t){return`resp_${t}`}function Ui(t){return`chatcmpl-${t}`}function Di(t){return`msg_${t}`}function be(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Fi(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function Hi(t){return`${JSON.stringify(t)}
12
+ `}var Ad=256,Id=128;function fe(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Id)}var nt=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>=Ad?"(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 u of e)u.type==="response.output_text.delta"&&typeof u.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+=u.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield u;let l=(performance.now()-(i??s))/1e3;a>0&&l>0&&(o.tokRates.push(a/l),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}}}},Od=256;function Td(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 rt=class extends Error{},vt=class{conversations=new Map;thread(e,n){let r=Td(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new rt(`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<=Od)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Bi=new WeakMap;function cn(t){let e=Bi.get(t);return e||(e=new vt,Bi.set(t,e)),e}function bt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Le(t){return t.find(e=>e.type==="response.completed")?.response??null}function St(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 qe=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}))}},Pd=["<tool_call>","<function="];function Cd(t){return Pd.find(e=>t.includes(e))}function ot(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 st(t,e,n){if(!(!t||e>0))return Cd(n)}function kt(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 Ue(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Ld(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 co(t,e){let n=Ld(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var Se=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Rt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof rt?new Se(n.message,"previous_response_not_found",400,"previous_response_id"):new Se(String(n instanceof Error?n.message:n),"invalid_input")}}function ji(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function po(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new Se("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}:{},...ji(e)!==void 0?{response_format:ji(e)}:{}},o)}async function pn(t){let{body:e,clients:n,store:r,stats:o}=t,s=Rt(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,l=e.store!==!1,u=fe(e);o.model(u);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await po(n,e,s,!0,c?be(c):void 0);return{responseId:i,events:Ud({events:p,conversation:s,responseId:i,modelKey:u,requestHadTools:d,remember:a,persist:l,store:r,stats:o,turn:t.turn})}}function $d(t,e){let n=[...t].sort((l,u)=>l.output_index-u.output_index).map(({item:l})=>l),r=Array.isArray(e?.output)?e.output:[],o=r.filter(l=>l!==null&&typeof l=="object"&&l.type==="message"),s=n.filter(l=>l.type==="message").length===o.length,i=0;return[...n.map(l=>l.type==="message"&&s?Nd(o[i++],l):l),...Md(r,n)]}function Md(t,e){let n=e.some(u=>u.type==="message"),r=e.some(u=>u.type==="reasoning"),o=u=>String(u.call_id??u.id??""),s=e.filter(u=>u.type==="function_call"),i=t.filter(u=>u!==null&&typeof u=="object"&&u.type==="function_call").length,a=s.length===i,l=new Set(s.map(o));return t.filter(u=>{if(u===null||typeof u!="object")return!0;let d=u;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!l.has(o(d)):!0})}function Nd(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*Ud(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:l,stats:u}=t,d=[],c=U=>U.response&&typeof U.response=="object"?{...U,response:{...U.response,id:r}}:U,p=`item_${r.slice(5)}`,h=!1,m=!1,_=0;function*b(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let v=[],R=(U,G)=>{v.push({output_index:U,item:G})},f=!1,g=0,y="",S=0,A="";function*w(){if(!f)return;f=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:g,content_index:0,text:A};let U={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:A}],status:"completed"};yield{type:"response.output_item.done",output_index:g,item:U},R(g,U),A=""}let E=!1,k=0,I="",x=0,O="",$="";function*M(U){if(!E)return;E=!1,yield{type:"response.output_text.done",item_id:I,output_index:k,content_index:0,text:O},yield{type:"response.content_part.done",item_id:I,output_index:k,content_index:0,part:{type:"output_text",text:O}};let G={id:I,type:"message",role:"assistant",status:U,content:[{type:"output_text",text:O}]};yield{type:"response.output_item.done",output_index:k,item:G},R(k,G),O=""}let q=new qe,H=null,he=-1;function*J(U){if(!H)return;let G=H;H=null,yield{type:"response.function_call_arguments.done",item_id:G.fcId,output_index:G.outputIndex,arguments:G.args};let K={id:G.fcId,type:"function_call",call_id:G.callId??G.fcId,name:G.name??"",arguments:G.args,status:U};yield{type:"response.output_item.done",output_index:G.outputIndex,item:K},R(G.outputIndex,K)}let pe=!1;for await(let U of u.track(e,o,t.turn)){d.push(U);let G=String(U.type??"");if(G==="response.created"||G==="response.in_progress"){h=!0,yield c(U);continue}if(G==="response.output_item.added"){m=!0,yield c(U);continue}if(G==="response.reasoning_text.delta"&&!m){yield*b(),f||(f=!0,g=_++,S+=1,y=S===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${S}`,yield{type:"response.output_item.added",output_index:g,item:{id:y,type:"reasoning",summary:[],content:[],status:"in_progress"}}),A+=String(U.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:g,content_index:0,delta:U.delta};continue}if(G==="response.output_text.delta"&&!m){yield*b(),yield*w(),E||(E=!0,k=_++,x+=1,I=x===1?p:`${p}_${x}`,yield{type:"response.output_item.added",output_index:k,item:{id:I,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:I,output_index:k,content_index:0,part:{type:"output_text",text:""}}),O+=String(U.delta??""),$+=String(U.delta??""),yield{type:G,item_id:I,output_index:k,content_index:0,delta:U.delta};continue}let K=m?null:St(U);if(K){if(yield*b(),yield*w(),yield*M("completed"),q.add(K),K.tool_index!==he){yield*J("completed"),he=K.tool_index;let ze=_++;H={fcId:`fc_${r.slice(5)}_${K.tool_index}`,outputIndex:ze,callId:K.call_id,name:K.name,args:""},yield{type:"response.output_item.added",output_index:ze,item:{id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:"",status:"in_progress"}}}H&&(K.call_id&&(H.callId=K.call_id),K.name&&(H.name=K.name),H.args+=K.delta,yield{type:"response.function_call_arguments.delta",item_id:H.fcId,output_index:H.outputIndex,delta:K.delta});continue}if(G==="response.completed"&&!m){let ze=bt(U.response),mt=st(s,q.size+ze.length,$);if(mt){pe=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ot(o,mt)}};break}if(yield*w(),yield*M("completed"),yield*J("completed"),q.size===0)for(let te of ze){let xe=_++,Ye=te.id??te.call_id??`fc_${xe}`,Wr=te.arguments??"",Ms={id:Ye,type:"function_call",call_id:te.call_id??Ye,name:te.name??""};yield{type:"response.output_item.added",output_index:xe,item:{...Ms,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Ye,output_index:xe,delta:Wr},yield{type:"response.function_call_arguments.done",item_id:Ye,output_index:xe,arguments:Wr};let Ns={...Ms,arguments:Wr,status:"completed"};yield{type:"response.output_item.done",output_index:xe,item:Ns},R(xe,Ns)}let z=$d(v,U.response);yield z.length>0?c({...U,response:{...U.response,output:z}}):c(U);continue}yield c(U)}if(yield*w(),yield*M("incomplete"),yield*J("incomplete"),i&&!pe){let U=Le(d);l.remember(r,n,co(U,kt(d,U)),a)}}var ke=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ae=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Ge=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},fn=class extends Ge{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},fo=class extends Ge{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},Ae=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Wn=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(){let e=this.slots.filter(n=>n.state==="paused"&&!n.opening).sort((n,r)=>n.slot.index-r.slot.index);return e.length>0?(this.openRuntime(e[0]),e[0]):this.ensureSlot()}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new fn;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new fn;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening);if(!s&&(i||a)&&this.slots.length<this.opts.max){this.openForDemand();continue}let l=r+n-Date.now();if(l<=0)throw new fo(n,this.slots.some(c=>c.state==="queued"));let u,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{u=setTimeout(c,l)})])}finally{clearTimeout(u);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new fn}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening);(r||o)&&this.openForDemand()}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let a=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};var mo=require("@urun-sh/core"),Ie=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},go=33e4;function qi(t,e=go){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((u,d)=>{o=d}),i=setTimeout(()=>o(new Vn),e),a;try{a=await Promise.race([r.next(),s])}catch(u){throw u instanceof F||u instanceof mo.SessionFailedError&&u.kind==="transport-failed"?u:u instanceof Vn?(await r.return?.(void 0),new Ie("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new Ie("upstream_threw",`decision stream failed: ${String(u instanceof Error?u.message:u)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let l=a.value;if(typeof l=="object"&&l!==null&&"type"in l&&l.type==="error")throw new Ie("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield l}})()}var Vn=class extends Error{constructor(){super("stream idle timeout")}};function Gi(t){return t instanceof Ie?!1:t instanceof F?!0:t instanceof mo.SessionFailedError?t.kind==="transport-failed":!1}var Dd=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function Te(t){return!Dd.some(e=>e.test(t))}function Pe(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function we(t,e){if(t instanceof F)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=Wi(t);return n||{message:Pe(e?.inferenceId??null),redacted:!0}}function Wi(t){return t instanceof He?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof Y?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof j?{message:t.message,redacted:!1}:t instanceof ke?{message:t.message,redacted:!1}:t instanceof Ge?{message:t.message,redacted:!1}:t instanceof Ie?Te(t.message)?{message:t.message,redacted:!1}:null:t instanceof Ae?{message:t.message,redacted:!1}:t instanceof ae?{message:t.message,redacted:!1}:null}function Et(t,e,n){let r=n??(i=>console.error(i)),o=Wi(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Oe(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Te(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Oe(e)}`),`the ${t} upstream failed while serving this request`)}function $e(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Te(e)?e:null}function Oe(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var wo="/v1/responses",Fd=64*1024*1024,Hd=8*1024*1024,Bd=16,Vi=32,Ji=3600*1e3,jd=/^[A-Za-z0-9._-]{1,256}$/;function me(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var qd=me(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 _o(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Gd(t){for(;t.bufferedAmount>Hd&&t.readyState===We.WebSocket.OPEN;){let{promise:e,resolve:n}=_o();setTimeout(n,5),await e}}var ho=class extends vt{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 rt))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)}},yo=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new ho(cn(n)),e.on("message",(a,l)=>this.onMessage(a,l)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(me(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Ji/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Ji).unref?.()}ws;clients;stats;statusOf;operatorLog;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(me(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(me(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(me(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(me(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(me(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(me(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"||!jd.test(o.stream_id)){this.sendFrame(qd);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Vi){this.sendFrame(me(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Vi}). 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??"",l=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,l.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=un();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await pn({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:dn(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let a of i){if(this.closed||this.ws.readyState!==We.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Gd(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=un(),o=dn(r);try{let s=Rt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:Oe(e);if(e instanceof Se)return me(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof j)return me(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof F){let a=we(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),me(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),me(s.status,{type:s.openaiType,message:o},n);let i=we(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),me(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=$e(o),a=i??Pe(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),me(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=Bd;){let{promise:e,resolve:n}=_o();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!==We.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!==We.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Jn(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
13
13
  `;t.end(`HTTP/1.1 ${e} ${r}\r
14
14
  Connection: close\r
15
15
  Content-Type: text/plain; charset=utf-8\r
16
16
  Content-Length: ${Buffer.byteLength(o)}\r
17
17
  \r
18
- ${o}`)}function yo(t,e){let n=new We.WebSocketServer({noServer:!0,maxPayload:Cd}),r=new nt,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{Wn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==go){i.add(c);return}s.add(c);let h=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Wn(c,401,"invalid local proxy api key");return}let v;try{v=await a(d)}catch(S){let w=e.statusOf?.(S)??null;Wn(c,w?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(h=!0,n.handleUpgrade(d,c,p,S=>{s.delete(c),o.add(S),S.on("close",()=>o.delete(S));try{new mo(S,v,r,e.statusOf,e.operatorLog??(w=>console.error(w)))}catch{o.delete(S),S.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!h&&!c.destroyed&&Wn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=ho();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let m of s)m.destroy();s.clear();for(let m of i)m.destroy();i.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==We.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Ro=require("@urun-sh/core");var Ji=require("@urun-sh/core"),Dd={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Fd={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function cn(t,e){let n=Fd[t.code];return e?`${n} (${e})`:n}function Jn(t){if(t==null)return null;let e=Dd[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Vn(t){if(t.kind==="create-failed")return Jn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Ji.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Jn(e?"cold_start_exceeded":"queue_timeout")}var Hd=de(require("os"),1),Bd=de(require("path"),1),jd=require("url"),qd=require("util");function Vi(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 Kn(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 Gd=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Wd(t){let e=t?.code;return typeof e=="string"&&Gd.has(e)}function Je(t,e){try{return t.write(e),!0}catch(n){if(Wd(n))return!1;throw n}}var Zi=require("ws");var Qi=require("@urun-sh/core");var zi=require("crypto");function C(t){return`${t}_${(0,zi.randomUUID)().replace(/-/g,"").slice(0,24)}`}var zn=4*1024*1024,wo=8*1024*1024,Yn=512,Xn=20*1024*1024;function oe(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Et(t,e){return{type:"server_error",code:t,message:e}}function z(t){return{type:"error",event_id:C("event"),error:t}}function _o(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var L=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Jd={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Vd={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Kd={format:!0,voice:!0,speed:!0};function zd(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function Rt(t,e){if(!Array.isArray(t)||t.length===0)throw new L(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new L(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function Ki(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new L(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Yd=10;function vo(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Yd})}function pn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new L("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Jd));if(s.length>0)throw new L(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=Rt(o.modalities,"modalities"),l=Rt(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new L("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[a,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new L(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new L(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(l==="transcription"&&!n.turns)throw new L('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new L(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=Rt(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new L('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");i.outputModalities=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!zd(l))throw new L(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(l!==null&&typeof l!="string")throw new L("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new L("instructions must be a string or null","instructions");i.instructions=vo(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new L("voice must be a string or null","voice");if(!n.voice)throw new L("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new L(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new L("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new L(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new L("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new L("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new L("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new L("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new L(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,m]of Object.entries(u))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new L(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(m!=null&&m!==c[p])throw new L(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new L("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!l||typeof l!="object"||Array.isArray(l))throw new L("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new L(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new L(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(l!==null)throw new L("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new L("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 L("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Vd))throw new L(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Ki(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=pn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=pn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new L("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 L("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Kd))throw new L(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Ki(d.format,"audio.output.format"),d.speed!==void 0)throw new L("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete i.voice;else{if(typeof d.voice!="string")throw new L("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new L("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function Qn(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function bo(t,e){let n=t;if(!n||typeof n!="object")throw new L("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 L("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:C("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 L('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new L("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 L("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 L(`${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 L("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 L("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 L(`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:C("item"),type:"message",role:r,content:o}}throw new L(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Zn(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 Xd=1001,Qd=1011,Yi=t=>t.slice(0,120),Zd=/^[A-Za-z0-9+/=]*$/,ec=2;function tc(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ec)return!1;return!0}var fn=class{id=C("conn");ws;binding;onClosed;operatorLog;config=_o();sessionId=C("sess");conversationId=C("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:C("event"),session:Qn(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:C("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof F&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(z(Et("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:C("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:C("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:C("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:C("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:C("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:C("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:C("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:C("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=C("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:C("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:C("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:C("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:C("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(oe("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>zn){this.fail(oe("frame_too_large",`frame exceeds the ${zn}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(oe("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(oe("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(z({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Et(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=pn(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(z(oe("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:C("event"),session:Qn(this.config,this.sessionId)});return}case"conversation.item.create":{let n=bo(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.added",event_id:C("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(z(oe("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:C("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(z(oe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:C("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(z(oe("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:C("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(z(oe("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Zd.test(e.audio)){this.send(z(oe("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>Xn){this.send(z(oe("buffer_full",`uncommitted input audio exceeds the ${Xn}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:C("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(z(oe("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=C("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:C("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:C("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:C("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:C("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(z(oe("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(z(oe("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(z(oe("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(z(oe("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(z({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(z(oe("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?Rt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?Rt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new L("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(z(oe("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,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=C("req"),a=`resp_${i}`;this.activeResponseId=a;let l=this.binding.composite===!0,u=l?0:this.items.length,d=l?null:Zn(this.items),c=vo(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,m=n.max_output_tokens??this.config.maxOutputTokens,h=m==="inf"||m===void 0?void 0:m,v=n.tools!==void 0?n.tools:this.config.tools,S=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,w={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...h!==void 0?{max_output_tokens:h}:{},...v!==void 0?{tools:v}:{},...S!==void 0?{tool_choice:S}:{}};if(!(l&&!this.ensureVoice())){for(let f of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(f);this.inFlight=(async()=>{let f=[],g=A=>{this.responseFlushed?this.send(A):f.push(A)},y=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:C("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:C("event"),response:this.responseObject(a,"in_progress")});for(let A of f)this.send(A);f.length=0,this.responseFlushed=!0}},_={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},I=null;try{if(l){if(this.pendingTranscriptItemId!==null&&(await new Promise(E=>{this.pendingTranscriptSettled=E}),this.cancelled||this.closed))return;u=this.items.length,d=Zn(this.items)}let{input:A,sawAudioOnlyItem:b}=d??{input:[],sawAudioOnlyItem:!1},R={...w,input:A,...l?this.compositeTurnAsk(n):{}};b&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let k;try{k=await this.upstreamStream(R,i)}catch(E){this.upstreamTurnFault(E,a);return}try{for await(let E of k){if(this.cancelled)break;let x=E;if(x.type==="error"){let T=this.upstreamErrorBody(x);this.responseFlushed?this.send(z(T)):this.send({type:"response.failed",event_id:C("event"),response:this.failedResponse(a,T)});return}if(x.type==="response.output_text.delta"&&typeof x.delta=="string"){y(),_.messageOpen||(this.beginMessageItem(a,_.nextOutputIndex++),_.messageOpen=!0),this.config.outputModalities.includes("text")&&g({type:"response.output_text.delta",event_id:C("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:x.delta}),this.turnOutputIsAudio()&&(_.transcriptDelta=!0,g({type:"response.output_audio_transcript.delta",event_id:C("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:x.delta})),_.messageText+=x.delta;continue}if(x.type==="response.function_call_arguments.delta"){y();let T=typeof x.delta=="string"?x.delta:"",$=typeof x.call_id=="string"&&x.call_id.length>0?x.call_id:`${a}_fc_${_.nextOutputIndex}`,D=_.tools.get($);if(!D){let q=typeof x.name=="string"&&x.name.length>0?x.name:void 0;D={outputIndex:_.nextOutputIndex++,name:q,args:""},_.tools.set($,D);let G={id:$,object:"realtime.item",type:"function_call",call_id:$,name:q??"",arguments:"",status:"in_progress"};g({type:"response.output_item.added",event_id:C("event"),response_id:a,output_index:D.outputIndex,item:G}),this.emitAssistantItemAdded(G)}typeof x.name=="string"&&x.name.length>0&&(D.name=x.name),D.args+=T,g({type:"response.function_call_arguments.delta",event_id:C("event"),item_id:$,response_id:a,output_index:D.outputIndex,call_id:$,name:D.name??"",delta:T});continue}if(x.type==="response.completed"){I=x.response??null;continue}}}catch(E){this.upstreamTurnFault(E,a);return}if(this.cancelled)return;this.closeOpenItems(a,_,u),y(),this.send({type:"response.done",event_id:C("event"),response:this.doneResponse(a,u,I)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(tc(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(z({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:C("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:C("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:C("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:C("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:C("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:C("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:C("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:C("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:C("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:C("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:C("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:C("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:C("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:C("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:C("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:C("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=$e(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??Te(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&Oe(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Ie(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Et("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof F){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Qi.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Et(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(z(r)):this.send({type:"response.failed",event_id:C("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(z(oe("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:C("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Yn&&(this.items.shift(),this.send(z({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Yn} 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>wo){this.ws.close(Xd,Yi("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=ye(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ie(e)}`),r.message}fail(e,n){this.send(z(e)),this.ws.close(Qd,Yi(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>Xi(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Xi(this.id,e)}},So=[];function Xi(t,e){So.push({id:t,reason:e}),So.length>256&&So.shift()}var mn="/v1/realtime",nc=t=>t.slice(0,120);function rc(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
18
+ ${o}`)}function vo(t,e){let n=new We.WebSocketServer({noServer:!0,maxPayload:Fd}),r=new nt,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,p)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{Jn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==wo){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Jn(c,401,"invalid local proxy api key");return}let _;try{_=await a(d)}catch(b){let v=e.statusOf?.(b)??null;Jn(c,v?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(m=!0,n.handleUpgrade(d,c,p,b=>{s.delete(c),o.add(b),b.on("close",()=>o.delete(b));try{new yo(b,_,r,e.statusOf,e.operatorLog??(v=>console.error(v)))}catch{o.delete(b),b.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&Jn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=_o();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let p=setTimeout(()=>{for(let h of o)h.readyState!==We.WebSocket.CLOSED&&h.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Ao=require("@urun-sh/core");var Ki=require("@urun-sh/core"),Wd={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Vd={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function mn(t,e){let n=Vd[t.code];return e?`${n} (${e})`:n}function Kn(t){if(t==null)return null;let e=Wd[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function zn(t){if(t.kind==="create-failed")return Kn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Ki.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Kn(e?"cold_start_exceeded":"queue_timeout")}var Jd=ce(require("os"),1),Kd=ce(require("path"),1),zd=require("url"),Yd=require("util");function zi(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 Yn(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 Xd=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Qd(t){let e=t?.code;return typeof e=="string"&&Xd.has(e)}function Ve(t,e){try{return t.write(e),!0}catch(n){if(Qd(n))return!1;throw n}}var ta=require("ws");var ea=require("@urun-sh/core");var Xi=require("crypto");function C(t){return`${t}_${(0,Xi.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Xn=4*1024*1024,bo=8*1024*1024,Qn=512,Zn=20*1024*1024;function X(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function it(t,e){return{type:"server_error",code:t,message:e}}function W(t){return{type:"error",event_id:C("event"),error:t}}function So(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var L=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Zd={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},ec={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},tc={format:!0,voice:!0,speed:!0};function nc(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function xt(t,e){if(!Array.isArray(t)||t.length===0)throw new L(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new L(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function Yi(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new L(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var rc=10;function ko(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:rc})}function gn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new L("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Zd));if(s.length>0)throw new L(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=xt(o.modalities,"modalities"),l=xt(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new L("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[a,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new L(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new L(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(l==="transcription"&&!n.turns)throw new L('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new L(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=xt(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new L('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");i.outputModalities=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!nc(l))throw new L(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(l!==null&&typeof l!="string")throw new L("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new L("instructions must be a string or null","instructions");i.instructions=ko(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new L("voice must be a string or null","voice");if(!n.voice)throw new L("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new L(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new L("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new L(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new L("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new L("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new L("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new L("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new L(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,h]of Object.entries(u))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new L(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(h!=null&&h!==c[p])throw new L(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new L("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!l||typeof l!="object"||Array.isArray(l))throw new L("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new L(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new L(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(l!==null)throw new L("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new L("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 L("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in ec))throw new L(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Yi(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=gn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=gn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new L("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 L("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in tc))throw new L(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Yi(d.format,"audio.output.format"),d.speed!==void 0)throw new L("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete i.voice;else{if(typeof d.voice!="string")throw new L("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new L("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function er(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Ro(t,e){let n=t;if(!n||typeof n!="object")throw new L("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 L("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:C("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 L('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new L("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 L("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 L(`${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 L("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 L("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new L("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new L("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new L("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let l=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...l!==void 0?{detail:l}:{}});continue}throw new L(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:C("item"),type:"message",role:r,content:o}}throw new L(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function tr(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 oc=1001,sc=1011,Qi=t=>t.slice(0,120),ic=/^[A-Za-z0-9+/=]*$/,ac=2;function lc(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ac)return!1;return!0}var hn=class{id=C("conn");ws;binding;onClosed;operatorLog;config=So();sessionId=C("sess");conversationId=C("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:C("event"),session:er(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:C("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof F&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(W(it("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:C("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:C("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:C("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:C("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:C("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:C("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:C("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:C("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=C("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:C("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:C("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:C("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:C("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(X("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Xn){this.fail(X("frame_too_large",`frame exceeds the ${Xn}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(X("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(X("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(W({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(it(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=gn(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(W(X("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:C("event"),session:er(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Ro(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:C("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(W(X("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:C("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(W(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:C("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(W(X("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:C("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(W(X("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ic.test(e.audio)){this.send(W(X("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>Zn){this.send(W(X("buffer_full",`uncommitted input audio exceeds the ${Zn}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:C("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(W(X("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=C("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:C("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:C("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:C("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:C("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(W(X("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(W(X("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(W(X("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(W(X("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(W({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(W(X("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?xt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?xt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new L("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(W(X("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,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=C("req"),a=`resp_${i}`;this.activeResponseId=a;let l=this.binding.composite===!0,u=l?0:this.items.length,d=l?null:tr(this.items),c=ko(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,h=n.max_output_tokens??this.config.maxOutputTokens,m=h==="inf"||h===void 0?void 0:h,_=n.tools!==void 0?n.tools:this.config.tools,b=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,v={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...m!==void 0?{max_output_tokens:m}:{},..._!==void 0?{tools:_}:{},...b!==void 0?{tool_choice:b}:{}};if(!(l&&!this.ensureVoice())){for(let R of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(R);this.inFlight=(async()=>{let R=[],f=A=>{this.responseFlushed?this.send(A):R.push(A)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:C("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:C("event"),response:this.responseObject(a,"in_progress")});for(let A of R)this.send(A);R.length=0,this.responseFlushed=!0}},y={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},S=null;try{if(l){if(this.pendingTranscriptItemId!==null&&(await new Promise(I=>{this.pendingTranscriptSettled=I}),this.cancelled||this.closed))return;u=this.items.length,d=tr(this.items)}let{input:A,sawAudioOnlyItem:w}=d??{input:[],sawAudioOnlyItem:!1},E={...v,input:A,...l?this.compositeTurnAsk(n):{}};w&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let k;try{k=await this.upstreamStream(E,i)}catch(I){this.upstreamTurnFault(I,a);return}try{for await(let I of k){if(this.cancelled)break;let x=I;if(x.type==="error"){let O=this.upstreamErrorBody(x);this.responseFlushed?this.send(W(O)):this.send({type:"response.failed",event_id:C("event"),response:this.failedResponse(a,O)});return}if(x.type==="response.output_text.delta"&&typeof x.delta=="string"){g(),y.messageOpen||(this.beginMessageItem(a,y.nextOutputIndex++),y.messageOpen=!0),this.config.outputModalities.includes("text")&&f({type:"response.output_text.delta",event_id:C("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:x.delta}),this.turnOutputIsAudio()&&(y.transcriptDelta=!0,f({type:"response.output_audio_transcript.delta",event_id:C("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:x.delta})),y.messageText+=x.delta;continue}if(x.type==="response.function_call_arguments.delta"){g();let O=typeof x.delta=="string"?x.delta:"",$=typeof x.call_id=="string"&&x.call_id.length>0?x.call_id:`${a}_fc_${y.nextOutputIndex}`,M=y.tools.get($);if(!M){let q=typeof x.name=="string"&&x.name.length>0?x.name:void 0;M={outputIndex:y.nextOutputIndex++,name:q,args:""},y.tools.set($,M);let H={id:$,object:"realtime.item",type:"function_call",call_id:$,name:q??"",arguments:"",status:"in_progress"};f({type:"response.output_item.added",event_id:C("event"),response_id:a,output_index:M.outputIndex,item:H}),this.emitAssistantItemAdded(H)}typeof x.name=="string"&&x.name.length>0&&(M.name=x.name),M.args+=O,f({type:"response.function_call_arguments.delta",event_id:C("event"),item_id:$,response_id:a,output_index:M.outputIndex,call_id:$,name:M.name??"",delta:O});continue}if(x.type==="response.completed"){S=x.response??null;continue}}}catch(I){this.upstreamTurnFault(I,a);return}if(this.cancelled)return;this.closeOpenItems(a,y,u),g(),this.send({type:"response.done",event_id:C("event"),response:this.doneResponse(a,u,S)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(lc(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(W({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:C("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:C("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:C("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:C("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:C("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:C("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:C("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:C("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:C("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:C("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:C("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:C("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:C("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:C("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:C("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:C("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=$e(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??Pe(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&Te(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Oe(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(it("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof F){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof ea.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=it(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(W(r)):this.send({type:"response.failed",event_id:C("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(W(X("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:C("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Qn&&(this.items.shift(),this.send(W({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Qn} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(W(X("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>en){this.send(W(X("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${en}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(W(X("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(W(it(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>bo){this.ws.close(oc,Qi("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=we(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Oe(e)}`),r.message}fail(e,n){this.send(W(e)),this.ws.close(sc,Qi(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>Zi(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Zi(this.id,e)}},Eo=[];function Zi(t,e){Eo.push({id:t,reason:e}),Eo.length>256&&Eo.shift()}var yn="/v1/realtime",uc=t=>t.slice(0,120);function dc(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
19
19
  Connection: close\r
20
20
  Content-Type: text/plain\r
21
21
  \r
22
- ${nc(n)}\r
23
- `),t.destroy()}function oc(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
24
- `}function sc(t){Je(process.stdout,t)}function ic(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ko(t){return t.audioSession?.audio.sessionId??void 0}function er(t,e){let n=new Zi.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==mn)return;r.add(s),s.on("close",()=>{r.delete(s)});let l=C("rtup"),u=ic(o),d=_=>{(e.log??sc)(oc(_))};d({stage:"accept",conn:l,model:u}),s.resume();let c=new AbortController,p=null,m=_=>{p??=_,c.abort(new Error(p))},h=()=>m("client socket closed"),v=()=>m("client socket closed (half-close)"),S=_=>m(`client socket error: ${_.message}`);s.once("close",h),s.once("end",v),s.once("error",S);let w=()=>{s.removeListener("close",h),s.removeListener("end",v),s.removeListener("error",S)},f=_=>{d({stage:"close",conn:l,model:u,..._})},g=_=>{let I=_,A=I.session!=null&&typeof I.session.sendResponseCreate=="function",b=I.clients!=null&&typeof I.clients.createResponse=="function";if(!A&&!b)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((R,k)=>{n.handleUpgrade(o,s,i,E=>{try{new fn({ws:E,binding:_,operatorLog:e.operatorLog,onClosed:(x,T)=>{f({while:"live",reason:T.reason})}}),d({stage:"admit",conn:l,model:u,...ko(_)===void 0?{}:{session:ko(_)}}),R()}catch(x){k(x)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async _=>{if(c.signal.aborted){w();let I=ko(_);try{await _.release?.()}catch(A){f({while:"queued",...I===void 0?{}:{session:I},reason:p??"client socket closed",release_failed:A instanceof Error?A.message:String(A)});return}f({while:"queued",...I===void 0?{}:{session:I},reason:p??"client socket closed",released:!0}),s.destroy();return}w(),await g(_)}).catch(_=>{let I=_ instanceof Ro.SessionFailedError?Vn(_):null,A=null;if(_!==null&&typeof _=="object"&&"status"in _){let E=_.status;typeof E=="number"&&(A=E)}let b=A??I?.status??502,R=_ instanceof Error?_.message:String(_),k=A!==null?R:I!==null?cn(I,_ instanceof Ro.SessionFailedError&&_.status.sessionId?`session ${_.status.sessionId}`:void 0):ye(_).message;f({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:R,status:b}}),s.destroyed||rc(s,b,k)}).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 ul=require("crypto");var mp=require("http");var M=class extends Error{},ke=class extends Error{};function ae(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function nr(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function xt(t,e){if(t!=null)throw new M(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function tr(t){let e=nr(t);return e!==null&&e<=1?e:null}function ea(t,e){if(!ae(t))throw new M("decisions requires a JSON object body");xt(t.prompt_cache_key,"prompt_cache_key"),xt(t.prompt_cache_options,"prompt_cache_options"),xt(t.safety_identifier,"safety_identifier");let n=[],r=ac(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new M("decisions requires a questions array of 1 to 400 questions");let s={},i=[],a=new Set;for(let u=0;u<o.length;u++){let{entry:d,spec:c}=cc(o[u],u,o.length,n);if(a.has(c.key))throw new M(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),s[c.key]=d,i.push(c)}let l={model:e,state:r,questions:s};return n.length>0&&(l.media=n),{systemone:l,specs:i}}function ac(t,e){if(typeof t=="string")return t;if(!ae(t)&&!Array.isArray(t))throw new M("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)uc(o,r,e);return lc(r)}function lc(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
22
+ ${uc(n)}\r
23
+ `),t.destroy()}function cc(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
24
+ `}function pc(t){Ve(process.stdout,t)}function fc(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function xo(t){return t.audioSession?.audio.sessionId??void 0}function nr(t,e){let n=new ta.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==yn)return;r.add(s),s.on("close",()=>{r.delete(s)});let l=C("rtup"),u=fc(o),d=y=>{(e.log??pc)(cc(y))};d({stage:"accept",conn:l,model:u}),s.resume();let c=new AbortController,p=null,h=y=>{p??=y,c.abort(new Error(p))},m=()=>h("client socket closed"),_=()=>h("client socket closed (half-close)"),b=y=>h(`client socket error: ${y.message}`);s.once("close",m),s.once("end",_),s.once("error",b);let v=()=>{s.removeListener("close",m),s.removeListener("end",_),s.removeListener("error",b)},R=y=>{d({stage:"close",conn:l,model:u,...y})},f=y=>{let S=y,A=S.session!=null&&typeof S.session.sendResponseCreate=="function",w=S.clients!=null&&typeof S.clients.createResponse=="function";if(!A&&!w)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((E,k)=>{n.handleUpgrade(o,s,i,I=>{try{new hn({ws:I,binding:y,operatorLog:e.operatorLog,onClosed:(x,O)=>{R({while:"live",reason:O.reason})}}),d({stage:"admit",conn:l,model:u,...xo(y)===void 0?{}:{session:xo(y)}}),E()}catch(x){k(x)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async y=>{if(c.signal.aborted){v();let S=xo(y);try{await y.release?.()}catch(A){R({while:"queued",...S===void 0?{}:{session:S},reason:p??"client socket closed",release_failed:A instanceof Error?A.message:String(A)});return}R({while:"queued",...S===void 0?{}:{session:S},reason:p??"client socket closed",released:!0}),s.destroy();return}v(),await f(y)}).catch(y=>{let S=y instanceof Ao.SessionFailedError?zn(y):null,A=null;if(y!==null&&typeof y=="object"&&"status"in y){let I=y.status;typeof I=="number"&&(A=I)}let w=A??S?.status??502,E=y instanceof Error?y.message:String(y),k=A!==null?E:S!==null?mn(S,y instanceof Ao.SessionFailedError&&y.status.sessionId?`session ${y.status.sessionId}`:void 0):we(y).message;R({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:E,status:w}}),s.destroyed||dc(s,w,k)}).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 cl=require("crypto");var bp=require("http");var N=class extends Error{},Re=class extends Error{};function le(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function or(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function At(t,e){if(t!=null)throw new N(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function rr(t){let e=or(t);return e!==null&&e<=1?e:null}function na(t,e){if(!le(t))throw new N("decisions requires a JSON object body");At(t.prompt_cache_key,"prompt_cache_key"),At(t.prompt_cache_options,"prompt_cache_options"),At(t.safety_identifier,"safety_identifier");let n=[],r=mc(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new N("decisions requires a questions array of 1 to 400 questions");let s={},i=[],a=new Set;for(let u=0;u<o.length;u++){let{entry:d,spec:c}=wc(o[u],u,o.length,n);if(a.has(c.key))throw new N(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),s[c.key]=d,i.push(c)}let l={model:e,state:r,questions:s};return n.length>0&&(l.media=n),{systemone:l,specs:i}}function mc(t,e){if(typeof t=="string")return t;if(!le(t)&&!Array.isArray(t))throw new N("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)hc(o,r,e);return gc(r)}function gc(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
25
25
 
26
- `)}function uc(t,e,n){if(!ae(t))throw new M("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){dc(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let s=t.output;if(typeof s=="string"){e.push({text:s});return}if(Array.isArray(s)){ta(s,e,n,void 0,!1);return}throw new M(`${o} output must be a string or an array of parts`)}default:throw new M(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function dc(t,e,n,r){e==="assistant"&&xt(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new M(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!ae(s))throw new M("decisions assistant message parts must be JSON objects");if(s.type==="output_text"&&typeof s.text=="string")n.push({role:e,text:s.text});else if(s.type==="refusal"&&typeof s.refusal=="string")n.push({role:e,text:`[refusal] ${s.refusal}`});else throw new M(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}ta(o,n,r,e)}function ta(t,e,n,r,o=!0){for(let s of t){if(!ae(s))throw new M("decisions content parts must be JSON objects");switch(xt(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new M("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new M("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let i=s.data;if(!ae(i)&&!(Array.isArray(i)&&i.every(ae)))throw new M("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(na(s));break}default:throw new M(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function na(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new M("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new M("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new M("input_image data URL carries no image data");let s=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(s?o.length%4!==0:o.length%4===1))throw new M("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=t.detail;if(i!=null&&i!=="low"&&i!=="high"&&i!=="auto"&&i!=="original")throw new M("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(a.detail=i),a}function cc(t,e,n,r){if(!ae(t))throw new M(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new M(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let s=t.name;if(s!==void 0&&typeof s!="string")throw new M(`questions[${e}] name must be a string`);let i=s??null,a=i??`q${e}`,l=pc(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:l,options:[["no","the condition is not true"],["yes","the condition is true"]]},spec:{type:o,key:a,name:i}};case"choice":{let u=t.choices;if(!Array.isArray(u)||u.length<2||u.length>255)throw new M(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let v of u){if(!ae(v))throw new M(`questions[${e}] choices must be JSON objects`);let S=v.value;if(typeof S!="string"&&typeof S!="boolean")throw new M(`questions[${e}] choice value must be a string or boolean`);let w=String(S);if(c.has(w))throw new M(`questions[${e}] has duplicate choice value ${JSON.stringify(w)} (choices must be unique)`);c.add(w);let f=v.description;if(f!==void 0&&typeof f!="string")throw new M(`questions[${e}] choice description must be a string`);d.push(S),p.push(f)}let m=u.map((v,S)=>({name:String(d[S]),description:p[S]??String(d[S])}));return{entry:{kind:"choice",prompt:l,options:m},spec:{type:o,key:a,name:i,choiceValues:d}}}case"score":{let u=t.levels;if(!Array.isArray(u)||u.length<2||u.length>10)throw new M(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let m of u){if(!ae(m)||typeof m.label!="string")throw new M(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new M(`questions[${e}] has duplicate level label ${JSON.stringify(m.label)}`);d.push(m.label);let h=m.description;if(h!==void 0&&typeof h!="string")throw new M(`questions[${e}] score level description must be a string`);let v=h!==void 0?`${m.label}: ${h}`:m.label;if(c.includes(v))throw new M(`questions[${e}] has duplicate score criterion ${JSON.stringify(v)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(v)}return{entry:{kind:"score",prompt:l,criteria:c},spec:{type:o,key:a,name:i,levelLabels:d,scoreCriteria:c}}}}}function pc(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new M(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!ae(s))throw new M(`questions[${e}] instruction parts must be JSON objects`);switch(xt(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new M(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new M(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(na(s));break}case"input_json":{let i=s.data;if(!ae(i)&&!(Array.isArray(i)&&i.every(ae)))throw new M(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new M(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
26
+ `)}function hc(t,e,n){if(!le(t))throw new N("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){yc(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let s=t.output;if(typeof s=="string"){e.push({text:s});return}if(Array.isArray(s)){ra(s,e,n,void 0,!1);return}throw new N(`${o} output must be a string or an array of parts`)}default:throw new N(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function yc(t,e,n,r){e==="assistant"&&At(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new N(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!le(s))throw new N("decisions assistant message parts must be JSON objects");if(s.type==="output_text"&&typeof s.text=="string")n.push({role:e,text:s.text});else if(s.type==="refusal"&&typeof s.refusal=="string")n.push({role:e,text:`[refusal] ${s.refusal}`});else throw new N(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}ra(o,n,r,e)}function ra(t,e,n,r,o=!0){for(let s of t){if(!le(s))throw new N("decisions content parts must be JSON objects");switch(At(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new N("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new N("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let i=s.data;if(!le(i)&&!(Array.isArray(i)&&i.every(le)))throw new N("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(oa(s));break}default:throw new N(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function oa(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new N("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new N("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new N("input_image data URL carries no image data");let s=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(s?o.length%4!==0:o.length%4===1))throw new N("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=t.detail;if(i!=null&&i!=="low"&&i!=="high"&&i!=="auto"&&i!=="original")throw new N("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(a.detail=i),a}function wc(t,e,n,r){if(!le(t))throw new N(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new N(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let s=t.name;if(s!==void 0&&typeof s!="string")throw new N(`questions[${e}] name must be a string`);let i=s??null,a=i??`q${e}`,l=_c(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:l,options:[["no","the condition is not true"],["yes","the condition is true"]]},spec:{type:o,key:a,name:i}};case"choice":{let u=t.choices;if(!Array.isArray(u)||u.length<2||u.length>255)throw new N(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let _ of u){if(!le(_))throw new N(`questions[${e}] choices must be JSON objects`);let b=_.value;if(typeof b!="string"&&typeof b!="boolean")throw new N(`questions[${e}] choice value must be a string or boolean`);let v=String(b);if(c.has(v))throw new N(`questions[${e}] has duplicate choice value ${JSON.stringify(v)} (choices must be unique)`);c.add(v);let R=_.description;if(R!==void 0&&typeof R!="string")throw new N(`questions[${e}] choice description must be a string`);d.push(b),p.push(R)}let h=u.map((_,b)=>({name:String(d[b]),description:p[b]??String(d[b])}));return{entry:{kind:"choice",prompt:l,options:h},spec:{type:o,key:a,name:i,choiceValues:d}}}case"score":{let u=t.levels;if(!Array.isArray(u)||u.length<2||u.length>10)throw new N(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let h of u){if(!le(h)||typeof h.label!="string")throw new N(`questions[${e}] score levels must carry a string label`);if(d.includes(h.label))throw new N(`questions[${e}] has duplicate level label ${JSON.stringify(h.label)}`);d.push(h.label);let m=h.description;if(m!==void 0&&typeof m!="string")throw new N(`questions[${e}] score level description must be a string`);let _=m!==void 0?`${h.label}: ${m}`:h.label;if(c.includes(_))throw new N(`questions[${e}] has duplicate score criterion ${JSON.stringify(_)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(_)}return{entry:{kind:"score",prompt:l,criteria:c},spec:{type:o,key:a,name:i,levelLabels:d,scoreCriteria:c}}}}}function _c(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new N(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!le(s))throw new N(`questions[${e}] instruction parts must be JSON objects`);switch(At(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new N(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new N(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(oa(s));break}case"input_json":{let i=s.data;if(!le(i)&&!(Array.isArray(i)&&i.every(le)))throw new N(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new N(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
27
27
 
28
- `)}function ra(t,e){if(!ae(e))throw new ke("decision answer was not a JSON object");let n=e.choices;if(!ae(n))throw new ke("decision answer carried no choices object");let r=[];for(let o of t){let s=n[o.key];if(!ae(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=ae(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let a=tr(i.yes),l=tr(i.no),u=a??(l!==null?1-l:null);if(u===null)throw new ke(`the predicate answer for "${o.key}" carries neither a yes nor a no probability to translate`);r.push({type:"predicate",name:o.name,probability:u});continue}case"choice":{let a=o.choiceValues??[],l=s.choice;if(typeof l!="string")throw new ke(`the choice answer for "${o.key}" carries no string choice`);let u=a.findIndex(p=>String(p)===l);if(u===-1)throw new ke(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(l)})`);let d=nr(s.confidence);if(d===null)throw new ke(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let m=tr(i[String(p)]);m!==null&&c.push({value:p,probability:m})}r.push({type:"choice",name:o.name,choice:a[u],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],l=o.scoreCriteria??[],u=nr(s.score);if(u===null)throw new ke(`the score answer for "${o.key}" carries no numeric score to translate`);let d=nr(s.confidence);if(d===null)throw new ke(`the score answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p=0;p<a.length;p++){let m=tr(i[l[p]]);m!==null&&c.push({value:p,label:a[p],probability:m})}r.push({type:"score",name:o.name,score:u,confidence:d,probabilities:c});continue}}}return r}var le=class extends Error{};async function rr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new le(`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 le(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function or(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 le(`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[u,d]of Object.entries(t.headers))if(typeof d=="string")i.set(u,d);else if(Array.isArray(d))for(let c of d)i.append(u,c);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 le?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var oa="/v1/images/generations",sr="/v1/images/edits";function sa(t){return t===oa||t===sr}var ia="/v1/images/models";async function aa(t,e,n){if(t){if(t.model=fe({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 H=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},fc=16*1024*1024,la=64*1024*1024;function ua(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 gn(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 da(t,e,n,r,o,s){let i=s??(h=>console.error(h)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),l=null;for await(let h of a){if(h.type==="error"){let v=h.error??{},S=typeof v.message=="string"&&v.message.length>0&&Oe(v.message)?v.message:null;throw S===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(h)}`),new H(502,"the image upstream failed while serving this request")):new H(502,`image upstream error: ${S}`)}if(h.type==="response.completed"){l=h.response??null;break}}if(l===null)throw new H(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Ue(l));let u=l.images;if(!Array.isArray(u)||u.length!==1||typeof u[0]!="string"||u[0].length===0)throw new H(502,`image upstream returned ${Array.isArray(u)?u.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 d=[],c=u[0].startsWith("data:")?u[0].slice(u[0].indexOf(";base64,")+8):u[0],p=Buffer.from(c,"base64");if(ua(p)===null)throw new H(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function ca(t,e){if(t instanceof H)return t;if(t instanceof Se)throw t;return t instanceof B?new H(404,t.message):new H(502,kt("image",t,e))}async function pa(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 gn(r,new H(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 fa(t,e){t&&(t.outputUnits=e.images.length)}function ma(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 mc={model:!0,prompt:!0,response_format:!0,n:!0};async function ga(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??la;try{if(t.method!=="POST")throw new H(405,`${String(t.method)} is not supported on ${oa}`);let s;try{s=JSON.parse((await rr(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof le?new H(413,p.message):new H(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new H(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!mc[p])throw new H(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 a=i.prompt;if(typeof a!="string"||a.trim().length===0)throw new H(400,"prompt is required and must be a non-empty string","prompt");let l=i.model===void 0?void 0:i.model;if(l!==void 0&&typeof l!="string")throw new H(400,"model must be a string","model");await aa(n.turn,n.clients,l);let u=i.n??1;if(u!==1)throw new H(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=i.response_format??"b64_json";if(d!=="b64_json")throw new H(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",a.length,a.length),!await pa(n.imageModels,l,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await da(n.clients,l,c,n.turn?ve(n.turn):void 0,n.turn,r);fa(n.turn,p),ma(e,p)}catch(p){throw ca(p,r)}}catch(s){if(s instanceof le){gn(e,new H(413,s.message));return}if(s instanceof H){gn(e,s);return}throw s}}var gc={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function ha(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??la,s=n.maxImagePartBytes??fc;try{if(t.method!=="POST")throw new H(405,`${String(t.method)} is not supported on ${sr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new H(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await or(t,o)}catch(h){throw h instanceof le?new H(413,h.message):new H(400,String(h instanceof Error?h.message:h))}let l=a.get("prompt");if(typeof l!="string"||l.trim().length===0)throw new H(400,"prompt is required and must be a non-empty string field","prompt");let u=a.get("model");if(u!==null&&typeof u!="string")throw new H(400,"model must be a string field","model");let d=u===null?void 0:u;await aa(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new H(400,`response_format ${JSON.stringify(c)} 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 a.keys())if(!gc[h])throw new H(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 p=[];for(let h of["image","image[]"])for(let v of a.getAll(h)){if(!(v instanceof File))throw new H(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",h);if(v.size>s)throw new H(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,h);let S=new Uint8Array(await v.arrayBuffer()),w=ua(S);if(w===null)throw new H(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",h);p.push({bytes:S,mime:w})}if(p.length===0)throw new H(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",l.length,l.length),!await pa(n.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:l}];for(let{bytes:h,mime:v}of p)m.push({type:"input_image",image_url:`data:${v};base64,${Buffer.from(h).toString("base64")}`});try{let h=await da(n.clients,d,m,n.turn?ve(n.turn):void 0,n.turn,r);fa(n.turn,h),ma(e,h)}catch(h){throw ca(h,r)}}catch(i){if(i instanceof le){gn(e,new H(413,i.message));return}if(i instanceof H){gn(e,i);return}throw i}}var hn="/v1/audio/speech";function Ea(t){return t===hn}var ya=4096,wa=18e4,_a=5e3,hc=64*1024*1024,va=8,ba=5,Sa=1024*1024,At="voice_applied",ar="X-Urun-Voice-Applied",U=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Eo(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 lr=class extends U{constructor(e){super(502,e)}};function xa(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Aa(t){return new U(502,`the runtime's ${At} receipt ${JSON.stringify(t)} cannot be relayed as the ${ar} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function yc(t,e,n){if(t){if(t.model=fe({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 Ia(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var wc=2;function _c(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>wc)return!1;return!0}function vc(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 ka=new WeakMap,ir=new WeakMap;function bc(t,e){let n=ir.get(t)??0;if(n>=va)throw new U(503,`this model's speech queue is full \u2014 ${va} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${ba}s`,void 0,ba);ir.set(t,n+1);let r=ka.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return ka.set(t,s),(async()=>{await r;try{return await e()}finally{ir.set(t,(ir.get(t)??1)-1),o()}})()}async function Sc(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new U(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 F))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 it(t,e){if(t instanceof U)return t;if(t instanceof Se)throw t;return t instanceof B?new U(404,t.message):new U(502,kt("speech",t,e))}async function Ra(t,e,n,r,o,s,i,a,l,u){let d=u??(p=>console.error(p)),c=a??(()=>{});return bc(e,async()=>{if(i?.()===!0)return null;let p=!1,m=!1,h=!1,v,S=new Promise(b=>{v=b}),w=[],f=()=>{m&&!h&&w.length>=o.quietRunFrames&&(h=!0,v())},g=e.onOutputAudio(b=>{let R=Buffer.from(b,"base64");if(R.byteLength===0)return;let k=_c(R);if(!p){if(k)return;p=!0}if(k){w.push(R),f();return}for(let E of w)c(E);w.length=0,c(R),f()}),y=null,_,I,A;try{A=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let R=new Promise(x=>{I=setTimeout(x,s.capMs)}),k=!1;for(;;){let x=A.next(),T=await Promise.race([x,R]);if(T===void 0){k=!0,x.catch(()=>{});break}if(T.done)break;let $=T.value;if($.type==="error"){let D=$.error??{};await A.return?.();let q=typeof D.message=="string"&&D.message.length>0&&Oe(D.message)?D.message:null;throw q===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify($)}`),new U(502,"the speech upstream failed while serving this request")):new U(502,`speech upstream error: ${q}`)}if($.type==="response.completed"){y=$.response??null,m=!0,l?.(y),f(),await A.return?.();break}}if(clearTimeout(I),k)throw new U(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(y===null)throw new U(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let E=!1;if(await Promise.race([S,new Promise(x=>{_=setTimeout(()=>{E=!0,x()},o.capMs)})]),_!==void 0&&clearTimeout(_),r.voice!==void 0){let x=y[At];if(typeof x!="string"||x!==r.voice){let T=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof x=="string"?`${At} ${JSON.stringify(x)}`:`no ${At} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw h?new lr(T):new U(502,T)}}if(!p)throw new U(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(E&&!h&&w.length<1)throw new U(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return y}catch(b){throw b instanceof lr||await Sc(t,n,A,s.returnBoundMs),b}finally{_!==void 0&&clearTimeout(_),I!==void 0&&clearTimeout(I),g()}})}function kc(t,e,n,r){let o=!1,s=0,i=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",ar)),t.write(a,l=>{l||(s+=a.byteLength,Ia(e,s))}),t.writableLength>Sa&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Sa} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let l=a[At];if(typeof l=="string"){if(!xa(l))throw Aa(l);t.addTrailers({[ar]:l})}}await new Promise(l=>{t.end(()=>l())})}},fail:i}}async function Rc(t,e,n,r){let o;try{o=await t(e)}catch(s){throw it(s,r)}return o?!0:(Eo(n,new U(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 Ec={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},xc="wav, pcm";async function Oa(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??hc,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new U(405,`${String(t.method)} is not supported on ${hn}`);let a;try{a=JSON.parse((await rr(t,o)).toString("utf8")||"{}")}catch(y){throw y instanceof le?new U(413,y.message):new U(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new U(400,"request body must be a JSON object");let l=a;for(let y of Object.keys(l))if(!Ec[y])throw new U(400,`request field "${y}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,y);let u=l.input;if(typeof u!="string"||u.trim().length===0)throw new U(400,"input is required and must be a non-empty string","input");if(u.length>ya)throw new U(400,`input is ${u.length} chars \u2014 over the ${ya}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=l.model===void 0?void 0:l.model;if(d!==void 0&&typeof d!="string")throw new U(400,"model must be a string","model");let c=l.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new U(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new U(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 ${hn} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(y){throw it(y,r)}if(p.defect!==null)throw new U(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 m=typeof c=="string"?c:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new U(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let h=l.response_format??"wav";if(h!=="wav"&&h!=="pcm")throw new U(400,`response_format ${JSON.stringify(h)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${xc} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(l.stream_format!==void 0&&typeof l.stream_format!="string")throw new U(400,"stream_format, when present, must be a string","stream_format");let v=l.speed;if(v!==void 0){if(typeof v!="number"||!Number.isFinite(v))throw new U(400,"speed, when present, must be a number","speed");if(v!==1)throw new U(400,`speed=${JSON.stringify(v)} 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=l.instructions;if(S!==void 0){if(typeof S!="string")throw new U(400,"instructions, when present, must be a string","instructions");if(S.trim().length>0)throw new U(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 yc(n.turn,n.clients,d);let w=Buffer.byteLength(JSON.stringify(l));if(n.stats?.request("audio_speech",w,w),!await Rc(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new U(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 U(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 U(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let f;try{f=await n.clients.speechSessionHandle(d)}catch(y){throw it(y,r)}let g;try{g=await n.clients.openAudioOn(f)}catch(y){throw it(y,r)}n.turn&&(n.turn.sessionId=g.sessionId);try{if(h==="wav"){let y=[],_=await Ra(n.clients,g,f,{model:d,text:u,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??wa,returnBoundMs:n.turnReturnBoundMs??_a},i,A=>y.push(A),A=>{n.turn&&(n.turn.outputSeconds=Ue(A))},r);if(_===null||i())return;let I=Buffer.concat(y);if(m===void 0){let A=_[At];if(typeof A=="string"){if(!xa(A))throw Aa(A);e.setHeader(ar,A)}}Ia(n.turn,I.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([vc(I.byteLength),I]))}else{let y=kc(e,n.turn,i,m===void 0),_;try{_=await Ra(n.clients,g,f,{model:d,text:u,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??wa,returnBoundMs:n.turnReturnBoundMs??_a},i,y.sink,I=>{n.turn&&(n.turn.outputSeconds=Ue(I))},r)}catch(I){let A=it(I,r);if(!y.started())throw A;n.turn&&(n.turn.streamError=!0),y.fail(A);return}if(_===null)return;try{await y.finish(_)}catch(I){let A=it(I,r);n.turn&&(n.turn.streamError=!0),y.fail(A);return}}}catch(y){throw it(y,r)}}catch(a){if(a instanceof le){Eo(e,new U(413,a.message));return}if(a instanceof U){Eo(e,a);return}throw a}}var ur="/v1/audio/transcriptions";function Ta(t){return t===ur}var Pa="/v1/audio/models",Ac=16*1024*1024,Ic=64*1024*1024,X=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function xo(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 Ca(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 Oc(t){if(!Ca(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 l=t[a+2]|t[a+3]<<8,u=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:u,channels:l,bitsPerSample:d}}else if(s==="data"){let l=t.length-a;r=Math.min(i===0||i===4294967295?l:i,l)}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 Tc(t,e,n){if(t){if(t.model=fe({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 Pc(t,e){t&&(t.outputUnits=e.seconds)}async function Cc(t,e,n,r,o,s,i){let a=i??(c=>console.error(c)),l=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),u=[],d=null;for await(let c of l){if(u.push(c),c.type==="error"){let p=c.error??{},m=typeof p.type=="string"?p.type:"upstream_error",h=typeof p.message=="string"&&p.message.length>0&&Oe(p.message)?p.message:null;throw h===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new X(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new X(m==="invalid_request_error"?400:502,`transcription upstream error: ${h}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new X(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=Ue(d)),bt(u,d)}function La(t,e){if(t instanceof X)return t;if(t instanceof Se)throw t;return t instanceof B?new X(404,t.message):new X(502,kt("transcription",t,e))}async function Lc(t,e,n,r){let o;try{o=await t(e)}catch(s){throw La(s,r)}return o?!0:(xo(n,new X(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 $c=new Set(["file","model","language","response_format"]);async function $a(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Ic,s=n.maxAudioPartBytes??Ac;try{if(t.method!=="POST")throw new X(405,`${String(t.method)} is not supported on ${ur}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new X(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await or(t,o)}catch(f){throw f instanceof le?new X(413,f.message):new X(400,String(f instanceof Error?f.message:f))}let l=new Map;for(let f of a.keys()){if(!$c.has(f))throw new X(400,`form field "${f}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,f);l.set(f,(l.get(f)??0)+1)}for(let[f,g]of l)if(g>1)throw new X(400,`form field "${f}" appears ${g} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,f);let u=a.get("model");if(u!==null&&typeof u!="string")throw new X(400,"model must be a string field","model");let d=u===null?void 0:u,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new X(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,m=a.get("response_format")??"json";if(m!=="json")throw new X(400,`response_format ${JSON.stringify(m)} 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 h=a.get("file");if(!(h instanceof File))throw new X(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(h.size>s)throw new X(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let v=new Uint8Array(await h.arrayBuffer());if(!Ca(v))throw new X(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 S=Oc(v);if(S===null)throw new X(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 Tc(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",v.length,v.length),!await Lc(n.transcriptionModels,d,e,r))return;let w=[{type:"input_audio",input_audio:{data:Buffer.from(v).toString("base64"),format:"wav"}}];try{let f=await Cc(n.clients,d,w,p,n.turn?ve(n.turn):void 0,n.turn,r);Pc(n.turn,S),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:f}))}catch(f){throw La(f,r)}}catch(i){if(i instanceof le){xo(e,new X(413,i.message));return}if(i instanceof X){xo(e,i);return}throw i}}var cr="/v1/usage/requests",Ma=1e4,Mc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ve=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},te=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},dr=class extends te{constructor(e){super(e),this.name="UsageWithholdingError"}},Fa=1024*1024;function Oo(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Ve(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Ve(`"${e}" must be an array of uuid strings`);if(n.length>Ma)throw new Ve(`"${e}" carries ${n.length} ids; at most ${Ma} 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"||!Mc.test(s))throw new Ve(`"${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 Ha(t){return Oo(t,"inference_ids")}var Nc=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function It(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new te(`${n}: ${e} is not a non-empty string (got ${Tt(r)})`);return r}function Ao(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new te(`${n}: ${e} is neither null nor a non-empty string (got ${Tt(r)})`);return r}function Ot(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 te(`${n}: ${e} is not a number (got ${Tt(o)})`);if(r&&!Number.isSafeInteger(s))throw new te(`${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 te(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Uc=40,Na=64,Ua=600;function Ba(t){let e=Object.keys(t).sort(),r=e.slice(0,Uc).map(o=>o.length>Na?`${o.slice(0,Na)}\u2026`:o).join(", ");return r.length>Ua&&(r=`${r.slice(0,Ua)}\u2026`),`${e.length} keys present: [${r}]`}function Tt(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function Io(t){Je(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
29
- `)}function Dc(t,e){let n;try{n=t(e)}catch{Da(t,e);return}Fc(n)&&Promise.resolve(n).catch(()=>{Da(t,e)})}function Fc(t){return typeof t?.then=="function"}function Da(t,e){if(t!==Io)try{Io(e)}catch{}}function ja(t,e=Io){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?Ba(t):Tt(t);throw new te(`the usage surface answered without a "requests" array: got ${Tt(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Hc(n[o],s))}catch(i){if(i instanceof dr||!(i instanceof te))throw i;Dc(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new te(`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 Hc(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new te(`${e} is not an object: got ${Tt(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new dr(`${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 Nc)if(!Object.hasOwn(n,o))throw new te(`${e} has no "${o}" column (${Ba(n)})`);let r=Ot(n,"http_status",e,!0);if(r===null)throw new te(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:It(n,"inference_id",e),model_id:It(n,"model_id",e),identity_kind:It(n,"identity_kind",e),variant:Ao(n,"variant",e),task:It(n,"task",e),http_status:r,started_at:It(n,"started_at",e),completed_at:It(n,"completed_at",e),prompt_tokens:Ot(n,"prompt_tokens",e,!0),completion_tokens:Ot(n,"completion_tokens",e,!0),output_units:Ot(n,"output_units",e,!1),output_minutes:Ot(n,"output_minutes",e,!1),cost_nano_usd:Ot(n,"cost_nano_usd",e,!0),price_version:Ao(n,"price_version",e),priced_at:Ao(n,"priced_at",e)}}function pr(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 te(`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 te(`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 hr=require("@urun-sh/core");var yn="/partners/huggingface/v1/billing/requests";function Bc(t){return Oo(t,"requestIds")}function jc(t){return t>=200&&t<=399}function qc(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&jc(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function qa(t,e){let n=Bc(t),r=await e(n);return pr(r,n),qc(r)}var Gc={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"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 Wc(t){return Gc[t]??null}var Va=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Jc(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Vc(t){return t==="surface"}function Kc(t){let e=t?.ledgerFailureReason;return Va.includes(e)?e:"unknown"}var zc=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Ga=["priced","unpriced"],Yc={written:Ga,already_written:Ga,skipped:zc,failed:Va},Ka=Object.entries(Yc).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Xc(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Qc(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 Zc=256,Wa=4096,_n=12e4,ep=250,tp=8e3,at=[],Ja=new Set,vn=0,wn=!1;function za(){return at.length}function Ya(t=Date.now()){let e=at[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var np=new Set;function rp(){return vn===0&&at.length===0}function op(){if(rp()){wn=!1;for(let t of[...np])t()}}function Xa(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
30
- `}function sp(t){Je(process.stdout,t)}function Qa(t,e){try{t(e)}catch{}}function Za(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??sp,o=Wc(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),Qa(r,Xa("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};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 l;if(a.kind==="catalog")l={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}l={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let u={inference_id:e.inference_id,...l,task:o,http_status:e.status,started_at:Qc(e),completed_at:e.ts,billable_outcome:Xc(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,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(at.length>=Wa){i("queue_full",`${at.length} ledger writes are already waiting (capacity ${Wa}, ${vn} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}at.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),vn<Zc&&(vn+=1,ip())}async function ip(){try{for(;;){let t=ap();if(t===void 0)return;Ja.add(t);try{await lp(t)}finally{Ja.delete(t)}}}finally{vn-=1,op()}}function ap(){let t=Date.now();for(;;){let e=at.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<_n)return e;Pt(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 ${_n}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 lp(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Pt(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=Jc(o);if(s!==null){Pt(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=Kc(o),a=Date.now()-t.queuedAt;if(wn){Pt(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(Vc(i)&&a<_n){if(await dp(up(t.attempts)),wn||Date.now()-t.queuedAt>=_n){let l=Date.now()-t.queuedAt;Pt(t,{outcome:"failed",reason:wn?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:wn?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:l,error:`this row's backoff outlived the ${_n}ms dwell bound (waited ${l}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}Pt(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 up(t){return Math.min(tp,ep*2**Math.max(0,t-1))}function dp(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Pt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Qa(t.report,Xa(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var Po="x-urun-profile",bn="voice";var ge=class extends Error{status=400},cp=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,pp=/\s/;function fp(t){return cp.test(t)}function To(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ge(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function el(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new ge(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new ge(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new ge(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function tl(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new ge(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let u=n.trim();if(u==="")throw new ge(`the ${Po} header is empty \u2014 the only profile this lane accepts is "${bn}" (omit the header for the ordinary lane)`);if(u!==bn)throw new ge(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${bn}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==bn)throw new ge(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${bn}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new ge("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new ge("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let l=a??{};return{flushMaxChars:el(l,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:el(l,"flush_max_ms",250,{max:2147483647}),sentenceFlush:To(l,"sentence_flush",!0),includeReasoning:To(l,"include_reasoning",!1),metadata:To(l,"metadata",!1)}}var Ct=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&fp(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(pp.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function $o(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function gp(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function ue(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function W(t,e,n,r="invalid_request_error",o){ue(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Mo(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=$e(r),a=i??Te(n?.inferenceId??null);i===null&&s(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let l=r?.code??null,u=o==="invalid_request_error"?400:l==="queue_timeout"?429:502;u===429&&t.setHeader("retry-after","30"),ue(t,u,{error:{message:a,type:o,code:l}})}function Pe(t,e,n,r){ue(t,e,{type:"error",error:{type:n,message:r}})}function Lt(t,e,n){if(e==="anthropic"){ue(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ue(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var hp=64*1024*1024,Sn=class extends Error{};async function nl(t,e=hp){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Sn(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function lt(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 ol(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:null,o=r(n.input_tokens),s=r(n.output_tokens),i=l=>l??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let l={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:l}:{kind:"counts",usage:l}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function fr(t){let e=ol(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function rl(t){let e=fr(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:yp(t)},completion_tokens_details:{reasoning_tokens:0}}}function yp(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function wp(t,e){let n=ol(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function _p(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=l=>{let u=n[l];return typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u: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 vp(t,e){let n=_p(e);n&&(t.timing=n),t.outputSeconds=Ue(e)}function ut(t,e){wp(t,e),vp(t,e)}async function yr(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 sl(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 bp(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 mr=class extends Error{};function Sp(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 mr(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function kp(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:Sp(n.role,n.content)})}return e}function Co(t){return _t(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 Rp(t,e,n,r,o,s,i){let a=an(s.id),l=t.stream===!0;if(s.model=fe(t),s.stream=l,await yr(s,e,typeof t.model=="string"?t.model:void 0),l){let f;try{f=await un({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(g){if(g instanceof B){Lt(r,"openai",g);return}if(g instanceof be){W(r,g.status,g.message);return}if(g instanceof xe||g instanceof se){r.setHeader("retry-after","2"),W(r,503,g.message,"capacity_error");return}throw g}$o(r);for await(let g of f.events){if(g.type==="error"){s.streamError=!0;let y=g.error,_=$e(y),I=_??Te(s.id);_===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(g)}`),r.write(`event: error
31
- data: ${JSON.stringify({error:{message:I,type:y?.type??"upstream_error",code:y?.code??null}})}
28
+ `)}function sa(t,e){if(!le(e))throw new Re("decision answer was not a JSON object");let n=e.choices;if(!le(n))throw new Re("decision answer carried no choices object");let r=[];for(let o of t){let s=n[o.key];if(!le(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=le(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let a=rr(i.yes),l=rr(i.no),u=a??(l!==null?1-l:null);if(u===null)throw new Re(`the predicate answer for "${o.key}" carries neither a yes nor a no probability to translate`);r.push({type:"predicate",name:o.name,probability:u});continue}case"choice":{let a=o.choiceValues??[],l=s.choice;if(typeof l!="string")throw new Re(`the choice answer for "${o.key}" carries no string choice`);let u=a.findIndex(p=>String(p)===l);if(u===-1)throw new Re(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(l)})`);let d=or(s.confidence);if(d===null)throw new Re(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let h=rr(i[String(p)]);h!==null&&c.push({value:p,probability:h})}r.push({type:"choice",name:o.name,choice:a[u],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],l=o.scoreCriteria??[],u=or(s.score);if(u===null)throw new Re(`the score answer for "${o.key}" carries no numeric score to translate`);let d=or(s.confidence);if(d===null)throw new Re(`the score answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p=0;p<a.length;p++){let h=rr(i[l[p]]);h!==null&&c.push({value:p,label:a[p],probability:h})}r.push({type:"score",name:o.name,score:u,confidence:d,probabilities:c});continue}}}return r}var ue=class extends Error{};async function sr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ue(`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 ue(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function ir(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 ue(`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[u,d]of Object.entries(t.headers))if(typeof d=="string")i.set(u,d);else if(Array.isArray(d))for(let c of d)i.append(u,c);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 ue?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var ia="/v1/images/generations",ar="/v1/images/edits";function aa(t){return t===ia||t===ar}var la="/v1/images/models";async function ua(t,e,n){if(t){if(t.model=fe({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 B=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},vc=16*1024*1024,da=64*1024*1024;function ca(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 wn(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 pa(t,e,n,r,o,s){let i=s??(m=>console.error(m)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),l=null;for await(let m of a){if(m.type==="error"){let _=m.error??{},b=typeof _.message=="string"&&_.message.length>0&&Te(_.message)?_.message:null;throw b===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(m)}`),new B(502,"the image upstream failed while serving this request")):new B(502,`image upstream error: ${b}`)}if(m.type==="response.completed"){l=m.response??null;break}}if(l===null)throw new B(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Ue(l));let u=l.images;if(!Array.isArray(u)||u.length!==1||typeof u[0]!="string"||u[0].length===0)throw new B(502,`image upstream returned ${Array.isArray(u)?u.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 d=[],c=u[0].startsWith("data:")?u[0].slice(u[0].indexOf(";base64,")+8):u[0],p=Buffer.from(c,"base64");if(ca(p)===null)throw new B(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function fa(t,e){if(t instanceof B)return t;if(t instanceof ke)throw t;return t instanceof j?new B(404,t.message):new B(502,Et("image",t,e))}async function ma(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 wn(r,new B(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 ga(t,e){t&&(t.outputUnits=e.images.length)}function ha(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 bc={model:!0,prompt:!0,response_format:!0,n:!0};async function ya(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??da;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${ia}`);let s;try{s=JSON.parse((await sr(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof ue?new B(413,p.message):new B(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new B(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!bc[p])throw new B(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 a=i.prompt;if(typeof a!="string"||a.trim().length===0)throw new B(400,"prompt is required and must be a non-empty string","prompt");let l=i.model===void 0?void 0:i.model;if(l!==void 0&&typeof l!="string")throw new B(400,"model must be a string","model");await ua(n.turn,n.clients,l);let u=i.n??1;if(u!==1)throw new B(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=i.response_format??"b64_json";if(d!=="b64_json")throw new B(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",a.length,a.length),!await ma(n.imageModels,l,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await pa(n.clients,l,c,n.turn?be(n.turn):void 0,n.turn,r);ga(n.turn,p),ha(e,p)}catch(p){throw fa(p,r)}}catch(s){if(s instanceof ue){wn(e,new B(413,s.message));return}if(s instanceof B){wn(e,s);return}throw s}}var Sc={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function wa(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??da,s=n.maxImagePartBytes??vc;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${ar}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new B(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await ir(t,o)}catch(m){throw m instanceof ue?new B(413,m.message):new B(400,String(m instanceof Error?m.message:m))}let l=a.get("prompt");if(typeof l!="string"||l.trim().length===0)throw new B(400,"prompt is required and must be a non-empty string field","prompt");let u=a.get("model");if(u!==null&&typeof u!="string")throw new B(400,"model must be a string field","model");let d=u===null?void 0:u;await ua(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new B(400,`response_format ${JSON.stringify(c)} 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 m of a.keys())if(!Sc[m])throw new B(400,`form field "${m}" 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[]).`,m);let p=[];for(let m of["image","image[]"])for(let _ of a.getAll(m)){if(!(_ instanceof File))throw new B(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(_.size>s)throw new B(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let b=new Uint8Array(await _.arrayBuffer()),v=ca(b);if(v===null)throw new B(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);p.push({bytes:b,mime:v})}if(p.length===0)throw new B(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",l.length,l.length),!await ma(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:l}];for(let{bytes:m,mime:_}of p)h.push({type:"input_image",image_url:`data:${_};base64,${Buffer.from(m).toString("base64")}`});try{let m=await pa(n.clients,d,h,n.turn?be(n.turn):void 0,n.turn,r);ga(n.turn,m),ha(e,m)}catch(m){throw fa(m,r)}}catch(i){if(i instanceof ue){wn(e,new B(413,i.message));return}if(i instanceof B){wn(e,i);return}throw i}}var _n="/v1/audio/speech";function Aa(t){return t===_n}var _a=4096,va=18e4,ba=5e3,kc=64*1024*1024,Sa=8,ka=5,Ra=1024*1024,It="voice_applied",ur="X-Urun-Voice-Applied",D=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Io(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 dr=class extends D{constructor(e){super(502,e)}};function Ia(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Oa(t){return new D(502,`the runtime's ${It} receipt ${JSON.stringify(t)} cannot be relayed as the ${ur} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function Rc(t,e,n){if(t){if(t.model=fe({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 Ta(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Ec=2;function xc(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Ec)return!1;return!0}function Ac(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 Ea=new WeakMap,lr=new WeakMap;function Ic(t,e){let n=lr.get(t)??0;if(n>=Sa)throw new D(503,`this model's speech queue is full \u2014 ${Sa} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${ka}s`,void 0,ka);lr.set(t,n+1);let r=Ea.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Ea.set(t,s),(async()=>{await r;try{return await e()}finally{lr.set(t,(lr.get(t)??1)-1),o()}})()}async function Oc(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new D(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 F))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 at(t,e){if(t instanceof D)return t;if(t instanceof ke)throw t;return t instanceof j?new D(404,t.message):new D(502,Et("speech",t,e))}async function xa(t,e,n,r,o,s,i,a,l,u){let d=u??(p=>console.error(p)),c=a??(()=>{});return Ic(e,async()=>{if(i?.()===!0)return null;let p=!1,h=!1,m=!1,_,b=new Promise(w=>{_=w}),v=[],R=()=>{h&&!m&&v.length>=o.quietRunFrames&&(m=!0,_())},f=e.onOutputAudio(w=>{let E=Buffer.from(w,"base64");if(E.byteLength===0)return;let k=xc(E);if(!p){if(k)return;p=!0}if(k){v.push(E),R();return}for(let I of v)c(I);v.length=0,c(E),R()}),g=null,y,S,A;try{A=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let E=new Promise(x=>{S=setTimeout(x,s.capMs)}),k=!1;for(;;){let x=A.next(),O=await Promise.race([x,E]);if(O===void 0){k=!0,x.catch(()=>{});break}if(O.done)break;let $=O.value;if($.type==="error"){let M=$.error??{};await A.return?.();let q=typeof M.message=="string"&&M.message.length>0&&Te(M.message)?M.message:null;throw q===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify($)}`),new D(502,"the speech upstream failed while serving this request")):new D(502,`speech upstream error: ${q}`)}if($.type==="response.completed"){g=$.response??null,h=!0,l?.(g),R(),await A.return?.();break}}if(clearTimeout(S),k)throw new D(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(g===null)throw new D(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let I=!1;if(await Promise.race([b,new Promise(x=>{y=setTimeout(()=>{I=!0,x()},o.capMs)})]),y!==void 0&&clearTimeout(y),r.voice!==void 0){let x=g[It];if(typeof x!="string"||x!==r.voice){let O=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof x=="string"?`${It} ${JSON.stringify(x)}`:`no ${It} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw m?new dr(O):new D(502,O)}}if(!p)throw new D(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(I&&!m&&v.length<1)throw new D(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return g}catch(w){throw w instanceof dr||await Oc(t,n,A,s.returnBoundMs),w}finally{y!==void 0&&clearTimeout(y),S!==void 0&&clearTimeout(S),f()}})}function Tc(t,e,n,r){let o=!1,s=0,i=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",ur)),t.write(a,l=>{l||(s+=a.byteLength,Ta(e,s))}),t.writableLength>Ra&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Ra} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let l=a[It];if(typeof l=="string"){if(!Ia(l))throw Oa(l);t.addTrailers({[ur]:l})}}await new Promise(l=>{t.end(()=>l())})}},fail:i}}async function Pc(t,e,n,r){let o;try{o=await t(e)}catch(s){throw at(s,r)}return o?!0:(Io(n,new D(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 Cc={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Lc="wav, pcm";async function Pa(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??kc,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new D(405,`${String(t.method)} is not supported on ${_n}`);let a;try{a=JSON.parse((await sr(t,o)).toString("utf8")||"{}")}catch(g){throw g instanceof ue?new D(413,g.message):new D(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new D(400,"request body must be a JSON object");let l=a;for(let g of Object.keys(l))if(!Cc[g])throw new D(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=l.input;if(typeof u!="string"||u.trim().length===0)throw new D(400,"input is required and must be a non-empty string","input");if(u.length>_a)throw new D(400,`input is ${u.length} chars \u2014 over the ${_a}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=l.model===void 0?void 0:l.model;if(d!==void 0&&typeof d!="string")throw new D(400,"model must be a string","model");let c=l.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new D(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new D(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 ${_n} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(g){throw at(g,r)}if(p.defect!==null)throw new D(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 h=typeof c=="string"?c:void 0;if(h!==void 0&&p.published.length>0&&!p.published.includes(h))throw new D(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let m=l.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new D(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Lc} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(l.stream_format!==void 0&&typeof l.stream_format!="string")throw new D(400,"stream_format, when present, must be a string","stream_format");let _=l.speed;if(_!==void 0){if(typeof _!="number"||!Number.isFinite(_))throw new D(400,"speed, when present, must be a number","speed");if(_!==1)throw new D(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 b=l.instructions;if(b!==void 0){if(typeof b!="string")throw new D(400,"instructions, when present, must be a string","instructions");if(b.trim().length>0)throw new D(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 Rc(n.turn,n.clients,d);let v=Buffer.byteLength(JSON.stringify(l));if(n.stats?.request("audio_speech",v,v),!await Pc(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new D(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 D(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 D(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let R;try{R=await n.clients.speechSessionHandle(d)}catch(g){throw at(g,r)}let f;try{f=await n.clients.openAudioOn(R)}catch(g){throw at(g,r)}n.turn&&(n.turn.sessionId=f.sessionId);try{if(m==="wav"){let g=[],y=await xa(n.clients,f,R,{model:d,text:u,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??va,returnBoundMs:n.turnReturnBoundMs??ba},i,A=>g.push(A),A=>{n.turn&&(n.turn.outputSeconds=Ue(A))},r);if(y===null||i())return;let S=Buffer.concat(g);if(h===void 0){let A=y[It];if(typeof A=="string"){if(!Ia(A))throw Oa(A);e.setHeader(ur,A)}}Ta(n.turn,S.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Ac(S.byteLength),S]))}else{let g=Tc(e,n.turn,i,h===void 0),y;try{y=await xa(n.clients,f,R,{model:d,text:u,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??va,returnBoundMs:n.turnReturnBoundMs??ba},i,g.sink,S=>{n.turn&&(n.turn.outputSeconds=Ue(S))},r)}catch(S){let A=at(S,r);if(!g.started())throw A;n.turn&&(n.turn.streamError=!0),g.fail(A);return}if(y===null)return;try{await g.finish(y)}catch(S){let A=at(S,r);n.turn&&(n.turn.streamError=!0),g.fail(A);return}}}catch(g){throw at(g,r)}}catch(a){if(a instanceof ue){Io(e,new D(413,a.message));return}if(a instanceof D){Io(e,a);return}throw a}}var cr="/v1/audio/transcriptions";function Ca(t){return t===cr}var La="/v1/audio/models",$c=16*1024*1024,Mc=64*1024*1024,Q=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Oo(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 $a(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 Nc(t){if(!$a(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 l=t[a+2]|t[a+3]<<8,u=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:u,channels:l,bitsPerSample:d}}else if(s==="data"){let l=t.length-a;r=Math.min(i===0||i===4294967295?l:i,l)}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 Uc(t,e,n){if(t){if(t.model=fe({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 Dc(t,e){t&&(t.outputUnits=e.seconds)}async function Fc(t,e,n,r,o,s,i){let a=i??(c=>console.error(c)),l=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),u=[],d=null;for await(let c of l){if(u.push(c),c.type==="error"){let p=c.error??{},h=typeof p.type=="string"?p.type:"upstream_error",m=typeof p.message=="string"&&p.message.length>0&&Te(p.message)?p.message:null;throw m===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new Q(h==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new Q(h==="invalid_request_error"?400:502,`transcription upstream error: ${m}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new Q(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=Ue(d)),kt(u,d)}function Ma(t,e){if(t instanceof Q)return t;if(t instanceof ke)throw t;return t instanceof j?new Q(404,t.message):new Q(502,Et("transcription",t,e))}async function Hc(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Ma(s,r)}return o?!0:(Oo(n,new Q(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 Bc=new Set(["file","model","language","response_format"]);async function Na(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Mc,s=n.maxAudioPartBytes??$c;try{if(t.method!=="POST")throw new Q(405,`${String(t.method)} is not supported on ${cr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new Q(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await ir(t,o)}catch(R){throw R instanceof ue?new Q(413,R.message):new Q(400,String(R instanceof Error?R.message:R))}let l=new Map;for(let R of a.keys()){if(!Bc.has(R))throw new Q(400,`form field "${R}" 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.`,R);l.set(R,(l.get(R)??0)+1)}for(let[R,f]of l)if(f>1)throw new Q(400,`form field "${R}" appears ${f} 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`,R);let u=a.get("model");if(u!==null&&typeof u!="string")throw new Q(400,"model must be a string field","model");let d=u===null?void 0:u,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new Q(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,h=a.get("response_format")??"json";if(h!=="json")throw new Q(400,`response_format ${JSON.stringify(h)} 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 m=a.get("file");if(!(m instanceof File))throw new Q(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>s)throw new Q(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let _=new Uint8Array(await m.arrayBuffer());if(!$a(_))throw new Q(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 b=Nc(_);if(b===null)throw new Q(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 Uc(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",_.length,_.length),!await Hc(n.transcriptionModels,d,e,r))return;let v=[{type:"input_audio",input_audio:{data:Buffer.from(_).toString("base64"),format:"wav"}}];try{let R=await Fc(n.clients,d,v,p,n.turn?be(n.turn):void 0,n.turn,r);Dc(n.turn,b),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:R}))}catch(R){throw Ma(R,r)}}catch(i){if(i instanceof ue){Oo(e,new Q(413,i.message));return}if(i instanceof Q){Oo(e,i);return}throw i}}var fr="/v1/usage/requests",Ua=1e4,jc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Je=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},ne=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},pr=class extends ne{constructor(e){super(e),this.name="UsageWithholdingError"}},Ba=1024*1024;function Co(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Je(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Je(`"${e}" must be an array of uuid strings`);if(n.length>Ua)throw new Je(`"${e}" carries ${n.length} ids; at most ${Ua} 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"||!jc.test(s))throw new Je(`"${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 ja(t){return Co(t,"inference_ids")}var qc=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function Ot(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new ne(`${n}: ${e} is not a non-empty string (got ${Pt(r)})`);return r}function To(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new ne(`${n}: ${e} is neither null nor a non-empty string (got ${Pt(r)})`);return r}function Tt(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 ne(`${n}: ${e} is not a number (got ${Pt(o)})`);if(r&&!Number.isSafeInteger(s))throw new ne(`${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 ne(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Gc=40,Da=64,Fa=600;function qa(t){let e=Object.keys(t).sort(),r=e.slice(0,Gc).map(o=>o.length>Da?`${o.slice(0,Da)}\u2026`:o).join(", ");return r.length>Fa&&(r=`${r.slice(0,Fa)}\u2026`),`${e.length} keys present: [${r}]`}function Pt(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function Po(t){Ve(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
29
+ `)}function Wc(t,e){let n;try{n=t(e)}catch{Ha(t,e);return}Vc(n)&&Promise.resolve(n).catch(()=>{Ha(t,e)})}function Vc(t){return typeof t?.then=="function"}function Ha(t,e){if(t!==Po)try{Po(e)}catch{}}function Ga(t,e=Po){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?qa(t):Pt(t);throw new ne(`the usage surface answered without a "requests" array: got ${Pt(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Jc(n[o],s))}catch(i){if(i instanceof pr||!(i instanceof ne))throw i;Wc(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new ne(`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 Jc(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ne(`${e} is not an object: got ${Pt(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new pr(`${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 qc)if(!Object.hasOwn(n,o))throw new ne(`${e} has no "${o}" column (${qa(n)})`);let r=Tt(n,"http_status",e,!0);if(r===null)throw new ne(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Ot(n,"inference_id",e),model_id:Ot(n,"model_id",e),identity_kind:Ot(n,"identity_kind",e),variant:To(n,"variant",e),task:Ot(n,"task",e),http_status:r,started_at:Ot(n,"started_at",e),completed_at:Ot(n,"completed_at",e),prompt_tokens:Tt(n,"prompt_tokens",e,!0),completion_tokens:Tt(n,"completion_tokens",e,!0),output_units:Tt(n,"output_units",e,!1),output_minutes:Tt(n,"output_minutes",e,!1),cost_nano_usd:Tt(n,"cost_nano_usd",e,!0),price_version:To(n,"price_version",e),priced_at:To(n,"priced_at",e)}}function mr(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 ne(`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 ne(`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 wr=require("@urun-sh/core");var vn="/partners/huggingface/v1/billing/requests";function Kc(t){return Co(t,"requestIds")}function zc(t){return t>=200&&t<=399}function Yc(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&zc(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Wa(t,e){let n=Kc(t),r=await e(n);return mr(r,n),Yc(r)}var Xc={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"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 Qc(t){return Xc[t]??null}var za=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Zc(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function ep(t){return t==="surface"}function tp(t){let e=t?.ledgerFailureReason;return za.includes(e)?e:"unknown"}var np=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Va=["priced","unpriced"],rp={written:Va,already_written:Va,skipped:np,failed:za},Ya=Object.entries(rp).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function op(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function sp(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 ip=256,Ja=4096,Sn=12e4,ap=250,lp=8e3,lt=[],Ka=new Set,kn=0,bn=!1;function Xa(){return lt.length}function Qa(t=Date.now()){let e=lt[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var up=new Set;function dp(){return kn===0&&lt.length===0}function cp(){if(dp()){bn=!1;for(let t of[...up])t()}}function Za(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
30
+ `}function pp(t){Ve(process.stdout,t)}function el(t,e){try{t(e)}catch{}}function tl(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??pp,o=Qc(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),el(r,Za("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};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 l;if(a.kind==="catalog")l={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}l={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let u={inference_id:e.inference_id,...l,task:o,http_status:e.status,started_at:sp(e),completed_at:e.ts,billable_outcome:op(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,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(lt.length>=Ja){i("queue_full",`${lt.length} ledger writes are already waiting (capacity ${Ja}, ${kn} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}lt.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),kn<ip&&(kn+=1,fp())}async function fp(){try{for(;;){let t=mp();if(t===void 0)return;Ka.add(t);try{await gp(t)}finally{Ka.delete(t)}}}finally{kn-=1,cp()}}function mp(){let t=Date.now();for(;;){let e=lt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Sn)return e;Ct(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 ${Sn}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 gp(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Ct(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=Zc(o);if(s!==null){Ct(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=tp(o),a=Date.now()-t.queuedAt;if(bn){Ct(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(ep(i)&&a<Sn){if(await yp(hp(t.attempts)),bn||Date.now()-t.queuedAt>=Sn){let l=Date.now()-t.queuedAt;Ct(t,{outcome:"failed",reason:bn?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:bn?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:l,error:`this row's backoff outlived the ${Sn}ms dwell bound (waited ${l}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}Ct(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 hp(t){return Math.min(lp,ap*2**Math.max(0,t-1))}function yp(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Ct(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;el(t.report,Za(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var $o="x-urun-profile",Rn="voice";var ge=class extends Error{status=400},wp=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,_p=/\s/;function vp(t){return wp.test(t)}function Lo(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ge(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function nl(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new ge(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new ge(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new ge(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function rl(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new ge(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let u=n.trim();if(u==="")throw new ge(`the ${$o} header is empty \u2014 the only profile this lane accepts is "${Rn}" (omit the header for the ordinary lane)`);if(u!==Rn)throw new ge(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${Rn}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Rn)throw new ge(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Rn}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new ge("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new ge("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let l=a??{};return{flushMaxChars:nl(l,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:nl(l,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Lo(l,"sentence_flush",!0),includeReasoning:Lo(l,"include_reasoning",!1),metadata:Lo(l,"metadata",!1)}}var Lt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&vp(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(_p.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function Uo(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Sp(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function de(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){de(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Do(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=$e(r),a=i??Pe(n?.inferenceId??null);i===null&&s(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let l=r?.code??null,u=o==="invalid_request_error"?400:l==="queue_timeout"?429:502;u===429&&t.setHeader("retry-after","30"),de(t,u,{error:{message:a,type:o,code:l}})}function Ce(t,e,n,r){de(t,e,{type:"error",error:{type:n,message:r}})}function $t(t,e,n){if(e==="anthropic"){de(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}de(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var kp=64*1024*1024,En=class extends Error{};async function ol(t,e=kp){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new En(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function ut(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 il(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:null,o=r(n.input_tokens),s=r(n.output_tokens),i=l=>l??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let l={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:l}:{kind:"counts",usage:l}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function gr(t){let e=il(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function sl(t){let e=gr(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:Rp(t)},completion_tokens_details:{reasoning_tokens:0}}}function Rp(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function Ep(t,e){let n=il(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function xp(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=l=>{let u=n[l];return typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u: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 Ap(t,e){let n=xp(e);n&&(t.timing=n),t.outputSeconds=Ue(e)}function dt(t,e){Ep(t,e),Ap(t,e)}async function _r(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 al(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 Ip(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 hr=class extends Error{};function Op(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 hr(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Tp(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:Op(n.role,n.content)})}return e}function Mo(t){return bt(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 Pp(t,e,n,r,o,s,i){let a=dn(s.id),l=t.stream===!0;if(s.model=fe(t),s.stream=l,await _r(s,e,typeof t.model=="string"?t.model:void 0),l){let R;try{R=await pn({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(f){if(f instanceof j){$t(r,"openai",f);return}if(f instanceof Se){V(r,f.status,f.message);return}if(f instanceof Ae||f instanceof ae){r.setHeader("retry-after","2"),V(r,503,f.message,"capacity_error");return}throw f}Uo(r);for await(let f of R.events){if(f.type==="error"){s.streamError=!0;let g=f.error,y=$e(g),S=y??Pe(s.id);y===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(f)}`),r.write(`event: error
31
+ data: ${JSON.stringify({error:{message:S,type:g?.type??"upstream_error",code:g?.code??null}})}
32
32
 
33
- `),r.end();return}g.type==="response.completed"&&ut(s,g.response),r.write(`event: ${String(g.type??"message")}
34
- data: ${JSON.stringify(g)}
33
+ `),r.end();return}f.type==="response.completed"&&dt(s,f.response),r.write(`event: ${String(f.type??"message")}
34
+ data: ${JSON.stringify(f)}
35
35
 
36
36
  `)}r.write(`data: [DONE]
37
37
 
38
- `),r.end();return}let u;try{u=St(n,t)}catch(f){if(f instanceof be){W(r,f.status,f.message);return}throw f}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=fe(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await lo(e,t,u,!1,ve(s))}catch(f){if(f instanceof B){Lt(r,"openai",f);return}if(f instanceof be){W(r,f.status,f.message);return}if(f instanceof xe||f instanceof se){r.setHeader("retry-after","2"),W(r,503,f.message,"capacity_error");return}throw f}let h=[],v=null;for await(let f of o.track(m,c,s)){if(h.push(f),f.type==="error"){Mo(r,f,{inferenceId:s.id,operatorError:i});return}f.type==="response.completed"&&(v=f.response)}if(v==null){W(r,502,"upstream produced no response.completed event","upstream_error");return}ut(s,v);let S=bt(h,v),w=st(p,_t(v).length,S);if(w){W(r,502,ot(c,w),"upstream_error");return}d&&n.remember(a,u,ao(v,S),d),ue(r,200,{...v,id:a})}async function Ep(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){W(n,400,"chat/completions requires a messages array");return}let l;try{l=tl(s,t)}catch(k){if(k instanceof ge){W(n,k.status,k.message);return}throw k}let u=String(t.model??"urun"),d=Mi(o.id),c;try{c=kp(a)}catch(k){if(k instanceof mr){W(n,400,k.message);return}throw k}let p=fe(t);r.model(p),o.model=p,o.stream=t.stream===!0,await yr(o,e,typeof t.model=="string"?t.model:void 0);let m=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:c,stream:!0,tools:bp(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}:{}},ve(o))}catch(k){if(k instanceof B){Lt(n,"openai",k);return}if(k instanceof xe||k instanceof se){n.setHeader("retry-after","2"),W(n,503,k.message,"capacity_error");return}throw k}if(t.stream===!0){l?gp(n):$o(n);let k=[],E=new qe,x="",T=l?new Ct(l,D=>{n.write(`data: ${JSON.stringify(lt(d,u,{content:D},null))}
38
+ `),r.end();return}let u;try{u=Rt(n,t)}catch(R){if(R instanceof Se){V(r,R.status,R.message);return}throw R}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=fe(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await po(e,t,u,!1,be(s))}catch(R){if(R instanceof j){$t(r,"openai",R);return}if(R instanceof Se){V(r,R.status,R.message);return}if(R instanceof Ae||R instanceof ae){r.setHeader("retry-after","2"),V(r,503,R.message,"capacity_error");return}throw R}let m=[],_=null;for await(let R of o.track(h,c,s)){if(m.push(R),R.type==="error"){Do(r,R,{inferenceId:s.id,operatorError:i});return}R.type==="response.completed"&&(_=R.response)}if(_==null){V(r,502,"upstream produced no response.completed event","upstream_error");return}dt(s,_);let b=kt(m,_),v=st(p,bt(_).length,b);if(v){V(r,502,ot(c,v),"upstream_error");return}d&&n.remember(a,u,co(_,b),d),de(r,200,{..._,id:a})}async function Cp(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){V(n,400,"chat/completions requires a messages array");return}let l;try{l=rl(s,t)}catch(k){if(k instanceof ge){V(n,k.status,k.message);return}throw k}let u=String(t.model??"urun"),d=Ui(o.id),c;try{c=Tp(a)}catch(k){if(k instanceof hr){V(n,400,k.message);return}throw k}let p=fe(t);r.model(p),o.model=p,o.stream=t.stream===!0,await _r(o,e,typeof t.model=="string"?t.model:void 0);let h=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:c,stream:!0,tools:Ip(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}:{}},be(o))}catch(k){if(k instanceof j){$t(n,"openai",k);return}if(k instanceof Ae||k instanceof ae){n.setHeader("retry-after","2"),V(n,503,k.message,"capacity_error");return}throw k}if(t.stream===!0){l?Sp(n):Uo(n);let k=[],I=new qe,x="",O=l?new Lt(l,M=>{n.write(`data: ${JSON.stringify(ut(d,u,{content:M},null))}
39
39
 
40
- `)}):null,$=D=>{T?.flush(),n.write(D),n.end()};try{l?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
40
+ `)}):null,$=M=>{O?.flush(),n.write(M),n.end()};try{l?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
41
41
 
42
- `),n.write(`data: ${JSON.stringify(lt(d,u,{role:"assistant"},null))}
42
+ `),n.write(`data: ${JSON.stringify(ut(d,u,{role:"assistant"},null))}
43
43
 
44
- `);for await(let J of r.track(h,p,o)){k.push(J);let pe=vt(J);if(J.type==="response.output_text.delta"&&typeof J.delta=="string")x+=J.delta,T?T.push(J.delta):n.write(`data: ${JSON.stringify(lt(d,u,{content:J.delta},null))}
44
+ `);for await(let J of r.track(m,p,o)){k.push(J);let pe=St(J);if(J.type==="response.output_text.delta"&&typeof J.delta=="string")x+=J.delta,O?O.push(J.delta):n.write(`data: ${JSON.stringify(ut(d,u,{content:J.delta},null))}
45
45
 
46
- `);else if(J.type==="response.reasoning_text.delta"&&typeof J.delta=="string")(!l||l.includeReasoning)&&n.write(`data: ${JSON.stringify(lt(d,u,{reasoning_content:J.delta},null))}
46
+ `);else if(J.type==="response.reasoning_text.delta"&&typeof J.delta=="string")(!l||l.includeReasoning)&&n.write(`data: ${JSON.stringify(ut(d,u,{reasoning_content:J.delta},null))}
47
47
 
48
- `);else if(pe){T?.flush();let{call:N,isNew:j}=E.add(pe),V=j?{index:pe.tool_index,id:N.id??`call_${pe.tool_index}`,type:"function",function:{name:N.name??"",arguments:pe.delta}}:{index:pe.tool_index,function:{arguments:pe.delta}};n.write(`data: ${JSON.stringify(lt(d,u,{tool_calls:[V]},null))}
48
+ `);else if(pe){O?.flush();let{call:U,isNew:G}=I.add(pe),K=G?{index:pe.tool_index,id:U.id??`call_${pe.tool_index}`,type:"function",function:{name:U.name??"",arguments:pe.delta}}:{index:pe.tool_index,function:{arguments:pe.delta}};n.write(`data: ${JSON.stringify(ut(d,u,{tool_calls:[K]},null))}
49
49
 
50
- `)}else if(J.type==="error"){o.streamError=!0;let N=J.error??{},j=$e(N),V=j??Te(o.id);j===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(J)}`),$(`data: ${JSON.stringify({error:{message:V,type:N.type??"upstream_error",code:N.code??null}})}
50
+ `)}else if(J.type==="error"){o.streamError=!0;let U=J.error??{},G=$e(U),K=G??Pe(o.id);G===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(J)}`),$(`data: ${JSON.stringify({error:{message:K,type:U.type??"upstream_error",code:U.code??null}})}
51
51
 
52
- `);return}}let D=Co(Le(k)),q=st(m,E.size+D.length,x);if(q){o.streamError=!0,$(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ot(p,q)}})}
52
+ `);return}}let M=Mo(Le(k)),q=st(h,I.size+M.length,x);if(q){o.streamError=!0,$(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ot(p,q)}})}
53
53
 
54
- `);return}T?.flush(),E.size===0&&D.length>0&&n.write(`data: ${JSON.stringify(lt(d,u,{tool_calls:D},null))}
54
+ `);return}O?.flush(),I.size===0&&M.length>0&&n.write(`data: ${JSON.stringify(ut(d,u,{tool_calls:M},null))}
55
55
 
56
- `);let G=E.size>0||D.length>0;n.write(`data: ${JSON.stringify(lt(d,u,{},G?"tool_calls":"stop"))}
56
+ `);let H=I.size>0||M.length>0;n.write(`data: ${JSON.stringify(ut(d,u,{},H?"tool_calls":"stop"))}
57
57
 
58
- `);let Ce=fr(Le(k));ut(o,Le(k)),Ce&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:rl(Le(k))})}
58
+ `);let he=gr(Le(k));dt(o,Le(k)),he&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:sl(Le(k))})}
59
59
 
60
60
  `),n.write(`data: [DONE]
61
61
 
62
- `),n.end();return}finally{T?.flush(),T?.dispose()}}let v="",S="",w=[],f=new qe;for await(let k of r.track(h,p,o)){w.push(k),k.type==="response.output_text.delta"&&typeof k.delta=="string"&&(v+=k.delta),k.type==="response.reasoning_text.delta"&&typeof k.delta=="string"&&(S+=k.delta);let E=vt(k);if(E&&f.add(E),k.type==="error"){Mo(n,k,{inferenceId:o.id,operatorError:i});return}}let g=Le(w);ut(o,g);let y=Co(g),_=y.length>0?y:Co({output:f.items()}),I=st(m,_.length,v);if(I){W(n,502,ot(p,I),"upstream_error");return}let A=_.map(({index:k,...E})=>E),b={role:"assistant",content:v||null},R=S||sl(g);R&&(b.reasoning_content=R),A.length>0&&(b.tool_calls=A),ue(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:b,finish_reason:A.length>0?"tool_calls":"stop"}],usage:rl(g)})}var wr="sense-latest";async function xp(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){W(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:wr,a=fe({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){W(n,400,"systemone requires a state (string or JSON structure)");return}let l=t.questions;if(l===null||typeof l!="object"||Array.isArray(l)||Object.keys(l).length===0){W(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){W(n,400,"systemone media, when present, must be an array");return}let u=await il(t,i,a,e,n,r,o,s);u!==null&&ue(n,200,u.answer)}async function il(t,e,n,r,o,s,i,a){let l={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=l;let u=performance.now();s.model(n),await yr(i,r,e),l.resolve_ms=Math.round(performance.now()-u);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},ve(i))}catch(w){if(w instanceof B)return Lt(o,"openai",w),null;if(w instanceof xe||w instanceof se)return o.setHeader("retry-after","2"),W(o,503,w.message,"capacity_error"),null;throw w}l.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let w of s.track(d,n,i))if(m===null&&(m=performance.now(),l.first_event_ms=Math.round(m-c)),p.push(w),w.type==="error")return Mo(o,w,{inferenceId:i.id,operatorError:a}),null}catch(w){if(w instanceof B)return m!==null&&(l.stream_ms=Math.round(performance.now()-m)),Lt(o,"openai",w),null;if(w instanceof xe||w instanceof se)return m!==null&&(l.stream_ms=Math.round(performance.now()-m)),o.setHeader("retry-after","2"),W(o,503,w.message,"capacity_error"),null;throw m!==null&&(l.stream_ms=Math.round(performance.now()-m)),w}m!==null&&(l.stream_ms=Math.round(performance.now()-m));let h=Le(p);if(h==null)return W(o,502,"upstream produced no response.completed event","upstream_error"),null;ut(i,h);let v=bt(p,h),S;try{S=JSON.parse(v)}catch{return W(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(S===null||typeof S!="object"||Array.isArray(S))return W(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof S=="object"&&S!==null&&!Array.isArray(S)&&"timing"in S){let w=S.timing;if(typeof w=="object"&&w!==null&&!Array.isArray(w)&&"question_fwd_ms"in w&&"head_ms"in w){let f=g=>typeof g=="number"&&Number.isFinite(g)&&g>=0?Math.round(g):null;l.question_fwd_ms=f(w.question_fwd_ms),l.head_ms=f(w.head_ms)}}return{answer:S,completed:h}}async function Ap(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){W(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:wr,a=fe({model:i});o.model=a,o.stream=!1;let l;try{l=ea(t,i)}catch(p){if(p instanceof M){W(n,400,p.message);return}throw p}let u=await il(l.systemone,i,a,e,n,r,o,s);if(u===null)return;let d;try{d=ra(l.specs,u.answer)}catch(p){if(p instanceof ke){W(n,502,p.message,"upstream_error");return}throw p}let c=u.completed.usage;ue(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function Ip(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var kn=class extends Error{};function gr(t){return new kn(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Op(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 Tp(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 kn(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Pp(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw gr(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw gr(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Cp(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 gr(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:Pp(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw gr(a)}}return s(),r}function Lo(t){return _t(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 Lp(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Pe(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){Pe(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Pe(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(b=>typeof b!="string"))){Pe(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),l=Ni(o.id),u=[],d;try{t.system&&u.push({role:"system",content:Ip(t.system)});for(let b of i)u.push(...Cp(b));d=Tp(t.tool_choice)}catch(b){if(b instanceof kn){Pe(n,400,"invalid_request_error",b.message);return}throw b}let c=fe(t);r.model(c),o.model=c,o.stream=t.stream===!0,await yr(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:u,stream:!0,tools:Op(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},ve(o))}catch(b){if(b instanceof B){Lt(n,"anthropic",b);return}if(b instanceof xe||b instanceof se){n.setHeader("retry-after","2"),Pe(n,503,"capacity_error",b.message);return}throw b}let h=(b,R)=>{n.destroyed||n.write(`event: ${b}
63
- data: ${JSON.stringify({type:b,...R})}
62
+ `),n.end();return}finally{O?.flush(),O?.dispose()}}let _="",b="",v=[],R=new qe;for await(let k of r.track(m,p,o)){v.push(k),k.type==="response.output_text.delta"&&typeof k.delta=="string"&&(_+=k.delta),k.type==="response.reasoning_text.delta"&&typeof k.delta=="string"&&(b+=k.delta);let I=St(k);if(I&&R.add(I),k.type==="error"){Do(n,k,{inferenceId:o.id,operatorError:i});return}}let f=Le(v);dt(o,f);let g=Mo(f),y=g.length>0?g:Mo({output:R.items()}),S=st(h,y.length,_);if(S){V(n,502,ot(p,S),"upstream_error");return}let A=y.map(({index:k,...I})=>I),w={role:"assistant",content:_||null},E=b||al(f);E&&(w.reasoning_content=E),A.length>0&&(w.tool_calls=A),de(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:w,finish_reason:A.length>0?"tool_calls":"stop"}],usage:sl(f)})}var vr="sense-latest";async function Lp(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){V(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:vr,a=fe({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){V(n,400,"systemone requires a state (string or JSON structure)");return}let l=t.questions;if(l===null||typeof l!="object"||Array.isArray(l)||Object.keys(l).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}let u=await ll(t,i,a,e,n,r,o,s);u!==null&&de(n,200,u.answer)}async function ll(t,e,n,r,o,s,i,a){let l={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=l;let u=performance.now();s.model(n),await _r(i,r,e),l.resolve_ms=Math.round(performance.now()-u);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},be(i))}catch(v){if(v instanceof j)return $t(o,"openai",v),null;if(v instanceof Ae||v instanceof ae)return o.setHeader("retry-after","2"),V(o,503,v.message,"capacity_error"),null;throw v}l.dial_ms=Math.round(performance.now()-c);let p=[],h=null;try{for await(let v of s.track(d,n,i))if(h===null&&(h=performance.now(),l.first_event_ms=Math.round(h-c)),p.push(v),v.type==="error")return Do(o,v,{inferenceId:i.id,operatorError:a}),null}catch(v){if(v instanceof j)return h!==null&&(l.stream_ms=Math.round(performance.now()-h)),$t(o,"openai",v),null;if(v instanceof Ae||v instanceof ae)return h!==null&&(l.stream_ms=Math.round(performance.now()-h)),o.setHeader("retry-after","2"),V(o,503,v.message,"capacity_error"),null;throw h!==null&&(l.stream_ms=Math.round(performance.now()-h)),v}h!==null&&(l.stream_ms=Math.round(performance.now()-h));let m=Le(p);if(m==null)return V(o,502,"upstream produced no response.completed event","upstream_error"),null;dt(i,m);let _=kt(p,m),b;try{b=JSON.parse(_)}catch{return V(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(b===null||typeof b!="object"||Array.isArray(b))return V(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof b=="object"&&b!==null&&!Array.isArray(b)&&"timing"in b){let v=b.timing;if(typeof v=="object"&&v!==null&&!Array.isArray(v)&&"question_fwd_ms"in v&&"head_ms"in v){let R=f=>typeof f=="number"&&Number.isFinite(f)&&f>=0?Math.round(f):null;l.question_fwd_ms=R(v.question_fwd_ms),l.head_ms=R(v.head_ms)}}return{answer:b,completed:m}}async function $p(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){V(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:vr,a=fe({model:i});o.model=a,o.stream=!1;let l;try{l=na(t,i)}catch(p){if(p instanceof N){V(n,400,p.message);return}throw p}let u=await ll(l.systemone,i,a,e,n,r,o,s);if(u===null)return;let d;try{d=sa(l.specs,u.answer)}catch(p){if(p instanceof Re){V(n,502,p.message,"upstream_error");return}throw p}let c=u.completed.usage;de(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function Mp(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var xn=class extends Error{};function yr(t){return new xn(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Np(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 Up(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 xn(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Dp(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw yr(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw yr(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Fp(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 yr(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:Dp(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw yr(a)}}return s(),r}function No(t){return bt(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 Hp(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){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(w=>typeof w!="string"))){Ce(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),l=Di(o.id),u=[],d;try{t.system&&u.push({role:"system",content:Mp(t.system)});for(let w of i)u.push(...Fp(w));d=Up(t.tool_choice)}catch(w){if(w instanceof xn){Ce(n,400,"invalid_request_error",w.message);return}throw w}let c=fe(t);r.model(c),o.model=c,o.stream=t.stream===!0,await _r(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:u,stream:!0,tools:Np(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},be(o))}catch(w){if(w instanceof j){$t(n,"anthropic",w);return}if(w instanceof Ae||w instanceof ae){n.setHeader("retry-after","2"),Ce(n,503,"capacity_error",w.message);return}throw w}let m=(w,E)=>{n.destroyed||n.write(`event: ${w}
63
+ data: ${JSON.stringify({type:w,...E})}
64
64
 
65
- `)};if(t.stream===!0){let b=r.track(m,c,o);$o(n),h("message_start",{message:{id:l,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let R=0,k="",E=0,x="none",T=()=>x,$=-1,D=-1,q=new qe,G=[],Ce=()=>{x!=="none"&&(x="none",h("content_block_stop",{index:$}))},J=(K,ee)=>{Ce(),x=K,$=E++,h("content_block_start",{index:$,content_block:ee})};for await(let K of b){if(n.destroyed)break;G.push(K);let ee=vt(K);if(K.type==="response.reasoning_text.delta"&&typeof K.delta=="string")T()!=="thinking"&&J("thinking",{type:"thinking",thinking:""}),h("content_block_delta",{index:$,delta:{type:"thinking_delta",thinking:K.delta}});else if(K.type==="response.output_text.delta"&&typeof K.delta=="string")T()!=="text"&&J("text",{type:"text",text:""}),R+=1,k+=K.delta,h("content_block_delta",{index:$,delta:{type:"text_delta",text:K.delta}});else if(ee){let{call:Ee}=q.add(ee);(T()!=="tool"||ee.tool_index!==D)&&(D=ee.tool_index,J("tool",{type:"tool_use",id:Ee.id??`call_${ee.tool_index}`,name:Ee.name??"",input:{}})),ee.delta&&h("content_block_delta",{index:$,delta:{type:"input_json_delta",partial_json:ee.delta}})}else if(K.type==="error"){o.streamError=!0;let Ee=K.error,Ye=$e(Ee);Ye===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(K)}`),h("error",{error:{type:"api_error",message:Ye??Te(o.id)}}),n.end();return}}if(n.destroyed)return;let pe=Le(G),N=_t(pe),j=st(p,q.size+N.length,k);if(j){o.streamError=!0,h("error",{error:{type:"api_error",message:ot(c,j)}}),n.end();return}Ce();let V=[];if(q.size===0)try{V=Lo(pe)}catch(K){o.streamError=!0;let ee=ye(K,{inferenceId:o.id});ee.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(K instanceof Error?K.message:K)}`),h("error",{error:{type:"api_error",message:ee.message}}),n.end();return}E===0&&V.length===0&&(J("text",{type:"text",text:""}),Ce()),V.forEach(K=>{let ee=E++;h("content_block_start",{index:ee,content_block:{...K,input:{}}}),h("content_block_delta",{index:ee,delta:{type:"input_json_delta",partial_json:JSON.stringify(K.input??{})}}),h("content_block_stop",{index:ee})});let ze=q.size>0||V.length>0,ft=fr(pe);ut(o,pe),h("message_delta",{delta:{stop_reason:ze?"tool_use":"end_turn"},usage:ft?{input_tokens:ft.input_tokens,output_tokens:ft.output_tokens}:{output_tokens:R}}),h("message_stop",{}),n.end();return}let v="",S="",w=[],f=new qe;for await(let b of r.track(m,c,o)){w.push(b),b.type==="response.output_text.delta"&&typeof b.delta=="string"&&(v+=b.delta),b.type==="response.reasoning_text.delta"&&typeof b.delta=="string"&&(S+=b.delta);let R=vt(b);if(R&&f.add(R),b.type==="error"){let k=b.error,E=k?.type==="invalid_request_error",x=$e(k);x===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(b)}`),Pe(n,E?400:502,E?"invalid_request_error":"api_error",x??Te(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let g=Le(w);ut(o,g);let y;try{y=Lo(g),y.length===0&&f.size>0&&(y=Lo({output:f.items()}))}catch(b){let R=ye(b,{inferenceId:o.id});R.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(b instanceof Error?b.message:b)}`),Pe(n,502,"api_error",R.message);return}let _=st(p,y.length,v);if(_){Pe(n,502,"api_error",ot(c,_));return}let I=[],A=S||sl(g);A&&I.push({type:"thinking",thinking:A}),(v||y.length===0)&&I.push({type:"text",text:v}),I.push(...y),ue(n,200,{id:l,type:"message",role:"assistant",content:I,model:a,stop_reason:y.length>0?"tool_use":"end_turn",usage:fr(g)??{input_tokens:0,output_tokens:0}})}function $p(t){Je(process.stdout,t)}function al(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??$p,a=t.operatorLog??(d=>console.error(d)),l=t.observe,u=new nt;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),h=(g,y,_,I,A)=>m?Pe(c,g,I,y):W(c,g,y,_,A),v=io(p.pathname),S=p.pathname.startsWith("/partners/"),w=v||S?{id:sn(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;w&&(c.setHeader(Li,w.id),c.once("close",()=>{let g=Ui({turn:w,method:d.method??"",path:p.pathname,res:c});i(Di(g)),l?.(g),Za({record:g,ledger:t.ledger??null,req:d})}));let f=()=>$i(p.pathname,w);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){ue(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){ue(c,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){h(401,"invalid local proxy api key","authentication_error","authentication_error");return}let g=p.pathname===cr?"canonical":p.pathname===yn?"huggingface":null;if(g){if(d.method!=="POST"){h(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let A=t.usage;if(!A){h(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 b=A.authorize(d),R;try{R=await nl(d,Fa)}catch(x){if(x instanceof Sn){h(413,x.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let k=x=>A.lookup(b,x),E;try{if(g==="canonical"){let x=Ha(R),T=await k(x);pr(T,x),E={requests:T}}else E=await qa(R,k)}catch(x){if(x instanceof Ve){h(x.status,x.message,"invalid_request_error","invalid_request_error");return}throw x}ue(c,200,E);return}if(d.method==="GET"&&p.pathname===Ze){let A=await s(d);if(w&&(w.org=A.tenant??null),!A.openRouterModels){h(501,`GET ${Ze} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ue(c,200,await A.openRouterModels());return}if(p.pathname.startsWith("/partners/")){h(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${yn} and GET ${Ze}`,"invalid_request_error","not_found_error");return}let y=await s(d);if(w&&(w.org=y.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:Ze}),c.end();return}ue(c,200,await y.listModels());return}if(d.method==="GET"&&p.pathname===ia){if(!y.listImageModels){h(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ue(c,200,await y.listImageModels());return}if(sa(p.pathname)){if(!y.supportsImages){h(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let A={clients:y,imageModels:y.supportsImages,stats:u,turn:f(),operatorLog:a};p.pathname===sr?await ha(d,c,A):await ga(d,c,A);return}if(d.method==="GET"&&p.pathname===Pa){if(!y.listSpeechToTextModels){h(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ue(c,200,await y.listSpeechToTextModels());return}if(Ta(p.pathname)){if(!y.supportsTranscription){h(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${ur}`,"not_implemented","not_implemented_error");return}let A={clients:y,transcriptionModels:y.supportsTranscription,stats:u,turn:f(),operatorLog:a};await $a(d,c,A);return}if(Ea(p.pathname)){if(!y.supportsSpeech){h(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${hn}`,"not_implemented","not_implemented_error");return}let A={clients:y,speechModels:y.supportsSpeech,stats:u,turn:f(),operatorLog:a};await Oa(d,c,A);return}if(d.method!=="POST"){h(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let _;try{_=await nl(d)}catch(A){if(A instanceof Sn){h(413,A.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let I=Buffer.byteLength(JSON.stringify(_));if(p.pathname==="/v1/responses"){u.request("responses",I,I),await Rp(_,y,ln(y),c,u,f(),a);return}if(p.pathname==="/v1/chat/completions"){u.request("chat_completions",I,I),await Ep(_,y,c,u,f(),d.headers[Po],a);return}if(p.pathname==="/v1/systemone"){u.request("systemone",I,I),await xp(_,y,c,u,f(),a);return}if(p.pathname==="/v1/decisions"){u.request("decisions",I,I),await Ap(_,y,c,u,f(),a);return}if(p.pathname==="/v1/messages"){u.request("messages",I,I),await Lp(_,y,c,u,f(),a);return}if(p.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",I,I),Pe(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}h(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(g=>{let y=String(g instanceof Error?g.message:g);if(!c.headersSent){let A=o?.(g)??null;if(A){A.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${A.operatorDetail}`),h(A.status,y,A.openaiType,A.anthropicType,A.code);return}if(g instanceof hr.SessionAllocationError){let R=Jn(g.code);if(R){let k=g.retryAfterSeconds??(R.status===429?30:void 0);k!==void 0&&c.setHeader("Retry-After",String(k)),h(R.status,cn(R,g.code??void 0),R.openaiType,R.anthropicType,R.code);return}}if(g instanceof hr.SessionFailedError){let R=Vn(g);if(R){let k=R.status===429?30:void 0;k!==void 0&&c.setHeader("Retry-After",String(k)),h(R.status,cn(R,g.status.sessionId?`session ${g.status.sessionId}`:void 0),R.openaiType,R.anthropicType,R.code);return}}if(g instanceof te){h(502,y,"upstream_error","api_error");return}if(g instanceof Ae){g.retryable&&c.setHeader("Retry-After","1");let R=ye(g,{inferenceId:w?.id??null});R.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:Ie(g)}`),h(502,R.message,"upstream_error","api_error",g.code);return}if(g instanceof Ge){c.setHeader("Retry-After",String(g.retryAfterSeconds)),h(g.status,y,g.status===429?"capacity_error":"upstream_error",g.status===429?"rate_limit_error":"overloaded_error",g.code);return}let b=ye(g,{inferenceId:w?.id??null});b.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:Ie(g)}`),h(500,b.message,"proxy_error","api_error","proxy_error");return}w&&(w.streamError=!0);let _=g instanceof Ae?g.code:null,I=ye(g,{inferenceId:w?.id??null});I.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:Ie(g)}`),c.destroyed||(m?c.write(`event: error
66
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:I.message}})}
65
+ `)};if(t.stream===!0){let w=r.track(h,c,o);Uo(n),m("message_start",{message:{id:l,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let E=0,k="",I=0,x="none",O=()=>x,$=-1,M=-1,q=new qe,H=[],he=()=>{x!=="none"&&(x="none",m("content_block_stop",{index:$}))},J=(z,te)=>{he(),x=z,$=I++,m("content_block_start",{index:$,content_block:te})};for await(let z of w){if(n.destroyed)break;H.push(z);let te=St(z);if(z.type==="response.reasoning_text.delta"&&typeof z.delta=="string")O()!=="thinking"&&J("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:$,delta:{type:"thinking_delta",thinking:z.delta}});else if(z.type==="response.output_text.delta"&&typeof z.delta=="string")O()!=="text"&&J("text",{type:"text",text:""}),E+=1,k+=z.delta,m("content_block_delta",{index:$,delta:{type:"text_delta",text:z.delta}});else if(te){let{call:xe}=q.add(te);(O()!=="tool"||te.tool_index!==M)&&(M=te.tool_index,J("tool",{type:"tool_use",id:xe.id??`call_${te.tool_index}`,name:xe.name??"",input:{}})),te.delta&&m("content_block_delta",{index:$,delta:{type:"input_json_delta",partial_json:te.delta}})}else if(z.type==="error"){o.streamError=!0;let xe=z.error,Ye=$e(xe);Ye===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(z)}`),m("error",{error:{type:"api_error",message:Ye??Pe(o.id)}}),n.end();return}}if(n.destroyed)return;let pe=Le(H),U=bt(pe),G=st(p,q.size+U.length,k);if(G){o.streamError=!0,m("error",{error:{type:"api_error",message:ot(c,G)}}),n.end();return}he();let K=[];if(q.size===0)try{K=No(pe)}catch(z){o.streamError=!0;let te=we(z,{inferenceId:o.id});te.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(z instanceof Error?z.message:z)}`),m("error",{error:{type:"api_error",message:te.message}}),n.end();return}I===0&&K.length===0&&(J("text",{type:"text",text:""}),he()),K.forEach(z=>{let te=I++;m("content_block_start",{index:te,content_block:{...z,input:{}}}),m("content_block_delta",{index:te,delta:{type:"input_json_delta",partial_json:JSON.stringify(z.input??{})}}),m("content_block_stop",{index:te})});let ze=q.size>0||K.length>0,mt=gr(pe);dt(o,pe),m("message_delta",{delta:{stop_reason:ze?"tool_use":"end_turn"},usage:mt?{input_tokens:mt.input_tokens,output_tokens:mt.output_tokens}:{output_tokens:E}}),m("message_stop",{}),n.end();return}let _="",b="",v=[],R=new qe;for await(let w of r.track(h,c,o)){v.push(w),w.type==="response.output_text.delta"&&typeof w.delta=="string"&&(_+=w.delta),w.type==="response.reasoning_text.delta"&&typeof w.delta=="string"&&(b+=w.delta);let E=St(w);if(E&&R.add(E),w.type==="error"){let k=w.error,I=k?.type==="invalid_request_error",x=$e(k);x===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(w)}`),Ce(n,I?400:502,I?"invalid_request_error":"api_error",x??Pe(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let f=Le(v);dt(o,f);let g;try{g=No(f),g.length===0&&R.size>0&&(g=No({output:R.items()}))}catch(w){let E=we(w,{inferenceId:o.id});E.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(w instanceof Error?w.message:w)}`),Ce(n,502,"api_error",E.message);return}let y=st(p,g.length,_);if(y){Ce(n,502,"api_error",ot(c,y));return}let S=[],A=b||al(f);A&&S.push({type:"thinking",thinking:A}),(_||g.length===0)&&S.push({type:"text",text:_}),S.push(...g),de(n,200,{id:l,type:"message",role:"assistant",content:S,model:a,stop_reason:g.length>0?"tool_use":"end_turn",usage:gr(f)??{input_tokens:0,output_tokens:0}})}function Bp(t){Ve(process.stdout,t)}function ul(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Bp,a=t.operatorLog??(d=>console.error(d)),l=t.observe,u=new nt;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),h=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),m=(f,g,y,S,A)=>h?Ce(c,f,S,g):V(c,f,g,y,A),_=uo(p.pathname),b=p.pathname.startsWith("/partners/"),v=_||b?{id:un(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;v&&(c.setHeader(Mi,v.id),c.once("close",()=>{let f=Fi({turn:v,method:d.method??"",path:p.pathname,res:c});i(Hi(f)),l?.(f),tl({record:f,ledger:t.ledger??null,req:d})}));let R=()=>Ni(p.pathname,v);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){de(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){de(c,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let f=p.pathname===fr?"canonical":p.pathname===vn?"huggingface":null;if(f){if(d.method!=="POST"){m(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let A=t.usage;if(!A){m(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 w=A.authorize(d),E;try{E=await ol(d,Ba)}catch(x){if(x instanceof En){m(413,x.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let k=x=>A.lookup(w,x),I;try{if(f==="canonical"){let x=ja(E),O=await k(x);mr(O,x),I={requests:O}}else I=await Wa(E,k)}catch(x){if(x instanceof Je){m(x.status,x.message,"invalid_request_error","invalid_request_error");return}throw x}de(c,200,I);return}if(d.method==="GET"&&p.pathname===Ze){let A=await s(d);if(v&&(v.org=A.tenant??null),!A.openRouterModels){m(501,`GET ${Ze} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}de(c,200,await A.openRouterModels());return}if(p.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${vn} and GET ${Ze}`,"invalid_request_error","not_found_error");return}let g=await s(d);if(v&&(v.org=g.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:Ze}),c.end();return}de(c,200,await g.listModels());return}if(d.method==="GET"&&p.pathname===la){if(!g.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}de(c,200,await g.listImageModels());return}if(aa(p.pathname)){if(!g.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let A={clients:g,imageModels:g.supportsImages,stats:u,turn:R(),operatorLog:a};p.pathname===ar?await wa(d,c,A):await ya(d,c,A);return}if(d.method==="GET"&&p.pathname===La){if(!g.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}de(c,200,await g.listSpeechToTextModels());return}if(Ca(p.pathname)){if(!g.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${cr}`,"not_implemented","not_implemented_error");return}let A={clients:g,transcriptionModels:g.supportsTranscription,stats:u,turn:R(),operatorLog:a};await Na(d,c,A);return}if(Aa(p.pathname)){if(!g.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${_n}`,"not_implemented","not_implemented_error");return}let A={clients:g,speechModels:g.supportsSpeech,stats:u,turn:R(),operatorLog:a};await Pa(d,c,A);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let y;try{y=await ol(d)}catch(A){if(A instanceof En){m(413,A.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let S=Buffer.byteLength(JSON.stringify(y));if(p.pathname==="/v1/responses"){u.request("responses",S,S),await Pp(y,g,cn(g),c,u,R(),a);return}if(p.pathname==="/v1/chat/completions"){u.request("chat_completions",S,S),await Cp(y,g,c,u,R(),d.headers[$o],a);return}if(p.pathname==="/v1/systemone"){u.request("systemone",S,S),await Lp(y,g,c,u,R(),a);return}if(p.pathname==="/v1/decisions"){u.request("decisions",S,S),await $p(y,g,c,u,R(),a);return}if(p.pathname==="/v1/messages"){u.request("messages",S,S),await Hp(y,g,c,u,R(),a);return}if(p.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",S,S),Ce(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(f=>{let g=String(f instanceof Error?f.message:f);if(!c.headersSent){let A=o?.(f)??null;if(A){A.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${A.operatorDetail}`),m(A.status,g,A.openaiType,A.anthropicType,A.code);return}if(f instanceof wr.SessionAllocationError){let E=Kn(f.code);if(E){let k=f.retryAfterSeconds??(E.status===429?30:void 0);k!==void 0&&c.setHeader("Retry-After",String(k)),m(E.status,mn(E,f.code??void 0),E.openaiType,E.anthropicType,E.code);return}}if(f instanceof wr.SessionFailedError){let E=zn(f);if(E){let k=E.status===429?30:void 0;k!==void 0&&c.setHeader("Retry-After",String(k)),m(E.status,mn(E,f.status.sessionId?`session ${f.status.sessionId}`:void 0),E.openaiType,E.anthropicType,E.code);return}}if(f instanceof ne){m(502,g,"upstream_error","api_error");return}if(f instanceof Ie){f.retryable&&c.setHeader("Retry-After","1");let E=we(f,{inferenceId:v?.id??null});E.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:Oe(f)}`),m(502,E.message,"upstream_error","api_error",f.code);return}if(f instanceof Ge){c.setHeader("Retry-After",String(f.retryAfterSeconds)),m(f.status,g,f.status===429?"capacity_error":"upstream_error",f.status===429?"rate_limit_error":"overloaded_error",f.code);return}let w=we(f,{inferenceId:v?.id??null});w.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:Oe(f)}`),m(500,w.message,"proxy_error","api_error","proxy_error");return}v&&(v.streamError=!0);let y=f instanceof Ie?f.code:null,S=we(f,{inferenceId:v?.id??null});S.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:Oe(f)}`),c.destroyed||(h?c.write(`event: error
66
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:S.message}})}
67
67
 
68
- `):c.write(`data: ${JSON.stringify({error:{message:I.message,type:"upstream_error",code:_}})}
68
+ `):c.write(`data: ${JSON.stringify({error:{message:S.message,type:"upstream_error",code:y}})}
69
69
 
70
- `)),c.end()})}}var De=(t,e)=>Object.assign(new Error(e),{status:t}),Up='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Uo=(t,e,n)=>new F(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),No=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof B?De(404,n.message):n}};async function ll(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw De(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Up}`);if(o==="transcription")throw De(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw De(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw De(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(m){throw m instanceof B?De(404,m.message):m}if(!p)throw De(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(m){throw m instanceof B?De(404,m.message):m}if(p!=="stt")throw De(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await No(t,n.stt),i=await No(t,e),a=await No(t,n.tts),l=await t.openAudioOn(s,r),u=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,Dp({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{l.appendInputAudio(p)},onOutputAudio:p=>u.onOutputAudio(p),sessionId:u.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(m){throw m instanceof F?Uo("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function Do(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var _r=class extends Error{};async function*Dp(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:l}=t;if(n?.aborted){r?.();return}let{output_modalities:u,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,h=null,v=null,S=[],w=null,f=new Promise((E,x)=>{n&&n.addEventListener("abort",()=>x(new _r),{once:!0})}),g=()=>m||n?.aborted===!0,y=async E=>{if(g())return;let x;try{x=await o.createResponseOn(i,{model:l.tts,input:[{role:"user",content:[{type:"input_text",text:E}]}],stream:!1,...l.voice!==void 0?{voice:l.voice}:{}})}catch($){throw $ instanceof F?Uo("tts",l.tts,$):$}let T=x[Symbol.asyncIterator]();v=T;try{for(;;){let $=T.next(),D;try{D=await Promise.race([$,f])}catch(G){if($.catch(()=>{}),G instanceof _r)return;throw G}if(D.done)return;let q=D.value;if(q.type==="error"){let G=q.error&&typeof q.error.message=="string"?q.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(l.tts)}) errored: ${G}`)}if(q.type==="response.completed")return}}finally{v===T&&(v=null)}},_=async()=>{for(;S.length>0&&!g();){let E=S.shift();await y(E)}},I=E=>{if(E===""||g()||(S.push(E),w!==null))return;let x=_();w=x,x.then(()=>{w===x&&(w=null)},T=>{w===x&&(w=null),h??=T})},A=()=>{m=!0,S.length=0;let E=v;if(v=null,E){let x=E.return?.();x&&x.catch(()=>{})}},b=async()=>{for(;S.length>0||w!==null;){let E=w;if(E===null){await y(S.shift());continue}await E}},R=p?new Ct({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},E=>I(E)):null,k=null;try{let E;try{E=await o.createResponseOn(s,d)}catch(x){throw x instanceof F?Uo("chat",a,x):x}for await(let x of E){if(g())return;let T=x;if(T.type==="error"){yield x;return}if(T.type==="response.output_text.delta"&&typeof T.delta=="string"){yield x,R?.push(T.delta);continue}if(T.type==="response.function_call_arguments.delta"){R?.flush(),yield x;continue}if(T.type==="response.completed"){k=x.response;continue}}R?.flush(),R?.dispose(),p&&await b(),k!==null&&(yield{type:"response.completed",response:k})}finally{R?.dispose(),A();try{if(h instanceof F)throw h}finally{r?.()}}}var Re=(t,e)=>Object.assign(new Error(e),{status:t});function dl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function cl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Fp='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function pl(t,e,n,r){if(!t.supportsAudio)throw Re(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(d){throw d instanceof B?Re(404,d.message):d}if(!o){let d=null;if(t.realtimeCompanionsFor)try{d=await t.realtimeCompanionsFor(e)}catch(c){throw c instanceof B?Re(404,c.message):c}if(d!==null)return await ll(t,e,d,n,r);throw Re(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw Re(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 s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(d){throw d instanceof B?Re(404,d.message):d}if(s&&!t.openTurnsOn)throw Re(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let d;try{d=await t.transcriptStreamFor(e)}catch(c){throw c instanceof B?Re(404,c.message):c}if(d!=="stt")throw Re(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw Re(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Fp}`);if(r==="transcription"&&!s)throw Re(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i;try{i=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(d){throw d instanceof se?Re(503,d.message):d}let a=`conn_${(0,ul.randomUUID)()}`,l={audio:await t.openAudioOn(i,n,a)},u={clients:{createResponse:async d=>await t.createResponseOn(i,d,a)},voice:o,audioSession:l};return s&&(u.turns=d=>t.openTurnsOn(i,d)),r==="transcription"&&(u.intent="transcription"),t.releaseSessionHandle&&(u.release=()=>t.releaseSessionHandle(i)),e!==void 0&&(u.model=e),u}var Al=require("@urun-sh/core/internal"),Il=de(require("ws"),1);async function fl(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}function ml(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 vr(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 gl(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 Hp="llm-resp";async function*Sr(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let a=typeof i.index=="number"?i.index:0,l=r.get(a)??{};i.id&&(l.id=i.id),i.function?.name&&(l.name=i.function.name),r.set(a,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:l.id,name:l.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield gl(s);return}}}async function*Fo(t,e){let n=`${Hp}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Sr(e,t.stream(n).messages())}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var kr=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=vr(e,n,this.consumerId);return this.write(r),Fo(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=ml(e,n,r,this.consumerId);return this.write(o),Fo(this.session,r)})}async writeGated(e,n){try{await fl(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var hl=0;function jp(){return hl+=1,`req_${Date.now().toString(36)}_${hl.toString(36)}`}var dt=class{transport;constructor(e,n){this.transport=new kr(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=jp(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var $t=de(require("yjs"),1),yl=require("@urun-sh/core/internal"),qp=3e4;function Gp(t){return(e,n,r)=>{let o=t(e);$t.applyUpdate(n,$t.encodeStateAsUpdate(o));let s=a=>$t.applyUpdate(o,a),i=a=>$t.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}function Ho(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Gp(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=r.get(d);return c||(c=new yl.SessionDocumentImpl(d,e,n),r.set(d,c)),c},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=i.get(d);if(!c){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);c=t.streamEndpoint(d),i.set(d,c)}return c},l=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);async function*p(){let m=a(d);try{yield*m.messages()}finally{i.delete(d),await m.close()}}return{messages:()=>p(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:l,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let p=d?.timeout??t.whenLiveTimeoutMs??qp;await new Promise((m,h)=>{let v=setTimeout(()=>{S(),h(new Error(`lane ${e} llm doc never synced within ${p}ms`))},p),S=c.onSynced(()=>{clearTimeout(v),d?.signal?.removeEventListener("abort",w),m()}),w=()=>{clearTimeout(v),S(),h(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",w,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,c]of i)i.delete(d),c.close()}}}var ct=de(require("ws"),1),pt=require("@urun-sh/core"),wl="/stream/";function _l(t){if(!t.startsWith(wl))return null;let e=t.slice(wl.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function xr(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Rr(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>pt.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Er=class{reassembler=new pt.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===pt.STREAM_END&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},jo=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;(a.list.length>=vl||a.bytes+o.byteLength>bl)&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${vl} frames / ${bl} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,l)=>a+l.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},vl=256,bl=8*1024*1024,Me=new jo;function Sl(t,e){let n=new Er,r={send(o){Me.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Rr(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),Me.detach(t,e,r)}};return Me.attach(t,e,r),r}function Wp(t){return{deliver(e){try{t.send(e,{binary:!0})}catch(n){console.warn(`[lane-stream] socket send failed: ${String(n)}`)}},close(e,n){try{t.close(e,n)}catch{}}}}function kl(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new ct.default(r,xr(e)),s=new Er;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Rr(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Rr(i),o.readyState!==ct.default.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function Bo(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
70
+ `)),c.end()})}}var De=(t,e)=>Object.assign(new Error(e),{status:t}),Gp='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Ho=(t,e,n)=>new F(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Fo=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof j?De(404,n.message):n}};async function dl(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw De(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Gp}`);if(o==="transcription")throw De(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw De(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw De(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(h){throw h instanceof j?De(404,h.message):h}if(!p)throw De(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(h){throw h instanceof j?De(404,h.message):h}if(p!=="stt")throw De(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await Fo(t,n.stt),i=await Fo(t,e),a=await Fo(t,n.tts),l=await t.openAudioOn(s,r),u=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let h=new AbortController;return d=h,Wp({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},p,h.signal,()=>{d===h&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{l.appendInputAudio(p)},onOutputAudio:p=>u.onOutputAudio(p),sessionId:u.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(h){throw h instanceof F?Ho("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function Bo(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var br=class extends Error{};async function*Wp(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:l}=t;if(n?.aborted){r?.();return}let{output_modalities:u,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),h=!1,m=null,_=null,b=[],v=null,R=new Promise((I,x)=>{n&&n.addEventListener("abort",()=>x(new br),{once:!0})}),f=()=>h||n?.aborted===!0,g=async I=>{if(f())return;let x;try{x=await o.createResponseOn(i,{model:l.tts,input:[{role:"user",content:[{type:"input_text",text:I}]}],stream:!1,...l.voice!==void 0?{voice:l.voice}:{}})}catch($){throw $ instanceof F?Ho("tts",l.tts,$):$}let O=x[Symbol.asyncIterator]();_=O;try{for(;;){let $=O.next(),M;try{M=await Promise.race([$,R])}catch(H){if($.catch(()=>{}),H instanceof br)return;throw H}if(M.done)return;let q=M.value;if(q.type==="error"){let H=q.error&&typeof q.error.message=="string"?q.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(l.tts)}) errored: ${H}`)}if(q.type==="response.completed")return}}finally{_===O&&(_=null)}},y=async()=>{for(;b.length>0&&!f();){let I=b.shift();await g(I)}},S=I=>{if(I===""||f()||(b.push(I),v!==null))return;let x=y();v=x,x.then(()=>{v===x&&(v=null)},O=>{v===x&&(v=null),m??=O})},A=()=>{h=!0,b.length=0;let I=_;if(_=null,I){let x=I.return?.();x&&x.catch(()=>{})}},w=async()=>{for(;b.length>0||v!==null;){let I=v;if(I===null){await g(b.shift());continue}await I}},E=p?new Lt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},I=>S(I)):null,k=null;try{let I;try{I=await o.createResponseOn(s,d)}catch(x){throw x instanceof F?Ho("chat",a,x):x}for await(let x of I){if(f())return;let O=x;if(O.type==="error"){yield x;return}if(O.type==="response.output_text.delta"&&typeof O.delta=="string"){yield x,E?.push(O.delta);continue}if(O.type==="response.function_call_arguments.delta"){E?.flush(),yield x;continue}if(O.type==="response.completed"){k=x.response;continue}}E?.flush(),E?.dispose(),p&&await w(),k!==null&&(yield{type:"response.completed",response:k})}finally{E?.dispose(),A();try{if(m instanceof F)throw m}finally{r?.()}}}var Ee=(t,e)=>Object.assign(new Error(e),{status:t});function pl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function fl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}function ml(t){let e=new URL(t.url??"/","http://localhost").searchParams.get("session"),n=t.headers?.["x-urun-session"],r=(e??(typeof n=="string"?n:n?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var Vp='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function gl(t,e,n,r){if(!t.supportsAudio)throw Ee(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(c){throw c instanceof j?Ee(404,c.message):c}if(!o){let c=null;if(t.realtimeCompanionsFor)try{c=await t.realtimeCompanionsFor(e)}catch(p){throw p instanceof j?Ee(404,p.message):p}if(c!==null)return await dl(t,e,c,n,r);throw Ee(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw Ee(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 s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(c){throw c instanceof j?Ee(404,c.message):c}if(s&&!t.openTurnsOn)throw Ee(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let c;try{c=await t.transcriptStreamFor(e)}catch(p){throw p instanceof j?Ee(404,p.message):p}if(c!=="stt")throw Ee(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(c)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw Ee(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Vp}`);if(r==="transcription"&&!s)throw Ee(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i;try{i=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(c){throw c instanceof ae?Ee(503,c.message):c}let a=`conn_${(0,cl.randomUUID)()}`,u={audio:await t.openAudioOn(i,n,a).catch(c=>{throw t.releaseSessionHandle?.(i),c})},d={clients:{createResponse:async c=>await t.createResponseOn(i,c,a)},voice:o,audioSession:u};return t.openVideoOn&&(d.video=()=>t.openVideoOn(i,n)),s&&(d.turns=c=>t.openTurnsOn(i,c)),r==="transcription"&&(d.intent="transcription"),t.releaseSessionHandle&&(d.release=()=>t.releaseSessionHandle(i)),e!==void 0&&(d.model=e),d}var Ml=require("@urun-sh/core"),Nl=require("@urun-sh/core/internal"),Ul=ce(require("ws"),1);var _l=require("http");var Jp=require("bullmq"),Kp=require("crypto");var hl=12e4;var zp="/pooler/v1/lanes/pick",Yp="/pooler/v1/lanes/status",Xp=1e4,An=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function yl(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),u=(0,_l.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:o},d=>{let c=[];d.on("data",p=>c.push(p)),d.on("end",()=>{let p=Buffer.concat(c).toString("utf8"),h=null;try{h=p===""?null:JSON.parse(p)}catch{h=null}s({status:d.statusCode??0,json:h})}),d.on("error",i)});u.on("timeout",()=>{u.destroy(new An(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),u.on("error",i),u.end(l)})}function wl(t,e,n){if(t===503)return new ae(n);let r=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${r}`)}function vl(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=Math.min(Math.max(Math.trunc(r),0),hl),s=await yl(t,"POST",zp,{pool:e,model:n,hold_ms:o},o+Xp);if(s.status!==200)throw wl(s.status,s.json,e);return(s.json?.lanes??[]).filter(a=>typeof a.lane_id=="string"&&a.lane_id!==""&&typeof a.host=="string"&&a.host!=="").map(a=>({laneId:a.lane_id,host:a.host}))},async status(){let e=await yl(t,"GET",Yp,void 0,5e3);if(e.status!==200)throw wl(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}async function bl(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}function Sl(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 Sr(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 kl(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 Qp="llm-resp";async function*Rr(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let a=typeof i.index=="number"?i.index:0,l=r.get(a)??{};i.id&&(l.id=i.id),i.function?.name&&(l.name=i.function.name),r.set(a,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:l.id,name:l.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield kl(s);return}}}async function*jo(t,e){let n=`${Qp}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Rr(e,t.stream(n).messages())}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var Er=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=Sr(e,n,this.consumerId);return this.write(r),jo(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=Sl(e,n,r,this.consumerId);return this.write(o),jo(this.session,r)})}async writeGated(e,n){try{await bl(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var Rl=0;function ef(){return Rl+=1,`req_${Date.now().toString(36)}_${Rl.toString(36)}`}var ct=class{transport;constructor(e,n){this.transport=new Er(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=ef(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var Mt=ce(require("yjs"),1),El=require("@urun-sh/core/internal"),tf=3e4;function nf(t){return(e,n,r)=>{let o=t(e);Mt.applyUpdate(n,Mt.encodeStateAsUpdate(o));let s=a=>Mt.applyUpdate(o,a),i=a=>Mt.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}function qo(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?nf(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=r.get(d);return c||(c=new El.SessionDocumentImpl(d,e,n),r.set(d,c)),c},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=i.get(d);if(!c){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);c=t.streamEndpoint(d),i.set(d,c)}return c},l=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);async function*p(){let h=a(d);try{yield*h.messages()}finally{i.delete(d),await h.close()}}return{messages:()=>p(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:l,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let p=d?.timeout??t.whenLiveTimeoutMs??tf;await new Promise((h,m)=>{let _=setTimeout(()=>{b(),m(new Error(`lane ${e} llm doc never synced within ${p}ms`))},p),b=c.onSynced(()=>{clearTimeout(_),d?.signal?.removeEventListener("abort",v),h()}),v=()=>{clearTimeout(_),b(),m(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",v,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,c]of i)i.delete(d),c.close()}}}var pt=ce(require("ws"),1),ft=require("@urun-sh/core"),xl="/stream/";function Al(t){if(!t.startsWith(xl))return null;let e=t.slice(xl.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function Ir(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function xr(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>ft.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Ar=class{reassembler=new ft.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===ft.STREAM_END&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},Wo=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;(a.list.length>=Il||a.bytes+o.byteLength>Ol)&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Il} frames / ${Ol} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,l)=>a+l.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},Il=256,Ol=8*1024*1024,Me=new Wo;function Tl(t,e){let n=new Ar,r={send(o){Me.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{xr(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),Me.detach(t,e,r)}};return Me.attach(t,e,r),r}function rf(t){return{deliver(e){try{t.send(e,{binary:!0})}catch(n){console.warn(`[lane-stream] socket send failed: ${String(n)}`)}},close(e,n){try{t.close(e,n)}catch{}}}}function Pl(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new pt.default(r,Ir(e)),s=new Ar;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{xr(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(xr(i),o.readyState!==pt.default.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function Go(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
71
71
  `;t.end(`HTTP/1.1 ${e} ${r}\r
72
72
  Connection: close\r
73
73
  Content-Type: text/plain; charset=utf-8\r
74
74
  Content-Length: ${Buffer.byteLength(o)}\r
75
75
  \r
76
- ${o}`)}function Rl(t,e){let n=e.heartbeatMs??3e4,r=new ct.WebSocketServer({noServer:!0,handleProtocols:(u,d)=>{let c=_l(new URL(d.url??"/","http://localhost").pathname);if(!c)return!1;let p=xr(c.name);return u.has(p)?p:!1}}),o=new Map,s=new Set,i=!1,a=(u,d,c,p)=>{let m={client:c,upstream:p,laneId:u,name:d};s.add(m);let h=v=>{if(s.delete(m)){console.warn(`[lane-stream] ${u}/${d}: host-affinity pump torn down (${v})`);for(let S of[c,p])try{(S.readyState===ct.default.OPEN||S.readyState===ct.default.CONNECTING)&&S.close(1001,"lane stream pump closed")}catch{}}};if(n>0){let v=(S,w)=>{let f=!0;S.on("pong",()=>{f=!0});let g=setInterval(()=>{if(!f){console.warn(`[lane-stream] ${u}/${d}: pong timeout on ${w} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${w} dial never sends a close)`),clearInterval(g);try{S.terminate()}catch{}h(`${w} pong timeout`);return}f=!1;try{S.ping()}catch{}},n);g.unref?.();let y=()=>clearInterval(g);S.once("close",y),S.once("error",y)};v(c,"client"),v(p,"host")}c.on("message",v=>{try{p.send(v,{binary:!0})}catch(S){h(`upstream send failed: ${String(S)}`)}}),p.on("message",v=>{try{c.send(v,{binary:!0})}catch(S){h(`client send failed: ${String(S)}`)}}),c.on("close",()=>h("client socket closed")),c.on("error",()=>h("client socket error")),p.on("close",()=>h("host socket closed")),p.on("error",()=>h("host socket error"))},l=(u,d,c)=>{let p;try{p=new URL(u.url??"/","http://localhost")}catch{Bo(d,400,"malformed upgrade URL");return}d.on("error",()=>d.destroy());let m=_l(p.pathname);m&&(i||d.destroyed||(async()=>{let h=p.searchParams.get("token")??"",v=null;try{v=h===""?null:await e.verifyToken(h,m.laneId,m.name)}catch{v=null}if(v===null){Bo(d,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let S=await e.hostOf(m.laneId).catch(()=>null);if(S&&S!==e.selfAddress)try{let w=await e.podToPodDial(m.laneId,m.name,S);r.handleUpgrade(u,d,c,f=>{a(m.laneId,m.name,f,w)});return}catch(w){console.warn(`[lane-stream] ${m.laneId}/${m.name}: host dial to ${S} failed (${String(w)}) \u2014 falling back to the local relay`)}}r.handleUpgrade(u,d,c,S=>{let w=Wp(S);if(o.set(S,w),Me.attach(m.laneId,m.name,w),n>0){let g=!0;S.on("pong",()=>{g=!0});let y=setInterval(()=>{if(!g){console.warn(`[lane-stream] ${m.laneId}/${m.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(y),S.terminate();return}g=!1;try{S.ping()}catch{}},n);y.unref?.();let _=()=>clearInterval(y);S.once("close",_),S.once("error",_)}S.on("message",g=>{let y=new Uint8Array(g);try{Rr(y)}catch(_){console.warn(`[lane-stream] ${m.laneId}/${m.name}: dropped malformed envelope: ${String(_)}`);return}Me.deliver(m.laneId,m.name,w,y),y[1]===pt.ENVELOPE_KIND.END&&Me.detach(m.laneId,m.name,w)});let f=()=>{o.delete(S),Me.detach(m.laneId,m.name,w)};S.on("close",f),S.on("error",f)})})().catch(()=>{d.destroyed||Bo(d,500,"lane stream upgrade failed")}))};return t.on("upgrade",l),{async close(){i=!0,t.off("upgrade",l),Me.clear();for(let u of o.values())u.close(1001,"lane stream host shutting down");o.clear();for(let u of s)for(let d of[u.client,u.upstream])try{d.close(1001,"lane stream host shutting down")}catch{}s.clear()}}}var Ke=require("crypto"),Jp=["sfu","urun-doc"],xl="runtime:lease",Vp="lane:join",Kp="urun-runtime-key-v1";function qo(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,Ke.createHmac)("sha256",t).update(`${Kp}|${e}`).digest("base64url")}var zp=120,Ny=1440*60;function El(t){return Buffer.from(t).toString("base64url")}function Yp(t,e,n){let r=El(JSON.stringify(t)),o=El(JSON.stringify(e)),s=(0,Ke.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function Rn(t,e,n=zp,r=Vp,o){let s=o?qo(e,o):e;return Xp(t,s,n,r,o)}function Xp(t,e,n,r,o){let s=Math.floor(Date.now()/1e3);return Yp({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,Ke.randomUUID)()},e)}function Go(t,e,n,r=Math.floor(Date.now()/1e3),o){let s=t.split(".");if(s.length!==3)return null;let[i,a,l]=s,u,d;try{u=JSON.parse(Buffer.from(i,"base64url").toString()),d=JSON.parse(Buffer.from(a,"base64url").toString())}catch{return null}if(u.alg!=="HS256")return null;let c;try{c=Buffer.from(l,"base64url")}catch{return null}let p=typeof d.tenant=="string"&&d.tenant!==""?d.tenant:void 0,m=[];if(p!==void 0?(m.push(qo(n,p)),o&&m.push(qo(o,p))):(m.push(n),o&&m.push(o)),!m.some(f=>{let g=(0,Ke.createHmac)("sha256",f).update(`${i}.${a}`).digest();return c.length===g.length&&(0,Ke.timingSafeEqual)(c,g)}))return null;let h=d.exp;if(typeof h!="number"||h<=r)return null;let v=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(v!==void 0&&Jp.some(f=>f===v||Array.isArray(v)&&v.includes(f))))return null;let w=d.session_id??d.sub;return typeof w!="string"||w!==e?null:{sessionId:w,aud:v,scope:typeof d.scope=="string"?d.scope:void 0,tenant:p,app:typeof d.app=="string"?d.app:void 0,fn:typeof d.fn=="string"?d.fn:void 0,exp:h}}var Qp=3,Zp="llm",ef=new Set(["paused","error"]);function Ar(t,e,n){let r=t.doc(Zp),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)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 i=null,a=!1,l=new Set,u=[],d=c=>{if(!i){i=c;for(let p of[...l])p(c);l.clear()}};return o&&u.push(r.onConnectionState(c=>{a&&(c.consecutiveFailures<Qp||d(new F(`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.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?u.push(r.onSynced(()=>{a=!0})):s&&u.push(t.onPhase(c=>{if(c.name==="live"){a=!0;return}a&&ef.has(c.name)&&d(new F(`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:()=>i,onGone(c){return i?(c(i),()=>{}):(l.add(c),()=>l.delete(c))},dispose(){l.clear();for(let c of u.splice(0))c()}}}async function*Wo(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(l=>a(l))});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 tf(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new Se(`the shared lane target (app slug "${t.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${e}.${t.appId}.${t.fnName??""}`}function Ol(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=(p,m,h,v,S)=>{let w=h?_=>Sl(p,_):_=>kl(p,_,{hostUrl:`ws://${v}/stream/${p}`,token:()=>Rn(p,t.tokenSecret,void 0,void 0,S)}),f=h?Ho({laneId:p,roomDoc:_=>t.roomDoc(p,_),streamEndpoint:w}):Ho({laneId:p,streamEndpoint:w,connector:(0,Al.createWebsocketDocConnector)({serverUrl:`ws://${v}/doc`,sessionId:p,token:()=>Rn(p,t.tokenSecret,void 0,void 0,S),WebSocketPolyfill:Il.default})}),g=h?a(p):Ar(f,`lane:${p}`,{armOnFirstSync:!0}),y={session:f,responses:new dt(f,{sessionTag:null}),gone:g,goneWatch:g,laneId:p,pool:m,inFlight:0,laneSession:f,self:h,host:v??""};return n.set(p,y),g.onGone(()=>l(y)),y},a=p=>{let m=null,h=!1,v=new Set,S=f=>{if(!m){m=f;for(let g of[...v])g(f);v.clear()}},w=t.hostedSignal?.(p,f=>{if(f){h=!0;return}h&&S(new F(`the lane ${p} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>m,onGone(f){return m?(f(m),()=>{}):(v.add(f),()=>v.delete(f))},dispose(){w?.(),v.clear()}}},l=p=>{u(p)&&(n.delete(p.laneId),r.delete(p.laneId),p.goneWatch?.dispose(),Me.forgetLane(p.laneId))},u=p=>{let m=p.laneId;return typeof m=="string"&&n.get(m)===p},d=(p,m)=>{throw t.metrics?.observeLane503Fast(m??""),s.set(p,e()),new se(p)},c=async(p,m)=>{let h=tf(m);o.add(h);let v=e();try{let S=await t.laneWarmWaitMsFor?.(p,m)??t.laneColdWakeDefaultMs??0,w=await t.plane.pick({pool:h,model:p,holdMs:S});t.metrics?.observeLaneReady(p??"",w.length);let g=w.map(_=>({laneId:_.laneId,self:_.host===t.selfAddress,host:_.host})).sort((_,I)=>_.self!==I.self?_.self?-1:1:(r.get(_.laneId)??0)-(r.get(I.laneId)??0))[0];g||d(h,p);let y=n.get(g.laneId);return y?.goneWatch?.gone()&&(l(y),y=void 0),y&&(y.pool!==h||y.self!==g.self||y.host!==g.host)&&(l(y),y=void 0),y||(y=i(g.laneId,h,g.self,g.host,m.sharedOrgId??void 0)),y.inFlight+=1,r.set(g.laneId,(r.get(g.laneId)??0)+1),{app:h,entry:y,identity:{kind:"catalog",model_id:m.modelId??p??"",variant:m.variant??""}}}finally{t.metrics?.observeLanePick(p??"",e()-v)}};return{sessionFor(p,m){return c(p,m)},release(p){u(p)&&(p.inFlight=Math.max(0,p.inFlight-1),r.set(p.laneId,p.inFlight))},owns(p){return u(p)},entryFor(p){return n.get(p)??null},evict(p){u(p)&&(p.gone.dispose(),n.delete(p.laneId),r.set(p.laneId,0),p.laneSession.destroy())},async status(){let p=[...new Set([...o,...[...n.values()].map(v=>v.pool)])].sort(),m=await t.plane.status().catch(()=>[]),h=new Map(nf(m));return Promise.all(p.map(async v=>{let S=h.get(v)??{pool:v,lanes:[],lastDemandAt:null};return{pool:v,lanes:S.lanes,lastDemandAt:S.lastDemandAt,local:[...n.values()].filter(w=>w.pool===v).map(w=>({laneId:w.laneId,inFlight:w.inFlight,self:w.self,host:w.host})),lastRefusalAt:s.get(v)??null}}))},async close(){for(let p of n.values())p.gone.dispose(),p.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(p=>({pool:p.pool,laneId:p.laneId,inFlight:p.inFlight}))}}}function nf(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}var Cl=require("http");var rf="/pooler/v1/lanes/pick",of="/pooler/v1/lanes/status",sf=1e4;function Tl(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),u=(0,Cl.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:o},d=>{let c=[];d.on("data",p=>c.push(p)),d.on("end",()=>{let p=Buffer.concat(c).toString("utf8"),m=null;try{m=p===""?null:JSON.parse(p)}catch{m=null}s({status:d.statusCode??0,json:m})}),d.on("error",i)});u.on("timeout",()=>{u.destroy(new Error(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),u.on("error",i),u.end(l)})}function Pl(t,e,n){if(t===503)return new se(n);let r=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${r}`)}function Ll(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=await Tl(t,"POST",rf,{pool:e,model:n,hold_ms:r},r+sf);if(o.status!==200)throw Pl(o.status,o.json,e);return(o.json?.lanes??[]).filter(i=>typeof i.lane_id=="string"&&i.lane_id!==""&&typeof i.host=="string"&&i.host!=="").map(i=>({laneId:i.lane_id,host:i.host}))},async status(){let e=await Tl(t,"GET",of,void 0,5e3);if(e.status!==200)throw Pl(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}var Hl=require("ws");var Ml=de(require("yjs"),1),Ut=de(require("y-protocols/sync"),1),Fe=de(require("y-protocols/awareness"),1),Z=de(require("lib0/encoding"),1),Dt=de(require("lib0/decoding"),1),Nl=de(require("lib0/map"),1),Ul=de(require("lodash.debounce"),1);var $l=()=>{};var lf=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,uf=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,df=0,cf=1;var pf=process.env.GC!=="false"&&process.env.GC!=="0",ff=process.env.YPERSISTENCE,Ir=null;if(typeof ff=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var Nt=new Map,Or=0,Vo=1,mf=(t,e,n)=>{let r=Z.createEncoder();Z.writeVarUint(r,Or),Ut.writeUpdate(r,t);let o=Z.toUint8Array(r);n.conns.forEach((s,i)=>En(n,i,o))},Jo=class extends Ml.Doc{constructor(e){super({gc:pf}),this.name=e,this.conns=new Map,this.awareness=new Fe.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let d=this.conns.get(i);d!==void 0&&(r.forEach(c=>{d.add(c)}),s.forEach(c=>{d.delete(c)}))}let l=Z.createEncoder();Z.writeVarUint(l,Vo),Z.writeVarUint8Array(l,Fe.encodeAwarenessUpdate(this.awareness,a));let u=Z.toUint8Array(l);this.conns.forEach((d,c)=>{En(this,c,u)})};this.awareness.on("update",n),this.on("update",mf),!1}},Ko=(t,e=!0)=>Nl.setIfUndefined(Nt,t,()=>{let n=new Jo(t);return n.gc=e,Ir!==null&&Ir.bindState(t,n),Nt.set(t,n),n}),gf=(t,e,n)=>{try{let r=Z.createEncoder(),o=Dt.createDecoder(n);switch(Dt.readVarUint(o)){case Or:Z.writeVarUint(r,Or),Ut.readSyncMessage(o,r,e,t),Z.length(r)>1&&En(e,t,Z.toUint8Array(r));break;case Vo:{Fe.applyAwarenessUpdate(e.awareness,Dt.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},Mt=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),Fe.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Ir!==null&&(Ir.writeState(t.name,t).then(()=>{t.destroy()}),Nt.delete(t.name))}e.close()},En=(t,e,n)=>{e.readyState!==df&&e.readyState!==cf&&Mt(t,e);try{e.send(n,r=>{r!=null&&Mt(t,e)})}catch{Mt(t,e)}},hf=3e4,Dl=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=Ko(n,r);o.conns.set(t,new Set),t.on("message",a=>gf(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&Mt(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{Mt(o,t),clearInterval(i)}}},hf);t.on("close",()=>{Mt(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=Z.createEncoder();Z.writeVarUint(a,Or),Ut.writeSyncStep1(a,o),En(o,t,Z.toUint8Array(a));let l=o.awareness.getStates();if(l.size>0){let u=Z.createEncoder();Z.writeVarUint(u,Vo),Z.writeVarUint8Array(u,Fe.encodeAwarenessUpdate(o.awareness,Array.from(l.keys()))),En(o,t,Z.toUint8Array(u))}}};var zo="/doc/",Bl=30,yf=1e4,Fl="llm";function wf(t){if(!t.startsWith(zo))return null;let e=t.slice(zo.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function xn(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
76
+ ${o}`)}function Cl(t,e){let n=e.heartbeatMs??3e4,r=new pt.WebSocketServer({noServer:!0,handleProtocols:(u,d)=>{let c=Al(new URL(d.url??"/","http://localhost").pathname);if(!c)return!1;let p=Ir(c.name);return u.has(p)?p:!1}}),o=new Map,s=new Set,i=!1,a=(u,d,c,p)=>{let h={client:c,upstream:p,laneId:u,name:d};s.add(h);let m=_=>{if(s.delete(h)){console.warn(`[lane-stream] ${u}/${d}: host-affinity pump torn down (${_})`);for(let b of[c,p])try{(b.readyState===pt.default.OPEN||b.readyState===pt.default.CONNECTING)&&b.close(1001,"lane stream pump closed")}catch{}}};if(n>0){let _=(b,v)=>{let R=!0;b.on("pong",()=>{R=!0});let f=setInterval(()=>{if(!R){console.warn(`[lane-stream] ${u}/${d}: pong timeout on ${v} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${v} dial never sends a close)`),clearInterval(f);try{b.terminate()}catch{}m(`${v} pong timeout`);return}R=!1;try{b.ping()}catch{}},n);f.unref?.();let g=()=>clearInterval(f);b.once("close",g),b.once("error",g)};_(c,"client"),_(p,"host")}c.on("message",_=>{try{p.send(_,{binary:!0})}catch(b){m(`upstream send failed: ${String(b)}`)}}),p.on("message",_=>{try{c.send(_,{binary:!0})}catch(b){m(`client send failed: ${String(b)}`)}}),c.on("close",()=>m("client socket closed")),c.on("error",()=>m("client socket error")),p.on("close",()=>m("host socket closed")),p.on("error",()=>m("host socket error"))},l=(u,d,c)=>{let p;try{p=new URL(u.url??"/","http://localhost")}catch{Go(d,400,"malformed upgrade URL");return}d.on("error",()=>d.destroy());let h=Al(p.pathname);h&&(i||d.destroyed||(async()=>{let m=p.searchParams.get("token")??"",_=null;try{_=m===""?null:await e.verifyToken(m,h.laneId,h.name)}catch{_=null}if(_===null){Go(d,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let b=await e.hostOf(h.laneId).catch(()=>null);if(b&&b!==e.selfAddress)try{let v=await e.podToPodDial(h.laneId,h.name,b);r.handleUpgrade(u,d,c,R=>{a(h.laneId,h.name,R,v)});return}catch(v){console.warn(`[lane-stream] ${h.laneId}/${h.name}: host dial to ${b} failed (${String(v)}) \u2014 falling back to the local relay`)}}r.handleUpgrade(u,d,c,b=>{let v=rf(b);if(o.set(b,v),Me.attach(h.laneId,h.name,v),n>0){let f=!0;b.on("pong",()=>{f=!0});let g=setInterval(()=>{if(!f){console.warn(`[lane-stream] ${h.laneId}/${h.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(g),b.terminate();return}f=!1;try{b.ping()}catch{}},n);g.unref?.();let y=()=>clearInterval(g);b.once("close",y),b.once("error",y)}b.on("message",f=>{let g=new Uint8Array(f);try{xr(g)}catch(y){console.warn(`[lane-stream] ${h.laneId}/${h.name}: dropped malformed envelope: ${String(y)}`);return}Me.deliver(h.laneId,h.name,v,g),g[1]===ft.ENVELOPE_KIND.END&&Me.detach(h.laneId,h.name,v)});let R=()=>{o.delete(b),Me.detach(h.laneId,h.name,v)};b.on("close",R),b.on("error",R)})})().catch(()=>{d.destroyed||Go(d,500,"lane stream upgrade failed")}))};return t.on("upgrade",l),{async close(){i=!0,t.off("upgrade",l),Me.clear();for(let u of o.values())u.close(1001,"lane stream host shutting down");o.clear();for(let u of s)for(let d of[u.client,u.upstream])try{d.close(1001,"lane stream host shutting down")}catch{}s.clear()}}}var Ke=require("crypto"),of=["sfu","urun-doc"],$l="runtime:lease",sf="lane:join",af="urun-runtime-key-v1";function Vo(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,Ke.createHmac)("sha256",t).update(`${af}|${e}`).digest("base64url")}var lf=120,tw=1440*60;function Ll(t){return Buffer.from(t).toString("base64url")}function uf(t,e,n){let r=Ll(JSON.stringify(t)),o=Ll(JSON.stringify(e)),s=(0,Ke.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function In(t,e,n=lf,r=sf,o){let s=o?Vo(e,o):e;return df(t,s,n,r,o)}function df(t,e,n,r,o){let s=Math.floor(Date.now()/1e3);return uf({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,Ke.randomUUID)()},e)}function Jo(t,e,n,r=Math.floor(Date.now()/1e3),o){let s=t.split(".");if(s.length!==3)return null;let[i,a,l]=s,u,d;try{u=JSON.parse(Buffer.from(i,"base64url").toString()),d=JSON.parse(Buffer.from(a,"base64url").toString())}catch{return null}if(u.alg!=="HS256")return null;let c;try{c=Buffer.from(l,"base64url")}catch{return null}let p=typeof d.tenant=="string"&&d.tenant!==""?d.tenant:void 0,h=[];if(p!==void 0?(h.push(Vo(n,p)),o&&h.push(Vo(o,p))):(h.push(n),o&&h.push(o)),!h.some(R=>{let f=(0,Ke.createHmac)("sha256",R).update(`${i}.${a}`).digest();return c.length===f.length&&(0,Ke.timingSafeEqual)(c,f)}))return null;let m=d.exp;if(typeof m!="number"||m<=r)return null;let _=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(_!==void 0&&of.some(R=>R===_||Array.isArray(_)&&_.includes(R))))return null;let v=d.session_id??d.sub;return typeof v!="string"||v!==e?null:{sessionId:v,aud:_,scope:typeof d.scope=="string"?d.scope:void 0,tenant:p,app:typeof d.app=="string"?d.app:void 0,fn:typeof d.fn=="string"?d.fn:void 0,exp:m}}var cf=3,pf="llm",ff=new Set(["paused","error"]);function Or(t,e,n){let r=t.doc(pf),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)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 i=null,a=!1,l=new Set,u=[],d=c=>{if(!i){i=c;for(let p of[...l])p(c);l.clear()}};return o&&u.push(r.onConnectionState(c=>{a&&(c.consecutiveFailures<cf||d(new F(`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.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?u.push(r.onSynced(()=>{a=!0})):s&&u.push(t.onPhase(c=>{if(c.name==="live"){a=!0;return}a&&ff.has(c.name)&&d(new F(`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:()=>i,onGone(c){return i?(c(i),()=>{}):(l.add(c),()=>l.delete(c))},dispose(){l.clear();for(let c of u.splice(0))c()}}}async function*Ko(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(l=>a(l))});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 mf(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new ke(`the shared lane target (app slug "${t.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${e}.${t.appId}.${t.fnName??""}`}function Dl(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=new Set,a=(m,_,b,v,R,f)=>{let g=b?w=>Tl(m,w):w=>Pl(m,w,{hostUrl:`ws://${v}/stream/${m}`,token:()=>In(m,t.tokenSecret,void 0,void 0,f)}),y=b?qo({laneId:m,roomDoc:w=>t.roomDoc(m,w),streamEndpoint:g}):qo({laneId:m,streamEndpoint:g,connector:(0,Nl.createWebsocketDocConnector)({serverUrl:`ws://${v}/doc`,sessionId:m,token:()=>In(m,t.tokenSecret,void 0,void 0,f),WebSocketPolyfill:Ul.default})}),S=b?l(m):Or(y,`lane:${m}`,{armOnFirstSync:!0}),A={session:y,responses:new ct(y,{sessionTag:null}),gone:S,goneWatch:S,laneId:m,pool:_,inFlight:0,laneSession:y,self:b,host:v??"",mintedRelease:R??"",retireWhenIdle:!1};return n.set(m,A),S.onGone(()=>u(A)),A},l=m=>{let _=null,b=!1,v=new Set,R=g=>{if(!_){_=g;for(let y of[...v])y(g);v.clear()}},f=t.hostedSignal?.(m,g=>{if(g){b=!0;return}b&&R(new F(`the lane ${m} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>_,onGone(g){return _?(g(_),()=>{}):(v.add(g),()=>v.delete(g))},dispose(){f?.(),v.clear()}}},u=m=>{d(m)&&(n.delete(m.laneId),r.delete(m.laneId),m.goneWatch?.dispose(),Me.forgetLane(m.laneId))},d=m=>{let _=m.laneId;return typeof _=="string"&&n.get(_)===m},c=m=>{d(m)&&(m.self&&!t.closeLane||(i.add(m.laneId),m.self&&t.closeLane?.(m.laneId),u(m)))},p=(m,_)=>{throw t.metrics?.observeLane503Fast(_??""),s.set(m,e()),new ae(m)},h=async(m,_)=>{let b=mf(_);o.add(b);let v=e();try{let R=await t.laneWarmWaitMsFor?.(m,_)??t.laneColdWakeDefaultMs??0,f;try{f=await t.plane.pick({pool:b,model:m,holdMs:R})}catch(E){throw E instanceof An?new Ml.SessionAllocationError(`lane pick hold expired for ${b}: ${E.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):E}t.metrics?.observeLaneReady(m??"",f.length);let g=await t.currentReleaseOf?.(_)??null,y=new Set(f.map(E=>E.laneId));for(let E of i)y.has(E)||i.delete(E);let A=f.filter(E=>{let k=n.get(E.laneId);return k!==void 0&&g!==null&&k.mintedRelease!==""&&k.mintedRelease!==g&&(k.retireWhenIdle=!0,k.inFlight===0)?(c(k),!1):!i.has(E.laneId)}).map(E=>({laneId:E.laneId,self:E.host===t.selfAddress,host:E.host})).sort((E,k)=>E.self!==k.self?E.self?-1:1:(r.get(E.laneId)??0)-(r.get(k.laneId)??0))[0];A||p(b,m);let w=n.get(A.laneId);return w?.goneWatch?.gone()&&(u(w),w=void 0),w&&(w.pool!==b||w.self!==A.self||w.host!==A.host)&&(u(w),w=void 0),w||(w=a(A.laneId,b,A.self,A.host,g,_.sharedOrgId??void 0)),w.inFlight+=1,r.set(A.laneId,(r.get(A.laneId)??0)+1),{app:b,entry:w,identity:{kind:"catalog",model_id:_.modelId??m??"",variant:_.variant??""}}}finally{t.metrics?.observeLanePick(m??"",e()-v)}};return{sessionFor(m,_){return h(m,_)},release(m){d(m)&&(m.inFlight=Math.max(0,m.inFlight-1),r.set(m.laneId,m.inFlight),m.inFlight===0&&m.retireWhenIdle&&c(m))},owns(m){return d(m)},entryFor(m){return n.get(m)??null},evict(m){d(m)&&(m.gone.dispose(),n.delete(m.laneId),r.set(m.laneId,0),m.laneSession.destroy())},async status(){let m=[...new Set([...o,...[...n.values()].map(v=>v.pool)])].sort(),_=await t.plane.status().catch(()=>[]),b=new Map(gf(_));return Promise.all(m.map(async v=>{let R=b.get(v)??{pool:v,lanes:[],lastDemandAt:null};return{pool:v,lanes:R.lanes,lastDemandAt:R.lastDemandAt,local:[...n.values()].filter(f=>f.pool===v).map(f=>({laneId:f.laneId,inFlight:f.inFlight,self:f.self,host:f.host})),lastRefusalAt:s.get(v)??null}}))},async close(){for(let m of n.values())m.gone.dispose(),m.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(m=>({pool:m.pool,laneId:m.laneId,inFlight:m.inFlight}))}}}function gf(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}var hf="urun:node-scheduler:apps:v1";function yf(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function Fl(t){return async e=>{let n=yf(e);if(n===null)return null;try{let r=await t.hget(hf,n);if(r===null||r==="")return null;let o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let s=o.current_release_id;if(typeof s!="string")return null;let i=s.trim();return i===""?null:i}catch{return null}}}var Vl=require("ws");var Bl=ce(require("yjs"),1),Dt=ce(require("y-protocols/sync"),1),Fe=ce(require("y-protocols/awareness"),1),ee=ce(require("lib0/encoding"),1),Ft=ce(require("lib0/decoding"),1),jl=ce(require("lib0/map"),1),ql=ce(require("lodash.debounce"),1);var Hl=()=>{};var _f=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,vf=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,bf=0,Sf=1;var kf=process.env.GC!=="false"&&process.env.GC!=="0",Rf=process.env.YPERSISTENCE,Tr=null;if(typeof Rf=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var Ut=new Map,Pr=0,Yo=1,Ef=(t,e,n)=>{let r=ee.createEncoder();ee.writeVarUint(r,Pr),Dt.writeUpdate(r,t);let o=ee.toUint8Array(r);n.conns.forEach((s,i)=>On(n,i,o))},zo=class extends Bl.Doc{constructor(e){super({gc:kf}),this.name=e,this.conns=new Map,this.awareness=new Fe.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let d=this.conns.get(i);d!==void 0&&(r.forEach(c=>{d.add(c)}),s.forEach(c=>{d.delete(c)}))}let l=ee.createEncoder();ee.writeVarUint(l,Yo),ee.writeVarUint8Array(l,Fe.encodeAwarenessUpdate(this.awareness,a));let u=ee.toUint8Array(l);this.conns.forEach((d,c)=>{On(this,c,u)})};this.awareness.on("update",n),this.on("update",Ef),!1}},Xo=(t,e=!0)=>jl.setIfUndefined(Ut,t,()=>{let n=new zo(t);return n.gc=e,Tr!==null&&Tr.bindState(t,n),Ut.set(t,n),n}),xf=(t,e,n)=>{try{let r=ee.createEncoder(),o=Ft.createDecoder(n);switch(Ft.readVarUint(o)){case Pr:ee.writeVarUint(r,Pr),Dt.readSyncMessage(o,r,e,t),ee.length(r)>1&&On(e,t,ee.toUint8Array(r));break;case Yo:{Fe.applyAwarenessUpdate(e.awareness,Ft.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},Nt=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),Fe.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Tr!==null&&(Tr.writeState(t.name,t).then(()=>{t.destroy()}),Ut.delete(t.name))}e.close()},On=(t,e,n)=>{e.readyState!==bf&&e.readyState!==Sf&&Nt(t,e);try{e.send(n,r=>{r!=null&&Nt(t,e)})}catch{Nt(t,e)}},Af=3e4,Gl=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=Xo(n,r);o.conns.set(t,new Set),t.on("message",a=>xf(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&Nt(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{Nt(o,t),clearInterval(i)}}},Af);t.on("close",()=>{Nt(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=ee.createEncoder();ee.writeVarUint(a,Pr),Dt.writeSyncStep1(a,o),On(o,t,ee.toUint8Array(a));let l=o.awareness.getStates();if(l.size>0){let u=ee.createEncoder();ee.writeVarUint(u,Yo),ee.writeVarUint8Array(u,Fe.encodeAwarenessUpdate(o.awareness,Array.from(l.keys()))),On(o,t,ee.toUint8Array(u))}}};var Qo="/doc/",Jl=30,If=1e4,Wl="llm";function Of(t){if(!t.startsWith(Qo))return null;let e=t.slice(Qo.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function Ht(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
77
77
  `;t.end(`HTTP/1.1 ${e} ${r}\r
78
78
  Connection: close\r
79
79
  Content-Type: text/plain; charset=utf-8\r
80
80
  Content-Length: ${Buffer.byteLength(o)}\r
81
81
  \r
82
- ${o}`)}function jl(t,e){let n=new Hl.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=w=>o.get(`${w}/${Fl}`)??0,a=w=>s.get(w)??0,l=new Map,u=new Map,d=new Set,c=new Set,p=!1,m=(w,f,g)=>{let y=i(w)>0,_=a(w),I=_>0,A=`${w}/${f}`,b=o.get(A)??0;g>0?o.set(A,g):o.delete(A);let R=_+g-b;R>0?s.set(w,R):s.delete(w);let k=i(w)>0,E=R>0;if(y!==k){k?h(w):v(w);for(let x of l.get(w)??[])x(k)}I&&!E&&queueMicrotask(()=>{let x=`${w}/`;for(let[T,$]of[...Nt.entries()])!T.startsWith(x)||$.conns.size>0||(Nt.delete(T),$.destroy())})},h=w=>{if(!e.hostRegistry||u.has(w))return;let f=()=>{e.hostRegistry?.setHost(w,e.selfAddress).catch(()=>{})};f();let g=setInterval(f,yf);g.unref?.(),u.set(w,g)},v=w=>{let f=u.get(w);f&&(clearInterval(f),u.delete(w)),e.hostRegistry&&e.hostRegistry.delHost(w,e.selfAddress).catch(()=>{})},S=(w,f,g)=>{let y;try{y=new URL(w.url??"/","http://localhost")}catch{xn(f,400,"malformed upgrade URL");return}f.on("error",()=>f.destroy()),f.on("close",()=>c.delete(f));let _=wf(y.pathname);if(!_){if(y.pathname.startsWith(zo)){xn(f,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(f);return}d.add(f);let I=!1;(async()=>{let A=y.searchParams.get("token")??"",b=null;try{b=A===""?null:await e.verifyToken(A,_.laneId,_.docName)}catch{b=null}if(b===null){xn(f,401,"invalid or missing lane doc token");return}let R=b;if(R.tenant!==void 0&&e.laneTenantOf){let k=null;try{k=await e.laneTenantOf(_.laneId)}catch{k=null}if(k==null||k==="")e.onLaneTenantMissing?.();else if(R.tenant!==k){xn(f,403,"lane doc token org does not match the lane record");return}}p||f.destroyed||(I=!0,n.handleUpgrade(w,f,g,k=>{d.delete(f),r.add(k),k.on("close",()=>r.delete(k));let E=R.scope===xl||R.scope===void 0&&typeof R.app=="string"&&typeof R.fn=="string"&&R.aud==="sfu";if(E){let T=`${_.laneId}/${_.docName}`,$=(o.get(T)??0)+1;m(_.laneId,_.docName,$),$>1&&_.docName===Fl&&e.hostRegistry?.setHost(_.laneId,e.selfAddress).catch(()=>{})}k.on("close",()=>{if(!E)return;let T=`${_.laneId}/${_.docName}`;m(_.laneId,_.docName,Math.max(0,(o.get(T)??1)-1))}),Dl(k,w,{docName:`${_.laneId}/${_.docName}`,gc:!0})}))})().catch(()=>{!I&&!f.destroyed&&xn(f,500,"lane doc upgrade failed")}).finally(()=>d.delete(f))};return t.on("upgrade",S),{async close(){p=!0,t.off("upgrade",S);for(let f of[...u.keys()])v(f);await new Promise(f=>{if(r.size===0&&d.size===0){f();return}let g=r.size+d.size,y=()=>{g-=1,g<=0&&f()};for(let _ of r)_.once("close",y);for(let _ of d)_.once("close",y);for(let _ of r)_.close(1001,"lane doc host shutting down");for(let _ of d)_.destroy()}),o.clear(),s.clear(),l.clear()},roomDoc(w,f){return Ko(`${w}/${f}`,!0)},isHosted(w){return i(w)>0},onHostedChange(w,f){let g=l.get(w);return g||(g=new Set,l.set(w,g)),g.add(f),f(i(w)>0),()=>{g.delete(f)}}}}var yu=de(require("ws"),1);var _f="urun:catalog:v1";function ql(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,s=null,i=async()=>{let l=await t.redis.hgetall(_f),u=[];for(let d of Object.values(l))try{u.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
83
- `)}return r=u,o=n(),u},a=()=>r===null||n()-o>=e;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}var ne=require("@prometheus-io/client"),Gl=require("http");var Wl=9464,Tr="/metrics",Ft="(other)",Yo="(none)",Xo=64,Qo=128,vf=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/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",cr,yn,Ze],bf=new Set(vf);function Zo(t){return bf.has(t)?t:Ft}function es(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var Ht=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?Yo:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,Ft):(this.admitted.add(e),e):Ft}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},Bt=class{registry=new ne.Registry;modelLabel=new Ht(Xo);orgLabel=new Ht(Qo);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new ne.Gauge({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),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 Ka)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"},za()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Ya()/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]}),this.lanesReady=new ne.Gauge({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new ne.Histogram({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new ne.Histogram({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new ne.Counter({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new ne.Counter({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",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})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=Zo(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 l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?Ft:e.method,status_class:es(e.status),stream:l,model:s,org:i}),this.duration.observe({lane:n,stream:l,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 Pr(t){return(0,Gl.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Tr){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Tr}
82
+ ${o}`)}function Kl(t,e){let n=new Vl.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=g=>o.get(`${g}/${Wl}`)??0,a=g=>s.get(g)??0,l=new Map,u=new Map,d=new Set,c=new Set,p=new Map,h=new Map,m=4096,_=!1,b=(g,y,S)=>{let A=i(g)>0,w=a(g),E=w>0,k=`${g}/${y}`,I=o.get(k)??0;S>0?o.set(k,S):o.delete(k);let x=w+S-I;x>0?s.set(g,x):s.delete(g);let O=i(g)>0,$=x>0;if(A!==O){O?v(g):R(g);for(let M of l.get(g)??[])M(O)}E&&!$&&queueMicrotask(()=>{let M=`${g}/`;for(let[q,H]of[...Ut.entries()])!q.startsWith(M)||H.conns.size>0||(Ut.delete(q),H.destroy())})},v=g=>{if(!e.hostRegistry||u.has(g))return;let y=()=>{e.hostRegistry?.setHost(g,e.selfAddress).catch(()=>{})};y();let S=setInterval(y,If);S.unref?.(),u.set(g,S)},R=g=>{let y=u.get(g);y&&(clearInterval(y),u.delete(g)),e.hostRegistry&&e.hostRegistry.delHost(g,e.selfAddress).catch(()=>{})},f=(g,y,S)=>{let A;try{A=new URL(g.url??"/","http://localhost")}catch{Ht(y,400,"malformed upgrade URL");return}y.on("error",()=>y.destroy()),y.on("close",()=>c.delete(y));let w=Of(A.pathname);if(!w){if(A.pathname.startsWith(Qo)){Ht(y,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(y);return}d.add(y);let E=!1;(async()=>{if(h.has(w.laneId)){Ht(y,409,"lane retired \u2014 the app's release moved; a fresh lane serves it");return}let k=A.searchParams.get("token")??"",I=null;try{I=k===""?null:await e.verifyToken(k,w.laneId,w.docName)}catch{I=null}if(I===null){Ht(y,401,"invalid or missing lane doc token");return}let x=I;if(x.tenant!==void 0&&e.laneTenantOf){let O=null;try{O=await e.laneTenantOf(w.laneId)}catch{O=null}if(O==null||O==="")e.onLaneTenantMissing?.();else if(x.tenant!==O){Ht(y,403,"lane doc token org does not match the lane record");return}}_||y.destroyed||(E=!0,n.handleUpgrade(g,y,S,O=>{d.delete(y),r.add(O),O.on("close",()=>r.delete(O));let $=p.get(w.laneId);$||($=new Set,p.set(w.laneId,$)),$.add(O),O.on("close",()=>{$.delete(O),$.size===0&&p.delete(w.laneId)});let M=x.scope===$l||x.scope===void 0&&typeof x.app=="string"&&typeof x.fn=="string"&&x.aud==="sfu";if(M){let H=`${w.laneId}/${w.docName}`,he=(o.get(H)??0)+1;b(w.laneId,w.docName,he),he>1&&w.docName===Wl&&e.hostRegistry?.setHost(w.laneId,e.selfAddress).catch(()=>{})}O.on("close",()=>{if(!M)return;let H=`${w.laneId}/${w.docName}`;b(w.laneId,w.docName,Math.max(0,(o.get(H)??1)-1))}),Gl(O,g,{docName:`${w.laneId}/${w.docName}`,gc:!0})}))})().catch(()=>{!E&&!y.destroyed&&Ht(y,500,"lane doc upgrade failed")}).finally(()=>d.delete(y))};return t.on("upgrade",f),{async close(){_=!0,t.off("upgrade",f);for(let y of[...u.keys()])R(y);await new Promise(y=>{if(r.size===0&&d.size===0){y();return}let S=r.size+d.size,A=()=>{S-=1,S<=0&&y()};for(let w of r)w.once("close",A);for(let w of d)w.once("close",A);for(let w of r)w.close(1001,"lane doc host shutting down");for(let w of d)w.destroy()}),o.clear(),s.clear(),l.clear()},roomDoc(g,y){return Xo(`${g}/${y}`,!0)},isHosted(g){return i(g)>0},onHostedChange(g,y){let S=l.get(g);return S||(S=new Set,l.set(g,S)),S.add(y),y(i(g)>0),()=>{S.delete(y)}},closeLane(g){if(h.set(g,!0),h.size>m){let y=h.keys().next().value;y!==void 0&&h.delete(y)}R(g);for(let y of p.get(g)??[])y.close(1001,`lane ${g} retired \u2014 the app's release moved`)}}}var Ru=ce(require("ws"),1);var Tf="urun:catalog:v1";function zl(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,s=null,i=async()=>{let l=await t.redis.hgetall(Tf),u=[];for(let d of Object.values(l))try{u.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
83
+ `)}return r=u,o=n(),u},a=()=>r===null||n()-o>=e;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}var re=require("@prometheus-io/client"),Yl=require("http");var Xl=9464,Cr="/metrics",Bt="(other)",Zo="(none)",es=64,ts=128,Pf=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/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",fr,vn,Ze],Cf=new Set(Pf);function ns(t){return Cf.has(t)?t:Bt}function rs(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var jt=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?Zo:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,Bt):(this.admitted.add(e),e):Bt}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},qt=class{registry=new re.Registry;modelLabel=new jt(es);orgLabel=new jt(ts);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new re.Gauge({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new re.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 re.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 re.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 re.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 re.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 re.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 Ya)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new re.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"},Xa()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Qa()/1e3)}}),this.labelCardinality=new re.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 re.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]}),this.lanesReady=new re.Gauge({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new re.Histogram({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new re.Histogram({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new re.Counter({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new re.Counter({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&(0,re.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=ns(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 l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?Bt:e.method,status_class:rs(e.status),stream:l,model:s,org:i}),this.duration.observe({lane:n,stream:l,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 Lr(t){return(0,Yl.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Cr){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Cr}
84
84
  `);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)}
85
- `);return}n.end()})})}var wu=de(require("ioredis"),1);var ts=require("crypto"),Jl=require("http"),Vl=9465,ns="x-urun-key-id",rs="x-urun-key-fingerprint",os="urun-ratelimit-bucket:",ss="urun-ratelimit-tier:",Cr="anonymous",Sf=/^urun_sk_[A-Za-z0-9_-]{43}$/;function is(t){return(0,ts.createHash)("sha256").update(`${os}${t}`).digest("hex")}function as(t){return(0,ts.createHash)("sha256").update(`${ss}${t}`).digest("hex")}function ls(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Sf.test(n)?n:null}function Lr(){return(0,Jl.createServer)((t,e)=>{let n=ls(t.headers.authorization);e.setHeader(ns,n===null?Cr:is(n)),e.setHeader(rs,n===null?Cr:as(n)),e.writeHead(200),e.end()})}var Mr=require("@urun-sh/core"),Nr=require("crypto"),Kl="urun-session-gateway",kf="machine",Rf=3e5;function Ef(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var Q=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},An=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},we=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function qt(t){let e=(t??"").trim();if(e==="")throw new Q("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 Q("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var xf=60,us=6e4,ds=4096;function Af(t){return t===401||t===403}var jt=class{constructor(e){this.opts=e;this.mint=e.mint??Mr.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new Q("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<us)return{apiKey:e,orgId:n.orgId,credential:"api-key",...n.billingAudience!==void 0?{billingAudience:n.billingAudience}:{},...n.creditsAdmissionOk!==void 0?{creditsAdmissionOk:n.creditsAdmissionOk}:{},...n.creditsRefusalReason!==void 0?{creditsRefusalReason:n.creditsRefusalReason}:{}};let r,o;try{let s=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:xf});r=s.orgId,o={...s.billingAudience!==void 0?{billingAudience:s.billingAudience}:{},...s.creditsAdmissionOk!==void 0?{creditsAdmissionOk:s.creditsAdmissionOk}:{},...s.creditsRefusalReason!==void 0?{creditsRefusalReason:s.creditsRefusalReason}:{}}}catch(s){throw s instanceof Mr.ClientTokenError&&Af(s.status)?(this.cache.delete(e),new Q("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new we("the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the API key against the control plane at ${this.opts.gatewayUrl}: ${s instanceof Error?s.message:String(s)}`)}if(!r)throw new we("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>=ds){let s=this.cache.keys().next();s.done||this.cache.delete(s.value)}return this.cache.set(e,{orgId:r,at:this.now(),...o}),{apiKey:e,orgId:r,credential:"api-key",...o}}clear(){this.cache.clear()}};function zl(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var $r=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now}opts;fetchImpl;now;jwks=null;inFlight=null;async jwksKeys(e){if(!e&&this.jwks!==null&&this.now()-this.jwks.at<Rf)return this.jwks.keys;if(this.inFlight!==null)return this.inFlight;this.inFlight=(async()=>{let r=`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,o;try{o=await this.fetchImpl(r,{signal:AbortSignal.timeout(3e3)})}catch(i){throw new we("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`could not fetch the machine issuer's JWKS at ${r}: ${i instanceof Error?i.message:String(i)}`)}if(!o.ok)throw new we("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered HTTP ${o.status}`);let s;try{let i=await o.json();if(!Array.isArray(i.keys))throw new we("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered no "keys" array`);s=i.keys}catch(i){throw i instanceof we?i:new we("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered a body that is not JSON`)}return s})().finally(()=>{this.inFlight=null});let n=await this.inFlight;return this.jwks={keys:n,at:this.now()},n}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new Q("malformed machine token");let s,i;try{s=zl(n),i=zl(r)}catch{throw new Q("malformed machine token")}if(s.alg!=="RS256")throw new Q(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new Q(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(i.aud!==Kl)throw new Q(`machine token audience must be ${Kl} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==kf)throw new Q(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new Q("machine token carries no org_id \u2014 no tenancy to route by");if((typeof i.exp=="number"?i.exp:0)<=Math.floor(this.now()/1e3))throw new Q("machine token is expired \u2014 re-mint and retry");let c=w=>w.kty==="RSA"&&w.n!==void 0&&w.e!==void 0,p=await this.jwksKeys(!1),m=a===""?void 0:p.find(w=>w.kid===a&&c(w));if(m===void 0&&(p=await this.jwksKeys(!0),m=a===""?void 0:p.find(w=>w.kid===a&&c(w))),m===void 0)throw new Q(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let h=Buffer.from(`${n}.${r}`,"ascii"),v=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),S=!1;try{let w=(0,Nr.createPublicKey)({key:m,format:"jwk"});S=(0,Nr.verify)("RSA-SHA256",h,w,v)}catch{S=!1}if(!S)throw new Q("machine token signature failed verification");return{apiKey:e,orgId:u,credential:"machine"}}};function cs(t,e,n){return n!==null&&Ef(t)?n.verify(t):e.resolve(t)}var On=require("crypto");var ce=require("@urun-sh/core");async function Yl(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,serve_app_slug,serve_function,created_at,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 Xl=require("@urun-sh/core"),ps=2;function If(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Of(t){let e=t?.type;return e==="response.completed"||e==="error"}function Ql(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=ps;i++){let{app:a,entry:l,identity:u}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(l)??null,identity:u});let d=!1,c=!1;try{let p=await t.createStream(l,n);for await(let m of p){if(Of(m)&&(d=!0),If(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof Xl.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,l,p)}catch{}throw p}if(i<ps&&!c){await t.evict(a,l);continue}throw p}if(d)return;if(i<ps&&!c){await t.evict(a,l);continue}return}})()}}var gs=require("crypto");var Zl=require("@urun-sh/core"),Tf="audio";function eu(t){let e=t.streamEndpoint(Tf);return{sessionId:t.id,appendInputAudio(n){let r=Buffer.from(n,"base64");r.byteLength!==0&&e.send((0,Zl.encodeStreamEnvelope)(new Uint8Array(r)))},onOutputAudio(){return()=>{}}}}var Cf=0,Lf=4,$f=4;function tu(t,e){let n=(i,a)=>{let l=(t[i]??"").trim();if(!l)return a;let u=Number.parseInt(l,10);if(!Number.isInteger(u)||u<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return u},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Cf;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let s=n("URUN_DECISION_POOL_MAX",Math.max(o,Lf));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",$f),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function fs(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 nu(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,l=t.sessionStartOptions?.(n),u=r||l||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...l,...r}:void 0,d=v=>({session:v,responses:new dt(v),gone:Ar(v,n)});if(i.lane==="jwt"){let v=(0,ce.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(fs(v,e.appSlug,a,u))}if(i.lane==="machine"){let{machineToken:v,gatewayUrl:S}=i,w=(typeof t.subject=="function"?t.subject():t.subject)??(0,gs.randomUUID)(),f=(0,ce.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,ce.createClientToken)(v,{baseUrl:S,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:w,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(fs(f,e.appSlug,a,u))}let{apiKey:c,gatewayUrl:p}=i,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,gs.randomUUID)(),h=(0,ce.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,ce.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(fs(h,e.appSlug,a,u))}function ru(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 ou(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 Mf=new Set(["error","paused"]);function hs(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let l=nu(t,i,a);return t.onSessionOpen&&typeof l.session.id=="string"&&l.session.id!==""&&t.onSessionOpen(a,l.session.id),l.gone.onGone(()=>{r?.evict(a,l)}),l},s=new jn({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"?()=>Ai({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>Yl(n):null),listPrices:n?()=>ci(n):null,shared:e.lane==="api-key"?()=>ii({apiUrl:t.apiUrl,apiKey:e.apiKey}):e.lane==="machine"&&t.catalogRows?async()=>{let i=await t.catalogRows();return si(i)}:null,sessionKey:ru});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},je({appSlug:t.defaultApp}))),s}function su(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,a=d=>{process.stderr.write(`[decision-pool] ${d}
86
- `)},l=(d,c)=>{let p=o.get(c);if(p)return p;let m=new qn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async h=>{let v=nu(t,d,c,{concurrencyKey:h.concurrencyKey});return v.gone.onGone(()=>m.markSessionDead(v)),await Dr(v.session),a(`slot attached pool=${c} slot=${h.concurrencyKey} session=${v.session.id??"(no id)"}`),v},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,v)=>a(`slot detached pool=${c} slot=${h.concurrencyKey} reason=${v}`),terminalOpenFailure:h=>h instanceof ce.SessionFailedError&&ou(h)});return s.set(c,{target:d,env:n}),o.set(c,m),m},u=async(d,c)=>{let p=s.get(c);if(p)try{let m=await e.poolTuningFor(d);l(d,c).retune({min:m?.min??p.env.min,max:m?.max??p.env.max,inFlightCap:m?.in_flight_cap??p.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){a(`pool tuning refresh failed pool=${c} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await l(d,je(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=je(c),m=l(c,p);await u(c,p);let h=await m.acquire({timeoutMs:m.requestWaitMs}),v=i.get(h.entry)??[];return v.push(h),i.set(h.entry,v),{app:p,entry:h.entry,identity:Bn(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await l(c,je(c)).boot()},end(d){let c=i.get(d)?.shift();c&&(i.get(d)?.length===0&&i.delete(d),c.release())},evict(d){for(let c of o.values())c.evict(d)},markSessionDead(d){for(let c of o.values())c.markSessionDead(d)},reap(){for(let[d,{target:c}]of s)u(c,d).then(()=>{let p=o.get(d);p&&p.reap()})},async pingReady(d){for(let c of o.values())if(await c.pingReady(d))return!0;return!1},stats(){return[...o.entries()].map(([d,c])=>({poolKey:d,...c.stats()}))},async drain(d){await Promise.all([...o.values()].map(c=>c.drain({timeoutMs:d})))},async close(){await Promise.all([...o.values()].map(d=>d.close()))}}}function Nf(t){return(0,ce.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?ce.DEFAULT_WHEN_LIVE_TIMEOUT_MS:ce.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:ce.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Dr(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,{timeout:Nf(t.phase),signal:e})}async function ms(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 ys(t,e=Fs,n,r,o=po,s){let i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakMap,c=f=>{let g=f.session.id;return typeof g=="string"&&g.length>0?g:null},p="lane",m=f=>{let g=nn(f);if(!s||!g||g.app!==p)return null;let y=s.entryFor(g.key);if(!y)throw new F(`the lane behind this handle (${g.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:g.key,entry:y}},h=async f=>m(f)?.entry??(await t.sessionForHandle(f)).entry,v=f=>{let g=i.get(f);if(!g){let y={waiting:0,gone:new AbortController};d.set(f,y),g=(async()=>{if(await Dr(f.session,y.gone.signal),y.gone.signal.aborted)throw Ur(y.gone.signal);d.get(f)===y&&d.delete(f);let _=await Us(f.session,await e());return Object.assign(_,{sessionId:f.session.id})})(),i.set(f,g),g.catch(()=>{i.get(f)===g&&i.delete(f)}),g.then(()=>{d.get(f)===y&&d.delete(f)},()=>{d.get(f)===y&&d.delete(f)})}return g},S=f=>{let g=u.get(f);return g||(g=(async()=>{let y=await v(f);return{appendInputAudio:_=>y.appendInputAudio(_),onOutputAudio:_=>y.onOutputAudio(_),sessionId:c(f)}})(),u.set(f,g),g.catch(()=>{u.get(f)===g&&u.delete(f)})),g},w=async(f,g,y)=>{if(y?.aborted){let A=d.get(f);throw(i.get(f)===void 0||A!==void 0&&A.waiting===0)&&await ms(f.session),Ur(y)}let _=g(f),I=d.get(f);return I!==void 0&&I.waiting++,y===void 0?_:new Promise((A,b)=>{let R=()=>{I!==void 0&&--I.waiting===0&&d.get(f)===I&&(I.gone.abort(),d.delete(f),i.delete(f),u.delete(f),ms(f.session).catch(()=>{})),b(Ur(y))};y.addEventListener("abort",R,{once:!0});let k=()=>y.removeEventListener("abort",R);_.then(E=>{k(),A(E)},E=>{k(),b(E)})})};return{createResponse:Ql({sessionFor:s?async f=>{let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g);return{app:y.app,entry:y.entry,identity:y.identity}}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(f,g)},onAdmissionVerdict:(f,g,y)=>{ou(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(f,g),n?.(f,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,g)=>{try{await Dr(f.session);let y=Bi(Wo(await f.responses.responses.create(g),f.gone),o);if(!r&&!s)return y;let _=f;return(async function*(){try{yield*y}catch(A){throw ji(A)&&(s&&s.owns(_)?s.evict(_):r&&(A instanceof F?r.markSessionDead(_):r.evict(_))),A}finally{s&&s.owns(_)?s.release(_):r?.end(_)}})()}catch(y){throw s&&s.owns(f)?s.release(f):r&&r.end(f),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,g)=>t.supportsImages(f,g),listImageModels:()=>t.imageModelList(),catalogIdentity:f=>t.catalogIdentityFor(f),servingAppSlug:async f=>await t.servingAppSlugFor(f),supportsAudio:f=>t.supportsAudio(f),supportsSpeech:f=>t.supportsSpeech(f),speechVoices:f=>t.speechVoices(f),supportsTranscription:f=>t.supportsTranscription(f),transcriptStreamFor:f=>t.transcriptStreamFor(f),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(f,g)=>{let{entry:y}=await t.sessionFor(f);return await w(y,v,g)},openAudioOn:async(f,g,y)=>{let _=m(f);if(_){let A=_.entry.session;return eu(A)}let{entry:I}=await t.sessionForHandle(f);return await w(I,S,g)},openTurnsOn:async function*(f,g){if(g?.aborted)throw Ur(g);let y=await h(f);yield*ki(y.session,g)},openVideo:async f=>{let{entry:g}=await t.sessionFor(f),y=a.get(g);return y||(y=Ds(g.session),a.set(g,y)),y},openVideoOut:async f=>{let{entry:g}=await t.sessionFor(f),y=l.get(g);return y||(y=Bs(g.session),l.set(g,y)),y},sessionHandle:async f=>{if(s){let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g),_=c(y.entry);if(_===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return tn(p,_)}}return(await t.handleFor(f)).handle},dedicatedSessionHandle:async f=>{if(!(await t.resolveTargetFor(f)).sharedApp)return(await t.handleFor(f)).handle;let{app:y,entry:_}=await t.dedicatedSessionFor(f);return tn(y,ru(_))},releaseSessionHandle:f=>{let g=nn(f);if(!g)return;if(g.app.startsWith(yt)){(async()=>{let _=null;try{_=(await t.sessionForHandle(f)).entry}catch{return}await ms(_.session).catch(()=>{}),await t.evict(g.app,_)})();return}if(!s||g.app!==p)return;let y=s.entryFor(g.key);y&&s.release(y)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:g,entry:y}=await t.sessionForHandle(f);await t.evict(g,y)},createResponseOn:async(f,g,y)=>{let _=await h(f);await Dr(_.session);let I=y!==void 0&&m(f)?new dt({..._.session,consumerId:y},{sessionTag:y}):_.responses;return Wo(await I.responses.create(g),_.gone)},onSessionEnd:async(f,g)=>{let y=m(f);if(y)return y.entry.gone.onGone(b=>g({timeLeftMs:null,reason:b.message}));let{entry:_}=await t.sessionForHandle(f),I=_.session;if(typeof I.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let A=!1;return I.onPhase(b=>{if(A||!Mf.has(b.name))return;A=!0;let R=I.endsAt??null;g({timeLeftMs:R?Math.max(0,R.getTime()-Date.now()):null,reason:b.reason??`session ${b.name}`})})}}}var au=require("http");var Uf="/pooler/v1/inference",Gt=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Df=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},Ff=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},lu=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),Hf=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await lu(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new Gt(t.status,e,n,t.retryAfterSeconds)};async function Bf(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${Uf}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Df(e),firstMessage:Ff(e)}});return new Promise((a,l)=>{let u=(0,au.request)({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let c=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(c)?c:void 0,body:d})});u.on("error",d=>l(new Gt(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var iu=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*jf(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
85
+ `);return}n.end()})})}var Eu=ce(require("ioredis"),1);var os=require("crypto"),Ql=require("http"),Zl=9465,ss="x-urun-key-id",is="x-urun-key-fingerprint",as="urun-ratelimit-bucket:",ls="urun-ratelimit-tier:",$r="anonymous",Lf=/^urun_sk_[A-Za-z0-9_-]{43}$/;function us(t){return(0,os.createHash)("sha256").update(`${as}${t}`).digest("hex")}function ds(t){return(0,os.createHash)("sha256").update(`${ls}${t}`).digest("hex")}function cs(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Lf.test(n)?n:null}function Mr(){return(0,Ql.createServer)((t,e)=>{let n=cs(t.headers.authorization);e.setHeader(ss,n===null?$r:us(n)),e.setHeader(is,n===null?$r:ds(n)),e.writeHead(200),e.end()})}var Ur=require("@urun-sh/core"),Dr=require("crypto"),eu="urun-session-gateway",$f="machine",Mf=3e5;function Nf(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var Z=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Tn=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},_e=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function Wt(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 Uf=60,ps=6e4,fs=4096;function Df(t){return t===401||t===403}var Gt=class{constructor(e){this.opts=e;this.mint=e.mint??Ur.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<ps)return{apiKey:e,orgId:n.orgId,credential:"api-key",...n.billingAudience!==void 0?{billingAudience:n.billingAudience}:{},...n.creditsAdmissionOk!==void 0?{creditsAdmissionOk:n.creditsAdmissionOk}:{},...n.creditsRefusalReason!==void 0?{creditsRefusalReason:n.creditsRefusalReason}:{}};let r,o;try{let s=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:Uf});r=s.orgId,o={...s.billingAudience!==void 0?{billingAudience:s.billingAudience}:{},...s.creditsAdmissionOk!==void 0?{creditsAdmissionOk:s.creditsAdmissionOk}:{},...s.creditsRefusalReason!==void 0?{creditsRefusalReason:s.creditsRefusalReason}:{}}}catch(s){throw s instanceof Ur.ClientTokenError&&Df(s.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 _e("the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the API key against the control plane at ${this.opts.gatewayUrl}: ${s instanceof Error?s.message:String(s)}`)}if(!r)throw new _e("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>=fs){let s=this.cache.keys().next();s.done||this.cache.delete(s.value)}return this.cache.set(e,{orgId:r,at:this.now(),...o}),{apiKey:e,orgId:r,credential:"api-key",...o}}clear(){this.cache.clear()}};function tu(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var Nr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now}opts;fetchImpl;now;jwks=null;inFlight=null;async jwksKeys(e){if(!e&&this.jwks!==null&&this.now()-this.jwks.at<Mf)return this.jwks.keys;if(this.inFlight!==null)return this.inFlight;this.inFlight=(async()=>{let r=`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,o;try{o=await this.fetchImpl(r,{signal:AbortSignal.timeout(3e3)})}catch(i){throw new _e("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`could not fetch the machine issuer's JWKS at ${r}: ${i instanceof Error?i.message:String(i)}`)}if(!o.ok)throw new _e("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered HTTP ${o.status}`);let s;try{let i=await o.json();if(!Array.isArray(i.keys))throw new _e("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered no "keys" array`);s=i.keys}catch(i){throw i instanceof _e?i:new _e("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered a body that is not JSON`)}return s})().finally(()=>{this.inFlight=null});let n=await this.inFlight;return this.jwks={keys:n,at:this.now()},n}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new Z("malformed machine token");let s,i;try{s=tu(n),i=tu(r)}catch{throw new Z("malformed machine token")}if(s.alg!=="RS256")throw new Z(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new Z(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(i.aud!==eu)throw new Z(`machine token audience must be ${eu} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==$f)throw new Z(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new Z("machine token carries no org_id \u2014 no tenancy to route by");if((typeof i.exp=="number"?i.exp:0)<=Math.floor(this.now()/1e3))throw new Z("machine token is expired \u2014 re-mint and retry");let c=v=>v.kty==="RSA"&&v.n!==void 0&&v.e!==void 0,p=await this.jwksKeys(!1),h=a===""?void 0:p.find(v=>v.kid===a&&c(v));if(h===void 0&&(p=await this.jwksKeys(!0),h=a===""?void 0:p.find(v=>v.kid===a&&c(v))),h===void 0)throw new Z(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let m=Buffer.from(`${n}.${r}`,"ascii"),_=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),b=!1;try{let v=(0,Dr.createPublicKey)({key:h,format:"jwk"});b=(0,Dr.verify)("RSA-SHA256",m,v,_)}catch{b=!1}if(!b)throw new Z("machine token signature failed verification");return{apiKey:e,orgId:u,credential:"machine"}}};function ms(t,e,n){return n!==null&&Nf(t)?n.verify(t):e.resolve(t)}var Cn=require("crypto");var ie=require("@urun-sh/core");async function nu(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,serve_app_slug,serve_function,created_at,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 ru=require("@urun-sh/core"),gs=2;function Ff(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Hf(t){let e=t?.type;return e==="response.completed"||e==="error"}function ou(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=gs;i++){let{app:a,entry:l,identity:u}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(l)??null,identity:u});let d=!1,c=!1;try{let p=await t.createStream(l,n);for await(let h of p){if(Hf(h)&&(d=!0),Ff(h)){if(i>1)continue}else c=!0;yield h}}catch(p){if(p instanceof ru.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,l,p)}catch{}throw p}if(i<gs&&!c){await t.evict(a,l);continue}throw p}if(d)return;if(i<gs&&!c){await t.evict(a,l);continue}return}})()}}var ws=require("crypto");var su=require("@urun-sh/core"),Bf="audio";function iu(t){let e=t.streamEndpoint(Bf);return{sessionId:t.id,appendInputAudio(n){let r=Buffer.from(n,"base64");r.byteLength!==0&&e.send((0,su.encodeStreamEnvelope)(new Uint8Array(r)))},onOutputAudio(){return()=>{}}}}var au=require("@urun-sh/core"),jf="rt-video-in";function lu(t){let e=t.streamEndpoint(jf);return{sendInputFrame:async n=>{e.send((0,au.encodeStreamEnvelope)(n))}}}var Gf=0,Wf=4,Vf=4;function uu(t,e){let n=(i,a)=>{let l=(t[i]??"").trim();if(!l)return a;let u=Number.parseInt(l,10);if(!Number.isInteger(u)||u<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return u},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Gf;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let s=n("URUN_DECISION_POOL_MAX",Math.max(o,Wf));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Vf),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function hs(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 du(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,l=t.sessionStartOptions?.(n),u=r||l||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...l,...r}:void 0,d=_=>({session:_,responses:new ct(_),gone:Or(_,n)});if(i.lane==="jwt"){let _=(0,ie.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(hs(_,e.appSlug,a,u))}if(i.lane==="machine"){let{machineToken:_,gatewayUrl:b}=i,v=(typeof t.subject=="function"?t.subject():t.subject)??(0,ws.randomUUID)(),R=(0,ie.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,ie.createClientToken)(_,{baseUrl:b,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:v,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(hs(R,e.appSlug,a,u))}let{apiKey:c,gatewayUrl:p}=i,h=(typeof t.subject=="function"?t.subject():t.subject)??(0,ws.randomUUID)(),m=(0,ie.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,ie.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:h,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(hs(m,e.appSlug,a,u))}function cu(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 _s(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 Jf=new Set(["error","paused"]);function vs(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let l=du(t,i,a);return t.onSessionOpen&&typeof l.session.id=="string"&&l.session.id!==""&&t.onSessionOpen(a,l.session.id),l.gone.onGone(()=>{r?.evict(a,l)}),l},s=new Gn({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"?()=>Oi({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>nu(n):null),listPrices:n?()=>fi(n):null,shared:e.lane==="api-key"?()=>li({apiUrl:t.apiUrl,apiKey:e.apiKey}):e.lane==="machine"&&t.catalogRows?async()=>{let i=await t.catalogRows();return ai(i)}:null,sessionKey:cu});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},je({appSlug:t.defaultApp}))),s}function pu(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,a=d=>{process.stderr.write(`[decision-pool] ${d}
86
+ `)},l=(d,c)=>{let p=o.get(c);if(p)return p;let h=new Wn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async m=>{let _=du(t,d,c,{concurrencyKey:m.concurrencyKey});return _.gone.onGone(()=>h.markSessionDead(_)),await Hr(_.session),a(`slot attached pool=${c} slot=${m.concurrencyKey} session=${_.session.id??"(no id)"}`),_},closeSlot:async m=>{m.gone.dispose(),await m.session.end()},onDetach:(m,_)=>a(`slot detached pool=${c} slot=${m.concurrencyKey} reason=${_}`),terminalOpenFailure:m=>m instanceof ie.SessionFailedError&&_s(m)});return s.set(c,{target:d,env:n}),o.set(c,h),h},u=async(d,c)=>{let p=s.get(c);if(p)try{let h=await e.poolTuningFor(d);l(d,c).retune({min:h?.min??p.env.min,max:h?.max??p.env.max,inFlightCap:h?.in_flight_cap??p.env.inFlightCap,idleGraceMs:h?.idle_grace_s!==void 0?h.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:h?.warm_wait_s!==void 0?h.warm_wait_s*1e3:void 0})}catch(h){a(`pool tuning refresh failed pool=${c} reason=${h instanceof Error?h.message:String(h)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await l(d,je(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=je(c),h=l(c,p);await u(c,p);let m=await h.acquire({timeoutMs:h.requestWaitMs}),_=i.get(m.entry)??[];return _.push(m),i.set(m.entry,_),{app:p,entry:m.entry,identity:qn(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await l(c,je(c)).boot()},end(d){let c=i.get(d)?.shift();c&&(i.get(d)?.length===0&&i.delete(d),c.release())},evict(d){for(let c of o.values())c.evict(d)},markSessionDead(d){for(let c of o.values())c.markSessionDead(d)},reap(){for(let[d,{target:c}]of s)u(c,d).then(()=>{let p=o.get(d);p&&p.reap()})},async pingReady(d){for(let c of o.values())if(await c.pingReady(d))return!0;return!1},stats(){return[...o.entries()].map(([d,c])=>({poolKey:d,...c.stats()}))},async drain(d){await Promise.all([...o.values()].map(c=>c.drain({timeoutMs:d})))},async close(){await Promise.all([...o.values()].map(d=>d.close()))}}}function Kf(t){return(0,ie.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?ie.DEFAULT_WHEN_LIVE_TIMEOUT_MS:ie.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:ie.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Hr(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,{timeout:Kf(t.phase),signal:e})}async function ys(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 Fr(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function bs(t,e=Bs,n,r,o=go,s){let i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakMap,c=f=>{let g=f.session.id;return typeof g=="string"&&g.length>0?g:null},p="lane",h=f=>{let g=an(f);if(!s||!g||g.app!==p)return null;let y=s.entryFor(g.key);if(!y)throw new F(`the lane behind this handle (${g.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:g.key,entry:y}},m=async f=>h(f)?.entry??(await t.sessionForHandle(f)).entry,_=f=>{let g=i.get(f);if(!g){let y={waiting:0,gone:new AbortController};d.set(f,y),g=(async()=>{if(await Hr(f.session,y.gone.signal),y.gone.signal.aborted)throw Fr(y.gone.signal);d.get(f)===y&&d.delete(f);let S=await Hs(f.session,await e());return Object.assign(S,{sessionId:f.session.id})})(),i.set(f,g),g.catch(()=>{i.get(f)===g&&i.delete(f)}),g.then(()=>{d.get(f)===y&&d.delete(f)},()=>{d.get(f)===y&&d.delete(f)})}return g},b=f=>{let g=u.get(f);return g||(g=(async()=>{let y=await _(f);return{appendInputAudio:S=>y.appendInputAudio(S),onOutputAudio:S=>y.onOutputAudio(S),sessionId:c(f)}})(),u.set(f,g),g.catch(()=>{u.get(f)===g&&u.delete(f)})),g},v=async(f,g,y)=>{if(y?.aborted){let w=d.get(f);throw(i.get(f)===void 0||w!==void 0&&w.waiting===0)&&await ys(f.session),Fr(y)}let S=g(f),A=d.get(f);return A!==void 0&&A.waiting++,y===void 0?S:new Promise((w,E)=>{let k=()=>{A!==void 0&&--A.waiting===0&&d.get(f)===A&&(A.gone.abort(),d.delete(f),i.delete(f),u.delete(f),ys(f.session).catch(()=>{})),E(Fr(y))};y.addEventListener("abort",k,{once:!0});let I=()=>y.removeEventListener("abort",k);S.then(x=>{I(),w(x)},x=>{I(),E(x)})})},R=async(f,g,y)=>{try{return await y}catch(S){throw(S instanceof F||S instanceof ie.SessionFailedError&&_s(S))&&(t.evict(f,g),S instanceof ie.SessionFailedError&&n?.(f,S.kind==="never-live"?"never-live":"create-failed")),S}};return{createResponse:ou({sessionFor:s?async f=>{let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g);return{app:y.app,entry:y.entry,identity:y.identity}}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(f,g)},onAdmissionVerdict:(f,g,y)=>{_s(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(f,g),n?.(f,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,g)=>{try{await Hr(f.session);let y=qi(Ko(await f.responses.responses.create(g),f.gone),o);if(!r&&!s)return y;let S=f;return(async function*(){try{yield*y}catch(w){throw Gi(w)&&(s&&s.owns(S)?s.evict(S):r&&(w instanceof F?r.markSessionDead(S):r.evict(S))),w}finally{s&&s.owns(S)?s.release(S):r?.end(S)}})()}catch(y){throw s&&s.owns(f)?s.release(f):r&&r.end(f),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,g)=>t.supportsImages(f,g),listImageModels:()=>t.imageModelList(),catalogIdentity:f=>t.catalogIdentityFor(f),servingAppSlug:async f=>await t.servingAppSlugFor(f),supportsAudio:f=>t.supportsAudio(f),supportsSpeech:f=>t.supportsSpeech(f),speechVoices:f=>t.speechVoices(f),supportsTranscription:f=>t.supportsTranscription(f),transcriptStreamFor:f=>t.transcriptStreamFor(f),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(f,g)=>{let{app:y,entry:S}=await t.sessionFor(f);return await R(y,S,v(S,_,g))},openAudioOn:async(f,g,y)=>{let S=h(f);if(S){let E=S.entry.session;return iu(E)}let{app:A,entry:w}=await t.sessionForHandle(f);return await R(A,w,v(w,b,g))},openTurnsOn:async function*(f,g){if(g?.aborted)throw Fr(g);let y=await m(f);yield*Ei(y.session,g)},openVideoOn:async f=>{let g=h(f);if(g)return lu(g.entry.session);let{entry:y}=await t.sessionForHandle(f),S=a.get(y);return S||(S=Jr(y.session),a.set(y,S)),S},openVideo:async f=>{let{entry:g}=await t.sessionFor(f),y=a.get(g);return y||(y=Jr(g.session),a.set(g,y)),y},openVideoOut:async f=>{let{entry:g}=await t.sessionFor(f),y=l.get(g);return y||(y=qs(g.session),l.set(g,y)),y},sessionHandle:async f=>{if(s){let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g),S=c(y.entry);if(S===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return sn(p,S)}}return(await t.handleFor(f)).handle},dedicatedSessionHandle:async f=>{if(!(await t.resolveTargetFor(f)).sharedApp)return(await t.handleFor(f)).handle;let{app:y,entry:S}=await t.dedicatedSessionFor(f);return sn(y,cu(S))},releaseSessionHandle:f=>{let g=an(f);if(!g)return;if(g.app.startsWith(_t)){(async()=>{let S=null;try{S=(await t.sessionForHandle(f)).entry}catch{return}await ys(S.session).catch(()=>{}),await t.evict(g.app,S)})();return}if(!s||g.app!==p)return;let y=s.entryFor(g.key);y&&s.release(y)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:g,entry:y}=await t.sessionForHandle(f);await t.evict(g,y)},createResponseOn:async(f,g,y)=>{let S=await m(f);await Hr(S.session);let A=y!==void 0&&h(f)?new ct({...S.session,consumerId:y},{sessionTag:y}):S.responses;return Ko(await A.responses.create(g),S.gone)},onSessionEnd:async(f,g)=>{let y=h(f);if(y)return y.entry.gone.onGone(E=>g({timeLeftMs:null,reason:E.message}));let{entry:S}=await t.sessionForHandle(f),A=S.session;if(typeof A.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let w=!1;return A.onPhase(E=>{if(w||!Jf.has(E.name))return;w=!0;let k=A.endsAt??null;g({timeLeftMs:k?Math.max(0,k.getTime()-Date.now()):null,reason:E.reason??`session ${E.name}`})})}}}var mu=require("http");var zf="/pooler/v1/inference",Vt=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Yf=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},Xf=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},gu=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),Qf=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await gu(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new Vt(t.status,e,n,t.retryAfterSeconds)};async function Zf(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${zf}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Yf(e),firstMessage:Xf(e)}});return new Promise((a,l)=>{let u=(0,mu.request)({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let c=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(c)?c:void 0,body:d})});u.on("error",d=>l(new Vt(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var fu=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*em(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
87
87
 
88
- `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=iu(s);i!==null&&(yield i)}let n=iu(e);n!==null&&(yield n)}async function uu(t,e,n,r){let o=vr(e,n,r),s=o.model??"";if(s==="")throw new Gt(400,"missing_model","the pooler submit requires a model");let i=await Bf(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Hf(i);let a=e.stream===!0?Sr(n,jf(i)):await qf(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function qf(t,e){let n=await lu(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new Gt(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Sr(e,(async function*(){yield o})())}var ws=8080,In="serve",du="0.0.0.0";function Gf(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function cu(t=process.env){let e=(t.PORT??"").trim(),n=e===""?ws: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=Vi(Kn(Gf(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?Kn(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 l=i?{catalogUrl:Kn(i,"URUN_CATALOG_URL"),anonKey:a}:null,u=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!u!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let c=u?{keyId:d,key:u}:void 0,p={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},m=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],h=m.filter((k,E)=>Object.values(p)[E]==="");if(h.length!==0&&h.length!==m.length)throw new Error(`${m.join(", ")} must be set together (or all left unset) \u2014 missing: ${h.join(", ")}, which would half-configure the lane plane`);let v=h.length===0?p:void 0,S={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},w=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],f=w.filter((k,E)=>Object.values(S)[E]==="");if(f.length!==0&&f.length!==w.length)throw new Error(`${w.join(", ")} must be set together (or all left unset) \u2014 missing: ${f.join(", ")}, which would half-configure the pooler cutover`);let g=f.length===0?S:void 0,y={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},_=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],I=_.filter((k,E)=>Object.values(y)[E]==="");if(I.length!==0&&I.length!==_.length)throw new Error(`${_.join(", ")} must be set together (or all left unset) \u2014 missing: ${I.join(", ")}, which would half-configure the machine-identity rung`);let A=y.issuers.split(",").map(k=>k.trim()).filter(k=>k!=="");if(A.length===0&&I.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let b=Number(y.tokenTtlS);if(I.length===0&&(!Number.isFinite(b)||b<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(y.tokenTtlS)}`);let R=I.length===0?{jwksBaseUrl:y.jwksBaseUrl,issuers:A,tokenTtlS:b}:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:l,ledgerSigning:c,lane:v,pooler:g,machine:R}}var _s=512;function Tn(t){return`urun-inference-proxy-${(0,On.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Wt=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),s=this.opts.pooler;if(s===void 0)return o;let i=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,l)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)try{return await o.createResponse(a,l)}catch(c){if(!(c instanceof se))throw c}let u=`px_${(0,On.randomUUID)()}`;return uu(s,a,u,u)}})}build(e){if(this.opts.build){let s=this.opts.build(e);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,e,s.router),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:In,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:tu(process.env,process.env.HOSTNAME)??void 0},r=hs(n),o=n.decisionPool?su(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(ys(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e,r),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;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>=_s;){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}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(s=>{n.push(String(s instanceof Error?s.message:s))})];r.decision&&o.push(r.decision.close().catch(s=>{n.push(String(s instanceof Error?s.message:s))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Fr=512,vs=1024,Jt=class extends Error{constructor(){super(`conversation capacity reached (${Fr} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Wf(t){return{sessionStartOptions:e=>{if(e.startsWith(rn)||e.startsWith(yt))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(rn)||e.startsWith(yt)||t.set(e,n)}}}function Jf(t,e,n,r){let o=hs({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:In,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...Wf(r)});return{clients:ys(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var Vt=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${Tn(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):Jf(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>=Fr;){let e=this.byCaller.keys().next();if(e.done)throw new Jt;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 Jt;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),dedicatedSessionHandle:i=>{let a=o().backhaul.clients.dedicatedSessionHandle;return a===void 0?o().backhaul.clients.sessionHandle(i):a(i)},releaseSessionHandle:i=>o().backhaul.clients.releaseSessionHandle?.(i),createResponseOn:(i,a,l)=>o().backhaul.clients.createResponseOn(i,a,l),onSessionEnd:(i,a)=>o().backhaul.clients.onSessionEnd(i,a)};return s.openAudio=async(i,a)=>{let l=o().backhaul.clients.openAudio;if(l===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return l(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,l)=>{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,l)},s.openTurnsOn=(i,a)=>{let l=o().backhaul.clients.openTurnsOn;if(l===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return l(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.transcriptStreamFor=async i=>{let a=o().backhaul.clients.transcriptStreamFor;if(a===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream 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>=vs;){let l=this.byHandle.keys().next();if(l.done)break;this.byHandle.delete(l.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async i=>{let a=this.byHandle.get(i),l=a===void 0?void 0:this.byCaller.get(a.apiKey),u=a===void 0||l===void 0?void 0:l.get(a.conversationId);if(a===void 0||u===void 0||a.apiKey!==e.apiKey)throw new F("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=u,u.attachments+=1,u.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 Hr="/inference-usage",pu=25e3;var Vf=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function fu(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Vf.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 Br=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Hr}`,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(pu)})}catch(i){throw new te(`the uRun usage surface (POST ${Hr}) could not be reached within ${pu}ms: ${fu(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new Q("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 te(`the uRun usage surface (POST ${Hr}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new te(`the uRun usage surface (POST ${Hr}) answered HTTP ${o.status} with a body that is not JSON: ${fu(i)}`)}return ja(s,this.opts.onRejectedRow)}};var xs="/inference-ledger",As=1e4,Kt=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},ks=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},ie=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Rs=class extends Q{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Es=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Kf=[["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",bs],["output_minutes",bs],["cost_nano_usd",bs],["price_version",t=>t===null||typeof t=="string"]];function zf(t){for(let[e,n]of Kf){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Yf(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"}:zf(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function bs(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Ss(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Xf(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function mu(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 Qf(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&&mu(t.started_at,n.started_at)&&mu(t.completed_at,n.completed_at)&&Ss(t.prompt_tokens,n.prompt_tokens)&&Ss(t.completion_tokens,n.completion_tokens)&&Ss(t.output_units,n.output_units)&&Xf(t.output_minutes,n.output_minutes)}function Zf(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
89
- `)}async function em(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(Zf(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Is(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ie(`${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 ie(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new ie(`${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 ie(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=u=>{if(!(u in n))throw new ie(`${e} answered a row with no ${u} field: ${JSON.stringify(t)}`);let d=n[u];if(d===null)return null;if(typeof d!="string")throw new ie(`${e} answered a non-string ${u}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new ie(`${e} answered a BLANK ${u} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},i=s("price_version"),a=s("unpriced_reason"),l=o!=null;if(l&&(i===null||a!==null))throw new ie(`${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(!l&&(i!==null||a===null))throw new ie(`${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 zt=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${xs}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await em(n,this.opts.signing)}):JSON.stringify(n)}catch(u){throw new ie(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${u instanceof Error?u.message:String(u)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(As)})}catch(u){throw new ie(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(s.status===409){let u=await s.text().catch(()=>""),d=Yf(u);throw d.status==="found"&&Qf(n,d.row)?new ks(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 Kt(`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 Kt(`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(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new Rs("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(!s.ok){let u=await s.text().catch(c=>`<body unreadable: ${c instanceof Error?c.message:String(c)}>`),d;try{let c=JSON.parse(u);if(c!==null&&typeof c=="object"&&"error"in c){let p=c.error;p!==null&&typeof p=="object"&&"code"in p&&(d=p.code)}}catch{}throw d==="ledger_signature_invalid"?new Es(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+u.slice(0,400)):new ie(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${u.slice(0,400)}`)}let i;try{i=await s.json()}catch(u){throw new ie(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let a=i?.recorded;if(a===void 0)throw new ie(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=Is(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new ie(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};var Os=5e3,tm=1e3,nm=1500,Ts=3e3,rm="/api/client-tokens";function jr(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function gu(t,e,n,r){jr(t,e,{error:{message:n,type:r}})}async function om(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${rm}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Ts)});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 _u(t){let e=t.resolver??new jt({gatewayUrl:t.baseUrl}),n=t.machine?new $r({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=new Bt(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,s=null,i=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let b=new wu.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),R=ql({redis:b});return{registry:Ol({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:Ll({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(E,x)=>o?.onHostedChange(E,x)??(()=>()=>{}),roomDoc:(E,x)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(E,x)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(E,x)=>R.rows().then(T=>{let $=no(T,x);return $?.warm_wait_s!==void 0?$.warm_wait_s*1e3:void 0})}),catalog:R,redis:b}})(),a=t.registry??new Wt({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry,pooler:t.pooler}),l=t.probeControlPlane??(()=>om(t.baseUrl)),u=async()=>{let b=null;for(let E of a.decisionPools()){b=E;break}if(!b)return null;let R=b.stats();if(R.some(E=>E.draining))return{ok:!1,detail:"decision pool draining"};if(R.every(E=>E.attached===0&&E.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let k=await b.pingReady(nm);return{ok:k,detail:k?"a decision slot answered its session ping":"no decision slot answered its session ping"}},d=t.usageClient??new Br({apiUrl:t.apiUrl}),c=t.ledgerClient??new zt({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),p=process.env.URUN_SHARED_ORG_ID?.trim(),m=process.env.URUN_SHARED_ORG_API_KEY?.trim();p&&m&&(async()=>{try{await a.decisionWarmerFor({orgId:p,apiKey:m})?.warmFor(wr)}catch(b){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(b instanceof Error?b.message:b)}
90
- `)}})();let h=async b=>cs(qt(b.headers.authorization),e,n),v=async b=>{let R=await h(b);if(R.billingAudience==="platform"&&R.creditsAdmissionOk===!1){let k=R.creditsRefusalReason;throw new An(k==="spend_cap_reached"||k==="insufficient_credits"?k:void 0)}return R},S=b=>b instanceof Q?{status:b.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:b instanceof An?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...b.code!==void 0?{code:b.code}:{}}:b instanceof we?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:b.detail}:null,w=al({clients:async b=>a.clientsFor(await v(b)),usage:{authorize:b=>qt(b.headers.authorization),lookup:(b,R)=>d.lookup(b,R)},statusOf:S,...t.requestLog?{requestLog:t.requestLog}:{},observe:b=>r.observe(b),ledger:{write:(b,R)=>c.write(qt(b.headers.authorization),R),observe:b=>r.observeLedger(b),...t.ledgerLog?{report:t.ledgerLog}:{}}}),f=null,g=null,y=(0,hu.createServer)((b,R)=>{let k=new URL(b.url??"/","http://localhost");(async()=>{if(b.method==="GET"&&k.pathname==="/healthz"){jr(R,200,{ok:!0});return}if(b.method==="GET"&&k.pathname==="/readyz"){let T=Date.now();if((!f||T-f.at>=Os)&&(f={at:T,...await l()}),!g||T-g.at>=tm){let q=await u();g=q===null?{at:T,ok:!0,detail:null}:{at:T,ok:q.ok,detail:q.detail}}let $=(f?.ready??!1)&&g.ok,D=g.detail===null?f?.detail??"control plane not yet probed":`${f?.detail??"control plane not yet probed"}; ${g.detail}`;jr(R,$?200:503,{ok:$,control_plane:D});return}if(b.method==="GET"&&k.pathname==="/lanez"){jr(R,200,{pools:i?await i.registry.status():null});return}let E=k.pathname==="/v1"||k.pathname.startsWith("/v1/"),x=k.pathname.startsWith("/partners/");if(!E&&!x){gu(R,404,`no route for ${b.method} ${k.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, /readyz and /lanez`,"invalid_request_error");return}w(b,R)})().catch(E=>{if(!R.headersSent){gu(R,500,String(E instanceof Error?E.message:E),"proxy_error");return}R.end()})}),_=t.conversations??new Vt({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry}),I=[so(y,{authenticate:async b=>{let R=await cs(b,e,n),k=_.connectionFor(R);return{clients:k.clients,scope:Tn(R.apiKey),onBindResumeHandle:k.bindResumeHandle,clientsForResume:k.clientsForResume,release:k.release}}}),yo(y,{clients:async b=>a.clientsFor(await v(b)),statusOf:S}).close,er(y,{resolver:{resolve:async(b,R)=>{let k=await v(b),E=_.connectionFor(k),x;try{x=await pl(Do(E.clients,t.realtimeCompanions),dl(b),R,cl(b))}catch($){throw E.release().catch(()=>{}),$}let T=x.release;return{...x,release:async()=>{await T?.(),await E.release()}}}}})];if(t.lane&&i){let b=t.lane,R=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=jl(y,{verifyToken:(E,x)=>Go(E,x,b.tokenSecret,void 0,R),selfAddress:b.selfAddress,laneTenantOf:E=>i.redis.get(`lane_tenant:${E}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:R,hostRegistry:{setHost:(E,x)=>i.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${E}`,x,String(Bl)),delHost:E=>i.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${E}`,b.selfAddress)}}),s=Rl(y,{verifyToken:(E,x)=>Go(E,x,b.tokenSecret,void 0,R),selfAddress:b.selfAddress,hostOf:async E=>{let x=await i.redis.get(`lane_hosts:${E}`);return x&&x.trim()!==""?x.trim():null},podToPodDial:(E,x,T)=>new Promise(($,D)=>{(async()=>{let q=await i.redis.get(`lane_tenant:${E}`),G=Rn(E,b.tokenSecret,void 0,void 0,q||void 0),Ce=`ws://${T}/stream/${encodeURIComponent(E)}/${encodeURIComponent(x)}?token=${encodeURIComponent(G)}`,J=new yu.default(Ce,xr(x));J.once("open",()=>$(J)),J.once("error",D)})().catch(D)})});let k=i;I.push(async()=>{await o.close(),await s.close(),await k.registry.close(),k.redis.quit().catch(()=>{})})}y.on("upgrade",(b,R)=>{let k=new URL(b.url??"/","http://localhost");k.pathname===Nn||k.pathname===go||k.pathname===mn||o!==null&&k.pathname.startsWith("/doc/")||s!==null&&k.pathname.startsWith("/stream/")||R.destroyed||(R.write(`HTTP/1.1 404 Not Found\r
88
+ `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=fu(s);i!==null&&(yield i)}let n=fu(e);n!==null&&(yield n)}async function hu(t,e,n,r){let o=Sr(e,n,r),s=o.model??"";if(s==="")throw new Vt(400,"missing_model","the pooler submit requires a model");let i=await Zf(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Qf(i);let a=e.stream===!0?Rr(n,em(i)):await tm(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function tm(t,e){let n=await gu(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new Vt(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Rr(e,(async function*(){yield o})())}var Ss=8080,Pn="serve",yu="0.0.0.0";function nm(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function wu(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Ss: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=zi(Yn(nm(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?Yn(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 l=i?{catalogUrl:Yn(i,"URUN_CATALOG_URL"),anonKey:a}:null,u=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!u!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let c=u?{keyId:d,key:u}:void 0,p={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},h=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],m=h.filter((k,I)=>Object.values(p)[I]==="");if(m.length!==0&&m.length!==h.length)throw new Error(`${h.join(", ")} must be set together (or all left unset) \u2014 missing: ${m.join(", ")}, which would half-configure the lane plane`);let _=m.length===0?p:void 0,b={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},v=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],R=v.filter((k,I)=>Object.values(b)[I]==="");if(R.length!==0&&R.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${R.join(", ")}, which would half-configure the pooler cutover`);let f=R.length===0?b:void 0,g={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},y=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],S=y.filter((k,I)=>Object.values(g)[I]==="");if(S.length!==0&&S.length!==y.length)throw new Error(`${y.join(", ")} must be set together (or all left unset) \u2014 missing: ${S.join(", ")}, which would half-configure the machine-identity rung`);let A=g.issuers.split(",").map(k=>k.trim()).filter(k=>k!=="");if(A.length===0&&S.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let w=Number(g.tokenTtlS);if(S.length===0&&(!Number.isFinite(w)||w<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(g.tokenTtlS)}`);let E=S.length===0?{jwksBaseUrl:g.jwksBaseUrl,issuers:A,tokenTtlS:w}:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:l,ledgerSigning:c,lane:_,pooler:f,machine:E}}var ks=512;function Jt(t){return`urun-inference-proxy-${(0,Cn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Kt=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),s=this.opts.pooler;if(s===void 0)return o;let i=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,l)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await o.createResponse(a,l);let u=`px_${(0,Cn.randomUUID)()}`;return hu(s,a,u,u)}})}build(e){if(this.opts.build){let s=this.opts.build(e);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,e,s.router),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Pn,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:uu(process.env,process.env.HOSTNAME)??void 0},r=vs(n),o=n.decisionPool?pu(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(bs(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e,r),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;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>=ks;){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}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(s=>{n.push(String(s instanceof Error?s.message:s))})];r.decision&&o.push(r.decision.close().catch(s=>{n.push(String(s instanceof Error?s.message:s))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Br=512,Rs=1024,zt=class extends Error{constructor(){super(`conversation capacity reached (${Br} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function rm(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(wt))return{concurrencyKey:e};if(n.startsWith(wt)||n.startsWith(_t))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(wt)||n.startsWith(_t)||t.set(n,r)}}}function om(t,e,n,r,o){let s=vs({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Pn,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...rm(r,o)});return{clients:bs(s,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await s.closeAll()}}}var Yt=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let o={id:n,subject:r!==void 0?`${Jt(e.apiKey)}:live`:`${Jt(e.apiKey)}:live:${n}`},s=new Map,i=this.opts.build?this.opts.build(e,o):om(this.opts,e,o,s,r);return{id:n,backhaul:i,attachments:0,nativeRefs:s}}attachEntry(e,n,r){let o=this.byCaller.get(e.apiKey);o===void 0&&(o=new Map,this.byCaller.set(e.apiKey,o));let s=o.get(n);if(s!==void 0)return o.delete(n),o.set(n,s),s.attachments+=1,s;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,o.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Br;){let e=this.byCaller.keys().next();if(e.done)throw new zt;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 zt;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,n){let r=null,o=!1,s=()=>(r===null&&(r=this.attachEntry(e,(0,Cn.randomUUID)(),n)),r),i={createResponse:(a,l)=>s().backhaul.clients.createResponse(a,l),catalogIdentity:a=>s().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let l=s().backhaul.clients.servingAppSlug;if(l===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 l(a)},listModels:()=>s().backhaul.clients.listModels(),sessionHandle:a=>s().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let l=s().backhaul.clients.dedicatedSessionHandle;return l===void 0?s().backhaul.clients.sessionHandle(a):l(a)},releaseSessionHandle:a=>s().backhaul.clients.releaseSessionHandle?.(a),createResponseOn:(a,l,u)=>s().backhaul.clients.createResponseOn(a,l,u),onSessionEnd:(a,l)=>s().backhaul.clients.onSessionEnd(a,l)};return i.openAudio=async(a,l)=>{let u=s().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(a,l)},i.openVideo=async a=>{let l=s().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(a)},i.openVideoOut=async a=>{let l=s().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(a)},i.supportsAudio=async a=>{let l=s().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(a)},i.supportsSpeech=async a=>{let l=s().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(a)},i.speechVoices=async a=>{let l=s().backhaul.clients.speechVoices;if(l===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 l(a)},i.speechSessionHandle=async a=>{let l=s().backhaul.clients.speechSessionHandle;if(l===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 l(a)},i.openAudioOn=async(a,l,u)=>{let d=s().backhaul.clients.openAudioOn;if(d===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 d(a,l,u)},i.openVideoOn=async(a,l)=>{let u=s().backhaul.clients.openVideoOn;if(u===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return u(a,l)},i.openTurnsOn=(a,l)=>{let u=s().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(a,l)},i.evictSpeechSession=async a=>{let l=s().backhaul.clients.evictSpeechSession;if(l===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 l(a)},i.supportsTranscription=async a=>{let l=s().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(a)},i.transcriptStreamFor=async a=>{let l=s().backhaul.clients.transcriptStreamFor;if(l===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return l(a)},i.listSpeechToTextModels=async()=>{let a=s().backhaul.clients.listSpeechToTextModels;if(a===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 a()},{clients:i,bindResumeHandle:a=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Rs;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async a=>{let l=this.byHandle.get(a),u=l===void 0?void 0:this.byCaller.get(l.apiKey),d=l===void 0||u===void 0?void 0:u.get(l.conversationId);if(l===void 0||d===void 0||l.apiKey!==e.apiKey)throw new F("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 r=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(o)return;o=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.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 jr="/inference-usage",_u=25e3;var sm=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function vu(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=sm.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 qr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${jr}`,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(_u)})}catch(i){throw new ne(`the uRun usage surface (POST ${jr}) could not be reached within ${_u}ms: ${vu(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 ne(`the uRun usage surface (POST ${jr}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new ne(`the uRun usage surface (POST ${jr}) answered HTTP ${o.status} with a body that is not JSON: ${vu(i)}`)}return Ga(s,this.opts.onRejectedRow)}};var Ts="/inference-ledger",Ps=1e4,Xt=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},As=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},se=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Is=class extends Z{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Os=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},im=[["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",Es],["output_minutes",Es],["cost_nano_usd",Es],["price_version",t=>t===null||typeof t=="string"]];function am(t){for(let[e,n]of im){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function lm(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"}:am(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Es(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function xs(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function um(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function bu(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 dm(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&&bu(t.started_at,n.started_at)&&bu(t.completed_at,n.completed_at)&&xs(t.prompt_tokens,n.prompt_tokens)&&xs(t.completion_tokens,n.completion_tokens)&&xs(t.output_units,n.output_units)&&um(t.output_minutes,n.output_minutes)}function cm(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
89
+ `)}async function pm(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(cm(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Cs(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new se(`${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 se(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new se(`${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 se(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=u=>{if(!(u in n))throw new se(`${e} answered a row with no ${u} field: ${JSON.stringify(t)}`);let d=n[u];if(d===null)return null;if(typeof d!="string")throw new se(`${e} answered a non-string ${u}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new se(`${e} answered a BLANK ${u} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},i=s("price_version"),a=s("unpriced_reason"),l=o!=null;if(l&&(i===null||a!==null))throw new se(`${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(!l&&(i!==null||a===null))throw new se(`${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 Qt=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Ts}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await pm(n,this.opts.signing)}):JSON.stringify(n)}catch(u){throw new se(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${u instanceof Error?u.message:String(u)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(Ps)})}catch(u){throw new se(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(s.status===409){let u=await s.text().catch(()=>""),d=lm(u);throw d.status==="found"&&dm(n,d.row)?new As(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 Xt(`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 Xt(`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(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new Is("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(!s.ok){let u=await s.text().catch(c=>`<body unreadable: ${c instanceof Error?c.message:String(c)}>`),d;try{let c=JSON.parse(u);if(c!==null&&typeof c=="object"&&"error"in c){let p=c.error;p!==null&&typeof p=="object"&&"code"in p&&(d=p.code)}}catch{}throw d==="ledger_signature_invalid"?new Os(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+u.slice(0,400)):new se(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${u.slice(0,400)}`)}let i;try{i=await s.json()}catch(u){throw new se(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let a=i?.recorded;if(a===void 0)throw new se(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=Cs(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new se(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};var Ls=5e3,fm=1e3,mm=1500,$s=3e3,gm="/api/client-tokens";function Gr(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Su(t,e,n,r){Gr(t,e,{error:{message:n,type:r}})}async function hm(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${gm}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout($s)});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 xu(t){let e=t.resolver??new Gt({gatewayUrl:t.baseUrl}),n=t.machine?new Nr({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=new qt(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,s=null,i=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let w=new Eu.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),E=zl({redis:w});return{registry:Dl({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:vl({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(I,x)=>o?.onHostedChange(I,x)??(()=>()=>{}),roomDoc:(I,x)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(I,x)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(I,x)=>E.rows().then(O=>{let $=so(O,x);return $?.warm_wait_s!==void 0?$.warm_wait_s*1e3:void 0}),currentReleaseOf:Fl(w),closeLane:I=>o?.closeLane(I)}),catalog:E,redis:w}})(),a=t.registry??new Kt({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry,pooler:t.pooler}),l=t.probeControlPlane??(()=>hm(t.baseUrl)),u=async()=>{let w=null;for(let I of a.decisionPools()){w=I;break}if(!w)return null;let E=w.stats();if(E.some(I=>I.draining))return{ok:!1,detail:"decision pool draining"};if(E.every(I=>I.attached===0&&I.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let k=await w.pingReady(mm);return{ok:k,detail:k?"a decision slot answered its session ping":"no decision slot answered its session ping"}},d=t.usageClient??new qr({apiUrl:t.apiUrl}),c=t.ledgerClient??new Qt({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),p=process.env.URUN_SHARED_ORG_ID?.trim(),h=process.env.URUN_SHARED_ORG_API_KEY?.trim();p&&h&&(async()=>{try{await a.decisionWarmerFor({orgId:p,apiKey:h})?.warmFor(vr)}catch(w){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(w instanceof Error?w.message:w)}
90
+ `)}})();let m=async w=>ms(Wt(w.headers.authorization),e,n),_=async w=>{let E=await m(w);if(E.billingAudience==="platform"&&E.creditsAdmissionOk===!1){let k=E.creditsRefusalReason;throw new Tn(k==="spend_cap_reached"||k==="insufficient_credits"?k:void 0)}return E},b=w=>w instanceof Z?{status:w.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:w instanceof Tn?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...w.code!==void 0?{code:w.code}:{}}:w instanceof _e?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:w.detail}:null,v=ul({clients:async w=>a.clientsFor(await _(w)),usage:{authorize:w=>Wt(w.headers.authorization),lookup:(w,E)=>d.lookup(w,E)},statusOf:b,...t.requestLog?{requestLog:t.requestLog}:{},observe:w=>r.observe(w),ledger:{write:(w,E)=>c.write(Wt(w.headers.authorization),E),observe:w=>r.observeLedger(w),...t.ledgerLog?{report:t.ledgerLog}:{}}}),R=null,f=null,g=(0,ku.createServer)((w,E)=>{let k=new URL(w.url??"/","http://localhost");(async()=>{if(w.method==="GET"&&k.pathname==="/healthz"){Gr(E,200,{ok:!0});return}if(w.method==="GET"&&k.pathname==="/readyz"){let O=Date.now();if((!R||O-R.at>=Ls)&&(R={at:O,...await l()}),!f||O-f.at>=fm){let q=await u();f=q===null?{at:O,ok:!0,detail:null}:{at:O,ok:q.ok,detail:q.detail}}let $=(R?.ready??!1)&&f.ok,M=f.detail===null?R?.detail??"control plane not yet probed":`${R?.detail??"control plane not yet probed"}; ${f.detail}`;Gr(E,$?200:503,{ok:$,control_plane:M});return}if(w.method==="GET"&&k.pathname==="/lanez"){Gr(E,200,{pools:i?await i.registry.status():null});return}let I=k.pathname==="/v1"||k.pathname.startsWith("/v1/"),x=k.pathname.startsWith("/partners/");if(!I&&!x){Su(E,404,`no route for ${w.method} ${k.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, /readyz and /lanez`,"invalid_request_error");return}v(w,E)})().catch(I=>{if(!E.headersSent){Su(E,500,String(I instanceof Error?I.message:I),"proxy_error");return}E.end()})}),y=t.conversations??new Yt({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry}),S=[lo(g,{authenticate:async w=>{let E=await ms(w,e,n),k=y.connectionFor(E);return{clients:k.clients,scope:Jt(E.apiKey),onBindResumeHandle:k.bindResumeHandle,clientsForResume:k.clientsForResume,release:k.release}}}),vo(g,{clients:async w=>a.clientsFor(await _(w)),statusOf:b}).close,nr(g,{resolver:{resolve:async(w,E)=>{let k=await _(w),I=y.connectionFor(k,ml(w)),x;try{x=await gl(Bo(I.clients,t.realtimeCompanions),pl(w),E,fl(w))}catch($){throw I.release().catch(()=>{}),$}let O=x.release;return{...x,release:async()=>{await O?.(),await I.release()}}}}})];if(t.lane&&i){let w=t.lane,E=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=Kl(g,{verifyToken:(I,x)=>Jo(I,x,w.tokenSecret,void 0,E),selfAddress:w.selfAddress,laneTenantOf:I=>i.redis.get(`lane_tenant:${I}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:E,hostRegistry:{setHost:(I,x)=>i.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${I}`,x,String(Jl)),delHost:I=>i.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${I}`,w.selfAddress)}}),s=Cl(g,{verifyToken:(I,x)=>Jo(I,x,w.tokenSecret,void 0,E),selfAddress:w.selfAddress,hostOf:async I=>{let x=await i.redis.get(`lane_hosts:${I}`);return x&&x.trim()!==""?x.trim():null},podToPodDial:(I,x,O)=>new Promise(($,M)=>{(async()=>{let q=await i.redis.get(`lane_tenant:${I}`),H=In(I,w.tokenSecret,void 0,void 0,q||void 0),he=`ws://${O}/stream/${encodeURIComponent(I)}/${encodeURIComponent(x)}?token=${encodeURIComponent(H)}`,J=new Ru.default(he,Ir(x));J.once("open",()=>$(J)),J.once("error",M)})().catch(M)})});let k=i;S.push(async()=>{await o.close(),await s.close(),await k.registry.close(),k.redis.quit().catch(()=>{})})}g.on("upgrade",(w,E)=>{let k=new URL(w.url??"/","http://localhost");k.pathname===Dn||k.pathname===wo||k.pathname===yn||o!==null&&k.pathname.startsWith("/doc/")||s!==null&&k.pathname.startsWith("/stream/")||E.destroyed||(E.write(`HTTP/1.1 404 Not Found\r
91
91
  Connection: close\r
92
92
  \r
93
- no WS route for ${k.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),R.destroy())});let A=async()=>{for(let b of I)await b();await _.detachAll()};return{server:y,metricsServer:Pr(r),metrics:r,edgeIdentityServer:Lr(),registry:a,closeAll:()=>a.closeAll(),closeWebSockets:A}}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});
93
+ no WS route for ${k.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),E.destroy())});let A=async()=>{for(let w of S)await w();await y.detachAll()};return{server:g,metricsServer:Lr(r),metrics:r,edgeIdentityServer:Mr(),registry:a,closeAll:()=>a.closeAll(),closeWebSockets:A}}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});