@urun-sh/openai 0.6.31 → 0.6.32

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 (49) hide show
  1. package/dist/chunk-5473ZAQ4.js +17 -0
  2. package/dist/chunk-7OH7UJ2H.js +60 -0
  3. package/dist/chunk-CAR4AEQJ.js +1 -0
  4. package/dist/{chunk-76BZLCGT.js → chunk-GL7EWL3V.js} +1 -1
  5. package/dist/chunk-KTMDSM7F.js +2 -0
  6. package/dist/chunk-L6HTHDVV.js +1 -0
  7. package/dist/chunk-LM4E5YM2.js +19 -0
  8. package/dist/chunk-M3YMNU5P.js +6 -0
  9. package/dist/chunk-NN6TQQUG.js +1 -0
  10. package/dist/chunk-OOCRI7ZM.js +6 -0
  11. package/dist/chunk-PAYCMH5F.js +1 -0
  12. package/dist/{responses-turn-BGb_XPOa.d.ts → composite-DMawda97.d.ts} +125 -83
  13. package/dist/{responses-turn-DXrwiPJh.d.cts → composite-DtBebn0Y.d.cts} +545 -309
  14. package/dist/gemini-live.cjs +2 -2
  15. package/dist/gemini-live.d.cts +85 -105
  16. package/dist/gemini-live.d.ts +48 -48
  17. package/dist/gemini-live.js +1 -1
  18. package/dist/hosted/bin.cjs +56 -42
  19. package/dist/hosted/bin.js +4 -22
  20. package/dist/hosted/index.cjs +52 -38
  21. package/dist/hosted/index.d.cts +230 -7
  22. package/dist/hosted/index.d.ts +114 -3
  23. package/dist/hosted/index.js +1 -1
  24. package/dist/index.cjs +1 -1
  25. package/dist/index.d.cts +1 -1
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.js +1 -1
  28. package/dist/{models-DUdx_Y6X.d.cts → models-D7F0bLJ3.d.cts} +14 -0
  29. package/dist/{models-DUdx_Y6X.d.ts → models-D7F0bLJ3.d.ts} +6 -0
  30. package/dist/pi-extension/index.cjs +6 -6
  31. package/dist/pi-extension/index.js +1 -1
  32. package/dist/pi-extension/standalone.cjs +33 -33
  33. package/dist/pooler/bin.cjs +335 -0
  34. package/dist/pooler/bin.js +316 -0
  35. package/dist/proxy/cli.cjs +58 -53
  36. package/dist/proxy/cli.js +1 -1
  37. package/dist/proxy/conformance-probe.cjs +1 -0
  38. package/dist/proxy/conformance-probe.js +1 -0
  39. package/dist/proxy/index.cjs +31 -28
  40. package/dist/proxy/index.d.cts +315 -167
  41. package/dist/proxy/index.d.ts +85 -53
  42. package/dist/proxy/index.js +1 -1
  43. package/package.json +14 -4
  44. package/dist/chunk-4MI2TNQS.js +0 -62
  45. package/dist/chunk-7SAW4IL4.js +0 -2
  46. package/dist/chunk-7V2JKPIG.js +0 -1
  47. package/dist/chunk-CUDFHFNX.js +0 -4
  48. package/dist/chunk-HZC2SKKI.js +0 -8
  49. package/dist/chunk-K23AZPI4.js +0 -1
