@urun-sh/openai 0.5.5 → 0.6.0

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 (56) hide show
  1. package/dist/{ResponsesClient-BYx3YLGo.d.ts → ResponsesClient-CSSrOYD8.d.ts} +7 -1
  2. package/dist/{ResponsesClient-Dft3bg3b.d.cts → ResponsesClient-_OZERUjH.d.cts} +11 -1
  3. package/dist/chunk-3JWYIKHM.js +2 -0
  4. package/dist/chunk-45FJ5GTP.js +7 -0
  5. package/dist/chunk-6M5JK4YC.js +1 -0
  6. package/dist/chunk-QTVTCMJU.js +1 -0
  7. package/dist/chunk-TDRZZGUK.js +1 -0
  8. package/dist/chunk-TPH77ZOW.js +58 -0
  9. package/dist/chunk-WCMX5VOF.js +4 -0
  10. package/dist/chunk-YXK42SKC.js +1 -0
  11. package/dist/gemini-live.cjs +2 -2
  12. package/dist/gemini-live.d.cts +79 -7
  13. package/dist/gemini-live.d.ts +32 -7
  14. package/dist/gemini-live.js +1 -1
  15. package/dist/hosted/bin.cjs +43 -27
  16. package/dist/hosted/bin.js +4 -4
  17. package/dist/hosted/index.cjs +41 -26
  18. package/dist/hosted/index.d.cts +710 -17
  19. package/dist/hosted/index.d.ts +171 -6
  20. package/dist/hosted/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.d.cts +5 -5
  23. package/dist/index.d.ts +5 -5
  24. package/dist/index.js +1 -1
  25. package/dist/{models-NYMZrklp.d.cts → models-DUdx_Y6X.d.cts} +1 -1
  26. package/dist/pi-extension/index.cjs +7 -7
  27. package/dist/pi-extension/index.d.cts +2 -2
  28. package/dist/pi-extension/index.d.ts +2 -2
  29. package/dist/pi-extension/index.js +1 -1
  30. package/dist/pi-extension/standalone.cjs +53 -53
  31. package/dist/proxy/cli.cjs +55 -43
  32. package/dist/proxy/cli.js +14 -13
  33. package/dist/proxy/index.cjs +31 -28
  34. package/dist/proxy/index.d.cts +132 -18
  35. package/dist/proxy/index.d.ts +28 -11
  36. package/dist/proxy/index.js +1 -6
  37. package/dist/responses-turn-BfdBbey8.d.cts +2394 -0
  38. package/dist/responses-turn-CdhIre_a.d.ts +652 -0
  39. package/dist/{translator-CcDBEfvm.d.cts → translator-CO8W_hmJ.d.cts} +3 -3
  40. package/dist/{translator-C9uPKypK.d.ts → translator-Ddd65sXR.d.ts} +1 -1
  41. package/dist/{types-lsVTbNcH.d.cts → types-CHPtJx6d.d.cts} +13 -0
  42. package/dist/{types-lsVTbNcH.d.ts → types-CHPtJx6d.d.ts} +4 -0
  43. package/dist/{video-out-D20UuJ8G.d.cts → video-out-BsuLqlID.d.cts} +6 -6
  44. package/dist/{video-out-CWesbk12.d.ts → video-out-Cawtm7SF.d.ts} +1 -1
  45. package/package.json +14 -11
  46. package/dist/chunk-5BZCM3RS.js +0 -4
  47. package/dist/chunk-5NXM4IO3.js +0 -2
  48. package/dist/chunk-CWJRDBDC.js +0 -1
  49. package/dist/chunk-DMD5UENK.js +0 -1
  50. package/dist/chunk-GBBY3PCZ.js +0 -1
  51. package/dist/chunk-I2Q3B3OG.js +0 -6
  52. package/dist/chunk-OI2OY32M.js +0 -1
  53. package/dist/chunk-QVF7NF7G.js +0 -44
  54. package/dist/responses-turn-KOAoIqZ-.d.ts +0 -200
  55. package/dist/responses-turn-OrO4euEN.d.cts +0 -513
  56. /package/dist/{models-NYMZrklp.d.ts → models-DUdx_Y6X.d.ts} +0 -0