@@ -1,69 +1,83 @@
1
- "use strict";var ya=Object.create;var qt=Object.defineProperty;var _a=Object.getOwnPropertyDescriptor;var wa=Object.getOwnPropertyNames;var va=Object.getPrototypeOf,ba=Object.prototype.hasOwnProperty;var Sa=(t,e)=>{for(var n in e)qt(t,n,{get:e[n],enumerable:!0})},yo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wa(e))!ba.call(t,o)&&o!==n&&qt(t,o,{get:()=>e[o],enumerable:!(r=_a(e,o))||r.enumerable});return t};var jt=(t,e,n)=>(n=t!=null?ya(va(t)):{},yo(e||!t||!t.__esModule?qt(n,"default",{value:t,enumerable:!0}):n,t)),ka=t=>yo(qt({},"__esModule",{value:!0}),t);var nc={};Sa(nc,{ANONYMOUS_KEY_ID:()=>Ln,BIND_HOST:()=>la,BUCKET_DOMAIN:()=>qr,BoundedLabel:()=>lt,ControlPlaneUnavailableError:()=>Te,ConversationBackhauls:()=>mt,ConversationCapacityError:()=>ft,DEFAULT_PORT:()=>eo,EDGE_IDENTITY_PORT:()=>Ki,EDGE_KEY_FINGERPRINT_HEADER:()=>Hr,EDGE_KEY_ID_HEADER:()=>Br,InferenceMetrics:()=>dt,LEDGER_FUNCTION_PATH:()=>uo,LEDGER_WRITE_TIMEOUT_MS:()=>lo,LedgerClient:()=>gt,LedgerDuplicateError:()=>ht,LedgerSurfaceError:()=>Y,MAX_CACHED_KEYS:()=>Kr,MAX_CONVERSATIONS:()=>qn,MAX_CONVERSATION_HANDLES:()=>no,MAX_MODEL_LABELS:()=>Nr,MAX_ORG_LABELS:()=>$r,MAX_TENANTS:()=>to,METRICS_PATH:()=>Pn,METRICS_PORT:()=>Ji,NO_MODEL_LABEL:()=>Mr,ORG_BINDING_TTL_MS:()=>Wr,OTHER_LABEL:()=>ut,OrgResolver:()=>ct,ProxyAuthError:()=>ae,READINESS_TIMEOUT_MS:()=>mo,READINESS_TTL_MS:()=>fo,SERVE_FUNCTION:()=>Ft,TIER_DOMAIN:()=>jr,TenantRegistry:()=>pt,bearerFrom:()=>Ve,bearerTokenOf:()=>Jr,createEdgeIdentityServer:()=>Mn,createHostedProxy:()=>ga,createMetricsServer:()=>Cn,edgeBucketId:()=>Gr,edgeTierFingerprint:()=>Vr,laneOf:()=>Ur,parseLedgerRecorded:()=>co,resolveHostedConfig:()=>da,statusClassOf:()=>Dr,tenantSubject:()=>Bt});module.exports=ka(nc);var ha=require("http");var vo="audio",Jn=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 bo(t,e,n=1e4){let r=new Jn(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(vo).attach(o);let s=await Ra(t,n);return await r.startInbound(s),r}function Ra(t,e){let n=t.stream(vo);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 _o="rt-video-in",wo=256e3;function So(t){let e=t.stream(_o),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${_o}') 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>wo)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${wo}-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 xa=24e3,yt=480,Ea=111;async function Aa(){let t=await import("opusscript"),e=t.default??t;return new e(xa,1,2048)}async function ko(){let t=await import("werift"),e=await Aa();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),h=e.encode(c,yt);o=o+1&65535,s=s+yt>>>0;let f=new t.RtpHeader({version:2,payloadType:Ea,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),p=new t.RtpPacket(f,h);n.writeRtp(p)}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 Gt=require("@urun-sh/core"),Wn="rt-video-out";var Ia="h264";function Oa(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 Ta(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;Oa(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 Ro="urun.videoOut.v2-ws";function xo(t){let e=t.stream(Wn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Wn}') 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: "${Wn}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=Ta(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:Ia,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 Kt="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Pa=1007,Ao=1008,ye=1011,zt=1008,k=class extends Error{constructor(n,r=Pa){super(n);this.closeCode=r}closeCode},j=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Vt=["setup","clientContent","realtimeInput","toolResponse"];function Io(t){let e;try{e=JSON.parse(t)}catch{throw new k("client message is not valid JSON")}let n=j(e);if(!n)throw new k("client message must be a JSON object");let r=Vt.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Vt.includes(a));if(o.length>0)throw new k(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Vt.join(", ")}`);if(r.length!==1)throw new k(`client message must contain exactly one of ${Vt.join(", ")} (got ${r.length})`);let s=r[0],i=j(n[s]);if(!i)throw new k(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Oo(t,e){if(typeof t=="string")return t;let n=j(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new k(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=j(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new k(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new k(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new k(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
2
- `)}var Ca={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Ce="urun.videoOut";function To(t){return{framing:Ro,codec:t}}function Po(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Ce]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var La={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ma=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Ce],Eo=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Na(t){let e=j(t);if(!e)throw new k("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new k(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=j(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new k("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new k(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new k("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!Eo.includes(e.activityHandling))throw new k(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Eo.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var $a=["temperature","maxOutputTokens","responseModalities"];function Co(t){for(let[c,h]of Object.entries(La))if(t[c]!==void 0)throw new k(h);for(let c of Object.keys(t))if(!Ma.includes(c))throw new k(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new k('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=j(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new k("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!$a.includes(c))throw new k(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new k("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new k("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let h of c){let f=String(h).toUpperCase();if(f==="AUDIO"){o=!0;continue}if(f!=="TEXT")throw new k(`responseModalities ${JSON.stringify(h)} 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:Oo(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new k("setup.tools must be an array");a=[];for(let c of t.tools){let h=j(c);if(!h)throw new k("setup.tools entries must be objects");for(let f of Object.keys(h))if(f!=="functionDeclarations")throw new k(`unsupported tool "${f}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(h.functionDeclarations))throw new k("tool.functionDeclarations must be an array");for(let f of h.functionDeclarations){let p=j(f);if(!p||typeof p.name!="string")throw new k("functionDeclarations entries require a string name");a.push({type:"function",name:p.name,description:p.description,parameters:p.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=j(t.sessionResumption);if(!c)throw new k("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let h of Object.keys(c))if(h!=="handle")throw new k(`unsupported sessionResumption field "${h}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new k("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?Ca:Na(t.realtimeInputConfig),d=!1;if(t[Ce]!==void 0){if(!j(t[Ce]))throw new k(`setup["${Ce}"] 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 Lo(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Mo(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function No(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new k(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new k("clientContent.turns must be an array");let n=[];for(let r of e){let o=j(r);if(!o)throw new k("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new k(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Oo(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Jt=16e3,$o=24e3,Ua=`audio/pcm;rate=${$o}`,Uo=Buffer.alloc(960).toString("base64");function Da(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 Fa(t){let e=j(t);if(!e)throw new k("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new k(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new k("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new k("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Ba(t){let e=j(t);if(!e)throw new k("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new k(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==Jt)throw new k(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Jt} Hz (audio/pcm;rate=${Jt})`);if(typeof e.data!="string"||e.data.length===0)throw new k("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new k(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=Da(o,Jt,$o);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Do(t){if(t.mediaChunks!==void 0)throw new k('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new k("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=j(t[o]);if(!s||Object.keys(s).length!==0)throw new k(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new k(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new k(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Ba(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Fa(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new k("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new k("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Fo(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new k(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new k("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=j(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new k("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Bo(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Ho(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Ua,data:t}}]}}}}function qo(t){let e=j(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=j(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let h=j(c);h?.type==="output_text"&&typeof h.text=="string"&&(s+=h.text)}}s&&o.push({role:"assistant",content:s});for(let u of n){let d=j(u);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new k(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,ye);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",h;try{h=JSON.parse(c)}catch{throw new k(`upstream function_call arguments are not valid JSON: ${c}`,ye)}r.push({id:d.call_id,name:d.name,args:h}),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=j(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 hs=require("crypto"),gs=require("ws");var K=class extends Error{},Ha=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function qa(t){if(typeof t!="string")return!1;let e=Ha.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 ja(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new K(`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 K(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new K(`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 K(`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 K(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);let d=(c,h)=>{if(u[c]!==void 0&&u[c]!==null&&!h)throw new K(`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",qa(u.ready_since));for(let c of["model_id","variant"]){let h=u[c];if(h.includes(":"))throw new K(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(h)}) \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 K(`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 K(`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 K(`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 We(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function jo(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 K(`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 Go(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new K(`catalog read failed: GET ${n} \u2192 ${r.status}`);return ja(await r.json())}function _e(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var ue=class extends Error{name="ModelPriceError"},Kn="per_million_input_tokens",zn="per_million_output_tokens",Jo="model_id,variant,unit,price_usd,effective_at,expires_at",Vo={per_request:!0,per_minute:!0,per_output_unit:!0},Ga=5e3;function Va(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ue(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Wo(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ue(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Ja(t,e,n){return t===null?null:Wo(t,e,n)}function Wa(t,e){if(t===Kn)return"input";if(t===zn)return"output";if(typeof t=="string"&&Object.hasOwn(Vo,t))return null;throw new ue(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Kn} | ${zn}) nor a known GPU-time unit (${Object.keys(Vo).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 Ka(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 Yn(t,e){return`${t}\0${e}`}function za(t){if(!Array.isArray(t))throw new ue(`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 ue(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of Jo.split(","))if(!Object.hasOwn(s,u))throw new ue(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=Wa(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new ue(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new ue(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Va(s.price_usd,o),effective_at:Wo(s.effective_at,o,"effective_at"),expires_at:Ja(s.expires_at,o,"expires_at")})}return e}function Ko(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=(h,f,p)=>{let y=h&&h.length>0?h:d?.[f];if(!y||y.length===0)return null;let g=Ka(y,f);return"reason"in g?g:g.rate.usd===0?f==="output"&&p!==null&&n?.has(Yn(l,p))?g.rate:{reason:`the ${f} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:g.rate};for(let[h,f]of o.get(l)){let p=u.get(h),y=c(p?.input,"input",f),g=c(p?.output,"output",f);if(y!==null&&"reason"in y){i.push({model_id:l,variant:f,reason:y.reason});continue}if(g!==null&&"reason"in g){i.push({model_id:l,variant:f,reason:g.reason});continue}y===null||g===null||s.push({model_id:l,variant:f,pricing:{input:y.usd,output:g.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 _t(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 wt={prices:[],refusals:[]};async function zo(t){let e=t.fetchImpl??fetch,n=`${Kn},${zn}`,r=await e(`${t.catalogUrl}/model_prices?select=${Jo}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Ga)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return za(await r.json())}var Me="/partners/openrouter/models",Ya={chat:!0,code:!0,agent:!0,vl:!0},Yo={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Xa(t){let e=t.toLowerCase();return Object.hasOwn(Yo,e)?Yo[e]:null}var Xo={"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 Qa(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Xo,o)?Xo[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 Qo={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Zo={2:"Llama2",3:"Llama3"};function Za(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(Qo,s))return Qo[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Zo,i))return Zo[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var eu=["context_length","max_model_len"];function tu(t){let e=eu.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 Xt(t){let e=t.map(tu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function nu(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function Xn(t){if(t.length===0)return null;let e=t.map(nu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function ru(t,e){let n=e.filter(o=>_e(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return Yt(n);let r=e.filter(o=>_e(o.model_id)===t);return r.length>0?Yt(r):null}function Yt(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:ou(t),matches:t}:null}function ou(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}function ns(t){return 0}function Le(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 Qt(t,e,n){let r=ru(t,e);if(!r)return Le({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Xt(s),a=_t(o.model_id,o.variant,n),l=rs(o,s),u=Xn(s);return Le({id:t,object:"model",created:ns(o),owned_by:"urun",...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...l.published.length>0?{voices:[...l.published]}:{},...u!==null?{capabilities:{reasoning:u}}:{}})}var su=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function rs(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:[...su],defect:o}:{published:[],defect:o}}function Qn(t){let e=t.length>0?Yt(t):null;return e===null?{published:[],defect:null}:rs(e.row,e.matches)}function es(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 ts(t){return{input:[{type:"prompt",unit:"token",cost_usd:es(t.input)}],output:[{type:"completion",unit:"token",cost_usd:es(t.output)}]}}function iu(t,e,n,r){if(e.length===0)return null;let o=Yt(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Ya[s.task]!==!0)return null;let a=Xt(i),l=_t(s.model_id,s.variant,n),u=Za(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:ns(s),quantization:Xa(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:ts(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:ts(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function os(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?We(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:Qa(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=iu(u,e.filter(h=>h.model_id===u.model_id&&h.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}var ss={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},Ke=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function is(t){let e=t.t;if(typeof e!="string"||!(e in ss))throw new Ke(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(ss).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 au(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Ke(`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 Ke(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return is(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Ke(`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 is(t)}function as(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function uu(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 us(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 as(e);let s=o.next();if(e!==void 0&&await uu(s,e)==="aborted")throw s.catch(()=>{}),as(e);let i=await s;if(i.done)return;yield au(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var $=class extends Error{},H=class extends Error{},er="urs1.";function ls(t,e){return er+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function lu(t){if(!t.startsWith(er))return null;try{let e=JSON.parse(Buffer.from(t.slice(er.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 fs(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 ds(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=cu(t);return e===null?[]:[e]}function Zn(t,e,n,r,o){if(!o)throw new K(`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 K(`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 K(`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 cs(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 K(`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 ms="shared:",vt="speech:";function xe(t){return t.sharedApp?ms+t.appSlug:t.appSlug}function en(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 ke(t,e){let n=e.filter(s=>_e(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>_e(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function du(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function cu(t){let e=t.map(du),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var ps={stt:"stt",tts:"tts"};function Re(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||ps[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?ps[e]:null}function pu(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 Error(`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 Zt=6e4,tn=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;rowsCache=null;seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??Zt;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}async sharedBlock(){if(!this.opts.shared)return null;let e=this.opts.appsTtlMs??Zt;if(this.sharedCache&&Date.now()-this.sharedCache.at<e)return this.sharedCache.block;let n=await this.opts.shared();return this.sharedCache={at:Date.now(),block:n},n}sharedCache=null;async catalogRows(){if(!this.opts.listCatalog)return[];let e=this.opts.appsTtlMs??Zt;if(this.rowsCache&&Date.now()-this.rowsCache.at<e)return this.rowsCache.rows;let n=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:n},n}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Zt;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 ue)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
3
- `),wt}let r=Ko(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
4
- `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(Yn(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(ms)||o.startsWith(vt)||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 $(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${r}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${r}`)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};let o=_e(n);if(o===r)return{appSlug:r};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let s=await this.deployedApps(),i=this.servable(s);if(i.includes(o))return{appSlug:o};let a=i.filter(u=>u.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new $(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=s.find(u=>u.app_slug===o||u.app_slug.startsWith(`${o}-`));if(l)throw new $(`model "${n}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.shared){let s=await this.sharedBlock();if(s){let i=jo(s,n);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant,sharedOrgId:s.shared_org_id}}}if(this.opts.listCatalog){let i=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===_e(a.model_id)||o===_e(`${a.model_id}-${a.variant}`));if(i)throw new $(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${i.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=en(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return xe(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,xe(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,vt+xe(n))}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:en(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:ls(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:ls(n,this.keyOf(r))}}async sessionForHandle(e){let n=lu(e);if(!n)throw new H(`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 H(`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 H(`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:wt;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
5
- `);let l=(n?We(n):[]).map(u=>{let d=s.filter(g=>g.model_id===u.model_id&&g.variant===u.variant),c=Xt(d),h=Xn(d),f=_t(u.model_id,u.variant,i),p=Qn(d);return Le({id:`${u.model_id}:${u.variant}`,object:"model",created:0,owned_by:"urun",...c!==null?{context_length:c}:{},...f!==null?{pricing:f}:{},...p.published.length>0?{voices:[...p.published]}:{},...h!==null?{capabilities:{reasoning:h}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?l:[...e.map(u=>Qt(u,s,i)),...l]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return os(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=Zn(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return cs(`${r.modelId}:${r.variant}`,s).includes(n)}return ds(ke(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Re(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Re(ke(n.appSlug,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Re(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Re(ke(n.appSlug,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Re(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Re(ke(n.appSlug,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):ke(n.appSlug,r);return pu(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):ke(n.appSlug,r);return Qn(o)}async imageModelList(){let e=await this.catalogRows(),n=wt,r=[];for(let s of await this.availableIds()){let i=ds(ke(s,e));i.length!==0&&r.push(Le({...Qt(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of We(o)){let i=Zn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=cs(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let l=Le({id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun",image_modes:a});r.push(l)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=wt,r=[];for(let s of await this.availableIds())Re(ke(s,e))==="stt"&&r.push(Qt(s,e,n));let o=await this.sharedBlock();if(o)for(let s of We(o)){let i=Zn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Re(i)!=="stt")continue;let a=Le({id:`${s.model_id}:${s.variant}`,object:"model",created:0,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 fu=256,tr=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>fu;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},mu="local",bt=t=>t.slice(0,120),nr=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 $){this.ws.close(Ao,bt(e.message));return}if(e instanceof H){this.ws.close(zt,bt(e.message));return}if(e instanceof k){this.ws.close(e.closeCode,bt(e.message));return}this.ws.close(ye,bt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Io(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new k(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=No(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Do(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:Uo);return}this.transcript.push(...Fo(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new k("setup may only be sent once, as the first client message");let n=Co(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new k("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",zt);if(s.model!==n.model)throw new k(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new k("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new k(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,zt);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(Po(u))),l=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),l()},o[Ce]=To(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new k("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new k("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",ye);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Ho(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new k("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new k("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",ye);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new k(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new k("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new k("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,hs.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Lo(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(Mo(e.timeLeftMs)),this.ws.close(ye,bt(`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 k(`upstream error: ${JSON.stringify(u)}`,ye);if(u.type==="response.completed"){o=u.response,s=!0;continue}let d=Bo(u);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new k("upstream produced no response.completed event",ye);let{messages:i,assistantItems:a}=qo(o);this.transcript.push(...a);for(let l of i)this.send(l);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ne=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function hu(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 Ne(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 Ne(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 Ne(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function rr(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 gs.WebSocketServer({noServer:!0}),o=new tr;t.on("upgrade",(i,a,l)=>{let u=new URL(i.url??"/","http://localhost");u.pathname===Kt&&(a.on("error",()=>{}),(async()=>{let d=hu(i,u,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Ne(401,"invalid local proxy api key");c={clients:e.clients,scope:mu}}r.handleUpgrade(i,a,l,h=>{new nr(h,c,o)})})().catch(d=>{let c=502;(d instanceof Ne||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let h=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",f=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${h}\r
1
+ "use strict";var $l=Object.create;var _n=Object.defineProperty;var Ul=Object.getOwnPropertyDescriptor;var Dl=Object.getOwnPropertyNames;var Fl=Object.getPrototypeOf,Bl=Object.prototype.hasOwnProperty;var Hl=(t,e)=>{for(var n in e)_n(t,n,{get:e[n],enumerable:!0})},us=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Dl(e))!Bl.call(t,o)&&o!==n&&_n(t,o,{get:()=>e[o],enumerable:!(r=Ul(e,o))||r.enumerable});return t};var ue=(t,e,n)=>(n=t!=null?$l(Fl(t)):{},us(e||!t||!t.__esModule?_n(n,"default",{value:t,enumerable:!0}):n,t)),jl=t=>us(_n({},"__esModule",{value:!0}),t);var uf={};Hl(uf,{ANONYMOUS_KEY_ID:()=>hr,BIND_HOST:()=>Al,BUCKET_DOMAIN:()=>Do,BoundedLabel:()=>Lt,ControlPlaneUnavailableError:()=>Ge,ConversationBackhauls:()=>Ft,ConversationCapacityError:()=>Dt,DEFAULT_PORT:()=>Ko,EDGE_IDENTITY_PORT:()=>dl,EDGE_KEY_FINGERPRINT_HEADER:()=>Uo,EDGE_KEY_ID_HEADER:()=>$o,InferenceMetrics:()=>Mt,LEDGER_FUNCTION_PATH:()=>ns,LEDGER_WRITE_TIMEOUT_MS:()=>rs,LedgerClient:()=>Ht,LedgerDuplicateError:()=>Bt,LedgerSurfaceError:()=>re,MAX_CACHED_KEYS:()=>Go,MAX_CONVERSATIONS:()=>br,MAX_CONVERSATION_HANDLES:()=>Yo,MAX_MODEL_LABELS:()=>Po,MAX_ORG_LABELS:()=>Co,MAX_TENANTS:()=>zo,METRICS_PATH:()=>mr,METRICS_PORT:()=>ll,NO_MODEL_LABEL:()=>To,ORG_BINDING_TTL_MS:()=>qo,OTHER_LABEL:()=>Ct,OrgResolver:()=>Nt,ProxyAuthError:()=>pe,READINESS_TIMEOUT_MS:()=>is,READINESS_TTL_MS:()=>ss,SERVE_FUNCTION:()=>hn,TIER_DOMAIN:()=>Fo,TenantRegistry:()=>Ut,bearerFrom:()=>at,bearerTokenOf:()=>jo,createEdgeIdentityServer:()=>yr,createHostedProxy:()=>Nl,createMetricsServer:()=>gr,edgeBucketId:()=>Bo,edgeTierFingerprint:()=>Ho,laneOf:()=>Lo,parseLedgerRecorded:()=>os,resolveHostedConfig:()=>Il,statusClassOf:()=>Mo,tenantSubject:()=>wn});module.exports=jl(uf);var Ll=require("http");var ps="audio",Er=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 fs(t,e,n=1e4){let r=new Er(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(ps).attach(o);let s=await ql(t,n);return await r.startInbound(s),r}function ql(t,e){let n=t.stream(ps);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",cs=256e3;function ms(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>cs)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${cs}-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 Gl=24e3,jt=480,Vl=111;async function Wl(){let t=await import("opusscript"),e=t.default??t;return new e(Gl,1,2048)}async function gs(){let t=await import("werift"),e=await Wl();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>=jt;){let d=l.subarray(u,u+jt);u+=jt;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,jt);o=o+1&65535,s=s+jt>>>0;let y=new t.RtpHeader({version:2,payloadType:Vl,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),h=new t.RtpPacket(y,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 vn=require("@urun-sh/core"),Ar="rt-video-out";var Jl="h264";function Kl(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 zl(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;Kl(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 ys(t){let e=t.stream(Ar);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Ar}') 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: "${Ar}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=zl(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:Jl,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 Rn="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Yl=1007,_s=1008,Te=1011,xn=1008,O=class extends Error{constructor(n,r=Yl){super(n);this.closeCode=r}closeCode},te=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,bn=["setup","clientContent","realtimeInput","toolResponse"];function vs(t){let e;try{e=JSON.parse(t)}catch{throw new O("client message is not valid JSON")}let n=te(e);if(!n)throw new O("client message must be a JSON object");let r=bn.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!bn.includes(a));if(o.length>0)throw new O(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${bn.join(", ")}`);if(r.length!==1)throw new O(`client message must contain exactly one of ${bn.join(", ")} (got ${r.length})`);let s=r[0],i=te(n[s]);if(!i)throw new O(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function bs(t,e){if(typeof t=="string")return t;let n=te(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=te(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 Xl={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Je="urun.videoOut";function Ss(t){return{framing:hs,codec:t}}function ks(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Je]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Ql={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Zl=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Je],ws=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function eu(t){let e=te(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=te(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(!ws.includes(e.activityHandling))throw new O(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${ws.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var tu=["temperature","maxOutputTokens","responseModalities"];function Rs(t){for(let[c,p]of Object.entries(Ql))if(t[c]!==void 0)throw new O(p);for(let c of Object.keys(t))if(!Zl.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=te(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(!tu.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 y=String(p).toUpperCase();if(y==="AUDIO"){o=!0;continue}if(y!=="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:bs(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=te(c);if(!p)throw new O("setup.tools entries must be objects");for(let y of Object.keys(p))if(y!=="functionDeclarations")throw new O(`unsupported tool "${y}" \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 y of p.functionDeclarations){let h=te(y);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=te(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?Xl:eu(t.realtimeInputConfig),d=!1;if(t[Je]!==void 0){if(!te(t[Je]))throw new O(`setup["${Je}"] 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 Es(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function As(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=te(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:bs(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Sn=16e3,Is=24e3,nu=`audio/pcm;rate=${Is}`,Os=Buffer.alloc(960).toString("base64");function ru(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 ou(t){let e=te(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 su(t){let e=te(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])!==Sn)throw new O(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Sn} Hz (audio/pcm;rate=${Sn})`);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=ru(o,Sn,Is);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Ts(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=te(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:su(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:ou(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 Ps(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=te(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 Cs(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Ls(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:nu,data:t}}]}}}}function Ms(t){let e=te(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=te(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=te(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=te(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)}`,Te);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}`,Te)}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=te(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 oi=require("crypto"),si=require("ws");var z=class extends Error{},iu=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function au(t){if(typeof t!="string")return!1;let e=iu.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 lu(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new z(`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 z(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new z(`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 z(`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 z(`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 z(`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 z(`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",au(u.ready_since));for(let c of["model_id","variant"]){let p=u[c];if(p.includes(":"))throw new z(`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 z(`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 z(`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 z(`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 ut(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Ir(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 z(`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 Ns(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 z(`catalog read failed: GET ${n} \u2192 ${r.status}`);return lu(await r.json())}function me(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var he=class extends Error{name="ModelPriceError"},Or="per_million_input_tokens",Tr="per_million_output_tokens",Us="model_id,variant,unit,price_usd,effective_at,expires_at",$s={per_request:!0,per_minute:!0,per_output_unit:!0},uu=5e3;function du(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new he(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Ds(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new he(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function cu(t,e,n){return t===null?null:Ds(t,e,n)}function pu(t,e){if(t===Or)return"input";if(t===Tr)return"output";if(typeof t=="string"&&Object.hasOwn($s,t))return null;throw new he(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Or} | ${Tr}) nor a known GPU-time unit (${Object.keys($s).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 fu(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 Pr(t,e){return`${t}\0${e}`}function mu(t){if(!Array.isArray(t))throw new he(`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 he(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of Us.split(","))if(!Object.hasOwn(s,u))throw new he(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=pu(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new he(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new he(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:du(s.price_usd,o),effective_at:Ds(s.effective_at,o,"effective_at"),expires_at:cu(s.expires_at,o,"expires_at")})}return e}function Fs(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,y,h)=>{let _=p&&p.length>0?p:d?.[y];if(!_||_.length===0)return null;let A=fu(_,y);return"reason"in A?A:A.rate.usd===0?y==="output"&&h!==null&&n?.has(Pr(l,h))?A.rate:{reason:`the ${y} 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`}:A.rate};for(let[p,y]of o.get(l)){let h=u.get(p),_=c(h?.input,"input",y),A=c(h?.output,"output",y);if(_!==null&&"reason"in _){i.push({model_id:l,variant:y,reason:_.reason});continue}if(A!==null&&"reason"in A){i.push({model_id:l,variant:y,reason:A.reason});continue}_===null||A===null||s.push({model_id:l,variant:y,pricing:{input:_.usd,output:A.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 qt(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 Gt={prices:[],refusals:[]};async function Bs(t){let e=t.fetchImpl??fetch,n=`${Or},${Tr}`,r=await e(`${t.catalogUrl}/model_prices?select=${Us}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(uu)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return mu(await r.json())}var ze="/partners/openrouter/models",gu={chat:!0,code:!0,agent:!0,vl:!0},Hs={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function hu(t){let e=t.toLowerCase();return Object.hasOwn(Hs,e)?Hs[e]:null}var js={"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 yu(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(js,o)?js[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 qs={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Gs={2:"Llama2",3:"Llama3"};function wu(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(qs,s))return qs[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Gs,i))return Gs[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var _u=["context_length","max_model_len"];function vu(t){let e=_u.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 En(t){let e=t.map(vu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function bu(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function Cr(t){if(t.length===0)return null;let e=t.map(bu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Lr(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 Su(t,e){let n=e.filter(s=>me(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Vt(n);let r=e.filter(s=>me(s.model_id)===t);if(r.length>0)return Vt(r);let o=Lr(t,e);return o.length>0?Vt(o):null}function Vt(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:ku(t),matches:t}:null}function ku(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 Ne=class extends Error{name="ModelCreatedError"};function dt(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 Ne(`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 Ne(`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 Ne(`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 Ne(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function Ke(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 An(t,e,n){let r=Su(t,e);if(!r)return Ke({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=En(s),a=dt(s),l=qt(o.model_id,o.variant,n),u=Js(o,s),d=Cr(s);return Ke({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 Ru=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Js(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:[...Ru],defect:o}:{published:[],defect:o}}function Mr(t){let e=t.length>0?Vt(t):null;return e===null?{published:[],defect:null}:Js(e.row,e.matches)}function Vs(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 Ws(t){return{input:[{type:"prompt",unit:"token",cost_usd:Vs(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Vs(t.output)}]}}function xu(t,e,n,r){if(e.length===0)return null;let o=Vt(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||gu[s.task]!==!0)return null;let a=En(i),l=qt(s.model_id,s.variant,n),u=wu(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:dt(i),quantization:hu(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:Ws(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:Ws(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Ks(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?ut(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:yu(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=xu(u,e.filter(p=>p.model_id===u.model_id&&p.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}var zs={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},ct=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Ys(t){let e=t.t;if(typeof e!="string"||!(e in zs))throw new ct(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(zs).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 Eu(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new ct(`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 ct(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Ys(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new ct(`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 Ys(t)}function Xs(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Au(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 Qs(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 Xs(e);let s=o.next();if(e!==void 0&&await Au(s,e)==="aborted")throw s.catch(()=>{}),Xs(e);let i=await s;if(i.done)return;yield Eu(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var F=class extends Error{},U=class extends Error{},$r="urs1.";function On(t,e){return $r+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Cn(t){if(!t.startsWith($r))return null;try{let e=JSON.parse(Buffer.from(t.slice($r.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 ti(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 Zs(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Tu(t);return e===null?[]:[e]}function Iu(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
+ `),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 Dr(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||me(`${r.model_id}-${r.variant}`)===e.appSlug||me(r.model_id)===e.appSlug)),n?Iu(n.engine_args?.pool):null}function Nr(t,e,n,r,o){if(!o)throw new z(`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 z(`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 z(`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 z(`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 ni="shared:",Jt="speech:";function Ue(t){return t.sharedApp?ni+t.appSlug:t.appSlug}function Tn(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 Ur(t,e){let n=e.filter(s=>me(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>me(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function Ou(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Tu(t){let e=t.map(Ou),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Pu={stt:"stt",tts:"tts"};function $e(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:Pu[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function ri(t,e){let n=Ur(t,e);return n.length>0?n:Lr(t,e)}function Wt(t,e){return ri(t.appSlug,e)}function Cu(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 z(`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 In=6e4,Pn=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??In):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??In):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??In):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??In;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 he)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
+ `),Gt}let r=Fs(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(Pr(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(ni)||o.startsWith(Jt)||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 F(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=Ir(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=me(s),l=n.endpoints.filter(c=>me(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:Ir(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=me(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 F(`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 F(`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===me(l.model_id)||o===me(`${l.model_id}-${l.variant}`));if(a)throw new F(`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=Tn(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return Dr(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return Ue(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ue(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Jt+Ue(n))}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:Tn(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:On(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:On(n,this.keyOf(r))}}async sessionForHandle(e){let n=Cn(e);if(!n)throw new U(`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 U(`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 U(`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:Gt;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?ut(n):[]).map(u=>{let d=s.filter(v=>v.model_id===u.model_id&&v.variant===u.variant),c=En(d),p=dt(d),y=Cr(d),h=qt(u.model_id,u.variant,i),_=Mr(d);return Ke({id:`${u.model_id}:${u.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...h!==null?{pricing:h}:{},..._.published.length>0?{voices:[..._.published]}:{},...y!==null?{capabilities:{reasoning:y}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?l:[...e.map(u=>An(u,s,i)),...l]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Ks(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=Nr(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return ei(`${r.modelId}:${r.variant}`,s).includes(n)}return Zs(Ur(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?$e(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:$e(Wt(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?$e(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":$e(Wt(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?$e(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":$e(Wt(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):Wt(n,r);return Cu(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):Wt(n,r);return Mr(o)}async imageModelList(){let e=await this.catalogRows(),n=Gt,r=[];for(let s of await this.availableIds()){let i=Zs(Ur(s,e));i.length!==0&&r.push(Ke({...An(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of ut(o)){let i=Nr(`${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=Ke({id:`${s.model_id}:${s.variant}`,object:"model",created:dt(i),owned_by:"urun",image_modes:a});r.push(l)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=Gt,r=[];for(let s of await this.availableIds())$e(ri(s,e))==="stt"&&r.push(An(s,e,n));let o=await this.sharedBlock();if(o)for(let s of ut(o)){let i=Nr(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if($e(i)!=="stt")continue;let a=Ke({id:`${s.model_id}:${s.variant}`,object:"model",created:dt(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 Lu=256,Fr=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Lu;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Mu="local",Kt=t=>t.slice(0,120),Br=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 F){this.ws.close(_s,Kt(e.message));return}if(e instanceof U){this.ws.close(xn,Kt(e.message));return}if(e instanceof O){this.ws.close(e.closeCode,Kt(e.message));return}this.ws.close(Te,Kt(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 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}=As(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Ts(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:Os);return}this.transcript.push(...Ps(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=Rs(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",xn);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`,xn);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(ks(u))),l=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),l()},o[Je]=Ss(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)",Te);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Ls(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)",Te);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,oi.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(Es(e.timeLeftMs)),this.ws.close(Te,Kt(`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)}`,Te);if(u.type==="response.completed"){o=u.response,s=!0;continue}let d=Cs(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",Te);let{messages:i,assistantItems:a}=Ms(o);this.transcript.push(...a);for(let l of i)this.send(l);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Xe=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Nu(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 Xe(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new Xe(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let l of r)a=l;if(a===void 0&&n)throw new Xe(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Hr(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 si.WebSocketServer({noServer:!0}),o=new Fr;t.on("upgrade",(i,a,l)=>{let u=new URL(i.url??"/","http://localhost");u.pathname===Rn&&(a.on("error",()=>{}),(async()=>{let d=Nu(i,u,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Xe(401,"invalid local proxy api key");c={clients:e.clients,scope:Mu}}r.handleUpgrade(i,a,l,p=>{new Br(p,c,o)})})().catch(d=>{let c=502;(d instanceof Xe||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",y=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
6
8
  Connection: close\r
7
9
  \r
8
- ${f}\r
9
- `),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(l=>l===void 0?i():a(l)))})(),s)}var Ae=require("ws");var ys=require("crypto"),_s="Inference-Id";function St(){return(0,ys.randomUUID)()}function or(t){return t==="/v1"||t.startsWith("/v1/")}function ws(t,e){if(!or(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 kt(t){return`resp_${t}`}function vs(t){return`chatcmpl-${t}`}function bs(t){return`msg_${t}`}function le(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Ss(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 ks(t){return`${JSON.stringify(t)}
10
- `}var gu=256,yu=128;function oe(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,yu)}var $e=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>=gu?"(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}}}},_u=256;function wu(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 Ue=class extends Error{},ze=class{conversations=new Map;thread(e,n){let r=wu(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ue(`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<=_u)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Rs=new WeakMap;function Rt(t){let e=Rs.get(t);return e||(e=new ze,Rs.set(t,e)),e}function Ye(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function fe(t){return t.find(e=>e.type==="response.completed")?.response??null}function Xe(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 Ee=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}))}},vu=["<tool_call>","<function="];function bu(t){return vu.find(e=>t.includes(e))}function De(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 Fe(t,e,n){if(!(!t||e>0))return bu(n)}function Qe(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 we(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Su(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 sr(t,e){let n=Su(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var de=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Ze(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ue?new de(n.message,"previous_response_not_found",400,"previous_response_id"):new de(String(n instanceof Error?n.message:n),"invalid_input")}}function xs(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function ir(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new de("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}:{},...xs(e)!==void 0?{response_format:xs(e)}:{}},o)}async function xt(t){let{body:e,clients:n,store:r,stats:o}=t,s=Ze(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=oe(e);o.model(u);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,h=await ir(n,e,s,!0,c?le(c):void 0);return{responseId:i,events:Eu({events:h,conversation:s,responseId:i,modelKey:u,requestHadTools:d,remember:a,persist:l,store:r,stats:o,turn:t.turn})}}function ku(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?xu(o[i++],l):l),...Ru(r,n)]}function Ru(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 xu(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*Eu(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:l,stats:u}=t,d=[],c=C=>C.response&&typeof C.response=="object"?{...C,response:{...C.response,id:r}}:C,h=`item_${r.slice(5)}`,f=!1,p=!1,y=0;function*g(){f||(f=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let w=[],v=(C,N)=>{w.push({output_index:C,item:N})},m=!1,R=0,b="",_=0,S="";function*T(){if(!m)return;m=!1,yield{type:"response.reasoning_text.done",item_id:b,output_index:R,content_index:0,text:S};let C={id:b,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:S}],status:"completed"};yield{type:"response.output_item.done",output_index:R,item:C},v(R,C),S=""}let x=!1,A=0,P="",U=0,W="",re="";function*pe(C){if(!x)return;x=!1,yield{type:"response.output_text.done",item_id:P,output_index:A,content_index:0,text:W},yield{type:"response.content_part.done",item_id:P,output_index:A,content_index:0,part:{type:"output_text",text:W}};let N={id:P,type:"message",role:"assistant",status:C,content:[{type:"output_text",text:W}]};yield{type:"response.output_item.done",output_index:A,item:N},v(A,N),W=""}let be=new Ee,V=null,J=-1;function*Z(C){if(!V)return;let N=V;V=null,yield{type:"response.function_call_arguments.done",item_id:N.fcId,output_index:N.outputIndex,arguments:N.args};let X={id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:N.args,status:C};yield{type:"response.output_item.done",output_index:N.outputIndex,item:X},v(N.outputIndex,X)}let Pe=!1;for await(let C of u.track(e,o,t.turn)){d.push(C);let N=String(C.type??"");if(N==="response.created"||N==="response.in_progress"){f=!0,yield c(C);continue}if(N==="response.output_item.added"){p=!0,yield c(C);continue}if(N==="response.reasoning_text.delta"&&!p){yield*g(),m||(m=!0,R=y++,_+=1,b=_===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${_}`,yield{type:"response.output_item.added",output_index:R,item:{id:b,type:"reasoning",summary:[],content:[],status:"in_progress"}}),S+=String(C.delta??""),yield{type:"response.reasoning_text.delta",item_id:b,output_index:R,content_index:0,delta:C.delta};continue}if(N==="response.output_text.delta"&&!p){yield*g(),yield*T(),x||(x=!0,A=y++,U+=1,P=U===1?h:`${h}_${U}`,yield{type:"response.output_item.added",output_index:A,item:{id:P,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:P,output_index:A,content_index:0,part:{type:"output_text",text:""}}),W+=String(C.delta??""),re+=String(C.delta??""),yield{type:N,item_id:P,output_index:A,content_index:0,delta:C.delta};continue}let X=p?null:Xe(C);if(X){if(yield*g(),yield*T(),yield*pe("completed"),be.add(X),X.tool_index!==J){yield*Z("completed"),J=X.tool_index;let ge=y++;V={fcId:`fc_${r.slice(5)}_${X.tool_index}`,outputIndex:ge,callId:X.call_id,name:X.name,args:""},yield{type:"response.output_item.added",output_index:ge,item:{id:V.fcId,type:"function_call",call_id:V.callId??V.fcId,name:V.name??"",arguments:"",status:"in_progress"}}}V&&(X.call_id&&(V.callId=X.call_id),X.name&&(V.name=X.name),V.args+=X.delta,yield{type:"response.function_call_arguments.delta",item_id:V.fcId,output_index:V.outputIndex,delta:X.delta});continue}if(N==="response.completed"&&!p){let ge=Ye(C.response),F=Fe(s,be.size+ge.length,re);if(F){Pe=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:De(o,F)}};break}if(yield*T(),yield*pe("completed"),yield*Z("completed"),be.size===0)for(let Se of ge){let Je=y++,Ht=Se.id??Se.call_id??`fc_${Je}`,Vn=Se.arguments??"",ho={id:Ht,type:"function_call",call_id:Se.call_id??Ht,name:Se.name??""};yield{type:"response.output_item.added",output_index:Je,item:{...ho,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Ht,output_index:Je,delta:Vn},yield{type:"response.function_call_arguments.done",item_id:Ht,output_index:Je,arguments:Vn};let go={...ho,arguments:Vn,status:"completed"};yield{type:"response.output_item.done",output_index:Je,item:go},v(Je,go)}let ee=ku(w,C.response);yield ee.length>0?c({...C,response:{...C.response,output:ee}}):c(C);continue}yield c(C)}if(yield*T(),yield*pe("incomplete"),yield*Z("incomplete"),i&&!Pe){let C=fe(d);l.remember(r,n,sr(C,Qe(d,C)),a)}}var lr="/v1/responses",Au=64*1024*1024,Iu=8*1024*1024,Ou=16,Es=32,As=3600*1e3,Tu=/^[A-Za-z0-9._-]{1,256}$/;function se(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Pu=se(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 dr(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Cu(t){for(;t.bufferedAmount>Iu&&t.readyState===Ae.WebSocket.OPEN;){let{promise:e,resolve:n}=dr();setTimeout(n,5),await e}}var ar=class extends ze{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 Ue))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)}},ur=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new ar(Rt(n)),e.on("message",(i,a)=>this.onMessage(i,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(se(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${As/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},As).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(se(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(se(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(se(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(se(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(se(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(se(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"||!Tu.test(o.stream_id)){this.sendFrame(Pu);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Es){this.sendFrame(se(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Es}). 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){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await xt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:kt(St())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let s=o.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==Ae.WebSocket.OPEN)break;this.send(i,n),await Cu(this.ws)}}finally{this.activeTurns.delete(s)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=kt(St());try{let o=Ze(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof de)return se(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof $)return se(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof H)return se(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?se(o.status,{type:o.openaiType,message:r},n):se(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Ou;){let{promise:e,resolve:n}=dr();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!==Ae.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!==Ae.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function rn(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
10
+ ${y}\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 Be=require("ws");var ii=require("crypto"),ai="Inference-Id";function zt(){return(0,ii.randomUUID)()}function jr(t){return t==="/v1"||t.startsWith("/v1/")}function li(t,e){if(!jr(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 Yt(t){return`resp_${t}`}function ui(t){return`chatcmpl-${t}`}function di(t){return`msg_${t}`}function ye(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function ci(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 pi(t){return`${JSON.stringify(t)}
12
+ `}var $u=256,Uu=128;function de(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Uu)}var Qe=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>=$u?"(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}}}},Du=256;function Fu(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 Ze=class extends Error{},pt=class{conversations=new Map;thread(e,n){let r=Fu(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ze(`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<=Du)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},fi=new WeakMap;function Xt(t){let e=fi.get(t);return e||(e=new pt,fi.set(t,e)),e}function ft(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Ie(t){return t.find(e=>e.type==="response.completed")?.response??null}function mt(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 De=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}))}},Bu=["<tool_call>","<function="];function Hu(t){return Bu.find(e=>t.includes(e))}function et(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 tt(t,e,n){if(!(!t||e>0))return Hu(n)}function gt(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 Pe(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function ju(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 qr(t,e){let n=ju(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var we=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function ht(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ze?new we(n.message,"previous_response_not_found",400,"previous_response_id"):new we(String(n instanceof Error?n.message:n),"invalid_input")}}function mi(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Gr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new we("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}:{},...mi(e)!==void 0?{response_format:mi(e)}:{}},o)}async function Qt(t){let{body:e,clients:n,store:r,stats:o}=t,s=ht(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=de(e);o.model(u);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await Gr(n,e,s,!0,c?ye(c):void 0);return{responseId:i,events:Wu({events:p,conversation:s,responseId:i,modelKey:u,requestHadTools:d,remember:a,persist:l,store:r,stats:o,turn:t.turn})}}function qu(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?Vu(o[i++],l):l),...Gu(r,n)]}function Gu(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 Vu(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*Wu(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:l,stats:u}=t,d=[],c=M=>M.response&&typeof M.response=="object"?{...M,response:{...M.response,id:r}}:M,p=`item_${r.slice(5)}`,y=!1,h=!1,_=0;function*A(){y||(y=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let v=[],f=(M,H)=>{v.push({output_index:M,item:H})},m=!1,w=0,g="",S=0,b="";function*k(){if(!m)return;m=!1,yield{type:"response.reasoning_text.done",item_id:g,output_index:w,content_index:0,text:b};let M={id:g,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:b}],status:"completed"};yield{type:"response.output_item.done",output_index:w,item:M},f(w,M),b=""}let x=!1,R=0,I="",E=0,C="",$="";function*B(M){if(!x)return;x=!1,yield{type:"response.output_text.done",item_id:I,output_index:R,content_index:0,text:C},yield{type:"response.content_part.done",item_id:I,output_index:R,content_index:0,part:{type:"output_text",text:C}};let H={id:I,type:"message",role:"assistant",status:M,content:[{type:"output_text",text:C}]};yield{type:"response.output_item.done",output_index:R,item:H},f(R,H),C=""}let K=new De,j=null,Me=-1;function*X(M){if(!j)return;let H=j;j=null,yield{type:"response.function_call_arguments.done",item_id:H.fcId,output_index:H.outputIndex,arguments:H.args};let q={id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:H.args,status:M};yield{type:"response.output_item.done",output_index:H.outputIndex,item:q},f(H.outputIndex,q)}let ae=!1;for await(let M of u.track(e,o,t.turn)){d.push(M);let H=String(M.type??"");if(H==="response.created"||H==="response.in_progress"){y=!0,yield c(M);continue}if(H==="response.output_item.added"){h=!0,yield c(M);continue}if(H==="response.reasoning_text.delta"&&!h){yield*A(),m||(m=!0,w=_++,S+=1,g=S===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${S}`,yield{type:"response.output_item.added",output_index:w,item:{id:g,type:"reasoning",summary:[],content:[],status:"in_progress"}}),b+=String(M.delta??""),yield{type:"response.reasoning_text.delta",item_id:g,output_index:w,content_index:0,delta:M.delta};continue}if(H==="response.output_text.delta"&&!h){yield*A(),yield*k(),x||(x=!0,R=_++,E+=1,I=E===1?p:`${p}_${E}`,yield{type:"response.output_item.added",output_index:R,item:{id:I,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:I,output_index:R,content_index:0,part:{type:"output_text",text:""}}),C+=String(M.delta??""),$+=String(M.delta??""),yield{type:H,item_id:I,output_index:R,content_index:0,delta:M.delta};continue}let q=h?null:mt(M);if(q){if(yield*A(),yield*k(),yield*B("completed"),K.add(q),q.tool_index!==Me){yield*X("completed"),Me=q.tool_index;let Ve=_++;j={fcId:`fc_${r.slice(5)}_${q.tool_index}`,outputIndex:Ve,callId:q.call_id,name:q.name,args:""},yield{type:"response.output_item.added",output_index:Ve,item:{id:j.fcId,type:"function_call",call_id:j.callId??j.fcId,name:j.name??"",arguments:"",status:"in_progress"}}}j&&(q.call_id&&(j.callId=q.call_id),q.name&&(j.name=q.name),j.args+=q.delta,yield{type:"response.function_call_arguments.delta",item_id:j.fcId,output_index:j.outputIndex,delta:q.delta});continue}if(H==="response.completed"&&!h){let Ve=ft(M.response),lt=tt(s,K.size+Ve.length,$);if(lt){ae=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:et(o,lt)}};break}if(yield*k(),yield*B("completed"),yield*X("completed"),K.size===0)for(let Q of Ve){let be=_++,We=Q.id??Q.call_id??`fc_${be}`,xr=Q.arguments??"",as={id:We,type:"function_call",call_id:Q.call_id??We,name:Q.name??""};yield{type:"response.output_item.added",output_index:be,item:{...as,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:We,output_index:be,delta:xr},yield{type:"response.function_call_arguments.done",item_id:We,output_index:be,arguments:xr};let ls={...as,arguments:xr,status:"completed"};yield{type:"response.output_item.done",output_index:be,item:ls},f(be,ls)}let G=qu(v,M.response);yield G.length>0?c({...M,response:{...M.response,output:G}}):c(M);continue}yield c(M)}if(yield*k(),yield*B("incomplete"),yield*X("incomplete"),i&&!ae){let M=Ie(d);l.remember(r,n,qr(M,gt(d,M)),a)}}var _e=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},oe=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Fe=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)}},Zt=class extends Fe{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},Vr=class extends Fe{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")}},Se=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Ln=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 Zt;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 Zt;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 Vr(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 Zt}}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 Wr=require("@urun-sh/core"),ke=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)}},Jr=33e4;function gi(t,e=Jr){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((u,d)=>{o=d}),i=setTimeout(()=>o(new Mn),e),a;try{a=await Promise.race([r.next(),s])}catch(u){throw u instanceof U||u instanceof Wr.SessionFailedError&&u.kind==="transport-failed"?u:u instanceof Mn?(await r.return?.(void 0),new ke("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 ke("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 ke("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield l}})()}var Mn=class extends Error{constructor(){super("stream idle timeout")}};function hi(t){return t instanceof ke?!1:t instanceof U?!0:t instanceof Wr.SessionFailedError?t.kind==="transport-failed":!1}var Ju=[/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 xe(t){return!Ju.some(e=>e.test(t))}function Ee(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 ge(t,e){if(t instanceof U)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=yi(t);return n||{message:Ee(e?.inferenceId??null),redacted:!0}}function yi(t){return t instanceof Ne?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof z?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof F?{message:t.message,redacted:!1}:t instanceof _e?{message:t.message,redacted:!1}:t instanceof Fe?{message:t.message,redacted:!1}:t instanceof ke?xe(t.message)?{message:t.message,redacted:!1}:null:t instanceof Se?{message:t.message,redacted:!1}:t instanceof oe?{message:t.message,redacted:!1}:null}function yt(t,e,n){let r=n??(i=>console.error(i)),o=yi(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Re(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&xe(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Re(e)}`),`the ${t} upstream failed while serving this request`)}function Oe(t){let e=t?.message;return typeof e=="string"&&e.length>0&&xe(e)?e:null}function Re(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Yr="/v1/responses",Ku=64*1024*1024,zu=8*1024*1024,Yu=16,wi=32,_i=3600*1e3,Xu=/^[A-Za-z0-9._-]{1,256}$/;function le(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Qu=le(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 Xr(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Zu(t){for(;t.bufferedAmount>zu&&t.readyState===Be.WebSocket.OPEN;){let{promise:e,resolve:n}=Xr();setTimeout(n,5),await e}}var Kr=class extends pt{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 Ze))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)}},zr=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 Kr(Xt(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(le(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${_i/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},_i).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(le(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(le(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(le(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(le(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(le(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(le(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"||!Xu.test(o.stream_id)){this.sendFrame(Qu);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=wi){this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${wi}). 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=zt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await Qt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Yt(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!==Be.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Zu(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=zt(),o=Yt(r);try{let s=ht(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:Re(e);if(e instanceof we)return le(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof F)return le(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof U){let a=ge(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}`),le(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}`),le(s.status,{type:s.openaiType,message:o},n);let i=ge(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}`),le(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Oe(o),a=i??Ee(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)}`),le(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=Yu;){let{promise:e,resolve:n}=Xr();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!==Be.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!==Be.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Nn(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
11
13
  `;t.end(`HTTP/1.1 ${e} ${r}\r
12
14
  Connection: close\r
13
15
  Content-Type: text/plain; charset=utf-8\r
14
16
  Content-Length: ${Buffer.byteLength(o)}\r
15
17
  \r
16
- ${o}`)}function cr(t,e){let n=new Ae.WebSocketServer({noServer:!0,maxPayload:Au}),r=new $e,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,h)=>{let f;try{f=new URL(d.url??"/","http://localhost")}catch{rn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),f.pathname!==lr){i.add(c);return}s.add(c);let p=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){rn(c,401,"invalid local proxy api key");return}let y;try{y=await a(d)}catch(g){let w=e.statusOf?.(g)??null;rn(c,w?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(p=!0,n.handleUpgrade(d,c,h,g=>{s.delete(c),o.add(g),g.on("close",()=>o.delete(g));try{new ur(g,y,r,e.statusOf)}catch{o.delete(g),g.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!p&&!c.destroyed&&rn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=dr();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let f of s)f.destroy();s.clear();for(let f of i)f.destroy();i.clear();for(let f of o)f.close(1001,"server shutting down");let h=setTimeout(()=>{for(let f of o)f.readyState!==Ae.WebSocket.CLOSED&&f.terminate()},2e3);return h.unref?.(),n.close(()=>{clearTimeout(h),c()}),d}}}var Ns=require("@urun-sh/core");var Is=require("@urun-sh/core"),Lu={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},Mu={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"admission is momentarily contended (lock convoy) \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function pr(t,e){let n=Mu[t.code];return e?`${n} (${e})`:n}function on(t){if(t==null)return null;let e=Lu[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 sn(t){if(t.kind==="create-failed")return on(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Is.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return on(e?"cold_start_exceeded":"queue_timeout")}var Nu=jt(require("os"),1),$u=jt(require("path"),1),Uu=require("url"),Du=require("util");function Os(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 an(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 Fu=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Bu(t){let e=t?.code;return typeof e=="string"&&Fu.has(e)}function Ie(t,e){try{return t.write(e),!0}catch(n){if(Bu(n))return!1;throw n}}var $s=require("ws");var Ms=require("@urun-sh/core");var Ps=require("crypto");function E(t){return`${t}_${(0,Ps.randomUUID)().replace(/-/g,"").slice(0,24)}`}var un=4*1024*1024,fr=8*1024*1024,ln=512,dn=20*1024*1024;function G(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 D(t){return{type:"error",event_id:E("event"),error:t}}function mr(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var O=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Hu={type:!0,model:!0,instructions:!0,modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},qu={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},ju={format:!0,voice:!0,speed:!0};function Ts(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new O(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function Et(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new O("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(i=>!(i in Hu));if(o.length>0)throw new O(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let s={...e,outputModalities:[...e.outputModalities]};for(let[i,a]of Object.entries(r))switch(i){case"type":{if(a!=="realtime"&&a!=="transcription")throw new O(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new O(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(a==="transcription"&&!n.turns)throw new O('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");s.type=a;break}case"model":if(a!==null&&typeof a!="string")throw new O("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new O("instructions must be a string or null","instructions");s.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new O("modalities must be a non-empty array","modalities");let l=[];for(let u of a){if(u!=="text"&&u!=="audio")throw new O(`modality ${JSON.stringify(u)} is not "text" or "audio"`,"modalities");if(u==="audio"&&!n.voice)throw new O('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");l.includes(u)||l.push(u)}s.outputModalities=l;break}case"voice":if(a===null){delete s.voice;break}if(typeof a!="string")throw new O("voice must be a string or null","voice");if(!n.voice)throw new O("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new O(`${i} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,i);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new O("temperature must be a finite number or null","temperature");s.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new O(`${i} must be a positive integer, "inf" or null`,i);s.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new O("tools must be an array","tools");s.tools=a;break;case"tool_choice":s.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new O("metadata must be an object or null","metadata");s.metadata=a??null;break;case"turn_detection":{if(a===null){s.turnDetection=null;break}if(!n.turns)throw new O("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new O("turn_detection must be an object or null","turn_detection");let u=String(l.type??"");if(u!=="server_vad"&&u!=="semantic_vad")throw new O(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");s.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new O("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new O("input_audio_transcription must be an object or null","input_audio_transcription");for(let u of Object.keys(a))if(!["model","language","languages","prompt"].includes(u))throw new O(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");let l=a.model;if(l!=null){let u=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new O(`input_audio_transcription.model ${JSON.stringify(u)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new O("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new O("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let u=l.input;if(!u||typeof u!="object"||Array.isArray(u))throw new O("audio.input must be an object","audio.input");for(let d of Object.keys(u))if(!(d in qu))throw new O(`audio.input field not supported by this backend: ${d}`,`audio.input.${d}`,"unsupported_field");if(u.format!==void 0&&Ts(u.format,"audio.input.format"),u.transcription!==null&&u.transcription!==void 0){let d=Et({input_audio_transcription:u.transcription},s,n);s.inputAudioTranscription=d.inputAudioTranscription}if(u.turn_detection!==null&&u.turn_detection!==void 0){let d=Et({turn_detection:u.turn_detection},s,n);s.turnDetection=d.turnDetection}if(u.noise_reduction!==null&&u.noise_reduction!==void 0)throw new O("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let u=l.output;if(!u||typeof u!="object"||Array.isArray(u))throw new O("audio.output must be an object","audio.output");for(let d of Object.keys(u))if(!(d in ju))throw new O(`audio.output field not supported by this backend: ${d}`,`audio.output.${d}`,"unsupported_field");if(u.format!==void 0&&Ts(u.format,"audio.output.format"),u.speed!==void 0)throw new O("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(u.voice!==void 0)if(u.voice===null)delete s.voice;else{if(typeof u.voice!="string")throw new O("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new O("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=u.voice}u.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function cn(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 hr(t,e){let n=t;if(!n||typeof n!="object")throw new O("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new O("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:E("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new O('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new O("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new O("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new O(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new O("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new O("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new O(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:E("item"),type:"message",role:r,content:o}}throw new O(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function gr(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 Gu=1001,Vu=1011,Cs=t=>t.slice(0,120),Ju=/^[A-Za-z0-9+/=]*$/,Wu=2;function Ku(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Wu)return!1;return!0}var At=class{id=E("conn");ws;binding;onClosed;config=mr();sessionId=E("sess");conversationId=E("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:E("event"),session:cn(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:E("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(D(et("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.isTranscriptionSession()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:e,content_index:0,transcript:n})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:E("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:E("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:E("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:E("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.isTranscriptionSession()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:E("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=E("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:E("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.created",event_id:E("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:E("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:E("event"),item_id:i,content_index:0,transcript:s}),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(G("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>un){this.fail(G("frame_too_large",`frame exceeds the ${un}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(G("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(G("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(D({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(et(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=Et(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model}),this.send({type:"session.updated",event_id:E("event"),session:cn(this.config,this.sessionId)});return;case"conversation.item.create":{let n=hr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:E("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(D(G("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:E("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(D(G("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:E("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(D(G("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:E("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(D(G("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Ju.test(e.audio)){this.send(D(G("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>dn){this.send(D(G("buffer_full",`uncommitted input audio exceeds the ${dn}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.isTranscriptionSession()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:E("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(D(G("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.isTranscriptionSession()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=E("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:E("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:E("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.isTranscriptionSession())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:r,content_index:0,transcript:n});else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:E("event"),item_id:r,content_index:0,transcript:s}),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;return}case"output_audio_buffer.clear":{this.send(D(G("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(D(G("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(D(G("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(D(G("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(D({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(D(G("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(y=>y!=="text"&&y!=="audio")){this.send(D(G("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(D(G("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=E("req"),o=`resp_${r}`;this.activeResponseId=o;let s=this.items.length,{input:i,sawAudioOnlyItem:a}=gr(this.items),l=typeof n.instructions=="string"?n.instructions:this.config.instructions,u=typeof n.temperature=="number"?n.temperature:this.config.temperature,d=n.max_output_tokens??this.config.maxOutputTokens,c=d==="inf"||d===void 0?void 0:d,h=n.tools!==void 0?n.tools:this.config.tools,f=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,p={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...l!==void 0?{instructions:l}:{},...u!==void 0?{temperature:u}:{},...c!==void 0?{max_output_tokens:c}:{},...h!==void 0?{tools:h}:{},...f!==void 0?{tool_choice:f}:{}};for(let y of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(y);this.inFlight=(async()=>{let y=[],g=R=>{this.responseFlushed?this.send(R):y.push(R)},w=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:E("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:E("event"),response:this.responseObject(o,"in_progress")});for(let R of y)this.send(R);y.length=0,this.responseFlushed=!0}},v={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},m=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let R;try{R=await this.upstreamStream(p,r)}catch(b){this.upstreamTurnFault(b,o);return}try{for await(let b of R){if(this.cancelled)break;let _=b;if(_.type==="error"){let S=this.upstreamErrorBody(_);this.responseFlushed?this.send(D(S)):this.send({type:"response.failed",event_id:E("event"),response:this.failedResponse(o,S)});return}if(_.type==="response.output_text.delta"&&typeof _.delta=="string"){w(),v.messageOpen||(this.beginMessageItem(o,v.nextOutputIndex++),v.messageOpen=!0),g({type:"response.output_text.delta",event_id:E("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:_.delta}),v.messageText+=_.delta;continue}if(_.type==="response.function_call_arguments.delta"){w();let S=typeof _.delta=="string"?_.delta:"",T=typeof _.call_id=="string"&&_.call_id.length>0?_.call_id:`${o}_fc_${v.nextOutputIndex}`,x=v.tools.get(T);if(!x){let A=typeof _.name=="string"&&_.name.length>0?_.name:void 0;x={outputIndex:v.nextOutputIndex++,name:A,args:""},v.tools.set(T,x),g({type:"response.output_item.added",event_id:E("event"),response_id:o,output_index:x.outputIndex,item:{id:T,object:"realtime.item",type:"function_call",call_id:T,name:A??"",arguments:"",status:"in_progress"}})}typeof _.name=="string"&&_.name.length>0&&(x.name=_.name),x.args+=S,g({type:"response.function_call_arguments.delta",event_id:E("event"),item_id:T,response_id:o,output_index:x.outputIndex,call_id:T,name:x.name??"",delta:S});continue}if(_.type==="response.completed"){m=_.response??null;continue}}}catch(b){this.upstreamTurnFault(b,o);return}if(this.cancelled)return;this.closeOpenItems(o,v,s),w(),this.send({type:"response.done",event_id:E("event"),response:this.doneResponse(o,s,m)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Ku(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(D({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:E("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:E("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:E("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:E("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:E("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:E("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:E("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio;s&&this.send({type:"response.output_audio.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:E("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let i=[];s&&i.push({type:"output_audio"}),n.messageText.length>0&&i.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:E("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:E("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:E("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(et("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof H){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Ms.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=et(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(D(r)):this.send({type:"response.failed",event_id:E("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(D(G("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:E("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>ln&&(this.items.shift(),this.send(D({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${ln} 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>fr){this.ws.close(Gu,Cs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(D(e)),this.ws.close(Vu,Cs(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null;let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>Ls(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Ls(this.id,e)}},yr=[];function Ls(t,e){yr.push({id:t,reason:e}),yr.length>256&&yr.shift()}var It="/v1/realtime",zu=t=>t.slice(0,120);function Yu(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
18
+ ${o}`)}function Qr(t,e){let n=new Be.WebSocketServer({noServer:!0,maxPayload:Ku}),r=new Qe,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 y;try{y=new URL(d.url??"/","http://localhost")}catch{Nn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),y.pathname!==Yr){i.add(c);return}s.add(c);let h=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Nn(c,401,"invalid local proxy api key");return}let _;try{_=await a(d)}catch(A){let v=e.statusOf?.(A)??null;Nn(c,v?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(h=!0,n.handleUpgrade(d,c,p,A=>{s.delete(c),o.add(A),A.on("close",()=>o.delete(A));try{new zr(A,_,r,e.statusOf,e.operatorLog??(v=>console.error(v)))}catch{o.delete(A),A.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!h&&!c.destroyed&&Nn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=Xr();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let y of s)y.destroy();s.clear();for(let y of i)y.destroy();i.clear();for(let y of o)y.close(1001,"server shutting down");let p=setTimeout(()=>{for(let y of o)y.readyState!==Be.WebSocket.CLOSED&&y.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var so=require("@urun-sh/core");var vi=require("@urun-sh/core"),ed={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},td={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 en(t,e){let n=td[t.code];return e?`${n} (${e})`:n}function $n(t){if(t==null)return null;let e=ed[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 Un(t){if(t.kind==="create-failed")return $n(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=vi.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return $n(e?"cold_start_exceeded":"queue_timeout")}var nd=ue(require("os"),1),rd=ue(require("path"),1),od=require("url"),sd=require("util");function bi(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 Dn(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 id=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function ad(t){let e=t?.code;return typeof e=="string"&&id.has(e)}function He(t,e){try{return t.write(e),!0}catch(n){if(ad(n))return!1;throw n}}var Ai=require("ws");var Ei=require("@urun-sh/core");var ki=require("crypto");function T(t){return`${t}_${(0,ki.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Fn=4*1024*1024,Zr=8*1024*1024,Bn=512,Hn=20*1024*1024;function ne(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function _t(t,e){return{type:"server_error",code:t,message:e}}function V(t){return{type:"error",event_id:T("event"),error:t}}function eo(){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},ld={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},ud={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},dd={format:!0,voice:!0,speed:!0};function cd(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function wt(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 Si(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 pd=10;function to(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:pd})}function tn(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 ld));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=wt(o.modalities,"modalities"),l=wt(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=wt(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(!cd(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=to(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,y]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(y!=null&&y!==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(y)}, 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 ud))throw new L(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Si(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=tn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=tn({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 dd))throw new L(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Si(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 jn(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 no(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:T("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:T("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 qn(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 fd=1001,md=1011,Ri=t=>t.slice(0,120),gd=/^[A-Za-z0-9+/=]*$/,hd=2;function yd(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>hd)return!1;return!0}var nn=class{id=T("conn");ws;binding;onClosed;operatorLog;config=eo();sessionId=T("sess");conversationId=T("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:T("event"),session:jn(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:T("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 U&&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(V(_t("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:T("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:T("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:T("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:T("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:T("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:T("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:T("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:T("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=T("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:T("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:T("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:T("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(ne("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Fn){this.fail(ne("frame_too_large",`frame exceeds the ${Fn}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ne("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ne("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(V({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(_t(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=tn(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(V(ne("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:T("event"),session:jn(this.config,this.sessionId)});return}case"conversation.item.create":{let n=no(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:T("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(V(ne("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:T("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(V(ne("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:T("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(V(ne("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:T("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(V(ne("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!gd.test(e.audio)){this.send(V(ne("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>Hn){this.send(V(ne("buffer_full",`uncommitted input audio exceeds the ${Hn}-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:T("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(V(ne("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=T("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:T("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:T("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:T("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:T("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(V(ne("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(V(ne("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(V(ne("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(V(ne("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(V({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(V(ne("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?wt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?wt(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(V(ne("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=T("req"),a=`resp_${i}`;this.activeResponseId=a;let l=this.binding.composite===!0,u=l?0:this.items.length,d=l?null:qn(this.items),c=to(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,y=n.max_output_tokens??this.config.maxOutputTokens,h=y==="inf"||y===void 0?void 0:y,_=n.tools!==void 0?n.tools:this.config.tools,A=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}:{},...h!==void 0?{max_output_tokens:h}:{},..._!==void 0?{tools:_}:{},...A!==void 0?{tool_choice:A}:{}};if(!(l&&!this.ensureVoice())){for(let f of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(f);this.inFlight=(async()=>{let f=[],m=b=>{this.responseFlushed?this.send(b):f.push(b)},w=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:T("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(a,"in_progress")});for(let b of f)this.send(b);f.length=0,this.responseFlushed=!0}},g={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=qn(this.items)}let{input:b,sawAudioOnlyItem:k}=d??{input:[],sawAudioOnlyItem:!1},x={...v,input:b,...l?this.compositeTurnAsk(n):{}};k&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let R;try{R=await this.upstreamStream(x,i)}catch(I){this.upstreamTurnFault(I,a);return}try{for await(let I of R){if(this.cancelled)break;let E=I;if(E.type==="error"){let C=this.upstreamErrorBody(E);this.responseFlushed?this.send(V(C)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(a,C)});return}if(E.type==="response.output_text.delta"&&typeof E.delta=="string"){w(),g.messageOpen||(this.beginMessageItem(a,g.nextOutputIndex++),g.messageOpen=!0),this.config.outputModalities.includes("text")&&m({type:"response.output_text.delta",event_id:T("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:E.delta}),this.turnOutputIsAudio()&&(g.transcriptDelta=!0,m({type:"response.output_audio_transcript.delta",event_id:T("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:E.delta})),g.messageText+=E.delta;continue}if(E.type==="response.function_call_arguments.delta"){w();let C=typeof E.delta=="string"?E.delta:"",$=typeof E.call_id=="string"&&E.call_id.length>0?E.call_id:`${a}_fc_${g.nextOutputIndex}`,B=g.tools.get($);if(!B){let K=typeof E.name=="string"&&E.name.length>0?E.name:void 0;B={outputIndex:g.nextOutputIndex++,name:K,args:""},g.tools.set($,B);let j={id:$,object:"realtime.item",type:"function_call",call_id:$,name:K??"",arguments:"",status:"in_progress"};m({type:"response.output_item.added",event_id:T("event"),response_id:a,output_index:B.outputIndex,item:j}),this.emitAssistantItemAdded(j)}typeof E.name=="string"&&E.name.length>0&&(B.name=E.name),B.args+=C,m({type:"response.function_call_arguments.delta",event_id:T("event"),item_id:$,response_id:a,output_index:B.outputIndex,call_id:$,name:B.name??"",delta:C});continue}if(E.type==="response.completed"){S=E.response??null;continue}}}catch(I){this.upstreamTurnFault(I,a);return}if(this.cancelled)return;this.closeOpenItems(a,g,u),w(),this.send({type:"response.done",event_id:T("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(yd(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(V({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:T("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:T("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:T("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:T("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:T("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:T("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:T("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:T("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:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:T("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:T("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:T("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:T("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:T("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:T("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:T("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=Oe(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??Ee(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&xe(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Re(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(_t("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof U){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Ei.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=_t(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(V(r)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(V(ne("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:T("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Bn&&(this.items.shift(),this.send(V({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Bn} 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>Zr){this.ws.close(fd,Ri("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=ge(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Re(e)}`),r.message}fail(e,n){this.send(V(e)),this.ws.close(md,Ri(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)}},ro=[];function xi(t,e){ro.push({id:t,reason:e}),ro.length>256&&ro.shift()}var rn="/v1/realtime",wd=t=>t.slice(0,120);function _d(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
17
19
  Connection: close\r
18
20
  Content-Type: text/plain\r
19
21
  \r
20
- ${zu(n)}\r
21
- `),t.destroy()}function Xu(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
22
- `}function Qu(t){Ie(process.stdout,t)}function Zu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function _r(t){return t.audioSession?.audio.sessionId??void 0}function pn(t,e){let n=new $s.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==It)return;r.add(s),s.on("close",()=>{r.delete(s)});let l=E("rtup"),u=Zu(o),d=b=>{(e.log??Qu)(Xu(b))};d({stage:"accept",conn:l,model:u}),s.resume();let c=new AbortController,h=null,f=b=>{h??=b,c.abort(new Error(h))},p=()=>f("client socket closed"),y=()=>f("client socket closed (half-close)"),g=b=>f(`client socket error: ${b.message}`);s.once("close",p),s.once("end",y),s.once("error",g);let w=()=>{s.removeListener("close",p),s.removeListener("end",y),s.removeListener("error",g)},v=b=>{d({stage:"close",conn:l,model:u,...b})},m=b=>{let _=b,S=_.session!=null&&typeof _.session.sendResponseCreate=="function",T=_.clients!=null&&typeof _.clients.createResponse=="function";if(!S&&!T)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((x,A)=>{n.handleUpgrade(o,s,i,P=>{try{new At({ws:P,binding:b,onClosed:(U,W)=>{v({while:"live",reason:W.reason})}}),d({stage:"admit",conn:l,model:u,..._r(b)===void 0?{}:{session:_r(b)}}),x()}catch(U){A(U)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async b=>{if(c.signal.aborted){w();let _=_r(b);try{await b.release?.()}catch(S){v({while:"queued",..._===void 0?{}:{session:_},reason:h??"client socket closed",release_failed:S instanceof Error?S.message:String(S)});return}v({while:"queued",..._===void 0?{}:{session:_},reason:h??"client socket closed",released:!0}),s.destroy();return}w(),await m(b)}).catch(b=>{let _=b instanceof Ns.SessionFailedError?sn(b):null,S=null;if(b!==null&&typeof b=="object"&&"status"in b){let A=b.status;typeof A=="number"&&(S=A)}let T=S??_?.status??502,x=b instanceof Error?b.message:String(b);v({while:"queued",...c.signal.aborted?{reason:h??"client socket closed"}:{reason:x,status:T}}),s.destroyed||Yu(s,T,x)}).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 td=require("http");var tt=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)}},Ot=class extends tt{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},wr=class extends tt{constructor(e){super("acquire_timeout",429,30,`no decision slot capacity within ${e}ms (all slots at their in-flight cap)`)}},Be=class extends Error{lastDemandAgeMs;constructor(e){super("no ready decision slot on this proxy \u2014 the request was refused fast, not fenced; retry shortly (an out-of-band slot add was submitted)"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},fn=class{constructor(e){this.opts=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.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}opts;slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;slotKey(e){return`decision:${this.opts.replicaId}:${e}`}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};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.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.state="paused",e.opening=null,this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n)),this.pump();return}e.opening=null})())}async acquire(){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Ot;this.lastDemandAt=this.now();let e=this.opts.acquireTimeoutMs??6e5,n=Date.now();for(;;){let r=this.tryLease();if(r)return r;if(this.draining)throw new Ot;if(!this.slots.some(l=>l.state==="queued")&&this.slots.length<this.opts.max){this.openForDemand();continue}let s=n+e-Date.now();if(s<=0)throw new wr(e);let i,a={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(l=>{a.resolve=l,this.waiters.push(a)}),new Promise(l=>{i=setTimeout(l,s)})])}finally{clearTimeout(i);let l=this.waiters.indexOf(a);l!==-1&&this.waiters.splice(l,1),a.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Ot}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();return n||(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max&&this.openForDemand(),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())}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(r=>r.state==="attached"&&r.inFlight===0&&r.idleSince!==null&&e-r.idleSince>=this.idleGraceMs).sort((r,o)=>(r.idleSince??0)-(o.idleSince??0)||o.slot.index-r.slot.index);for(let r of n)this.endSlot(r)}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 Q=class extends Error{};async function mn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Q(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new Q(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function hn(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new Q(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[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 Q?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Us="/v1/images/generations",gn="/v1/images/edits";function Ds(t){return t===Us||t===gn}var Fs="/v1/images/models";async function Bs(t,e,n){if(t){if(t.model=oe({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var M=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},el=16*1024*1024,Hs=64*1024*1024;function qs(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 Tt(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 js(t,e,n,r,o){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),i=null;for await(let h of s){if(h.type==="error"){let f=h.error??{};throw new M(502,`image upstream error: ${String(f.message??"upstream reported an error")}`)}if(h.type==="response.completed"){i=h.response??null;break}}if(i===null)throw new M(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=we(i));let a=i.images;if(!Array.isArray(a)||a.length!==1||typeof a[0]!="string"||a[0].length===0)throw new M(502,`image upstream returned ${Array.isArray(a)?a.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 l=[],u=a[0].startsWith("data:")?a[0].slice(a[0].indexOf(";base64,")+8):a[0],d=Buffer.from(u,"base64");if(qs(d)===null)throw new M(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return l.push(u),{images:l}}function Gs(t){return t instanceof M?t:t instanceof $?new M(404,t.message):new M(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Vs(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 Tt(r,new M(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Js(t,e){t&&(t.outputUnits=e.images.length)}function Ws(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 tl={model:!0,prompt:!0,response_format:!0,n:!0};async function Ks(t,e,n){let r=n.maxBodyBytes??Hs;try{if(t.method!=="POST")throw new M(405,`${String(t.method)} is not supported on ${Us}`);let o;try{o=JSON.parse((await mn(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof Q?new M(413,c.message):new M(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new M(400,"request body must be a JSON object");let s=o;for(let c of Object.keys(s))if(!tl[c])throw new M(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new M(400,"prompt is required and must be a non-empty string","prompt");let a=s.model===void 0?void 0:s.model;if(a!==void 0&&typeof a!="string")throw new M(400,"model must be a string","model");await Bs(n.turn,n.clients,a);let l=s.n??1;if(l!==1)throw new M(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let u=s.response_format??"b64_json";if(u!=="b64_json")throw new M(400,`response_format ${JSON.stringify(u)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",i.length,i.length),!await Vs(n.imageModels,a,"generation",e))return;let d=[{type:"input_text",text:i}];try{let c=await js(n.clients,a,d,n.turn?le(n.turn):void 0,n.turn);Js(n.turn,c),Ws(e,c)}catch(c){throw Gs(c)}}catch(o){if(o instanceof Q){Tt(e,new M(413,o.message));return}if(o instanceof M){Tt(e,o);return}throw o}}var nl={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function zs(t,e,n){let r=n.maxBodyBytes??Hs,o=n.maxImagePartBytes??el;try{if(t.method!=="POST")throw new M(405,`${String(t.method)} is not supported on ${gn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new M(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await hn(t,r)}catch(f){throw f instanceof Q?new M(413,f.message):new M(400,String(f instanceof Error?f.message:f))}let a=i.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new M(400,"prompt is required and must be a non-empty string field","prompt");let l=i.get("model");if(l!==null&&typeof l!="string")throw new M(400,"model must be a string field","model");let u=l===null?void 0:l;await Bs(n.turn,n.clients,u);let d=i.get("response_format")??"b64_json";if(d!=="b64_json")throw new M(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");for(let f of i.keys())if(!nl[f])throw new M(400,`form field "${f}" 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[]).`,f);let c=[];for(let f of["image","image[]"])for(let p of i.getAll(f)){if(!(p instanceof File))throw new M(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",f);if(p.size>o)throw new M(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let y=new Uint8Array(await p.arrayBuffer()),g=qs(y);if(g===null)throw new M(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",f);c.push({bytes:y,mime:g})}if(c.length===0)throw new M(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await Vs(n.imageModels,u,"edit",e))return;let h=[{type:"input_text",text:a}];for(let{bytes:f,mime:p}of c)h.push({type:"input_image",image_url:`data:${p};base64,${Buffer.from(f).toString("base64")}`});try{let f=await js(n.clients,u,h,n.turn?le(n.turn):void 0,n.turn);Js(n.turn,f),Ws(e,f)}catch(f){throw Gs(f)}}catch(s){if(s instanceof Q){Tt(e,new M(413,s.message));return}if(s instanceof M){Tt(e,s);return}throw s}}var Pt="/v1/audio/speech";function oi(t){return t===Pt}var Ys=4096,Xs=18e4,Qs=5e3,rl=64*1024*1024,Zs=8,ei=5,ti=1024*1024,nt="voice_applied",_n="X-Urun-Voice-Applied",L=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function vr(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 wn=class extends L{constructor(e){super(502,e)}};function si(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 ii(t){return new L(502,`the runtime's ${nt} receipt ${JSON.stringify(t)} cannot be relayed as the ${_n} 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 ol(t,e,n){if(t){if(t.model=oe({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function ai(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var sl=2;function il(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>sl)return!1;return!0}function al(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 ni=new WeakMap,yn=new WeakMap;function ul(t,e){let n=yn.get(t)??0;if(n>=Zs)throw new L(503,`this model's speech queue is full \u2014 ${Zs} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${ei}s`,void 0,ei);yn.set(t,n+1);let r=ni.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return ni.set(t,s),(async()=>{await r;try{return await e()}finally{yn.set(t,(yn.get(t)??1)-1),o()}})()}async function ll(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new L(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 H))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 He(t){return t instanceof L?t:t instanceof $?new L(404,t.message):new L(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function ri(t,e,n,r,o,s,i,a,l){let u=a??(()=>{});return ul(e,async()=>{if(i?.()===!0)return null;let d=!1,c=!1,h=!1,f,p=new Promise(_=>{f=_}),y=[],g=()=>{c&&!h&&y.length>=o.quietRunFrames&&(h=!0,f())},w=e.onOutputAudio(_=>{let S=Buffer.from(_,"base64");if(S.byteLength===0)return;let T=il(S);if(!d){if(T)return;d=!0}if(T){y.push(S),g();return}for(let x of y)u(x);y.length=0,u(S),g()}),v=null,m,R,b;try{b=(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 S=new Promise(A=>{R=setTimeout(A,s.capMs)}),T=!1;for(;;){let A=b.next(),P=await Promise.race([A,S]);if(P===void 0){T=!0,A.catch(()=>{});break}if(P.done)break;let U=P.value;if(U.type==="error"){let W=U.error??{};throw await b.return?.(),new L(502,`speech upstream error: ${String(W.message??"upstream reported an error")}`)}if(U.type==="response.completed"){v=U.response??null,c=!0,l?.(v),g(),await b.return?.();break}}if(clearTimeout(R),T)throw new L(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(v===null)throw new L(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let x=!1;if(await Promise.race([p,new Promise(A=>{m=setTimeout(()=>{x=!0,A()},o.capMs)})]),m!==void 0&&clearTimeout(m),r.voice!==void 0){let A=v[nt];if(typeof A!="string"||A!==r.voice){let P=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof A=="string"?`${nt} ${JSON.stringify(A)}`:`no ${nt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw h?new wn(P):new L(502,P)}}if(!d)throw new L(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(x&&!h&&y.length<1)throw new L(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 v}catch(_){throw _ instanceof wn||await ll(t,n,b,s.returnBoundMs),_}finally{m!==void 0&&clearTimeout(m),R!==void 0&&clearTimeout(R),w()}})}function dl(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",_n)),t.write(a,l=>{l||(s+=a.byteLength,ai(e,s))}),t.writableLength>ti&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${ti} 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[nt];if(typeof l=="string"){if(!si(l))throw ii(l);t.addTrailers({[_n]:l})}}await new Promise(l=>{t.end(()=>l())})}},fail:i}}async function cl(t,e,n){let r;try{r=await t(e)}catch(o){throw He(o)}return r?!0:(vr(n,new L(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 pl={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},fl="wav, pcm";async function ui(t,e,n){let r=n.maxBodyBytes??rl,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${Pt}`);let i;try{i=JSON.parse((await mn(t,r)).toString("utf8")||"{}")}catch(m){throw m instanceof Q?new L(413,m.message):new L(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new L(400,"request body must be a JSON object");let a=i;for(let m of Object.keys(a))if(!pl[m])throw new L(400,`request field "${m}" 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.`,m);let l=a.input;if(typeof l!="string"||l.trim().length===0)throw new L(400,"input is required and must be a non-empty string","input");if(l.length>Ys)throw new L(400,`input is ${l.length} chars \u2014 over the ${Ys}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let u=a.model===void 0?void 0:a.model;if(u!==void 0&&typeof u!="string")throw new L(400,"model must be a string","model");let d=a.voice;if(d!==void 0&&(typeof d!="string"||d.trim().length===0))throw new L(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new L(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 ${Pt} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(u)}catch(m){throw He(m)}if(c.defect!==null)throw new L(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let h=typeof d=="string"?d:void 0;if(h!==void 0&&c.published.length>0&&!c.published.includes(h))throw new L(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let f=a.response_format??"wav";if(f!=="wav"&&f!=="pcm")throw new L(400,`response_format ${JSON.stringify(f)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${fl} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new L(400,"stream_format, when present, must be a string","stream_format");let p=a.speed;if(p!==void 0){if(typeof p!="number"||!Number.isFinite(p))throw new L(400,"speed, when present, must be a number","speed");if(p!==1)throw new L(400,`speed=${JSON.stringify(p)} 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 y=a.instructions;if(y!==void 0){if(typeof y!="string")throw new L(400,"instructions, when present, must be a string","instructions");if(y.trim().length>0)throw new L(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 ol(n.turn,n.clients,u);let g=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",g,g),!await cl(n.speechModels,u,e))return;if(typeof n.clients.openAudioOn!="function")throw new L(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 L(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 L(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let w;try{w=await n.clients.speechSessionHandle(u)}catch(m){throw He(m)}let v;try{v=await n.clients.openAudioOn(w)}catch(m){throw He(m)}n.turn&&(n.turn.sessionId=v.sessionId);try{if(f==="wav"){let m=[],R=await ri(n.clients,v,w,{model:u,text:l,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Xs,returnBoundMs:n.turnReturnBoundMs??Qs},s,_=>m.push(_),_=>{n.turn&&(n.turn.outputSeconds=we(_))});if(R===null||s())return;let b=Buffer.concat(m);if(h===void 0){let _=R[nt];if(typeof _=="string"){if(!si(_))throw ii(_);e.setHeader(_n,_)}}ai(n.turn,b.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([al(b.byteLength),b]))}else{let m=dl(e,n.turn,s,h===void 0),R;try{R=await ri(n.clients,v,w,{model:u,text:l,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Xs,returnBoundMs:n.turnReturnBoundMs??Qs},s,m.sink,b=>{n.turn&&(n.turn.outputSeconds=we(b))})}catch(b){let _=He(b);if(!m.started())throw _;n.turn&&(n.turn.streamError=!0),m.fail(_);return}if(R===null)return;try{await m.finish(R)}catch(b){let _=He(b);n.turn&&(n.turn.streamError=!0),m.fail(_);return}}}catch(m){throw He(m)}}catch(i){if(i instanceof Q){vr(e,new L(413,i.message));return}if(i instanceof L){vr(e,i);return}throw i}}var vn="/v1/audio/transcriptions";function li(t){return t===vn}var di="/v1/audio/models",ml=16*1024*1024,hl=64*1024*1024,B=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function br(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 ci(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 gl(t){if(!ci(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 yl(t,e,n){if(t){if(t.model=oe({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function _l(t,e){t&&(t.outputUnits=e.seconds)}async function wl(t,e,n,r,o,s){let i=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),a=[],l=null;for await(let u of i){if(a.push(u),u.type==="error"){let d=u.error??{},c=typeof d.type=="string"?d.type:"upstream_error",h=String(d.message??"upstream reported an error");throw new B(c==="invalid_request_error"?400:502,`transcription upstream error: ${h}`)}if(u.type==="response.completed"){l=u.response??null;break}}if(l===null)throw new B(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=we(l)),Qe(a,l)}function pi(t){return t instanceof B?t:t instanceof $?new B(404,t.message):new B(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function vl(t,e,n){let r;try{r=await t(e)}catch(o){throw pi(o)}return r?!0:(br(n,new B(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var bl=new Set(["file","model","language","response_format"]);async function fi(t,e,n){let r=n.maxBodyBytes??hl,o=n.maxAudioPartBytes??ml;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${vn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new B(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await hn(t,r)}catch(w){throw w instanceof Q?new B(413,w.message):new B(400,String(w instanceof Error?w.message:w))}let a=new Map;for(let w of i.keys()){if(!bl.has(w))throw new B(400,`form field "${w}" 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.`,w);a.set(w,(a.get(w)??0)+1)}for(let[w,v]of a)if(v>1)throw new B(400,`form field "${w}" appears ${v} 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`,w);let l=i.get("model");if(l!==null&&typeof l!="string")throw new B(400,"model must be a string field","model");let u=l===null?void 0:l,d=i.get("language");if(d!==null&&(typeof d!="string"||d.trim().length===0))throw new B(400,"language, when present, must be a non-empty string","language");let c=d===null?void 0:d,h=i.get("response_format")??"json";if(h!=="json")throw new B(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 f=i.get("file");if(!(f instanceof File))throw new B(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(f.size>o)throw new B(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let p=new Uint8Array(await f.arrayBuffer());if(!ci(p))throw new B(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let y=gl(p);if(y===null)throw new B(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await yl(n.turn,n.clients,u),n.stats?.request("audio_transcriptions",p.length,p.length),!await vl(n.transcriptionModels,u,e))return;let g=[{type:"input_audio",input_audio:{data:Buffer.from(p).toString("base64"),format:"wav"}}];try{let w=await wl(n.clients,u,g,c,n.turn?le(n.turn):void 0,n.turn);_l(n.turn,y),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:w}))}catch(w){throw pi(w)}}catch(s){if(s instanceof Q){br(e,new B(413,s.message));return}if(s instanceof B){br(e,s);return}throw s}}var Sn="/v1/usage/requests",mi=1e4,Sl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Oe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},q=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},bn=class extends q{constructor(e){super(e),this.name="UsageWithholdingError"}},_i=1024*1024;function Rr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Oe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Oe(`"${e}" must be an array of uuid strings`);if(n.length>mi)throw new Oe(`"${e}" carries ${n.length} ids; at most ${mi} 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"||!Sl.test(s))throw new Oe(`"${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 wi(t){return Rr(t,"inference_ids")}var kl=["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 rt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new q(`${n}: ${e} is not a non-empty string (got ${st(r)})`);return r}function Sr(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new q(`${n}: ${e} is neither null nor a non-empty string (got ${st(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 q(`${n}: ${e} is not a number (got ${st(o)})`);if(r&&!Number.isSafeInteger(s))throw new q(`${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 q(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Rl=40,hi=64,gi=600;function vi(t){let e=Object.keys(t).sort(),r=e.slice(0,Rl).map(o=>o.length>hi?`${o.slice(0,hi)}\u2026`:o).join(", ");return r.length>gi&&(r=`${r.slice(0,gi)}\u2026`),`${e.length} keys present: [${r}]`}function st(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function kr(t){Ie(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
23
- `)}function xl(t,e){let n;try{n=t(e)}catch{yi(t,e);return}El(n)&&Promise.resolve(n).catch(()=>{yi(t,e)})}function El(t){return typeof t?.then=="function"}function yi(t,e){if(t!==kr)try{kr(e)}catch{}}function bi(t,e=kr){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?vi(t):st(t);throw new q(`the usage surface answered without a "requests" array: got ${st(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Al(n[o],s))}catch(i){if(i instanceof bn||!(i instanceof q))throw i;xl(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new q(`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 Al(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new q(`${e} is not an object: got ${st(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new bn(`${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 kl)if(!Object.hasOwn(n,o))throw new q(`${e} has no "${o}" column (${vi(n)})`);let r=ot(n,"http_status",e,!0);if(r===null)throw new q(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:rt(n,"inference_id",e),model_id:rt(n,"model_id",e),identity_kind:rt(n,"identity_kind",e),variant:Sr(n,"variant",e),task:rt(n,"task",e),http_status:r,started_at:rt(n,"started_at",e),completed_at:rt(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:Sr(n,"price_version",e),priced_at:Sr(n,"priced_at",e)}}function kn(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 q(`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 q(`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 On=require("@urun-sh/core");var xr=require("@urun-sh/core"),ve=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)}},Er=33e4;function Si(t,e=Er){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((u,d)=>{o=d}),i=setTimeout(()=>o(new Rn),e),a;try{a=await Promise.race([r.next(),s])}catch(u){throw u instanceof H||u instanceof xr.SessionFailedError&&u.kind==="transport-failed"?u:u instanceof Rn?(await r.return?.(void 0),new ve("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 ve("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 ve("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield l}})()}var Rn=class extends Error{constructor(){super("stream idle timeout")}};function ki(t){return t instanceof ve?!1:t instanceof H?!0:t instanceof xr.SessionFailedError?t.kind==="transport-failed":!1}var Ct="/partners/huggingface/v1/billing/requests";function Il(t){return Rr(t,"requestIds")}function Ol(t){return t>=200&&t<=399}function Tl(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Ol(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Ri(t,e){let n=Il(t),r=await e(n);return kn(r,n),Tl(r)}var Pl={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Cl(t){return Pl[t]??null}var Ii=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Ll(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Ml(t){return t==="surface"}function Nl(t){let e=t?.ledgerFailureReason;return Ii.includes(e)?e:"unknown"}var $l=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],xi=["priced","unpriced"],Ul={written:xi,already_written:xi,skipped:$l,failed:Ii},Oi=Object.entries(Ul).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Dl(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Fl(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 Bl=256,Ei=4096,Mt=12e4,Hl=250,ql=8e3,qe=[],Ai=new Set,Nt=0,Lt=!1;function Ti(){return qe.length}function Pi(t=Date.now()){let e=qe[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var jl=new Set;function Gl(){return Nt===0&&qe.length===0}function Vl(){if(Gl()){Lt=!1;for(let t of[...jl])t()}}function Ci(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
24
- `}function Jl(t){Ie(process.stdout,t)}function Li(t,e){try{t(e)}catch{}}function Mi(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Jl,o=Cl(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),Li(r,Ci("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:Fl(e),completed_at:e.ts,billable_outcome:Dl(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(qe.length>=Ei){i("queue_full",`${qe.length} ledger writes are already waiting (capacity ${Ei}, ${Nt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}qe.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Nt<Bl&&(Nt+=1,Wl())}async function Wl(){try{for(;;){let t=Kl();if(t===void 0)return;Ai.add(t);try{await zl(t)}finally{Ai.delete(t)}}}finally{Nt-=1,Vl()}}function Kl(){let t=Date.now();for(;;){let e=qe.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Mt)return e;it(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 ${Mt}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 zl(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);it(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=Ll(o);if(s!==null){it(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=Nl(o),a=Date.now()-t.queuedAt;if(Lt){it(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(Ml(i)&&a<Mt){if(await Xl(Yl(t.attempts)),Lt||Date.now()-t.queuedAt>=Mt){let l=Date.now()-t.queuedAt;it(t,{outcome:"failed",reason:Lt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Lt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:l,error:`this row's backoff outlived the ${Mt}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}it(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 Yl(t){return Math.min(ql,Hl*2**Math.max(0,t-1))}function Xl(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function it(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Li(t.report,Ci(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var Ir="x-urun-profile",$t="voice";var ie=class extends Error{status=400},Ql=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Zl=/\s/;function ed(t){return Ql.test(t)}function Ar(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ie(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Ni(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 ie(`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 ie(`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 ie(`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 $i(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 ie(`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 ie(`the ${Ir} header is empty \u2014 the only profile this lane accepts is "${$t}" (omit the header for the ordinary lane)`);if(u!==$t)throw new ie(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${$t}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==$t)throw new ie(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${$t}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new ie("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 ie("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:Ni(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:Ni(l,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Ar(l,"sentence_flush",!0),includeReasoning:Ar(l,"include_reasoning",!1),metadata:Ar(l,"metadata",!1)}}var xn=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&&ed(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(Zl.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 Pr(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function nd(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 te(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function z(t,e,n,r="invalid_request_error",o){te(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Cr(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);te(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function me(t,e,n,r){te(t,e,{type:"error",error:{type:n,message:r}})}function at(t,e,n){if(e==="anthropic"){te(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}te(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var rd=64*1024*1024,Ut=class extends Error{};async function Ui(t,e=rd){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Ut(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function je(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 Fi(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 En(t){let e=Fi(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Di(t){let e=En(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function od(t,e){let n=Fi(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function sd(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 id(t,e){let n=sd(e);n&&(t.timing=n),t.outputSeconds=we(e)}function Ge(t,e){od(t,e),id(t,e)}async function Tn(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 Bi(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 ad(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 An=class extends Error{};function ud(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 An(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function ld(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:ud(n.role,n.content)})}return e}function Or(t){return Ye(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 dd(t,e,n,r,o,s){let i=kt(s.id),a=t.stream===!0;if(s.model=oe(t),s.stream=a,await Tn(s,e,typeof t.model=="string"?t.model:void 0),a){let w;try{w=await xt({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(v){if(v instanceof $){at(r,"openai",v);return}if(v instanceof de){z(r,v.status,v.message);return}throw v}Pr(r);for await(let v of w.events)v.type==="error"&&(s.streamError=!0),v.type==="response.completed"&&Ge(s,v.response),r.write(`event: ${String(v.type??"message")}
25
- data: ${JSON.stringify(v)}
22
+ ${wd(n)}\r
23
+ `),t.destroy()}function vd(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
24
+ `}function bd(t){He(process.stdout,t)}function Sd(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function oo(t){return t.audioSession?.audio.sessionId??void 0}function Gn(t,e){let n=new Ai.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==rn)return;r.add(s),s.on("close",()=>{r.delete(s)});let l=T("rtup"),u=Sd(o),d=g=>{(e.log??bd)(vd(g))};d({stage:"accept",conn:l,model:u}),s.resume();let c=new AbortController,p=null,y=g=>{p??=g,c.abort(new Error(p))},h=()=>y("client socket closed"),_=()=>y("client socket closed (half-close)"),A=g=>y(`client socket error: ${g.message}`);s.once("close",h),s.once("end",_),s.once("error",A);let v=()=>{s.removeListener("close",h),s.removeListener("end",_),s.removeListener("error",A)},f=g=>{d({stage:"close",conn:l,model:u,...g})},m=g=>{let S=g,b=S.session!=null&&typeof S.session.sendResponseCreate=="function",k=S.clients!=null&&typeof S.clients.createResponse=="function";if(!b&&!k)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((x,R)=>{n.handleUpgrade(o,s,i,I=>{try{new nn({ws:I,binding:g,operatorLog:e.operatorLog,onClosed:(E,C)=>{f({while:"live",reason:C.reason})}}),d({stage:"admit",conn:l,model:u,...oo(g)===void 0?{}:{session:oo(g)}}),x()}catch(E){R(E)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async g=>{if(c.signal.aborted){v();let S=oo(g);try{await g.release?.()}catch(b){f({while:"queued",...S===void 0?{}:{session:S},reason:p??"client socket closed",release_failed:b instanceof Error?b.message:String(b)});return}f({while:"queued",...S===void 0?{}:{session:S},reason:p??"client socket closed",released:!0}),s.destroy();return}v(),await m(g)}).catch(g=>{let S=g instanceof so.SessionFailedError?Un(g):null,b=null;if(g!==null&&typeof g=="object"&&"status"in g){let I=g.status;typeof I=="number"&&(b=I)}let k=b??S?.status??502,x=g instanceof Error?g.message:String(g),R=b!==null?x:S!==null?en(S,g instanceof so.SessionFailedError&&g.status.sessionId?`session ${g.status.sessionId}`:void 0):ge(g).message;f({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:x,status:k}}),s.destroyed||_d(s,k,R)}).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 Ca=require("crypto");var Rc=require("http");var se=class extends Error{};async function Vn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new se(`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 se(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function Wn(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 se(`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 se?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Ii="/v1/images/generations",Jn="/v1/images/edits";function Oi(t){return t===Ii||t===Jn}var Ti="/v1/images/models";async function Pi(t,e,n){if(t){if(t.model=de({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 D=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},kd=16*1024*1024,Ci=64*1024*1024;function Li(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 on(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 Mi(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 _=h.error??{},A=typeof _.message=="string"&&_.message.length>0&&xe(_.message)?_.message:null;throw A===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(h)}`),new D(502,"the image upstream failed while serving this request")):new D(502,`image upstream error: ${A}`)}if(h.type==="response.completed"){l=h.response??null;break}}if(l===null)throw new D(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Pe(l));let u=l.images;if(!Array.isArray(u)||u.length!==1||typeof u[0]!="string"||u[0].length===0)throw new D(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(Li(p)===null)throw new D(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 Ni(t,e){if(t instanceof D)return t;if(t instanceof _e)throw t;return t instanceof F?new D(404,t.message):new D(502,yt("image",t,e))}async function $i(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 on(r,new D(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 Ui(t,e){t&&(t.outputUnits=e.images.length)}function Di(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 Rd={model:!0,prompt:!0,response_format:!0,n:!0};async function Fi(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Ci;try{if(t.method!=="POST")throw new D(405,`${String(t.method)} is not supported on ${Ii}`);let s;try{s=JSON.parse((await Vn(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof se?new D(413,p.message):new D(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new D(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!Rd[p])throw new D(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 D(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 D(400,"model must be a string","model");await Pi(n.turn,n.clients,l);let u=i.n??1;if(u!==1)throw new D(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 D(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 $i(n.imageModels,l,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Mi(n.clients,l,c,n.turn?ye(n.turn):void 0,n.turn,r);Ui(n.turn,p),Di(e,p)}catch(p){throw Ni(p,r)}}catch(s){if(s instanceof se){on(e,new D(413,s.message));return}if(s instanceof D){on(e,s);return}throw s}}var xd={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Bi(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Ci,s=n.maxImagePartBytes??kd;try{if(t.method!=="POST")throw new D(405,`${String(t.method)} is not supported on ${Jn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new D(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await Wn(t,o)}catch(h){throw h instanceof se?new D(413,h.message):new D(400,String(h instanceof Error?h.message:h))}let l=a.get("prompt");if(typeof l!="string"||l.trim().length===0)throw new D(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 D(400,"model must be a string field","model");let d=u===null?void 0:u;await Pi(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new D(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(!xd[h])throw new D(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 _ of a.getAll(h)){if(!(_ instanceof File))throw new D(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",h);if(_.size>s)throw new D(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,h);let A=new Uint8Array(await _.arrayBuffer()),v=Li(A);if(v===null)throw new D(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:A,mime:v})}if(p.length===0)throw new D(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",l.length,l.length),!await $i(n.imageModels,d,"edit",e))return;let y=[{type:"input_text",text:l}];for(let{bytes:h,mime:_}of p)y.push({type:"input_image",image_url:`data:${_};base64,${Buffer.from(h).toString("base64")}`});try{let h=await Mi(n.clients,d,y,n.turn?ye(n.turn):void 0,n.turn,r);Ui(n.turn,h),Di(e,h)}catch(h){throw Ni(h,r)}}catch(i){if(i instanceof se){on(e,new D(413,i.message));return}if(i instanceof D){on(e,i);return}throw i}}var sn="/v1/audio/speech";function zi(t){return t===sn}var Hi=4096,ji=18e4,qi=5e3,Ed=64*1024*1024,Gi=8,Vi=5,Wi=1024*1024,vt="voice_applied",zn="X-Urun-Voice-Applied",N=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 Yn=class extends N{constructor(e){super(502,e)}};function Yi(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 Xi(t){return new N(502,`the runtime's ${vt} receipt ${JSON.stringify(t)} cannot be relayed as the ${zn} 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 Ad(t,e,n){if(t){if(t.model=de({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 Qi(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Id=2;function Od(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Id)return!1;return!0}function Td(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 Ji=new WeakMap,Kn=new WeakMap;function Pd(t,e){let n=Kn.get(t)??0;if(n>=Gi)throw new N(503,`this model's speech queue is full \u2014 ${Gi} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Vi}s`,void 0,Vi);Kn.set(t,n+1);let r=Ji.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Ji.set(t,s),(async()=>{await r;try{return await e()}finally{Kn.set(t,(Kn.get(t)??1)-1),o()}})()}async function Cd(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new N(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 U))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 nt(t,e){if(t instanceof N)return t;if(t instanceof _e)throw t;return t instanceof F?new N(404,t.message):new N(502,yt("speech",t,e))}async function Ki(t,e,n,r,o,s,i,a,l,u){let d=u??(p=>console.error(p)),c=a??(()=>{});return Pd(e,async()=>{if(i?.()===!0)return null;let p=!1,y=!1,h=!1,_,A=new Promise(k=>{_=k}),v=[],f=()=>{y&&!h&&v.length>=o.quietRunFrames&&(h=!0,_())},m=e.onOutputAudio(k=>{let x=Buffer.from(k,"base64");if(x.byteLength===0)return;let R=Od(x);if(!p){if(R)return;p=!0}if(R){v.push(x),f();return}for(let I of v)c(I);v.length=0,c(x),f()}),w=null,g,S,b;try{b=(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 x=new Promise(E=>{S=setTimeout(E,s.capMs)}),R=!1;for(;;){let E=b.next(),C=await Promise.race([E,x]);if(C===void 0){R=!0,E.catch(()=>{});break}if(C.done)break;let $=C.value;if($.type==="error"){let B=$.error??{};await b.return?.();let K=typeof B.message=="string"&&B.message.length>0&&xe(B.message)?B.message:null;throw K===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify($)}`),new N(502,"the speech upstream failed while serving this request")):new N(502,`speech upstream error: ${K}`)}if($.type==="response.completed"){w=$.response??null,y=!0,l?.(w),f(),await b.return?.();break}}if(clearTimeout(S),R)throw new N(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(w===null)throw new N(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let I=!1;if(await Promise.race([A,new Promise(E=>{g=setTimeout(()=>{I=!0,E()},o.capMs)})]),g!==void 0&&clearTimeout(g),r.voice!==void 0){let E=w[vt];if(typeof E!="string"||E!==r.voice){let C=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof E=="string"?`${vt} ${JSON.stringify(E)}`:`no ${vt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw h?new Yn(C):new N(502,C)}}if(!p)throw new N(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(I&&!h&&v.length<1)throw new N(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 w}catch(k){throw k instanceof Yn||await Cd(t,n,b,s.returnBoundMs),k}finally{g!==void 0&&clearTimeout(g),S!==void 0&&clearTimeout(S),m()}})}function Ld(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",zn)),t.write(a,l=>{l||(s+=a.byteLength,Qi(e,s))}),t.writableLength>Wi&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Wi} 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[vt];if(typeof l=="string"){if(!Yi(l))throw Xi(l);t.addTrailers({[zn]:l})}}await new Promise(l=>{t.end(()=>l())})}},fail:i}}async function Md(t,e,n,r){let o;try{o=await t(e)}catch(s){throw nt(s,r)}return o?!0:(io(n,new N(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 Nd={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},$d="wav, pcm";async function Zi(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??Ed,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new N(405,`${String(t.method)} is not supported on ${sn}`);let a;try{a=JSON.parse((await Vn(t,o)).toString("utf8")||"{}")}catch(w){throw w instanceof se?new N(413,w.message):new N(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new N(400,"request body must be a JSON object");let l=a;for(let w of Object.keys(l))if(!Nd[w])throw new N(400,`request field "${w}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,w);let u=l.input;if(typeof u!="string"||u.trim().length===0)throw new N(400,"input is required and must be a non-empty string","input");if(u.length>Hi)throw new N(400,`input is ${u.length} chars \u2014 over the ${Hi}-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 N(400,"model must be a string","model");let c=l.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new N(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new N(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 ${sn} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(w){throw nt(w,r)}if(p.defect!==null)throw new N(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 y=typeof c=="string"?c:void 0;if(y!==void 0&&p.published.length>0&&!p.published.includes(y))throw new N(400,`voice ${JSON.stringify(y)} 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 N(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 ${$d} \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 N(400,"stream_format, when present, must be a string","stream_format");let _=l.speed;if(_!==void 0){if(typeof _!="number"||!Number.isFinite(_))throw new N(400,"speed, when present, must be a number","speed");if(_!==1)throw new N(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 A=l.instructions;if(A!==void 0){if(typeof A!="string")throw new N(400,"instructions, when present, must be a string","instructions");if(A.trim().length>0)throw new N(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 Ad(n.turn,n.clients,d);let v=Buffer.byteLength(JSON.stringify(l));if(n.stats?.request("audio_speech",v,v),!await Md(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new N(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 N(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 N(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(w){throw nt(w,r)}let m;try{m=await n.clients.openAudioOn(f)}catch(w){throw nt(w,r)}n.turn&&(n.turn.sessionId=m.sessionId);try{if(h==="wav"){let w=[],g=await Ki(n.clients,m,f,{model:d,text:u,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??ji,returnBoundMs:n.turnReturnBoundMs??qi},i,b=>w.push(b),b=>{n.turn&&(n.turn.outputSeconds=Pe(b))},r);if(g===null||i())return;let S=Buffer.concat(w);if(y===void 0){let b=g[vt];if(typeof b=="string"){if(!Yi(b))throw Xi(b);e.setHeader(zn,b)}}Qi(n.turn,S.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Td(S.byteLength),S]))}else{let w=Ld(e,n.turn,i,y===void 0),g;try{g=await Ki(n.clients,m,f,{model:d,text:u,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??ji,returnBoundMs:n.turnReturnBoundMs??qi},i,w.sink,S=>{n.turn&&(n.turn.outputSeconds=Pe(S))},r)}catch(S){let b=nt(S,r);if(!w.started())throw b;n.turn&&(n.turn.streamError=!0),w.fail(b);return}if(g===null)return;try{await w.finish(g)}catch(S){let b=nt(S,r);n.turn&&(n.turn.streamError=!0),w.fail(b);return}}}catch(w){throw nt(w,r)}}catch(a){if(a instanceof se){io(e,new N(413,a.message));return}if(a instanceof N){io(e,a);return}throw a}}var Xn="/v1/audio/transcriptions";function ea(t){return t===Xn}var ta="/v1/audio/models",Ud=16*1024*1024,Dd=64*1024*1024,W=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function ao(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 na(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 Fd(t){if(!na(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 Bd(t,e,n){if(t){if(t.model=de({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 Hd(t,e){t&&(t.outputUnits=e.seconds)}async function jd(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??{},y=typeof p.type=="string"?p.type:"upstream_error",h=typeof p.message=="string"&&p.message.length>0&&xe(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 W(y==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new W(y==="invalid_request_error"?400:502,`transcription upstream error: ${h}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new W(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=Pe(d)),gt(u,d)}function ra(t,e){if(t instanceof W)return t;if(t instanceof _e)throw t;return t instanceof F?new W(404,t.message):new W(502,yt("transcription",t,e))}async function qd(t,e,n,r){let o;try{o=await t(e)}catch(s){throw ra(s,r)}return o?!0:(ao(n,new W(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 Gd=new Set(["file","model","language","response_format"]);async function oa(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Dd,s=n.maxAudioPartBytes??Ud;try{if(t.method!=="POST")throw new W(405,`${String(t.method)} is not supported on ${Xn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new W(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await Wn(t,o)}catch(f){throw f instanceof se?new W(413,f.message):new W(400,String(f instanceof Error?f.message:f))}let l=new Map;for(let f of a.keys()){if(!Gd.has(f))throw new W(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,m]of l)if(m>1)throw new W(400,`form field "${f}" appears ${m} 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 W(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 W(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,y=a.get("response_format")??"json";if(y!=="json")throw new W(400,`response_format ${JSON.stringify(y)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let h=a.get("file");if(!(h instanceof File))throw new W(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 W(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let _=new Uint8Array(await h.arrayBuffer());if(!na(_))throw new W(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 A=Fd(_);if(A===null)throw new W(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 Bd(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",_.length,_.length),!await qd(n.transcriptionModels,d,e,r))return;let v=[{type:"input_audio",input_audio:{data:Buffer.from(_).toString("base64"),format:"wav"}}];try{let f=await jd(n.clients,d,v,p,n.turn?ye(n.turn):void 0,n.turn,r);Hd(n.turn,A),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:f}))}catch(f){throw ra(f,r)}}catch(i){if(i instanceof se){ao(e,new W(413,i.message));return}if(i instanceof W){ao(e,i);return}throw i}}var Zn="/v1/usage/requests",sa=1e4,Vd=/^[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},Z=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Qn=class extends Z{constructor(e){super(e),this.name="UsageWithholdingError"}},ua=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>sa)throw new je(`"${e}" carries ${n.length} ids; at most ${sa} 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"||!Vd.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 da(t){return co(t,"inference_ids")}var Wd=["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 bt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new Z(`${n}: ${e} is not a non-empty string (got ${kt(r)})`);return r}function lo(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new Z(`${n}: ${e} is neither null nor a non-empty string (got ${kt(r)})`);return r}function St(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 Z(`${n}: ${e} is not a number (got ${kt(o)})`);if(r&&!Number.isSafeInteger(s))throw new Z(`${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 Z(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Jd=40,ia=64,aa=600;function ca(t){let e=Object.keys(t).sort(),r=e.slice(0,Jd).map(o=>o.length>ia?`${o.slice(0,ia)}\u2026`:o).join(", ");return r.length>aa&&(r=`${r.slice(0,aa)}\u2026`),`${e.length} keys present: [${r}]`}function kt(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function uo(t){He(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
25
+ `)}function Kd(t,e){let n;try{n=t(e)}catch{la(t,e);return}zd(n)&&Promise.resolve(n).catch(()=>{la(t,e)})}function zd(t){return typeof t?.then=="function"}function la(t,e){if(t!==uo)try{uo(e)}catch{}}function pa(t,e=uo){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?ca(t):kt(t);throw new Z(`the usage surface answered without a "requests" array: got ${kt(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Yd(n[o],s))}catch(i){if(i instanceof Qn||!(i instanceof Z))throw i;Kd(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new Z(`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 Yd(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Z(`${e} is not an object: got ${kt(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new Qn(`${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 Wd)if(!Object.hasOwn(n,o))throw new Z(`${e} has no "${o}" column (${ca(n)})`);let r=St(n,"http_status",e,!0);if(r===null)throw new Z(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:bt(n,"inference_id",e),model_id:bt(n,"model_id",e),identity_kind:bt(n,"identity_kind",e),variant:lo(n,"variant",e),task:bt(n,"task",e),http_status:r,started_at:bt(n,"started_at",e),completed_at:bt(n,"completed_at",e),prompt_tokens:St(n,"prompt_tokens",e,!0),completion_tokens:St(n,"completion_tokens",e,!0),output_units:St(n,"output_units",e,!1),output_minutes:St(n,"output_minutes",e,!1),cost_nano_usd:St(n,"cost_nano_usd",e,!0),price_version:lo(n,"price_version",e),priced_at:lo(n,"priced_at",e)}}function er(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 Z(`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 Z(`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 or=require("@urun-sh/core");var an="/partners/huggingface/v1/billing/requests";function Xd(t){return co(t,"requestIds")}function Qd(t){return t>=200&&t<=399}function Zd(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Qd(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function fa(t,e){let n=Xd(t),r=await e(n);return er(r,n),Zd(r)}var ec={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function tc(t){return ec[t]??null}var ya=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function nc(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function rc(t){return t==="surface"}function oc(t){let e=t?.ledgerFailureReason;return ya.includes(e)?e:"unknown"}var sc=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ma=["priced","unpriced"],ic={written:ma,already_written:ma,skipped:sc,failed:ya},wa=Object.entries(ic).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function ac(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function lc(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 uc=256,ga=4096,un=12e4,dc=250,cc=8e3,rt=[],ha=new Set,dn=0,ln=!1;function _a(){return rt.length}function va(t=Date.now()){let e=rt[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var pc=new Set;function fc(){return dn===0&&rt.length===0}function mc(){if(fc()){ln=!1;for(let t of[...pc])t()}}function ba(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
26
+ `}function gc(t){He(process.stdout,t)}function Sa(t,e){try{t(e)}catch{}}function ka(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??gc,o=tc(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),Sa(r,ba("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:lc(e),completed_at:e.ts,billable_outcome:ac(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(rt.length>=ga){i("queue_full",`${rt.length} ledger writes are already waiting (capacity ${ga}, ${dn} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}rt.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),dn<uc&&(dn+=1,hc())}async function hc(){try{for(;;){let t=yc();if(t===void 0)return;ha.add(t);try{await wc(t)}finally{ha.delete(t)}}}finally{dn-=1,mc()}}function yc(){let t=Date.now();for(;;){let e=rt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<un)return e;Rt(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 ${un}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 wc(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Rt(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=nc(o);if(s!==null){Rt(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=oc(o),a=Date.now()-t.queuedAt;if(ln){Rt(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(rc(i)&&a<un){if(await vc(_c(t.attempts)),ln||Date.now()-t.queuedAt>=un){let l=Date.now()-t.queuedAt;Rt(t,{outcome:"failed",reason:ln?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:ln?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:l,error:`this row's backoff outlived the ${un}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}Rt(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 _c(t){return Math.min(cc,dc*2**Math.max(0,t-1))}function vc(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Rt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Sa(t.report,ba(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var fo="x-urun-profile",cn="voice";var ce=class extends Error{status=400},bc=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Sc=/\s/;function kc(t){return bc.test(t)}function po(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ce(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Ra(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 ce(`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 ce(`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 ce(`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 xa(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 ce(`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 ce(`the ${fo} header is empty \u2014 the only profile this lane accepts is "${cn}" (omit the header for the ordinary lane)`);if(u!==cn)throw new ce(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${cn}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==cn)throw new ce(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${cn}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new ce("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 ce("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:Ra(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:Ra(l,"flush_max_ms",250,{max:2147483647}),sentenceFlush:po(l,"sentence_flush",!0),includeReasoning:po(l,"include_reasoning",!1),metadata:po(l,"metadata",!1)}}var xt=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&&kc(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(Sc.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 ho(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function xc(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 ie(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function J(t,e,n,r="invalid_request_error",o){ie(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function yo(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Oe(r),a=i??Ee(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"),ie(t,u,{error:{message:a,type:o,code:l}})}function Ae(t,e,n,r){ie(t,e,{type:"error",error:{type:n,message:r}})}function Et(t,e,n){if(e==="anthropic"){ie(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ie(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Ec=64*1024*1024,pn=class extends Error{};async function Ea(t,e=Ec){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new pn(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function ot(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 Ia(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 tr(t){let e=Ia(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Aa(t){let e=tr(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Ac(t,e){let n=Ia(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Ic(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 Oc(t,e){let n=Ic(e);n&&(t.timing=n),t.outputSeconds=Pe(e)}function st(t,e){Ac(t,e),Oc(t,e)}async function sr(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 Oa(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 Tc(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 nr=class extends Error{};function Pc(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 nr(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Cc(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:Pc(n.role,n.content)})}return e}function mo(t){return ft(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 Lc(t,e,n,r,o,s,i){let a=Yt(s.id),l=t.stream===!0;if(s.model=de(t),s.stream=l,await sr(s,e,typeof t.model=="string"?t.model:void 0),l){let f;try{f=await Qt({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(m){if(m instanceof F){Et(r,"openai",m);return}if(m instanceof we){J(r,m.status,m.message);return}if(m instanceof Se||m instanceof oe){r.setHeader("retry-after","2"),J(r,503,m.message,"capacity_error");return}throw m}ho(r);for await(let m of f.events){if(m.type==="error"){s.streamError=!0;let w=m.error,g=Oe(w),S=g??Ee(s.id);g===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(m)}`),r.write(`event: error
27
+ data: ${JSON.stringify({error:{message:S,type:w?.type??"upstream_error",code:w?.code??null}})}
26
28
 
27
- `);r.write(`data: [DONE]
29
+ `),r.end();return}m.type==="response.completed"&&st(s,m.response),r.write(`event: ${String(m.type??"message")}
30
+ data: ${JSON.stringify(m)}
28
31
 
29
- `),r.end();return}let l;try{l=Ze(n,t)}catch(w){if(w instanceof de){z(r,w.status,w.message);return}throw w}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let u=t.store!==!1,d=oe(t);o.model(d);let c=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await ir(e,t,l,!1,le(s))}catch(w){if(w instanceof $){at(r,"openai",w);return}if(w instanceof de){z(r,w.status,w.message);return}throw w}let f=[],p=null;for await(let w of o.track(h,d,s)){if(f.push(w),w.type==="error"){Cr(r,w);return}w.type==="response.completed"&&(p=w.response)}if(p==null){z(r,502,"upstream produced no response.completed event","upstream_error");return}Ge(s,p);let y=Qe(f,p),g=Fe(c,Ye(p).length,y);if(g){z(r,502,De(d,g),"upstream_error");return}u&&n.remember(i,l,sr(p,y),u),te(r,200,{...p,id:i})}async function cd(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){z(n,400,"chat/completions requires a messages array");return}let a;try{a=$i(s,t)}catch(x){if(x instanceof ie){z(n,x.status,x.message);return}throw x}let l=String(t.model??"urun"),u=vs(o.id),d;try{d=ld(i)}catch(x){if(x instanceof An){z(n,400,x.message);return}throw x}let c=oe(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Tn(o,e,typeof t.model=="string"?t.model:void 0);let h=Array.isArray(t.tools)&&t.tools.length>0,f;try{f=await e.createResponse({model:t.model,input:d,stream:!0,tools:ad(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}:{}},le(o))}catch(x){if(x instanceof $){at(n,"openai",x);return}throw x}if(t.stream===!0){a?nd(n):Pr(n);let x=[],A=new Ee,P="",U=a?new xn(a,re=>{n.write(`data: ${JSON.stringify(je(u,l,{content:re},null))}
32
+ `)}r.write(`data: [DONE]
30
33
 
31
- `)}):null,W=re=>{U?.flush(),n.write(re),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:u,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
34
+ `),r.end();return}let u;try{u=ht(n,t)}catch(f){if(f instanceof we){J(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=de(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,y;try{y=await Gr(e,t,u,!1,ye(s))}catch(f){if(f instanceof F){Et(r,"openai",f);return}if(f instanceof we){J(r,f.status,f.message);return}if(f instanceof Se||f instanceof oe){r.setHeader("retry-after","2"),J(r,503,f.message,"capacity_error");return}throw f}let h=[],_=null;for await(let f of o.track(y,c,s)){if(h.push(f),f.type==="error"){yo(r,f,{inferenceId:s.id,operatorError:i});return}f.type==="response.completed"&&(_=f.response)}if(_==null){J(r,502,"upstream produced no response.completed event","upstream_error");return}st(s,_);let A=gt(h,_),v=tt(p,ft(_).length,A);if(v){J(r,502,et(c,v),"upstream_error");return}d&&n.remember(a,u,qr(_,A),d),ie(r,200,{..._,id:a})}async function Mc(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){J(n,400,"chat/completions requires a messages array");return}let l;try{l=xa(s,t)}catch(R){if(R instanceof ce){J(n,R.status,R.message);return}throw R}let u=String(t.model??"urun"),d=ui(o.id),c;try{c=Cc(a)}catch(R){if(R instanceof nr){J(n,400,R.message);return}throw R}let p=de(t);r.model(p),o.model=p,o.stream=t.stream===!0,await sr(o,e,typeof t.model=="string"?t.model:void 0);let y=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:c,stream:!0,tools:Tc(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}:{}},ye(o))}catch(R){if(R instanceof F){Et(n,"openai",R);return}if(R instanceof Se||R instanceof oe){n.setHeader("retry-after","2"),J(n,503,R.message,"capacity_error");return}throw R}if(t.stream===!0){l?xc(n):ho(n);let R=[],I=new De,E="",C=l?new xt(l,B=>{n.write(`data: ${JSON.stringify(ot(d,u,{content:B},null))}
32
35
 
33
- `),n.write(`data: ${JSON.stringify(je(u,l,{role:"assistant"},null))}
36
+ `)}):null,$=B=>{C?.flush(),n.write(B),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}})}
34
37
 
35
- `);for await(let J of r.track(f,c,o)){x.push(J);let Z=Xe(J);if(J.type==="response.output_text.delta"&&typeof J.delta=="string")P+=J.delta,U?U.push(J.delta):n.write(`data: ${JSON.stringify(je(u,l,{content:J.delta},null))}
38
+ `),n.write(`data: ${JSON.stringify(ot(d,u,{role:"assistant"},null))}
36
39
 
37
- `);else if(J.type==="response.reasoning_text.delta"&&typeof J.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(je(u,l,{reasoning_content:J.delta},null))}
40
+ `);for await(let X of r.track(h,p,o)){R.push(X);let ae=mt(X);if(X.type==="response.output_text.delta"&&typeof X.delta=="string")E+=X.delta,C?C.push(X.delta):n.write(`data: ${JSON.stringify(ot(d,u,{content:X.delta},null))}
38
41
 
39
- `);else if(Z){U?.flush();let{call:Pe,isNew:C}=A.add(Z),N=C?{index:Z.tool_index,id:Pe.id??`call_${Z.tool_index}`,type:"function",function:{name:Pe.name??"",arguments:Z.delta}}:{index:Z.tool_index,function:{arguments:Z.delta}};n.write(`data: ${JSON.stringify(je(u,l,{tool_calls:[N]},null))}
42
+ `);else if(X.type==="response.reasoning_text.delta"&&typeof X.delta=="string")(!l||l.includeReasoning)&&n.write(`data: ${JSON.stringify(ot(d,u,{reasoning_content:X.delta},null))}
40
43
 
41
- `)}else if(J.type==="error"){o.streamError=!0,W(`data: ${JSON.stringify({error:J})}
44
+ `);else if(ae){C?.flush();let{call:M,isNew:H}=I.add(ae),q=H?{index:ae.tool_index,id:M.id??`call_${ae.tool_index}`,type:"function",function:{name:M.name??"",arguments:ae.delta}}:{index:ae.tool_index,function:{arguments:ae.delta}};n.write(`data: ${JSON.stringify(ot(d,u,{tool_calls:[q]},null))}
42
45
 
43
- `);return}}let re=Or(fe(x)),pe=Fe(h,A.size+re.length,P);if(pe){o.streamError=!0,W(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:De(c,pe)}})}
46
+ `)}else if(X.type==="error"){o.streamError=!0;let M=X.error??{},H=Oe(M),q=H??Ee(o.id);H===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(X)}`),$(`data: ${JSON.stringify({error:{message:q,type:M.type??"upstream_error",code:M.code??null}})}
44
47
 
45
- `);return}U?.flush(),A.size===0&&re.length>0&&n.write(`data: ${JSON.stringify(je(u,l,{tool_calls:re},null))}
48
+ `);return}}let B=mo(Ie(R)),K=tt(y,I.size+B.length,E);if(K){o.streamError=!0,$(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:et(p,K)}})}
46
49
 
47
- `);let be=A.size>0||re.length>0;n.write(`data: ${JSON.stringify(je(u,l,{},be?"tool_calls":"stop"))}
50
+ `);return}C?.flush(),I.size===0&&B.length>0&&n.write(`data: ${JSON.stringify(ot(d,u,{tool_calls:B},null))}
48
51
 
49
- `);let V=En(fe(x));Ge(o,fe(x)),V&&n.write(`data: ${JSON.stringify({id:u,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:Di(fe(x))})}
52
+ `);let j=I.size>0||B.length>0;n.write(`data: ${JSON.stringify(ot(d,u,{},j?"tool_calls":"stop"))}
53
+
54
+ `);let Me=tr(Ie(R));st(o,Ie(R)),Me&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:Aa(Ie(R))})}
50
55
 
51
56
  `),n.write(`data: [DONE]
52
57
 
53
- `),n.end();return}finally{U?.flush(),U?.dispose()}}let p="",y="",g=[],w=new Ee;for await(let x of r.track(f,c,o)){g.push(x),x.type==="response.output_text.delta"&&typeof x.delta=="string"&&(p+=x.delta),x.type==="response.reasoning_text.delta"&&typeof x.delta=="string"&&(y+=x.delta);let A=Xe(x);if(A&&w.add(A),x.type==="error"){Cr(n,x);return}}let v=fe(g);Ge(o,v);let m=Or(v),R=m.length>0?m:Or({output:w.items()}),b=Fe(h,R.length,p);if(b){z(n,502,De(c,b),"upstream_error");return}let _=R.map(({index:x,...A})=>A),S={role:"assistant",content:p||null},T=y||Bi(v);T&&(S.reasoning_content=T),_.length>0&&(S.tool_calls=_),te(n,200,{id:u,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:S,finish_reason:_.length>0?"tool_calls":"stop"}],usage:Di(v)})}var Lr="sense-latest";async function pd(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){z(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:Lr,i=oe({model:s});if(o.model=i,o.stream=!1,t.state===void 0||t.state===null){z(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){z(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){z(n,400,"systemone media, when present, must be an array");return}let l={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=l;let u=performance.now();r.model(i),await Tn(o,e,s),l.resolve_ms=Math.round(performance.now()-u);let d,c=performance.now();try{d=await e.createResponse({model:s,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},le(o))}catch(w){if(w instanceof $){at(n,"openai",w);return}if(w instanceof Be){n.setHeader("retry-after","2"),z(n,503,w.message,"capacity_error");return}throw w}l.dial_ms=Math.round(performance.now()-c);let h=[],f=null;try{for await(let w of r.track(d,i,o))if(f===null&&(f=performance.now(),l.first_event_ms=Math.round(f-c)),h.push(w),w.type==="error"){Cr(n,w);return}}catch(w){if(w instanceof $){f!==null&&(l.stream_ms=Math.round(performance.now()-f)),at(n,"openai",w);return}if(w instanceof Be){f!==null&&(l.stream_ms=Math.round(performance.now()-f)),n.setHeader("retry-after","2"),z(n,503,w.message,"capacity_error");return}throw f!==null&&(l.stream_ms=Math.round(performance.now()-f)),w}f!==null&&(l.stream_ms=Math.round(performance.now()-f));let p=fe(h);if(p==null){z(n,502,"upstream produced no response.completed event","upstream_error");return}Ge(o,p);let y=Qe(h,p),g;try{g=JSON.parse(y)}catch{z(n,502,"systemone answer was not valid JSON","upstream_error");return}if(g===null||typeof g!="object"||Array.isArray(g)){z(n,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof g=="object"&&g!==null&&!Array.isArray(g)&&"timing"in g){let w=g.timing;if(typeof w=="object"&&w!==null&&!Array.isArray(w)&&"question_fwd_ms"in w&&"head_ms"in w){let v=m=>typeof m=="number"&&Number.isFinite(m)&&m>=0?Math.round(m):null;l.question_fwd_ms=v(w.question_fwd_ms),l.head_ms=v(w.head_ms)}}te(n,200,g)}function fd(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Dt=class extends Error{};function In(t){return new Dt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function md(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function hd(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new Dt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function gd(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw In(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw In(`tool_result > ${r}`);e+=String(n.text??"")}return e}function yd(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 In(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:gd(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw In(a)}}return s(),r}function Tr(t){return Ye(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 _d(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){me(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){me(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){me(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(S=>typeof S!="string"))){me(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(t.model??"urun"),a=bs(o.id),l=[],u;try{t.system&&l.push({role:"system",content:fd(t.system)});for(let S of s)l.push(...yd(S));u=hd(t.tool_choice)}catch(S){if(S instanceof Dt){me(n,400,"invalid_request_error",S.message);return}throw S}let d=oe(t);r.model(d),o.model=d,o.stream=t.stream===!0,await Tn(o,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:l,stream:!0,tools:md(t.tools),tool_choice:u,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},le(o))}catch(S){if(S instanceof $){at(n,"anthropic",S);return}throw S}let f=(S,T)=>{n.destroyed||n.write(`event: ${S}
54
- data: ${JSON.stringify({type:S,...T})}
58
+ `),n.end();return}finally{C?.flush(),C?.dispose()}}let _="",A="",v=[],f=new De;for await(let R of r.track(h,p,o)){v.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(_+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(A+=R.delta);let I=mt(R);if(I&&f.add(I),R.type==="error"){yo(n,R,{inferenceId:o.id,operatorError:i});return}}let m=Ie(v);st(o,m);let w=mo(m),g=w.length>0?w:mo({output:f.items()}),S=tt(y,g.length,_);if(S){J(n,502,et(p,S),"upstream_error");return}let b=g.map(({index:R,...I})=>I),k={role:"assistant",content:_||null},x=A||Oa(m);x&&(k.reasoning_content=x),b.length>0&&(k.tool_calls=b),ie(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:k,finish_reason:b.length>0?"tool_calls":"stop"}],usage:Aa(m)})}var wo="sense-latest";async function Nc(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){J(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:wo,a=de({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){J(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){J(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){J(n,400,"systemone media, when present, must be an array");return}let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=u;let d=performance.now();r.model(a),await sr(o,e,i),u.resolve_ms=Math.round(performance.now()-d);let c,p=performance.now();try{c=await e.createResponse({model:i,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},ye(o))}catch(f){if(f instanceof F){Et(n,"openai",f);return}if(f instanceof Se){n.setHeader("retry-after","2"),J(n,503,f.message,"capacity_error");return}if(f instanceof oe){n.setHeader("retry-after","2"),J(n,503,f.message,"capacity_error");return}throw f}u.dial_ms=Math.round(performance.now()-p);let y=[],h=null;try{for await(let f of r.track(c,a,o))if(h===null&&(h=performance.now(),u.first_event_ms=Math.round(h-p)),y.push(f),f.type==="error"){yo(n,f,{inferenceId:o.id,operatorError:s});return}}catch(f){if(f instanceof F){h!==null&&(u.stream_ms=Math.round(performance.now()-h)),Et(n,"openai",f);return}if(f instanceof Se){h!==null&&(u.stream_ms=Math.round(performance.now()-h)),n.setHeader("retry-after","2"),J(n,503,f.message,"capacity_error");return}if(f instanceof oe){h!==null&&(u.stream_ms=Math.round(performance.now()-h)),n.setHeader("retry-after","2"),J(n,503,f.message,"capacity_error");return}throw h!==null&&(u.stream_ms=Math.round(performance.now()-h)),f}h!==null&&(u.stream_ms=Math.round(performance.now()-h));let _=Ie(y);if(_==null){J(n,502,"upstream produced no response.completed event","upstream_error");return}st(o,_);let A=gt(y,_),v;try{v=JSON.parse(A)}catch{J(n,502,"systemone answer was not valid JSON","upstream_error");return}if(v===null||typeof v!="object"||Array.isArray(v)){J(n,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof v=="object"&&v!==null&&!Array.isArray(v)&&"timing"in v){let f=v.timing;if(typeof f=="object"&&f!==null&&!Array.isArray(f)&&"question_fwd_ms"in f&&"head_ms"in f){let m=w=>typeof w=="number"&&Number.isFinite(w)&&w>=0?Math.round(w):null;u.question_fwd_ms=m(f.question_fwd_ms),u.head_ms=m(f.head_ms)}}ie(n,200,v)}function $c(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var fn=class extends Error{};function rr(t){return new fn(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Uc(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 Dc(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 fn(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Fc(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw rr(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw rr(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Bc(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 rr(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:Fc(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw rr(a)}}return s(),r}function go(t){return ft(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 Hc(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Ae(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){Ae(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Ae(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(k=>typeof k!="string"))){Ae(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:$c(t.system)});for(let k of i)u.push(...Bc(k));d=Dc(t.tool_choice)}catch(k){if(k instanceof fn){Ae(n,400,"invalid_request_error",k.message);return}throw k}let c=de(t);r.model(c),o.model=c,o.stream=t.stream===!0,await sr(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,y;try{y=await e.createResponse({model:t.model,input:u,stream:!0,tools:Uc(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},ye(o))}catch(k){if(k instanceof F){Et(n,"anthropic",k);return}if(k instanceof Se||k instanceof oe){n.setHeader("retry-after","2"),Ae(n,503,"capacity_error",k.message);return}throw k}let h=(k,x)=>{n.destroyed||n.write(`event: ${k}
59
+ data: ${JSON.stringify({type:k,...x})}
55
60
 
56
- `)};if(t.stream===!0){let S=r.track(h,d,o);Pr(n),f("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let T=0,x="",A=0,P="none",U=()=>P,W=-1,re=-1,pe=new Ee,be=[],V=()=>{P!=="none"&&(P="none",f("content_block_stop",{index:W}))},J=(F,ee)=>{V(),P=F,W=A++,f("content_block_start",{index:W,content_block:ee})};for await(let F of S){if(n.destroyed)break;be.push(F);let ee=Xe(F);if(F.type==="response.reasoning_text.delta"&&typeof F.delta=="string")U()!=="thinking"&&J("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:W,delta:{type:"thinking_delta",thinking:F.delta}});else if(F.type==="response.output_text.delta"&&typeof F.delta=="string")U()!=="text"&&J("text",{type:"text",text:""}),T+=1,x+=F.delta,f("content_block_delta",{index:W,delta:{type:"text_delta",text:F.delta}});else if(ee){let{call:Se}=pe.add(ee);(U()!=="tool"||ee.tool_index!==re)&&(re=ee.tool_index,J("tool",{type:"tool_use",id:Se.id??`call_${ee.tool_index}`,name:Se.name??"",input:{}})),ee.delta&&f("content_block_delta",{index:W,delta:{type:"input_json_delta",partial_json:ee.delta}})}else if(F.type==="error"){o.streamError=!0,f("error",{error:{type:"api_error",message:JSON.stringify(F)}}),n.end();return}}if(n.destroyed)return;let Z=fe(be),Pe=Ye(Z),C=Fe(c,pe.size+Pe.length,x);if(C){o.streamError=!0,f("error",{error:{type:"api_error",message:De(d,C)}}),n.end();return}V();let N=[];if(pe.size===0)try{N=Tr(Z)}catch(F){o.streamError=!0,f("error",{error:{type:"api_error",message:String(F instanceof Error?F.message:F)}}),n.end();return}A===0&&N.length===0&&(J("text",{type:"text",text:""}),V()),N.forEach(F=>{let ee=A++;f("content_block_start",{index:ee,content_block:{...F,input:{}}}),f("content_block_delta",{index:ee,delta:{type:"input_json_delta",partial_json:JSON.stringify(F.input??{})}}),f("content_block_stop",{index:ee})});let X=pe.size>0||N.length>0,ge=En(Z);Ge(o,Z),f("message_delta",{delta:{stop_reason:X?"tool_use":"end_turn"},usage:ge?{input_tokens:ge.input_tokens,output_tokens:ge.output_tokens}:{output_tokens:T}}),f("message_stop",{}),n.end();return}let p="",y="",g=[],w=new Ee;for await(let S of r.track(h,d,o)){g.push(S),S.type==="response.output_text.delta"&&typeof S.delta=="string"&&(p+=S.delta),S.type==="response.reasoning_text.delta"&&typeof S.delta=="string"&&(y+=S.delta);let T=Xe(S);if(T&&w.add(T),S.type==="error"){let x=S.error,A=x?.type==="invalid_request_error";me(n,A?400:502,A?"invalid_request_error":"api_error",x?.message??JSON.stringify(S));return}if(n.destroyed)break}if(n.destroyed)return;let v=fe(g);Ge(o,v);let m;try{m=Tr(v),m.length===0&&w.size>0&&(m=Tr({output:w.items()}))}catch(S){me(n,502,"api_error",String(S instanceof Error?S.message:S));return}let R=Fe(c,m.length,p);if(R){me(n,502,"api_error",De(d,R));return}let b=[],_=y||Bi(v);_&&b.push({type:"thinking",thinking:_}),(p||m.length===0)&&b.push({type:"text",text:p}),b.push(...m),te(n,200,{id:a,type:"message",role:"assistant",content:b,model:i,stop_reason:m.length>0?"tool_use":"end_turn",usage:En(v)??{input_tokens:0,output_tokens:0}})}function wd(t){Ie(process.stdout,t)}function Hi(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??wd,a=t.observe,l=new $e;return(u,d)=>{let c=new URL(u.url??"/","http://localhost"),h=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),f=(v,m,R,b,_)=>h?me(d,v,b,m):z(d,v,m,R,_),p=or(c.pathname),y=c.pathname.startsWith("/partners/"),g=p||y?{id:St(),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;g&&(d.setHeader(_s,g.id),d.once("close",()=>{let v=Ss({turn:g,method:u.method??"",path:c.pathname,res:d});i(ks(v)),a?.(v),Mi({record:v,ledger:t.ledger??null,req:u})}));let w=()=>ws(c.pathname,g);(async()=>{if(u.method==="GET"&&c.pathname==="/healthz"){te(d,200,{ok:!0});return}if(u.method==="GET"&&c.pathname==="/stats"){te(d,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(u.headers.authorization??"")!==`Bearer ${n}`){f(401,"invalid local proxy api key","authentication_error","authentication_error");return}let v=c.pathname===Sn?"canonical":c.pathname===Ct?"huggingface":null;if(v){if(u.method!=="POST"){f(405,`${c.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let _=t.usage;if(!_){f(501,`${c.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let S=_.authorize(u),T;try{T=await Ui(u,_i)}catch(P){if(P instanceof Ut){f(413,P.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let x=P=>_.lookup(S,P),A;try{if(v==="canonical"){let P=wi(T),U=await x(P);kn(U,P),A={requests:U}}else A=await Ri(T,x)}catch(P){if(P instanceof Oe){f(P.status,P.message,"invalid_request_error","invalid_request_error");return}throw P}te(d,200,A);return}if(u.method==="GET"&&c.pathname===Me){let _=await s(u);if(g&&(g.org=_.tenant??null),!_.openRouterModels){f(501,`GET ${Me} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}te(d,200,await _.openRouterModels());return}if(c.pathname.startsWith("/partners/")){f(404,`no partner adapter for ${u.method} ${c.pathname} \u2014 the partner surface currently carries ${Ct} and GET ${Me}`,"invalid_request_error","not_found_error");return}let m=await s(u);if(g&&(g.org=m.tenant??null),u.method==="GET"&&c.pathname==="/v1/models"){if(c.searchParams.get("format")==="openrouter"){d.writeHead(308,{location:Me}),d.end();return}te(d,200,await m.listModels());return}if(u.method==="GET"&&c.pathname===Fs){if(!m.listImageModels){f(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}te(d,200,await m.listImageModels());return}if(Ds(c.pathname)){if(!m.supportsImages){f(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${c.pathname}`,"not_implemented","not_implemented_error");return}let _={clients:m,imageModels:m.supportsImages,stats:l,turn:w()};c.pathname===gn?await zs(u,d,_):await Ks(u,d,_);return}if(u.method==="GET"&&c.pathname===di){if(!m.listSpeechToTextModels){f(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}te(d,200,await m.listSpeechToTextModels());return}if(li(c.pathname)){if(!m.supportsTranscription){f(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${vn}`,"not_implemented","not_implemented_error");return}let _={clients:m,transcriptionModels:m.supportsTranscription,stats:l,turn:w()};await fi(u,d,_);return}if(oi(c.pathname)){if(!m.supportsSpeech){f(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Pt}`,"not_implemented","not_implemented_error");return}let _={clients:m,speechModels:m.supportsSpeech,stats:l,turn:w()};await ui(u,d,_);return}if(u.method!=="POST"){f(404,`no route for ${u.method} ${c.pathname}`,"invalid_request_error","not_found_error");return}let R;try{R=await Ui(u)}catch(_){if(_ instanceof Ut){f(413,_.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let b=Buffer.byteLength(JSON.stringify(R));if(c.pathname==="/v1/responses"){l.request("responses",b,b),await dd(R,m,Rt(m),d,l,w());return}if(c.pathname==="/v1/chat/completions"){l.request("chat_completions",b,b),await cd(R,m,d,l,w(),u.headers[Ir]);return}if(c.pathname==="/v1/systemone"){l.request("systemone",b,b),await pd(R,m,d,l,w());return}if(c.pathname==="/v1/messages"){l.request("messages",b,b),await _d(R,m,d,l,w());return}if(c.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",b,b),me(d,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}f(404,`no route for POST ${c.pathname}`,"invalid_request_error","not_found_error")})().catch(v=>{let m=String(v instanceof Error?v.message:v);if(!d.headersSent){let b=o?.(v)??null;if(b){f(b.status,m,b.openaiType,b.anthropicType);return}if(v instanceof On.SessionAllocationError){let _=on(v.code);if(_){let S=v.retryAfterSeconds??(_.status===429?30:void 0);S!==void 0&&d.setHeader("Retry-After",String(S)),f(_.status,pr(_,v.code??void 0),_.openaiType,_.anthropicType,_.code);return}}if(v instanceof On.SessionFailedError){let _=sn(v);if(_){let S=_.status===429?30:void 0;S!==void 0&&d.setHeader("Retry-After",String(S)),f(_.status,pr(_,v.status.sessionId?`session ${v.status.sessionId}`:void 0),_.openaiType,_.anthropicType,_.code);return}}if(v instanceof q){f(502,m,"upstream_error","api_error");return}if(v instanceof ve){v.retryable&&d.setHeader("Retry-After","1"),f(502,m,"upstream_error","api_error",v.code);return}if(v instanceof tt){d.setHeader("Retry-After",String(v.retryAfterSeconds)),f(v.status,m,v.status===429?"capacity_error":"upstream_error",v.status===429?"rate_limit_error":"overloaded_error",v.code);return}f(500,m,"proxy_error","api_error","proxy_error");return}g&&(g.streamError=!0);let R=v instanceof ve?v.code:null;d.destroyed||(h?d.write(`event: error
57
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:m}})}
61
+ `)};if(t.stream===!0){let k=r.track(y,c,o);ho(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 x=0,R="",I=0,E="none",C=()=>E,$=-1,B=-1,K=new De,j=[],Me=()=>{E!=="none"&&(E="none",h("content_block_stop",{index:$}))},X=(G,Q)=>{Me(),E=G,$=I++,h("content_block_start",{index:$,content_block:Q})};for await(let G of k){if(n.destroyed)break;j.push(G);let Q=mt(G);if(G.type==="response.reasoning_text.delta"&&typeof G.delta=="string")C()!=="thinking"&&X("thinking",{type:"thinking",thinking:""}),h("content_block_delta",{index:$,delta:{type:"thinking_delta",thinking:G.delta}});else if(G.type==="response.output_text.delta"&&typeof G.delta=="string")C()!=="text"&&X("text",{type:"text",text:""}),x+=1,R+=G.delta,h("content_block_delta",{index:$,delta:{type:"text_delta",text:G.delta}});else if(Q){let{call:be}=K.add(Q);(C()!=="tool"||Q.tool_index!==B)&&(B=Q.tool_index,X("tool",{type:"tool_use",id:be.id??`call_${Q.tool_index}`,name:be.name??"",input:{}})),Q.delta&&h("content_block_delta",{index:$,delta:{type:"input_json_delta",partial_json:Q.delta}})}else if(G.type==="error"){o.streamError=!0;let be=G.error,We=Oe(be);We===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(G)}`),h("error",{error:{type:"api_error",message:We??Ee(o.id)}}),n.end();return}}if(n.destroyed)return;let ae=Ie(j),M=ft(ae),H=tt(p,K.size+M.length,R);if(H){o.streamError=!0,h("error",{error:{type:"api_error",message:et(c,H)}}),n.end();return}Me();let q=[];if(K.size===0)try{q=go(ae)}catch(G){o.streamError=!0;let Q=ge(G,{inferenceId:o.id});Q.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(G instanceof Error?G.message:G)}`),h("error",{error:{type:"api_error",message:Q.message}}),n.end();return}I===0&&q.length===0&&(X("text",{type:"text",text:""}),Me()),q.forEach(G=>{let Q=I++;h("content_block_start",{index:Q,content_block:{...G,input:{}}}),h("content_block_delta",{index:Q,delta:{type:"input_json_delta",partial_json:JSON.stringify(G.input??{})}}),h("content_block_stop",{index:Q})});let Ve=K.size>0||q.length>0,lt=tr(ae);st(o,ae),h("message_delta",{delta:{stop_reason:Ve?"tool_use":"end_turn"},usage:lt?{input_tokens:lt.input_tokens,output_tokens:lt.output_tokens}:{output_tokens:x}}),h("message_stop",{}),n.end();return}let _="",A="",v=[],f=new De;for await(let k of r.track(y,c,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"&&(A+=k.delta);let x=mt(k);if(x&&f.add(x),k.type==="error"){let R=k.error,I=R?.type==="invalid_request_error",E=Oe(R);E===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(k)}`),Ae(n,I?400:502,I?"invalid_request_error":"api_error",E??Ee(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let m=Ie(v);st(o,m);let w;try{w=go(m),w.length===0&&f.size>0&&(w=go({output:f.items()}))}catch(k){let x=ge(k,{inferenceId:o.id});x.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(k instanceof Error?k.message:k)}`),Ae(n,502,"api_error",x.message);return}let g=tt(p,w.length,_);if(g){Ae(n,502,"api_error",et(c,g));return}let S=[],b=A||Oa(m);b&&S.push({type:"thinking",thinking:b}),(_||w.length===0)&&S.push({type:"text",text:_}),S.push(...w),ie(n,200,{id:l,type:"message",role:"assistant",content:S,model:a,stop_reason:w.length>0?"tool_use":"end_turn",usage:tr(m)??{input_tokens:0,output_tokens:0}})}function jc(t){He(process.stdout,t)}function Ta(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??jc,a=t.operatorLog??(d=>console.error(d)),l=t.observe,u=new Qe;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),y=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),h=(m,w,g,S,b)=>y?Ae(c,m,S,w):J(c,m,w,g,b),_=jr(p.pathname),A=p.pathname.startsWith("/partners/"),v=_||A?{id:zt(),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(ai,v.id),c.once("close",()=>{let m=ci({turn:v,method:d.method??"",path:p.pathname,res:c});i(pi(m)),l?.(m),ka({record:m,ledger:t.ledger??null,req:d})}));let f=()=>li(p.pathname,v);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){ie(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){ie(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 m=p.pathname===Zn?"canonical":p.pathname===an?"huggingface":null;if(m){if(d.method!=="POST"){h(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let b=t.usage;if(!b){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 k=b.authorize(d),x;try{x=await Ea(d,ua)}catch(E){if(E instanceof pn){h(413,E.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let R=E=>b.lookup(k,E),I;try{if(m==="canonical"){let E=da(x),C=await R(E);er(C,E),I={requests:C}}else I=await fa(x,R)}catch(E){if(E instanceof je){h(E.status,E.message,"invalid_request_error","invalid_request_error");return}throw E}ie(c,200,I);return}if(d.method==="GET"&&p.pathname===ze){let b=await s(d);if(v&&(v.org=b.tenant??null),!b.openRouterModels){h(501,`GET ${ze} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ie(c,200,await b.openRouterModels());return}if(p.pathname.startsWith("/partners/")){h(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${an} and GET ${ze}`,"invalid_request_error","not_found_error");return}let w=await s(d);if(v&&(v.org=w.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:ze}),c.end();return}ie(c,200,await w.listModels());return}if(d.method==="GET"&&p.pathname===Ti){if(!w.listImageModels){h(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ie(c,200,await w.listImageModels());return}if(Oi(p.pathname)){if(!w.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 b={clients:w,imageModels:w.supportsImages,stats:u,turn:f(),operatorLog:a};p.pathname===Jn?await Bi(d,c,b):await Fi(d,c,b);return}if(d.method==="GET"&&p.pathname===ta){if(!w.listSpeechToTextModels){h(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ie(c,200,await w.listSpeechToTextModels());return}if(ea(p.pathname)){if(!w.supportsTranscription){h(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Xn}`,"not_implemented","not_implemented_error");return}let b={clients:w,transcriptionModels:w.supportsTranscription,stats:u,turn:f(),operatorLog:a};await oa(d,c,b);return}if(zi(p.pathname)){if(!w.supportsSpeech){h(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${sn}`,"not_implemented","not_implemented_error");return}let b={clients:w,speechModels:w.supportsSpeech,stats:u,turn:f(),operatorLog:a};await Zi(d,c,b);return}if(d.method!=="POST"){h(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let g;try{g=await Ea(d)}catch(b){if(b instanceof pn){h(413,b.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let S=Buffer.byteLength(JSON.stringify(g));if(p.pathname==="/v1/responses"){u.request("responses",S,S),await Lc(g,w,Xt(w),c,u,f(),a);return}if(p.pathname==="/v1/chat/completions"){u.request("chat_completions",S,S),await Mc(g,w,c,u,f(),d.headers[fo],a);return}if(p.pathname==="/v1/systemone"){u.request("systemone",S,S),await Nc(g,w,c,u,f(),a);return}if(p.pathname==="/v1/messages"){u.request("messages",S,S),await Hc(g,w,c,u,f(),a);return}if(p.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",S,S),Ae(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(m=>{let w=String(m instanceof Error?m.message:m);if(!c.headersSent){let b=o?.(m)??null;if(b){b.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${b.operatorDetail}`),h(b.status,w,b.openaiType,b.anthropicType);return}if(m instanceof or.SessionAllocationError){let x=$n(m.code);if(x){let R=m.retryAfterSeconds??(x.status===429?30:void 0);R!==void 0&&c.setHeader("Retry-After",String(R)),h(x.status,en(x,m.code??void 0),x.openaiType,x.anthropicType,x.code);return}}if(m instanceof or.SessionFailedError){let x=Un(m);if(x){let R=x.status===429?30:void 0;R!==void 0&&c.setHeader("Retry-After",String(R)),h(x.status,en(x,m.status.sessionId?`session ${m.status.sessionId}`:void 0),x.openaiType,x.anthropicType,x.code);return}}if(m instanceof Z){h(502,w,"upstream_error","api_error");return}if(m instanceof ke){m.retryable&&c.setHeader("Retry-After","1");let x=ge(m,{inferenceId:v?.id??null});x.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:Re(m)}`),h(502,x.message,"upstream_error","api_error",m.code);return}if(m instanceof Fe){c.setHeader("Retry-After",String(m.retryAfterSeconds)),h(m.status,w,m.status===429?"capacity_error":"upstream_error",m.status===429?"rate_limit_error":"overloaded_error",m.code);return}let k=ge(m,{inferenceId:v?.id??null});k.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:Re(m)}`),h(500,k.message,"proxy_error","api_error","proxy_error");return}v&&(v.streamError=!0);let g=m instanceof ke?m.code:null,S=ge(m,{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: ${m instanceof Error?`${m.name}: ${m.message}`:Re(m)}`),c.destroyed||(y?c.write(`event: error
62
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:S.message}})}
58
63
 
59
- `):d.write(`data: ${JSON.stringify({error:{message:m,type:"upstream_error",code:R}})}
64
+ `):c.write(`data: ${JSON.stringify({error:{message:S.message,type:"upstream_error",code:g}})}
60
65
 
61
- `)),d.end()})}}var he=(t,e)=>Object.assign(new Error(e),{status:t});function qi(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ji(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var vd='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Gi(t,e,n,r){if(!t.supportsAudio)throw he(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(u){throw u instanceof $?he(404,u.message):u}if(!o)throw he(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw he(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(u){throw u instanceof $?he(404,u.message):u}if(s&&!t.openTurnsOn)throw he(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 u;try{u=await t.transcriptStreamFor(e)}catch(d){throw d instanceof $?he(404,d.message):d}if(u!=="stt")throw he(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(u)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw he(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${vd}`);if(r==="transcription"&&!s)throw he(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=await t.sessionHandle(e),a={audio:await t.openAudioOn(i,n)},l={clients:{createResponse:async u=>await t.createResponseOn(i,u)},voice:o,audioSession:a};return s&&(l.turns=u=>t.openTurnsOn(i,u)),r==="transcription"&&(l.intent="transcription"),e!==void 0&&(l.model=e),l}var ne=require("@prometheus-io/client"),Vi=require("http");var Ji=9464,Pn="/metrics",ut="(other)",Mr="(none)",Nr=64,$r=128,bd=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",Sn,Ct,Me],Sd=new Set(bd);function Ur(t){return Sd.has(t)?t:ut}function Dr(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var lt=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?Mr:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,ut):(this.admitted.add(e),e):ut}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},dt=class{registry=new ne.Registry;modelLabel=new lt(Nr);orgLabel=new lt($r);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new ne.Counter({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new ne.Histogram({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new ne.Histogram({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new ne.Counter({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new ne.Counter({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new ne.Counter({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of Oi)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"},Ti()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Pi()/1e3)}}),this.labelCardinality=new ne.Gauge({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new ne.Counter({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),e.defaultMetrics!==!1&&(0,ne.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=Ur(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===""?ut:e.method,status_class:Dr(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 Cn(t){return(0,Vi.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Pn){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Pn}
66
+ `)),c.end()})}}var Ce=(t,e)=>Object.assign(new Error(e),{status:t}),Vc='"transcription" (a transcription session), or no intent at all (the realtime voice session)',vo=(t,e,n)=>new U(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),_o=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof F?Ce(404,n.message):n}};async function Pa(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Ce(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Vc}`);if(o==="transcription")throw Ce(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 Ce(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 Ce(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(y){throw y instanceof F?Ce(404,y.message):y}if(!p)throw Ce(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(y){throw y instanceof F?Ce(404,y.message):y}if(p!=="stt")throw Ce(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 _o(t,n.stt),i=await _o(t,e),a=await _o(t,n.tts),l=await t.openAudioOn(s,r),u=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let y=new AbortController;return d=y,Wc({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},p,y.signal,()=>{d===y&&(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(y){throw y instanceof U?vo("stt",n.stt,y):y}},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 ir=class extends Error{};async function*Wc(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"),y=!1,h=null,_=null,A=[],v=null,f=new Promise((I,E)=>{n&&n.addEventListener("abort",()=>E(new ir),{once:!0})}),m=()=>y||n?.aborted===!0,w=async I=>{if(m())return;let E;try{E=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 U?vo("tts",l.tts,$):$}let C=E[Symbol.asyncIterator]();_=C;try{for(;;){let $=C.next(),B;try{B=await Promise.race([$,f])}catch(j){if($.catch(()=>{}),j instanceof ir)return;throw j}if(B.done)return;let K=B.value;if(K.type==="error"){let j=K.error&&typeof K.error.message=="string"?K.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(l.tts)}) errored: ${j}`)}if(K.type==="response.completed")return}}finally{_===C&&(_=null)}},g=async()=>{for(;A.length>0&&!m();){let I=A.shift();await w(I)}},S=I=>{if(I===""||m()||(A.push(I),v!==null))return;let E=g();v=E,E.then(()=>{v===E&&(v=null)},C=>{v===E&&(v=null),h??=C})},b=()=>{y=!0,A.length=0;let I=_;if(_=null,I){let E=I.return?.();E&&E.catch(()=>{})}},k=async()=>{for(;A.length>0||v!==null;){let I=v;if(I===null){await w(A.shift());continue}await I}},x=p?new xt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},I=>S(I)):null,R=null;try{let I;try{I=await o.createResponseOn(s,d)}catch(E){throw E instanceof U?vo("chat",a,E):E}for await(let E of I){if(m())return;let C=E;if(C.type==="error"){yield E;return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){yield E,x?.push(C.delta);continue}if(C.type==="response.function_call_arguments.delta"){x?.flush(),yield E;continue}if(C.type==="response.completed"){R=E.response;continue}}x?.flush(),x?.dispose(),p&&await k(),R!==null&&(yield{type:"response.completed",response:R})}finally{x?.dispose(),b();try{if(h instanceof U)throw h}finally{r?.()}}}var ve=(t,e)=>Object.assign(new Error(e),{status:t});function La(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Ma(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Jc='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Na(t,e,n,r){if(!t.supportsAudio)throw ve(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 F?ve(404,d.message):d}if(!o){let d=null;if(t.realtimeCompanionsFor)try{d=await t.realtimeCompanionsFor(e)}catch(c){throw c instanceof F?ve(404,c.message):c}if(d!==null)return await Pa(t,e,d,n,r);throw ve(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 ve(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 F?ve(404,d.message):d}if(s&&!t.openTurnsOn)throw ve(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 F?ve(404,c.message):c}if(d!=="stt")throw ve(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 ve(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Jc}`);if(r==="transcription"&&!s)throw ve(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=await t.sessionHandle(e)}catch(d){throw d instanceof oe?ve(503,d.message):d}let a=`conn_${(0,Ca.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 Ga=require("@urun-sh/core/internal"),Va=ue(require("ws"),1);function $a(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 ar(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 Ua(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 Kc="llm-resp";async function*ur(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 Ua(s);return}}}async function*So(t,e){let n=`${Kc}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*ur(e,t.stream(n).messages())}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var dr=class t{constructor(e,n=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((o,s)=>{let i=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(e){e.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=ar(e,n,this.consumerId);return this.write(r),So(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=$a(e,n,r,this.consumerId);return this.write(o),So(this.session,r)})}async writeGated(e,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var Da=0;function zc(){return Da+=1,`req_${Date.now().toString(36)}_${Da.toString(36)}`}var it=class{transport;constructor(e){this.transport=new dr(e)}responses={create:async e=>{let n=zc(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var At=ue(require("yjs"),1),Fa=require("@urun-sh/core/internal"),Yc=3e4;function Xc(t){return(e,n,r)=>{let o=t(e);At.applyUpdate(n,At.encodeStateAsUpdate(o));let s=a=>At.applyUpdate(o,a),i=a=>At.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)}}}}async function*Qc(t,e){let n=[],r=!1,o=null,s="",i=l=>{if(!("responses"in l)||typeof l.responses!="object"||l.responses===null)return null;let u=l.responses;if(!(e in u))return null;let d=u[e];if(d===null||typeof d!="object"||!("error"in d))return{body:d,error:null};let c=d.error;return c===null?{body:d,error:null}:{body:d,error:c}},a=l=>{let u={};for(let[c,p]of Object.entries(l)){let y=p;u[c]=typeof y?.toJSON=="function"?y.toJSON():p}if("tokens"in u&&typeof u.tokens=="object"&&u.tokens!==null){let c=u.tokens[e];typeof c=="string"&&c.length>s.length&&(n.push({t:"delta",delta:c.slice(s.length)}),s=c)}let d=i(u);if(d!==null){d.error!==null?n.push({t:"error",body:d.error}):n.push({t:"response",body:d.body}),r=!0,o?.(),o=null;return}if("progress"in u&&typeof u.progress=="object"&&u.progress!==null){let c=u.progress[e];if(typeof c=="object"&&c!==null&&"state"in c&&c.state==="error"){let y="error"in c&&typeof c.error=="string"?c.error:"lane request failed";n.push({t:"error",body:{message:y}}),r=!0,o?.(),o=null;return}}o?.(),o=null};if(a(t.get()??{}),!r){let l=t.on("change",a);try{for(;!r;){if(n.length>0){yield n.shift();continue}await new Promise(u=>{o=u})}}finally{l()}}for(;n.length>0;)yield n.shift()}function ko(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Xc(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=l=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let u=r.get(l);return u||(u=new Fa.SessionDocumentImpl(l,e,n),r.set(l,u)),u},i=l=>{let u="llm-resp:";if(!l.startsWith(u))throw new Error(`lane session exposes no stream "${l}" \u2014 only the llm reply lanes (${u}<rid>)`);let d=l.slice(u.length);return{messages:()=>Qc(s("llm"),d),attach:async()=>{throw new Error("lane session carries no media track \u2014 the doc mirror IS the reply lane")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(l){return s(l)},stream:i,async end(){},async whenLive(l){let u=s("llm");if(u.synced===!0)return;let d=l?.timeout??t.whenLiveTimeoutMs??Yc;await new Promise((c,p)=>{let y=setTimeout(()=>{h(),p(new Error(`lane ${e} llm doc never synced within ${d}ms`))},d),h=u.onSynced(()=>{clearTimeout(y),l?.signal?.removeEventListener("abort",_),c()}),_=()=>{clearTimeout(y),h(),p(l?.signal?.reason instanceof Error?l.signal.reason:new Error("aborted"))};l?.signal?.addEventListener("abort",_,{once:!0})})},destroy(){o=!0;for(let l of r.values())l.dispose();r.clear()}}}var qe=require("crypto"),Zc=["sfu","urun-doc"],Ha="runtime:lease",ep="lane:join",tp="urun-runtime-key-v1";function Ro(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,qe.createHmac)("sha256",t).update(`${tp}|${e}`).digest("base64url")}var np=120;function Ba(t){return Buffer.from(t).toString("base64url")}function rp(t,e,n){let r=Ba(JSON.stringify(t)),o=Ba(JSON.stringify(e)),s=(0,qe.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function ja(t,e,n=np,r=ep,o){let s=Math.floor(Date.now()/1e3),i=o?Ro(e,o):e;return rp({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,qe.randomUUID)()},i)}function qa(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,y=[];if(p!==void 0?(y.push(Ro(n,p)),o&&y.push(Ro(o,p))):(y.push(n),o&&y.push(o)),!y.some(f=>{let m=(0,qe.createHmac)("sha256",f).update(`${i}.${a}`).digest();return c.length===m.length&&(0,qe.timingSafeEqual)(c,m)}))return null;let h=d.exp;if(typeof h!="number"||h<=r)return null;let _=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(_!==void 0&&Zc.some(f=>f===_||Array.isArray(_)&&_.includes(f))))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:h}}var op=3,sp="llm",ip=new Set(["paused","error"]);function cr(t,e,n){let r=t.doc(sp),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<op||d(new U(`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&&ip.has(c.name)&&d(new U(`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*xo(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 ap(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new _e(`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 Wa(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=(p,y,h,_,A)=>{let v=h?ko({laneId:p,roomDoc:w=>t.roomDoc(p,w)}):ko({laneId:p,connector:(0,Ga.createWebsocketDocConnector)({serverUrl:`ws://${_}/doc`,sessionId:p,token:()=>ja(p,t.tokenSecret,void 0,void 0,A),WebSocketPolyfill:Va.default})}),f=h?a(p):cr(v,`lane:${p}`,{armOnFirstSync:!0}),m={session:v,responses:new it(v),gone:f,goneWatch:f,laneId:p,pool:y,inFlight:0,laneSession:v,self:h,host:_??""};return n.set(p,m),f.onGone(()=>l(m)),m},a=p=>{let y=null,h=!1,_=new Set,A=f=>{if(!y){y=f;for(let m of[..._])m(f);_.clear()}},v=t.hostedSignal?.(p,f=>{if(f){h=!0;return}h&&A(new U(`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:()=>y,onGone(f){return y?(f(y),()=>{}):(_.add(f),()=>_.delete(f))},dispose(){v?.(),_.clear()}}},l=p=>{u(p)&&(n.delete(p.laneId),r.delete(p.laneId),p.goneWatch?.dispose())},u=p=>{let y=p.laneId;return typeof y=="string"&&n.get(y)===p},d=(p,y)=>{throw t.metrics?.observeLane503Fast(y??""),s.set(p,e()),new oe(p)},c=async(p,y)=>{let h=ap(y);o.add(h);let _=e();try{let A=await t.laneWarmWaitMsFor?.(p,y)??t.laneColdWakeDefaultMs??0,v=await t.plane.pick({pool:h,model:p,holdMs:A});t.metrics?.observeLaneReady(p??"",v.length);let m=v.map(g=>({laneId:g.laneId,self:g.host===t.selfAddress,host:g.host})).sort((g,S)=>g.self!==S.self?g.self?-1:1:(r.get(g.laneId)??0)-(r.get(S.laneId)??0))[0];m||d(h,p);let w=n.get(m.laneId);return w?.goneWatch?.gone()&&(l(w),w=void 0),w&&(w.pool!==h||w.self!==m.self||w.host!==m.host)&&(l(w),w=void 0),w||(w=i(m.laneId,h,m.self,m.host,y.sharedOrgId??void 0)),w.inFlight+=1,r.set(m.laneId,(r.get(m.laneId)??0)+1),{app:h,entry:w,identity:{kind:"catalog",model_id:y.modelId??p??"",variant:y.variant??""}}}finally{t.metrics?.observeLanePick(p??"",e()-_)}};return{sessionFor(p,y){return c(p,y)},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(_=>_.pool)])].sort(),y=await t.plane.status().catch(()=>[]),h=new Map(lp(y));return Promise.all(p.map(async _=>{let A=h.get(_)??{pool:_,lanes:[],lastDemandAt:null};return{pool:_,lanes:A.lanes,lastDemandAt:A.lastDemandAt,local:[...n.values()].filter(v=>v.pool===_).map(v=>({laneId:v.laneId,inFlight:v.inFlight,self:v.self,host:v.host})),lastRefusalAt:s.get(_)??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 lp(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}var za=require("http");var up="/pooler/v1/lanes/pick",dp="/pooler/v1/lanes/status",cp=1e4;function Ja(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,za.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"),y=null;try{y=p===""?null:JSON.parse(p)}catch{y=null}s({status:d.statusCode??0,json:y})}),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 Ka(t,e,n){if(t===503)return new oe(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 Ya(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=await Ja(t,"POST",up,{pool:e,model:n,hold_ms:r},r+cp);if(o.status!==200)throw Ka(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 Ja(t,"GET",dp,void 0,5e3);if(e.status!==200)throw Ka(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}var rl=require("ws");var Qa=ue(require("yjs"),1),Tt=ue(require("y-protocols/sync"),1),Le=ue(require("y-protocols/awareness"),1),Y=ue(require("lib0/encoding"),1),Pt=ue(require("lib0/decoding"),1),Za=ue(require("lib0/map"),1),el=ue(require("lodash.debounce"),1);var Xa=()=>{};var fp=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,mp=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,gp=0,hp=1;var yp=process.env.GC!=="false"&&process.env.GC!=="0",wp=process.env.YPERSISTENCE,pr=null;if(typeof wp=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var Ot=new Map,fr=0,Ao=1,_p=(t,e,n)=>{let r=Y.createEncoder();Y.writeVarUint(r,fr),Tt.writeUpdate(r,t);let o=Y.toUint8Array(r);n.conns.forEach((s,i)=>mn(n,i,o))},Eo=class extends Qa.Doc{constructor(e){super({gc:yp}),this.name=e,this.conns=new Map,this.awareness=new Le.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=Y.createEncoder();Y.writeVarUint(l,Ao),Y.writeVarUint8Array(l,Le.encodeAwarenessUpdate(this.awareness,a));let u=Y.toUint8Array(l);this.conns.forEach((d,c)=>{mn(this,c,u)})};this.awareness.on("update",n),this.on("update",_p),!1}},Io=(t,e=!0)=>Za.setIfUndefined(Ot,t,()=>{let n=new Eo(t);return n.gc=e,pr!==null&&pr.bindState(t,n),Ot.set(t,n),n}),vp=(t,e,n)=>{try{let r=Y.createEncoder(),o=Pt.createDecoder(n);switch(Pt.readVarUint(o)){case fr:Y.writeVarUint(r,fr),Tt.readSyncMessage(o,r,e,t),Y.length(r)>1&&mn(e,t,Y.toUint8Array(r));break;case Ao:{Le.applyAwarenessUpdate(e.awareness,Pt.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},It=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),Le.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&pr!==null&&(pr.writeState(t.name,t).then(()=>{t.destroy()}),Ot.delete(t.name))}e.close()},mn=(t,e,n)=>{e.readyState!==gp&&e.readyState!==hp&&It(t,e);try{e.send(n,r=>{r!=null&&It(t,e)})}catch{It(t,e)}},bp=3e4,tl=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=Io(n,r);o.conns.set(t,new Set),t.on("message",a=>vp(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&It(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{It(o,t),clearInterval(i)}}},bp);t.on("close",()=>{It(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=Y.createEncoder();Y.writeVarUint(a,fr),Tt.writeSyncStep1(a,o),mn(o,t,Y.toUint8Array(a));let l=o.awareness.getStates();if(l.size>0){let u=Y.createEncoder();Y.writeVarUint(u,Ao),Y.writeVarUint8Array(u,Le.encodeAwarenessUpdate(o.awareness,Array.from(l.keys()))),mn(o,t,Y.toUint8Array(u))}}};var Oo="/doc/",ol=30,Sp=1e4,nl="llm";function kp(t){if(!t.startsWith(Oo))return null;let e=t.slice(Oo.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 gn(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
67
+ `;t.end(`HTTP/1.1 ${e} ${r}\r
68
+ Connection: close\r
69
+ Content-Type: text/plain; charset=utf-8\r
70
+ Content-Length: ${Buffer.byteLength(o)}\r
71
+ \r
72
+ ${o}`)}function sl(t,e){let n=new rl.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=v=>o.get(`${v}/${nl}`)??0,a=v=>s.get(v)??0,l=new Map,u=new Map,d=new Set,c=new Set,p=!1,y=(v,f,m)=>{let w=i(v)>0,g=a(v),S=g>0,b=`${v}/${f}`,k=o.get(b)??0;m>0?o.set(b,m):o.delete(b);let x=g+m-k;x>0?s.set(v,x):s.delete(v);let R=i(v)>0,I=x>0;if(w!==R){R?h(v):_(v);for(let E of l.get(v)??[])E(R)}S&&!I&&queueMicrotask(()=>{let E=`${v}/`;for(let[C,$]of[...Ot.entries()])!C.startsWith(E)||$.conns.size>0||(Ot.delete(C),$.destroy())})},h=v=>{if(!e.hostRegistry||u.has(v))return;let f=()=>{e.hostRegistry?.setHost(v,e.selfAddress).catch(()=>{})};f();let m=setInterval(f,Sp);m.unref?.(),u.set(v,m)},_=v=>{let f=u.get(v);f&&(clearInterval(f),u.delete(v)),e.hostRegistry&&e.hostRegistry.delHost(v,e.selfAddress).catch(()=>{})},A=(v,f,m)=>{let w;try{w=new URL(v.url??"/","http://localhost")}catch{gn(f,400,"malformed upgrade URL");return}f.on("error",()=>f.destroy()),f.on("close",()=>c.delete(f));let g=kp(w.pathname);if(!g){if(w.pathname.startsWith(Oo)){gn(f,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(f);return}d.add(f);let S=!1;(async()=>{let b=w.searchParams.get("token")??"",k=null;try{k=b===""?null:await e.verifyToken(b,g.laneId,g.docName)}catch{k=null}if(k===null){gn(f,401,"invalid or missing lane doc token");return}let x=k;if(x.tenant!==void 0&&e.laneTenantOf){let R=null;try{R=await e.laneTenantOf(g.laneId)}catch{R=null}if(R==null||R==="")e.onLaneTenantMissing?.();else if(x.tenant!==R){gn(f,403,"lane doc token org does not match the lane record");return}}p||f.destroyed||(S=!0,n.handleUpgrade(v,f,m,R=>{d.delete(f),r.add(R),R.on("close",()=>r.delete(R));let I=x.scope===Ha||x.scope===void 0&&typeof x.app=="string"&&typeof x.fn=="string"&&x.aud==="sfu";if(I){let C=`${g.laneId}/${g.docName}`,$=(o.get(C)??0)+1;y(g.laneId,g.docName,$),$>1&&g.docName===nl&&e.hostRegistry?.setHost(g.laneId,e.selfAddress).catch(()=>{})}R.on("close",()=>{if(!I)return;let C=`${g.laneId}/${g.docName}`;y(g.laneId,g.docName,Math.max(0,(o.get(C)??1)-1))}),tl(R,v,{docName:`${g.laneId}/${g.docName}`,gc:!0})}))})().catch(()=>{!S&&!f.destroyed&&gn(f,500,"lane doc upgrade failed")}).finally(()=>d.delete(f))};return t.on("upgrade",A),{async close(){p=!0,t.off("upgrade",A);for(let f of[...u.keys()])_(f);await new Promise(f=>{if(r.size===0&&d.size===0){f();return}let m=r.size+d.size,w=()=>{m-=1,m<=0&&f()};for(let g of r)g.once("close",w);for(let g of d)g.once("close",w);for(let g of r)g.close(1001,"lane doc host shutting down");for(let g of d)g.destroy()}),o.clear(),s.clear(),l.clear()},roomDoc(v,f){return Io(`${v}/${f}`,!0)},isHosted(v){return i(v)>0},onHostedChange(v,f){let m=l.get(v);return m||(m=new Set,l.set(v,m)),m.add(f),f(i(v)>0),()=>{m.delete(f)}}}}var Rp="urun:catalog:v1";function il(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(Rp),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)
73
+ `)}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 ee=require("@prometheus-io/client"),al=require("http");var ll=9464,mr="/metrics",Ct="(other)",To="(none)",Po=64,Co=128,xp=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",Zn,an,ze],Ep=new Set(xp);function Lo(t){return Ep.has(t)?t:Ct}function Mo(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var Lt=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?To:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,Ct):(this.admitted.add(e),e):Ct}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},Mt=class{registry=new ee.Registry;modelLabel=new Lt(Po);orgLabel=new Lt(Co);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new ee.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 ee.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 ee.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 ee.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 ee.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 ee.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 ee.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 wa)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ee.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"},_a()),this.ledgerQueue.set({measure:"oldest_age_seconds"},va()/1e3)}}),this.labelCardinality=new ee.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 ee.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 ee.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 ee.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 ee.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 ee.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 ee.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,ee.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=Lo(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===""?Ct:e.method,status_class:Mo(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 gr(t){return(0,al.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==mr){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${mr}
62
74
  `);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)}
63
- `);return}n.end()})})}var Fr=require("crypto"),Wi=require("http"),Ki=9465,Br="x-urun-key-id",Hr="x-urun-key-fingerprint",qr="urun-ratelimit-bucket:",jr="urun-ratelimit-tier:",Ln="anonymous",kd=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Gr(t){return(0,Fr.createHash)("sha256").update(`${qr}${t}`).digest("hex")}function Vr(t){return(0,Fr.createHash)("sha256").update(`${jr}${t}`).digest("hex")}function Jr(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return kd.test(n)?n:null}function Mn(){return(0,Wi.createServer)((t,e)=>{let n=Jr(t.headers.authorization);e.setHeader(Br,n===null?Ln:Gr(n)),e.setHeader(Hr,n===null?Ln:Vr(n)),e.writeHead(200),e.end()})}var Nn=require("@urun-sh/core"),ae=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Te=class extends Error{constructor(e){super(e),this.name="ControlPlaneUnavailableError"}};function Ve(t){let e=(t??"").trim();if(e==="")throw new ae("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 ae("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var Rd=60,Wr=6e4,Kr=4096;function xd(t){return t===401||t===403}var ct=class{constructor(e){this.opts=e;this.mint=e.mint??Nn.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new ae("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<Wr)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:Rd})).orgId}catch(o){throw o instanceof Nn.ClientTokenError&&xd(o.status)?(this.cache.delete(e),new ae("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Te(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new Te("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>=Kr){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};var Hn=require("crypto");var ce=require("@urun-sh/core");function zi(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 Yi(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 Xi(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 Ed="llm-resp";async function*zr(t,e){let n=`${Ed}:${e}`,r=`resp_${e}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;try{for await(let s of t.stream(n).messages()){let i=s;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let l=typeof a.index=="number"?a.index:0,u=o.get(l)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),o.set(l,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${l}`,tool_index:l,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...i.body}};return}else if(i.t==="error"){yield Xi(i);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var Un=class t{constructor(e,n=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((o,s)=>{let i=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(e){e.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=Yi(e,n,this.consumerId);return this.write(r),zr(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=zi(e,n,r,this.consumerId);return this.write(o),zr(this.session,r)})}async writeGated(e,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var Qi=0;function Ad(){return Qi+=1,`req_${Date.now().toString(36)}_${Qi.toString(36)}`}var Dn=class{transport;constructor(e){this.transport=new Un(e)}responses={create:async e=>{let n=Ad(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};async function Zi(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}var ea=require("@urun-sh/core"),Yr=2;function Id(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Od(t){let e=t?.type;return e==="response.completed"||e==="error"}function ta(t){return async function(n,r){return(async function*(){for(let s=1;s<=Yr;s++){let{app:i,entry:a,identity:l}=await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:l});let u=!1,d=!1;try{let c=await t.createStream(a,n);for await(let h of c){if(Od(h)&&(u=!0),Id(h)){if(s>1)continue}else d=!0;yield h}}catch(c){if(c instanceof ea.SessionFailedError&&(c.kind==="never-live"||c.kind==="create-failed")){try{t.onAdmissionVerdict?.(i,a,c)}catch{}throw c}if(s<Yr&&!d){await t.evict(i,a);continue}throw c}if(u)return;if(s<Yr&&!d){await t.evict(i,a);continue}return}})()}}var sa=require("crypto");var Td=3,Pd="llm",Cd=new Set(["paused","error"]);function na(t,e){let n=t.doc(Pd),r=typeof n.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let s=null,i=!1,a=new Set,l=[],u=d=>{if(!s){s=d;for(let c of[...a])c(d);a.clear()}};return r&&l.push(n.onConnectionState(d=>{i&&(d.consecutiveFailures<Td||u(new H(`the pooled session for app "${e}" is gone: its doc backhaul failed ${d.consecutiveFailures} consecutive times (last close ${d.lastCloseCode===null?"by provider liveness reap":`code ${d.lastCloseCode}`}${d.lastCloseReason?`, reason ${JSON.stringify(d.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),o&&l.push(t.onPhase(d=>{if(d.name==="live"){i=!0;return}i&&Cd.has(d.name)&&u(new H(`the pooled session for app "${e}" lost its compute binding (phase "${d.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>s,onGone(d){return s?(d(s),()=>{}):(a.add(d),()=>a.delete(d))},dispose(){a.clear();for(let d of l.splice(0))d()}}}async function*Xr(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)}}var Md=1,Nd=4,$d=4;function ia(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):Md;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,Nd));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",$d),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function ra(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 aa(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=y=>({session:y,responses:new Dn(y),gone:na(y,n)});if(i.lane==="jwt"){let y=(0,ce.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(ra(y,e.appSlug,a,u))}let{apiKey:c,gatewayUrl:h}=i,f=(typeof t.subject=="function"?t.subject():t.subject)??(0,sa.randomUUID)(),p=(0,ce.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,ce.createClientToken)(c,{baseUrl:h,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:f,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(ra(p,e.appSlug,a,u))}function Ud(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 Dd(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 Fd=new Set(["error","paused"]);function Qr(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let l=aa(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 tn({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"?()=>fs({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>Zi(n):null,listPrices:n?()=>zo(n):null,shared:e.lane==="api-key"?()=>Go({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:Ud});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},xe({appSlug:t.defaultApp}))),s}function ua(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=l=>{process.stderr.write(`[decision-pool] ${l}
64
- `)},a=(l,u)=>{let d=o.get(u);if(d)return d;let c=new fn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async h=>{let f=aa(t,l,u,{concurrencyKey:h.concurrencyKey});return f.gone.onGone(()=>c.evict(f)),await Bn(f.session),i(`slot attached pool=${u} slot=${h.concurrencyKey} session=${f.session.id??"(no id)"}`),f},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,f)=>i(`slot detached pool=${u} slot=${h.concurrencyKey} reason=${f}`)});return o.set(u,c),c};return{async boot(){if(t.defaultApp===null)return;let l={appSlug:t.defaultApp};await a(l,xe(l)).boot()},async sessionFor(l){let u=await e.resolveTargetFor(l),d=xe(u),c=a(u,d).tryAcquireReady();if(!c)throw new Be(a(u,d).stats().lastMissAgeMs);let h=s.get(c.entry)??[];return h.push(c),s.set(c.entry,h),{app:d,entry:c.entry,identity:en(u)}},async warmFor(l){let u=await e.resolveTargetFor(l);await a(u,xe(u)).boot()},end(l){let u=s.get(l)?.shift();u&&(s.get(l)?.length===0&&s.delete(l),u.release())},evict(l){for(let u of o.values())u.evict(l)},reap(){for(let l of o.values())l.reap()},async pingReady(l){for(let u of o.values())if(await u.pingReady(l))return!0;return!1},stats(){return[...o.entries()].map(([l,u])=>({poolKey:l,...u.stats()}))},async drain(l){await Promise.all([...o.values()].map(u=>u.drain({timeoutMs:l})))},async close(){await Promise.all([...o.values()].map(l=>l.close()))}}}function Bd(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 Bn(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:Bd(t.phase),signal:e})}async function oa(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 Fn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Zr(t,e=ko,n,r,o=Er){let s=new WeakMap,i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,d=p=>{let y=p.session.id;return typeof y=="string"&&y.length>0?y:null},c=p=>{let y=s.get(p);if(!y){let g={waiting:0,gone:new AbortController};u.set(p,g),y=(async()=>{if(await Bn(p.session,g.gone.signal),g.gone.signal.aborted)throw Fn(g.gone.signal);u.get(p)===g&&u.delete(p);let w=await bo(p.session,await e());return Object.assign(w,{sessionId:p.session.id})})(),s.set(p,y),y.catch(()=>{s.get(p)===y&&s.delete(p)}),y.then(()=>{u.get(p)===g&&u.delete(p)},()=>{u.get(p)===g&&u.delete(p)})}return y},h=p=>{let y=l.get(p);return y||(y=(async()=>{let g=await c(p);return{appendInputAudio:w=>g.appendInputAudio(w),onOutputAudio:w=>g.onOutputAudio(w),sessionId:d(p)}})(),l.set(p,y),y.catch(()=>{l.get(p)===y&&l.delete(p)})),y},f=async(p,y,g)=>{if(g?.aborted){let m=u.get(p);throw(s.get(p)===void 0||m!==void 0&&m.waiting===0)&&await oa(p.session),Fn(g)}let w=y(p),v=u.get(p);return v!==void 0&&v.waiting++,g===void 0?w:new Promise((m,R)=>{let b=()=>{v!==void 0&&--v.waiting===0&&u.get(p)===v&&(v.gone.abort(),u.delete(p),s.delete(p),l.delete(p),oa(p.session).catch(()=>{})),R(Fn(g))};g.addEventListener("abort",b,{once:!0});let _=()=>g.removeEventListener("abort",b);w.then(S=>{_(),m(S)},S=>{_(),R(S)})})};return{createResponse:ta({sessionFor:r?p=>r.sessionFor(p):p=>t.sessionFor(p),sessionIdOf:p=>d(p),evict:(p,y)=>{r?r.evict(y):t.evict(p,y)},onAdmissionVerdict:(p,y,g)=>{Dd(g)&&(r?r.evict(y):t.evict(p,y),n?.(p,g.kind==="never-live"?"never-live":"create-failed"))},createStream:async(p,y)=>{try{await Bn(p.session);let g=Si(Xr(await p.responses.responses.create(y),p.gone),o);if(!r)return g;let w=p;return(async function*(){try{yield*g}catch(m){throw ki(m)&&r.evict(w),m}finally{r.end(w)}})()}catch(g){throw r&&r.end(p),g}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(p,y)=>t.supportsImages(p,y),listImageModels:()=>t.imageModelList(),catalogIdentity:p=>t.catalogIdentityFor(p),servingAppSlug:async p=>await t.servingAppSlugFor(p),supportsAudio:p=>t.supportsAudio(p),supportsSpeech:p=>t.supportsSpeech(p),speechVoices:p=>t.speechVoices(p),supportsTranscription:p=>t.supportsTranscription(p),transcriptStreamFor:p=>t.transcriptStreamFor(p),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(p,y)=>{let{entry:g}=await t.sessionFor(p);return await f(g,c,y)},openAudioOn:async(p,y)=>{let{entry:g}=await t.sessionForHandle(p);return await f(g,h,y)},openTurnsOn:async function*(p,y){if(y?.aborted)throw Fn(y);let{entry:g}=await t.sessionForHandle(p);yield*us(g.session,y)},openVideo:async p=>{let{entry:y}=await t.sessionFor(p),g=i.get(y);return g||(g=So(y.session),i.set(y,g)),g},openVideoOut:async p=>{let{entry:y}=await t.sessionFor(p),g=a.get(y);return g||(g=xo(y.session),a.set(y,g)),g},sessionHandle:async p=>(await t.handleFor(p)).handle,speechSessionHandle:async p=>(await t.speechHandleFor(p)).handle,evictSpeechSession:async p=>{let{app:y,entry:g}=await t.sessionForHandle(p);await t.evict(y,g)},createResponseOn:async(p,y)=>{let{entry:g}=await t.sessionForHandle(p);return await Bn(g.session),Xr(await g.responses.responses.create(y),g.gone)},onSessionEnd:async(p,y)=>{let{entry:g}=await t.sessionForHandle(p),w=g.session;if(typeof w.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let v=!1;return w.onPhase(m=>{if(v||!Fd.has(m.name))return;v=!0;let R=w.endsAt??null;y({timeLeftMs:R?Math.max(0,R.getTime()-Date.now()):null,reason:m.reason??`session ${m.name}`})})}}}var eo=8080,Ft="serve",la="0.0.0.0";function Hd(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function da(t=process.env){let e=(t.PORT??"").trim(),n=e===""?eo: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=Os(an(Hd(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?an(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:an(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");return{port:n,baseUrl:r,apiUrl:s,catalog:l,ledgerSigning:u?{keyId:d,key:u}:void 0}}var to=512;function Bt(t){return`urun-inference-proxy-${(0,Hn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var pt=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){return Object.assign(Object.create(e),{tenant:n.orgId})}build(e){if(this.opts.build){let s=this.opts.build(e);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,e),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ft,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,release:"end",decisionPool:ia(process.env,process.env.HOSTNAME)??void 0},r=Qr(n),o=n.decisionPool?ua(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(Zr(r,void 0,void 0,o??void 0),e),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>=to;){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("; ")}`)}},qn=512,no=1024,ft=class extends Error{constructor(){super(`conversation capacity reached (${qn} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function qd(t){return{sessionStartOptions:e=>{if(e.startsWith(vt))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(vt)||t.set(e,n)}}}function jd(t,e,n,r){let o=Qr({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ft,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalog,subject:n.subject,release:"detach",...qd(r)});return{clients:Zr(o),release:async()=>{await o.closeAll()}}}var mt=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${Bt(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):jd(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>=qn;){let e=this.byCaller.keys().next();if(e.done)throw new ft;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 ft;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,Hn.randomUUID)())),n),s={createResponse:(i,a)=>o().backhaul.clients.createResponse(i,a),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),createResponseOn:(i,a)=>o().backhaul.clients.createResponseOn(i,a),onSessionEnd:(i,a)=>o().backhaul.clients.onSessionEnd(i,a)};return s.openAudio=async(i,a)=>{let 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)=>{let l=o().backhaul.clients.openAudioOn;if(l===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 l(i,a)},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>=no;){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 H("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 jn="/inference-usage",ca=25e3;var Gd=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function pa(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Gd.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 Gn=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${jn}`,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(ca)})}catch(i){throw new q(`the uRun usage surface (POST ${jn}) could not be reached within ${ca}ms: ${pa(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new ae("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 q(`the uRun usage surface (POST ${jn}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new q(`the uRun usage surface (POST ${jn}) answered HTTP ${o.status} with a body that is not JSON: ${pa(i)}`)}return bi(s,this.opts.onRejectedRow)}};var uo="/inference-ledger",lo=1e4,ht=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},so=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},Y=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},io=class extends ae{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ao=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Vd=[["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",ro],["output_minutes",ro],["cost_nano_usd",ro],["price_version",t=>t===null||typeof t=="string"]];function Jd(t){for(let[e,n]of Vd){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Wd(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:Jd(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function ro(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function oo(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Kd(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function fa(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 zd(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&&fa(t.started_at,n.started_at)&&fa(t.completed_at,n.completed_at)&&oo(t.prompt_tokens,n.prompt_tokens)&&oo(t.completion_tokens,n.completion_tokens)&&oo(t.output_units,n.output_units)&&Kd(t.output_minutes,n.output_minutes)}function Yd(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v1",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(n),t.started_at,t.completed_at].join(`
65
- `)}async function Xd(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(Yd(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function co(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Y(`${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 Y(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new Y(`${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 Y(`${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 Y(`${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 Y(`${e} answered a non-string ${u}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new Y(`${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 Y(`${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 Y(`${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 gt=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${uo}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Xd(n,this.opts.signing)}):JSON.stringify(n)}catch(u){throw new Y(`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(lo)})}catch(u){throw new Y(`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=Wd(u);throw d.status==="found"&&zd(n,d.row)?new so(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 ht(`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 ht(`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 io("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 h=c.error;h!==null&&typeof h=="object"&&"code"in h&&(d=h.code)}}catch{}throw d==="ledger_signature_invalid"?new ao(`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 Y(`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 Y(`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 Y(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=co(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new Y(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};var fo=5e3,Qd=1e3,Zd=1500,mo=3e3,ec="/api/client-tokens";function po(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function ma(t,e,n,r){po(t,e,{error:{message:n,type:r}})}async function tc(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${ec}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(mo)});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 ga(t){let e=t.resolver??new ct({gatewayUrl:t.baseUrl}),n=t.registry??new pt({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),r=t.probeControlPlane??(()=>tc(t.baseUrl)),o=async()=>{let m=null;for(let _ of n.decisionPools()){m=_;break}if(!m)return null;let R=m.stats();if(R.some(_=>_.draining))return{ok:!1,detail:"decision pool draining"};if(R.every(_=>_.attached===0&&_.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let b=await m.pingReady(Zd);return{ok:b,detail:b?"a decision slot answered its session ping":"no decision slot answered its session ping"}},s=t.usageClient??new Gn({apiUrl:t.apiUrl}),i=t.ledgerClient??new gt({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),a=process.env.URUN_SHARED_ORG_ID?.trim(),l=process.env.URUN_SHARED_ORG_API_KEY?.trim();a&&l&&(async()=>{try{await n.decisionWarmerFor({orgId:a,apiKey:l})?.warmFor(Lr)}catch(m){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(m instanceof Error?m.message:m)}
66
- `)}})();let u=new dt(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),d=async m=>e.resolve(Ve(m.headers.authorization)),c=m=>m instanceof ae?{status:m.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:m instanceof Te?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null,h=Hi({clients:async m=>n.clientsFor(await d(m)),usage:{authorize:m=>Ve(m.headers.authorization),lookup:(m,R)=>s.lookup(m,R)},statusOf:c,...t.requestLog?{requestLog:t.requestLog}:{},observe:m=>u.observe(m),ledger:{write:(m,R)=>i.write(Ve(m.headers.authorization),R),observe:m=>u.observeLedger(m),...t.ledgerLog?{report:t.ledgerLog}:{}}}),f=null,p=null,y=(0,ha.createServer)((m,R)=>{let b=new URL(m.url??"/","http://localhost");(async()=>{if(m.method==="GET"&&b.pathname==="/healthz"){po(R,200,{ok:!0});return}if(m.method==="GET"&&b.pathname==="/readyz"){let T=Date.now();if((!f||T-f.at>=fo)&&(f={at:T,...await r()}),!p||T-p.at>=Qd){let P=await o();p=P===null?{at:T,ok:!0,detail:null}:{at:T,ok:P.ok,detail:P.detail}}let x=(f?.ready??!1)&&p.ok,A=p.detail===null?f?.detail??"control plane not yet probed":`${f?.detail??"control plane not yet probed"}; ${p.detail}`;po(R,x?200:503,{ok:x,control_plane:A});return}let _=b.pathname==="/v1"||b.pathname.startsWith("/v1/"),S=b.pathname.startsWith("/partners/");if(!_&&!S){ma(R,404,`no route for ${m.method} ${b.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz and /readyz`,"invalid_request_error");return}h(m,R)})().catch(_=>{if(!R.headersSent){ma(R,500,String(_ instanceof Error?_.message:_),"proxy_error");return}R.end()})}),g=t.conversations??new mt({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),w=[rr(y,{authenticate:async m=>{let R=await e.resolve(m),b=g.connectionFor(R);return{clients:b.clients,scope:Bt(R.apiKey),onBindResumeHandle:b.bindResumeHandle,clientsForResume:b.clientsForResume,release:b.release}}}),cr(y,{clients:async m=>n.clientsFor(await d(m)),statusOf:c}).close,pn(y,{resolver:{resolve:async(m,R)=>{let b=await e.resolve(Ve(m.headers.authorization)),_=g.connectionFor(b),S;try{S=await Gi(_.clients,qi(m),R,ji(m))}catch(T){throw _.release().catch(()=>{}),T}return{...S,release:_.release}}}})];y.on("upgrade",(m,R)=>{let b=new URL(m.url??"/","http://localhost");b.pathname===Kt||b.pathname===lr||b.pathname===It||R.destroyed||(R.write(`HTTP/1.1 404 Not Found\r
75
+ `);return}n.end()})})}var Ml=ue(require("ioredis"),1);var No=require("crypto"),ul=require("http"),dl=9465,$o="x-urun-key-id",Uo="x-urun-key-fingerprint",Do="urun-ratelimit-bucket:",Fo="urun-ratelimit-tier:",hr="anonymous",Ap=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Bo(t){return(0,No.createHash)("sha256").update(`${Do}${t}`).digest("hex")}function Ho(t){return(0,No.createHash)("sha256").update(`${Fo}${t}`).digest("hex")}function jo(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Ap.test(n)?n:null}function yr(){return(0,ul.createServer)((t,e)=>{let n=jo(t.headers.authorization);e.setHeader($o,n===null?hr:Bo(n)),e.setHeader(Uo,n===null?hr:Ho(n)),e.writeHead(200),e.end()})}var wr=require("@urun-sh/core"),pe=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Ge=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function at(t){let e=(t??"").trim();if(e==="")throw new pe("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 pe("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var Ip=60,qo=6e4,Go=4096;function Op(t){return t===401||t===403}var Nt=class{constructor(e){this.opts=e;this.mint=e.mint??wr.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new pe("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<qo)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:Ip})).orgId}catch(o){throw o instanceof wr.ClientTokenError&&Op(o.status)?(this.cache.delete(e),new pe("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Ge("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}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new Ge("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>=Go){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};var yn=require("crypto");var fe=require("@urun-sh/core");async function cl(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 pl=require("@urun-sh/core"),Vo=2;function Tp(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Pp(t){let e=t?.type;return e==="response.completed"||e==="error"}function fl(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Vo;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 y of p){if(Pp(y)&&(d=!0),Tp(y)){if(i>1)continue}else c=!0;yield y}}catch(p){if(p instanceof pl.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,l,p)}catch{}throw p}if(i<Vo&&!c){await t.evict(a,l);continue}throw p}if(d)return;if(i<Vo&&!c){await t.evict(a,l);continue}return}})()}}var wl=require("crypto");var Cp="audio";var ml=new WeakMap;function gl(t,e,n){let r=t.doc(Cp),o=[],s=0,i=0;return{sessionId:e,appendInputAudio(a){let l=Buffer.from(a,"base64");if(l.byteLength===0||(o.push(l),s+=l.byteLength,s<4800))return;let u=Buffer.concat(o,s).toString("base64");if(o=[],s=0,n===void 0){let d=(ml.get(t)??0)+1;ml.set(t,d),r.set({frames:{[String(d%32)]:{s:d,pcm16:u}}})}else{let d=++i;r.set({frames:{[`${n}:${d%32}`]:{s:d,pcm16:u,c:n}}})}},onOutputAudio(){return()=>{}}}}var Mp=0,Np=4,$p=4;function _l(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):Mp;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,Np));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",$p),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function hl(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 vl(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 it(_),gone:cr(_,n)});if(i.lane==="jwt"){let _=(0,fe.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(hl(_,e.appSlug,a,u))}let{apiKey:c,gatewayUrl:p}=i,y=(typeof t.subject=="function"?t.subject():t.subject)??(0,wl.randomUUID)(),h=(0,fe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,fe.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:y,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(hl(h,e.appSlug,a,u))}function Up(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 bl(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 Dp=new Set(["error","paused"]);function Wo(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let l=vl(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 Pn({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"?()=>ti({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>cl(n):null),listPrices:n?()=>Bs(n):null,shared:e.lane==="api-key"?()=>Ns({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:Up});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ue({appSlug:t.defaultApp}))),s}function Sl(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}
76
+ `)},l=(d,c)=>{let p=o.get(c);if(p)return p;let y=new Ln({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async h=>{let _=vl(t,d,c,{concurrencyKey:h.concurrencyKey});return _.gone.onGone(()=>y.markSessionDead(_)),await vr(_.session),a(`slot attached pool=${c} slot=${h.concurrencyKey} session=${_.session.id??"(no id)"}`),_},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,_)=>a(`slot detached pool=${c} slot=${h.concurrencyKey} reason=${_}`),terminalOpenFailure:h=>h instanceof fe.SessionFailedError&&bl(h)});return s.set(c,{target:d,env:n}),o.set(c,y),y},u=async(d,c)=>{let p=s.get(c);if(p)try{let y=await e.poolTuningFor(d);l(d,c).retune({min:y?.min??p.env.min,max:y?.max??p.env.max,inFlightCap:y?.in_flight_cap??p.env.inFlightCap,idleGraceMs:y?.idle_grace_s!==void 0?y.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:y?.warm_wait_s!==void 0?y.warm_wait_s*1e3:void 0})}catch(y){a(`pool tuning refresh failed pool=${c} reason=${y instanceof Error?y.message:String(y)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await l(d,Ue(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=Ue(c),y=l(c,p);await u(c,p);let h=await y.acquire({timeoutMs:y.requestWaitMs}),_=i.get(h.entry)??[];return _.push(h),i.set(h.entry,_),{app:p,entry:h.entry,identity:Tn(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await l(c,Ue(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 Fp(t){return(0,fe.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?fe.DEFAULT_WHEN_LIVE_TIMEOUT_MS:fe.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:fe.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function vr(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:Fp(t.phase),signal:e})}async function yl(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 _r(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Jo(t,e=gs,n,r,o=Jr,s){let i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakMap,c=f=>{let m=f.session.id;return typeof m=="string"&&m.length>0?m:null},p="lane",y=f=>{let m=Cn(f);if(!s||!m||m.app!==p)return null;let w=s.entryFor(m.key);if(!w)throw new U(`the lane behind this handle (${m.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:m.key,entry:w}},h=async f=>y(f)?.entry??(await t.sessionForHandle(f)).entry,_=f=>{let m=i.get(f);if(!m){let w={waiting:0,gone:new AbortController};d.set(f,w),m=(async()=>{if(await vr(f.session,w.gone.signal),w.gone.signal.aborted)throw _r(w.gone.signal);d.get(f)===w&&d.delete(f);let g=await fs(f.session,await e());return Object.assign(g,{sessionId:f.session.id})})(),i.set(f,m),m.catch(()=>{i.get(f)===m&&i.delete(f)}),m.then(()=>{d.get(f)===w&&d.delete(f)},()=>{d.get(f)===w&&d.delete(f)})}return m},A=f=>{let m=u.get(f);return m||(m=(async()=>{let w=await _(f);return{appendInputAudio:g=>w.appendInputAudio(g),onOutputAudio:g=>w.onOutputAudio(g),sessionId:c(f)}})(),u.set(f,m),m.catch(()=>{u.get(f)===m&&u.delete(f)})),m},v=async(f,m,w)=>{if(w?.aborted){let b=d.get(f);throw(i.get(f)===void 0||b!==void 0&&b.waiting===0)&&await yl(f.session),_r(w)}let g=m(f),S=d.get(f);return S!==void 0&&S.waiting++,w===void 0?g:new Promise((b,k)=>{let x=()=>{S!==void 0&&--S.waiting===0&&d.get(f)===S&&(S.gone.abort(),d.delete(f),i.delete(f),u.delete(f),yl(f.session).catch(()=>{})),k(_r(w))};w.addEventListener("abort",x,{once:!0});let R=()=>w.removeEventListener("abort",x);g.then(I=>{R(),b(I)},I=>{R(),k(I)})})};return{createResponse:fl({sessionFor:s?async f=>{let m=await t.resolveTargetFor(f);if(m.sharedApp){let w=await s.sessionFor(f,m);return{app:w.app,entry:w.entry,identity:w.identity}}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,m)=>{s&&s.owns(m)?s.evict(m):r?r.evict(m):t.evict(f,m)},onAdmissionVerdict:(f,m,w)=>{bl(w)&&(s&&s.owns(m)?s.evict(m):r?r.markSessionDead(m):t.evict(f,m),n?.(f,w.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,m)=>{try{await vr(f.session);let w=gi(xo(await f.responses.responses.create(m),f.gone),o);if(!r&&!s)return w;let g=f;return(async function*(){try{yield*w}catch(b){throw hi(b)&&(s&&s.owns(g)?s.evict(g):r&&(b instanceof U?r.markSessionDead(g):r.evict(g))),b}finally{s&&s.owns(g)?s.release(g):r?.end(g)}})()}catch(w){throw s&&s.owns(f)?s.release(f):r&&r.end(f),w}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,m)=>t.supportsImages(f,m),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,m)=>{let{entry:w}=await t.sessionFor(f);return await v(w,_,m)},openAudioOn:async(f,m,w)=>{let g=y(f);if(g)return gl(g.entry.session,g.laneId,w);let{entry:S}=await t.sessionForHandle(f);return await v(S,A,m)},openTurnsOn:async function*(f,m){if(m?.aborted)throw _r(m);let w=await h(f);yield*Qs(w.session,m)},openVideo:async f=>{let{entry:m}=await t.sessionFor(f),w=a.get(m);return w||(w=ms(m.session),a.set(m,w)),w},openVideoOut:async f=>{let{entry:m}=await t.sessionFor(f),w=l.get(m);return w||(w=ys(m.session),l.set(m,w)),w},sessionHandle:async f=>{if(s){let m=await t.resolveTargetFor(f);if(m.sharedApp){let w=await s.sessionFor(f,m),g=c(w.entry);if(g===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return On(p,g)}}return(await t.handleFor(f)).handle},releaseSessionHandle:f=>{let m=Cn(f);if(!s||m?.app!==p)return;let w=s.entryFor(m.key);w&&s.release(w)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:m,entry:w}=await t.sessionForHandle(f);await t.evict(m,w)},createResponseOn:async(f,m,w)=>{let g=await h(f);await vr(g.session);let S=w!==void 0&&y(f)?new it({...g.session,consumerId:w}):g.responses;return xo(await S.responses.create(m),g.gone)},onSessionEnd:async(f,m)=>{let w=y(f);if(w)return w.entry.gone.onGone(k=>m({timeLeftMs:null,reason:k.message}));let{entry:g}=await t.sessionForHandle(f),S=g.session;if(typeof S.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let b=!1;return S.onPhase(k=>{if(b||!Dp.has(k.name))return;b=!0;let x=S.endsAt??null;m({timeLeftMs:x?Math.max(0,x.getTime()-Date.now()):null,reason:k.reason??`session ${k.name}`})})}}}var Rl=require("http");var Bp="/pooler/v1/inference",$t=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},Hp=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)},jp=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)}},xl=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)}),qp=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await xl(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 $t(t.status,e,n,t.retryAfterSeconds)};async function Gp(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${Bp}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Hp(e),firstMessage:jp(e)}});return new Promise((a,l)=>{let u=(0,Rl.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 $t(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var kl=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*Vp(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
77
+
78
+ `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=kl(s);i!==null&&(yield i)}let n=kl(e);n!==null&&(yield n)}async function El(t,e,n,r){let o=ar(e,n,r),s=o.model??"";if(s==="")throw new $t(400,"missing_model","the pooler submit requires a model");let i=await Gp(t,o,n,s,e.stream===!0);if(i.status>=400)throw await qp(i);let a=e.stream===!0?ur(n,Vp(i)):await Wp(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Wp(t,e){let n=await xl(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 $t(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return ur(e,(async function*(){yield o})())}var Ko=8080,hn="serve",Al="0.0.0.0";function Jp(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Il(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Ko: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=bi(Dn(Jp(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?Dn(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:Dn(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()},y=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],h=y.filter((w,g)=>Object.values(p)[g]==="");if(h.length!==0&&h.length!==y.length)throw new Error(`${y.join(", ")} must be set together (or all left unset) \u2014 missing: ${h.join(", ")}, which would half-configure the lane plane`);let _=h.length===0?p:void 0,A={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"],f=v.filter((w,g)=>Object.values(A)[g]==="");if(f.length!==0&&f.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${f.join(", ")}, which would half-configure the pooler cutover`);let m=f.length===0?A:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:l,ledgerSigning:c,lane:_,pooler:m}}var zo=512;function wn(t){return`urun-inference-proxy-${(0,yn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Ut=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){let r=Object.assign(Object.create(e),{tenant:n.orgId}),o=this.opts.pooler;return o===void 0?r:Object.assign(Object.create(r),{createResponse:(s,i)=>{let a=`px_${(0,yn.randomUUID)()}`;return El(o,s,a,a)}})}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),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:hn,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{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:_l(process.env,process.env.HOSTNAME)??void 0},r=Wo(n),o=n.decisionPool?Sl(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(Jo(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e),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>=zo;){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,Yo=1024,Dt=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 Kp(t){return{sessionStartOptions:e=>{if(e.startsWith(Jt))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(Jt)||t.set(e,n)}}}function zp(t,e,n,r){let o=Wo({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:hn,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{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",...Kp(r)});return{clients:Jo(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var Ft=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${wn(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):zp(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>=br;){let e=this.byCaller.keys().next();if(e.done)throw new Dt;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 Dt;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,yn.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),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>=Yo;){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 U("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 Sr="/inference-usage",Ol=25e3;var Yp=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Tl(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Yp.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 kr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Sr}`,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(Ol)})}catch(i){throw new Z(`the uRun usage surface (POST ${Sr}) could not be reached within ${Ol}ms: ${Tl(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new pe("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 Z(`the uRun usage surface (POST ${Sr}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new Z(`the uRun usage surface (POST ${Sr}) answered HTTP ${o.status} with a body that is not JSON: ${Tl(i)}`)}return pa(s,this.opts.onRejectedRow)}};var ns="/inference-ledger",rs=1e4,Bt=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Zo=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},re=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},es=class extends pe{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ts=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Xp=[["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",Xo],["output_minutes",Xo],["cost_nano_usd",Xo],["price_version",t=>t===null||typeof t=="string"]];function Qp(t){for(let[e,n]of Xp){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Zp(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"}:Qp(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Xo(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Qo(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function ef(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Pl(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 tf(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&&Pl(t.started_at,n.started_at)&&Pl(t.completed_at,n.completed_at)&&Qo(t.prompt_tokens,n.prompt_tokens)&&Qo(t.completion_tokens,n.completion_tokens)&&Qo(t.output_units,n.output_units)&&ef(t.output_minutes,n.output_minutes)}function nf(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(`
79
+ `)}async function rf(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(nf(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function os(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new re(`${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 re(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new re(`${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 re(`${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 re(`${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 re(`${e} answered a non-string ${u}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new re(`${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 re(`${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 re(`${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 Ht=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${ns}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await rf(n,this.opts.signing)}):JSON.stringify(n)}catch(u){throw new re(`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(rs)})}catch(u){throw new re(`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=Zp(u);throw d.status==="found"&&tf(n,d.row)?new Zo(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 Bt(`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 Bt(`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 es("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 ts(`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 re(`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 re(`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 re(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=os(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new re(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};var ss=5e3,of=1e3,sf=1500,is=3e3,af="/api/client-tokens";function Rr(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Cl(t,e,n,r){Rr(t,e,{error:{message:n,type:r}})}async function lf(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${af}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(is)});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 Nl(t){let e=t.resolver??new Nt({gatewayUrl:t.baseUrl}),n=new Mt(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),r=null,o=(()=>{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 g=new Ml.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),S=il({redis:g});return{registry:Wa({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:Ya({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(k,x)=>r?.onHostedChange(k,x)??(()=>()=>{}),roomDoc:(k,x)=>{if(!r)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return r.roomDoc(k,x)},metrics:n,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(k,x)=>S.rows().then(R=>{let I=Dr(R,x);return I?.warm_wait_s!==void 0?I.warm_wait_s*1e3:void 0})}),catalog:S,redis:g}})(),s=t.registry??new Ut({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:o?null:t.catalog,catalogRows:o?()=>o.catalog.rows():void 0,lanes:o?.registry,pooler:t.pooler}),i=t.probeControlPlane??(()=>lf(t.baseUrl)),a=async()=>{let g=null;for(let k of s.decisionPools()){g=k;break}if(!g)return null;let S=g.stats();if(S.some(k=>k.draining))return{ok:!1,detail:"decision pool draining"};if(S.every(k=>k.attached===0&&k.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let b=await g.pingReady(sf);return{ok:b,detail:b?"a decision slot answered its session ping":"no decision slot answered its session ping"}},l=t.usageClient??new kr({apiUrl:t.apiUrl}),u=t.ledgerClient??new Ht({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),d=process.env.URUN_SHARED_ORG_ID?.trim(),c=process.env.URUN_SHARED_ORG_API_KEY?.trim();d&&c&&(async()=>{try{await s.decisionWarmerFor({orgId:d,apiKey:c})?.warmFor(wo)}catch(g){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(g instanceof Error?g.message:g)}
80
+ `)}})();let p=async g=>e.resolve(at(g.headers.authorization)),y=g=>g instanceof pe?{status:g.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:g instanceof Ge?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:g.detail}:null,h=Ta({clients:async g=>s.clientsFor(await p(g)),usage:{authorize:g=>at(g.headers.authorization),lookup:(g,S)=>l.lookup(g,S)},statusOf:y,...t.requestLog?{requestLog:t.requestLog}:{},observe:g=>n.observe(g),ledger:{write:(g,S)=>u.write(at(g.headers.authorization),S),observe:g=>n.observeLedger(g),...t.ledgerLog?{report:t.ledgerLog}:{}}}),_=null,A=null,v=(0,Ll.createServer)((g,S)=>{let b=new URL(g.url??"/","http://localhost");(async()=>{if(g.method==="GET"&&b.pathname==="/healthz"){Rr(S,200,{ok:!0});return}if(g.method==="GET"&&b.pathname==="/readyz"){let R=Date.now();if((!_||R-_.at>=ss)&&(_={at:R,...await i()}),!A||R-A.at>=of){let C=await a();A=C===null?{at:R,ok:!0,detail:null}:{at:R,ok:C.ok,detail:C.detail}}let I=(_?.ready??!1)&&A.ok,E=A.detail===null?_?.detail??"control plane not yet probed":`${_?.detail??"control plane not yet probed"}; ${A.detail}`;Rr(S,I?200:503,{ok:I,control_plane:E});return}if(g.method==="GET"&&b.pathname==="/lanez"){Rr(S,200,{pools:o?await o.registry.status():null});return}let k=b.pathname==="/v1"||b.pathname.startsWith("/v1/"),x=b.pathname.startsWith("/partners/");if(!k&&!x){Cl(S,404,`no route for ${g.method} ${b.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}h(g,S)})().catch(k=>{if(!S.headersSent){Cl(S,500,String(k instanceof Error?k.message:k),"proxy_error");return}S.end()})}),f=t.conversations??new Ft({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:o?null:t.catalog,catalogRows:o?()=>o.catalog.rows():void 0,lanes:o?.registry}),m=[Hr(v,{authenticate:async g=>{let S=await e.resolve(g),b=f.connectionFor(S);return{clients:b.clients,scope:wn(S.apiKey),onBindResumeHandle:b.bindResumeHandle,clientsForResume:b.clientsForResume,release:b.release}}}),Qr(v,{clients:async g=>s.clientsFor(await p(g)),statusOf:y}).close,Gn(v,{resolver:{resolve:async(g,S)=>{let b=await e.resolve(at(g.headers.authorization)),k=f.connectionFor(b),x;try{x=await Na(bo(k.clients,t.realtimeCompanions),La(g),S,Ma(g))}catch(I){throw k.release().catch(()=>{}),I}let R=x.release;return{...x,release:async()=>{await R?.(),await k.release()}}}}})];if(t.lane&&o){let g=t.lane,S=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;r=sl(v,{verifyToken:(k,x)=>qa(k,x,g.tokenSecret,void 0,S),selfAddress:g.selfAddress,laneTenantOf:k=>o.redis.get(`lane_tenant:${k}`),onLaneTenantMissing:()=>n.observeLaneDocTenantMissing(),previousTokenSecret:S,hostRegistry:{setHost:(k,x)=>o.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:${k}`,x,String(ol)),delHost:k=>o.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${k}`,g.selfAddress)}});let b=o;m.push(async()=>{await r.close(),await b.registry.close(),b.redis.quit().catch(()=>{})})}v.on("upgrade",(g,S)=>{let b=new URL(g.url??"/","http://localhost");b.pathname===Rn||b.pathname===Yr||b.pathname===rn||r!==null&&b.pathname.startsWith("/doc/")||S.destroyed||(S.write(`HTTP/1.1 404 Not Found\r
67
81
  Connection: close\r
68
82
  \r
69
- no WS route for ${b.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),R.destroy())});let v=async()=>{for(let m of w)await m();await g.detachAll()};return{server:y,metricsServer:Cn(u),metrics:u,edgeIdentityServer:Mn(),registry:n,closeAll:()=>n.closeAll(),closeWebSockets:v}}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});
83
+ no WS route for ${b.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),S.destroy())});let w=async()=>{for(let g of m)await g();await f.detachAll()};return{server:v,metricsServer:gr(n),metrics:n,edgeIdentityServer:yr(),registry:s,closeAll:()=>s.closeAll(),closeWebSockets:w}}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});