@@ -1,50 +1,53 @@
1
- "use strict";var He=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var qt=Object.prototype.hasOwnProperty;var Ht=(n,e)=>{for(var t in e)He(n,t,{get:e[t],enumerable:!0})},Jt=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jt(e))!qt.call(n,s)&&s!==t&&He(n,s,{get:()=>e[s],enumerable:!(o=Vt(e,s))||o.enumerable});return n};var Wt=n=>Jt(He({},"__esModule",{value:!0}),n);var Hn={};Ht(Hn,{GEMINI_LIVE_PATH:()=>Ee,OPENAI_REALTIME_PATH:()=>qe,OpenAIRealtimeConnection:()=>le,ResumptionRegistry:()=>pe,SessionGoneError:()=>X,UnknownModelError:()=>V,VIDEO_OUT_SETUP_KEY:()=>Q,attachGeminiLive:()=>Pe,attachOpenAIRealtime:()=>it,createOpenAIProxy:()=>Nt,serveGeminiLiveSocket:()=>Ot});module.exports=Wt(Hn);var Lt=require("http");var At=require("crypto"),St=require("ws");var V=class extends Error{},X=class extends Error{};var Se=require("@urun-sh/core");var at="urun.videoOut.v2-ws";var Ee="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Kt=1007,dt=1008,Z=1011,Te=1008,m=class extends Error{constructor(t,o=Kt){super(t);this.closeCode=o}closeCode},E=n=>typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null,Oe=["setup","clientContent","realtimeInput","toolResponse"];function lt(n){let e;try{e=JSON.parse(n)}catch{throw new m("client message is not valid JSON")}let t=E(e);if(!t)throw new m("client message must be a JSON object");let o=Oe.filter(a=>t[a]!==void 0),s=Object.keys(t).filter(a=>!Oe.includes(a));if(s.length>0)throw new m(`unknown client message field(s) ${JSON.stringify(s)} \u2014 expected exactly one of ${Oe.join(", ")}`);if(o.length!==1)throw new m(`client message must contain exactly one of ${Oe.join(", ")} (got ${o.length})`);let i=o[0],r=E(t[i]);if(!r)throw new m(`"${i}" must be a JSON object`);return{kind:i,[i]:r}}function ct(n,e){if(typeof n=="string")return n;let t=E(n),o=t?t.parts:void 0;if(!Array.isArray(o))throw new m(`${e}: expected a Content with a parts array`);let s=[];for(let i of o){let r=E(i);if(r&&typeof r.text=="string"){s.push(r.text);continue}throw r&&(r.inlineData!==void 0||r.fileData!==void 0)?new m(`${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`):r&&(r.functionCall!==void 0||r.functionResponse!==void 0)?new m(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new m(`${e}: unsupported part ${JSON.stringify(i)}`)}return s.join(`
2
- `)}var Yt={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Q="urun.videoOut";function pt(n){return{framing:at,codec:n}}function ft(n){let{seq:e,ptsUs:t,codec:o,key:s}=n.header;return{[Q]:{v:1,seq:e,ptsUs:t,codec:o,key:s,data:Buffer.from(n.au).toString("base64")}}}var Xt={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Qt=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Q],ut=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Zt(n){let e=E(n);if(!e)throw new m("setup.realtimeInputConfig must be an object");for(let s of Object.keys(e))if(!(s==="automaticActivityDetection"||s==="activityHandling"))throw new m(s==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${s}"`);let t=E(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!t)throw new m("realtimeInputConfig.automaticActivityDetection must be an object");for(let s of Object.keys(t??{}))if(s!=="disabled")throw new m(`automaticActivityDetection.${s} 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(t?.disabled!==!0)throw new m("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 o="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!ut.includes(e.activityHandling))throw new m(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${ut.join(", ")}`);o=e.activityHandling}return{manualActivity:!0,activityHandling:o}}var en=["temperature","maxOutputTokens","responseModalities"];function mt(n){for(let[l,f]of Object.entries(Xt))if(n[l]!==void 0)throw new m(f);for(let l of Object.keys(n))if(!Qt.includes(l))throw new m(`unsupported setup field "${l}"`);if(typeof n.model!="string"||n.model.length===0)throw new m('setup.model is required (format "models/{model}")');let e=n.model.replace(/^models\//,""),t,o,s=!1,i=E(n.generationConfig);if(n.generationConfig!==void 0&&!i)throw new m("setup.generationConfig must be an object");if(i){for(let l of Object.keys(i))if(!en.includes(l))throw new m(`unsupported generationConfig field "${l}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new m("generationConfig.temperature must be a number");t=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new m("generationConfig.maxOutputTokens must be a number");o=i.maxOutputTokens}if(i.responseModalities!==void 0){let l=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let f of l){let h=String(f).toUpperCase();if(h==="AUDIO"){s=!0;continue}if(h!=="TEXT")throw new m(`responseModalities ${JSON.stringify(f)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge rt-audio-out lane)`)}}}let r=[];n.systemInstruction!==void 0&&r.push({role:"system",content:ct(n.systemInstruction,"setup.systemInstruction")});let a;if(n.tools!==void 0){if(!Array.isArray(n.tools))throw new m("setup.tools must be an array");a=[];for(let l of n.tools){let f=E(l);if(!f)throw new m("setup.tools entries must be objects");for(let h of Object.keys(f))if(h!=="functionDeclarations")throw new m(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new m("tool.functionDeclarations must be an array");for(let h of f.functionDeclarations){let w=E(h);if(!w||typeof w.name!="string")throw new m("functionDeclarations entries require a string name");a.push({type:"function",name:w.name,description:w.description,parameters:w.parameters})}}a.length===0&&(a=void 0)}let d={enabled:!1,handle:null};if(n.sessionResumption!==void 0){let l=E(n.sessionResumption);if(!l)throw new m("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(l))if(f!=="handle")throw new m(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(l.handle!==void 0&&(typeof l.handle!="string"||l.handle.length===0))throw new m("sessionResumption.handle must be a non-empty string when present");d={enabled:!0,handle:typeof l.handle=="string"?l.handle:null}}let u=n.realtimeInputConfig===void 0?Yt:Zt(n.realtimeInputConfig),c=!1;if(n[Q]!==void 0){if(!E(n[Q]))throw new m(`setup["${Q}"] must be an object (the v1 opt-in is {})`);c=!0}return{model:e,systemItems:r,tools:a,temperature:t,maxOutputTokens:o,audioModality:s,activity:u,sessionResumption:d,videoOut:c}}function ht(n){return{sessionResumptionUpdate:{newHandle:n,resumable:!0}}}function gt(n){let e=Math.max(0,n??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function yt(n){for(let o of Object.keys(n))if(o!=="turns"&&o!=="turnComplete")throw new m(`unsupported clientContent field "${o}"`);let e=n.turns===void 0?[]:n.turns;if(!Array.isArray(e))throw new m("clientContent.turns must be an array");let t=[];for(let o of e){let s=E(o);if(!s)throw new m("clientContent.turns entries must be Content objects");let i=s.role===void 0?"user":String(s.role).toLowerCase();if(i!=="user"&&i!=="model")throw new m(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(s.role)})`);t.push({role:i==="model"?"assistant":"user",content:ct(s,"clientContent.turns")})}return{items:t,turnComplete:n.turnComplete===!0}}var Ie=16e3,_t=24e3,tn=`audio/pcm;rate=${_t}`,wt=Buffer.alloc(960).toString("base64");function nn(n,e,t){if(e===t)return n;let o=Math.floor(n.length*t/e),s=new Int16Array(o),i=e/t,r=n.length-1;for(let a=0;a<o;a++){let d=a*i,u=Math.floor(d);if(u>=r){s[a]=n[r];continue}let c=d-u;s[a]=Math.round(n[u]+(n[u+1]-n[u])*c)}return s}function on(n){let e=E(n);if(!e)throw new m("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new m(`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 m("realtimeInput.video.data must be non-empty base64");let t=Buffer.from(e.data,"base64");if(t.length<3||t[0]!==255||t[1]!==216)throw new m("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(t)}function sn(n){let e=E(n);if(!e)throw new m("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new m(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let t=/;\s*rate=(\d+)/.exec(e.mimeType);if(t&&Number(t[1])!==Ie)throw new m(`realtimeInput.audio.mimeType declares rate=${t[1]} \u2014 the Live spec input format is ${Ie} Hz (audio/pcm;rate=${Ie})`);if(typeof e.data!="string"||e.data.length===0)throw new m("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(e.data,"base64");if(o.length===0||o.length%2!==0)throw new m(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let s=new Int16Array(o.length/2);for(let r=0;r<s.length;r++)s[r]=o.readInt16LE(r*2);let i=nn(s,Ie,_t);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function vt(n){if(n.mediaChunks!==void 0)throw new m('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(n.activityStart!==void 0||n.activityEnd!==void 0){if(Object.keys(n).length!==1||n.activityStart!==void 0&&n.activityEnd!==void 0)throw new m("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let s=n.activityStart!==void 0?"activityStart":"activityEnd",i=E(n[s]);if(!i||Object.keys(i).length!==0)throw new m(`realtimeInput.${s} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:s}}let e=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(n))if(!e.includes(o))throw new m(`unsupported realtimeInput field "${o}"`);let t=e.filter(o=>n[o]!==void 0);if(t.length!==1)throw new m(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${t.length})`);if(n.audio!==void 0)return{kind:"audio",base64Pcm24k:sn(n.audio)};if(n.video!==void 0)return{kind:"video",jpegFrame:on(n.video)};if(n.audioStreamEnd!==void 0){if(n.audioStreamEnd!==!0)throw new m("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof n.text!="string"||n.text.length===0)throw new m("realtimeInput.text must be a non-empty string");return{kind:"text",text:n.text}}function kt(n){for(let e of Object.keys(n))if(e!=="functionResponses")throw new m(`unsupported toolResponse field "${e}"`);if(!Array.isArray(n.functionResponses)||n.functionResponses.length===0)throw new m("toolResponse.functionResponses must be a non-empty array");return n.functionResponses.map(e=>{let t=E(e);if(!t||typeof t.id!="string"||t.id.length===0)throw new m("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:t.id,output:JSON.stringify(t.response??null)}})}function bt(n){return n.type!=="response.output_text.delta"||typeof n.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:n.delta}]}}}}function xt(n){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:tn,data:n}}]}}}}function Rt(n){let e=E(n)??{},t=Array.isArray(e.output)?e.output:[],o=[],s=[],i=typeof e.output_text=="string"?e.output_text:"";if(!i)for(let u of t){let c=E(u);if(!(c?.type!=="message"||!Array.isArray(c.content)))for(let l of c.content){let f=E(l);f?.type==="output_text"&&typeof f.text=="string"&&(i+=f.text)}}i&&s.push({role:"assistant",content:i});for(let u of t){let c=E(u);if(c?.type!=="function_call")continue;if(typeof c.call_id!="string"||typeof c.name!="string")throw new m(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,Z);let l=typeof c.arguments=="string"&&c.arguments.length>0?c.arguments:"{}",f;try{f=JSON.parse(l)}catch{throw new m(`upstream function_call arguments are not valid JSON: ${l}`,Z)}o.push({id:c.call_id,name:c.name,args:f}),s.push({type:"function_call",call_id:c.call_id,name:c.name,arguments:l})}let r=[];o.length>0&&r.push({toolCall:{functionCalls:o}}),r.push({serverContent:{generationComplete:!0}});let a=E(e.usage),d={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(d.usageMetadata=u)}return r.push(d),{messages:r,assistantItems:s}}var rn=256,pe=class{snapshots=new Map;store(e,t,o){for(this.snapshots.set(`${e}\0${t}`,o);this.snapshots.size>rn;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},an="local",we=n=>n.slice(0,120),Ce=class{constructor(e,t,o){this.ws=e;this.call=t;this.registry=o;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),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 V){this.ws.close(dt,we(e.message));return}if(e instanceof X){this.ws.close(Te,we(e.message));return}if(e instanceof m){this.ws.close(e.closeCode,we(e.message));return}this.ws.close(Z,we(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=lt(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new m(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:i}=yt(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=vt(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,o);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:wt);return}this.transcript.push(...kt(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new m("setup may only be sent once, as the first client message");let t=mt(e),o=t.sessionResumption.handle;if(o!==null){let i=this.registry.get(this.scope,o);if(!i)throw new m("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",Te);if(i.model!==t.model)throw new m(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new m("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(o)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new m(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Te);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let r=await i.call(this.clients,t.model),a=r.onOutputFrame(u=>this.send(ft(u))),d=r.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),d()},s[Q]=pt(r.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new m("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new m("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",Z);return this.audio=(async()=>{let o=await t.call(this.clients,e.model);return this.detachAudio=o.onOutputAudio(s=>this.send(xt(s))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new m("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new m("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Z);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new m(`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 m("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new m("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(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let o=(0,At.randomUUID)();this.registry.store(this.scope,o,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(o),this.send(ht(o))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(gt(e.timeLeftMs)),this.ws.close(Z,we(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let o=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,i=!1;for await(let d of o){if(t.interrupted)break;let u=d;if(u.type==="error")throw new m(`upstream error: ${JSON.stringify(u)}`,Z);if(u.type==="response.completed"){s=u.response,i=!0;continue}let c=bt(u);c&&this.send(c)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new m("upstream produced no response.completed event",Z);let{messages:r,assistantItems:a}=Rt(s);this.transcript.push(...a);for(let d of r)this.send(d);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},ie=class extends Error{constructor(t,o){super(o);this.status=t;this.name="UpgradeAuthError"}status};function un(n,e,t){let o=new Set;(d=>{if(typeof d=="string")d!==""&&o.add(d);else if(Array.isArray(d))for(let u of d)u!==""&&o.add(u)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&o.add(i.slice(7));let r=e.searchParams.get("key")??void 0;if(r!==void 0&&r!==""&&o.add(r),o.size>1)throw new ie(401,`contradictory credentials: ${o.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&r!==void 0&&r!=="")throw new ie(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let d of o)a=d;if(a===void 0&&t)throw new ie(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Pe(n,e){let t=e.authenticate!==void 0;if(t&&(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(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let o=new St.WebSocketServer({noServer:!0}),s=new pe;n.on("upgrade",(r,a,d)=>{let u=new URL(r.url??"/","http://localhost");u.pathname===Ee&&(a.on("error",()=>{}),(async()=>{let c=un(r,u,t),l;if(e.authenticate)l=await e.authenticate(c,r);else{if(e.apiKey!==void 0&&c!==e.apiKey)throw new ie(401,"invalid local proxy api key");l={clients:e.clients,scope:an}}o.handleUpgrade(r,a,d,f=>{new Ce(f,l,s)})})().catch(c=>{let l=502;(c instanceof ie||typeof c=="object"&&c!==null&&"status"in c&&typeof c.status=="number")&&(l=c.status);let f=l===401?"Unauthorized":l===403?"Forbidden":l===502?"Bad Gateway":"Internal Server Error",h=c instanceof Error?c.message:String(c);a.destroyed||(a.write(`HTTP/1.1 ${l} ${f}\r
1
+ "use strict";var xr=Object.create;var Ze=Object.defineProperty;var Sr=Object.getOwnPropertyDescriptor;var Er=Object.getOwnPropertyNames;var Ar=Object.getPrototypeOf,Ir=Object.prototype.hasOwnProperty;var Or=(t,e)=>{for(var n in e)Ze(t,n,{get:e[n],enumerable:!0})},Qt=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Er(e))!Ir.call(t,r)&&r!==n&&Ze(t,r,{get:()=>e[r],enumerable:!(o=Sr(e,r))||o.enumerable});return t};var At=(t,e,n)=>(n=t!=null?xr(Ar(t)):{},Qt(e||!t||!t.__esModule?Ze(n,"default",{value:t,enumerable:!0}):n,t)),Tr=t=>Qt(Ze({},"__esModule",{value:!0}),t);var js={};Or(js,{GEMINI_LIVE_PATH:()=>ot,OPENAI_REALTIME_PATH:()=>Be,OpenAIRealtimeConnection:()=>ve,ResumptionRegistry:()=>ke,SessionGoneError:()=>Q,UnknownModelError:()=>U,VIDEO_OUT_SETUP_KEY:()=>oe,attachGeminiLive:()=>at,attachOpenAIRealtime:()=>Fe,createOpenAIProxy:()=>Rr,fixedClientsResolver:()=>ht,realtimeBindingFor:()=>Ht,realtimeModelOf:()=>jt,serveGeminiLiveSocket:()=>vn});module.exports=Tr(js);var vr=require("http");var _n=require("crypto"),wn=require("ws");var U=class extends Error{},Q=class extends Error{};function It(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}}var et=require("@urun-sh/core");var Zt="urun.videoOut.v2-ws";var ot="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Mr=1007,tn=1008,se=1011,st=1008,w=class extends Error{constructor(n,o=Mr){super(n);this.closeCode=o}closeCode},D=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,tt=["setup","clientContent","realtimeInput","toolResponse"];function nn(t){let e;try{e=JSON.parse(t)}catch{throw new w("client message is not valid JSON")}let n=D(e);if(!n)throw new w("client message must be a JSON object");let o=tt.filter(a=>n[a]!==void 0),r=Object.keys(n).filter(a=>!tt.includes(a));if(r.length>0)throw new w(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${tt.join(", ")}`);if(o.length!==1)throw new w(`client message must contain exactly one of ${tt.join(", ")} (got ${o.length})`);let s=o[0],i=D(n[s]);if(!i)throw new w(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function rn(t,e){if(typeof t=="string")return t;let n=D(t),o=n?n.parts:void 0;if(!Array.isArray(o))throw new w(`${e}: expected a Content with a parts array`);let r=[];for(let s of o){let i=D(s);if(i&&typeof i.text=="string"){r.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new w(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new w(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new w(`${e}: unsupported part ${JSON.stringify(s)}`)}return r.join(`
2
+ `)}var Ur={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},oe="urun.videoOut";function on(t){return{framing:Zt,codec:t}}function sn(t){let{seq:e,ptsUs:n,codec:o,key:r}=t.header;return{[oe]:{v:1,seq:e,ptsUs:n,codec:o,key:r,data:Buffer.from(t.au).toString("base64")}}}var Lr={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Nr=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",oe],en=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Dr(t){let e=D(t);if(!e)throw new w("setup.realtimeInputConfig must be an object");for(let r of Object.keys(e))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new w(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let n=D(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new w("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(n??{}))if(r!=="disabled")throw new w(`automaticActivityDetection.${r} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new w("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let o="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!en.includes(e.activityHandling))throw new w(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${en.join(", ")}`);o=e.activityHandling}return{manualActivity:!0,activityHandling:o}}var Br=["temperature","maxOutputTokens","responseModalities"];function an(t){for(let[d,m]of Object.entries(Lr))if(t[d]!==void 0)throw new w(m);for(let d of Object.keys(t))if(!Nr.includes(d))throw new w(`unsupported setup field "${d}"`);if(typeof t.model!="string"||t.model.length===0)throw new w('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,o,r=!1,s=D(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new w("setup.generationConfig must be an object");if(s){for(let d of Object.keys(s))if(!Br.includes(d))throw new w(`unsupported generationConfig field "${d}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new w("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new w("generationConfig.maxOutputTokens must be a number");o=s.maxOutputTokens}if(s.responseModalities!==void 0){let d=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let m of d){let p=String(m).toUpperCase();if(p==="AUDIO"){r=!0;continue}if(p!=="TEXT")throw new w(`responseModalities ${JSON.stringify(m)} 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:rn(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new w("setup.tools must be an array");a=[];for(let d of t.tools){let m=D(d);if(!m)throw new w("setup.tools entries must be objects");for(let p of Object.keys(m))if(p!=="functionDeclarations")throw new w(`unsupported tool "${p}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(m.functionDeclarations))throw new w("tool.functionDeclarations must be an array");for(let p of m.functionDeclarations){let k=D(p);if(!k||typeof k.name!="string")throw new w("functionDeclarations entries require a string name");a.push({type:"function",name:k.name,description:k.description,parameters:k.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let d=D(t.sessionResumption);if(!d)throw new w("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let m of Object.keys(d))if(m!=="handle")throw new w(`unsupported sessionResumption field "${m}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(d.handle!==void 0&&(typeof d.handle!="string"||d.handle.length===0))throw new w("sessionResumption.handle must be a non-empty string when present");l={enabled:!0,handle:typeof d.handle=="string"?d.handle:null}}let u=t.realtimeInputConfig===void 0?Ur:Dr(t.realtimeInputConfig),c=!1;if(t[oe]!==void 0){if(!D(t[oe]))throw new w(`setup["${oe}"] must be an object (the v1 opt-in is {})`);c=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:o,audioModality:r,activity:u,sessionResumption:l,videoOut:c}}function un(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function dn(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function ln(t){for(let o of Object.keys(t))if(o!=="turns"&&o!=="turnComplete")throw new w(`unsupported clientContent field "${o}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new w("clientContent.turns must be an array");let n=[];for(let o of e){let r=D(o);if(!r)throw new w("clientContent.turns entries must be Content objects");let s=r.role===void 0?"user":String(r.role).toLowerCase();if(s!=="user"&&s!=="model")throw new w(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);n.push({role:s==="model"?"assistant":"user",content:rn(r,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var nt=16e3,cn=24e3,Fr=`audio/pcm;rate=${cn}`,pn=Buffer.alloc(960).toString("base64");function qr(t,e,n){if(e===n)return t;let o=Math.floor(t.length*n/e),r=new Int16Array(o),s=e/n,i=t.length-1;for(let a=0;a<o;a++){let l=a*s,u=Math.floor(l);if(u>=i){r[a]=t[i];continue}let c=l-u;r[a]=Math.round(t[u]+(t[u+1]-t[u])*c)}return r}function jr(t){let e=D(t);if(!e)throw new w("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new w(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new w("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new w("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Hr(t){let e=D(t);if(!e)throw new w("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new w(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==nt)throw new w(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${nt} Hz (audio/pcm;rate=${nt})`);if(typeof e.data!="string"||e.data.length===0)throw new w("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(e.data,"base64");if(o.length===0||o.length%2!==0)throw new w(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let r=new Int16Array(o.length/2);for(let i=0;i<r.length;i++)r[i]=o.readInt16LE(i*2);let s=qr(r,nt,cn);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function fn(t){if(t.mediaChunks!==void 0)throw new w('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new w("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let r=t.activityStart!==void 0?"activityStart":"activityEnd",s=D(t[r]);if(!s||Object.keys(s).length!==0)throw new w(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let e=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(t))if(!e.includes(o))throw new w(`unsupported realtimeInput field "${o}"`);let n=e.filter(o=>t[o]!==void 0);if(n.length!==1)throw new w(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Hr(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:jr(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new w("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new w("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function mn(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new w(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new w("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=D(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new w("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function gn(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function hn(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Fr,data:t}}]}}}}function yn(t){let e=D(t)??{},n=Array.isArray(e.output)?e.output:[],o=[],r=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let u of n){let c=D(u);if(!(c?.type!=="message"||!Array.isArray(c.content)))for(let d of c.content){let m=D(d);m?.type==="output_text"&&typeof m.text=="string"&&(s+=m.text)}}s&&r.push({role:"assistant",content:s});for(let u of n){let c=D(u);if(c?.type!=="function_call")continue;if(typeof c.call_id!="string"||typeof c.name!="string")throw new w(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,se);let d=typeof c.arguments=="string"&&c.arguments.length>0?c.arguments:"{}",m;try{m=JSON.parse(d)}catch{throw new w(`upstream function_call arguments are not valid JSON: ${d}`,se)}o.push({id:c.call_id,name:c.name,args:m}),r.push({type:"function_call",call_id:c.call_id,name:c.name,arguments:d})}let i=[];o.length>0&&i.push({toolCall:{functionCalls:o}}),i.push({serverContent:{generationComplete:!0}});let a=D(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:r}}var Vr=256,ke=class{snapshots=new Map;store(e,n,o){for(this.snapshots.set(`${e}\0${n}`,o);this.snapshots.size>Vr;){let r=this.snapshots.keys().next().value;this.snapshots.delete(r)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Gr="local",Ce=t=>t.slice(0,120),it=class{constructor(e,n,o){this.ws=e;this.call=n;this.registry=o;this.clients=n.clients,this.scope=n.scope,e.on("message",r=>this.onMessage(r)),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 U){this.ws.close(tn,Ce(e.message));return}if(e instanceof Q){this.ws.close(st,Ce(e.message));return}if(e instanceof w){this.ws.close(e.closeCode,Ce(e.message));return}this.ws.close(se,Ce(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=nn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(r=>this.fail(r));return}if(!this.config)throw new w(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(n.kind==="clientContent"){let{items:r,turnComplete:s}=ln(n.clientContent);this.transcript.push(...r),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let r=fn(n.realtimeInput);if(r.kind==="activityStart"||r.kind==="activityEnd"){this.onActivity(r.kind,o);return}if(r.kind==="text"){this.transcript.push({role:"user",content:r.text}),this.enqueue(()=>this.runTurn());return}if(r.kind==="video"){this.appendVideoFrame(r.jpegFrame);return}this.appendAudio(r.kind==="audio"?r.base64Pcm24k:pn);return}this.transcript.push(...mn(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new w("setup may only be sent once, as the first client message");let n=an(e),o=n.sessionResumption.handle;if(o!==null){let s=this.registry.get(this.scope,o);if(!s)throw new w("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",st);if(s.model!==n.model)throw new w(`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 w("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(o)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new w(`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`,st);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 r={};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(sn(u))),l=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),l()},r[oe]=on(i.codec)}}this.send({setupComplete:r}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new w("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new w("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",se);return this.audio=(async()=>{let o=await n.call(this.clients,e.model);return this.detachAudio=o.onOutputAudio(r=>this.send(hn(r))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new w("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new w("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",se);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new w(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new w("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new w("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let o=(0,_n.randomUUID)();this.registry.store(this.scope,o,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(o),this.send(un(o))}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,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(dn(e.timeLeftMs)),this.ws.close(se,Ce(`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 o=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),r,s=!1;for await(let l of o){if(n.interrupted)break;let u=l;if(u.type==="error")throw new w(`upstream error: ${JSON.stringify(u)}`,se);if(u.type==="response.completed"){r=u.response,s=!0;continue}let c=gn(u);c&&this.send(c)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new w("upstream produced no response.completed event",se);let{messages:i,assistantItems:a}=yn(r);this.transcript.push(...a);for(let l of i)this.send(l);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},me=class extends Error{constructor(n,o){super(o);this.status=n;this.name="UpgradeAuthError"}status};function Jr(t,e,n){let o=new Set;(l=>{if(typeof l=="string")l!==""&&o.add(l);else if(Array.isArray(l))for(let u of l)u!==""&&o.add(u)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&o.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&o.add(i),o.size>1)throw new me(401,`contradictory credentials: ${o.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 me(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 o)a=l;if(a===void 0&&n)throw new me(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function at(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 o=new wn.WebSocketServer({noServer:!0}),r=new ke;t.on("upgrade",(i,a,l)=>{let u=new URL(i.url??"/","http://localhost");u.pathname===ot&&(a.on("error",()=>{}),(async()=>{let c=Jr(i,u,n),d;if(e.authenticate)d=await e.authenticate(c,i);else{if(e.apiKey!==void 0&&c!==e.apiKey)throw new me(401,"invalid local proxy api key");d={clients:e.clients,scope:Gr}}o.handleUpgrade(i,a,l,m=>{new it(m,d,r)})})().catch(c=>{let d=502;(c instanceof me||typeof c=="object"&&c!==null&&"status"in c&&typeof c.status=="number")&&(d=c.status);let m=d===401?"Unauthorized":d===403?"Forbidden":d===502?"Bad Gateway":"Internal Server Error",p=c instanceof Error?c.message:String(c);a.destroyed||(a.write(`HTTP/1.1 ${d} ${m}\r
3
3
  Connection: close\r
4
4
  \r
5
- ${h}\r
6
- `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let r of o.clients)r.close(1001,"server closing");await new Promise((r,a)=>o.close(d=>d===void 0?r():a(d)))})(),i)}function Ot(n,e,t=new pe){new Ce(n,e,t)}var oe=require("ws");function me(n){return typeof n.model!="string"||!n.model.trim()?"(default)":n.model.trim().slice(0,128)}var re=class n{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,t,o){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=t,this.naiveInBytes+=o}modelEntry(e){let t=this.models[e];if(t)return t;let o=Object.keys(this.models).length>=256?"(other)":e;return this.models[o]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,t){let o=this,s=performance.now(),i=null,r=0;return(async function*(){for await(let d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift()),r+=1,o.tokensOut+=1,o.charsOut+=d.delta.length,t!==void 0&&(o.modelEntry(t).tokens_out+=1)),yield d;let a=(performance.now()-(i??s))/1e3;r>0&&a>0&&(o.tokRates.push(r/a),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let t=[...e].sort((o,s)=>o-s);return t[Math.floor(t.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((t,o)=>t+o,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:n.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:n.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}}}},dn=256;function ln(n){if(typeof n=="string")return[{role:"user",content:n}];if(Array.isArray(n))return n;throw new Error("responses input must be a string or an array of messages/items")}var ae=class extends Error{},fe=class{conversations=new Map;thread(e,t){let o=ln(t);if(e==null)return o;let s=this.conversations.get(String(e));if(!s)throw new ae(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...s,...o]}remember(e,t,o,s=!0){this.conversations.set(e,[...t,...o]);for(let i of this.conversations.keys()){if(this.conversations.size<=dn)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},It=new WeakMap;function ve(n){let e=It.get(n);return e||(e=new fe,It.set(n,e)),e}function he(n){let e=n?.output;return Array.isArray(e)?e.filter(t=>t.type==="function_call"):[]}function ne(n){return n.find(e=>e.type==="response.completed")?.response??null}function ge(n){return n.type!=="response.function_call_arguments.delta"||typeof n.tool_index!="number"?null:{tool_index:n.tool_index,call_id:typeof n.call_id=="string"?n.call_id:void 0,name:typeof n.name=="string"?n.name:void 0,delta:typeof n.delta=="string"?n.delta:""}}var te=class{calls=new Map;add(e){let t=this.calls.get(e.tool_index),o=!t;return t||(t={args:""},this.calls.set(e.tool_index,t)),e.call_id&&(t.id=e.call_id),e.name&&(t.name=e.name),t.args+=e.delta,{call:t,isNew:o}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,t])=>({type:"function_call",call_id:t.id??`call_${e}`,name:t.name??"",arguments:t.args}))}},cn=["<tool_call>","<function="];function pn(n){return cn.find(e=>n.includes(e))}function ue(n,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 "${n}" (see catalog parser_defaults)`}function de(n,e,t){if(!(!n||e>0))return pn(t)}function Je(n,e){let t=e?.output_text;return typeof t=="string"?t:n.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}function fn(n){let e=n?.output;if(!Array.isArray(e))return[];let t=[];for(let o of e){if(o===null||typeof o!="object")continue;let s=o;s.type==="message"?t.push({role:"assistant",content:s.content??""}):s.type==="function_call"&&t.push({type:"function_call",call_id:s.call_id,name:s.name,arguments:s.arguments})}return t}function We(n,e){let t=fn(n);return t.length>0?t:e?[{role:"assistant",content:e}]:[]}var H=class extends Error{constructor(t,o,s=400,i){super(t);this.code=o;this.status=s;this.param=i}code;status;param};function ye(n,e){try{return n.thread(e.previous_response_id,e.input)}catch(t){throw t instanceof ae?new H(t.message,"previous_response_not_found",400,"previous_response_id"):new H(String(t instanceof Error?t.message:t),"invalid_input")}}async function Ge(n,e,t,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new H("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return n.createResponse({model:e.model,input:t,stream:o,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}:{}})}async function ke(n){let{body:e,clients:t,store:o,stats:s}=n,i=ye(o,e);e.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let r=`resp_${Math.random().toString(36).slice(2,14)}`,a=n.remember??e.store!==!1,d=e.store!==!1,u=me(e);s.model(u);let c=Array.isArray(e.tools)&&e.tools.length>0,l=await Ge(t,e,i,!0);return{responseId:r,events:mn({events:l,conversation:i,responseId:r,modelKey:u,requestHadTools:c,remember:a,persist:d,store:o,stats:s})}}async function*mn(n){let{events:e,conversation:t,responseId:o,modelKey:s,requestHadTools:i,remember:r,persist:a,store:d,stats:u}=n,c=[],l=b=>b.response&&typeof b.response=="object"?{...b,response:{...b.response,id:o}}:b,f=`item_${o.slice(5)}`,h=`rs_${o.slice(5)}`,w=!1,v=!1,y=0;function*x(){w||(w=!0,yield{type:"response.created",response:{id:o,object:"response",status:"in_progress"}})}let R=!1,U=0,T="";function*N(){R&&(R=!1,yield{type:"response.reasoning_text.done",item_id:h,output_index:U,content_index:0,text:T},yield{type:"response.output_item.done",output_index:U,item:{id:h,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:T}],status:"completed"}})}let p=!1,k=0,L="";function*I(b){p&&(p=!1,yield{type:"response.output_text.done",item_id:f,output_index:k,content_index:0,text:L},yield{type:"response.content_part.done",item_id:f,output_index:k,content_index:0,part:{type:"output_text",text:L}},yield{type:"response.output_item.done",output_index:k,item:{id:f,type:"message",role:"assistant",status:b,content:[{type:"output_text",text:L}]}})}let D=new te,C=null,G=-1;function*$(b){if(!C)return;let S=C;C=null,yield{type:"response.function_call_arguments.done",item_id:S.fcId,output_index:S.outputIndex,arguments:S.args},yield{type:"response.output_item.done",output_index:S.outputIndex,item:{id:S.fcId,type:"function_call",call_id:S.callId??S.fcId,name:S.name??"",arguments:S.args,status:b}}}let B=!1;for await(let b of u.track(e,s)){c.push(b);let S=String(b.type??"");if(S==="response.created"||S==="response.in_progress"){w=!0,yield l(b);continue}if(S==="response.output_item.added"){v=!0,yield l(b);continue}if(S==="response.reasoning_text.delta"&&!v){yield*x(),R||(R=!0,U=y++,yield{type:"response.output_item.added",output_index:U,item:{id:h,type:"reasoning",summary:[],content:[],status:"in_progress"}}),T+=String(b.delta??""),yield{type:"response.reasoning_text.delta",item_id:h,output_index:U,content_index:0,delta:b.delta};continue}if(S==="response.output_text.delta"&&!v){yield*x(),yield*N(),p||(p=!0,k=y++,yield{type:"response.output_item.added",output_index:k,item:{id:f,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:f,output_index:k,content_index:0,part:{type:"output_text",text:""}}),L+=String(b.delta??""),yield{type:S,item_id:f,output_index:k,content_index:0,delta:b.delta};continue}let P=v?null:ge(b);if(P){if(yield*x(),yield*N(),yield*I("completed"),D.add(P),P.tool_index!==G){yield*$("completed"),G=P.tool_index;let Y=y++;C={fcId:`fc_${o.slice(5)}_${P.tool_index}`,outputIndex:Y,callId:P.call_id,name:P.name,args:""},yield{type:"response.output_item.added",output_index:Y,item:{id:C.fcId,type:"function_call",call_id:C.callId??C.fcId,name:C.name??"",arguments:"",status:"in_progress"}}}C&&(P.call_id&&(C.callId=P.call_id),P.name&&(C.name=P.name),C.args+=P.delta,yield{type:"response.function_call_arguments.delta",item_id:C.fcId,output_index:C.outputIndex,delta:P.delta});continue}if(S==="response.completed"&&!v){let Y=he(b.response),Ae=de(i,D.size+Y.length,L);if(Ae){B=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ue(s,Ae)}};break}if(yield*N(),yield*I("completed"),yield*$("completed"),D.size===0)for(let ee of Y){let z=y++,ce=ee.id??ee.call_id??`fc_${z}`,se=ee.arguments??"",O={id:ce,type:"function_call",call_id:ee.call_id??ce,name:ee.name??""};yield{type:"response.output_item.added",output_index:z,item:{...O,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:ce,output_index:z,delta:se},yield{type:"response.function_call_arguments.done",item_id:ce,output_index:z,arguments:se},yield{type:"response.output_item.done",output_index:z,item:{...O,arguments:se,status:"completed"}}}yield l(b);continue}yield l(b)}if(yield*N(),yield*I("incomplete"),yield*$("incomplete"),r&&!B){let b=ne(c);d.remember(o,t,We(b,Je(c,b)),a)}}var hn="/v1/responses",gn=64*1024*1024,yn=8*1024*1024,_n=16,Et=32,Tt=3600*1e3,wn=/^[A-Za-z0-9._-]{1,256}$/;function j(n,e,t){return{type:"error",status:n,...t!==void 0?{stream_id:t}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var vn=j(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 Ye(){let n,e;return{promise:new Promise((o,s)=>{n=o,e=s}),resolve:n,reject:e}}async function kn(n){for(;n.bufferedAmount>yn&&n.readyState===oe.WebSocket.OPEN;){let{promise:e,resolve:t}=Ye();setTimeout(t,5),await e}}var ze=class extends fe{constructor(t){super();this.shared=t}shared;thread(t,o){if(t==null)return super.thread(t,o);try{return super.thread(t,o)}catch(s){if(!(s instanceof ae))throw s;return this.shared.thread(t,o)}}remember(t,o,s,i=!0){i?this.shared.remember(t,o,s):super.remember(t,o,s)}forget(t){super.forget(t),this.shared.forget(t)}},Ke=class{constructor(e,t,o,s){this.ws=e;this.clients=t;this.stats=o;this.statusOf=s;this.store=new ze(ve(t)),e.on("message",(r,a)=>this.onMessage(r,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(j(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Tt/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Tt).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,t){if(this.closed)return;if(t){this.sendFrame(j(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 o;try{o=JSON.parse(e.toString())}catch{this.sendFrame(j(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(o===null||typeof o!="object"||Array.isArray(o)){this.sendFrame(j(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let s=o;if(s.type!=="response.create"){this.sendFrame(j(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(s.type??null)}; only "response.create" is supported`}));return}if("stream"in s){this.sendFrame(j(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 s){this.sendFrame(j(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(s.stream_id!==void 0){if(typeof s.stream_id!="string"||!wn.test(s.stream_id)){this.sendFrame(vn);return}if(i=s.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=Et){this.sendFrame(j(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Et}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let r=s.generate===!1?()=>this.runWarmup(s,i):()=>this.runTurn(s,i),a=i??"",d=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,d.then(r).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,t){if(!this.closed){await this.acquire();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await ke({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0})}catch(r){this.failTurn(r,t,e);return}this.laneOfResponse.set(s.responseId,t??null);let i=s.events;this.activeTurns.add(i);try{for await(let r of i){if(this.closed||this.ws.readyState!==oe.WebSocket.OPEN)break;this.send(r,t),await kn(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,t,e)}finally{this.release()}}}runWarmup(e,t){if(this.closed)return;let o=`resp_${Math.random().toString(36).slice(2,14)}`;try{let s=ye(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,t??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},t)}catch(s){this.failTurn(s,t,e)}}failTurn(e,t,o){this.sendFrame(this.errorFrameOf(e,t));let s=o.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(t??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,t){let o=String(e instanceof Error?e.message:e);if(e instanceof H)return j(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},t);if(e instanceof V)return j(404,{type:"invalid_request_error",code:"model_not_found",message:o},t);if(e instanceof X)return j(503,{type:"upstream_error",code:"session_gone",message:o},t);let s=this.statusOf?.(e)??null;return s?j(s.status,{type:s.openaiType,message:o},t):j(500,{type:"upstream_error",message:o},t)}async acquire(){for(;this.active>=_n;){let{promise:e,resolve:t}=Ye();this.waiters.push(t),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,t){if(this.closed||this.ws.readyState!==oe.WebSocket.OPEN)return;let o=t===void 0?e:{...e,stream_id:t};this.ws.send(JSON.stringify(o))}sendFrame(e){this.closed||this.ws.readyState!==oe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Me(n,e,t){let o=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",s=`${t}\r
7
- `;n.end(`HTTP/1.1 ${e} ${o}\r
5
+ ${p}\r
6
+ `),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of o.clients)i.close(1001,"server closing");await new Promise((i,a)=>o.close(l=>l===void 0?i():a(l)))})(),s)}function vn(t,e,n=new ke){new it(t,e,n)}var le=require("ws");var bn=require("crypto"),kn="Inference-Id";function $e(){return(0,bn.randomUUID)()}function Ot(t){return t==="/v1"||t.startsWith("/v1/")}function Rn(t,e){if(!Ot(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 Me(t){return`resp_${t}`}function xn(t){return`chatcmpl-${t}`}function Sn(t){return`msg_${t}`}function Z(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function En(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,catalog:t.turn.catalog}}function An(t){return`${JSON.stringify(t)}
7
+ `}var Wr=256,Kr=128;function X(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Kr)}var ge=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,o){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=o}modelEntry(e){let n=this.models[e];if(n)return n;let o=Object.keys(this.models).length>=Wr?"(other)":e;return this.models[o]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,o){let r=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(),r.ttftMs.push(i-s),r.ttftMs.length>512&&r.ttftMs.shift(),o!==void 0&&(o.ttftMs=i-o.startedAt)),a+=1,r.tokensOut+=1,r.charsOut+=u.delta.length,n!==void 0&&(r.modelEntry(n).tokens_out+=1)),yield u;let l=(performance.now()-(i??s))/1e3;a>0&&l>0&&(r.tokRates.push(a/l),r.tokRates.length>512&&r.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((o,r)=>o-r);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,o)=>n+o,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}}}},zr=256;function Yr(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 he=class extends Error{},Re=class{conversations=new Map;thread(e,n){let o=Yr(n);if(e==null)return o;let r=this.conversations.get(String(e));if(!r)throw new he(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...r,...o]}remember(e,n,o,r=!0){this.conversations.set(e,[...n,...o]);for(let s of this.conversations.keys()){if(this.conversations.size<=zr)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},In=new WeakMap;function Ue(t){let e=In.get(t);return e||(e=new Re,In.set(t,e)),e}function xe(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function ee(t){return t.find(e=>e.type==="response.completed")?.response??null}function Se(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),o=!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:o}}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}))}},Xr=["<tool_call>","<function="];function Qr(t){return Xr.find(e=>t.includes(e))}function ye(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 _e(t,e,n){if(!(!t||e>0))return Qr(n)}function ut(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}function Zr(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let o of e){if(o===null||typeof o!="object")continue;let r=o;r.type==="message"?n.push({role:"assistant",content:r.content??""}):r.type==="function_call"&&n.push({type:"function_call",call_id:r.call_id,name:r.name,arguments:r.arguments})}return n}function Tt(t,e){let n=Zr(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var Y=class extends Error{constructor(n,o,r=400,s){super(n);this.code=o;this.status=r;this.param=s}code;status;param};function Ee(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof he?new Y(n.message,"previous_response_not_found",400,"previous_response_id"):new Y(String(n instanceof Error?n.message:n),"invalid_input")}}function On(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Pt(t,e,n,o,r){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new Y("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:o,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}:{},...On(e)!==void 0?{response_format:On(e)}:{}},r)}async function Le(t){let{body:e,clients:n,store:o,stats:r}=t,s=Ee(o,e);e.previous_response_id!=null&&(r.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=X(e);r.model(u);let c=Array.isArray(e.tools)&&e.tools.length>0,d=t.turn,m=await Pt(n,e,s,!0,d?Z(d):void 0);return{responseId:i,events:eo({events:m,conversation:s,responseId:i,modelKey:u,requestHadTools:c,remember:a,persist:l,store:o,stats:r,turn:t.turn})}}async function*eo(t){let{events:e,conversation:n,responseId:o,modelKey:r,requestHadTools:s,remember:i,persist:a,store:l,stats:u}=t,c=[],d=T=>T.response&&typeof T.response=="object"?{...T,response:{...T.response,id:o}}:T,m=`item_${o.slice(5)}`,p=`rs_${o.slice(5)}`,k=!1,O=!1,y=0;function*v(){k||(k=!0,yield{type:"response.created",response:{id:o,object:"response",status:"in_progress"}})}let _=!1,h=0,S="";function*g(){_&&(_=!1,yield{type:"response.reasoning_text.done",item_id:p,output_index:h,content_index:0,text:S},yield{type:"response.output_item.done",output_index:h,item:{id:p,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:S}],status:"completed"}})}let b=!1,f=0,R="";function*I(T){b&&(b=!1,yield{type:"response.output_text.done",item_id:m,output_index:f,content_index:0,text:R},yield{type:"response.content_part.done",item_id:m,output_index:f,content_index:0,part:{type:"output_text",text:R}},yield{type:"response.output_item.done",output_index:f,item:{id:m,type:"message",role:"assistant",status:T,content:[{type:"output_text",text:R}]}})}let $=new de,A=null,G=-1;function*J(T){if(!A)return;let N=A;A=null,yield{type:"response.function_call_arguments.done",item_id:N.fcId,output_index:N.outputIndex,arguments:N.args},yield{type:"response.output_item.done",output_index:N.outputIndex,item:{id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:N.args,status:T}}}let V=!1;for await(let T of u.track(e,r,t.turn)){c.push(T);let N=String(T.type??"");if(N==="response.created"||N==="response.in_progress"){k=!0,yield d(T);continue}if(N==="response.output_item.added"){O=!0,yield d(T);continue}if(N==="response.reasoning_text.delta"&&!O){yield*v(),_||(_=!0,h=y++,yield{type:"response.output_item.added",output_index:h,item:{id:p,type:"reasoning",summary:[],content:[],status:"in_progress"}}),S+=String(T.delta??""),yield{type:"response.reasoning_text.delta",item_id:p,output_index:h,content_index:0,delta:T.delta};continue}if(N==="response.output_text.delta"&&!O){yield*v(),yield*g(),b||(b=!0,f=y++,yield{type:"response.output_item.added",output_index:f,item:{id:m,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:m,output_index:f,content_index:0,part:{type:"output_text",text:""}}),R+=String(T.delta??""),yield{type:N,item_id:m,output_index:f,content_index:0,delta:T.delta};continue}let q=O?null:Se(T);if(q){if(yield*v(),yield*g(),yield*I("completed"),$.add(q),q.tool_index!==G){yield*J("completed"),G=q.tool_index;let z=y++;A={fcId:`fc_${o.slice(5)}_${q.tool_index}`,outputIndex:z,callId:q.call_id,name:q.name,args:""},yield{type:"response.output_item.added",output_index:z,item:{id:A.fcId,type:"function_call",call_id:A.callId??A.fcId,name:A.name??"",arguments:"",status:"in_progress"}}}A&&(q.call_id&&(A.callId=q.call_id),q.name&&(A.name=q.name),A.args+=q.delta,yield{type:"response.function_call_arguments.delta",item_id:A.fcId,output_index:A.outputIndex,delta:q.delta});continue}if(N==="response.completed"&&!O){let z=xe(T.response),pe=_e(s,$.size+z.length,R);if(pe){V=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ye(r,pe)}};break}if(yield*g(),yield*I("completed"),yield*J("completed"),$.size===0)for(let fe of z){let ue=y++,re=fe.id??fe.call_id??`fc_${ue}`,Pe=fe.arguments??"",be={id:re,type:"function_call",call_id:fe.call_id??re,name:fe.name??""};yield{type:"response.output_item.added",output_index:ue,item:{...be,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:re,output_index:ue,delta:Pe},yield{type:"response.function_call_arguments.done",item_id:re,output_index:ue,arguments:Pe},yield{type:"response.output_item.done",output_index:ue,item:{...be,arguments:Pe,status:"completed"}}}yield d(T);continue}yield d(T)}if(yield*g(),yield*I("incomplete"),yield*J("incomplete"),i&&!V){let T=ee(c);l.remember(o,n,Tt(T,ut(c,T)),a)}}var to="/v1/responses",no=64*1024*1024,ro=8*1024*1024,oo=16,Tn=32,Pn=3600*1e3,so=/^[A-Za-z0-9._-]{1,256}$/;function W(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var io=W(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 Mt(){let t,e;return{promise:new Promise((o,r)=>{t=o,e=r}),resolve:t,reject:e}}async function ao(t){for(;t.bufferedAmount>ro&&t.readyState===le.WebSocket.OPEN;){let{promise:e,resolve:n}=Mt();setTimeout(n,5),await e}}var Ct=class extends Re{constructor(n){super();this.shared=n}shared;thread(n,o){if(n==null)return super.thread(n,o);try{return super.thread(n,o)}catch(r){if(!(r instanceof he))throw r;return this.shared.thread(n,o)}}remember(n,o,r,s=!0){s?this.shared.remember(n,o,r):super.remember(n,o,r)}forget(n){super.forget(n),this.shared.forget(n)}},$t=class{constructor(e,n,o,r){this.ws=e;this.clients=n;this.stats=o;this.statusOf=r;this.store=new Ct(Ue(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(W(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Pn/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Pn).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(W(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 o;try{o=JSON.parse(e.toString())}catch{this.sendFrame(W(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(o===null||typeof o!="object"||Array.isArray(o)){this.sendFrame(W(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let r=o;if(r.type!=="response.create"){this.sendFrame(W(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(r.type??null)}; only "response.create" is supported`}));return}if("stream"in r){this.sendFrame(W(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 r){this.sendFrame(W(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(r.stream_id!==void 0){if(typeof r.stream_id!="string"||!so.test(r.stream_id)){this.sendFrame(io);return}if(s=r.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Tn){this.sendFrame(W(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Tn}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=r.generate===!1?()=>this.runWarmup(r,s):()=>this.runTurn(r,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 o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let r;try{r=await Le({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Me($e())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(r.responseId,n??null);let s=r.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==le.WebSocket.OPEN)break;this.send(i,n),await ao(this.ws)}}finally{this.activeTurns.delete(s)}}catch(o){this.failTurn(o,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let o=Me($e());try{let r=Ee(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,r,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(r){this.failTurn(r,n,e)}}failTurn(e,n,o){this.sendFrame(this.errorFrameOf(e,n));let r=o.previous_response_id;typeof r=="string"&&this.laneOfResponse.get(r)===(n??null)&&(this.store.forget(r),this.laneOfResponse.delete(r))}errorFrameOf(e,n){let o=String(e instanceof Error?e.message:e);if(e instanceof Y)return W(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof U)return W(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof Q)return W(503,{type:"upstream_error",code:"session_gone",message:o},n);let r=this.statusOf?.(e)??null;return r?W(r.status,{type:r.openaiType,message:o},n):W(500,{type:"upstream_error",message:o},n)}async acquire(){for(;this.active>=oo;){let{promise:e,resolve:n}=Mt();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!==le.WebSocket.OPEN)return;let o=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(o))}sendFrame(e){this.closed||this.ws.readyState!==le.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function dt(t,e,n){let o=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",r=`${n}\r
8
+ `;t.end(`HTTP/1.1 ${e} ${o}\r
8
9
  Connection: close\r
9
10
  Content-Type: text/plain; charset=utf-8\r
10
- Content-Length: ${Buffer.byteLength(s)}\r
11
+ Content-Length: ${Buffer.byteLength(r)}\r
11
12
  \r
12
- ${s}`)}function Ct(n,e){let t=new oe.WebSocketServer({noServer:!0,maxPayload:gn}),o=new re,s=new Set,i=new Set,r=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,d=!1,u=(c,l,f)=>{let h;try{h=new URL(c.url??"/","http://localhost")}catch{Me(l,400,"malformed upgrade URL");return}if(l.on("error",()=>l.destroy()),l.on("close",()=>r.delete(l)),h.pathname!==hn){r.add(l);return}i.add(l);let w=!1;(async()=>{if(e.apiKey&&(c.headers.authorization??"")!==`Bearer ${e.apiKey}`){Me(l,401,"invalid local proxy api key");return}let v;try{v=await a(c)}catch(y){let x=e.statusOf?.(y)??null;Me(l,x?.status??500,"upstream resolver rejected the connection");return}d||l.destroyed||(w=!0,t.handleUpgrade(c,l,f,y=>{i.delete(l),s.add(y),y.on("close",()=>s.delete(y));try{new Ke(y,v,o,e.statusOf)}catch{s.delete(y),y.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!w&&!l.destroyed&&Me(l,500,"responses websocket upgrade failed")}).finally(()=>i.delete(l))};return n.on("upgrade",u),{stats:o,close:()=>{let{promise:c,resolve:l}=Ye();if(d)return l(),c;d=!0,n.off("upgrade",u);for(let h of i)h.destroy();i.clear();for(let h of r)h.destroy();r.clear();for(let h of s)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of s)h.readyState!==oe.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),t.close(()=>{clearTimeout(f),l()}),c}}}function Ze(n){n.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function W(n,e,t){n.writeHead(e,{"content-type":"application/json"}),n.end(JSON.stringify(t))}function J(n,e,t,o="invalid_request_error"){W(n,e,{error:{message:t,type:o}})}function K(n,e,t,o){W(n,e,{type:"error",error:{type:t,message:o}})}function Le(n,e,t){if(e==="anthropic"){W(n,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}W(n,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var Pt=64*1024*1024,$e=class extends Error{};async function bn(n){let e=[],t=0;for await(let s of n){if(t+=s.length,t>Pt)throw new $e(`request body exceeds ${Pt} bytes`);e.push(s)}let o=Buffer.concat(e).toString("utf8");return o?JSON.parse(o):{}}function _e(n,e,t,o){return{id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:t,finish_reason:o}]}}function Ne(n){let e=n?.usage;if(!e||typeof e!="object")return null;let t=r=>typeof r=="number"&&Number.isFinite(r)&&r>=0?r:0,o=t(e.input_tokens),s=t(e.output_tokens);if(o===0&&s===0)return null;let i=t(e.total_tokens)||o+s;return{input_tokens:o,output_tokens:s,total_tokens:i}}function Mt(n){let e=Ne(n);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 $t(n){let e=n?.output;if(!Array.isArray(e))return"";let t="";for(let o of e)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let s of o.content)s.type==="reasoning_text"&&(t+=String(s.text??""));return t}function xn(n){if(Array.isArray(n))return n.map(e=>{let t=e.function;return!t||typeof t!="object"?e:{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}})}var Ue=class extends Error{};function Rn(n,e){return Array.isArray(e)?e.map(t=>{let o=t;if(o.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:o.text};if(o.type==="image_url"){let s=o.image_url??{};return{type:"input_image",image_url:s.url,detail:s.detail}}throw new Ue(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function An(n){let e=[];for(let t of n){if(t.role==="tool"){e.push({type:"function_call_output",call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:JSON.stringify(t.content??"")});continue}if(t.role==="assistant"&&Array.isArray(t.tool_calls)){typeof t.content=="string"&&t.content&&e.push({role:"assistant",content:t.content});for(let o of t.tool_calls){let s=o.function??{};e.push({type:"function_call",call_id:o.id,name:s.name,arguments:s.arguments})}continue}e.push({...t,content:Rn(t.role,t.content)})}return e}function Xe(n){return he(n).map((e,t)=>({index:t,id:e.call_id??e.id??`call_${t}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function Sn(n,e,t,o,s){if(n.stream===!0){let y;try{y=await ke({body:n,clients:e,store:t,stats:s})}catch(x){if(x instanceof V){Le(o,"openai",x);return}if(x instanceof H){J(o,x.status,x.message);return}throw x}Ze(o);for await(let x of y.events)o.write(`event: ${String(x.type??"message")}
13
- data: ${JSON.stringify(x)}
13
+ ${r}`)}function Cn(t,e){let n=new le.WebSocketServer({noServer:!0,maxPayload:no}),o=new ge,r=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(c,d,m)=>{let p;try{p=new URL(c.url??"/","http://localhost")}catch{dt(d,400,"malformed upgrade URL");return}if(d.on("error",()=>d.destroy()),d.on("close",()=>i.delete(d)),p.pathname!==to){i.add(d);return}s.add(d);let k=!1;(async()=>{if(e.apiKey&&(c.headers.authorization??"")!==`Bearer ${e.apiKey}`){dt(d,401,"invalid local proxy api key");return}let O;try{O=await a(c)}catch(y){let v=e.statusOf?.(y)??null;dt(d,v?.status??500,"upstream resolver rejected the connection");return}l||d.destroyed||(k=!0,n.handleUpgrade(c,d,m,y=>{s.delete(d),r.add(y),y.on("close",()=>r.delete(y));try{new $t(y,O,o,e.statusOf)}catch{r.delete(y),y.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!k&&!d.destroyed&&dt(d,500,"responses websocket upgrade failed")}).finally(()=>s.delete(d))};return t.on("upgrade",u),{stats:o,close:()=>{let{promise:c,resolve:d}=Mt();if(l)return d(),c;l=!0,t.off("upgrade",u);for(let p of s)p.destroy();s.clear();for(let p of i)p.destroy();i.clear();for(let p of r)p.close(1001,"server shutting down");let m=setTimeout(()=>{for(let p of r)p.readyState!==le.WebSocket.CLOSED&&p.terminate()},2e3);return m.unref?.(),n.close(()=>{clearTimeout(m),d()}),c}}}var Dn=require("@urun-sh/core");var $n=require("@urun-sh/core"),uo={no_capacity:429,queue_timeout:429,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},lo={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"admission is momentarily contended (lock convoy) \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session"};function Ut(t,e){let n=lo[t.code];return e?`${n} (${e})`:n}function lt(t){if(t==null)return null;let e=uo[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:e===429?"capacity_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function ct(t){if(t.kind==="create-failed")return lt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=$n.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return lt(e?"cold_start_exceeded":"queue_timeout")}var co=At(require("os"),1),po=At(require("path"),1),fo=require("url"),mo=require("util");var go=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function ho(t){let e=t?.code;return typeof e=="string"&&go.has(e)}function we(t,e){try{return t.write(e),!0}catch(n){if(ho(n))return!1;throw n}}var Bn=require("ws");var Un=require("crypto");function x(t){return`${t}_${(0,Un.randomUUID)().replace(/-/g,"").slice(0,24)}`}var pt=4*1024*1024,Lt=8*1024*1024,ft=512,mt=20*1024*1024;function F(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function De(t,e){return{type:"server_error",code:t,message:e}}function L(t){return{type:"error",event_id:x("event"),error:t}}function Nt(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var E=class extends Error{constructor(n,o,r="invalid_value"){super(n);this.param=o;this.code=r;this.name="SessionUpdateError"}param;code},yo={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},_o={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},wo={format:!0,voice:!0,speed:!0};function Mn(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new E(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function Ne(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new E("session must be an object","session","invalid_request");let o=t,r=Object.keys(o).filter(i=>!(i in yo));if(r.length>0)throw new E(`session field(s) not supported by this backend: ${r.join(", ")}`,r[0],"unsupported_field");let s={...e,outputModalities:[...e.outputModalities]};for(let[i,a]of Object.entries(o))switch(i){case"model":if(a!==null&&typeof a!="string")throw new E("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new E("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 E("modalities must be a non-empty array","modalities");let l=[];for(let u of a){if(u!=="text"&&u!=="audio")throw new E(`modality ${JSON.stringify(u)} is not "text" or "audio"`,"modalities");if(u==="audio"&&!n.voice)throw new E('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 E("voice must be a string or null","voice");if(!n.voice)throw new E("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 E(`${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 E("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 E(`${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 E("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 E("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 E("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 E("turn_detection must be an object or null","turn_detection");let u=String(l.type??"");if(u!=="server_vad"&&u!=="semantic_vad")throw new E(`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 E("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 E("input_audio_transcription must be an object or null","input_audio_transcription");for(let l of Object.keys(a))if(!["model","language","languages","prompt"].includes(l))throw new E(`input_audio_transcription field not honored by this backend: ${l} (transcription comes from the voice engine itself)`,`input_audio_transcription.${l}`,"unsupported_field");s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new E("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 E("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 E("audio.input must be an object","audio.input");for(let c of Object.keys(u))if(!(c in _o))throw new E(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(u.format!==void 0&&Mn(u.format,"audio.input.format"),u.transcription!==null&&u.transcription!==void 0){let c=Ne({input_audio_transcription:u.transcription},s,n);s.inputAudioTranscription=c.inputAudioTranscription}if(u.turn_detection!==null&&u.turn_detection!==void 0){let c=Ne({turn_detection:u.turn_detection},s,n);s.turnDetection=c.turnDetection}if(u.noise_reduction!==null&&u.noise_reduction!==void 0)throw new E("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 E("audio.output must be an object","audio.output");for(let c of Object.keys(u))if(!(c in wo))throw new E(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(u.format!==void 0&&Mn(u.format,"audio.output.format"),u.speed!==void 0)throw new E("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 E("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new E("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 gt(t,e){return{id:e,object:"realtime.session",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Dt(t,e){let n=t;if(!n||typeof n!="object")throw new E("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 E("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:x("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let o=n.role;if(o!=="user"&&o!=="assistant"&&o!=="system")throw new E('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new E("message item content must be an array","item.content","invalid_request");let r=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new E("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||o==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new E(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");r.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new E("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 E("input_audio part requires base64 audio","item.content.audio","invalid_request");r.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new E(`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:x("item"),type:"message",role:o,content:r}}throw new E(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Bt(t){let e=[],n=!1;for(let o of t){if(o.type==="function_call"){e.push({type:"function_call",call_id:o.callId,name:o.name,arguments:o.arguments??"{}"});continue}if(o.type==="function_call_output"){e.push({type:"function_call_output",call_id:o.callId,output:o.output});continue}let r=[];for(let s of o.content??[]){if(s.type==="input_text"||s.type==="output_text"){r.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){r.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:o.role,content:r})}return{input:e,sawAudioOnlyItem:n}}var vo=1001,bo=1011,Ln=t=>t.slice(0,120),ko=/^[A-Za-z0-9+/=]*$/,Ro=2;function xo(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Ro)return!1;return!0}var ve=class{id=x("conn");ws;binding;onClosed;config=Nt();sessionId=x("sess");conversationId=x("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnTranscript={open:!1,text:""};lastCommittedTranscript=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:x("event"),session:gt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:x("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns;(async()=>{try{for await(let o of n()){if(this.closed||e.signal.aborted)return;this.onTurnEvent(o)}}catch(o){!this.closed&&!e.signal.aborted&&this.send(L(De("turn_lane_fault",`the backend turn/transcript lane failed: ${o instanceof Error?o.message:String(o)}`)))}})()}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"";if(n.length===0)return;this.turnTranscript.open=!0,this.turnTranscript.text+=n,this.config.inputAudioTranscription&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:x("event"),item_id:"input_audio_turn",content_index:0,delta:n});return}case"turn_start":{this.turnTranscript={open:!0,text:this.turnTranscript.text},this.send({type:"input_audio_buffer.speech_started",event_id:x("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.turnTranscript.text.trim(),o=n.length>0?n:null;this.turnTranscript={open:!1,text:""},this.lastCommittedTranscript=o,this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let r=x("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...o!==null?{transcript:o}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:x("event"),previous_item_id:s,item_id:r}),this.send({type:"conversation.item.created",event_id:x("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:x("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.inputAudioTranscription&&o!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:x("event"),item_id:r,content_index:0,transcript:o}),this.config.turnDetection?.createResponse&&!this.inFlight&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(F("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>pt){this.fail(F("frame_too_large",`frame exceeds the ${pt}-byte limit`),"invalid_frame");return}let o;try{o=JSON.parse(n)}catch{this.fail(F("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof o.type!="string"||o.type.length===0){this.fail(F("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(o)}catch(r){let s=r;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(L({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(De(null,r instanceof Error?r.message:String(r)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=Ne(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0}),this.send({type:"session.updated",event_id:x("event"),session:gt(this.config,this.sessionId)});return;case"conversation.item.create":{let n=Dt(e.item,this.binding.voice),o=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:x("event"),previous_item_id:o,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(o=>o.id===e.item_id);if(n<0){this.send(L(F("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:x("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(o=>o.id===e.item_id);if(!n){this.send(L(F("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:x("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(o=>o.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(L(F("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:x("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(L(F("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ko.test(e.audio)){this.send(L(F("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioBytes.length+n>mt){this.send(L(F("buffer_full",`uncommitted input audio exceeds the ${mt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.send({type:"input_audio_buffer.cleared",event_id:x("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(L(F("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let o=x("item"),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:x("event"),previous_item_id:r,item_id:o}),this.send({type:"conversation.item.created",event_id:x("event"),previous_item_id:r,item:this.itemToProtocol(this.items[this.items.length-1])});return}case"output_audio_buffer.clear":{this.send(L(F("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(L(F("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(L(F("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(L({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 o=this.binding.session;if(o&&typeof o.sendResponseCreate=="function"){let s=e.response??e;return o.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let r=this.binding.clients;if(r&&typeof r.createResponse=="function"){let{response:s,input:i,...a}=e;return await r.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(L(F("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(O=>O!=="text"&&O!=="audio")){this.send(L(F("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(L(F("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 o=x("req"),r=`resp_${o}`;this.activeResponseId=r;let s=this.items.length,{input:i,sawAudioOnlyItem:a}=Bt(this.items),l=typeof n.instructions=="string"?n.instructions:this.config.instructions,u=typeof n.temperature=="number"?n.temperature:this.config.temperature,c=n.max_output_tokens??this.config.maxOutputTokens,d=c==="inf"||c===void 0?void 0:c,m=n.tools!==void 0?n.tools:this.config.tools,p=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,k={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...l!==void 0?{instructions:l}:{},...u!==void 0?{temperature:u}:{},...d!==void 0?{max_output_tokens:d}:{},...m!==void 0?{tools:m}:{},...p!==void 0?{tool_choice:p}:{}};for(let O of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(O);this.inFlight=(async()=>{let O=[],y=S=>{this.responseFlushed?this.send(S):O.push(S)},v=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:x("event"),response:this.responseObject(r,"in_progress")}),this.send({type:"response.in_progress",event_id:x("event"),response:this.responseObject(r,"in_progress")});for(let S of O)this.send(S);O.length=0,this.responseFlushed=!0}},_={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},h=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let S;try{S=await this.upstreamStream(k,o)}catch(g){this.emitUpstreamFault(g,r);return}try{for await(let g of S){if(this.cancelled)break;let b=g;if(b.type==="error"){let f=this.upstreamErrorBody(b);this.responseFlushed?this.send(L(f)):this.send({type:"response.failed",event_id:x("event"),response:this.failedResponse(r,f)});return}if(b.type==="response.output_text.delta"&&typeof b.delta=="string"){v(),_.messageOpen||(this.beginMessageItem(r,_.nextOutputIndex++),_.messageOpen=!0),y({type:"response.output_text.delta",event_id:x("event"),item_id:`${r}_msg_0`,response_id:r,output_index:0,content_index:0,delta:b.delta}),_.messageText+=b.delta;continue}if(b.type==="response.function_call_arguments.delta"){v();let f=typeof b.delta=="string"?b.delta:"",R=typeof b.call_id=="string"&&b.call_id.length>0?b.call_id:`${r}_fc_${_.nextOutputIndex}`,I=_.tools.get(R);if(!I){let $=typeof b.name=="string"&&b.name.length>0?b.name:void 0;I={outputIndex:_.nextOutputIndex++,name:$,args:""},_.tools.set(R,I),y({type:"response.output_item.added",event_id:x("event"),response_id:r,output_index:I.outputIndex,item:{id:R,object:"realtime.item",type:"function_call",call_id:R,name:$??"",arguments:"",status:"in_progress"}})}typeof b.name=="string"&&b.name.length>0&&(I.name=b.name),I.args+=f,y({type:"response.function_call_arguments.delta",event_id:x("event"),item_id:R,response_id:r,output_index:I.outputIndex,call_id:R,name:I.name??"",delta:f});continue}if(b.type==="response.completed"){h=b.response??null;continue}}}catch(g){this.emitUpstreamFault(g,r);return}if(this.cancelled)return;this.closeOpenItems(r,_,s),v(),this.send({type:"response.done",event_id:x("event"),response:this.doneResponse(r,s,h)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(xo(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(L({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:x("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:x("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let o=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:x("event"),item_id:o,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let o=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:x("event"),response_id:e,output_index:n,item:{id:o,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:x("event"),item_id:o,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:x("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:x("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,o){if(n.messageOpen||this.messageItemOpenForAudio){let r=`${e}_msg_0`,s=this.messageItemOpenForAudio;s&&this.send({type:"response.output_audio.done",event_id:x("event"),item_id:r,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:x("event"),item_id:r,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:x("event"),item_id:r,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:r,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:x("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[r,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:x("event"),item_id:r,response_id:e,output_index:s.outputIndex,call_id:r,name:s.name??"",arguments:i});let a={id:r,type:"function_call",callId:r,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:x("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,o){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...o??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,o){let r=o&&typeof o.usage=="object"&&o.usage!==null?o.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:r?{input_tokens:typeof r.input_tokens=="number"&&Number.isFinite(r.input_tokens)?r.input_tokens:0,output_tokens:typeof r.output_tokens=="number"&&Number.isFinite(r.output_tokens)?r.output_tokens:0,total_tokens:typeof r.total_tokens=="number"&&Number.isFinite(r.total_tokens)?r.total_tokens:(typeof r.input_tokens=="number"&&Number.isFinite(r.input_tokens)?r.input_tokens:0)+(typeof r.output_tokens=="number"&&Number.isFinite(r.output_tokens)?r.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,o=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}emitUpstreamFault(e,n){if(this.cancelled)return;let o=De(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(L(o)):this.send({type:"response.failed",event_id:x("event"),response:this.failedResponse(n,o)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(L(F("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:x("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>ft&&(this.items.shift(),this.send(L({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${ft} 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 o=(e.content??[]).map(r=>r.type==="input_text"||r.type==="output_text"?{type:r.type,text:r.text}:r.type==="input_audio"?{type:"input_audio",...r.transcript?{transcript:r.transcript}:{}}:{type:"output_audio",transcript:r.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:o}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Lt){this.ws.close(vo,Ln("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(L(e)),this.ws.close(bo,Ln(n)),this.teardown(n)}teardown(e){if(!this.closed){this.closed=!0,this.turnLaneAbort?.abort(),this.turnLaneAbort=null,this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(n=>Nn(this.id,`binding release failed: ${n instanceof Error?n.message:String(n)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Nn(this.id,e)}}},Ft=[];function Nn(t,e){Ft.push({id:t,reason:e}),Ft.length>256&&Ft.shift()}var Be="/v1/realtime",So=t=>t.slice(0,120);function Eo(t,e,n){let o=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${o}\r
14
+ Connection: close\r
15
+ Content-Type: text/plain\r
16
+ \r
17
+ ${So(n)}\r
18
+ `),t.destroy()}function Ao(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
19
+ `}function Io(t){we(process.stdout,t)}function Oo(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function qt(t){return t.audioSession?.audio.sessionId??void 0}function Fe(t,e){let n=new Bn.WebSocketServer({noServer:!0}),o=new Set;return t.on("upgrade",(r,s,i)=>{if(new URL(r.url??"/","http://localhost").pathname!==Be)return;o.add(s),s.on("close",()=>{o.delete(s)});let l=x("rtup"),u=Oo(r),c=g=>{(e.log??Io)(Ao(g))};c({stage:"accept",conn:l,model:u}),s.resume();let d=new AbortController,m=null,p=g=>{m??=g,d.abort(new Error(m))},k=()=>p("client socket closed"),O=()=>p("client socket closed (half-close)"),y=g=>p(`client socket error: ${g.message}`);s.once("close",k),s.once("end",O),s.once("error",y);let v=()=>{s.removeListener("close",k),s.removeListener("end",O),s.removeListener("error",y)},_=g=>{c({stage:"close",conn:l,model:u,...g})},h=g=>{let b=g,f=b.session!=null&&typeof b.session.sendResponseCreate=="function",R=b.clients!=null&&typeof b.clients.createResponse=="function";if(!f&&!R)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((I,$)=>{n.handleUpgrade(r,s,i,A=>{try{new ve({ws:A,binding:g,onClosed:(G,J)=>{_({while:"live",reason:J.reason})}}),c({stage:"admit",conn:l,model:u,...qt(g)===void 0?{}:{session:qt(g)}}),I()}catch(G){$(G)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(r,d.signal).then(async g=>{if(d.signal.aborted){v();let b=qt(g);try{await g.release?.()}catch(f){_({while:"queued",...b===void 0?{}:{session:b},reason:m??"client socket closed",release_failed:f instanceof Error?f.message:String(f)});return}_({while:"queued",...b===void 0?{}:{session:b},reason:m??"client socket closed",released:!0}),s.destroy();return}v(),await h(g)}).catch(g=>{let b=g instanceof Dn.SessionFailedError?ct(g):null,f=null;if(g!==null&&typeof g=="object"&&"status"in g){let $=g.status;typeof $=="number"&&(f=$)}let R=f??b?.status??502,I=g instanceof Error?g.message:String(g);_({while:"queued",...d.signal.aborted?{reason:m??"client socket closed"}:{reason:I,status:R}}),s.destroyed||Eo(s,R,I)}).finally(()=>{o.delete(s)})}),async()=>{let r=Date.now()+5e3;for(;o.size>0&&Date.now()<r;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}var qe=(t,e)=>Object.assign(new Error(e),{status:t});function jt(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}async function Ht(t,e,n){if(!t.supportsAudio)throw qe(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(i){throw i instanceof U?qe(404,i.message):i}if(!o)throw qe(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudio)throw qe(501,"an audio-capable model needs a router-backed client (openAudio) to open its native session audio bridge \u2014 refusing loudly rather than binding a voiceless session");let r={audio:await t.openAudio(e,n)},s={clients:t,voice:o,audioSession:r};return e!==void 0&&(s.model=e),s}function ht(t,e){return{resolve:async(n,o)=>{if(e!==void 0){let r=n.headers.authorization,s=typeof r=="string"?r.trim():"",i=s.startsWith("Bearer ")?s.slice(7).trim():"";if(i===""||i!==e)throw qe(401,"invalid local proxy api key")}return Ht(t,jt(n),o)}}}var Fn="/v1/images/generations",yt="/v1/images/edits";function qn(t){return t===Fn||t===yt}var jn="/v1/images/models";async function Hn(t,e,n){if(t){if(t.model=X({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 o=await e.catalogIdentity(n);if(o!==null){t.catalog={kind:"catalog",model_id:o.model_id,variant:o.variant};return}let r=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:r??n??null}}catch(o){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${o instanceof Error?o.message:String(o)}`}}}}var C=class extends Error{status;param;constructor(e,n,o){super(n),this.status=e,this.param=o}},To=16*1024*1024,Vn=64*1024*1024;function Gn(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 je(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var ie=class extends Error{};async function Po(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ie(`request body exceeds the ${e}-byte limit`);let o=[],r=0;for await(let s of t){let i=s;if(r+=i.length,r>e)throw new ie(`request body exceeds the ${e}-byte limit`);o.push(i)}return Buffer.concat(o)}async function Jn(t,e,n,o){let r=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},o),s=null;for await(let d of r){if(d.type==="error"){let m=d.error??{};throw new C(502,`image upstream error: ${String(m.message??"upstream reported an error")}`)}if(d.type==="response.completed"){s=d.response??null;break}}if(s===null)throw new C(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=s.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new C(502,`image upstream returned ${Array.isArray(i)?i.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],l=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],u=Buffer.from(l,"base64");if(Gn(u)===null)throw new C(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${u.length} bytes) \u2014 refusing to pass it through`);return a.push(l),{images:a}}function Wn(t){return t instanceof C?t:t instanceof U?new C(404,t.message):new C(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Kn(t,e,n,o){if(await t(e,n))return!0;let r=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return je(o,new C(404,e===void 0?`no image-capable default model is configured for this caller (${r}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${r}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function zn(t,e){t&&(t.outputUnits=e.images.length)}function Yn(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 Co={model:!0,prompt:!0,response_format:!0,n:!0};async function Xn(t,e,n){let o=n.maxBodyBytes??Vn;try{if(t.method!=="POST")throw new C(405,`${String(t.method)} is not supported on ${Fn}`);let r;try{r=JSON.parse((await Po(t,o)).toString("utf8")||"{}")}catch(d){throw d instanceof ie?new C(413,d.message):new C(400,"request body is not valid JSON")}if(r===null||typeof r!="object"||Array.isArray(r))throw new C(400,"request body must be a JSON object");let s=r;for(let d of Object.keys(s))if(!Co[d])throw new C(400,`request field "${d}" 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.`,d);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new C(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 C(400,"model must be a string","model");await Hn(n.turn,n.clients,a);let l=s.n??1;if(l!==1)throw new C(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 C(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 Kn(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:i}];try{let d=await Jn(n.clients,a,c,n.turn?Z(n.turn):void 0);zn(n.turn,d),Yn(e,d)}catch(d){throw Wn(d)}}catch(r){if(r instanceof ie){je(e,new C(413,r.message));return}if(r instanceof C){je(e,r);return}throw r}}var $o={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Qn(t,e,n){let o=n.maxBodyBytes??Vn,r=n.maxImagePartBytes??To;try{if(t.method!=="POST")throw new C(405,`${String(t.method)} is not supported on ${yt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new C(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i=t[Symbol.asyncIterator](),a=0,l=new ReadableStream({async pull(y){try{let v=await i.next();if(v.done){y.close();return}if(a+=v.value.length,a>o){y.error(new ie(`request body exceeds the ${o}-byte limit`));return}y.enqueue(v.value)}catch(v){y.error(v)}},cancel(){i.return?.()}}),u;try{let y=new Headers;for(let[h,S]of Object.entries(t.headers))if(typeof S=="string")y.set(h,S);else if(Array.isArray(S))for(let g of S)y.append(h,g);let v={method:"POST",headers:y,body:l,duplex:"half"};u=await new Request(`https://proxy.internal${t.url??"/"}`,v).formData()}catch(y){throw y instanceof ie?new C(413,y.message):new C(400,`malformed multipart body: ${String(y instanceof Error?y.message:y)}`)}let c=u.get("prompt");if(typeof c!="string"||c.trim().length===0)throw new C(400,"prompt is required and must be a non-empty string field","prompt");let d=u.get("model");if(d!==null&&typeof d!="string")throw new C(400,"model must be a string field","model");let m=d===null?void 0:d;await Hn(n.turn,n.clients,m);let p=u.get("response_format")??"b64_json";if(p!=="b64_json")throw new C(400,`response_format ${JSON.stringify(p)} 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 y of u.keys())if(!$o[y])throw new C(400,`form field "${y}" 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[]).`,y);let k=[];for(let y of["image","image[]"])for(let v of u.getAll(y)){if(!(v instanceof File))throw new C(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",y);if(v.size>r)throw new C(413,`image part exceeds the ${r}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,y);let _=new Uint8Array(await v.arrayBuffer()),h=Gn(_);if(h===null)throw new C(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",y);k.push({bytes:_,mime:h})}if(k.length===0)throw new C(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",c.length,c.length),!await Kn(n.imageModels,m,"edit",e))return;let O=[{type:"input_text",text:c}];for(let{bytes:y,mime:v}of k)O.push({type:"input_image",image_url:`data:${v};base64,${Buffer.from(y).toString("base64")}`});try{let y=await Jn(n.clients,m,O,n.turn?Z(n.turn):void 0);zn(n.turn,y),Yn(e,y)}catch(y){throw Wn(y)}}catch(s){if(s instanceof ie){je(e,new C(413,s.message));return}if(s instanceof C){je(e,s);return}throw s}}var Ve="/v1/audio/speech";function rr(t){return t===Ve}var Zn=4096,Mo=18e4,Uo=5e3,Lo=64*1024*1024,er=8,tr=5,wt="voice_applied",No="X-Urun-Voice-Applied",P=class extends Error{status;param;retryAfterSeconds;constructor(e,n,o,r){super(n),this.status=e,this.param=o,this.retryAfterSeconds=r}};function Vt(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 Ae=class extends Error{},vt=class extends P{constructor(e){super(502,e)}};async function Do(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Ae(`request body exceeds the ${e}-byte limit`);let o=[],r=0;for await(let s of t){let i=s;if(r+=i.length,r>e)throw new Ae(`request body exceeds the ${e}-byte limit`);o.push(i)}return Buffer.concat(o)}async function Bo(t,e,n){if(t){if(t.model=X({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 o=await e.catalogIdentity(n);if(o!==null){t.catalog={kind:"catalog",model_id:o.model_id,variant:o.variant};return}let r=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:r??n??null}}catch(o){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${o instanceof Error?o.message:String(o)}`}}}}function Fo(t,e){t&&(t.outputUnits=e/(24e3*2))}var qo=2;function jo(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>qo)return!1;return!0}function Ho(t){let e=24e3,n=2,o=1,r=Buffer.alloc(44);return r.write("RIFF",0,"ascii"),r.writeUInt32LE(36+t,4),r.write("WAVE",8,"ascii"),r.write("fmt ",12,"ascii"),r.writeUInt32LE(16,16),r.writeUInt16LE(1,20),r.writeUInt16LE(o,22),r.writeUInt32LE(e,24),r.writeUInt32LE(e*o*n,28),r.writeUInt16LE(o*n,32),r.writeUInt16LE(16,34),r.write("data",36,"ascii"),r.writeUInt32LE(t,40),r}var nr=new WeakMap,_t=new WeakMap;function Vo(t,e){let n=_t.get(t)??0;if(n>=er)throw new P(503,`this model's speech queue is full \u2014 ${er} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${tr}s`,void 0,tr);_t.set(t,n+1);let o=nr.get(t)??Promise.resolve(),r,s=new Promise(i=>{r=i});return nr.set(t,s),(async()=>{await o;try{return await e()}finally{_t.set(t,(_t.get(t)??1)-1),r()}})()}async function Go(t,e,n,o){if(typeof t.evictSpeechSession!="function")throw new P(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof Q))throw i}if(n?.return===void 0)return;let r=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([r,new Promise(i=>{s=setTimeout(i,o)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function He(t){return t instanceof P?t:t instanceof U?new P(404,t.message):new P(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Jo(t,e,n,o,r,s,i){return Vo(e,async()=>{if(i?.()===!0)return null;let a=[],l=!1,u=0,c=!1,d=!1,m,p=new Promise(S=>{m=S}),k=()=>{c&&!d&&u>=r.quietRunFrames&&(d=!0,m())},O=e.onOutputAudio(S=>{let g=Buffer.from(S,"base64");if(g.byteLength===0)return;let b=jo(g);if(!l){if(b)return;l=!0}a.push(g),u=b?u+1:0,k()}),y=null,v,_,h;try{h=(await t.createResponseOn(n,{model:o.model,input:[{role:"user",content:[{type:"input_text",text:o.text}]}],stream:!1,...o.voice!==void 0?{voice:o.voice}:{}}))[Symbol.asyncIterator]();let g=new Promise(I=>{_=setTimeout(I,s.capMs)}),b=!1;for(;;){let I=h.next(),$=await Promise.race([I,g]);if($===void 0){b=!0,I.catch(()=>{});break}if($.done)break;let A=$.value;if(A.type==="error"){let G=A.error??{};throw await h.return?.(),new P(502,`speech upstream error: ${String(G.message??"upstream reported an error")}`)}if(A.type==="response.completed"){y=A.response??null,c=!0,k(),await h.return?.();break}}if(clearTimeout(_),b)throw new P(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(y===null)throw new P(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let f=!1;if(await Promise.race([p,new Promise(I=>{v=setTimeout(()=>{f=!0,I()},r.capMs)})]),v!==void 0&&clearTimeout(v),o.voice!==void 0){let I=y[wt];if(typeof I!="string"||I!==o.voice){let $=`the runtime did not acknowledge the requested voice ${JSON.stringify(o.voice)} \u2014 the terminal response carried ${typeof I=="string"?`${wt} ${JSON.stringify(I)}`:`no ${wt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw d?new vt($):new P(502,$)}}if(!l)throw new P(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(f&&!d&&u<1)throw new P(502,`the upstream audio stream did not quiesce within ${r.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);let R=u>0?a.slice(0,a.length-u):a;return{pcm:Buffer.concat(R),completed:y}}catch(S){throw S instanceof vt||await Go(t,n,h,s.returnBoundMs),S}finally{v!==void 0&&clearTimeout(v),_!==void 0&&clearTimeout(_),O()}})}async function Wo(t,e,n){let o;try{o=await t(e)}catch(r){throw He(r)}return o?!0:(Vt(n,new P(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Ko={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},zo="wav, pcm";async function or(t,e,n){let o=n.maxBodyBytes??Lo,r=!1;e.once("close",()=>{r=!0});let s=()=>r||e.destroyed;try{if(t.method!=="POST")throw new P(405,`${String(t.method)} is not supported on ${Ve}`);let i;try{i=JSON.parse((await Do(t,o)).toString("utf8")||"{}")}catch(h){throw h instanceof Ae?new P(413,h.message):new P(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new P(400,"request body must be a JSON object");let a=i;for(let h of Object.keys(a))if(!Ko[h])throw new P(400,`request field "${h}" 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.`,h);let l=a.input;if(typeof l!="string"||l.trim().length===0)throw new P(400,"input is required and must be a non-empty string","input");if(l.length>Zn)throw new P(400,`input is ${l.length} chars \u2014 over the ${Zn}-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 P(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new P(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new P(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Ve} against a stale copy of the list`);let d;try{d=await n.clients.speechVoices(u)}catch(h){throw He(h)}if(d.defect!==null)throw new P(500,`the voice set for this model cannot be resolved: ${d.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof c=="string"?c:void 0;if(m!==void 0&&d.published.length>0&&!d.published.includes(m))throw new P(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${d.published.join(", ")}`,"voice");let p=a.response_format??"wav";if(p!=="wav"&&p!=="pcm")throw new P(400,`response_format ${JSON.stringify(p)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${zo} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new P(400,"stream_format, when present, must be a string","stream_format");let k=a.speed;if(k!==void 0){if(typeof k!="number"||!Number.isFinite(k))throw new P(400,"speed, when present, must be a number","speed");if(k!==1)throw new P(400,`speed=${JSON.stringify(k)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let O=a.instructions;if(O!==void 0){if(typeof O!="string")throw new P(400,"instructions, when present, must be a string","instructions");if(O.trim().length>0)throw new P(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await Bo(n.turn,n.clients,u);let y=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",y,y),!await Wo(n.speechModels,u,e))return;if(typeof n.clients.openAudioOn!="function")throw new P(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new P(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new P(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let v;try{v=await n.clients.speechSessionHandle(u)}catch(h){throw He(h)}let _;try{_=await n.clients.openAudioOn(v)}catch(h){throw He(h)}n.turn&&(n.turn.sessionId=_.sessionId);try{let h=await Jo(n.clients,_,v,{model:u,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Mo,returnBoundMs:n.turnReturnBoundMs??Uo},s);if(h===null||s())return;if(Fo(n.turn,h.pcm.byteLength),e.statusCode=200,m===void 0){let S=h.completed[wt];typeof S=="string"&&e.setHeader(No,S)}p==="wav"?(e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Ho(h.pcm.byteLength),h.pcm]))):(e.setHeader("content-type","audio/pcm"),e.end(h.pcm))}catch(h){throw He(h)}}catch(i){if(i instanceof Ae){Vt(e,new P(413,i.message));return}if(i instanceof P){Vt(e,i);return}throw i}}var ir="/v1/usage/requests",sr=1e4,Yo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ce=class extends Error{constructor(n,o=400){super(n);this.status=o;this.name="UsageRequestError"}status},Ie=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var ar=1024*1024;function Gt(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ce(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new ce(`"${e}" must be an array of uuid strings`);if(n.length>sr)throw new ce(`"${e}" carries ${n.length} ids; at most ${sr} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let o=[],r=new Set;for(let s of n){if(typeof s!="string"||!Yo.test(s))throw new ce(`"${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`);r.has(s)||(r.add(s),o.push(s))}return o}function ur(t){return Gt(t,"inference_ids")}function bt(t,e){let n=new Set(e),o=new Set;for(let r=0;r<t.length;r++){let s=t[r];if(!n.has(s.inference_id))throw new Ie(`the usage surface returned an id at validated answer position ${r} 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(o.has(s.inference_id))throw new Ie(`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`);o.add(s.inference_id)}}var St=require("@urun-sh/core");var Jt="/partners/huggingface/v1/billing/requests";function Xo(t){return Gt(t,"requestIds")}function Qo(t){return t>=200&&t<=399}function Zo(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Qo(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function dr(t,e){let n=Xo(t),o=await e(n);return bt(o,n),Zo(o)}var es={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech"};function ts(t){return es[t]??null}var fr=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function ns(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function rs(t){return t==="surface"}function os(t){let e=t?.ledgerFailureReason;return fr.includes(e)?e:"unknown"}var ss=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],lr=["priced","unpriced"],is={written:lr,already_written:lr,skipped:ss,failed:fr},Pa=Object.entries(is).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function as(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function us(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 ds=256,cr=4096,Je=12e4,ls=250,cs=8e3,We=[],pr=new Set,Ke=0,Ge=!1;var ps=new Set;function fs(){return Ke===0&&We.length===0}function ms(){if(fs()){Ge=!1;for(let t of[...ps])t()}}function mr(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
20
+ `}function gs(t){we(process.stdout,t)}function gr(t,e){try{t(e)}catch{}}function hr(t){let{record:e,ledger:n}=t;if(n===null)return;let o=n.report??gs,r=ts(e.path);if(r===null)return;let s=c=>{try{n.observe(c)}catch{}},i=(c,d)=>{s({outcome:"skipped",reason:c}),gr(o,mr("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:c,detail:d}))};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:r,http_status:e.status,started_at:us(e),completed_at:e.ts,billable_outcome:as(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(We.length>=cr){i("queue_full",`${We.length} ledger writes are already waiting (capacity ${cr}, ${Ke} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}We.push({entry:u,req:t.req,record:e,ledger:n,report:o,queuedAt:Date.now(),attempts:0,settled:!1}),Ke<ds&&(Ke+=1,hs())}async function hs(){try{for(;;){let t=ys();if(t===void 0)return;pr.add(t);try{await _s(t)}finally{pr.delete(t)}}}finally{Ke-=1,ms()}}function ys(){let t=Date.now();for(;;){let e=We.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Je)return e;Oe(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 ${Je}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 _s(t){let{entry:e,record:n,ledger:o}=t;for(;;){t.attempts+=1;try{let r=await o.write(t.req,e);Oe(t,{outcome:"written",reason:r.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:r.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:r.cost_nano_usd,price_version:r.price_version,unpriced_reason:r.unpriced_reason,attempts:t.attempts});return}catch(r){let s=ns(r);if(s!==null){Oe(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=os(r),a=Date.now()-t.queuedAt;if(Ge){Oe(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: ${r instanceof Error?r.message:String(r)}`});return}if(rs(i)&&a<Je){if(await vs(ws(t.attempts)),Ge||Date.now()-t.queuedAt>=Je){let l=Date.now()-t.queuedAt;Oe(t,{outcome:"failed",reason:Ge?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Ge?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:l,error:`this row's backoff outlived the ${Je}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: ${r instanceof Error?r.message:String(r)}`});return}continue}Oe(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:r instanceof Error?r.message:String(r)});return}}}function ws(t){return Math.min(cs,ls*2**Math.max(0,t-1))}function vs(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Oe(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:o,...r}=n;gr(t.report,mr(o,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...r}))}var bs=At(require("crypto"),1);var ks=6e4,Ma=ks/1e3+5;var yr=15;var Ua=yr*1e3,La=yr*500;var ze=class extends Error{constructor(n,o){super(`runtime answered ${n}`);this.status=n;this.body=o}status;body},Ye=class extends Error{};function zt(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function j(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function H(t,e,n,o="invalid_request_error",r){j(t,e,{error:r?{message:n,type:o,code:r}:{message:n,type:o}})}function Yt(t,e){let n=e.error,o=n?.type??"upstream_error",r=n?.message??JSON.stringify(e);j(t,o==="invalid_request_error"?400:502,{error:{message:r,type:o,code:n?.code??null}})}function te(t,e,n,o){j(t,e,{type:"error",error:{type:n,message:o}})}function ne(t,e,n){if(e==="anthropic"){j(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}j(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Rs=64*1024*1024,Xe=class extends Error{};async function _r(t,e=Rs){let n=[],o=0;for await(let s of t){if(o+=s.length,o>e)throw new Xe(`request body exceeds ${e} bytes`);n.push(s)}let r=Buffer.concat(n).toString("utf8");return r?JSON.parse(r):{}}function Te(t,e,n,o){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:o}]}}function br(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,o=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:null,r=o(n.input_tokens),s=o(n.output_tokens),i=l=>l??0,a=o(n.total_tokens)??i(r)+i(s);if(i(r)>0||i(s)>0){let l={input_tokens:i(r),output_tokens:i(s),total_tokens:a};return r===null||s===null?{kind:"partial",usage:l}:{kind:"counts",usage:l}}return r===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function kt(t){let e=br(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function wr(t){let e=kt(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 xs(t,e){let n=br(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Ss(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,o=l=>{let u=n[l];return typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u:null},r=o("queue_ms"),s=o("prefill_ms"),i=o("decode_ms"),a=o("total_ms");return r===null||s===null||i===null||a===null?null:{queue_ms:r,prefill_ms:s,decode_ms:i,total_ms:a}}function Es(t,e){let n=Ss(e);n&&(t.timing=n)}function ae(t,e){xs(t,e),Es(t,e)}async function Et(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 o=await e.catalogIdentity(n);if(o!==null){t.catalog={kind:"catalog",model_id:o.model_id,variant:o.variant};return}let r=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:r??n??null}}catch(o){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${o instanceof Error?o.message:String(o)}`}}}function kr(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let o of e)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let r of o.content)r.type==="reasoning_text"&&(n+=String(r.text??""));return n}function As(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 Rt=class extends Error{};function Is(t,e){return Array.isArray(e)?e.map(n=>{let o=n;if(o.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:o.text};if(o.type==="image_url"){let r=o.image_url??{};return{type:"input_image",image_url:r.url,detail:r.detail}}throw new Rt(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Os(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 o of n.tool_calls){let r=o.function??{};e.push({type:"function_call",call_id:o.id,name:r.name,arguments:r.arguments})}continue}e.push({...n,content:Is(n.role,n.content)})}return e}function Wt(t){return xe(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 Ts(t,e,n,o,r,s){let i=Me(s.id),a=t.stream===!0;if(s.model=X(t),s.stream=a,await Et(s,e,typeof t.model=="string"?t.model:void 0),a){let v;try{v=await Le({body:t,clients:e,store:n,stats:r,responseId:i,turn:s})}catch(_){if(_ instanceof U){ne(o,"openai",_);return}if(_ instanceof Y){H(o,_.status,_.message);return}throw _}zt(o);for await(let _ of v.events)_.type==="error"&&(s.streamError=!0),_.type==="response.completed"&&ae(s,_.response),o.write(`event: ${String(_.type??"message")}
21
+ data: ${JSON.stringify(_)}
14
22
 
15
23
  `);o.write(`data: [DONE]
16
24
 
17
- `),o.end();return}let r;try{r=ye(t,n)}catch(y){if(y instanceof H){J(o,y.status,y.message);return}throw y}n.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(r))-Buffer.byteLength(JSON.stringify(n.input)));let a=`resp_${Math.random().toString(36).slice(2,14)}`,d=n.store!==!1,u=me(n);s.model(u);let c=Array.isArray(n.tools)&&n.tools.length>0,l;try{l=await Ge(e,n,r,!1)}catch(y){if(y instanceof V){Le(o,"openai",y);return}if(y instanceof H){J(o,y.status,y.message);return}throw y}let f=[],h=null;for await(let y of s.track(l,u)){if(f.push(y),y.type==="error"){J(o,502,JSON.stringify(y),"upstream_error");return}y.type==="response.completed"&&(h=y.response)}if(h==null){J(o,502,"upstream produced no response.completed event","upstream_error");return}let w=Je(f,h),v=de(c,he(h).length,w);if(v){J(o,502,ue(u,v),"upstream_error");return}d&&t.remember(a,r,We(h,w),d),W(o,200,{...h,id:a})}async function On(n,e,t,o){let s=n.messages;if(!Array.isArray(s)){J(t,400,"chat/completions requires a messages array");return}let i=String(n.model??"urun"),r=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,a;try{a=An(s)}catch(p){if(p instanceof Ue){J(t,400,p.message);return}throw p}let d=me(n);o.model(d);let u=Array.isArray(n.tools)&&n.tools.length>0,c;try{c=await e.createResponse({model:n.model,input:a,stream:!0,tools:xn(n.tools),tool_choice:n.tool_choice,temperature:n.temperature,top_p:n.top_p,stop:n.stop,max_output_tokens:n.max_completion_tokens??n.max_tokens,...n.reasoning_effort!==void 0?{reasoning_effort:n.reasoning_effort}:{},...n.chat_template_kwargs!==void 0?{chat_template_kwargs:n.chat_template_kwargs}:{}})}catch(p){if(p instanceof V){Le(t,"openai",p);return}throw p}if(n.stream===!0){Ze(t);let p=[],k=new te,L="";t.write(`data: ${JSON.stringify(_e(r,i,{role:"assistant"},null))}
25
+ `),o.end();return}let l;try{l=Ee(n,t)}catch(v){if(v instanceof Y){H(o,v.status,v.message);return}throw v}t.previous_response_id!=null&&(r.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let u=t.store!==!1,c=X(t);r.model(c);let d=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await Pt(e,t,l,!1,Z(s))}catch(v){if(v instanceof U){ne(o,"openai",v);return}if(v instanceof Y){H(o,v.status,v.message);return}throw v}let p=[],k=null;for await(let v of r.track(m,c,s)){if(p.push(v),v.type==="error"){Yt(o,v);return}v.type==="response.completed"&&(k=v.response)}if(k==null){H(o,502,"upstream produced no response.completed event","upstream_error");return}ae(s,k);let O=ut(p,k),y=_e(d,xe(k).length,O);if(y){H(o,502,ye(c,y),"upstream_error");return}u&&n.remember(i,l,Tt(k,O),u),j(o,200,{...k,id:i})}async function Ps(t,e,n,o,r){let s=t.messages;if(!Array.isArray(s)){H(n,400,"chat/completions requires a messages array");return}let i=String(t.model??"urun"),a=xn(r.id),l;try{l=Os(s)}catch(f){if(f instanceof Rt){H(n,400,f.message);return}throw f}let u=X(t);o.model(u),r.model=u,r.stream=t.stream===!0,await Et(r,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0;if(t.stream!==!0&&e.stateless?.enabled){let f;try{f=await e.stateless.targetFor(typeof t.model=="string"?t.model:void 0)}catch(R){if(R instanceof U){ne(n,"openai",R);return}throw R}if(f!==null){try{let R=await e.stateless.decide(t,typeof t.model=="string"?t.model:void 0);r.catalog=It(R.target),ae(r,R.completed),j(n,200,{...R.body,id:a})}catch(R){if(R instanceof U){ne(n,"openai",R);return}if(R instanceof ze){j(n,R.status,R.body);return}if(R instanceof Ye){H(n,503,R.message,"upstream_error");return}throw R}return}}let d;try{d=await e.createResponse({model:t.model,input:l,stream:!0,tools:As(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}:{}},Z(r))}catch(f){if(f instanceof U){ne(n,"openai",f);return}throw f}if(t.stream===!0){zt(n);let f=[],R=new de,I="";n.write(`data: ${JSON.stringify(Te(a,i,{role:"assistant"},null))}
18
26
 
19
- `);for await(let $ of o.track(c,d)){p.push($);let B=ge($);if($.type==="response.output_text.delta"&&typeof $.delta=="string")L+=$.delta,t.write(`data: ${JSON.stringify(_e(r,i,{content:$.delta},null))}
27
+ `);for await(let V of o.track(d,u,r)){f.push(V);let T=Se(V);if(V.type==="response.output_text.delta"&&typeof V.delta=="string")I+=V.delta,n.write(`data: ${JSON.stringify(Te(a,i,{content:V.delta},null))}
20
28
 
21
- `);else if($.type==="response.reasoning_text.delta"&&typeof $.delta=="string")t.write(`data: ${JSON.stringify(_e(r,i,{reasoning_content:$.delta},null))}
29
+ `);else if(V.type==="response.reasoning_text.delta"&&typeof V.delta=="string")n.write(`data: ${JSON.stringify(Te(a,i,{reasoning_content:V.delta},null))}
22
30
 
23
- `);else if(B){let{call:b,isNew:S}=k.add(B),P=S?{index:B.tool_index,id:b.id??`call_${B.tool_index}`,type:"function",function:{name:b.name??"",arguments:B.delta}}:{index:B.tool_index,function:{arguments:B.delta}};t.write(`data: ${JSON.stringify(_e(r,i,{tool_calls:[P]},null))}
31
+ `);else if(T){let{call:N,isNew:q}=R.add(T),z=q?{index:T.tool_index,id:N.id??`call_${T.tool_index}`,type:"function",function:{name:N.name??"",arguments:T.delta}}:{index:T.tool_index,function:{arguments:T.delta}};n.write(`data: ${JSON.stringify(Te(a,i,{tool_calls:[z]},null))}
24
32
 
25
- `)}else if($.type==="error"){t.write(`data: ${JSON.stringify({error:$})}
33
+ `)}else if(V.type==="error"){r.streamError=!0,n.write(`data: ${JSON.stringify({error:V})}
26
34
 
27
- `),t.end();return}}let I=Xe(ne(p)),D=de(u,k.size+I.length,L);if(D){t.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ue(d,D)}})}
35
+ `),n.end();return}}let $=Wt(ee(f)),A=_e(c,R.size+$.length,I);if(A){r.streamError=!0,n.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ye(u,A)}})}
28
36
 
29
- `),t.end();return}k.size===0&&I.length>0&&t.write(`data: ${JSON.stringify(_e(r,i,{tool_calls:I},null))}
37
+ `),n.end();return}R.size===0&&$.length>0&&n.write(`data: ${JSON.stringify(Te(a,i,{tool_calls:$},null))}
30
38
 
31
- `);let C=k.size>0||I.length>0;t.write(`data: ${JSON.stringify(_e(r,i,{},C?"tool_calls":"stop"))}
39
+ `);let G=R.size>0||$.length>0;n.write(`data: ${JSON.stringify(Te(a,i,{},G?"tool_calls":"stop"))}
32
40
 
33
- `),Ne(ne(p))&&t.write(`data: ${JSON.stringify({id:r,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:i,choices:[],usage:Mt(ne(p))})}
41
+ `);let J=kt(ee(f));ae(r,ee(f)),J&&n.write(`data: ${JSON.stringify({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:i,choices:[],usage:wr(ee(f))})}
34
42
 
35
- `),t.write(`data: [DONE]
43
+ `),n.write(`data: [DONE]
36
44
 
37
- `),t.end();return}let l="",f="",h=[],w=new te;for await(let p of o.track(c,d)){h.push(p),p.type==="response.output_text.delta"&&typeof p.delta=="string"&&(l+=p.delta),p.type==="response.reasoning_text.delta"&&typeof p.delta=="string"&&(f+=p.delta);let k=ge(p);if(k&&w.add(k),p.type==="error"){J(t,502,JSON.stringify(p),"upstream_error");return}}let v=ne(h),y=Xe(v),x=y.length>0?y:Xe({output:w.items()}),R=de(u,x.length,l);if(R){J(t,502,ue(d,R),"upstream_error");return}let U=x.map(({index:p,...k})=>k),T={role:"assistant",content:l||null},N=f||$t(v);N&&(T.reasoning_content=N),U.length>0&&(T.tool_calls=U),W(t,200,{id:r,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:i,choices:[{index:0,message:T,finish_reason:U.length>0?"tool_calls":"stop"}],usage:Mt(v)})}function In(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var be=class extends Error{};function Be(n){return new be(`unsupported anthropic content block type "${n}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function En(n){if(Array.isArray(n))return n.map(e=>{let t=e;return{type:"function",name:t.name,description:t.description,parameters:t.input_schema}})}function Tn(n){if(n==null)return;let e=n.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:n.name};throw new be(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Cn(n){if(typeof n=="string")return n;if(n==null)return"";if(!Array.isArray(n))throw Be(typeof n);let e="";for(let t of n){let o=String(t.type??"");if(o!=="text")throw Be(`tool_result > ${o}`);e+=String(t.text??"")}return e}function Pn(n){let{role:e,content:t}=n;if(typeof t=="string")return[{role:e,content:t}];if(t==null)return[];if(!Array.isArray(t))throw Be(typeof t);let o=[],s="",i=()=>{s&&(o.push({role:e,content:s}),s="")};for(let r of t){let a=String(r.type??"");if(a==="text")s+=String(r.text??"");else if(a==="tool_use")i(),o.push({type:"function_call",call_id:r.id,name:r.name,arguments:JSON.stringify(r.input??{})});else if(a==="tool_result")i(),o.push({type:"function_call_output",call_id:r.tool_use_id,output:Cn(r.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Be(a)}}return i(),o}function Qe(n){return he(n).map((e,t)=>{let o;try{o=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_${t}`,name:e.name??"",input:o}})}async function Mn(n,e,t,o){let s=n.messages;if(!Array.isArray(s)){K(t,400,"invalid_request_error","messages requires a messages array");return}if(typeof n.max_tokens!="number"||!Number.isInteger(n.max_tokens)||n.max_tokens<1){K(t,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(n.top_k!==void 0){K(t,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(n.stop_sequences!==void 0&&(!Array.isArray(n.stop_sequences)||n.stop_sequences.some(p=>typeof p!="string"))){K(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(n.model??"urun"),r=`msg_${Math.random().toString(36).slice(2,14)}`,a=[],d;try{n.system&&a.push({role:"system",content:In(n.system)});for(let p of s)a.push(...Pn(p));d=Tn(n.tool_choice)}catch(p){if(p instanceof be){K(t,400,"invalid_request_error",p.message);return}throw p}let u=me(n);o.model(u);let c=Array.isArray(n.tools)&&n.tools.length>0,l;try{l=await e.createResponse({model:n.model,input:a,stream:!0,tools:En(n.tools),tool_choice:d,temperature:n.temperature,max_output_tokens:n.max_tokens,top_p:n.top_p,stop:n.stop_sequences})}catch(p){if(p instanceof V){Le(t,"anthropic",p);return}throw p}let f=(p,k)=>{t.destroyed||t.write(`event: ${p}
38
- data: ${JSON.stringify({type:p,...k})}
45
+ `),n.end();return}let m="",p="",k=[],O=new de;for await(let f of o.track(d,u,r)){k.push(f),f.type==="response.output_text.delta"&&typeof f.delta=="string"&&(m+=f.delta),f.type==="response.reasoning_text.delta"&&typeof f.delta=="string"&&(p+=f.delta);let R=Se(f);if(R&&O.add(R),f.type==="error"){Yt(n,f);return}}let y=ee(k);ae(r,y);let v=Wt(y),_=v.length>0?v:Wt({output:O.items()}),h=_e(c,_.length,m);if(h){H(n,502,ye(u,h),"upstream_error");return}let S=_.map(({index:f,...R})=>R),g={role:"assistant",content:m||null},b=p||kr(y);b&&(g.reasoning_content=b),S.length>0&&(g.tool_calls=S),j(n,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:i,choices:[{index:0,message:g,finish_reason:S.length>0?"tool_calls":"stop"}],usage:wr(y)})}var Cs="reflex-latest";async function $s(t,e,n,o,r){if(t===null||typeof t!="object"||Array.isArray(t)){H(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:Cs,i=X({model:s});if(r.model=i,r.stream=!1,t.state===void 0||t.state===null){H(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){H(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){H(n,400,"systemone media, when present, must be an array");return}if(o.model(i),await Et(r,e,s),e.stateless?.enabled){let p;try{p=await e.stateless.targetFor(s)}catch(k){if(k instanceof U){ne(n,"openai",k);return}throw k}if(p!==null){try{let k=await e.stateless.decide(t,s);r.catalog=It(k.target),ae(r,k.completed),j(n,200,k.body)}catch(k){if(k instanceof U){ne(n,"openai",k);return}if(k instanceof ze){j(n,k.status,k.body);return}if(k instanceof Ye){H(n,503,k.message,"upstream_error");return}throw k}return}}let l;try{l=await e.createResponse({model:s,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},Z(r))}catch(p){if(p instanceof U){ne(n,"openai",p);return}throw p}let u=[];try{for await(let p of o.track(l,i,r))if(u.push(p),p.type==="error"){Yt(n,p);return}}catch(p){if(p instanceof U){ne(n,"openai",p);return}throw p}let c=ee(u);if(c==null){H(n,502,"upstream produced no response.completed event","upstream_error");return}ae(r,c);let d=ut(u,c),m;try{m=JSON.parse(d)}catch{H(n,502,"systemone answer was not valid JSON","upstream_error");return}if(m===null||typeof m!="object"||Array.isArray(m)){H(n,502,"systemone answer was not a JSON object","upstream_error");return}j(n,200,m)}function Ms(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Qe=class extends Error{};function xt(t){return new Qe(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Us(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 Ls(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 Qe(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Ns(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw xt(typeof t);let e="";for(let n of t){let o=String(n.type??"");if(o!=="text")throw xt(`tool_result > ${o}`);e+=String(n.text??"")}return e}function Ds(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 xt(typeof n);let o=[],r="",s=()=>{r&&(o.push({role:e,content:r}),r="")};for(let i of n){let a=String(i.type??"");if(a==="text")r+=String(i.text??"");else if(a==="tool_use")s(),o.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),o.push({type:"function_call_output",call_id:i.tool_use_id,output:Ns(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw xt(a)}}return s(),o}function Kt(t){return xe(t).map((e,n)=>{let o;try{o=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:o}})}async function Bs(t,e,n,o,r){let s=t.messages;if(!Array.isArray(s)){te(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){te(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){te(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(f=>typeof f!="string"))){te(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(t.model??"urun"),a=Sn(r.id),l=[],u;try{t.system&&l.push({role:"system",content:Ms(t.system)});for(let f of s)l.push(...Ds(f));u=Ls(t.tool_choice)}catch(f){if(f instanceof Qe){te(n,400,"invalid_request_error",f.message);return}throw f}let c=X(t);o.model(c),r.model=c,r.stream=t.stream===!0,await Et(r,e,typeof t.model=="string"?t.model:void 0);let d=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:l,stream:!0,tools:Us(t.tools),tool_choice:u,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},Z(r))}catch(f){if(f instanceof U){ne(n,"anthropic",f);return}throw f}let p=(f,R)=>{n.destroyed||n.write(`event: ${f}
46
+ data: ${JSON.stringify({type:f,...R})}
39
47
 
40
- `)};if(n.stream===!0){let p=o.track(l,u);Ze(t),f("message_start",{message:{id:r,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let k=0,L="",I=0,D="none",C=()=>D,G=-1,$=-1,B=new te,b=[],S=()=>{D!=="none"&&(D="none",f("content_block_stop",{index:G}))},P=(O,q)=>{S(),D=O,G=I++,f("content_block_start",{index:G,content_block:q})};for await(let O of p){if(t.destroyed)break;b.push(O);let q=ge(O);if(O.type==="response.reasoning_text.delta"&&typeof O.delta=="string")C()!=="thinking"&&P("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:G,delta:{type:"thinking_delta",thinking:O.delta}});else if(O.type==="response.output_text.delta"&&typeof O.delta=="string")C()!=="text"&&P("text",{type:"text",text:""}),k+=1,L+=O.delta,f("content_block_delta",{index:G,delta:{type:"text_delta",text:O.delta}});else if(q){let{call:rt}=B.add(q);(C()!=="tool"||q.tool_index!==$)&&($=q.tool_index,P("tool",{type:"tool_use",id:rt.id??`call_${q.tool_index}`,name:rt.name??"",input:{}})),q.delta&&f("content_block_delta",{index:G,delta:{type:"input_json_delta",partial_json:q.delta}})}else if(O.type==="error"){f("error",{error:{type:"api_error",message:JSON.stringify(O)}}),t.end();return}}if(t.destroyed)return;let Y=ne(b),Ae=he(Y),ee=de(c,B.size+Ae.length,L);if(ee){f("error",{error:{type:"api_error",message:ue(u,ee)}}),t.end();return}S();let z=[];if(B.size===0)try{z=Qe(Y)}catch(O){f("error",{error:{type:"api_error",message:String(O instanceof Error?O.message:O)}}),t.end();return}I===0&&z.length===0&&(P("text",{type:"text",text:""}),S()),z.forEach(O=>{let q=I++;f("content_block_start",{index:q,content_block:{...O,input:{}}}),f("content_block_delta",{index:q,delta:{type:"input_json_delta",partial_json:JSON.stringify(O.input??{})}}),f("content_block_stop",{index:q})});let ce=B.size>0||z.length>0,se=Ne(Y);f("message_delta",{delta:{stop_reason:ce?"tool_use":"end_turn"},usage:se?{input_tokens:se.input_tokens,output_tokens:se.output_tokens}:{output_tokens:k}}),f("message_stop",{}),t.end();return}let h="",w="",v=[],y=new te;for await(let p of o.track(l,u)){v.push(p),p.type==="response.output_text.delta"&&typeof p.delta=="string"&&(h+=p.delta),p.type==="response.reasoning_text.delta"&&typeof p.delta=="string"&&(w+=p.delta);let k=ge(p);if(k&&y.add(k),p.type==="error"){K(t,502,"api_error",JSON.stringify(p));return}if(t.destroyed)break}if(t.destroyed)return;let x=ne(v),R;try{R=Qe(x),R.length===0&&y.size>0&&(R=Qe({output:y.items()}))}catch(p){K(t,502,"api_error",String(p instanceof Error?p.message:p));return}let U=de(c,R.length,h);if(U){K(t,502,"api_error",ue(u,U));return}let T=[],N=w||$t(x);N&&T.push({type:"thinking",thinking:N}),(h||R.length===0)&&T.push({type:"text",text:h}),T.push(...R),W(t,200,{id:r,type:"message",role:"assistant",content:T,model:i,stop_reason:R.length>0?"tool_use":"end_turn",usage:Ne(x)??{input_tokens:0,output_tokens:0}})}function Ln(n){let{clients:e,apiKey:t,identity:o,statusOf:s}=n,i=typeof e=="function"?e:()=>e,r=new re;return(a,d)=>{let u=new URL(a.url??"/","http://localhost"),c=u.pathname==="/v1/messages"||u.pathname.startsWith("/v1/messages/"),l=(f,h,w,v)=>c?K(d,f,v,h):J(d,f,h,w);(async()=>{if(a.method==="GET"&&u.pathname==="/healthz"){W(d,200,{ok:!0});return}if(a.method==="GET"&&u.pathname==="/stats"){W(d,200,o?{identity:o,...r.snapshot()}:r.snapshot());return}if(t&&(a.headers.authorization??"")!==`Bearer ${t}`){l(401,"invalid local proxy api key","authentication_error","authentication_error");return}let f=await i(a);if(a.method==="GET"&&u.pathname==="/v1/models"){if(u.searchParams.get("format")==="openrouter"){if(!f.openRouterModels){l(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}W(d,200,await f.openRouterModels());return}W(d,200,await f.listModels());return}if(a.method!=="POST"){l(404,`no route for ${a.method} ${u.pathname}`,"invalid_request_error","not_found_error");return}let h;try{h=await bn(a)}catch(v){if(v instanceof $e){l(413,v.message,"request_too_large","request_too_large");return}l(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let w=Buffer.byteLength(JSON.stringify(h));if(u.pathname==="/v1/responses"){r.request("responses",w,w),await Sn(h,f,ve(f),d,r);return}if(u.pathname==="/v1/chat/completions"){r.request("chat_completions",w,w),await On(h,f,d,r);return}if(u.pathname==="/v1/messages"){r.request("messages",w,w),await Mn(h,f,d,r);return}if(u.pathname==="/v1/messages/count_tokens"){r.request("count_tokens",w,w),K(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}l(404,`no route for POST ${u.pathname}`,"invalid_request_error","not_found_error")})().catch(f=>{let h=String(f instanceof Error?f.message:f);if(!d.headersSent){let w=s?.(f)??null;if(w){l(w.status,h,w.openaiType,w.anthropicType);return}l(500,h,"proxy_error","api_error");return}d.destroyed||(c?d.write(`event: error
48
+ `)};if(t.stream===!0){let f=o.track(m,c,r);zt(n),p("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let R=0,I="",$=0,A="none",G=()=>A,J=-1,V=-1,T=new de,N=[],q=()=>{A!=="none"&&(A="none",p("content_block_stop",{index:J}))},z=(B,K)=>{q(),A=B,J=$++,p("content_block_start",{index:J,content_block:K})};for await(let B of f){if(n.destroyed)break;N.push(B);let K=Se(B);if(B.type==="response.reasoning_text.delta"&&typeof B.delta=="string")G()!=="thinking"&&z("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:J,delta:{type:"thinking_delta",thinking:B.delta}});else if(B.type==="response.output_text.delta"&&typeof B.delta=="string")G()!=="text"&&z("text",{type:"text",text:""}),R+=1,I+=B.delta,p("content_block_delta",{index:J,delta:{type:"text_delta",text:B.delta}});else if(K){let{call:Xt}=T.add(K);(G()!=="tool"||K.tool_index!==V)&&(V=K.tool_index,z("tool",{type:"tool_use",id:Xt.id??`call_${K.tool_index}`,name:Xt.name??"",input:{}})),K.delta&&p("content_block_delta",{index:J,delta:{type:"input_json_delta",partial_json:K.delta}})}else if(B.type==="error"){r.streamError=!0,p("error",{error:{type:"api_error",message:JSON.stringify(B)}}),n.end();return}}if(n.destroyed)return;let pe=ee(N),fe=xe(pe),ue=_e(d,T.size+fe.length,I);if(ue){r.streamError=!0,p("error",{error:{type:"api_error",message:ye(c,ue)}}),n.end();return}q();let re=[];if(T.size===0)try{re=Kt(pe)}catch(B){r.streamError=!0,p("error",{error:{type:"api_error",message:String(B instanceof Error?B.message:B)}}),n.end();return}$===0&&re.length===0&&(z("text",{type:"text",text:""}),q()),re.forEach(B=>{let K=$++;p("content_block_start",{index:K,content_block:{...B,input:{}}}),p("content_block_delta",{index:K,delta:{type:"input_json_delta",partial_json:JSON.stringify(B.input??{})}}),p("content_block_stop",{index:K})});let Pe=T.size>0||re.length>0,be=kt(pe);ae(r,pe),p("message_delta",{delta:{stop_reason:Pe?"tool_use":"end_turn"},usage:be?{input_tokens:be.input_tokens,output_tokens:be.output_tokens}:{output_tokens:R}}),p("message_stop",{}),n.end();return}let k="",O="",y=[],v=new de;for await(let f of o.track(m,c,r)){y.push(f),f.type==="response.output_text.delta"&&typeof f.delta=="string"&&(k+=f.delta),f.type==="response.reasoning_text.delta"&&typeof f.delta=="string"&&(O+=f.delta);let R=Se(f);if(R&&v.add(R),f.type==="error"){let I=f.error,$=I?.type==="invalid_request_error";te(n,$?400:502,$?"invalid_request_error":"api_error",I?.message??JSON.stringify(f));return}if(n.destroyed)break}if(n.destroyed)return;let _=ee(y);ae(r,_);let h;try{h=Kt(_),h.length===0&&v.size>0&&(h=Kt({output:v.items()}))}catch(f){te(n,502,"api_error",String(f instanceof Error?f.message:f));return}let S=_e(d,h.length,k);if(S){te(n,502,"api_error",ye(c,S));return}let g=[],b=O||kr(_);b&&g.push({type:"thinking",thinking:b}),(k||h.length===0)&&g.push({type:"text",text:k}),g.push(...h),j(n,200,{id:a,type:"message",role:"assistant",content:g,model:i,stop_reason:h.length>0?"tool_use":"end_turn",usage:kt(_)??{input_tokens:0,output_tokens:0}})}function Fs(t){we(process.stdout,t)}function qs(t){let{clients:e,apiKey:n,identity:o,statusOf:r}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Fs,a=t.observe,l=new ge;return(u,c)=>{let d=new URL(u.url??"/","http://localhost"),m=d.pathname==="/v1/messages"||d.pathname.startsWith("/v1/messages/"),p=(_,h,S,g,b)=>m?te(c,_,g,h):H(c,_,h,S,b),k=Ot(d.pathname),O=d.pathname.startsWith("/partners/"),y=k||O?{id:$e(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,sessionId:null,timing:null}:null;y&&(c.setHeader(kn,y.id),c.once("close",()=>{let _=En({turn:y,method:u.method??"",path:d.pathname,res:c});i(An(_)),a?.(_),hr({record:_,ledger:t.ledger??null,req:u})}));let v=()=>Rn(d.pathname,y);(async()=>{if(u.method==="GET"&&d.pathname==="/healthz"){j(c,200,{ok:!0});return}if(u.method==="GET"&&d.pathname==="/stats"){j(c,200,o?{identity:o,...l.snapshot()}:l.snapshot());return}if(n&&(u.headers.authorization??"")!==`Bearer ${n}`){p(401,"invalid local proxy api key","authentication_error","authentication_error");return}let _=d.pathname===ir?"canonical":d.pathname===Jt?"huggingface":null;if(_){if(u.method!=="POST"){p(405,`${d.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let b=t.usage;if(!b){p(501,`${d.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 f=b.authorize(u),R;try{R=await _r(u,ar)}catch(A){if(A instanceof Xe){p(413,A.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let I=A=>b.lookup(f,A),$;try{if(_==="canonical"){let A=ur(R),G=await I(A);bt(G,A),$={requests:G}}else $=await dr(R,I)}catch(A){if(A instanceof ce){p(A.status,A.message,"invalid_request_error","invalid_request_error");return}throw A}j(c,200,$);return}if(d.pathname.startsWith("/partners/")){p(404,`no partner adapter for ${u.method} ${d.pathname} \u2014 the partner surface currently carries ${Jt}`,"invalid_request_error","not_found_error");return}let h=await s(u);if(y&&(y.org=h.tenant??null),u.method==="GET"&&d.pathname==="/v1/models"){if(d.searchParams.get("format")==="openrouter"){if(!h.openRouterModels){p(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}j(c,200,await h.openRouterModels());return}j(c,200,await h.listModels());return}if(u.method==="GET"&&d.pathname===jn){if(!h.listImageModels){p(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}j(c,200,await h.listImageModels());return}if(qn(d.pathname)){if(!h.supportsImages){p(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${d.pathname}`,"not_implemented","not_implemented_error");return}let b={clients:h,imageModels:h.supportsImages,stats:l,turn:v()};d.pathname===yt?await Qn(u,c,b):await Xn(u,c,b);return}if(rr(d.pathname)){if(!h.supportsSpeech){p(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Ve}`,"not_implemented","not_implemented_error");return}let b={clients:h,speechModels:h.supportsSpeech,stats:l,turn:v()};await or(u,c,b);return}if(u.method!=="POST"){p(404,`no route for ${u.method} ${d.pathname}`,"invalid_request_error","not_found_error");return}let S;try{S=await _r(u)}catch(b){if(b instanceof Xe){p(413,b.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let g=Buffer.byteLength(JSON.stringify(S));if(d.pathname==="/v1/responses"){l.request("responses",g,g),await Ts(S,h,Ue(h),c,l,v());return}if(d.pathname==="/v1/chat/completions"){l.request("chat_completions",g,g),await Ps(S,h,c,l,v());return}if(d.pathname==="/v1/systemone"){l.request("systemone",g,g),await $s(S,h,c,l,v());return}if(d.pathname==="/v1/messages"){l.request("messages",g,g),await Bs(S,h,c,l,v());return}if(d.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",g,g),te(c,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}p(404,`no route for POST ${d.pathname}`,"invalid_request_error","not_found_error")})().catch(_=>{let h=String(_ instanceof Error?_.message:_);if(!c.headersSent){let S=r?.(_)??null;if(S){p(S.status,h,S.openaiType,S.anthropicType);return}if(_ instanceof St.SessionAllocationError){let g=lt(_.code);if(g){let b=_.retryAfterSeconds??(g.status===429?30:void 0);b!==void 0&&c.setHeader("Retry-After",String(b)),p(g.status,Ut(g,_.code??void 0),g.openaiType,g.anthropicType,g.code);return}}if(_ instanceof St.SessionFailedError){let g=ct(_);if(g){let b=g.status===429?30:void 0;b!==void 0&&c.setHeader("Retry-After",String(b)),p(g.status,Ut(g,_.status.sessionId?`session ${_.status.sessionId}`:void 0),g.openaiType,g.anthropicType,g.code);return}}if(_ instanceof Ie){p(502,h,"upstream_error","api_error");return}p(500,h,"proxy_error","api_error","proxy_error");return}y&&(y.streamError=!0),c.destroyed||(m?c.write(`event: error
41
49
  data: ${JSON.stringify({type:"error",error:{type:"api_error",message:h}})}
42
50
 
43
- `):d.write(`data: ${JSON.stringify({error:{message:h,type:"upstream_error"}})}
51
+ `):c.write(`data: ${JSON.stringify({error:{message:h,type:"upstream_error"}})}
44
52
 
45
- `)),d.end()})}}function Nt(n){let{clients:e,apiKey:t}=n,o=(0,Lt.createServer)(Ln(n)),s=Ct(o,{clients:e,apiKey:t,statusOf:n.statusOf}),i=o.close.bind(o);return o.close=(r=>(s.close(),i(r))),Pe(o,{clients:e,apiKey:t}),o}var Ft=require("ws");var Bt=require("crypto");function g(n){return`${n}_${(0,Bt.randomUUID)().replace(/-/g,"").slice(0,24)}`}var De=4*1024*1024,et=8*1024*1024,Fe=512,Ve=20*1024*1024;function M(n,e,t){return{type:"invalid_request_error",code:n,message:e,param:t??null}}function Re(n,e){return{type:"server_error",code:n,message:e}}function A(n){return{type:"error",event_id:g("event"),error:n}}function tt(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var _=class extends Error{constructor(t,o,s="invalid_value"){super(t);this.param=o;this.code=s;this.name="SessionUpdateError"}param;code},$n={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},Nn={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Un={format:!0,voice:!0,speed:!0};function Ut(n,e){let t=n;if(!t||typeof t!="object"||t.type!=="audio/pcm"||t.rate!==void 0&&t.rate!==24e3)throw new _(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function xe(n,e,t){if(!n||typeof n!="object"||Array.isArray(n))throw new _("session must be an object","session","invalid_request");let o=n,s=Object.keys(o).filter(r=>!(r in $n));if(s.length>0)throw new _(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");let i={...e,outputModalities:[...e.outputModalities]};for(let[r,a]of Object.entries(o))switch(r){case"model":if(a!==null&&typeof a!="string")throw new _("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new _("instructions must be a string or null","instructions");i.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new _("modalities must be a non-empty array","modalities");let d=[];for(let u of a){if(u!=="text"&&u!=="audio")throw new _(`modality ${JSON.stringify(u)} is not "text" or "audio"`,"modalities");if(u==="audio"&&!t.voice)throw new _('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");d.includes(u)||d.push(u)}i.outputModalities=d;break}case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new _("voice must be a string or null","voice");if(!t.voice)throw new _("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new _(`${r} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,r);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new _("temperature must be a finite number or null","temperature");i.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new _(`${r} must be a positive integer, "inf" or null`,r);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new _("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new _("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!t.turns)throw new _("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let d=a;if(!d||typeof d!="object"||Array.isArray(d))throw new _("turn_detection must be an object or null","turn_detection");let u=String(d.type??"");if(u!=="server_vad"&&u!=="semantic_vad")throw new _(`turn_detection.type ${JSON.stringify(d.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");i.turnDetection={createResponse:d.create_response!==!1,interruptResponse:d.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!t.turns)throw new _("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 _("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new _(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new _("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let d=a;if(!d||typeof d!="object"||Array.isArray(d))throw new _("audio must be an object or null","audio");if(d.input!==void 0&&d.input!==null){let u=d.input;if(!u||typeof u!="object"||Array.isArray(u))throw new _("audio.input must be an object","audio.input");for(let c of Object.keys(u))if(!(c in Nn))throw new _(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(u.format!==void 0&&Ut(u.format,"audio.input.format"),u.transcription!==null&&u.transcription!==void 0){let c=xe({input_audio_transcription:u.transcription},i,t);i.inputAudioTranscription=c.inputAudioTranscription}if(u.turn_detection!==null&&u.turn_detection!==void 0){let c=xe({turn_detection:u.turn_detection},i,t);i.turnDetection=c.turnDetection}if(u.noise_reduction!==null&&u.noise_reduction!==void 0)throw new _("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(d.output!==void 0&&d.output!==null){let u=d.output;if(!u||typeof u!="object"||Array.isArray(u))throw new _("audio.output must be an object","audio.output");for(let c of Object.keys(u))if(!(c in Un))throw new _(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(u.format!==void 0&&Ut(u.format,"audio.output.format"),u.speed!==void 0)throw new _("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(u.voice!==void 0)if(u.voice===null)delete i.voice;else{if(typeof u.voice!="string")throw new _("audio.output.voice must be a string or null","audio.output.voice");if(!t.voice)throw new _("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=u.voice}u.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function je(n,e){return{id:e,object:"realtime.session",model:n.model??null,instructions:n.instructions??"",modalities:[...n.outputModalities],voice:n.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:n.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:n.turnDetection?{type:"server_vad",create_response:n.turnDetection.createResponse,interrupt_response:n.turnDetection.interruptResponse}:null,temperature:n.temperature??null,max_response_output_tokens:n.maxOutputTokens??"inf",tool_choice:n.toolChoice??"auto",tools:n.tools??[],metadata:n.metadata??null}}function nt(n,e){let t=n;if(!t||typeof t!="object")throw new _("item must be an object","item","invalid_request");if(t.type==="function_call_output"){if(typeof t.call_id!="string"||typeof t.output!="string")throw new _("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof t.id=="string"?t.id:g("item"),type:"function_call_output",callId:t.call_id,output:t.output}}if(t.type==="message"){let o=t.role;if(o!=="user"&&o!=="assistant"&&o!=="system")throw new _('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(t.content))throw new _("message item content must be an array","item.content","invalid_request");let s=[];for(let i of t.content){let r=i;if(!r||typeof r!="object")throw new _("content part must be an object","item.content","invalid_request");if(r.type==="input_text"||o==="assistant"&&r.type==="output_text"){if(typeof r.text!="string")throw new _(`${String(r.type)} part requires string text`,"item.content.text","invalid_request");s.push({type:r.type,text:r.text});continue}if(r.type==="input_audio"){if(!e)throw new _("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof r.audio!="string")throw new _("input_audio part requires base64 audio","item.content.audio","invalid_request");s.push({type:"input_audio",...typeof r.transcript=="string"?{transcript:r.transcript}:{}});continue}throw new _(`content part type ${String(r.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof t.id=="string"?t.id:g("item"),type:"message",role:o,content:s}}throw new _(`item type ${String(t.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function ot(n){let e=[],t=!1;for(let o of n){if(o.type==="function_call"){e.push({type:"function_call",call_id:o.callId,name:o.name,arguments:o.arguments??"{}"});continue}if(o.type==="function_call_output"){e.push({type:"function_call_output",call_id:o.callId,output:o.output});continue}let s=[];for(let i of o.content??[]){if(i.type==="input_text"||i.type==="output_text"){s.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let r=i.transcript;if(typeof r=="string"&&r.trim().length>0){s.push({type:"input_text",text:r});continue}t=!0;continue}}e.push({role:o.role,content:s})}return{input:e,sawAudioOnlyItem:t}}var Bn=1001,Dn=1011,Dt=n=>n.slice(0,120),Fn=/^[A-Za-z0-9+/=]*$/,le=class{id=g("conn");ws;binding;onClosed;config=tt();sessionId=g("sess");conversationId=g("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnTranscript={open:!1,text:""};lastCommittedTranscript=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.ws.on("message",t=>{this.onMessage(t)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:g("event"),session:je(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:g("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let t=this.binding.turns;(async()=>{try{for await(let o of t()){if(this.closed||e.signal.aborted)return;this.onTurnEvent(o)}}catch(o){!this.closed&&!e.signal.aborted&&this.send(A(Re("turn_lane_fault",`the backend turn/transcript lane failed: ${o instanceof Error?o.message:String(o)}`)))}})()}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let t=typeof e.text=="string"?e.text:"";if(t.length===0)return;this.turnTranscript.open=!0,this.turnTranscript.text+=t,this.config.inputAudioTranscription&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:g("event"),item_id:"input_audio_turn",content_index:0,delta:t});return}case"turn_start":{this.turnTranscript={open:!0,text:this.turnTranscript.text},this.send({type:"input_audio_buffer.speech_started",event_id:g("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 t=this.turnTranscript.text.trim(),o=t.length>0?t:null;this.turnTranscript={open:!1,text:""},this.lastCommittedTranscript=o,this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let s=g("item"),i=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...o!==null?{transcript:o}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:g("event"),previous_item_id:i,item_id:s}),this.send({type:"conversation.item.created",event_id:g("event"),previous_item_id:i,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:g("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.inputAudioTranscription&&o!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:g("event"),item_id:s,content_index:0,transcript:o}),this.config.turnDetection?.createResponse&&!this.inFlight&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let t;try{t=e.toString()}catch{this.fail(M("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(t,"utf8")>De){this.fail(M("frame_too_large",`frame exceeds the ${De}-byte limit`),"invalid_frame");return}let o;try{o=JSON.parse(t)}catch{this.fail(M("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof o.type!="string"||o.type.length===0){this.fail(M("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(o)}catch(s){let i=s;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(A({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}this.fail(Re(null,s instanceof Error?s.message:String(s)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=xe(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0}),this.send({type:"session.updated",event_id:g("event"),session:je(this.config,this.sessionId)});return;case"conversation.item.create":{let t=nt(e.item,this.binding.voice),o=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(t),this.send({type:"conversation.item.created",event_id:g("event"),previous_item_id:o,item:this.itemToProtocol(t)});return}case"conversation.item.delete":{let t=this.items.findIndex(o=>o.id===e.item_id);if(t<0){this.send(A(M("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(t,1),this.send({type:"conversation.item.deleted",event_id:g("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let t=this.items.find(o=>o.id===e.item_id);if(!t){this.send(A(M("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:g("event"),item:this.itemToProtocol(t)});return}case"conversation.item.truncate":{let t=this.items.find(o=>o.id===e.item_id);if(!t||t.type!=="message"||t.role!=="assistant"){this.send(A(M("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}t.truncated=!0,this.send({type:"conversation.item.truncated",event_id:g("event"),item_id:t.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(A(M("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Fn.test(e.audio)){this.send(A(M("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioBytes.length+t>Ve){this.send(A(M("buffer_full",`uncommitted input audio exceeds the ${Ve}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=t;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.send({type:"input_audio_buffer.cleared",event_id:g("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(A(M("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let t=this.takeTurnTranscript();t===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let o=g("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...t!==null?{transcript:t}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:g("event"),previous_item_id:s,item_id:o}),this.send({type:"conversation.item.created",event_id:g("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])});return}case"output_audio_buffer.clear":{this.send(A(M("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(A(M("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(A(M("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,t=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(t.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)");t.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(A({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"})))}upstreamStream(e,t){let o=this.binding.session;if(o&&typeof o.sendResponseCreate=="function")return o.sendResponseCreate(e,e.input??[],t);let s=this.binding.clients;if(s&&typeof s.createResponse=="function")return s.createResponse(e);throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(A(M("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let t=e??{};if(t.modalities!==void 0){if(!Array.isArray(t.modalities)||t.modalities.some(v=>v!=="text"&&v!=="audio")){this.send(A(M("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(t.modalities.includes("audio")&&!this.ensureVoice())return}if(t.input!==void 0){this.send(A(M("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 o=g("req"),s=`resp_${o}`;this.activeResponseId=s;let i=this.items.length,{input:r,sawAudioOnlyItem:a}=ot(this.items),d=typeof t.instructions=="string"?t.instructions:this.config.instructions,u=typeof t.temperature=="number"?t.temperature:this.config.temperature,c=t.max_output_tokens??this.config.maxOutputTokens,l=c==="inf"||c===void 0?void 0:c,f=t.tools!==void 0?t.tools:this.config.tools,h=t.tool_choice!==void 0?t.tool_choice:this.config.toolChoice,w={input:r,stream:!0,...this.config.model?{model:this.config.model}:{},...d!==void 0?{instructions:d}:{},...u!==void 0?{temperature:u}:{},...l!==void 0?{max_output_tokens:l}:{},...f!==void 0?{tools:f}:{},...h!==void 0?{tool_choice:h}:{}};for(let v of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(v);this.inFlight=(async()=>{let v=[],y=T=>{this.responseFlushed?this.send(T):v.push(T)},x=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:g("event"),response:this.responseObject(s,"in_progress")}),this.send({type:"response.in_progress",event_id:g("event"),response:this.responseObject(s,"in_progress")});for(let T of v)this.send(T);v.length=0,this.responseFlushed=!0}},R={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},U=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let T;try{T=this.upstreamStream(w,o)}catch(N){this.emitUpstreamFault(N,s);return}try{for await(let N of T){if(this.cancelled)break;let p=N;if(p.type==="error"){let k=this.upstreamErrorBody(p);this.responseFlushed?this.send(A(k)):this.send({type:"response.failed",event_id:g("event"),response:this.failedResponse(s,k)});return}if(p.type==="response.output_text.delta"&&typeof p.delta=="string"){x(),R.messageOpen||(this.beginMessageItem(s,R.nextOutputIndex++),R.messageOpen=!0),y({type:"response.output_text.delta",event_id:g("event"),item_id:`${s}_msg_0`,response_id:s,output_index:0,content_index:0,delta:p.delta}),R.messageText+=p.delta;continue}if(p.type==="response.function_call_arguments.delta"){x();let k=typeof p.delta=="string"?p.delta:"",L=typeof p.call_id=="string"&&p.call_id.length>0?p.call_id:`${s}_fc_${R.nextOutputIndex}`,I=R.tools.get(L);if(!I){let D=typeof p.name=="string"&&p.name.length>0?p.name:void 0;I={outputIndex:R.nextOutputIndex++,name:D,args:""},R.tools.set(L,I),y({type:"response.output_item.added",event_id:g("event"),response_id:s,output_index:I.outputIndex,item:{id:L,object:"realtime.item",type:"function_call",call_id:L,name:D??"",arguments:"",status:"in_progress"}})}typeof p.name=="string"&&p.name.length>0&&(I.name=p.name),I.args+=k,y({type:"response.function_call_arguments.delta",event_id:g("event"),item_id:L,response_id:s,output_index:I.outputIndex,call_id:L,name:I.name??"",delta:k});continue}if(p.type==="response.completed"){U=p.response??null;continue}}}catch(N){this.emitUpstreamFault(N,s);return}if(this.cancelled)return;this.closeOpenItems(s,R,i),x(),this.send({type:"response.done",event_id:g("event"),response:this.doneResponse(s,i,U)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,t){if(this.cancelled)return;if(this.activeResponseId!==e){!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(A({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:g("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:g("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let o=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:g("event"),item_id:o,response_id:e,output_index:0,content_index:0,delta:t})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,t){let o=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:g("event"),response_id:e,output_index:t,item:{id:o,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:g("event"),item_id:o,response_id:e,output_index:t,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let t=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:g("event"),response_id:e,output_index:0,item:{id:t,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:g("event"),item_id:t,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,t,o){if(t.messageOpen||this.messageItemOpenForAudio){let s=`${e}_msg_0`,i=this.messageItemOpenForAudio;i&&this.send({type:"response.output_audio.done",event_id:g("event"),item_id:s,response_id:e,output_index:0,content_index:0}),t.messageText.length>0&&this.send({type:"response.output_text.done",event_id:g("event"),item_id:s,response_id:e,output_index:0,content_index:0,text:t.messageText}),this.send({type:"response.content_part.done",event_id:g("event"),item_id:s,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:""}:{type:"output_text",text:t.messageText}});let r=[];i&&r.push({type:"output_audio"}),t.messageText.length>0&&r.push({type:"output_text",text:t.messageText});let a={id:s,type:"message",role:"assistant",content:r};this.pushItem(a),this.send({type:"response.output_item.done",event_id:g("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[s,i]of t.tools){let r=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:g("event"),item_id:s,response_id:e,output_index:i.outputIndex,call_id:s,name:i.name??"",arguments:r});let a={id:s,type:"function_call",callId:s,name:i.name,arguments:r};this.pushItem(a),this.send({type:"response.output_item.done",event_id:g("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,t,o){return{id:e,object:"realtime.response",status:t,conversation_id:this.conversationId,usage:null,...o??{}}}failedResponse(e,t){return this.responseObject(e,"failed",{status_details:{error:{code:t.code,message:t.message}}})}doneResponse(e,t,o){let s=o&&typeof o.usage=="object"&&o.usage!==null?o.usage:null,i=[];for(let r=t;r<this.items.length;r++)i.push(this.itemToProtocol(this.items[r]));return this.responseObject(e,"completed",{output:i,usage:s?{input_tokens:typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0,output_tokens:typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0,total_tokens:typeof s.total_tokens=="number"&&Number.isFinite(s.total_tokens)?s.total_tokens:(typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0)+(typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.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 t=e.error,o=t&&typeof t.message=="string"?t.message:JSON.stringify(e);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:o}}emitUpstreamFault(e,t){if(this.cancelled)return;let o=Re(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(A(o)):this.send({type:"response.failed",event_id:g("event"),response:this.failedResponse(t,o)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(A(M("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let t=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:g("event"),response:this.responseObject(t,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Fe&&(this.items.shift(),this.send(A({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Fe} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let t={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...t,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...t,type:"function_call_output",call_id:e.callId,output:e.output};let o=(e.content??[]).map(s=>s.type==="input_text"||s.type==="output_text"?{type:s.type,text:s.text}:s.type==="input_audio"?{type:"input_audio",...s.transcript?{transcript:s.transcript}:{}}:{type:"output_audio",transcript:s.transcript??""});return{...t,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:o}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>et){this.ws.close(Bn,Dt("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,t){this.send(A(e)),this.ws.close(Dn,Dt(t)),this.teardown(t)}teardown(e){if(!this.closed){this.closed=!0,this.turnLaneAbort?.abort(),this.turnLaneAbort=null,this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null;try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this),Vn(this.id,e)}}},st=[];function Vn(n,e){st.push({id:n,reason:e}),st.length>256&&st.shift()}var qe="/v1/realtime",jn=n=>n.slice(0,120);function qn(n,e,t){let o=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";n.write(`HTTP/1.1 ${e} ${o}\r
46
- Connection: close\r
47
- Content-Type: text/plain\r
48
- \r
49
- ${jn(t)}\r
50
- `),n.destroy()}function it(n,e){let t=new Ft.WebSocketServer({noServer:!0}),o=new Set;return n.on("upgrade",(s,i,r)=>{if(new URL(s.url??"/","http://localhost").pathname!==qe)return;o.add(i),i.on("close",()=>{o.delete(i)});let d=c=>{let l=c,f=l.session!=null&&typeof l.session.sendResponseCreate=="function",h=l.clients!=null&&typeof l.clients.createResponse=="function";if(!f&&!h)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((w,v)=>{t.handleUpgrade(s,i,r,y=>{try{new le({ws:y,binding:c}),w()}catch(x){v(x)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(s).then(d).catch(c=>{let l=c&&typeof c=="object"&&typeof c.status=="number"?c.status:502,f=c instanceof Error?c.message:String(c);i.destroyed||qn(i,l,f)}).finally(()=>{o.delete(i)})}),async()=>{let s=Date.now()+5e3;for(;o.size>0&&Date.now()<s;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>t.close(()=>i()))}}0&&(module.exports={GEMINI_LIVE_PATH,OPENAI_REALTIME_PATH,OpenAIRealtimeConnection,ResumptionRegistry,SessionGoneError,UnknownModelError,VIDEO_OUT_SETUP_KEY,attachGeminiLive,attachOpenAIRealtime,createOpenAIProxy,serveGeminiLiveSocket});
53
+ `)),c.end()})}}function Rr(t){let{clients:e,apiKey:n}=t,o=(0,vr.createServer)(qs(t)),r=Cn(o,{clients:e,apiKey:n,statusOf:t.statusOf}),s=Fe(o,{resolver:ht(e,n)}),i=o.close.bind(o);return o.close=(a=>(r.close(),s(),i(a))),at(o,{clients:e,apiKey:n}),o}0&&(module.exports={GEMINI_LIVE_PATH,OPENAI_REALTIME_PATH,OpenAIRealtimeConnection,ResumptionRegistry,SessionGoneError,UnknownModelError,VIDEO_OUT_SETUP_KEY,attachGeminiLive,attachOpenAIRealtime,createOpenAIProxy,fixedClientsResolver,realtimeBindingFor,realtimeModelOf,serveGeminiLiveSocket});