@urun-sh/openai 0.6.42 → 0.6.43

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 (62) hide show
  1. package/dist/{ResponsesClient-gfg7qUoE.d.ts → ResponsesClient-2EsjJUz1.d.ts} +1 -1
  2. package/dist/{ResponsesClient-6QsC7NPJ.d.cts → ResponsesClient-BIcQ6p6Z.d.cts} +1 -1
  3. package/dist/{chunk-XKCWX72M.js → chunk-27HP3RMZ.js} +1 -1
  4. package/dist/chunk-2NKCALKY.js +22 -0
  5. package/dist/chunk-2RO722HS.js +2 -0
  6. package/dist/chunk-7DUSLXPG.js +1 -0
  7. package/dist/chunk-BFIKVTQB.js +1 -0
  8. package/dist/{chunk-4NMMWAKD.js → chunk-FF3RWDFM.js} +1 -1
  9. package/dist/chunk-GDH2D3S6.js +1 -0
  10. package/dist/chunk-J3KCHTSA.js +6 -0
  11. package/dist/{chunk-QTHFMDZY.js → chunk-JMSVHETI.js} +1 -1
  12. package/dist/{chunk-L4QBHSVY.js → chunk-MJSK6W3W.js} +1 -1
  13. package/dist/chunk-MOX5FG2R.js +1 -0
  14. package/dist/chunk-YRBUHHI3.js +2 -0
  15. package/dist/chunk-ZCF6EV4Y.js +65 -0
  16. package/dist/{composite-B-F2J0NK.d.cts → composite-BoS9-74g.d.cts} +320 -4
  17. package/dist/{composite-B--rGI5m.d.ts → composite-D4_XPSas.d.ts} +91 -4
  18. package/dist/gemini-live.cjs +2 -2
  19. package/dist/gemini-live.d.cts +4 -4
  20. package/dist/gemini-live.d.ts +4 -4
  21. package/dist/gemini-live.js +1 -1
  22. package/dist/hosted/bin.cjs +44 -43
  23. package/dist/hosted/bin.js +1 -1
  24. package/dist/hosted/index.cjs +43 -42
  25. package/dist/hosted/index.d.cts +54 -10
  26. package/dist/hosted/index.d.ts +11 -5
  27. package/dist/hosted/index.js +1 -1
  28. package/dist/index.cjs +1 -1
  29. package/dist/index.d.cts +4 -4
  30. package/dist/index.d.ts +4 -4
  31. package/dist/index.js +1 -1
  32. package/dist/pi-extension/index.cjs +7 -7
  33. package/dist/pi-extension/index.d.cts +2 -2
  34. package/dist/pi-extension/index.d.ts +2 -2
  35. package/dist/pi-extension/index.js +1 -1
  36. package/dist/pi-extension/standalone.cjs +55 -55
  37. package/dist/pooler/bin.cjs +40 -41
  38. package/dist/pooler/bin.js +39 -40
  39. package/dist/proxy/cli.cjs +54 -53
  40. package/dist/proxy/cli.js +1 -1
  41. package/dist/proxy/conformance-probe.cjs +1 -1
  42. package/dist/proxy/conformance-probe.js +1 -1
  43. package/dist/proxy/index.cjs +33 -32
  44. package/dist/proxy/index.d.cts +37 -214
  45. package/dist/proxy/index.d.ts +17 -65
  46. package/dist/proxy/index.js +1 -1
  47. package/dist/{translator-BqpmZ-vh.d.ts → translator-BemK1Of5.d.ts} +1 -1
  48. package/dist/{translator-Dox25ky9.d.cts → translator-PsmsZT62.d.cts} +1 -1
  49. package/dist/{types-CHPtJx6d.d.cts → types-CxWQ84Ew.d.cts} +5 -0
  50. package/dist/{types-CHPtJx6d.d.ts → types-CxWQ84Ew.d.ts} +2 -0
  51. package/dist/{video-out-DnCKUUO2.d.cts → video-out-DPLqpGbQ.d.cts} +17 -3
  52. package/dist/{video-out-REmiQMBJ.d.ts → video-out-DkMqKSOi.d.ts} +6 -2
  53. package/package.json +2 -2
  54. package/dist/chunk-7KRHHEKZ.js +0 -1
  55. package/dist/chunk-G7CSAISC.js +0 -1
  56. package/dist/chunk-GX243AIV.js +0 -1
  57. package/dist/chunk-HPUX2H65.js +0 -6
  58. package/dist/chunk-IFYB6QUQ.js +0 -64
  59. package/dist/chunk-KKCUIOL4.js +0 -1
  60. package/dist/chunk-OZ7HE3VG.js +0 -23
  61. package/dist/chunk-QNJKRB7Q.js +0 -2
  62. package/dist/chunk-Z3QCHKJB.js +0 -1
@@ -1,64 +1,65 @@
1
- "use strict";var No=Object.create;var Et=Object.defineProperty;var Uo=Object.getOwnPropertyDescriptor;var Do=Object.getOwnPropertyNames;var Fo=Object.getPrototypeOf,qo=Object.prototype.hasOwnProperty;var Bo=(t,e)=>{for(var n in e)Et(t,n,{get:e[n],enumerable:!0})},qn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Do(e))!qo.call(t,o)&&o!==n&&Et(t,o,{get:()=>e[o],enumerable:!(r=Uo(e,o))||r.enumerable});return t};var Bn=(t,e,n)=>(n=t!=null?No(Fo(t)):{},qn(e||!t||!t.__esModule?Et(n,"default",{value:t,enumerable:!0}):n,t)),jo=t=>qn(Et({},"__esModule",{value:!0}),t);var xa={};Bo(xa,{GEMINI_LIVE_PATH:()=>$t,OPENAI_REALTIME_PATH:()=>gt,OpenAIRealtimeConnection:()=>qe,ResumptionRegistry:()=>Ge,SessionGoneError:()=>Y,UnknownModelError:()=>F,VIDEO_OUT_SETUP_KEY:()=>Se,attachGeminiLive:()=>Nt,attachOpenAIRealtime:()=>yt,createOpenAIProxy:()=>Lo,fixedClientsResolver:()=>Gt,realtimeBindingFor:()=>In,realtimeModelOf:()=>En,serveGeminiLiveSocket:()=>ur});module.exports=jo(xa);var To=require("http");var sr=require("crypto"),ar=require("ws");var Go=require("crypto");var at=class extends Error{};var ut="/partners/openrouter/models";var It=class extends Error{name="ModelCreatedError"};var F=class extends Error{},Y=class extends Error{};var ln=256e3;var Ot=require("@urun-sh/core");var jn="urun.videoOut.v2-ws";var $t="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Wo=1007,Jn=1008,ke=1011,Mt=1008,S=class extends Error{constructor(n,r=Wo){super(n);this.closeCode=r}closeCode},Z=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Tt=["setup","clientContent","realtimeInput","toolResponse"];function Vn(t){let e;try{e=JSON.parse(t)}catch{throw new S("client message is not valid JSON")}let n=Z(e);if(!n)throw new S("client message must be a JSON object");let r=Tt.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Tt.includes(a));if(o.length>0)throw new S(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Tt.join(", ")}`);if(r.length!==1)throw new S(`client message must contain exactly one of ${Tt.join(", ")} (got ${r.length})`);let i=r[0],s=Z(n[i]);if(!s)throw new S(`"${i}" must be a JSON object`);return{kind:i,[i]:s}}function Gn(t,e){if(typeof t=="string")return t;let n=Z(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new S(`${e}: expected a Content with a parts array`);let o=[];for(let i of r){let s=Z(i);if(s&&typeof s.text=="string"){o.push(s.text);continue}throw s&&(s.inlineData!==void 0||s.fileData!==void 0)?new S(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):s&&(s.functionCall!==void 0||s.functionResponse!==void 0)?new S(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new S(`${e}: unsupported part ${JSON.stringify(i)}`)}return o.join(`
2
- `)}var Ko={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Se="urun.videoOut";function Wn(t){return{framing:jn,codec:t}}function Kn(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Se]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var zo={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Yo=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Se],Hn=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Xo(t){let e=Z(t);if(!e)throw new S("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new S(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=Z(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new S("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new S(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new S("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!Hn.includes(e.activityHandling))throw new S(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Hn.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Qo=["temperature","maxOutputTokens","responseModalities"];function zn(t){for(let[d,p]of Object.entries(zo))if(t[d]!==void 0)throw new S(p);for(let d of Object.keys(t))if(!Yo.includes(d))throw new S(`unsupported setup field "${d}"`);if(typeof t.model!="string"||t.model.length===0)throw new S('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,i=Z(t.generationConfig);if(t.generationConfig!==void 0&&!i)throw new S("setup.generationConfig must be an object");if(i){for(let d of Object.keys(i))if(!Qo.includes(d))throw new S(`unsupported generationConfig field "${d}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new S("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new S("generationConfig.maxOutputTokens must be a number");r=i.maxOutputTokens}if(i.responseModalities!==void 0){let d=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let p of d){let m=String(p).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="TEXT")throw new S(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let s=[];t.systemInstruction!==void 0&&s.push({role:"system",content:Gn(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new S("setup.tools must be an array");a=[];for(let d of t.tools){let p=Z(d);if(!p)throw new S("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new S(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new S("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let f=Z(m);if(!f||typeof f.name!="string")throw new S("functionDeclarations entries require a string name");a.push({type:"function",name:f.name,description:f.description,parameters:f.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let d=Z(t.sessionResumption);if(!d)throw new S("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(d))if(p!=="handle")throw new S(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(d.handle!==void 0&&(typeof d.handle!="string"||d.handle.length===0))throw new S("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof d.handle=="string"?d.handle:null}}let l=t.realtimeInputConfig===void 0?Ko:Xo(t.realtimeInputConfig),c=!1;if(t[Se]!==void 0){if(!Z(t[Se]))throw new S(`setup["${Se}"] must be an object (the v1 opt-in is {})`);c=!0}return{model:e,systemItems:s,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:u,videoOut:c}}function Yn(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Xn(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Qn(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new S(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new S("clientContent.turns must be an array");let n=[];for(let r of e){let o=Z(r);if(!o)throw new S("clientContent.turns entries must be Content objects");let i=o.role===void 0?"user":String(o.role).toLowerCase();if(i!=="user"&&i!=="model")throw new S(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:i==="model"?"assistant":"user",content:Gn(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Pt=16e3,Zn=24e3,Zo=`audio/pcm;rate=${Zn}`,er=Buffer.alloc(960).toString("base64");function ei(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),i=e/n,s=t.length-1;for(let a=0;a<r;a++){let u=a*i,l=Math.floor(u);if(l>=s){o[a]=t[s];continue}let c=u-l;o[a]=Math.round(t[l]+(t[l+1]-t[l])*c)}return o}function ti(t){let e=Z(t);if(!e)throw new S("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new S(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new S("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new S("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function ni(t){let e=Z(t);if(!e)throw new S("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new S(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==Pt)throw new S(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Pt} Hz (audio/pcm;rate=${Pt})`);if(typeof e.data!="string"||e.data.length===0)throw new S("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new S(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let s=0;s<o.length;s++)o[s]=r.readInt16LE(s*2);let i=ei(o,Pt,Zn);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function tr(t){if(t.mediaChunks!==void 0)throw new S('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new S("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",i=Z(t[o]);if(!i||Object.keys(i).length!==0)throw new S(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new S(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new S(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:ni(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:ti(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new S("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new S("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function nr(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new S(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new S("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=Z(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new S("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function rr(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function or(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Zo,data:t}}]}}}}function ir(t){let e=Z(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],i=typeof e.output_text=="string"?e.output_text:"";if(!i)for(let l of n){let c=Z(l);if(!(c?.type!=="message"||!Array.isArray(c.content)))for(let d of c.content){let p=Z(d);p?.type==="output_text"&&typeof p.text=="string"&&(i+=p.text)}}i&&o.push({role:"assistant",content:i});for(let l of n){let c=Z(l);if(c?.type!=="function_call")continue;if(typeof c.call_id!="string"||typeof c.name!="string")throw new S(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,ke);let d=typeof c.arguments=="string"&&c.arguments.length>0?c.arguments:"{}",p;try{p=JSON.parse(d)}catch{throw new S(`upstream function_call arguments are not valid JSON: ${d}`,ke)}r.push({id:c.call_id,name:c.name,args:p}),o.push({type:"function_call",call_id:c.call_id,name:c.name,arguments:d})}let s=[];r.length>0&&s.push({toolCall:{functionCalls:r}}),s.push({serverContent:{generationComplete:!0}});let a=Z(e.usage),u={serverContent:{turnComplete:!0}};if(a){let l={};typeof a.input_tokens=="number"&&(l.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(l.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(l.totalTokenCount=a.total_tokens),Object.keys(l).length>0&&(u.usageMetadata=l)}return s.push(u),{messages:s,assistantItems:o}}var ri=256,Ge=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>ri;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},oi="local",lt=t=>t.slice(0,120),Lt=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof F){this.ws.close(Jn,lt(e.message));return}if(e instanceof Y){this.ws.close(Mt,lt(e.message));return}if(e instanceof S){this.ws.close(e.closeCode,lt(e.message));return}this.ws.close(ke,lt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Vn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new S(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:i}=Qn(n.clientContent);this.transcript.push(...o),i&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=tr(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:er);return}this.transcript.push(...nr(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new S("setup may only be sent once, as the first client message");let n=zn(e),r=n.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new S("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Mt);if(i.model!==n.model)throw new S(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new S("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==i.proxyHandle)throw new S(`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`,Mt);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let i=this.clients.openVideoOut;if(i){let s=await i.call(this.clients,n.model),a=s.onOutputFrame(l=>this.send(Kn(l))),u=s.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[Se]=Wn(s.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new S("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new S("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",ke);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(or(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new S("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new S("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",ke);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new S(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new S("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new S("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,sr.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Yn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Xn(e.timeLeftMs)),this.ws.close(ke,lt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,i=!1;for await(let u of r){if(n.interrupted)break;let l=u;if(l.type==="error")throw new S(`upstream error: ${JSON.stringify(l)}`,ke);if(l.type==="response.completed"){o=l.response,i=!0;continue}let c=rr(l);c&&this.send(c)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new S("upstream produced no response.completed event",ke);let{messages:s,assistantItems:a}=ir(o);this.transcript.push(...a);for(let u of s)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ce=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function ii(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let i=t.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let s=e.searchParams.get("key")??void 0;if(s!==void 0&&s!==""&&r.add(s),r.size>1)throw new Ce(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&s!==void 0&&s!=="")throw new Ce(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new Ce(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Nt(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new ar.WebSocketServer({noServer:!0}),o=new Ge;t.on("upgrade",(s,a,u)=>{let l=new URL(s.url??"/","http://localhost");l.pathname===$t&&(a.on("error",()=>{}),(async()=>{let c=ii(s,l,n),d;if(e.authenticate)d=await e.authenticate(c,s);else{if(e.apiKey!==void 0&&c!==e.apiKey)throw new Ce(401,"invalid local proxy api key");d={clients:e.clients,scope:oi}}r.handleUpgrade(s,a,u,p=>{new Lt(p,d,o)})})().catch(c=>{let d=502;(c instanceof Ce||typeof c=="object"&&c!==null&&"status"in c&&typeof c.status=="number")&&(d=c.status);let p=d===401?"Unauthorized":d===403?"Forbidden":d===502?"Bad Gateway":"Internal Server Error",m=c instanceof Error?c.message:String(c);a.destroyed||(a.write(`HTTP/1.1 ${d} ${p}\r
1
+ "use strict";var Fo=Object.create;var It=Object.defineProperty;var Bo=Object.getOwnPropertyDescriptor;var qo=Object.getOwnPropertyNames;var jo=Object.getPrototypeOf,Ho=Object.prototype.hasOwnProperty;var Jo=(t,e)=>{for(var n in e)It(t,n,{get:e[n],enumerable:!0})},jn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of qo(e))!Ho.call(t,o)&&o!==n&&It(t,o,{get:()=>e[o],enumerable:!(r=Bo(e,o))||r.enumerable});return t};var Hn=(t,e,n)=>(n=t!=null?Fo(jo(t)):{},jn(e||!t||!t.__esModule?It(n,"default",{value:t,enumerable:!0}):n,t)),Vo=t=>jn(It({},"__esModule",{value:!0}),t);var Ea={};Jo(Ea,{GEMINI_LIVE_PATH:()=>Mt,OPENAI_REALTIME_PATH:()=>yt,OpenAIRealtimeConnection:()=>Be,ResumptionRegistry:()=>Ge,SessionGoneError:()=>X,UnknownModelError:()=>H,VIDEO_OUT_SETUP_KEY:()=>ke,attachGeminiLive:()=>Ut,attachOpenAIRealtime:()=>_t,createOpenAIProxy:()=>Do,fixedClientsResolver:()=>Kt,realtimeBindingFor:()=>Tn,realtimeModelOf:()=>On,serveGeminiLiveSocket:()=>dr});module.exports=Vo(Ea);var $o=require("http");var ur=require("crypto"),lr=require("ws");var zo=require("crypto");var at=class extends Error{};var ut="/partners/openrouter/models";var Ot=class extends Error{name="ModelCreatedError"};var H=class extends Error{},X=class extends Error{};var cn=256e3;var Tt=require("@urun-sh/core");var Jn="urun.videoOut.v2-ws";var Mt="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Yo=1007,Gn=1008,xe=1011,Lt=1008,S=class extends Error{constructor(n,r=Yo){super(n);this.closeCode=r}closeCode},Z=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Pt=["setup","clientContent","realtimeInput","toolResponse"];function Wn(t){let e;try{e=JSON.parse(t)}catch{throw new S("client message is not valid JSON")}let n=Z(e);if(!n)throw new S("client message must be a JSON object");let r=Pt.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Pt.includes(a));if(o.length>0)throw new S(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Pt.join(", ")}`);if(r.length!==1)throw new S(`client message must contain exactly one of ${Pt.join(", ")} (got ${r.length})`);let i=r[0],s=Z(n[i]);if(!s)throw new S(`"${i}" must be a JSON object`);return{kind:i,[i]:s}}function Kn(t,e){if(typeof t=="string")return t;let n=Z(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new S(`${e}: expected a Content with a parts array`);let o=[];for(let i of r){let s=Z(i);if(s&&typeof s.text=="string"){o.push(s.text);continue}throw s&&(s.inlineData!==void 0||s.fileData!==void 0)?new S(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):s&&(s.functionCall!==void 0||s.functionResponse!==void 0)?new S(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new S(`${e}: unsupported part ${JSON.stringify(i)}`)}return o.join(`
2
+ `)}var Xo={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},ke="urun.videoOut";function zn(t){return{framing:Jn,codec:t}}function Yn(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[ke]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Qo={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Zo=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",ke],Vn=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function ei(t){let e=Z(t);if(!e)throw new S("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new S(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=Z(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new S("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new S(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new S("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!Vn.includes(e.activityHandling))throw new S(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Vn.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var ti=["temperature","maxOutputTokens","responseModalities"];function Xn(t){for(let[c,p]of Object.entries(Qo))if(t[c]!==void 0)throw new S(p);for(let c of Object.keys(t))if(!Zo.includes(c))throw new S(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new S('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,i=Z(t.generationConfig);if(t.generationConfig!==void 0&&!i)throw new S("setup.generationConfig must be an object");if(i){for(let c of Object.keys(i))if(!ti.includes(c))throw new S(`unsupported generationConfig field "${c}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new S("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new S("generationConfig.maxOutputTokens must be a number");r=i.maxOutputTokens}if(i.responseModalities!==void 0){let c=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let p of c){let f=String(p).toUpperCase();if(f==="AUDIO"){o=!0;continue}if(f!=="TEXT")throw new S(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let s=[];t.systemInstruction!==void 0&&s.push({role:"system",content:Kn(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new S("setup.tools must be an array");a=[];for(let c of t.tools){let p=Z(c);if(!p)throw new S("setup.tools entries must be objects");for(let f of Object.keys(p))if(f!=="functionDeclarations")throw new S(`unsupported tool "${f}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new S("tool.functionDeclarations must be an array");for(let f of p.functionDeclarations){let m=Z(f);if(!m||typeof m.name!="string")throw new S("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=Z(t.sessionResumption);if(!c)throw new S("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new S(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new S("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let l=t.realtimeInputConfig===void 0?Xo:ei(t.realtimeInputConfig),d=!1;if(t[ke]!==void 0){if(!Z(t[ke]))throw new S(`setup["${ke}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:s,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:u,videoOut:d}}function Qn(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Zn(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function er(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new S(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new S("clientContent.turns must be an array");let n=[];for(let r of e){let o=Z(r);if(!o)throw new S("clientContent.turns entries must be Content objects");let i=o.role===void 0?"user":String(o.role).toLowerCase();if(i!=="user"&&i!=="model")throw new S(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:i==="model"?"assistant":"user",content:Kn(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Ct=16e3,tr=24e3,ni=`audio/pcm;rate=${tr}`,nr=Buffer.alloc(960).toString("base64");function ri(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),i=e/n,s=t.length-1;for(let a=0;a<r;a++){let u=a*i,l=Math.floor(u);if(l>=s){o[a]=t[s];continue}let d=u-l;o[a]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function oi(t){let e=Z(t);if(!e)throw new S("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new S(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new S("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new S("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function ii(t){let e=Z(t);if(!e)throw new S("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new S(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==Ct)throw new S(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Ct} Hz (audio/pcm;rate=${Ct})`);if(typeof e.data!="string"||e.data.length===0)throw new S("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new S(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let s=0;s<o.length;s++)o[s]=r.readInt16LE(s*2);let i=ri(o,Ct,tr);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function rr(t){if(t.mediaChunks!==void 0)throw new S('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new S("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",i=Z(t[o]);if(!i||Object.keys(i).length!==0)throw new S(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new S(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new S(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:ii(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:oi(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new S("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new S("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function or(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new S(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new S("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=Z(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new S("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function ir(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function sr(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:ni,data:t}}]}}}}function ar(t){let e=Z(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],i=typeof e.output_text=="string"?e.output_text:"";if(!i)for(let l of n){let d=Z(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=Z(c);p?.type==="output_text"&&typeof p.text=="string"&&(i+=p.text)}}i&&o.push({role:"assistant",content:i});for(let l of n){let d=Z(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new S(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,xe);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new S(`upstream function_call arguments are not valid JSON: ${c}`,xe)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let s=[];r.length>0&&s.push({toolCall:{functionCalls:r}}),s.push({serverContent:{generationComplete:!0}});let a=Z(e.usage),u={serverContent:{turnComplete:!0}};if(a){let l={};typeof a.input_tokens=="number"&&(l.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(l.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(l.totalTokenCount=a.total_tokens),Object.keys(l).length>0&&(u.usageMetadata=l)}return s.push(u),{messages:s,assistantItems:o}}var si=256,Ge=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>si;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},ai="local",lt=t=>t.slice(0,120),Nt=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof H){this.ws.close(Gn,lt(e.message));return}if(e instanceof X){this.ws.close(Lt,lt(e.message));return}if(e instanceof S){this.ws.close(e.closeCode,lt(e.message));return}this.ws.close(xe,lt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Wn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new S(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:i}=er(n.clientContent);this.transcript.push(...o),i&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=rr(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:nr);return}this.transcript.push(...or(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new S("setup may only be sent once, as the first client message");let n=Xn(e),r=n.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new S("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Lt);if(i.model!==n.model)throw new S(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new S("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==i.proxyHandle)throw new S(`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`,Lt);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let i=this.clients.openVideoOut;if(i){let s=await i.call(this.clients,n.model),a=s.onOutputFrame(l=>this.send(Yn(l))),u=s.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[ke]=zn(s.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new S("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new S("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",xe);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(sr(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new S("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new S("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",xe);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new S(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new S("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new S("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,ur.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Qn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Zn(e.timeLeftMs)),this.ws.close(xe,lt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,i=!1;for await(let u of r){if(n.interrupted)break;let l=u;if(l.type==="error")throw new S(`upstream error: ${JSON.stringify(l)}`,xe);if(l.type==="response.completed"){o=l.response,i=!0;continue}let d=ir(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new S("upstream produced no response.completed event",xe);let{messages:s,assistantItems:a}=ar(o);this.transcript.push(...a);for(let u of s)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ce=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function ui(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let i=t.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let s=e.searchParams.get("key")??void 0;if(s!==void 0&&s!==""&&r.add(s),r.size>1)throw new Ce(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&s!==void 0&&s!=="")throw new Ce(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new Ce(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Ut(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new lr.WebSocketServer({noServer:!0}),o=new Ge;t.on("upgrade",(s,a,u)=>{let l=new URL(s.url??"/","http://localhost");l.pathname===Mt&&(a.on("error",()=>{}),(async()=>{let d=ui(s,l,n),c;if(e.authenticate)c=await e.authenticate(d,s);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Ce(401,"invalid local proxy api key");c={clients:e.clients,scope:ai}}r.handleUpgrade(s,a,u,p=>{new Nt(p,c,o)})})().catch(d=>{let c=502;(d instanceof Ce||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",f=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
3
3
  Connection: close\r
4
4
  \r
5
- ${m}\r
6
- `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let s of r.clients)s.close(1001,"server closing");await new Promise((s,a)=>r.close(u=>u===void 0?s():a(u)))})(),i)}function ur(t,e,n=new Ge){new Lt(t,e,n)}var Ie=require("ws");var lr=require("crypto"),dr="Inference-Id";function dt(){return(0,lr.randomUUID)()}function dn(t){return t==="/v1"||t.startsWith("/v1/")}function cr(t,e){if(!dn(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 ct(t){return`resp_${t}`}function pr(t){return`chatcmpl-${t}`}function fr(t){return`msg_${t}`}function de(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function mr(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function hr(t){return`${JSON.stringify(t)}
7
- `}var si=256,ai=128;function oe(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,ai)}var $e=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=si?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,i=performance.now(),s=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-i),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=s-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let u=(performance.now()-(s??i))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},ui=256;function li(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 Me=class extends Error{},We=class{conversations=new Map;thread(e,n){let r=li(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Me(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let i of this.conversations.keys()){if(this.conversations.size<=ui)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},gr=new WeakMap;function pt(t){let e=gr.get(t);return e||(e=new We,gr.set(t,e)),e}function Ke(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function we(t){return t.find(e=>e.type==="response.completed")?.response??null}function ze(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var Ee=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},di=["<tool_call>","<function="];function ci(t){return di.find(e=>t.includes(e))}function Le(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 Ne(t,e,n){if(!(!t||e>0))return ci(n)}function Ye(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function xe(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function pi(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function cn(t,e){let n=pi(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ce=class extends Error{constructor(n,r,o=400,i){super(n);this.code=r;this.status=o;this.param=i}code;status;param};function Xe(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Me?new ce(n.message,"previous_response_not_found",400,"previous_response_id"):new ce(String(n instanceof Error?n.message:n),"invalid_input")}}function yr(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function pn(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ce("instructions must be a string","invalid_instructions");let i=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...i!==void 0?{instructions:i}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...yr(e)!==void 0?{response_format:yr(e)}:{}},o)}async function ft(t){let{body:e,clients:n,store:r,stats:o}=t,i=Xe(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let s=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,l=oe(e);o.model(l);let c=Array.isArray(e.tools)&&e.tools.length>0,d=t.turn,p=await pn(n,e,i,!0,d?de(d):void 0);return{responseId:s,events:gi({events:p,conversation:i,responseId:s,modelKey:l,requestHadTools:c,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function fi(t,e){let n=[...t].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=n.filter(u=>u.type==="message").length===o.length,s=0;return[...n.map(u=>u.type==="message"&&i?hi(o[s++],u):u),...mi(r,n)]}function mi(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),i=e.filter(l=>l.type==="function_call"),s=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=i.length===s,u=new Set(i.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let c=l;return c.type==="message"?!n:c.type==="reasoning"?!r:c.type==="function_call"?!a&&!u.has(o(c)):!0})}function hi(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(n);if(i===void 0)return e;let s={...t};return s.id=e.id,t.role===void 0&&(s.role=e.role),t.status===void 0&&(s.status=e.status),s.content=r.map(a=>n(a)?{...a,text:i.text}:a),s}async function*gi(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:i,remember:s,persist:a,store:u,stats:l}=t,c=[],d=M=>M.response&&typeof M.response=="object"?{...M,response:{...M.response,id:r}}:M,p=`item_${r.slice(5)}`,m=!1,f=!1,k=0;function*R(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let y=[],g=(M,B)=>{y.push({output_index:M,item:B})},h=!1,_=0,v="",E=0,b="";function*A(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:v,output_index:_,content_index:0,text:b};let M={id:v,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:b}],status:"completed"};yield{type:"response.output_item.done",output_index:_,item:M},g(_,M),b=""}let T=!1,x=0,I="",w=0,C="",q="";function*D(M){if(!T)return;T=!1,yield{type:"response.output_text.done",item_id:I,output_index:x,content_index:0,text:C},yield{type:"response.content_part.done",item_id:I,output_index:x,content_index:0,part:{type:"output_text",text:C}};let B={id:I,type:"message",role:"assistant",status:M,content:[{type:"output_text",text:C}]};yield{type:"response.output_item.done",output_index:x,item:B},g(x,B),C=""}let z=new Ee,H=null,Ae=-1;function*X(M){if(!H)return;let B=H;H=null,yield{type:"response.function_call_arguments.done",item_id:B.fcId,output_index:B.outputIndex,arguments:B.args};let V={id:B.fcId,type:"function_call",call_id:B.callId??B.fcId,name:B.name??"",arguments:B.args,status:M};yield{type:"response.output_item.done",output_index:B.outputIndex,item:V},g(B.outputIndex,V)}let re=!1;for await(let M of l.track(e,o,t.turn)){c.push(M);let B=String(M.type??"");if(B==="response.created"||B==="response.in_progress"){m=!0,yield d(M);continue}if(B==="response.output_item.added"){f=!0,yield d(M);continue}if(B==="response.reasoning_text.delta"&&!f){yield*R(),h||(h=!0,_=k++,E+=1,v=E===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${E}`,yield{type:"response.output_item.added",output_index:_,item:{id:v,type:"reasoning",summary:[],content:[],status:"in_progress"}}),b+=String(M.delta??""),yield{type:"response.reasoning_text.delta",item_id:v,output_index:_,content_index:0,delta:M.delta};continue}if(B==="response.output_text.delta"&&!f){yield*R(),yield*A(),T||(T=!0,x=k++,w+=1,I=w===1?p:`${p}_${w}`,yield{type:"response.output_item.added",output_index:x,item:{id:I,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:I,output_index:x,content_index:0,part:{type:"output_text",text:""}}),C+=String(M.delta??""),q+=String(M.delta??""),yield{type:B,item_id:I,output_index:x,content_index:0,delta:M.delta};continue}let V=f?null:ze(M);if(V){if(yield*R(),yield*A(),yield*D("completed"),z.add(V),V.tool_index!==Ae){yield*X("completed"),Ae=V.tool_index;let Te=k++;H={fcId:`fc_${r.slice(5)}_${V.tool_index}`,outputIndex:Te,callId:V.call_id,name:V.name,args:""},yield{type:"response.output_item.added",output_index:Te,item:{id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:"",status:"in_progress"}}}H&&(V.call_id&&(H.callId=V.call_id),V.name&&(H.name=V.name),H.args+=V.delta,yield{type:"response.function_call_arguments.delta",item_id:H.fcId,output_index:H.outputIndex,delta:V.delta});continue}if(B==="response.completed"&&!f){let Te=Ke(M.response),Je=Ne(i,z.size+Te.length,q);if(Je){re=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Le(o,Je)}};break}if(yield*A(),yield*D("completed"),yield*X("completed"),z.size===0)for(let Q of Te){let fe=k++,Pe=Q.id??Q.call_id??`fc_${fe}`,un=Q.arguments??"",Dn={id:Pe,type:"function_call",call_id:Q.call_id??Pe,name:Q.name??""};yield{type:"response.output_item.added",output_index:fe,item:{...Dn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Pe,output_index:fe,delta:un},yield{type:"response.function_call_arguments.done",item_id:Pe,output_index:fe,arguments:un};let Fn={...Dn,arguments:un,status:"completed"};yield{type:"response.output_item.done",output_index:fe,item:Fn},g(fe,Fn)}let G=fi(y,M.response);yield G.length>0?d({...M,response:{...M.response,output:G}}):d(M);continue}yield d(M)}if(yield*A(),yield*D("incomplete"),yield*X("incomplete"),s&&!re){let M=we(c);u.remember(r,n,cn(M,Ye(c,M)),a)}}var ve=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ae=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Qe=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}};var me=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}};var yi=require("@urun-sh/core"),Ue=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}};var _i=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ge(t){return!_i.some(e=>e.test(t))}function ye(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function ue(t,e){if(t instanceof Y)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=_r(t);return n||{message:ye(e?.inferenceId??null),redacted:!0}}function _r(t){return t instanceof It?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof at?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof F?{message:t.message,redacted:!1}:t instanceof ve?{message:t.message,redacted:!1}:t instanceof Qe?{message:t.message,redacted:!1}:t instanceof Ue?ge(t.message)?{message:t.message,redacted:!1}:null:t instanceof me?{message:t.message,redacted:!1}:t instanceof ae?{message:t.message,redacted:!1}:null}function Ze(t,e,n){let r=n??(s=>console.error(s)),o=_r(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${he(e)}`),`the ${t} upstream failed: ${o.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ge(i)?`the ${t} upstream failed: ${i}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${he(e)}`),`the ${t} upstream failed while serving this request`)}function be(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ge(e)?e:null}function he(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var wi="/v1/responses",vi=64*1024*1024,bi=8*1024*1024,Si=16,wr=32,vr=3600*1e3,ki=/^[A-Za-z0-9._-]{1,256}$/;function ie(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var xi=ie(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function hn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Ri(t){for(;t.bufferedAmount>bi&&t.readyState===Ie.WebSocket.OPEN;){let{promise:e,resolve:n}=hn();setTimeout(n,5),await e}}var fn=class extends We{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof Me))throw o;return this.shared.thread(n,r)}}remember(n,r,o,i=!0){i?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},mn=class{constructor(e,n,r,o,i){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=i;this.store=new fn(pt(n)),e.on("message",(a,u)=>this.onMessage(a,u)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ie(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${vr/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},vr).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(ie(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(ie(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(ie(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(ie(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(ie(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(ie(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!ki.test(o.stream_id)){this.sendFrame(xi);return}if(i=o.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=wr){this.sendFrame(ie(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${wr}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let s=o.generate===!1?()=>this.runWarmup(o,i):()=>this.runTurn(o,i),a=i??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(s).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=dt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let i;try{i=await ft({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:ct(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(i.responseId,n??null);let s=i.events;this.activeTurns.add(s);try{for await(let a of s){if(this.closed||this.ws.readyState!==Ie.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Ri(this.ws)}}finally{this.activeTurns.delete(s)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=dt(),o=ct(r);try{let i=Xe(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,i,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(i){this.failTurn(i,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let i=r.previous_response_id;typeof i=="string"&&this.laneOfResponse.get(i)===(n??null)&&(this.store.forget(i),this.laneOfResponse.delete(i))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:he(e);if(e instanceof ce)return ie(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof F)return ie(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof Y){let a=ue(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ie(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let i=this.statusOf?.(e)??null;if(i)return i.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${i.operatorDetail}`),ie(i.status,{type:i.openaiType,message:o},n);let s=ue(e,{inferenceId:r});return s.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ie(500,{type:"upstream_error",message:s.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,i=o?.type??"upstream_error",s=be(o),a=s??ye(r);return s===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),ie(i==="invalid_request_error"?400:502,{type:i,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=Si;){let{promise:e,resolve:n}=hn();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Ie.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Ie.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Ut(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
5
+ ${f}\r
6
+ `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let s of r.clients)s.close(1001,"server closing");await new Promise((s,a)=>r.close(u=>u===void 0?s():a(u)))})(),i)}function dr(t,e,n=new Ge){new Nt(t,e,n)}var Ie=require("ws");var cr=require("crypto"),pr="Inference-Id";function dt(){return(0,cr.randomUUID)()}function pn(t){return t==="/v1"||t.startsWith("/v1/")}function fr(t,e){if(!pn(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 ct(t){return`resp_${t}`}function mr(t){return`chatcmpl-${t}`}function gr(t){return`msg_${t}`}function ce(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function hr(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_seconds:null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function yr(t){return`${JSON.stringify(t)}
7
+ `}var li=256,di=128;function ie(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,di)}var $e=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=li?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,i=performance.now(),s=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-i),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=s-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let u=(performance.now()-(s??i))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},ci=256;function pi(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 Me=class extends Error{},We=class{conversations=new Map;thread(e,n){let r=pi(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Me(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let i of this.conversations.keys()){if(this.conversations.size<=ci)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},_r=new WeakMap;function pt(t){let e=_r.get(t);return e||(e=new We,_r.set(t,e)),e}function Ke(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function ve(t){return t.find(e=>e.type==="response.completed")?.response??null}function ze(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var Ee=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},fi=["<tool_call>","<function="];function mi(t){return fi.find(e=>t.includes(e))}function Le(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 Ne(t,e,n){if(!(!t||e>0))return mi(n)}function Ye(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Re(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function gi(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function fn(t,e){let n=gi(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var pe=class extends Error{constructor(n,r,o=400,i){super(n);this.code=r;this.status=o;this.param=i}code;status;param};function Xe(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Me?new pe(n.message,"previous_response_not_found",400,"previous_response_id"):new pe(String(n instanceof Error?n.message:n),"invalid_input")}}function wr(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function mn(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new pe("instructions must be a string","invalid_instructions");let i=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...i!==void 0?{instructions:i}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...wr(e)!==void 0?{response_format:wr(e)}:{}},o)}async function ft(t){let{body:e,clients:n,store:r,stats:o}=t,i=Xe(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let s=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,l=ie(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await mn(n,e,i,!0,c?ce(c):void 0);return{responseId:s,events:wi({events:p,conversation:i,responseId:s,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function hi(t,e){let n=[...t].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=n.filter(u=>u.type==="message").length===o.length,s=0;return[...n.map(u=>u.type==="message"&&i?_i(o[s++],u):u),...yi(r,n)]}function yi(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),i=e.filter(l=>l.type==="function_call"),s=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=i.length===s,u=new Set(i.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!u.has(o(d)):!0})}function _i(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(n);if(i===void 0)return e;let s={...t};return s.id=e.id,t.role===void 0&&(s.role=e.role),t.status===void 0&&(s.status=e.status),s.content=r.map(a=>n(a)?{...a,text:i.text}:a),s}async function*wi(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:i,remember:s,persist:a,store:u,stats:l}=t,d=[],c=$=>$.response&&typeof $.response=="object"?{...$,response:{...$.response,id:r}}:$,p=`item_${r.slice(5)}`,f=!1,m=!1,k=0;function*x(){f||(f=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let w=[],y=($,q)=>{w.push({output_index:$,item:q})},g=!1,v=0,T="",P=0,R="";function*E(){if(!g)return;g=!1,yield{type:"response.reasoning_text.done",item_id:T,output_index:v,content_index:0,text:R};let $={id:T,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:R}],status:"completed"};yield{type:"response.output_item.done",output_index:v,item:$},y(v,$),R=""}let O=!1,h=0,b="",_=0,C="",D="";function*F($){if(!O)return;O=!1,yield{type:"response.output_text.done",item_id:b,output_index:h,content_index:0,text:C},yield{type:"response.content_part.done",item_id:b,output_index:h,content_index:0,part:{type:"output_text",text:C}};let q={id:b,type:"message",role:"assistant",status:$,content:[{type:"output_text",text:C}]};yield{type:"response.output_item.done",output_index:h,item:q},y(h,q),C=""}let L=new Ee,N=null,te=-1;function*J($){if(!N)return;let q=N;N=null,yield{type:"response.function_call_arguments.done",item_id:q.fcId,output_index:q.outputIndex,arguments:q.args};let W={id:q.fcId,type:"function_call",call_id:q.callId??q.fcId,name:q.name??"",arguments:q.args,status:$};yield{type:"response.output_item.done",output_index:q.outputIndex,item:W},y(q.outputIndex,W)}let ee=!1;for await(let $ of l.track(e,o,t.turn)){d.push($);let q=String($.type??"");if(q==="response.created"||q==="response.in_progress"){f=!0,yield c($);continue}if(q==="response.output_item.added"){m=!0,yield c($);continue}if(q==="response.reasoning_text.delta"&&!m){yield*x(),g||(g=!0,v=k++,P+=1,T=P===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${P}`,yield{type:"response.output_item.added",output_index:v,item:{id:T,type:"reasoning",summary:[],content:[],status:"in_progress"}}),R+=String($.delta??""),yield{type:"response.reasoning_text.delta",item_id:T,output_index:v,content_index:0,delta:$.delta};continue}if(q==="response.output_text.delta"&&!m){yield*x(),yield*E(),O||(O=!0,h=k++,_+=1,b=_===1?p:`${p}_${_}`,yield{type:"response.output_item.added",output_index:h,item:{id:b,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:b,output_index:h,content_index:0,part:{type:"output_text",text:""}}),C+=String($.delta??""),D+=String($.delta??""),yield{type:q,item_id:b,output_index:h,content_index:0,delta:$.delta};continue}let W=m?null:ze($);if(W){if(yield*x(),yield*E(),yield*F("completed"),L.add(W),W.tool_index!==te){yield*J("completed"),te=W.tool_index;let Te=k++;N={fcId:`fc_${r.slice(5)}_${W.tool_index}`,outputIndex:Te,callId:W.call_id,name:W.name,args:""},yield{type:"response.output_item.added",output_index:Te,item:{id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:"",status:"in_progress"}}}N&&(W.call_id&&(N.callId=W.call_id),W.name&&(N.name=W.name),N.args+=W.delta,yield{type:"response.function_call_arguments.delta",item_id:N.fcId,output_index:N.outputIndex,delta:W.delta});continue}if(q==="response.completed"&&!m){let Te=Ke($.response),Je=Ne(i,L.size+Te.length,D);if(Je){ee=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Le(o,Je)}};break}if(yield*E(),yield*F("completed"),yield*J("completed"),L.size===0)for(let Q of Te){let me=k++,Pe=Q.id??Q.call_id??`fc_${me}`,dn=Q.arguments??"",Bn={id:Pe,type:"function_call",call_id:Q.call_id??Pe,name:Q.name??""};yield{type:"response.output_item.added",output_index:me,item:{...Bn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Pe,output_index:me,delta:dn},yield{type:"response.function_call_arguments.done",item_id:Pe,output_index:me,arguments:dn};let qn={...Bn,arguments:dn,status:"completed"};yield{type:"response.output_item.done",output_index:me,item:qn},y(me,qn)}let K=hi(w,$.response);yield K.length>0?c({...$,response:{...$.response,output:K}}):c($);continue}yield c($)}if(yield*E(),yield*F("incomplete"),yield*J("incomplete"),s&&!ee){let $=ve(d);u.remember(r,n,fn($,Ye(d,$)),a)}}var be=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ue=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Qe=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}};var ge=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}};var vi=require("@urun-sh/core"),Ue=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}};var bi=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ye(t){return!bi.some(e=>e.test(t))}function _e(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function le(t,e){if(t instanceof X)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=vr(t);return n||{message:_e(e?.inferenceId??null),redacted:!0}}function vr(t){return t instanceof Ot?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof at?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof H?{message:t.message,redacted:!1}:t instanceof be?{message:t.message,redacted:!1}:t instanceof Qe?{message:t.message,redacted:!1}:t instanceof Ue?ye(t.message)?{message:t.message,redacted:!1}:null:t instanceof ge?{message:t.message,redacted:!1}:t instanceof ue?{message:t.message,redacted:!1}:null}function Ze(t,e,n){let r=n??(s=>console.error(s)),o=vr(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${he(e)}`),`the ${t} upstream failed: ${o.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ye(i)?`the ${t} upstream failed: ${i}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${he(e)}`),`the ${t} upstream failed while serving this request`)}function Se(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ye(e)?e:null}function he(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Si="/v1/responses",ki=64*1024*1024,xi=8*1024*1024,Ri=16,br=32,Sr=3600*1e3,Ai=/^[A-Za-z0-9._-]{1,256}$/;function se(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Ei=se(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function yn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Ii(t){for(;t.bufferedAmount>xi&&t.readyState===Ie.WebSocket.OPEN;){let{promise:e,resolve:n}=yn();setTimeout(n,5),await e}}var gn=class extends We{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof Me))throw o;return this.shared.thread(n,r)}}remember(n,r,o,i=!0){i?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},hn=class{constructor(e,n,r,o,i){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=i;this.store=new gn(pt(n)),e.on("message",(a,u)=>this.onMessage(a,u)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(se(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Sr/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Sr).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(se(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(se(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(se(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(se(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(se(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(se(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Ai.test(o.stream_id)){this.sendFrame(Ei);return}if(i=o.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=br){this.sendFrame(se(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${br}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let s=o.generate===!1?()=>this.runWarmup(o,i):()=>this.runTurn(o,i),a=i??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(s).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=dt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let i;try{i=await ft({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:ct(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(i.responseId,n??null);let s=i.events;this.activeTurns.add(s);try{for await(let a of s){if(this.closed||this.ws.readyState!==Ie.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Ii(this.ws)}}finally{this.activeTurns.delete(s)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=dt(),o=ct(r);try{let i=Xe(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,i,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(i){this.failTurn(i,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let i=r.previous_response_id;typeof i=="string"&&this.laneOfResponse.get(i)===(n??null)&&(this.store.forget(i),this.laneOfResponse.delete(i))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:he(e);if(e instanceof pe)return se(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof H)return se(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof X){let a=le(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),se(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let i=this.statusOf?.(e)??null;if(i)return i.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${i.operatorDetail}`),se(i.status,{type:i.openaiType,message:o},n);let s=le(e,{inferenceId:r});return s.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),se(500,{type:"upstream_error",message:s.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,i=o?.type??"upstream_error",s=Se(o),a=s??_e(r);return s===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),se(i==="invalid_request_error"?400:502,{type:i,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=Ri;){let{promise:e,resolve:n}=yn();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!==Ie.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Ie.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Dt(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
8
8
  `;t.end(`HTTP/1.1 ${e} ${r}\r
9
9
  Connection: close\r
10
10
  Content-Type: text/plain; charset=utf-8\r
11
11
  Content-Length: ${Buffer.byteLength(o)}\r
12
12
  \r
13
- ${o}`)}function br(t,e){let n=new Ie.WebSocketServer({noServer:!0,maxPayload:vi}),r=new $e,o=new Set,i=new Set,s=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(c,d,p)=>{let m;try{m=new URL(c.url??"/","http://localhost")}catch{Ut(d,400,"malformed upgrade URL");return}if(d.on("error",()=>d.destroy()),d.on("close",()=>s.delete(d)),m.pathname!==wi){s.add(d);return}i.add(d);let f=!1;(async()=>{if(e.apiKey&&(c.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ut(d,401,"invalid local proxy api key");return}let k;try{k=await a(c)}catch(R){let y=e.statusOf?.(R)??null;Ut(d,y?.status??500,"upstream resolver rejected the connection");return}u||d.destroyed||(f=!0,n.handleUpgrade(c,d,p,R=>{i.delete(d),o.add(R),R.on("close",()=>o.delete(R));try{new mn(R,k,r,e.statusOf,e.operatorLog??(y=>console.error(y)))}catch{o.delete(R),R.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!f&&!d.destroyed&&Ut(d,500,"responses websocket upgrade failed")}).finally(()=>i.delete(d))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:c,resolve:d}=hn();if(u)return d(),c;u=!0,t.off("upgrade",l);for(let m of i)m.destroy();i.clear();for(let m of s)m.destroy();s.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==Ie.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),d()}),c}}}var Sn=require("@urun-sh/core");var Sr=require("@urun-sh/core"),Ai={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Ei={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function mt(t,e){let n=Ei[t.code];return e?`${n} (${e})`:n}function Dt(t){if(t==null)return null;let e=Ai[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Ft(t){if(t.kind==="create-failed")return Dt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Sr.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Dt(e?"cold_start_exceeded":"queue_timeout")}var Ii=Bn(require("os"),1),Oi=Bn(require("path"),1),Ti=require("url"),Pi=require("util");var Ci=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function $i(t){let e=t?.code;return typeof e=="string"&&Ci.has(e)}function De(t,e){try{return t.write(e),!0}catch(n){if($i(n))return!1;throw n}}var Ir=require("ws");var Er=require("@urun-sh/core");var xr=require("crypto");function O(t){return`${t}_${(0,xr.randomUUID)().replace(/-/g,"").slice(0,24)}`}var qt=4*1024*1024,gn=8*1024*1024,Bt=512,jt=20*1024*1024;function W(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Fe(t,e){return{type:"server_error",code:t,message:e}}function j(t){return{type:"error",event_id:O("event"),error:t}}function yn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var P=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Mi={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Li={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ni={format:!0,voice:!0,speed:!0};function Ui(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function et(t,e){if(!Array.isArray(t)||t.length===0)throw new P(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new P(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function kr(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new P(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Di=10;function _n(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Di})}function ht(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new P("session must be an object","session","invalid_request");let o=t,i=Object.keys(o).filter(a=>!(a in Mi));if(i.length>0)throw new P(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=et(o.modalities,"modalities"),u=et(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new P("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let s={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(o))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new P(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new P(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!n.turns)throw new P('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");s.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new P(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=et(u,a);for(let c of l)if(c==="audio"&&!n.voice)throw new P('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");s.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Ui(u))throw new P(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new P("model must be a string or null","model");s.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new P("instructions must be a string or null","instructions");s.instructions=_n(u??void 0)??void 0;break;case"voice":if(u===null){delete s.voice;break}if(typeof u!="string")throw new P("voice must be a string or null","voice");if(!n.voice)throw new P("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new P(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new P("temperature must be a finite number or null","temperature");s.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new P(`${a} must be a positive integer, "inf" or null`,a);s.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new P("tools must be an array","tools");s.tools=u;break;case"tool_choice":s.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new P("metadata must be an object or null","metadata");s.metadata=u??null;break;case"turn_detection":{if(u===null){s.turnDetection=null;break}if(!n.turns)throw new P("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=u;if(!l||typeof l!="object"||Array.isArray(l))throw new P("turn_detection must be an object or null","turn_detection");let c=String(l.type??"");if(c!=="server_vad"&&c!=="semantic_vad")throw new P(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let d=c==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in d))throw new P(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(m!=null&&m!==d[p])throw new P(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}s.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new P("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(!u||typeof u!="object"||Array.isArray(u))throw new P("input_audio_transcription must be an object or null","input_audio_transcription");for(let c of Object.keys(u))if(!["model","language","languages","prompt"].includes(c))throw new P(`input_audio_transcription field not honored by this backend: ${c} (transcription comes from the voice engine itself)`,`input_audio_transcription.${c}`,"unsupported_field");let l=u.model;if(l!=null){let c=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new P(`input_audio_transcription.model ${JSON.stringify(c)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new P("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(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new P("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let c=l.input;if(!c||typeof c!="object"||Array.isArray(c))throw new P("audio.input must be an object","audio.input");for(let d of Object.keys(c))if(!(d in Li))throw new P(`audio.input field not supported by this backend: ${d}`,`audio.input.${d}`,"unsupported_field");if(c.format!==void 0&&kr(c.format,"audio.input.format"),c.transcription!==null&&c.transcription!==void 0){let d=ht({input_audio_transcription:c.transcription},s,n,r);s.inputAudioTranscription=d.inputAudioTranscription}if(c.turn_detection!==void 0){let d=ht({turn_detection:c.turn_detection},s,n,r);s.turnDetection=d.turnDetection}if(c.noise_reduction!==null&&c.noise_reduction!==void 0)throw new P("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 c=l.output;if(!c||typeof c!="object"||Array.isArray(c))throw new P("audio.output must be an object","audio.output");for(let d of Object.keys(c))if(!(d in Ni))throw new P(`audio.output field not supported by this backend: ${d}`,`audio.output.${d}`,"unsupported_field");if(c.format!==void 0&&kr(c.format,"audio.output.format"),c.speed!==void 0)throw new P("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(c.voice!==void 0)if(c.voice===null)delete s.voice;else{if(typeof c.voice!="string")throw new P("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new P("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=c.voice}c.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function Ht(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function wn(t,e){let n=t;if(!n||typeof n!="object")throw new P("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 P("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:O("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new P('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new P("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new P("content part must be an object","item.content","invalid_request");if(s.type==="input_text"||r==="assistant"&&s.type==="output_text"){if(typeof s.text!="string")throw new P(`${String(s.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){if(!e)throw new P("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof s.audio!="string")throw new P("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}if(s.type==="input_image"){if(r!=="user")throw new P("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof s.image_url=="string"?s.image_url:s.image_url?.url;if(typeof a!="string"||a.length===0)throw new P("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new P("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof s.detail=="string"?s.detail:void 0;o.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new P(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:O("item"),type:"message",role:r,content:o}}throw new P(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Jt(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let s=i.transcript;if(typeof s=="string"&&s.trim().length>0){o.push({type:"input_text",text:s});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Fi=1001,qi=1011,Rr=t=>t.slice(0,120),Bi=/^[A-Za-z0-9+/=]*$/,ji=2;function Hi(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ji)return!1;return!0}var qe=class{id=O("conn");ws;binding;onClosed;operatorLog;config=yn();sessionId=O("sess");conversationId=O("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:O("event"),session:Ht(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:O("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof Y&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,o):this.send(j(Fe("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:O("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(i=>i.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:O("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:O("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:O("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),i=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let s=O("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:O("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:s,content_index:0,transcript:i}),this.emitItemDone(s),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(W("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>qt){this.fail(W("frame_too_large",`frame exceeds the ${qt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(W("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(W("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let i=o;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(j({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}this.fail(Fe(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=ht(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(j(W("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:O("event"),session:Ht(this.config,this.sessionId)});return}case"conversation.item.create":{let n=wn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(j(W("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:O("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(j(W("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:O("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(j(W("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:O("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(j(W("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Bi.test(e.audio)){this.send(j(W("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>jt){this.send(j(W("buffer_full",`uncommitted input audio exceeds the ${jt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:O("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(j(W("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=O("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:O("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:r,content_index:0,transcript:i}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(j(W("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(j(W("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(j(W("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(j(W("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(j({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:i,input:s,...a}=e;return await o.createResponse({...a,input:s})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(j(W("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?et(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?et(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new P("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(j(W("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let s=O("req"),a=`resp_${s}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,c=u?null:Jt(this.items),d=_n(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,m=n.max_output_tokens??this.config.maxOutputTokens,f=m==="inf"||m===void 0?void 0:m,k=n.tools!==void 0?n.tools:this.config.tools,R=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,y={stream:!0,...this.config.model?{model:this.config.model}:{},...d!==void 0?{instructions:d}:{},...p!==void 0?{temperature:p}:{},...f!==void 0?{max_output_tokens:f}:{},...k!==void 0?{tools:k}:{},...R!==void 0?{tool_choice:R}:{}};if(!(u&&!this.ensureVoice())){for(let g of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(g);this.inFlight=(async()=>{let g=[],h=b=>{this.responseFlushed?this.send(b):g.push(b)},_=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:O("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:O("event"),response:this.responseObject(a,"in_progress")});for(let b of g)this.send(b);g.length=0,this.responseFlushed=!0}},v={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},E=null;try{if(u){if(this.pendingTranscriptItemId!==null&&(await new Promise(I=>{this.pendingTranscriptSettled=I}),this.cancelled||this.closed))return;l=this.items.length,c=Jt(this.items)}let{input:b,sawAudioOnlyItem:A}=c??{input:[],sawAudioOnlyItem:!1},T={...y,input:b,...u?this.compositeTurnAsk(n):{}};A&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let x;try{x=await this.upstreamStream(T,s)}catch(I){this.upstreamTurnFault(I,a);return}try{for await(let I of x){if(this.cancelled)break;let w=I;if(w.type==="error"){let C=this.upstreamErrorBody(w);this.responseFlushed?this.send(j(C)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(a,C)});return}if(w.type==="response.output_text.delta"&&typeof w.delta=="string"){_(),v.messageOpen||(this.beginMessageItem(a,v.nextOutputIndex++),v.messageOpen=!0),this.config.outputModalities.includes("text")&&h({type:"response.output_text.delta",event_id:O("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:w.delta}),this.turnOutputIsAudio()&&(v.transcriptDelta=!0,h({type:"response.output_audio_transcript.delta",event_id:O("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:w.delta})),v.messageText+=w.delta;continue}if(w.type==="response.function_call_arguments.delta"){_();let C=typeof w.delta=="string"?w.delta:"",q=typeof w.call_id=="string"&&w.call_id.length>0?w.call_id:`${a}_fc_${v.nextOutputIndex}`,D=v.tools.get(q);if(!D){let z=typeof w.name=="string"&&w.name.length>0?w.name:void 0;D={outputIndex:v.nextOutputIndex++,name:z,args:""},v.tools.set(q,D);let H={id:q,object:"realtime.item",type:"function_call",call_id:q,name:z??"",arguments:"",status:"in_progress"};h({type:"response.output_item.added",event_id:O("event"),response_id:a,output_index:D.outputIndex,item:H}),this.emitAssistantItemAdded(H)}typeof w.name=="string"&&w.name.length>0&&(D.name=w.name),D.args+=C,h({type:"response.function_call_arguments.delta",event_id:O("event"),item_id:q,response_id:a,output_index:D.outputIndex,call_id:q,name:D.name??"",delta:C});continue}if(w.type==="response.completed"){E=w.response??null;continue}}}catch(I){this.upstreamTurnFault(I,a);return}if(this.cancelled)return;this.closeOpenItems(a,v,l),_(),this.send({type:"response.done",event_id:O("event"),response:this.doneResponse(a,l,E)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Hi(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(j({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:O("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:O("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:O("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:O("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:O("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:O("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:O("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,i=this.messageItemOpenForAudio,s=this.config.outputModalities.includes("text"),a=n.messageText;i?(this.send({type:"response.output_audio_transcript.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&s&&this.send({type:"response.output_text.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let u=[];i&&u.push({type:"output_audio",transcript:a}),n.messageText.length>0&&u.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:O("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,i]of n.tools){let s=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:O("event"),item_id:o,response_id:e,output_index:i.outputIndex,call_id:o,name:i.name??"",arguments:s});let a={id:o,type:"function_call",callId:o,name:i.name,arguments:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:O("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let s=n;s<this.items.length;s++)i.push(this.itemToProtocol(this.items[s]));return this.responseObject(e,"completed",{output:i,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=be(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??ye(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&ge(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${he(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Fe("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof Y){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Er.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Fe(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(j(r)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(j(W("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:O("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Bt&&(this.items.shift(),this.send(j({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Bt} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(j(W("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>ln){this.send(j(W("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${ln}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(j(W("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(o))).catch(i=>this.send(j(Fe(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>gn){this.ws.close(Fi,Rr("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=ue(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${he(e)}`),r.message}fail(e,n){this.send(j(e)),this.ws.close(qi,Rr(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>Ar(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Ar(this.id,e)}},vn=[];function Ar(t,e){vn.push({id:t,reason:e}),vn.length>256&&vn.shift()}var gt="/v1/realtime",Ji=t=>t.slice(0,120);function Vi(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
13
+ ${o}`)}function kr(t,e){let n=new Ie.WebSocketServer({noServer:!0,maxPayload:ki}),r=new $e,o=new Set,i=new Set,s=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,p)=>{let f;try{f=new URL(d.url??"/","http://localhost")}catch{Dt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>s.delete(c)),f.pathname!==Si){s.add(c);return}i.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Dt(c,401,"invalid local proxy api key");return}let k;try{k=await a(d)}catch(x){let w=e.statusOf?.(x)??null;Dt(c,w?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(m=!0,n.handleUpgrade(d,c,p,x=>{i.delete(c),o.add(x),x.on("close",()=>o.delete(x));try{new hn(x,k,r,e.statusOf,e.operatorLog??(w=>console.error(w)))}catch{o.delete(x),x.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&Dt(c,500,"responses websocket upgrade failed")}).finally(()=>i.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=yn();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let f of i)f.destroy();i.clear();for(let f of s)f.destroy();s.clear();for(let f of o)f.close(1001,"server shutting down");let p=setTimeout(()=>{for(let f of o)f.readyState!==Ie.WebSocket.CLOSED&&f.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var xn=require("@urun-sh/core");var xr=require("@urun-sh/core"),Oi={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Ti={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function mt(t,e){let n=Ti[t.code];return e?`${n} (${e})`:n}function Ft(t){if(t==null)return null;let e=Oi[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Bt(t){if(t.kind==="create-failed")return Ft(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=xr.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Ft(e?"cold_start_exceeded":"queue_timeout")}var Pi=Hn(require("os"),1),Ci=Hn(require("path"),1),$i=require("url"),Mi=require("util");var Li=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Ni(t){let e=t?.code;return typeof e=="string"&&Li.has(e)}function De(t,e){try{return t.write(e),!0}catch(n){if(Ni(n))return!1;throw n}}var ht=require("ws");var Or=require("@urun-sh/core");var Ar=require("crypto");function A(t){return`${t}_${(0,Ar.randomUUID)().replace(/-/g,"").slice(0,24)}`}var qt=4*1024*1024,_n=8*1024*1024,jt=512,Ht=20*1024*1024;function z(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Fe(t,e){return{type:"server_error",code:t,message:e}}function V(t){return{type:"error",event_id:A("event"),error:t}}function wn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var I=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Ui={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Di={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Fi={format:!0,voice:!0,speed:!0};function Bi(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function et(t,e){if(!Array.isArray(t)||t.length===0)throw new I(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new I(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function Rr(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new I(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var qi=10;function vn(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:qi})}function gt(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new I("session must be an object","session","invalid_request");let o=t,i=Object.keys(o).filter(a=>!(a in Ui));if(i.length>0)throw new I(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=et(o.modalities,"modalities"),u=et(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new I("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let s={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(o))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new I(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new I(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!n.turns)throw new I('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");s.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new I(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=et(u,a);for(let d of l)if(d==="audio"&&!n.voice)throw new I('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");s.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Bi(u))throw new I(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new I("model must be a string or null","model");s.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new I("instructions must be a string or null","instructions");s.instructions=vn(u??void 0)??void 0;break;case"voice":if(u===null){delete s.voice;break}if(typeof u!="string")throw new I("voice must be a string or null","voice");if(!n.voice)throw new I("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new I(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new I("temperature must be a finite number or null","temperature");s.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new I(`${a} must be a positive integer, "inf" or null`,a);s.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new I("tools must be an array","tools");s.tools=u;break;case"tool_choice":s.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new I("metadata must be an object or null","metadata");s.metadata=u??null;break;case"turn_detection":{if(u===null){s.turnDetection=null;break}if(!n.turns)throw new I("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=u;if(!l||typeof l!="object"||Array.isArray(l))throw new I("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new I(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,f]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new I(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(f!=null&&f!==c[p])throw new I(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(f)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}s.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new I("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(!u||typeof u!="object"||Array.isArray(u))throw new I("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new I(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new I(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new I("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(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new I("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new I("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Di))throw new I(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Rr(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=gt({input_audio_transcription:d.transcription},s,n,r);s.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=gt({turn_detection:d.turn_detection},s,n,r);s.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new I("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 d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new I("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Fi))throw new I(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Rr(d.format,"audio.output.format"),d.speed!==void 0)throw new I("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new I("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new I("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function Jt(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function bn(t,e){let n=t;if(!n||typeof n!="object")throw new I("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 I("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:A("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new I('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new I("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new I("content part must be an object","item.content","invalid_request");if(s.type==="input_text"||r==="assistant"&&s.type==="output_text"){if(typeof s.text!="string")throw new I(`${String(s.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){if(!e)throw new I("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof s.audio!="string")throw new I("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}if(s.type==="input_image"){if(r!=="user")throw new I("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof s.image_url=="string"?s.image_url:s.image_url?.url;if(typeof a!="string"||a.length===0)throw new I("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new I("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof s.detail=="string"?s.detail:void 0;o.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new I(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:A("item"),type:"message",role:r,content:o}}throw new I(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Vt(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let s=i.transcript;if(typeof s=="string"&&s.trim().length>0){o.push({type:"input_text",text:s});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var ji=1001,Hi=1011,Ji=15e3;var Gt=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Er=t=>t.slice(0,120),Vi=/^[A-Za-z0-9+/=]*$/,Gi=2;function Wi(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Gi)return!1;return!0}var Be=class{id=A("conn");ws;binding;onClosed;operatorLog;turnStallMs;config=wn();sessionId=A("sess");conversationId=A("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??Ji,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:A("event"),session:Jt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:A("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof X&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,o):this.send(V(Fe("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:A("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(i=>i.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:A("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:A("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:A("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),i=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let s=A("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:A("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:s,content_index:0,transcript:i}),this.emitItemDone(s),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(z("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>qt){this.fail(z("frame_too_large",`frame exceeds the ${qt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(z("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(z("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let i=o;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(V({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}this.fail(Fe(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=gt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(V(z("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:A("event"),session:Jt(this.config,this.sessionId)});return}case"conversation.item.create":{let n=bn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(V(z("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:A("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(V(z("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:A("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(V(z("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:A("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(V(z("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Vi.test(e.audio)){this.send(V(z("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Ht){this.send(V(z("buffer_full",`uncommitted input audio exceeds the ${Ht}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:A("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(V(z("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=A("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:A("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:r,content_index:0,transcript:i}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(V(z("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(V(z("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(V(z("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(V(z("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(V({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=!0;try{for(;;){let o;if(r||this.turnStallMs<=0)r=!1,o=await n.next();else{let i,s=new Promise((a,u)=>{i=setTimeout(()=>u(new Gt),this.turnStallMs)});o=await Promise.race([n.next(),s]).finally(()=>clearTimeout(i))}if(o.done===!0)return;yield o.value}}finally{await n.return?.()}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:i,input:s,...a}=e;return await o.createResponse({...a,input:s})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(V(z("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?et(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?et(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new I("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(V(z("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let s=A("req"),a=`resp_${s}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:Vt(this.items),c=vn(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,f=n.max_output_tokens??this.config.maxOutputTokens,m=f==="inf"||f===void 0?void 0:f,k=n.tools!==void 0?n.tools:this.config.tools,x=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,w={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...m!==void 0?{max_output_tokens:m}:{},...k!==void 0?{tools:k}:{},...x!==void 0?{tool_choice:x}:{}};if(!(u&&!this.ensureVoice())){for(let{audio:y,captureWallMs:g}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(y,g);this.inFlight=(async()=>{let y=[],g=R=>{this.responseFlushed?this.send(R):y.push(R)},v=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:A("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:A("event"),response:this.responseObject(a,"in_progress")});for(let R of y)this.send(R);y.length=0,this.responseFlushed=!0}},T={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},P=null;try{if(u){if(this.pendingTranscriptItemId!==null&&(await new Promise(b=>{this.pendingTranscriptSettled=b}),this.cancelled||this.closed))return;l=this.items.length,d=Vt(this.items)}let{input:R,sawAudioOnlyItem:E}=d??{input:[],sawAudioOnlyItem:!1},O={...w,input:R,...u?this.compositeTurnAsk(n):{}};E&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let h;try{h=await this.upstreamStream(O,s)}catch(b){this.upstreamTurnFault(b,a);return}try{for await(let b of this.stallBoundedTurn(h)){if(this.cancelled)break;let _=b;if(_.type==="error"){let C=this.upstreamErrorBody(_);this.responseFlushed?this.send(V(C)):this.send({type:"response.failed",event_id:A("event"),response:this.failedResponse(a,C)});return}if(_.type==="response.output_text.delta"&&typeof _.delta=="string"){v(),T.messageOpen||(this.beginMessageItem(a,T.nextOutputIndex++),T.messageOpen=!0),this.config.outputModalities.includes("text")&&g({type:"response.output_text.delta",event_id:A("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:_.delta}),this.turnOutputIsAudio()&&(T.transcriptDelta=!0,g({type:"response.output_audio_transcript.delta",event_id:A("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:_.delta})),T.messageText+=_.delta;continue}if(_.type==="response.function_call_arguments.delta"){v();let C=typeof _.delta=="string"?_.delta:"",D=typeof _.call_id=="string"&&_.call_id.length>0?_.call_id:`${a}_fc_${T.nextOutputIndex}`,F=T.tools.get(D);if(!F){let L=typeof _.name=="string"&&_.name.length>0?_.name:void 0;F={outputIndex:T.nextOutputIndex++,name:L,args:""},T.tools.set(D,F);let N={id:D,object:"realtime.item",type:"function_call",call_id:D,name:L??"",arguments:"",status:"in_progress"};g({type:"response.output_item.added",event_id:A("event"),response_id:a,output_index:F.outputIndex,item:N}),this.emitAssistantItemAdded(N)}typeof _.name=="string"&&_.name.length>0&&(F.name=_.name),F.args+=C,g({type:"response.function_call_arguments.delta",event_id:A("event"),item_id:D,response_id:a,output_index:F.outputIndex,call_id:D,name:F.name??"",delta:C});continue}if(_.type==="response.completed"){P=_.response??null;continue}}}catch(b){if(b instanceof Gt)this.operatorLog(`[realtime] turn ${a} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(b,a);return}}if(this.cancelled)return;this.closeOpenItems(a,T,l),v(),this.send({type:"response.done",event_id:A("event"),response:this.doneResponse(a,l,P)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Wi(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(V({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:A("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:A("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:A("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:A("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:A("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:A("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:A("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,i=this.messageItemOpenForAudio,s=this.config.outputModalities.includes("text"),a=n.messageText;i?(this.send({type:"response.output_audio_transcript.done",event_id:A("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:A("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:A("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&s&&this.send({type:"response.output_text.done",event_id:A("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:A("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let u=[];i&&u.push({type:"output_audio",transcript:a}),n.messageText.length>0&&u.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:A("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,i]of n.tools){let s=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:A("event"),item_id:o,response_id:e,output_index:i.outputIndex,call_id:o,name:i.name??"",arguments:s});let a={id:o,type:"function_call",callId:o,name:i.name,arguments:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:A("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let s=n;s<this.items.length;s++)i.push(this.itemToProtocol(this.items[s]));return this.responseObject(e,"completed",{output:i,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=Se(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??_e(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&ye(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${he(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Fe("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof X){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Or.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Fe(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(V(r)):this.send({type:"response.failed",event_id:A("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(V(z("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:A("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>jt&&(this.items.shift(),this.send(V({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${jt} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(V(z("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>cn){this.send(V(z("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${cn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(V(z("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(o))).catch(i=>this.send(V(Fe(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>_n){this.ws.close(ji,Er("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=le(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${he(e)}`),r.message}fail(e,n){this.send(V(e)),this.ws.close(Hi,Er(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>Ir(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Ir(this.id,e)}},Sn=[];function Ir(t,e){Sn.push({id:t,reason:e}),Sn.length>256&&Sn.shift()}var yt="/v1/realtime",Tr="urun.admission",Pr=t=>t.slice(0,120);function Ki(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
14
14
  Connection: close\r
15
15
  Content-Type: text/plain\r
16
16
  \r
17
- ${Ji(n)}\r
18
- `),t.destroy()}function Gi(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
19
- `}function Wi(t){De(process.stdout,t)}function Ki(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function bn(t){return t.audioSession?.audio.sessionId??void 0}function yt(t,e){let n=new Ir.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==gt)return;r.add(i),i.on("close",()=>{r.delete(i)});let u=O("rtup"),l=Ki(o),c=v=>{(e.log??Wi)(Gi(v))};c({stage:"accept",conn:u,model:l}),i.resume();let d=new AbortController,p=null,m=v=>{p??=v,d.abort(new Error(p))},f=()=>m("client socket closed"),k=()=>m("client socket closed (half-close)"),R=v=>m(`client socket error: ${v.message}`);i.once("close",f),i.once("end",k),i.once("error",R);let y=()=>{i.removeListener("close",f),i.removeListener("end",k),i.removeListener("error",R)},g=v=>{c({stage:"close",conn:u,model:l,...v})},h=v=>{let E=v,b=E.session!=null&&typeof E.session.sendResponseCreate=="function",A=E.clients!=null&&typeof E.clients.createResponse=="function";if(!b&&!A)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((T,x)=>{n.handleUpgrade(o,i,s,I=>{try{new qe({ws:I,binding:v,operatorLog:e.operatorLog,onClosed:(w,C)=>{g({while:"live",reason:C.reason})}}),c({stage:"admit",conn:u,model:l,...bn(v)===void 0?{}:{session:bn(v)}}),T()}catch(w){x(w)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,d.signal).then(async v=>{if(d.signal.aborted){y();let E=bn(v);try{await v.release?.()}catch(b){g({while:"queued",...E===void 0?{}:{session:E},reason:p??"client socket closed",release_failed:b instanceof Error?b.message:String(b)});return}g({while:"queued",...E===void 0?{}:{session:E},reason:p??"client socket closed",released:!0}),i.destroy();return}y(),await h(v)}).catch(v=>{let E=v instanceof Sn.SessionFailedError?Ft(v):null,b=null;if(v!==null&&typeof v=="object"&&"status"in v){let I=v.status;typeof I=="number"&&(b=I)}let A=b??E?.status??502,T=v instanceof Error?v.message:String(v),x=b!==null?T:E!==null?mt(E,v instanceof Sn.SessionFailedError&&v.status.sessionId?`session ${v.status.sessionId}`:void 0):ue(v).message;g({while:"queued",...d.signal.aborted?{reason:p??"client socket closed"}:{reason:T,status:A}}),i.destroyed||Vi(i,A,x)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}var $r=require("crypto");var xn="x-urun-profile",_t="voice";var se=class extends Error{status=400},zi=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Yi=/\s/;function Xi(t){return zi.test(t)}function kn(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new se(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Or(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new se(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new se(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new se(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function Tr(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new se(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let l=n.trim();if(l==="")throw new se(`the ${xn} header is empty \u2014 the only profile this lane accepts is "${_t}" (omit the header for the ordinary lane)`);if(l!==_t)throw new se(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${_t}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==_t)throw new se(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${_t}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new se("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new se("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Or(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Or(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:kn(u,"sentence_flush",!0),includeReasoning:kn(u,"include_reasoning",!1),metadata:kn(u,"metadata",!1)}}var tt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&Xi(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(Yi.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};var Re=(t,e)=>Object.assign(new Error(e),{status:t}),es='"transcription" (a transcription session), or no intent at all (the realtime voice session)',An=(t,e,n)=>new Y(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Rn=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof F?Re(404,n.message):n}};async function Pr(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Re(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${es}`);if(o==="transcription")throw Re(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw Re(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw Re(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(m){throw m instanceof F?Re(404,m.message):m}if(!p)throw Re(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(m){throw m instanceof F?Re(404,m.message):m}if(p!=="stt")throw Re(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let i=await Rn(t,n.stt),s=await Rn(t,e),a=await Rn(t,n.tts),u=await t.openAudioOn(i,r),l=await t.openAudioOn(a,r),c=null,d={clients:{createResponse:p=>{let m=new AbortController;return c=m,ts({clients:t,chatHandle:s,ttsHandle:a,chatModel:e,companions:n},p,m.signal,()=>{c===m&&(c=null)})}},cancelActiveTurn:()=>{let p=c;c=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(i,p)}catch(m){throw m instanceof Y?An("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(d.model=e),d}function Cr(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Vt=class extends Error{};async function*ts(t,e,n,r){let{clients:o,chatHandle:i,ttsHandle:s,chatModel:a,companions:u}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...c}=e,d=e.output_modalities,p=!Array.isArray(d)||d.includes("audio"),m=!1,f=null,k=null,R=[],y=null,g=new Promise((I,w)=>{n&&n.addEventListener("abort",()=>w(new Vt),{once:!0})}),h=()=>m||n?.aborted===!0,_=async I=>{if(h())return;let w;try{w=await o.createResponseOn(s,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:I}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(q){throw q instanceof Y?An("tts",u.tts,q):q}let C=w[Symbol.asyncIterator]();k=C;try{for(;;){let q=C.next(),D;try{D=await Promise.race([q,g])}catch(H){if(q.catch(()=>{}),H instanceof Vt)return;throw H}if(D.done)return;let z=D.value;if(z.type==="error"){let H=z.error&&typeof z.error.message=="string"?z.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${H}`)}if(z.type==="response.completed")return}}finally{k===C&&(k=null)}},v=async()=>{for(;R.length>0&&!h();){let I=R.shift();await _(I)}},E=I=>{if(I===""||h()||(R.push(I),y!==null))return;let w=v();y=w,w.then(()=>{y===w&&(y=null)},C=>{y===w&&(y=null),f??=C})},b=()=>{m=!0,R.length=0;let I=k;if(k=null,I){let w=I.return?.();w&&w.catch(()=>{})}},A=async()=>{for(;R.length>0||y!==null;){let I=y;if(I===null){await _(R.shift());continue}await I}},T=p?new tt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},I=>E(I)):null,x=null;try{let I;try{I=await o.createResponseOn(i,c)}catch(w){throw w instanceof Y?An("chat",a,w):w}for await(let w of I){if(h())return;let C=w;if(C.type==="error"){yield w;return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){yield w,T?.push(C.delta);continue}if(C.type==="response.function_call_arguments.delta"){T?.flush(),yield w;continue}if(C.type==="response.completed"){x=w.response;continue}}T?.flush(),T?.dispose(),p&&await A(),x!==null&&(yield{type:"response.completed",response:x})}finally{T?.dispose(),b();try{if(f instanceof Y)throw f}finally{r?.()}}}var le=(t,e)=>Object.assign(new Error(e),{status:t});function En(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ns(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var rs='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function In(t,e,n,r){if(!t.supportsAudio)throw le(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(d){throw d instanceof F?le(404,d.message):d}if(!o){let d=null;if(t.realtimeCompanionsFor)try{d=await t.realtimeCompanionsFor(e)}catch(p){throw p instanceof F?le(404,p.message):p}if(d!==null)return await Pr(t,e,d,n,r);throw le(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw le(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(d){throw d instanceof F?le(404,d.message):d}if(i&&!t.openTurnsOn)throw le(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let d;try{d=await t.transcriptStreamFor(e)}catch(p){throw p instanceof F?le(404,p.message):p}if(d!=="stt")throw le(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw le(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${rs}`);if(r==="transcription"&&!i)throw le(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let s;try{s=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(d){throw d instanceof ae?le(503,d.message):d}let a=`conn_${(0,$r.randomUUID)()}`,l={audio:await t.openAudioOn(s,n,a).catch(d=>{throw t.releaseSessionHandle?.(s),d})},c={clients:{createResponse:async d=>await t.createResponseOn(s,d,a)},voice:o,audioSession:l};return t.openVideoOn&&(c.video=()=>t.openVideoOn(s,n)),i&&(c.turns=d=>t.openTurnsOn(s,d)),r==="transcription"&&(c.intent="transcription"),t.releaseSessionHandle&&(c.release=()=>t.releaseSessionHandle(s)),e!==void 0&&(c.model=e),c}function Gt(t,e,n){let r=Cr(t,n);return{resolve:async(o,i)=>{if(e!==void 0){let s=o.headers.authorization,a=typeof s=="string"?s.trim():"",u=a.startsWith("Bearer ")?a.slice(7).trim():"";if(u===""||u!==e)throw le(401,"invalid local proxy api key")}return In(r,En(o),i,ns(o))}}}var $=class extends Error{},pe=class extends Error{};function ee(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Wt(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function nt(t,e){if(t!=null)throw new $(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function On(t){let e=Wt(t);return e!==null&&e<=1?e:null}function Mr(t,e){if(!ee(t))throw new $("decisions requires a JSON object body");nt(t.prompt_cache_key,"prompt_cache_key"),nt(t.prompt_cache_options,"prompt_cache_options"),nt(t.safety_identifier,"safety_identifier");let n=[],r=os(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new $("decisions requires a questions array of 1 to 400 questions");let i={},s=[],a=new Set;for(let l=0;l<o.length;l++){let{entry:c,spec:d}=us(o[l],l,o.length,n);if(a.has(d.key))throw new $(`duplicate question name "${d.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(d.key),i[d.key]=c,s.push(d)}let u={model:e,state:r,questions:i};return n.length>0&&(u.media=n),{systemone:u,specs:s}}function os(t,e){if(typeof t=="string")return t;if(!ee(t)&&!Array.isArray(t))throw new $("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)ss(o,r,e);return is(r)}function is(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
17
+ ${Pr(n)}\r
18
+ `),t.destroy()}function zi(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
19
+ `}function Yi(t){De(process.stdout,t)}function Xi(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function kn(t){return t.audioSession?.audio.sessionId??void 0}function _t(t,e){let n=new ht.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==yt)return;r.add(i),i.on("close",()=>{r.delete(i)});let u=A("rtup"),l=Xi(o),d=h=>{(e.log??Yi)(zi(h))};d({stage:"accept",conn:u,model:l}),i.resume();let c=new AbortController,p=null,f=h=>{p??=h,c.abort(new Error(p))},m=()=>f("client socket closed"),k=()=>f("client socket closed (half-close)"),x=h=>f(`client socket error: ${h.message}`);i.once("close",m),i.once("end",k),i.once("error",x);let w=()=>{i.removeListener("close",m),i.removeListener("end",k),i.removeListener("error",x)},y=h=>{d({stage:"close",conn:u,model:l,...h})},g=null,v=!1,T=null,P=h=>JSON.stringify({type:Tr,event_id:A("event"),...h}),R=h=>{if(g!==null){g.readyState===ht.WebSocket.OPEN&&g.send(P(h));return}v||(v=!0,n.handleUpgrade(o,i,s,b=>{g=b,T=[],b.on("message",_=>{T?.push(String(_))}),d({stage:"waiting",conn:u,model:l,status:h.status}),b.send(P(h))}))},E=h=>{let b=h,_=b.session!=null&&typeof b.session.sendResponseCreate=="function",C=b.clients!=null&&typeof b.clients.createResponse=="function";if(!_&&!C)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((D,F)=>{let L=(N,te)=>{try{let J=Date.now();new Be({ws:N,binding:h,operatorLog:e.operatorLog,...te.length>0?{replayFrames:te}:{},onClosed:(ee,$)=>{y({while:"live",reason:$.reason});try{e.onSessionEnded?.({req:o,binding:h,connected_ms:Math.max(0,Date.now()-J),reason:$.reason})}catch(q){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${q instanceof Error?q.message:String(q)}
20
+ `)}}}),d({stage:"admit",conn:u,model:l,...kn(h)===void 0?{}:{session:kn(h)}}),D()}catch(J){F(J)}};if(g!==null){let N=T??[];T=null,L(g,N);return}n.handleUpgrade(o,i,s,N=>L(N,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,R).then(async h=>{if(c.signal.aborted){w();let b=kn(h);try{await h.release?.()}catch(_){y({while:"queued",...b===void 0?{}:{session:b},reason:p??"client socket closed",release_failed:_ instanceof Error?_.message:String(_)});return}y({while:"queued",...b===void 0?{}:{session:b},reason:p??"client socket closed",released:!0}),i.destroy();return}w(),await E(h)}).catch(h=>{let b=h instanceof xn.SessionFailedError?Bt(h):null,_=null;if(h!==null&&typeof h=="object"&&"status"in h){let L=h.status;typeof L=="number"&&(_=L)}let C=_??b?.status??502,D=h instanceof Error?h.message:String(h),F=_!==null?D:b!==null?mt(b,h instanceof xn.SessionFailedError&&h.status.sessionId?`session ${h.status.sessionId}`:void 0):le(h).message;if(y({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:D,status:C}}),g!==null&&!c.signal.aborted){let L=JSON.stringify({type:Tr,event_id:A("event"),status:C<500?"rejected":"failed",reason:F});g.readyState===ht.WebSocket.OPEN&&g.send(L),g.close(1011,Pr(F));return}i.destroyed||Ki(i,C,F)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}var Nr=require("crypto");var An="x-urun-profile",wt="voice";var ae=class extends Error{status=400},Qi=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Zi=/\s/;function es(t){return Qi.test(t)}function Rn(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ae(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Cr(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new ae(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new ae(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new ae(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function $r(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new ae(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let l=n.trim();if(l==="")throw new ae(`the ${An} header is empty \u2014 the only profile this lane accepts is "${wt}" (omit the header for the ordinary lane)`);if(l!==wt)throw new ae(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${wt}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==wt)throw new ae(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${wt}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new ae("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new ae("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Cr(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Cr(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Rn(u,"sentence_flush",!0),includeReasoning:Rn(u,"include_reasoning",!1),metadata:Rn(u,"metadata",!1)}}var tt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&es(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(Zi.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};var Ae=(t,e)=>Object.assign(new Error(e),{status:t}),rs='"transcription" (a transcription session), or no intent at all (the realtime voice session)',In=(t,e,n)=>new X(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),En=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof H?Ae(404,n.message):n}};async function Mr(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Ae(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${rs}`);if(o==="transcription")throw Ae(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw Ae(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw Ae(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(f){throw f instanceof H?Ae(404,f.message):f}if(!p)throw Ae(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(f){throw f instanceof H?Ae(404,f.message):f}if(p!=="stt")throw Ae(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let i=await En(t,n.stt),s=await En(t,e),a=await En(t,n.tts),u=await t.openAudioOn(i,r),l=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let f=new AbortController;return d=f,os({clients:t,chatHandle:s,ttsHandle:a,chatModel:e,companions:n},p,f.signal,()=>{d===f&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(i,p)}catch(f){throw f instanceof X?In("stt",n.stt,f):f}},composite:!0};return e!==void 0&&(c.model=e),c}function Lr(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Wt=class extends Error{};async function*os(t,e,n,r){let{clients:o,chatHandle:i,ttsHandle:s,chatModel:a,companions:u}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),f=!1,m=null,k=null,x=[],w=null,y=new Promise((b,_)=>{n&&n.addEventListener("abort",()=>_(new Wt),{once:!0})}),g=()=>f||n?.aborted===!0,v=async b=>{if(g())return;let _;try{_=await o.createResponseOn(s,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:b}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(D){throw D instanceof X?In("tts",u.tts,D):D}let C=_[Symbol.asyncIterator]();k=C;try{for(;;){let D=C.next(),F;try{F=await Promise.race([D,y])}catch(N){if(D.catch(()=>{}),N instanceof Wt)return;throw N}if(F.done)return;let L=F.value;if(L.type==="error"){let N=L.error&&typeof L.error.message=="string"?L.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${N}`)}if(L.type==="response.completed")return}}finally{k===C&&(k=null)}},T=async()=>{for(;x.length>0&&!g();){let b=x.shift();await v(b)}},P=b=>{if(b===""||g()||(x.push(b),w!==null))return;let _=T();w=_,_.then(()=>{w===_&&(w=null)},C=>{w===_&&(w=null),m??=C})},R=()=>{f=!0,x.length=0;let b=k;if(k=null,b){let _=b.return?.();_&&_.catch(()=>{})}},E=async()=>{for(;x.length>0||w!==null;){let b=w;if(b===null){await v(x.shift());continue}await b}},O=p?new tt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},b=>P(b)):null,h=null;try{let b;try{b=await o.createResponseOn(i,d)}catch(_){throw _ instanceof X?In("chat",a,_):_}for await(let _ of b){if(g())return;let C=_;if(C.type==="error"){yield _;return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){yield _,O?.push(C.delta);continue}if(C.type==="response.function_call_arguments.delta"){O?.flush(),yield _;continue}if(C.type==="response.completed"){h=_.response;continue}}O?.flush(),O?.dispose(),p&&await E(),h!==null&&(yield{type:"response.completed",response:h})}finally{O?.dispose(),R();try{if(m instanceof X)throw m}finally{r?.()}}}var de=(t,e)=>Object.assign(new Error(e),{status:t});function On(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function is(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var ss='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Tn(t,e,n,r,o){if(!t.supportsAudio)throw de(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 i;try{i=await t.supportsAudio(e)}catch(f){throw f instanceof H?de(404,f.message):f}if(!i){let f=null;if(t.realtimeCompanionsFor)try{f=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof H?de(404,m.message):m}if(f!==null)return await Mr(t,e,f,n,r);throw de(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw de(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(f){throw f instanceof H?de(404,f.message):f}if(s&&!t.openTurnsOn)throw de(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let f;try{f=await t.transcriptStreamFor(e)}catch(m){throw m instanceof H?de(404,m.message):m}if(f!=="stt")throw de(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw de(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ss}`);if(r==="transcription"&&!s)throw de(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(f){throw f instanceof ue?de(503,f.message):f}let u=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,l=`conn_${(0,Nr.randomUUID)()}`,c={audio:await t.openAudioOn(a,n,l,o).catch(f=>{throw t.releaseSessionHandle?.(a),f})},p={clients:{createResponse:async f=>await t.createResponseOn(a,f,l)},voice:i,audioSession:c};return t.openVideoOn&&(p.video=()=>t.openVideoOn(a,n)),s&&(p.turns=f=>t.openTurnsOn(a,f)),r==="transcription"&&(p.intent="transcription"),t.releaseSessionHandle&&(p.release=()=>t.releaseSessionHandle(a)),e!==void 0&&(p.model=e),u!==null&&(p.catalog=u),p}function Kt(t,e,n){let r=Lr(t,n);return{resolve:async(o,i,s)=>{if(e!==void 0){let a=o.headers.authorization,u=typeof a=="string"?a.trim():"",l=u.startsWith("Bearer ")?u.slice(7).trim():"";if(l===""||l!==e)throw de(401,"invalid local proxy api key")}return Tn(r,On(o),i,is(o),s)}}}var M=class extends Error{},fe=class extends Error{};function ne(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function zt(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function nt(t,e){if(t!=null)throw new M(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Pn(t){let e=zt(t);return e!==null&&e<=1?e:null}function Ur(t,e){if(!ne(t))throw new M("decisions requires a JSON object body");nt(t.prompt_cache_key,"prompt_cache_key"),nt(t.prompt_cache_options,"prompt_cache_options"),nt(t.safety_identifier,"safety_identifier");let n=[],r=as(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new M("decisions requires a questions array of 1 to 400 questions");let i={},s=[],a=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=cs(o[l],l,o.length,n);if(a.has(c.key))throw new M(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),i[c.key]=d,s.push(c)}let u={model:e,state:r,questions:i};return n.length>0&&(u.media=n),{systemone:u,specs:s}}function as(t,e){if(typeof t=="string")return t;if(!ne(t)&&!Array.isArray(t))throw new M("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)ls(o,r,e);return us(r)}function us(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
20
21
 
21
- `)}function ss(t,e,n){if(!ee(t))throw new $("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){as(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let i=t.output;if(typeof i=="string"){e.push({text:i});return}if(Array.isArray(i)){Lr(i,e,n,void 0,!1);return}throw new $(`${o} output must be a string or an array of parts`)}default:throw new $(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function as(t,e,n,r){e==="assistant"&&nt(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new $(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let i of o){if(!ee(i))throw new $("decisions assistant message parts must be JSON objects");if(i.type==="output_text"&&typeof i.text=="string")n.push({role:e,text:i.text});else if(i.type==="refusal"&&typeof i.refusal=="string")n.push({role:e,text:`[refusal] ${i.refusal}`});else throw new $(`unsupported decisions assistant message part type ${JSON.stringify(i.type??null)}`)}return}Lr(o,n,r,e)}function Lr(t,e,n,r,o=!0){for(let i of t){if(!ee(i))throw new $("decisions content parts must be JSON objects");switch(nt(i.prompt_cache_breakpoint,"prompt_cache_breakpoint"),i.type){case"input_text":{if(typeof i.text!="string")throw new $("input_text requires a string text");e.push({role:r,text:i.text});break}case"input_json":{if(!o)throw new $("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let s=i.data;if(!ee(s)&&!(Array.isArray(s)&&s.every(ee)))throw new $("input_json data must be an object or an array of objects");e.push({role:r,json:s});break}case"input_image":{n.push(Nr(i));break}default:throw new $(`unsupported decisions content part type ${JSON.stringify(i.type??null)}`)}}}function Nr(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new $("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new $("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new $("input_image data URL carries no image data");let i=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(i?o.length%4!==0:o.length%4===1))throw new $("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let s=t.detail;if(s!=null&&s!=="low"&&s!=="high"&&s!=="auto"&&s!=="original")throw new $("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(s==="low"||s==="high")&&(a.detail=s),a}function us(t,e,n,r){if(!ee(t))throw new $(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new $(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let i=t.name;if(i!==void 0&&typeof i!="string")throw new $(`questions[${e}] name must be a string`);let s=i??null,a=s??`q${e}`,u=ls(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:u,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:a,name:s}};case"choice":{let l=t.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new $(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let c=[],d=new Set,p=[];for(let k of l){if(!ee(k))throw new $(`questions[${e}] choices must be JSON objects`);let R=k.value;if(typeof R!="string"&&typeof R!="boolean")throw new $(`questions[${e}] choice value must be a string or boolean`);let y=String(R);if(d.has(y))throw new $(`questions[${e}] has duplicate choice value ${JSON.stringify(y)} (choices must be unique)`);d.add(y);let g=k.description;if(g!==void 0&&typeof g!="string")throw new $(`questions[${e}] choice description must be a string`);c.push(R),p.push(g)}let m=l.map((k,R)=>({name:String(c[R]),description:p[R]??String(c[R])}));return{entry:{kind:"choice",prompt:u,options:m},spec:{type:o,key:a,name:s,choiceValues:c}}}case"score":{let l=t.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new $(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let c=[],d=[];for(let m of l){if(!ee(m)||typeof m.label!="string")throw new $(`questions[${e}] score levels must carry a string label`);if(c.includes(m.label))throw new $(`questions[${e}] has duplicate level label ${JSON.stringify(m.label)}`);c.push(m.label);let f=m.description;if(f!==void 0&&typeof f!="string")throw new $(`questions[${e}] score level description must be a string`);let k=f!==void 0?`${m.label}: ${f}`:m.label;if(d.includes(k))throw new $(`questions[${e}] has duplicate score criterion ${JSON.stringify(k)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);d.push(k)}return{entry:{kind:"score",prompt:u,criteria:d},spec:{type:o,key:a,name:s,levelLabels:c}}}}}function ls(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new $(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let i of t){if(!ee(i))throw new $(`questions[${e}] instruction parts must be JSON objects`);switch(nt(i.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),i.type){case"input_text":{if(typeof i.text!="string")throw new $(`questions[${e}] input_text requires a string text`);o.push(i.text);break}case"input_image":{if(n>1)throw new $(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(Nr(i));break}case"input_json":{let s=i.data;if(!ee(s)&&!(Array.isArray(s)&&s.every(ee)))throw new $(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(s));break}default:throw new $(`unsupported decisions instruction part type ${JSON.stringify(i.type??null)}`)}}return o.join(`
22
+ `)}function ls(t,e,n){if(!ne(t))throw new M("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){ds(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let i=t.output;if(typeof i=="string"){e.push({text:i});return}if(Array.isArray(i)){Dr(i,e,n,void 0,!1);return}throw new M(`${o} output must be a string or an array of parts`)}default:throw new M(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function ds(t,e,n,r){e==="assistant"&&nt(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new M(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let i of o){if(!ne(i))throw new M("decisions assistant message parts must be JSON objects");if(i.type==="output_text"&&typeof i.text=="string")n.push({role:e,text:i.text});else if(i.type==="refusal"&&typeof i.refusal=="string")n.push({role:e,text:`[refusal] ${i.refusal}`});else throw new M(`unsupported decisions assistant message part type ${JSON.stringify(i.type??null)}`)}return}Dr(o,n,r,e)}function Dr(t,e,n,r,o=!0){for(let i of t){if(!ne(i))throw new M("decisions content parts must be JSON objects");switch(nt(i.prompt_cache_breakpoint,"prompt_cache_breakpoint"),i.type){case"input_text":{if(typeof i.text!="string")throw new M("input_text requires a string text");e.push({role:r,text:i.text});break}case"input_json":{if(!o)throw new M("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let s=i.data;if(!ne(s)&&!(Array.isArray(s)&&s.every(ne)))throw new M("input_json data must be an object or an array of objects");e.push({role:r,json:s});break}case"input_image":{n.push(Fr(i));break}default:throw new M(`unsupported decisions content part type ${JSON.stringify(i.type??null)}`)}}}function Fr(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new M("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new M("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new M("input_image data URL carries no image data");let i=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(i?o.length%4!==0:o.length%4===1))throw new M("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let s=t.detail;if(s!=null&&s!=="low"&&s!=="high"&&s!=="auto"&&s!=="original")throw new M("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(s==="low"||s==="high")&&(a.detail=s),a}function cs(t,e,n,r){if(!ne(t))throw new M(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new M(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let i=t.name;if(i!==void 0&&typeof i!="string")throw new M(`questions[${e}] name must be a string`);let s=i??null,a=s??`q${e}`,u=ps(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:u,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:a,name:s}};case"choice":{let l=t.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new M(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let k of l){if(!ne(k))throw new M(`questions[${e}] choices must be JSON objects`);let x=k.value;if(typeof x!="string"&&typeof x!="boolean")throw new M(`questions[${e}] choice value must be a string or boolean`);let w=String(x);if(c.has(w))throw new M(`questions[${e}] has duplicate choice value ${JSON.stringify(w)} (choices must be unique)`);c.add(w);let y=k.description;if(y!==void 0&&typeof y!="string")throw new M(`questions[${e}] choice description must be a string`);d.push(x),p.push(y)}let f=l.map((k,x)=>({name:String(d[x]),description:p[x]??String(d[x])}));return{entry:{kind:"choice",prompt:u,options:f},spec:{type:o,key:a,name:s,choiceValues:d}}}case"score":{let l=t.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new M(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let f of l){if(!ne(f)||typeof f.label!="string")throw new M(`questions[${e}] score levels must carry a string label`);if(d.includes(f.label))throw new M(`questions[${e}] has duplicate level label ${JSON.stringify(f.label)}`);d.push(f.label);let m=f.description;if(m!==void 0&&typeof m!="string")throw new M(`questions[${e}] score level description must be a string`);let k=m!==void 0?`${f.label}: ${m}`:f.label;if(c.includes(k))throw new M(`questions[${e}] has duplicate score criterion ${JSON.stringify(k)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(k)}return{entry:{kind:"score",prompt:u,criteria:c},spec:{type:o,key:a,name:s,levelLabels:d}}}}}function ps(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new M(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let i of t){if(!ne(i))throw new M(`questions[${e}] instruction parts must be JSON objects`);switch(nt(i.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),i.type){case"input_text":{if(typeof i.text!="string")throw new M(`questions[${e}] input_text requires a string text`);o.push(i.text);break}case"input_image":{if(n>1)throw new M(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(Fr(i));break}case"input_json":{let s=i.data;if(!ne(s)&&!(Array.isArray(s)&&s.every(ne)))throw new M(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(s));break}default:throw new M(`unsupported decisions instruction part type ${JSON.stringify(i.type??null)}`)}}return o.join(`
22
23
 
23
- `)}function Ur(t,e){if(!ee(e))throw new pe("decision answer was not a JSON object");let n=e.answers;if(!ee(n))throw new pe("decision answer carried no answers object");let r=[];for(let o of t){let i=n[o.key];if(!ee(i)||i.skipped===!0){r.push({type:"refusal",name:o.name});continue}let s=ee(i.probabilities)?i.probabilities:{};switch(o.type){case"predicate":{let a=On(i.noul);if(a===null)throw new pe(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:a});continue}case"choice":{let a=o.choiceValues??[],u=i.choice;if(typeof u!="string")throw new pe(`the choice answer for "${o.key}" carries no string choice`);let l=a.findIndex(p=>String(p)===u);if(l===-1)throw new pe(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(u)})`);let c=Wt(i.confidence);if(c===null)throw new pe(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let p of a){let m=On(s[String(p)]);m!==null&&d.push({value:p,probability:m})}r.push({type:"choice",name:o.name,choice:a[l],confidence:c,probabilities:d});continue}case"score":{let a=o.levelLabels??[],u=Wt(i.score);if(u===null)throw new pe(`the score answer for "${o.key}" carries no numeric score to translate`);let l=Wt(i.confidence);if(l===null)throw new pe(`the score answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let d=0;d<a.length;d++){let p=On(s[String(d)]);p!==null&&c.push({value:d,label:a[d],probability:p})}r.push({type:"score",name:o.name,score:u,confidence:l,probabilities:c});continue}}}return r}var te=class extends Error{};async function Kt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new te(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let i of t){let s=i;if(o+=s.length,o>e)throw new te(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function zt(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(s){try{let a=await n.next();if(a.done){s.close();return}if(r+=a.value.length,r>e){s.error(new te(`request body exceeds the ${e}-byte limit`));return}s.enqueue(a.value)}catch(a){s.error(a)}},cancel(){n.return?.()}}),i;try{let s=new Headers;for(let[l,c]of Object.entries(t.headers))if(typeof c=="string")s.set(l,c);else if(Array.isArray(c))for(let d of c)s.append(l,d);let a={method:"POST",headers:s,body:o,duplex:"half"};i=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(s){throw s instanceof te?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var Dr="/v1/images/generations",Yt="/v1/images/edits";function Fr(t){return t===Dr||t===Yt}var qr="/v1/images/models";async function Br(t,e,n){if(t){if(t.model=oe({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var N=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},ds=16*1024*1024,jr=64*1024*1024;function Hr(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 wt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function Jr(t,e,n,r,o,i){let s=i??(f=>console.error(f)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),u=null;for await(let f of a){if(f.type==="error"){let k=f.error??{},R=typeof k.message=="string"&&k.message.length>0&&ge(k.message)?k.message:null;throw R===null?(s(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(f)}`),new N(502,"the image upstream failed while serving this request")):new N(502,`image upstream error: ${R}`)}if(f.type==="response.completed"){u=f.response??null;break}}if(u===null)throw new N(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=xe(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new N(502,`image upstream returned ${Array.isArray(l)?l.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 c=[],d=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(d,"base64");if(Hr(p)===null)throw new N(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return c.push(d),{images:c}}function Vr(t,e){if(t instanceof N)return t;if(t instanceof ve)throw t;return t instanceof F?new N(404,t.message):new N(502,Ze("image",t,e))}async function Gr(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return wt(r,new N(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Wr(t,e){t&&(t.outputUnits=e.images.length)}function Kr(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 cs={model:!0,prompt:!0,response_format:!0,n:!0};async function zr(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??jr;try{if(t.method!=="POST")throw new N(405,`${String(t.method)} is not supported on ${Dr}`);let i;try{i=JSON.parse((await Kt(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof te?new N(413,p.message):new N(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new N(400,"request body must be a JSON object");let s=i;for(let p of Object.keys(s))if(!cs[p])throw new N(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let a=s.prompt;if(typeof a!="string"||a.trim().length===0)throw new N(400,"prompt is required and must be a non-empty string","prompt");let u=s.model===void 0?void 0:s.model;if(u!==void 0&&typeof u!="string")throw new N(400,"model must be a string","model");await Br(n.turn,n.clients,u);let l=s.n??1;if(l!==1)throw new N(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 c=s.response_format??"b64_json";if(c!=="b64_json")throw new N(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",a.length,a.length),!await Gr(n.imageModels,u,"generation",e))return;let d=[{type:"input_text",text:a}];try{let p=await Jr(n.clients,u,d,n.turn?de(n.turn):void 0,n.turn,r);Wr(n.turn,p),Kr(e,p)}catch(p){throw Vr(p,r)}}catch(i){if(i instanceof te){wt(e,new N(413,i.message));return}if(i instanceof N){wt(e,i);return}throw i}}var ps={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Yr(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??jr,i=n.maxImagePartBytes??ds;try{if(t.method!=="POST")throw new N(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 N(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let a;try{a=await zt(t,o)}catch(f){throw f instanceof te?new N(413,f.message):new N(400,String(f instanceof Error?f.message:f))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new N(400,"prompt is required and must be a non-empty string field","prompt");let l=a.get("model");if(l!==null&&typeof l!="string")throw new N(400,"model must be a string field","model");let c=l===null?void 0:l;await Br(n.turn,n.clients,c);let d=a.get("response_format")??"b64_json";if(d!=="b64_json")throw new N(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let f of a.keys())if(!ps[f])throw new N(400,`form field "${f}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,f);let p=[];for(let f of["image","image[]"])for(let k of a.getAll(f)){if(!(k instanceof File))throw new N(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",f);if(k.size>i)throw new N(413,`image part exceeds the ${i}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let R=new Uint8Array(await k.arrayBuffer()),y=Hr(R);if(y===null)throw new N(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",f);p.push({bytes:R,mime:y})}if(p.length===0)throw new N(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await Gr(n.imageModels,c,"edit",e))return;let m=[{type:"input_text",text:u}];for(let{bytes:f,mime:k}of p)m.push({type:"input_image",image_url:`data:${k};base64,${Buffer.from(f).toString("base64")}`});try{let f=await Jr(n.clients,c,m,n.turn?de(n.turn):void 0,n.turn,r);Wr(n.turn,f),Kr(e,f)}catch(f){throw Vr(f,r)}}catch(s){if(s instanceof te){wt(e,new N(413,s.message));return}if(s instanceof N){wt(e,s);return}throw s}}var vt="/v1/audio/speech";function io(t){return t===vt}var Xr=4096,Qr=18e4,Zr=5e3,fs=64*1024*1024,eo=8,to=5,no=1024*1024,rt="voice_applied",Qt="X-Urun-Voice-Applied",L=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Tn(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 Zt=class extends L{constructor(e){super(502,e)}};function so(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function ao(t){return new L(502,`the runtime's ${rt} receipt ${JSON.stringify(t)} cannot be relayed as the ${Qt} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function ms(t,e,n){if(t){if(t.model=oe({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function uo(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var hs=2;function gs(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>hs)return!1;return!0}function ys(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var ro=new WeakMap,Xt=new WeakMap;function _s(t,e){let n=Xt.get(t)??0;if(n>=eo)throw new L(503,`this model's speech queue is full \u2014 ${eo} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${to}s`,void 0,to);Xt.set(t,n+1);let r=ro.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return ro.set(t,i),(async()=>{await r;try{return await e()}finally{Xt.set(t,(Xt.get(t)??1)-1),o()}})()}async function ws(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new L(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(s){if(!(s instanceof Y))throw s}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),i;await Promise.race([o,new Promise(s=>{i=setTimeout(s,r)})]).finally(()=>{i!==void 0&&clearTimeout(i)})}function Be(t,e){if(t instanceof L)return t;if(t instanceof ve)throw t;return t instanceof F?new L(404,t.message):new L(502,Ze("speech",t,e))}async function oo(t,e,n,r,o,i,s,a,u,l){let c=l??(p=>console.error(p)),d=a??(()=>{});return _s(e,async()=>{if(s?.()===!0)return null;let p=!1,m=!1,f=!1,k,R=new Promise(A=>{k=A}),y=[],g=()=>{m&&!f&&y.length>=o.quietRunFrames&&(f=!0,k())},h=e.onOutputAudio(A=>{let T=Buffer.from(A,"base64");if(T.byteLength===0)return;let x=gs(T);if(!p){if(x)return;p=!0}if(x){y.push(T),g();return}for(let I of y)d(I);y.length=0,d(T),g()}),_=null,v,E,b;try{b=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let T=new Promise(w=>{E=setTimeout(w,i.capMs)}),x=!1;for(;;){let w=b.next(),C=await Promise.race([w,T]);if(C===void 0){x=!0,w.catch(()=>{});break}if(C.done)break;let q=C.value;if(q.type==="error"){let D=q.error??{};await b.return?.();let z=typeof D.message=="string"&&D.message.length>0&&ge(D.message)?D.message:null;throw z===null?(c(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(q)}`),new L(502,"the speech upstream failed while serving this request")):new L(502,`speech upstream error: ${z}`)}if(q.type==="response.completed"){_=q.response??null,m=!0,u?.(_),g(),await b.return?.();break}}if(clearTimeout(E),x)throw new L(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(_===null)throw new L(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let I=!1;if(await Promise.race([R,new Promise(w=>{v=setTimeout(()=>{I=!0,w()},o.capMs)})]),v!==void 0&&clearTimeout(v),r.voice!==void 0){let w=_[rt];if(typeof w!="string"||w!==r.voice){let C=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof w=="string"?`${rt} ${JSON.stringify(w)}`:`no ${rt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw f?new Zt(C):new L(502,C)}}if(!p)throw new L(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(I&&!f&&y.length<1)throw new L(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return _}catch(A){throw A instanceof Zt||await ws(t,n,b,i.returnBoundMs),A}finally{v!==void 0&&clearTimeout(v),E!==void 0&&clearTimeout(E),h()}})}function vs(t,e,n,r){let o=!1,i=0,s=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Qt)),t.write(a,u=>{u||(i+=a.byteLength,uo(e,i))}),t.writableLength>no&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${no} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let u=a[rt];if(typeof u=="string"){if(!so(u))throw ao(u);t.addTrailers({[Qt]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:s}}async function bs(t,e,n,r){let o;try{o=await t(e)}catch(i){throw Be(i,r)}return o?!0:(Tn(n,new L(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Ss={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},ks="wav, pcm";async function lo(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??fs,i=!1;e.once("close",()=>{i=!0});let s=()=>i||e.destroyed;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${vt}`);let a;try{a=JSON.parse((await Kt(t,o)).toString("utf8")||"{}")}catch(_){throw _ instanceof te?new L(413,_.message):new L(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new L(400,"request body must be a JSON object");let u=a;for(let _ of Object.keys(u))if(!Ss[_])throw new L(400,`request field "${_}" 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.`,_);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new L(400,"input is required and must be a non-empty string","input");if(l.length>Xr)throw new L(400,`input is ${l.length} chars \u2014 over the ${Xr}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let c=u.model===void 0?void 0:u.model;if(c!==void 0&&typeof c!="string")throw new L(400,"model must be a string","model");let d=u.voice;if(d!==void 0&&(typeof d!="string"||d.trim().length===0))throw new L(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new L(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${vt} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(c)}catch(_){throw Be(_,r)}if(p.defect!==null)throw new L(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof d=="string"?d:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new L(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let f=u.response_format??"wav";if(f!=="wav"&&f!=="pcm")throw new L(400,`response_format ${JSON.stringify(f)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${ks} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new L(400,"stream_format, when present, must be a string","stream_format");let k=u.speed;if(k!==void 0){if(typeof k!="number"||!Number.isFinite(k))throw new L(400,"speed, when present, must be a number","speed");if(k!==1)throw new L(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 R=u.instructions;if(R!==void 0){if(typeof R!="string")throw new L(400,"instructions, when present, must be a string","instructions");if(R.trim().length>0)throw new L(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await ms(n.turn,n.clients,c);let y=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",y,y),!await bs(n.speechModels,c,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new L(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new L(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new L(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let g;try{g=await n.clients.speechSessionHandle(c)}catch(_){throw Be(_,r)}let h;try{h=await n.clients.openAudioOn(g)}catch(_){throw Be(_,r)}n.turn&&(n.turn.sessionId=h.sessionId);try{if(f==="wav"){let _=[],v=await oo(n.clients,h,g,{model:c,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Qr,returnBoundMs:n.turnReturnBoundMs??Zr},s,b=>_.push(b),b=>{n.turn&&(n.turn.outputSeconds=xe(b))},r);if(v===null||s())return;let E=Buffer.concat(_);if(m===void 0){let b=v[rt];if(typeof b=="string"){if(!so(b))throw ao(b);e.setHeader(Qt,b)}}uo(n.turn,E.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([ys(E.byteLength),E]))}else{let _=vs(e,n.turn,s,m===void 0),v;try{v=await oo(n.clients,h,g,{model:c,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Qr,returnBoundMs:n.turnReturnBoundMs??Zr},s,_.sink,E=>{n.turn&&(n.turn.outputSeconds=xe(E))},r)}catch(E){let b=Be(E,r);if(!_.started())throw b;n.turn&&(n.turn.streamError=!0),_.fail(b);return}if(v===null)return;try{await _.finish(v)}catch(E){let b=Be(E,r);n.turn&&(n.turn.streamError=!0),_.fail(b);return}}}catch(_){throw Be(_,r)}}catch(a){if(a instanceof te){Tn(e,new L(413,a.message));return}if(a instanceof L){Tn(e,a);return}throw a}}var en="/v1/audio/transcriptions";function co(t){return t===en}var po="/v1/audio/models",xs=16*1024*1024,Rs=64*1024*1024,K=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Pn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function fo(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function As(t){if(!fo(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),s=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,l=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,c=t[a+14]|t[a+15]<<8;n={sampleRate:l,channels:u,bitsPerSample:c}}else if(i==="data"){let u=t.length-a;r=Math.min(s===0||s===4294967295?u:s,u)}e=a+s+s%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Es(t,e,n){if(t){if(t.model=oe({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Is(t,e){t&&(t.outputUnits=e.seconds)}async function Os(t,e,n,r,o,i,s){let a=s??(d=>console.error(d)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],c=null;for await(let d of u){if(l.push(d),d.type==="error"){let p=d.error??{},m=typeof p.type=="string"?p.type:"upstream_error",f=typeof p.message=="string"&&p.message.length>0&&ge(p.message)?p.message:null;throw f===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(d)}`),new K(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new K(m==="invalid_request_error"?400:502,`transcription upstream error: ${f}`)}if(d.type==="response.completed"){c=d.response??null;break}}if(c===null)throw new K(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return i&&(i.outputSeconds=xe(c)),Ye(l,c)}function mo(t,e){if(t instanceof K)return t;if(t instanceof ve)throw t;return t instanceof F?new K(404,t.message):new K(502,Ze("transcription",t,e))}async function Ts(t,e,n,r){let o;try{o=await t(e)}catch(i){throw mo(i,r)}return o?!0:(Pn(n,new K(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Ps=new Set(["file","model","language","response_format"]);async function ho(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Rs,i=n.maxAudioPartBytes??xs;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${en}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new K(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let a;try{a=await zt(t,o)}catch(g){throw g instanceof te?new K(413,g.message):new K(400,String(g instanceof Error?g.message:g))}let u=new Map;for(let g of a.keys()){if(!Ps.has(g))throw new K(400,`form field "${g}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,g);u.set(g,(u.get(g)??0)+1)}for(let[g,h]of u)if(h>1)throw new K(400,`form field "${g}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,g);let l=a.get("model");if(l!==null&&typeof l!="string")throw new K(400,"model must be a string field","model");let c=l===null?void 0:l,d=a.get("language");if(d!==null&&(typeof d!="string"||d.trim().length===0))throw new K(400,"language, when present, must be a non-empty string","language");let p=d===null?void 0:d,m=a.get("response_format")??"json";if(m!=="json")throw new K(400,`response_format ${JSON.stringify(m)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let f=a.get("file");if(!(f instanceof File))throw new K(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(f.size>i)throw new K(413,`file part exceeds the ${i}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let k=new Uint8Array(await f.arrayBuffer());if(!fo(k))throw new K(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let R=As(k);if(R===null)throw new K(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Es(n.turn,n.clients,c),n.stats?.request("audio_transcriptions",k.length,k.length),!await Ts(n.transcriptionModels,c,e,r))return;let y=[{type:"input_audio",input_audio:{data:Buffer.from(k).toString("base64"),format:"wav"}}];try{let g=await Os(n.clients,c,y,p,n.turn?de(n.turn):void 0,n.turn,r);Is(n.turn,R),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:g}))}catch(g){throw mo(g,r)}}catch(s){if(s instanceof te){Pn(e,new K(413,s.message));return}if(s instanceof K){Pn(e,s);return}throw s}}var yo="/v1/usage/requests",go=1e4,Cs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Oe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},ot=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var _o=1024*1024;function Cn(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Oe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Oe(`"${e}" must be an array of uuid strings`);if(n.length>go)throw new Oe(`"${e}" carries ${n.length} ids; at most ${go} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let i of n){if(typeof i!="string"||!Cs.test(i))throw new Oe(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(i)||(o.add(i),r.push(i))}return r}function wo(t){return Cn(t,"inference_ids")}function tn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let i=t[o];if(!n.has(i.inference_id))throw new ot(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(i.inference_id))throw new ot(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(i.inference_id)}}var sn=require("@urun-sh/core");var $n="/partners/huggingface/v1/billing/requests";function $s(t){return Cn(t,"requestIds")}function Ms(t){return t>=200&&t<=399}function Ls(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Ms(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function vo(t,e){let n=$s(t),r=await e(n);return tn(r,n),Ls(r)}var Ns={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Us(t){return Ns[t]??null}var xo=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Ds(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Fs(t){return t==="surface"}function qs(t){let e=t?.ledgerFailureReason;return xo.includes(e)?e:"unknown"}var Bs=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],bo=["priced","unpriced"],js={written:bo,already_written:bo,skipped:Bs,failed:xo},fd=Object.entries(js).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Hs(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Js(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 Vs=256,So=4096,St=12e4,Gs=250,Ws=8e3,kt=[],ko=new Set,xt=0,bt=!1;var Ks=new Set;function zs(){return xt===0&&kt.length===0}function Ys(){if(zs()){bt=!1;for(let t of[...Ks])t()}}function Ro(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
24
- `}function Xs(t){De(process.stdout,t)}function Ao(t,e){try{t(e)}catch{}}function Eo(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Xs,o=Us(e.path);if(o===null)return;let i=c=>{try{n.observe(c)}catch{}},s=(c,d)=>{i({outcome:"skipped",reason:c}),Ao(r,Ro("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:c,detail:d}))};if(e.status===null){s("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){s("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){s("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){s("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:Js(e),completed_at:e.ts,billable_outcome:Hs(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(kt.length>=So){s("queue_full",`${kt.length} ledger writes are already waiting (capacity ${So}, ${xt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}kt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),xt<Vs&&(xt+=1,Qs())}async function Qs(){try{for(;;){let t=Zs();if(t===void 0)return;ko.add(t);try{await ea(t)}finally{ko.delete(t)}}}finally{xt-=1,Ys()}}function Zs(){let t=Date.now();for(;;){let e=kt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<St)return e;it(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${St}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function ea(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);it(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let i=Ds(o);if(i!==null){it(t,{outcome:"already_written",reason:i.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:i.cost_nano_usd,price_version:i.price_version,attempts:t.attempts});return}let s=qs(o),a=Date.now()-t.queuedAt;if(bt){it(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Fs(s)&&a<St){if(await na(ta(t.attempts)),bt||Date.now()-t.queuedAt>=St){let u=Date.now()-t.queuedAt;it(t,{outcome:"failed",reason:bt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:bt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${St}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}it(t,{outcome:"failed",reason:s},{event:"inference_ledger_write_failed",reason:s,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function ta(t){return Math.min(Ws,Gs*2**Math.max(0,t-1))}function na(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function it(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Ao(t.report,Ro(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function Nn(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function ra(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function ne(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function J(t,e,n,r="invalid_request_error",o){ne(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Un(t,e,n){let r=e.error,o=r?.type??"upstream_error",i=n?.operatorError??(c=>console.error(c)),s=be(r),a=s??ye(n?.inferenceId??null);s===null&&i(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let u=r?.code??null,l=o==="invalid_request_error"?400:u==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),ne(t,l,{error:{message:a,type:o,code:u}})}function _e(t,e,n,r){ne(t,e,{type:"error",error:{type:n,message:r}})}function st(t,e,n){if(e==="anthropic"){ne(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ne(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var oa=64*1024*1024,Rt=class extends Error{};async function Io(t,e=oa){let n=[],r=0;for await(let i of t){if(r+=i.length,r>e)throw new Rt(`request body exceeds ${e} bytes`);n.push(i)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function je(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function Po(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),i=r(n.output_tokens),s=u=>u??0,a=r(n.total_tokens)??s(o)+s(i);if(s(o)>0||s(i)>0){let u={input_tokens:s(o),output_tokens:s(i),total_tokens:a};return o===null||i===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function nn(t){let e=Po(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Oo(t){let e=nn(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:ia(t)},completion_tokens_details:{reasoning_tokens:0}}}function ia(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function sa(t,e){let n=Po(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function aa(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let l=n[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),i=r("prefill_ms"),s=r("decode_ms"),a=r("total_ms");return o===null||i===null||s===null||a===null?null:{queue_ms:o,prefill_ms:i,decode_ms:s,total_ms:a}}function ua(t,e){let n=aa(e);n&&(t.timing=n),t.outputSeconds=xe(e)}function He(t,e){sa(t,e),ua(t,e)}async function an(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function Co(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function la(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 rn=class extends Error{};function da(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new rn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function ca(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:da(n.role,n.content)})}return e}function Mn(t){return Ke(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 pa(t,e,n,r,o,i,s){let a=ct(i.id),u=t.stream===!0;if(i.model=oe(t),i.stream=u,await an(i,e,typeof t.model=="string"?t.model:void 0),u){let g;try{g=await ft({body:t,clients:e,store:n,stats:o,responseId:a,turn:i})}catch(h){if(h instanceof F){st(r,"openai",h);return}if(h instanceof ce){J(r,h.status,h.message);return}if(h instanceof me||h instanceof ae){r.setHeader("retry-after","2"),J(r,503,h.message,"capacity_error");return}throw h}Nn(r);for await(let h of g.events){if(h.type==="error"){i.streamError=!0;let _=h.error,v=be(_),E=v??ye(i.id);v===null&&s(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(h)}`),r.write(`event: error
25
- data: ${JSON.stringify({error:{message:E,type:_?.type??"upstream_error",code:_?.code??null}})}
24
+ `)}function Br(t,e){if(!ne(e))throw new fe("decision answer was not a JSON object");let n=e.answers;if(!ne(n))throw new fe("decision answer carried no answers object");let r=[];for(let o of t){let i=n[o.key];if(!ne(i)||i.skipped===!0){r.push({type:"refusal",name:o.name});continue}let s=ne(i.probabilities)?i.probabilities:{};switch(o.type){case"predicate":{let a=Pn(i.noul);if(a===null)throw new fe(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:a});continue}case"choice":{let a=o.choiceValues??[],u=i.choice;if(typeof u!="string")throw new fe(`the choice answer for "${o.key}" carries no string choice`);let l=a.findIndex(p=>String(p)===u);if(l===-1)throw new fe(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(u)})`);let d=zt(i.confidence);if(d===null)throw new fe(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let f=Pn(s[String(p)]);f!==null&&c.push({value:p,probability:f})}r.push({type:"choice",name:o.name,choice:a[l],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],u=zt(i.score);if(u===null)throw new fe(`the score answer for "${o.key}" carries no numeric score to translate`);let l=zt(i.confidence);if(l===null)throw new fe(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<a.length;c++){let p=Pn(s[String(c)]);p!==null&&d.push({value:c,label:a[c],probability:p})}r.push({type:"score",name:o.name,score:u,confidence:l,probabilities:d});continue}}}return r}var re=class extends Error{};async function Yt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new re(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let i of t){let s=i;if(o+=s.length,o>e)throw new re(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function Xt(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(s){try{let a=await n.next();if(a.done){s.close();return}if(r+=a.value.length,r>e){s.error(new re(`request body exceeds the ${e}-byte limit`));return}s.enqueue(a.value)}catch(a){s.error(a)}},cancel(){n.return?.()}}),i;try{let s=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")s.set(l,d);else if(Array.isArray(d))for(let c of d)s.append(l,c);let a={method:"POST",headers:s,body:o,duplex:"half"};i=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(s){throw s instanceof re?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var qr="/v1/images/generations",Qt="/v1/images/edits";function jr(t){return t===qr||t===Qt}var Hr="/v1/images/models";async function Jr(t,e,n){if(t){if(t.model=ie({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var B=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},fs=16*1024*1024,Vr=64*1024*1024;function Gr(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 vt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function Wr(t,e,n,r,o,i){let s=i??(m=>console.error(m)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),u=null;for await(let m of a){if(m.type==="error"){let k=m.error??{},x=typeof k.message=="string"&&k.message.length>0&&ye(k.message)?k.message:null;throw x===null?(s(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(m)}`),new B(502,"the image upstream failed while serving this request")):new B(502,`image upstream error: ${x}`)}if(m.type==="response.completed"){u=m.response??null;break}}if(u===null)throw new B(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Re(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new B(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(Gr(p)===null)throw new B(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function Kr(t,e){if(t instanceof B)return t;if(t instanceof be)throw t;return t instanceof H?new B(404,t.message):new B(502,Ze("image",t,e))}async function zr(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return vt(r,new B(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Yr(t,e){t&&(t.outputUnits=e.images.length)}function Xr(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 ms={model:!0,prompt:!0,response_format:!0,n:!0};async function Qr(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Vr;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${qr}`);let i;try{i=JSON.parse((await Yt(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof re?new B(413,p.message):new B(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new B(400,"request body must be a JSON object");let s=i;for(let p of Object.keys(s))if(!ms[p])throw new B(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let a=s.prompt;if(typeof a!="string"||a.trim().length===0)throw new B(400,"prompt is required and must be a non-empty string","prompt");let u=s.model===void 0?void 0:s.model;if(u!==void 0&&typeof u!="string")throw new B(400,"model must be a string","model");await Jr(n.turn,n.clients,u);let l=s.n??1;if(l!==1)throw new B(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 d=s.response_format??"b64_json";if(d!=="b64_json")throw new B(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",a.length,a.length),!await zr(n.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Wr(n.clients,u,c,n.turn?ce(n.turn):void 0,n.turn,r);Yr(n.turn,p),Xr(e,p)}catch(p){throw Kr(p,r)}}catch(i){if(i instanceof re){vt(e,new B(413,i.message));return}if(i instanceof B){vt(e,i);return}throw i}}var gs={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Zr(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Vr,i=n.maxImagePartBytes??fs;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${Qt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new B(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let a;try{a=await Xt(t,o)}catch(m){throw m instanceof re?new B(413,m.message):new B(400,String(m instanceof Error?m.message:m))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new B(400,"prompt is required and must be a non-empty string field","prompt");let l=a.get("model");if(l!==null&&typeof l!="string")throw new B(400,"model must be a string field","model");let d=l===null?void 0:l;await Jr(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new B(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let m of a.keys())if(!gs[m])throw new B(400,`form field "${m}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,m);let p=[];for(let m of["image","image[]"])for(let k of a.getAll(m)){if(!(k instanceof File))throw new B(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(k.size>i)throw new B(413,`image part exceeds the ${i}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let x=new Uint8Array(await k.arrayBuffer()),w=Gr(x);if(w===null)throw new B(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);p.push({bytes:x,mime:w})}if(p.length===0)throw new B(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await zr(n.imageModels,d,"edit",e))return;let f=[{type:"input_text",text:u}];for(let{bytes:m,mime:k}of p)f.push({type:"input_image",image_url:`data:${k};base64,${Buffer.from(m).toString("base64")}`});try{let m=await Wr(n.clients,d,f,n.turn?ce(n.turn):void 0,n.turn,r);Yr(n.turn,m),Xr(e,m)}catch(m){throw Kr(m,r)}}catch(s){if(s instanceof re){vt(e,new B(413,s.message));return}if(s instanceof B){vt(e,s);return}throw s}}var bt="/v1/audio/speech";function uo(t){return t===bt}var eo=4096,to=18e4,no=5e3,hs=64*1024*1024,ro=8,oo=5,io=1024*1024,rt="voice_applied",en="X-Urun-Voice-Applied",U=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Cn(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 tn=class extends U{constructor(e){super(502,e)}};function lo(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function co(t){return new U(502,`the runtime's ${rt} receipt ${JSON.stringify(t)} cannot be relayed as the ${en} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function ys(t,e,n){if(t){if(t.model=ie({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function po(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var _s=2;function ws(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>_s)return!1;return!0}function vs(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var so=new WeakMap,Zt=new WeakMap;function bs(t,e){let n=Zt.get(t)??0;if(n>=ro)throw new U(503,`this model's speech queue is full \u2014 ${ro} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${oo}s`,void 0,oo);Zt.set(t,n+1);let r=so.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return so.set(t,i),(async()=>{await r;try{return await e()}finally{Zt.set(t,(Zt.get(t)??1)-1),o()}})()}async function Ss(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new U(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(s){if(!(s instanceof X))throw s}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),i;await Promise.race([o,new Promise(s=>{i=setTimeout(s,r)})]).finally(()=>{clearTimeout(i)})}function qe(t,e){if(t instanceof U)return t;if(t instanceof be)throw t;return t instanceof H?new U(404,t.message):new U(502,Ze("speech",t,e))}async function ao(t,e,n,r,o,i,s,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return bs(e,async()=>{if(s?.()===!0)return null;let p=!1,f=!1,m=!1,k,x=new Promise(b=>{k=b}),w=[],y,g=!1,v=null,T=()=>{v!==null&&(clearTimeout(y),y=setTimeout(()=>{g=!0,v?.()},o.capMs))},P=()=>{f&&!m&&w.length>=o.quietRunFrames&&(m=!0,k())},R=e.onOutputAudio(b=>{let _=Buffer.from(b,"base64");if(_.byteLength===0)return;T();let C=ws(_);if(!p){if(C)return;p=!0}if(C){w.push(_),P();return}for(let D of w)c(D);w.length=0,c(_),P()}),E=null,O,h;try{h=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let _=()=>(clearTimeout(O),new Promise(L=>{O=setTimeout(L,i.capMs)})),C=_(),D=!1;for(;;){let L=h.next(),N=await Promise.race([L,C]);if(N===void 0){D=!0,L.catch(()=>{});break}if(N.done)break;let te=N.value;if(C=_(),te.type==="error"){let J=te.error??{};await h.return?.();let ee=typeof J.message=="string"&&J.message.length>0&&ye(J.message)?J.message:null;throw ee===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(te)}`),new U(502,"the speech upstream failed while serving this request")):new U(502,`speech upstream error: ${ee}`)}if(te.type==="response.completed"){E=te.response??null,f=!0,u?.(E),P(),await h.return?.();break}}if(clearTimeout(O),D)throw new U(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(E===null)throw new U(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let F=new Promise(L=>{v=L});if(T(),await Promise.race([x,F]),clearTimeout(y),y=void 0,v=null,r.voice!==void 0){let L=E[rt];if(typeof L!="string"||L!==r.voice){let N=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof L=="string"?`${rt} ${JSON.stringify(L)}`:`no ${rt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw m?new tn(N):new U(502,N)}}if(!p)throw new U(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(g&&!m&&w.length<1)throw new U(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return E}catch(b){throw b instanceof tn||await Ss(t,n,h,i.returnBoundMs),b}finally{clearTimeout(y),clearTimeout(O),R()}})}function ks(t,e,n,r){let o=!1,i=0,s=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",en)),t.write(a,u=>{u||(i+=a.byteLength,po(e,i))}),t.writableLength>io&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${io} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let u=a[rt];if(typeof u=="string"){if(!lo(u))throw co(u);t.addTrailers({[en]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:s}}async function xs(t,e,n,r){let o;try{o=await t(e)}catch(i){throw qe(i,r)}return o?!0:(Cn(n,new U(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Rs={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},As="wav, pcm";async function fo(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??hs,i=!1;e.once("close",()=>{i=!0});let s=()=>i||e.destroyed;try{if(t.method!=="POST")throw new U(405,`${String(t.method)} is not supported on ${bt}`);let a;try{a=JSON.parse((await Yt(t,o)).toString("utf8")||"{}")}catch(v){throw v instanceof re?new U(413,v.message):new U(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new U(400,"request body must be a JSON object");let u=a;for(let v of Object.keys(u))if(!Rs[v])throw new U(400,`request field "${v}" 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.`,v);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new U(400,"input is required and must be a non-empty string","input");if(l.length>eo)throw new U(400,`input is ${l.length} chars \u2014 over the ${eo}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=u.model===void 0?void 0:u.model;if(d!==void 0&&typeof d!="string")throw new U(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new U(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new U(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${bt} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(v){throw qe(v,r)}if(p.defect!==null)throw new U(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let f=typeof c=="string"?c:void 0;if(f!==void 0&&p.published.length>0&&!p.published.includes(f))throw new U(400,`voice ${JSON.stringify(f)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let m=u.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new U(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${As} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new U(400,"stream_format, when present, must be a string","stream_format");let k=u.speed;if(k!==void 0){if(typeof k!="number"||!Number.isFinite(k))throw new U(400,"speed, when present, must be a number","speed");if(k!==1)throw new U(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 x=u.instructions;if(x!==void 0){if(typeof x!="string")throw new U(400,"instructions, when present, must be a string","instructions");if(x.trim().length>0)throw new U(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await ys(n.turn,n.clients,d);let w=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",w,w),!await xs(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new U(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new U(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new U(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let y;try{y=await n.clients.speechSessionHandle(d)}catch(v){throw qe(v,r)}let g;try{g=await n.clients.openAudioOn(y)}catch(v){throw qe(v,r)}n.turn&&(n.turn.sessionId=g.sessionId);try{if(m==="wav"){let v=[],T=await ao(n.clients,g,y,{model:d,text:l,...f!==void 0?{voice:f}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??to,returnBoundMs:n.turnReturnBoundMs??no},s,R=>v.push(R),R=>{n.turn&&(n.turn.outputSeconds=Re(R))},r);if(T===null||s())return;let P=Buffer.concat(v);if(f===void 0){let R=T[rt];if(typeof R=="string"){if(!lo(R))throw co(R);e.setHeader(en,R)}}po(n.turn,P.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([vs(P.byteLength),P]))}else{let v=ks(e,n.turn,s,f===void 0),T;try{T=await ao(n.clients,g,y,{model:d,text:l,...f!==void 0?{voice:f}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??to,returnBoundMs:n.turnReturnBoundMs??no},s,v.sink,P=>{n.turn&&(n.turn.outputSeconds=Re(P))},r)}catch(P){let R=qe(P,r);if(!v.started())throw R;n.turn&&(n.turn.streamError=!0),v.fail(R);return}if(T===null)return;try{await v.finish(T)}catch(P){let R=qe(P,r);n.turn&&(n.turn.streamError=!0),v.fail(R);return}}}catch(v){throw qe(v,r)}}catch(a){if(a instanceof re){Cn(e,new U(413,a.message));return}if(a instanceof U){Cn(e,a);return}throw a}}var nn="/v1/audio/transcriptions";function mo(t){return t===nn}var go="/v1/audio/models",Es=16*1024*1024,Is=64*1024*1024,Y=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function $n(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function ho(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function Os(t){if(!ho(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),s=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,l=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:l,channels:u,bitsPerSample:d}}else if(i==="data"){let u=t.length-a;r=Math.min(s===0||s===4294967295?u:s,u)}e=a+s+s%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Ts(t,e,n){if(t){if(t.model=ie({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Ps(t,e){t&&(t.outputUnits=e.seconds)}async function Cs(t,e,n,r,o,i,s){let a=s??(c=>console.error(c)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of u){if(l.push(c),c.type==="error"){let p=c.error??{},f=typeof p.type=="string"?p.type:"upstream_error",m=typeof p.message=="string"&&p.message.length>0&&ye(p.message)?p.message:null;throw m===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new Y(f==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new Y(f==="invalid_request_error"?400:502,`transcription upstream error: ${m}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new Y(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return i&&(i.outputSeconds=Re(d)),Ye(l,d)}function yo(t,e){if(t instanceof Y)return t;if(t instanceof be)throw t;return t instanceof H?new Y(404,t.message):new Y(502,Ze("transcription",t,e))}async function $s(t,e,n,r){let o;try{o=await t(e)}catch(i){throw yo(i,r)}return o?!0:($n(n,new Y(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Ms=new Set(["file","model","language","response_format"]);async function _o(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Is,i=n.maxAudioPartBytes??Es;try{if(t.method!=="POST")throw new Y(405,`${String(t.method)} is not supported on ${nn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new Y(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let a;try{a=await Xt(t,o)}catch(y){throw y instanceof re?new Y(413,y.message):new Y(400,String(y instanceof Error?y.message:y))}let u=new Map;for(let y of a.keys()){if(!Ms.has(y))throw new Y(400,`form field "${y}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,y);u.set(y,(u.get(y)??0)+1)}for(let[y,g]of u)if(g>1)throw new Y(400,`form field "${y}" appears ${g} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,y);let l=a.get("model");if(l!==null&&typeof l!="string")throw new Y(400,"model must be a string field","model");let d=l===null?void 0:l,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new Y(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,f=a.get("response_format")??"json";if(f!=="json")throw new Y(400,`response_format ${JSON.stringify(f)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let m=a.get("file");if(!(m instanceof File))throw new Y(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>i)throw new Y(413,`file part exceeds the ${i}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let k=new Uint8Array(await m.arrayBuffer());if(!ho(k))throw new Y(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let x=Os(k);if(x===null)throw new Y(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Ts(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",k.length,k.length),!await $s(n.transcriptionModels,d,e,r))return;let w=[{type:"input_audio",input_audio:{data:Buffer.from(k).toString("base64"),format:"wav"}}];try{let y=await Cs(n.clients,d,w,p,n.turn?ce(n.turn):void 0,n.turn,r);Ps(n.turn,x),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:y}))}catch(y){throw yo(y,r)}}catch(s){if(s instanceof re){$n(e,new Y(413,s.message));return}if(s instanceof Y){$n(e,s);return}throw s}}var vo="/v1/usage/requests",wo=1e4,Ls=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Oe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},ot=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var bo=1024*1024;function Mn(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Oe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Oe(`"${e}" must be an array of uuid strings`);if(n.length>wo)throw new Oe(`"${e}" carries ${n.length} ids; at most ${wo} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let i of n){if(typeof i!="string"||!Ls.test(i))throw new Oe(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(i)||(o.add(i),r.push(i))}return r}function So(t){return Mn(t,"inference_ids")}function rn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let i=t[o];if(!n.has(i.inference_id))throw new ot(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(i.inference_id))throw new ot(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(i.inference_id)}}var un=require("@urun-sh/core");var Ln="/partners/huggingface/v1/billing/requests";function Ns(t){return Mn(t,"requestIds")}function Us(t){return t>=200&&t<=399}function Ds(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Us(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function ko(t,e){let n=Ns(t),r=await e(n);return rn(r,n),Ds(r)}var Fs={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text","/v1/realtime":"realtime"};function Bs(t){return Fs[t]??null}var Eo=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function qs(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function js(t){return t==="surface"}function Hs(t){let e=t?.ledgerFailureReason;return Eo.includes(e)?e:"unknown"}var Js=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],xo=["priced","unpriced"],Vs={written:xo,already_written:xo,skipped:Js,failed:Eo},hd=Object.entries(Vs).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Gs(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Ws(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 Ks=256,Ro=4096,kt=12e4,zs=250,Ys=8e3,xt=[],Ao=new Set,Rt=0,St=!1;var Xs=new Set;function Qs(){return Rt===0&&xt.length===0}function Zs(){if(Qs()){St=!1;for(let t of[...Xs])t()}}function Io(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
25
+ `}function ea(t){De(process.stdout,t)}function Oo(t,e){try{t(e)}catch{}}function To(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??ea,o=Bs(e.path);if(o===null)return;let i=d=>{try{n.observe(d)}catch{}},s=(d,c)=>{i({outcome:"skipped",reason:d}),Oo(r,Io("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){s("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){s("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){s("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){s("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:Ws(e),completed_at:e.ts,billable_outcome:Gs(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,session_seconds:e.session_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(xt.length>=Ro){s("queue_full",`${xt.length} ledger writes are already waiting (capacity ${Ro}, ${Rt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}xt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Rt<Ks&&(Rt+=1,ta())}async function ta(){try{for(;;){let t=na();if(t===void 0)return;Ao.add(t);try{await ra(t)}finally{Ao.delete(t)}}}finally{Rt-=1,Zs()}}function na(){let t=Date.now();for(;;){let e=xt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<kt)return e;it(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${kt}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 ra(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);it(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let i=qs(o);if(i!==null){it(t,{outcome:"already_written",reason:i.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:i.cost_nano_usd,price_version:i.price_version,attempts:t.attempts});return}let s=Hs(o),a=Date.now()-t.queuedAt;if(St){it(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(js(s)&&a<kt){if(await ia(oa(t.attempts)),St||Date.now()-t.queuedAt>=kt){let u=Date.now()-t.queuedAt;it(t,{outcome:"failed",reason:St?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:St?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${kt}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}it(t,{outcome:"failed",reason:s},{event:"inference_ledger_write_failed",reason:s,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function oa(t){return Math.min(Ys,zs*2**Math.max(0,t-1))}function ia(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function it(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Oo(t.report,Io(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function Dn(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function sa(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function oe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function G(t,e,n,r="invalid_request_error",o){oe(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Fn(t,e,n){let r=e.error,o=r?.type??"upstream_error",i=n?.operatorError??(d=>console.error(d)),s=Se(r),a=s??_e(n?.inferenceId??null);s===null&&i(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let u=r?.code??null,l=o==="invalid_request_error"?400:u==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),oe(t,l,{error:{message:a,type:o,code:u}})}function we(t,e,n,r){oe(t,e,{type:"error",error:{type:n,message:r}})}function st(t,e,n){if(e==="anthropic"){oe(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}oe(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var aa=64*1024*1024,At=class extends Error{};async function Po(t,e=aa){let n=[],r=0;for await(let i of t){if(r+=i.length,r>e)throw new At(`request body exceeds ${e} bytes`);n.push(i)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function je(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function Mo(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),i=r(n.output_tokens),s=u=>u??0,a=r(n.total_tokens)??s(o)+s(i);if(s(o)>0||s(i)>0){let u={input_tokens:s(o),output_tokens:s(i),total_tokens:a};return o===null||i===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function on(t){let e=Mo(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Co(t){let e=on(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:ua(t)},completion_tokens_details:{reasoning_tokens:0}}}function ua(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function la(t,e){let n=Mo(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function da(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let l=n[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),i=r("prefill_ms"),s=r("decode_ms"),a=r("total_ms");return o===null||i===null||s===null||a===null?null:{queue_ms:o,prefill_ms:i,decode_ms:s,total_ms:a}}function ca(t,e){let n=da(e);n&&(t.timing=n),t.outputSeconds=Re(e)}function He(t,e){la(t,e),ca(t,e)}async function ln(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function Lo(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function pa(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 sn=class extends Error{};function fa(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new sn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function ma(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:fa(n.role,n.content)})}return e}function Nn(t){return Ke(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 ga(t,e,n,r,o,i,s){let a=ct(i.id),u=t.stream===!0;if(i.model=ie(t),i.stream=u,await ln(i,e,typeof t.model=="string"?t.model:void 0),u){let y;try{y=await ft({body:t,clients:e,store:n,stats:o,responseId:a,turn:i})}catch(g){if(g instanceof H){st(r,"openai",g);return}if(g instanceof pe){G(r,g.status,g.message);return}if(g instanceof ge||g instanceof ue){r.setHeader("retry-after","2"),G(r,503,g.message,"capacity_error");return}throw g}Dn(r);for await(let g of y.events){if(g.type==="error"){i.streamError=!0;let v=g.error,T=Se(v),P=T??_e(i.id);T===null&&s(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(g)}`),r.write(`event: error
26
+ data: ${JSON.stringify({error:{message:P,type:v?.type??"upstream_error",code:v?.code??null}})}
26
27
 
27
- `),r.end();return}h.type==="response.completed"&&He(i,h.response),r.write(`event: ${String(h.type??"message")}
28
- data: ${JSON.stringify(h)}
28
+ `),r.end();return}g.type==="response.completed"&&He(i,g.response),r.write(`event: ${String(g.type??"message")}
29
+ data: ${JSON.stringify(g)}
29
30
 
30
31
  `)}r.write(`data: [DONE]
31
32
 
32
- `),r.end();return}let l;try{l=Xe(n,t)}catch(g){if(g instanceof ce){J(r,g.status,g.message);return}throw g}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let c=t.store!==!1,d=oe(t);o.model(d);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await pn(e,t,l,!1,de(i))}catch(g){if(g instanceof F){st(r,"openai",g);return}if(g instanceof ce){J(r,g.status,g.message);return}if(g instanceof me||g instanceof ae){r.setHeader("retry-after","2"),J(r,503,g.message,"capacity_error");return}throw g}let f=[],k=null;for await(let g of o.track(m,d,i)){if(f.push(g),g.type==="error"){Un(r,g,{inferenceId:i.id,operatorError:s});return}g.type==="response.completed"&&(k=g.response)}if(k==null){J(r,502,"upstream produced no response.completed event","upstream_error");return}He(i,k);let R=Ye(f,k),y=Ne(p,Ke(k).length,R);if(y){J(r,502,Le(d,y),"upstream_error");return}c&&n.remember(a,l,cn(k,R),c),ne(r,200,{...k,id:a})}async function fa(t,e,n,r,o,i,s){let a=t.messages;if(!Array.isArray(a)){J(n,400,"chat/completions requires a messages array");return}let u;try{u=Tr(i,t)}catch(x){if(x instanceof se){J(n,x.status,x.message);return}throw x}let l=String(t.model??"urun"),c=pr(o.id),d;try{d=ca(a)}catch(x){if(x instanceof rn){J(n,400,x.message);return}throw x}let p=oe(t);r.model(p),o.model=p,o.stream=t.stream===!0,await an(o,e,typeof t.model=="string"?t.model:void 0);let m=Array.isArray(t.tools)&&t.tools.length>0,f;try{f=await e.createResponse({model:t.model,input:d,stream:!0,tools:la(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}:{}},de(o))}catch(x){if(x instanceof F){st(n,"openai",x);return}if(x instanceof me||x instanceof ae){n.setHeader("retry-after","2"),J(n,503,x.message,"capacity_error");return}throw x}if(t.stream===!0){u?ra(n):Nn(n);let x=[],I=new Ee,w="",C=u?new tt(u,D=>{n.write(`data: ${JSON.stringify(je(c,l,{content:D},null))}
33
+ `),r.end();return}let l;try{l=Xe(n,t)}catch(y){if(y instanceof pe){G(r,y.status,y.message);return}throw y}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=ie(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,f;try{f=await mn(e,t,l,!1,ce(i))}catch(y){if(y instanceof H){st(r,"openai",y);return}if(y instanceof pe){G(r,y.status,y.message);return}if(y instanceof ge||y instanceof ue){r.setHeader("retry-after","2"),G(r,503,y.message,"capacity_error");return}throw y}let m=[],k=null;for await(let y of o.track(f,c,i)){if(m.push(y),y.type==="error"){Fn(r,y,{inferenceId:i.id,operatorError:s});return}y.type==="response.completed"&&(k=y.response)}if(k==null){G(r,502,"upstream produced no response.completed event","upstream_error");return}He(i,k);let x=Ye(m,k),w=Ne(p,Ke(k).length,x);if(w){G(r,502,Le(c,w),"upstream_error");return}d&&n.remember(a,l,fn(k,x),d),oe(r,200,{...k,id:a})}async function ha(t,e,n,r,o,i,s){let a=t.messages;if(!Array.isArray(a)){G(n,400,"chat/completions requires a messages array");return}let u;try{u=$r(i,t)}catch(h){if(h instanceof ae){G(n,h.status,h.message);return}throw h}let l=String(t.model??"urun"),d=mr(o.id),c;try{c=ma(a)}catch(h){if(h instanceof sn){G(n,400,h.message);return}throw h}let p=ie(t);r.model(p),o.model=p,o.stream=t.stream===!0,await ln(o,e,typeof t.model=="string"?t.model:void 0);let f=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:c,stream:!0,tools:pa(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}:{}},ce(o))}catch(h){if(h instanceof H){st(n,"openai",h);return}if(h instanceof ge||h instanceof ue){n.setHeader("retry-after","2"),G(n,503,h.message,"capacity_error");return}throw h}if(t.stream===!0){u?sa(n):Dn(n);let h=[],b=new Ee,_="",C=u?new tt(u,F=>{n.write(`data: ${JSON.stringify(je(d,l,{content:F},null))}
33
34
 
34
- `)}):null,q=D=>{C?.flush(),n.write(D),n.end()};try{u?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:c,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
35
+ `)}):null,D=F=>{C?.flush(),n.write(F),n.end()};try{u?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
35
36
 
36
- `),n.write(`data: ${JSON.stringify(je(c,l,{role:"assistant"},null))}
37
+ `),n.write(`data: ${JSON.stringify(je(d,l,{role:"assistant"},null))}
37
38
 
38
- `);for await(let X of r.track(f,p,o)){x.push(X);let re=ze(X);if(X.type==="response.output_text.delta"&&typeof X.delta=="string")w+=X.delta,C?C.push(X.delta):n.write(`data: ${JSON.stringify(je(c,l,{content:X.delta},null))}
39
+ `);for await(let J of r.track(m,p,o)){h.push(J);let ee=ze(J);if(J.type==="response.output_text.delta"&&typeof J.delta=="string")_+=J.delta,C?C.push(J.delta):n.write(`data: ${JSON.stringify(je(d,l,{content:J.delta},null))}
39
40
 
40
- `);else if(X.type==="response.reasoning_text.delta"&&typeof X.delta=="string")(!u||u.includeReasoning)&&n.write(`data: ${JSON.stringify(je(c,l,{reasoning_content:X.delta},null))}
41
+ `);else if(J.type==="response.reasoning_text.delta"&&typeof J.delta=="string")(!u||u.includeReasoning)&&n.write(`data: ${JSON.stringify(je(d,l,{reasoning_content:J.delta},null))}
41
42
 
42
- `);else if(re){C?.flush();let{call:M,isNew:B}=I.add(re),V=B?{index:re.tool_index,id:M.id??`call_${re.tool_index}`,type:"function",function:{name:M.name??"",arguments:re.delta}}:{index:re.tool_index,function:{arguments:re.delta}};n.write(`data: ${JSON.stringify(je(c,l,{tool_calls:[V]},null))}
43
+ `);else if(ee){C?.flush();let{call:$,isNew:q}=b.add(ee),W=q?{index:ee.tool_index,id:$.id??`call_${ee.tool_index}`,type:"function",function:{name:$.name??"",arguments:ee.delta}}:{index:ee.tool_index,function:{arguments:ee.delta}};n.write(`data: ${JSON.stringify(je(d,l,{tool_calls:[W]},null))}
43
44
 
44
- `)}else if(X.type==="error"){o.streamError=!0;let M=X.error??{},B=be(M),V=B??ye(o.id);B===null&&s(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(X)}`),q(`data: ${JSON.stringify({error:{message:V,type:M.type??"upstream_error",code:M.code??null}})}
45
+ `)}else if(J.type==="error"){o.streamError=!0;let $=J.error??{},q=Se($),W=q??_e(o.id);q===null&&s(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(J)}`),D(`data: ${JSON.stringify({error:{message:W,type:$.type??"upstream_error",code:$.code??null}})}
45
46
 
46
- `);return}}let D=Mn(we(x)),z=Ne(m,I.size+D.length,w);if(z){o.streamError=!0,q(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Le(p,z)}})}
47
+ `);return}}let F=Nn(ve(h)),L=Ne(f,b.size+F.length,_);if(L){o.streamError=!0,D(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Le(p,L)}})}
47
48
 
48
- `);return}C?.flush(),I.size===0&&D.length>0&&n.write(`data: ${JSON.stringify(je(c,l,{tool_calls:D},null))}
49
+ `);return}C?.flush(),b.size===0&&F.length>0&&n.write(`data: ${JSON.stringify(je(d,l,{tool_calls:F},null))}
49
50
 
50
- `);let H=I.size>0||D.length>0;n.write(`data: ${JSON.stringify(je(c,l,{},H?"tool_calls":"stop"))}
51
+ `);let N=b.size>0||F.length>0;n.write(`data: ${JSON.stringify(je(d,l,{},N?"tool_calls":"stop"))}
51
52
 
52
- `);let Ae=nn(we(x));He(o,we(x)),Ae&&n.write(`data: ${JSON.stringify({id:c,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:Oo(we(x))})}
53
+ `);let te=on(ve(h));He(o,ve(h)),te&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:Co(ve(h))})}
53
54
 
54
55
  `),n.write(`data: [DONE]
55
56
 
56
- `),n.end();return}finally{C?.flush(),C?.dispose()}}let k="",R="",y=[],g=new Ee;for await(let x of r.track(f,p,o)){y.push(x),x.type==="response.output_text.delta"&&typeof x.delta=="string"&&(k+=x.delta),x.type==="response.reasoning_text.delta"&&typeof x.delta=="string"&&(R+=x.delta);let I=ze(x);if(I&&g.add(I),x.type==="error"){Un(n,x,{inferenceId:o.id,operatorError:s});return}}let h=we(y);He(o,h);let _=Mn(h),v=_.length>0?_:Mn({output:g.items()}),E=Ne(m,v.length,k);if(E){J(n,502,Le(p,E),"upstream_error");return}let b=v.map(({index:x,...I})=>I),A={role:"assistant",content:k||null},T=R||Co(h);T&&(A.reasoning_content=T),b.length>0&&(A.tool_calls=b),ne(n,200,{id:c,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:A,finish_reason:b.length>0?"tool_calls":"stop"}],usage:Oo(h)})}var $o="sense-latest";async function ma(t,e,n,r,o,i){if(t===null||typeof t!="object"||Array.isArray(t)){J(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:$o,a=oe({model:s});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){J(n,400,"systemone requires a state (string or JSON structure)");return}let u=t.questions;if(u===null||typeof u!="object"||Array.isArray(u)||Object.keys(u).length===0){J(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){J(n,400,"systemone media, when present, must be an array");return}let l=await Mo(t,s,a,e,n,r,o,i);l!==null&&ne(n,200,l.answer)}async function Mo(t,e,n,r,o,i,s,a){let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};s.decision=u;let l=performance.now();i.model(n),await an(s,r,e),u.resolve_ms=Math.round(performance.now()-l);let c,d=performance.now();try{c=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},de(s))}catch(y){if(y instanceof F)return st(o,"openai",y),null;if(y instanceof me||y instanceof ae)return o.setHeader("retry-after","2"),J(o,503,y.message,"capacity_error"),null;throw y}u.dial_ms=Math.round(performance.now()-d);let p=[],m=null;try{for await(let y of i.track(c,n,s))if(m===null&&(m=performance.now(),u.first_event_ms=Math.round(m-d)),p.push(y),y.type==="error")return Un(o,y,{inferenceId:s.id,operatorError:a}),null}catch(y){if(y instanceof F)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),st(o,"openai",y),null;if(y instanceof me||y instanceof ae)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),o.setHeader("retry-after","2"),J(o,503,y.message,"capacity_error"),null;throw m!==null&&(u.stream_ms=Math.round(performance.now()-m)),y}m!==null&&(u.stream_ms=Math.round(performance.now()-m));let f=we(p);if(f==null)return J(o,502,"upstream produced no response.completed event","upstream_error"),null;He(s,f);let k=Ye(p,f),R;try{R=JSON.parse(k)}catch{return J(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(R===null||typeof R!="object"||Array.isArray(R))return J(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof R=="object"&&R!==null&&!Array.isArray(R)&&"timing"in R){let y=R.timing;if(typeof y=="object"&&y!==null&&!Array.isArray(y)&&"question_fwd_ms"in y&&"head_ms"in y){let g=h=>typeof h=="number"&&Number.isFinite(h)&&h>=0?Math.round(h):null;u.question_fwd_ms=g(y.question_fwd_ms),u.head_ms=g(y.head_ms)}}return{answer:R,completed:f}}async function ha(t,e,n,r,o,i){if(t===null||typeof t!="object"||Array.isArray(t)){J(n,400,"decisions requires a JSON object body");return}let s=typeof t.model=="string"&&t.model?t.model:$o,a=oe({model:s});o.model=a,o.stream=!1;let u;try{u=Mr(t,s)}catch(p){if(p instanceof $){J(n,400,p.message);return}throw p}let l=await Mo(u.systemone,s,a,e,n,r,o,i);if(l===null)return;let c;try{c=Ur(u.specs,l.answer)}catch(p){if(p instanceof pe){J(n,502,p.message,"upstream_error");return}throw p}let d=l.completed.usage;ne(n,200,{model:s,answers:c,...d===void 0?{}:{usage:d}})}function ga(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var At=class extends Error{};function on(t){return new At(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function ya(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 _a(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 At(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function wa(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw on(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw on(`tool_result > ${r}`);e+=String(n.text??"")}return e}function va(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 on(typeof n);let r=[],o="",i=()=>{o&&(r.push({role:e,content:o}),o="")};for(let s of n){let a=String(s.type??"");if(a==="text")o+=String(s.text??"");else if(a==="tool_use")i(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});else if(a==="tool_result")i(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:wa(s.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw on(a)}}return i(),r}function Ln(t){return Ke(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function ba(t,e,n,r,o,i){let s=t.messages;if(!Array.isArray(s)){_e(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){_e(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){_e(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(A=>typeof A!="string"))){_e(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),u=fr(o.id),l=[],c;try{t.system&&l.push({role:"system",content:ga(t.system)});for(let A of s)l.push(...va(A));c=_a(t.tool_choice)}catch(A){if(A instanceof At){_e(n,400,"invalid_request_error",A.message);return}throw A}let d=oe(t);r.model(d),o.model=d,o.stream=t.stream===!0,await an(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:l,stream:!0,tools:ya(t.tools),tool_choice:c,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},de(o))}catch(A){if(A instanceof F){st(n,"anthropic",A);return}if(A instanceof me||A instanceof ae){n.setHeader("retry-after","2"),_e(n,503,"capacity_error",A.message);return}throw A}let f=(A,T)=>{n.destroyed||n.write(`event: ${A}
57
- data: ${JSON.stringify({type:A,...T})}
57
+ `),n.end();return}finally{C?.flush(),C?.dispose()}}let k="",x="",w=[],y=new Ee;for await(let h of r.track(m,p,o)){w.push(h),h.type==="response.output_text.delta"&&typeof h.delta=="string"&&(k+=h.delta),h.type==="response.reasoning_text.delta"&&typeof h.delta=="string"&&(x+=h.delta);let b=ze(h);if(b&&y.add(b),h.type==="error"){Fn(n,h,{inferenceId:o.id,operatorError:s});return}}let g=ve(w);He(o,g);let v=Nn(g),T=v.length>0?v:Nn({output:y.items()}),P=Ne(f,T.length,k);if(P){G(n,502,Le(p,P),"upstream_error");return}let R=T.map(({index:h,...b})=>b),E={role:"assistant",content:k||null},O=x||Lo(g);O&&(E.reasoning_content=O),R.length>0&&(E.tool_calls=R),oe(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:E,finish_reason:R.length>0?"tool_calls":"stop"}],usage:Co(g)})}var No="sense-latest";async function ya(t,e,n,r,o,i){if(t===null||typeof t!="object"||Array.isArray(t)){G(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:No,a=ie({model:s});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){G(n,400,"systemone requires a state (string or JSON structure)");return}let u=t.questions;if(u===null||typeof u!="object"||Array.isArray(u)||Object.keys(u).length===0){G(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){G(n,400,"systemone media, when present, must be an array");return}let l=await Uo(t,s,a,e,n,r,o,i);l!==null&&oe(n,200,l.answer)}async function Uo(t,e,n,r,o,i,s,a){let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};s.decision=u;let l=performance.now();i.model(n),await ln(s,r,e),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},ce(s))}catch(w){if(w instanceof H)return st(o,"openai",w),null;if(w instanceof ge||w instanceof ue)return o.setHeader("retry-after","2"),G(o,503,w.message,"capacity_error"),null;throw w}u.dial_ms=Math.round(performance.now()-c);let p=[],f=null;try{for await(let w of i.track(d,n,s))if(f===null&&(f=performance.now(),u.first_event_ms=Math.round(f-c)),p.push(w),w.type==="error")return Fn(o,w,{inferenceId:s.id,operatorError:a}),null}catch(w){if(w instanceof H)return f!==null&&(u.stream_ms=Math.round(performance.now()-f)),st(o,"openai",w),null;if(w instanceof ge||w instanceof ue)return f!==null&&(u.stream_ms=Math.round(performance.now()-f)),o.setHeader("retry-after","2"),G(o,503,w.message,"capacity_error"),null;throw f!==null&&(u.stream_ms=Math.round(performance.now()-f)),w}f!==null&&(u.stream_ms=Math.round(performance.now()-f));let m=ve(p);if(m==null)return G(o,502,"upstream produced no response.completed event","upstream_error"),null;He(s,m);let k=Ye(p,m),x;try{x=JSON.parse(k)}catch{return G(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(x===null||typeof x!="object"||Array.isArray(x))return G(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof x=="object"&&x!==null&&!Array.isArray(x)&&"timing"in x){let w=x.timing;if(typeof w=="object"&&w!==null&&!Array.isArray(w)&&"question_fwd_ms"in w&&"head_ms"in w){let y=g=>typeof g=="number"&&Number.isFinite(g)&&g>=0?Math.round(g):null;u.question_fwd_ms=y(w.question_fwd_ms),u.head_ms=y(w.head_ms)}}return{answer:x,completed:m}}async function _a(t,e,n,r,o,i){if(t===null||typeof t!="object"||Array.isArray(t)){G(n,400,"decisions requires a JSON object body");return}let s=typeof t.model=="string"&&t.model?t.model:No,a=ie({model:s});o.model=a,o.stream=!1;let u;try{u=Ur(t,s)}catch(p){if(p instanceof M){G(n,400,p.message);return}throw p}let l=await Uo(u.systemone,s,a,e,n,r,o,i);if(l===null)return;let d;try{d=Br(u.specs,l.answer)}catch(p){if(p instanceof fe){G(n,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;oe(n,200,{model:s,answers:d,...c===void 0?{}:{usage:c}})}function wa(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Et=class extends Error{};function an(t){return new Et(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function va(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 ba(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new Et(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Sa(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw an(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw an(`tool_result > ${r}`);e+=String(n.text??"")}return e}function ka(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 an(typeof n);let r=[],o="",i=()=>{o&&(r.push({role:e,content:o}),o="")};for(let s of n){let a=String(s.type??"");if(a==="text")o+=String(s.text??"");else if(a==="tool_use")i(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});else if(a==="tool_result")i(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:Sa(s.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw an(a)}}return i(),r}function Un(t){return Ke(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function xa(t,e,n,r,o,i){let s=t.messages;if(!Array.isArray(s)){we(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){we(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){we(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(E=>typeof E!="string"))){we(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),u=gr(o.id),l=[],d;try{t.system&&l.push({role:"system",content:wa(t.system)});for(let E of s)l.push(...ka(E));d=ba(t.tool_choice)}catch(E){if(E instanceof Et){we(n,400,"invalid_request_error",E.message);return}throw E}let c=ie(t);r.model(c),o.model=c,o.stream=t.stream===!0,await ln(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,f;try{f=await e.createResponse({model:t.model,input:l,stream:!0,tools:va(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},ce(o))}catch(E){if(E instanceof H){st(n,"anthropic",E);return}if(E instanceof ge||E instanceof ue){n.setHeader("retry-after","2"),we(n,503,"capacity_error",E.message);return}throw E}let m=(E,O)=>{n.destroyed||n.write(`event: ${E}
58
+ data: ${JSON.stringify({type:E,...O})}
58
59
 
59
- `)};if(t.stream===!0){let A=r.track(m,d,o);Nn(n),f("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let T=0,x="",I=0,w="none",C=()=>w,q=-1,D=-1,z=new Ee,H=[],Ae=()=>{w!=="none"&&(w="none",f("content_block_stop",{index:q}))},X=(G,Q)=>{Ae(),w=G,q=I++,f("content_block_start",{index:q,content_block:Q})};for await(let G of A){if(n.destroyed)break;H.push(G);let Q=ze(G);if(G.type==="response.reasoning_text.delta"&&typeof G.delta=="string")C()!=="thinking"&&X("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:q,delta:{type:"thinking_delta",thinking:G.delta}});else if(G.type==="response.output_text.delta"&&typeof G.delta=="string")C()!=="text"&&X("text",{type:"text",text:""}),T+=1,x+=G.delta,f("content_block_delta",{index:q,delta:{type:"text_delta",text:G.delta}});else if(Q){let{call:fe}=z.add(Q);(C()!=="tool"||Q.tool_index!==D)&&(D=Q.tool_index,X("tool",{type:"tool_use",id:fe.id??`call_${Q.tool_index}`,name:fe.name??"",input:{}})),Q.delta&&f("content_block_delta",{index:q,delta:{type:"input_json_delta",partial_json:Q.delta}})}else if(G.type==="error"){o.streamError=!0;let fe=G.error,Pe=be(fe);Pe===null&&i(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(G)}`),f("error",{error:{type:"api_error",message:Pe??ye(o.id)}}),n.end();return}}if(n.destroyed)return;let re=we(H),M=Ke(re),B=Ne(p,z.size+M.length,x);if(B){o.streamError=!0,f("error",{error:{type:"api_error",message:Le(d,B)}}),n.end();return}Ae();let V=[];if(z.size===0)try{V=Ln(re)}catch(G){o.streamError=!0;let Q=ue(G,{inferenceId:o.id});Q.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(G instanceof Error?G.message:G)}`),f("error",{error:{type:"api_error",message:Q.message}}),n.end();return}I===0&&V.length===0&&(X("text",{type:"text",text:""}),Ae()),V.forEach(G=>{let Q=I++;f("content_block_start",{index:Q,content_block:{...G,input:{}}}),f("content_block_delta",{index:Q,delta:{type:"input_json_delta",partial_json:JSON.stringify(G.input??{})}}),f("content_block_stop",{index:Q})});let Te=z.size>0||V.length>0,Je=nn(re);He(o,re),f("message_delta",{delta:{stop_reason:Te?"tool_use":"end_turn"},usage:Je?{input_tokens:Je.input_tokens,output_tokens:Je.output_tokens}:{output_tokens:T}}),f("message_stop",{}),n.end();return}let k="",R="",y=[],g=new Ee;for await(let A of r.track(m,d,o)){y.push(A),A.type==="response.output_text.delta"&&typeof A.delta=="string"&&(k+=A.delta),A.type==="response.reasoning_text.delta"&&typeof A.delta=="string"&&(R+=A.delta);let T=ze(A);if(T&&g.add(T),A.type==="error"){let x=A.error,I=x?.type==="invalid_request_error",w=be(x);w===null&&i(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(A)}`),_e(n,I?400:502,I?"invalid_request_error":"api_error",w??ye(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let h=we(y);He(o,h);let _;try{_=Ln(h),_.length===0&&g.size>0&&(_=Ln({output:g.items()}))}catch(A){let T=ue(A,{inferenceId:o.id});T.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(A instanceof Error?A.message:A)}`),_e(n,502,"api_error",T.message);return}let v=Ne(p,_.length,k);if(v){_e(n,502,"api_error",Le(d,v));return}let E=[],b=R||Co(h);b&&E.push({type:"thinking",thinking:b}),(k||_.length===0)&&E.push({type:"text",text:k}),E.push(..._),ne(n,200,{id:u,type:"message",role:"assistant",content:E,model:a,stop_reason:_.length>0?"tool_use":"end_turn",usage:nn(h)??{input_tokens:0,output_tokens:0}})}function Sa(t){De(process.stdout,t)}function ka(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,i=typeof e=="function"?e:()=>e,s=t.requestLog??Sa,a=t.operatorLog??(c=>console.error(c)),u=t.observe,l=new $e;return(c,d)=>{let p=new URL(c.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),f=(h,_,v,E,b)=>m?_e(d,h,E,_):J(d,h,_,v,b),k=dn(p.pathname),R=p.pathname.startsWith("/partners/"),y=k||R?{id:dt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;y&&(d.setHeader(dr,y.id),d.once("close",()=>{let h=mr({turn:y,method:c.method??"",path:p.pathname,res:d});s(hr(h)),u?.(h),Eo({record:h,ledger:t.ledger??null,req:c})}));let g=()=>cr(p.pathname,y);(async()=>{if(c.method==="GET"&&p.pathname==="/healthz"){ne(d,200,{ok:!0});return}if(c.method==="GET"&&p.pathname==="/stats"){ne(d,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(c.headers.authorization??"")!==`Bearer ${n}`){f(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=p.pathname===yo?"canonical":p.pathname===$n?"huggingface":null;if(h){if(c.method!=="POST"){f(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let b=t.usage;if(!b){f(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let A=b.authorize(c),T;try{T=await Io(c,_o)}catch(w){if(w instanceof Rt){f(413,w.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let x=w=>b.lookup(A,w),I;try{if(h==="canonical"){let w=wo(T),C=await x(w);tn(C,w),I={requests:C}}else I=await vo(T,x)}catch(w){if(w instanceof Oe){f(w.status,w.message,"invalid_request_error","invalid_request_error");return}throw w}ne(d,200,I);return}if(c.method==="GET"&&p.pathname===ut){let b=await i(c);if(y&&(y.org=b.tenant??null),!b.openRouterModels){f(501,`GET ${ut} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ne(d,200,await b.openRouterModels());return}if(p.pathname.startsWith("/partners/")){f(404,`no partner adapter for ${c.method} ${p.pathname} \u2014 the partner surface currently carries ${$n} and GET ${ut}`,"invalid_request_error","not_found_error");return}let _=await i(c);if(y&&(y.org=_.tenant??null),c.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){d.writeHead(308,{location:ut}),d.end();return}ne(d,200,await _.listModels());return}if(c.method==="GET"&&p.pathname===qr){if(!_.listImageModels){f(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ne(d,200,await _.listImageModels());return}if(Fr(p.pathname)){if(!_.supportsImages){f(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let b={clients:_,imageModels:_.supportsImages,stats:l,turn:g(),operatorLog:a};p.pathname===Yt?await Yr(c,d,b):await zr(c,d,b);return}if(c.method==="GET"&&p.pathname===po){if(!_.listSpeechToTextModels){f(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ne(d,200,await _.listSpeechToTextModels());return}if(co(p.pathname)){if(!_.supportsTranscription){f(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${en}`,"not_implemented","not_implemented_error");return}let b={clients:_,transcriptionModels:_.supportsTranscription,stats:l,turn:g(),operatorLog:a};await ho(c,d,b);return}if(io(p.pathname)){if(!_.supportsSpeech){f(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${vt}`,"not_implemented","not_implemented_error");return}let b={clients:_,speechModels:_.supportsSpeech,stats:l,turn:g(),operatorLog:a};await lo(c,d,b);return}if(c.method!=="POST"){f(404,`no route for ${c.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let v;try{v=await Io(c)}catch(b){if(b instanceof Rt){f(413,b.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let E=Buffer.byteLength(JSON.stringify(v));if(p.pathname==="/v1/responses"){l.request("responses",E,E),await pa(v,_,pt(_),d,l,g(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",E,E),await fa(v,_,d,l,g(),c.headers[xn],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",E,E),await ma(v,_,d,l,g(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",E,E),await ha(v,_,d,l,g(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",E,E),await ba(v,_,d,l,g(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",E,E),_e(d,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}f(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let _=String(h instanceof Error?h.message:h);if(!d.headersSent){let b=o?.(h)??null;if(b){b.operatorDetail!==void 0&&a(`[caller-message-boundary] ${c.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${b.operatorDetail}`),f(b.status,_,b.openaiType,b.anthropicType,b.code);return}if(h instanceof sn.SessionAllocationError){let T=Dt(h.code);if(T){let x=h.retryAfterSeconds??(T.status===429?30:void 0);x!==void 0&&d.setHeader("Retry-After",String(x)),f(T.status,mt(T,h.code??void 0),T.openaiType,T.anthropicType,T.code);return}}if(h instanceof sn.SessionFailedError){let T=Ft(h);if(T){let x=T.status===429?30:void 0;x!==void 0&&d.setHeader("Retry-After",String(x)),f(T.status,mt(T,h.status.sessionId?`session ${h.status.sessionId}`:void 0),T.openaiType,T.anthropicType,T.code);return}}if(h instanceof ot){f(502,_,"upstream_error","api_error");return}if(h instanceof Ue){h.retryable&&d.setHeader("Retry-After","1");let T=ue(h,{inferenceId:y?.id??null});T.redacted&&a(`[caller-message-boundary] ${c.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:he(h)}`),f(502,T.message,"upstream_error","api_error",h.code);return}if(h instanceof Qe){d.setHeader("Retry-After",String(h.retryAfterSeconds)),f(h.status,_,h.status===429?"capacity_error":"upstream_error",h.status===429?"rate_limit_error":"overloaded_error",h.code);return}let A=ue(h,{inferenceId:y?.id??null});A.redacted&&a(`[caller-message-boundary] ${c.method??""} ${p.pathname} failed; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:he(h)}`),f(500,A.message,"proxy_error","api_error","proxy_error");return}y&&(y.streamError=!0);let v=h instanceof Ue?h.code:null,E=ue(h,{inferenceId:y?.id??null});E.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:he(h)}`),d.destroyed||(m?d.write(`event: error
60
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:E.message}})}
60
+ `)};if(t.stream===!0){let E=r.track(f,c,o);Dn(n),m("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let O=0,h="",b=0,_="none",C=()=>_,D=-1,F=-1,L=new Ee,N=[],te=()=>{_!=="none"&&(_="none",m("content_block_stop",{index:D}))},J=(K,Q)=>{te(),_=K,D=b++,m("content_block_start",{index:D,content_block:Q})};for await(let K of E){if(n.destroyed)break;N.push(K);let Q=ze(K);if(K.type==="response.reasoning_text.delta"&&typeof K.delta=="string")C()!=="thinking"&&J("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:D,delta:{type:"thinking_delta",thinking:K.delta}});else if(K.type==="response.output_text.delta"&&typeof K.delta=="string")C()!=="text"&&J("text",{type:"text",text:""}),O+=1,h+=K.delta,m("content_block_delta",{index:D,delta:{type:"text_delta",text:K.delta}});else if(Q){let{call:me}=L.add(Q);(C()!=="tool"||Q.tool_index!==F)&&(F=Q.tool_index,J("tool",{type:"tool_use",id:me.id??`call_${Q.tool_index}`,name:me.name??"",input:{}})),Q.delta&&m("content_block_delta",{index:D,delta:{type:"input_json_delta",partial_json:Q.delta}})}else if(K.type==="error"){o.streamError=!0;let me=K.error,Pe=Se(me);Pe===null&&i(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(K)}`),m("error",{error:{type:"api_error",message:Pe??_e(o.id)}}),n.end();return}}if(n.destroyed)return;let ee=ve(N),$=Ke(ee),q=Ne(p,L.size+$.length,h);if(q){o.streamError=!0,m("error",{error:{type:"api_error",message:Le(c,q)}}),n.end();return}te();let W=[];if(L.size===0)try{W=Un(ee)}catch(K){o.streamError=!0;let Q=le(K,{inferenceId:o.id});Q.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(K instanceof Error?K.message:K)}`),m("error",{error:{type:"api_error",message:Q.message}}),n.end();return}b===0&&W.length===0&&(J("text",{type:"text",text:""}),te()),W.forEach(K=>{let Q=b++;m("content_block_start",{index:Q,content_block:{...K,input:{}}}),m("content_block_delta",{index:Q,delta:{type:"input_json_delta",partial_json:JSON.stringify(K.input??{})}}),m("content_block_stop",{index:Q})});let Te=L.size>0||W.length>0,Je=on(ee);He(o,ee),m("message_delta",{delta:{stop_reason:Te?"tool_use":"end_turn"},usage:Je?{input_tokens:Je.input_tokens,output_tokens:Je.output_tokens}:{output_tokens:O}}),m("message_stop",{}),n.end();return}let k="",x="",w=[],y=new Ee;for await(let E of r.track(f,c,o)){w.push(E),E.type==="response.output_text.delta"&&typeof E.delta=="string"&&(k+=E.delta),E.type==="response.reasoning_text.delta"&&typeof E.delta=="string"&&(x+=E.delta);let O=ze(E);if(O&&y.add(O),E.type==="error"){let h=E.error,b=h?.type==="invalid_request_error",_=Se(h);_===null&&i(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(E)}`),we(n,b?400:502,b?"invalid_request_error":"api_error",_??_e(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let g=ve(w);He(o,g);let v;try{v=Un(g),v.length===0&&y.size>0&&(v=Un({output:y.items()}))}catch(E){let O=le(E,{inferenceId:o.id});O.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(E instanceof Error?E.message:E)}`),we(n,502,"api_error",O.message);return}let T=Ne(p,v.length,k);if(T){we(n,502,"api_error",Le(c,T));return}let P=[],R=x||Lo(g);R&&P.push({type:"thinking",thinking:R}),(k||v.length===0)&&P.push({type:"text",text:k}),P.push(...v),oe(n,200,{id:u,type:"message",role:"assistant",content:P,model:a,stop_reason:v.length>0?"tool_use":"end_turn",usage:on(g)??{input_tokens:0,output_tokens:0}})}function Ra(t){De(process.stdout,t)}function Aa(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,i=typeof e=="function"?e:()=>e,s=t.requestLog??Ra,a=t.operatorLog??(d=>console.error(d)),u=t.observe,l=new $e;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),f=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),m=(g,v,T,P,R)=>f?we(c,g,P,v):G(c,g,v,T,R),k=pn(p.pathname),x=p.pathname.startsWith("/partners/"),w=k||x?{id:dt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;w&&(c.setHeader(pr,w.id),c.once("close",()=>{let g=hr({turn:w,method:d.method??"",path:p.pathname,res:c});s(yr(g)),u?.(g),To({record:g,ledger:t.ledger??null,req:d})}));let y=()=>fr(p.pathname,w);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){oe(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){oe(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let g=p.pathname===vo?"canonical":p.pathname===Ln?"huggingface":null;if(g){if(d.method!=="POST"){m(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let R=t.usage;if(!R){m(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let E=R.authorize(d),O;try{O=await Po(d,bo)}catch(_){if(_ instanceof At){m(413,_.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let h=_=>R.lookup(E,_),b;try{if(g==="canonical"){let _=So(O),C=await h(_);rn(C,_),b={requests:C}}else b=await ko(O,h)}catch(_){if(_ instanceof Oe){m(_.status,_.message,"invalid_request_error","invalid_request_error");return}throw _}oe(c,200,b);return}if(d.method==="GET"&&p.pathname===ut){let R=await i(d);if(w&&(w.org=R.tenant??null),!R.openRouterModels){m(501,`GET ${ut} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}oe(c,200,await R.openRouterModels());return}if(p.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Ln} and GET ${ut}`,"invalid_request_error","not_found_error");return}let v=await i(d);if(w&&(w.org=v.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:ut}),c.end();return}oe(c,200,await v.listModels());return}if(d.method==="GET"&&p.pathname===Hr){if(!v.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}oe(c,200,await v.listImageModels());return}if(jr(p.pathname)){if(!v.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let R={clients:v,imageModels:v.supportsImages,stats:l,turn:y(),operatorLog:a};p.pathname===Qt?await Zr(d,c,R):await Qr(d,c,R);return}if(d.method==="GET"&&p.pathname===go){if(!v.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}oe(c,200,await v.listSpeechToTextModels());return}if(mo(p.pathname)){if(!v.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${nn}`,"not_implemented","not_implemented_error");return}let R={clients:v,transcriptionModels:v.supportsTranscription,stats:l,turn:y(),operatorLog:a};await _o(d,c,R);return}if(uo(p.pathname)){if(!v.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${bt}`,"not_implemented","not_implemented_error");return}let R={clients:v,speechModels:v.supportsSpeech,stats:l,turn:y(),operatorLog:a};await fo(d,c,R);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let T;try{T=await Po(d)}catch(R){if(R instanceof At){m(413,R.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let P=Buffer.byteLength(JSON.stringify(T));if(p.pathname==="/v1/responses"){l.request("responses",P,P),await ga(T,v,pt(v),c,l,y(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",P,P),await ha(T,v,c,l,y(),d.headers[An],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",P,P),await ya(T,v,c,l,y(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",P,P),await _a(T,v,c,l,y(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",P,P),await xa(T,v,c,l,y(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",P,P),we(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(g=>{let v=String(g instanceof Error?g.message:g);if(!c.headersSent){let R=o?.(g)??null;if(R){R.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${R.operatorDetail}`),m(R.status,v,R.openaiType,R.anthropicType,R.code);return}if(g instanceof un.SessionAllocationError){let O=Ft(g.code);if(O){let h=g.retryAfterSeconds??(O.status===429?30:void 0);h!==void 0&&c.setHeader("Retry-After",String(h)),m(O.status,mt(O,g.code??void 0),O.openaiType,O.anthropicType,O.code);return}}if(g instanceof un.SessionFailedError){let O=Bt(g);if(O){let h=O.status===429?30:void 0;h!==void 0&&c.setHeader("Retry-After",String(h)),m(O.status,mt(O,g.status.sessionId?`session ${g.status.sessionId}`:void 0),O.openaiType,O.anthropicType,O.code);return}}if(g instanceof ot){m(502,v,"upstream_error","api_error");return}if(g instanceof Ue){g.retryable&&c.setHeader("Retry-After","1");let O=le(g,{inferenceId:w?.id??null});O.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:he(g)}`),m(502,O.message,"upstream_error","api_error",g.code);return}if(g instanceof Qe){c.setHeader("Retry-After",String(g.retryAfterSeconds)),m(g.status,v,g.status===429?"capacity_error":"upstream_error",g.status===429?"rate_limit_error":"overloaded_error",g.code);return}let E=le(g,{inferenceId:w?.id??null});E.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:he(g)}`),m(500,E.message,"proxy_error","api_error","proxy_error");return}w&&(w.streamError=!0);let T=g instanceof Ue?g.code:null,P=le(g,{inferenceId:w?.id??null});P.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:he(g)}`),c.destroyed||(f?c.write(`event: error
61
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:P.message}})}
61
62
 
62
- `):d.write(`data: ${JSON.stringify({error:{message:E.message,type:"upstream_error",code:v}})}
63
+ `):c.write(`data: ${JSON.stringify({error:{message:P.message,type:"upstream_error",code:T}})}
63
64
 
64
- `)),d.end()})}}function Lo(t){let{clients:e,apiKey:n}=t,r=(0,To.createServer)(ka(t)),o=br(r,{clients:e,apiKey:n,statusOf:t.statusOf,operatorLog:t.operatorLog}),i=yt(r,{resolver:Gt(e,n,t.realtimeCompanions),operatorLog:t.operatorLog}),s=r.close.bind(r);return r.close=(a=>(o.close(),i(),s(a))),Nt(r,{clients:e,apiKey:n}),r}0&&(module.exports={GEMINI_LIVE_PATH,OPENAI_REALTIME_PATH,OpenAIRealtimeConnection,ResumptionRegistry,SessionGoneError,UnknownModelError,VIDEO_OUT_SETUP_KEY,attachGeminiLive,attachOpenAIRealtime,createOpenAIProxy,fixedClientsResolver,realtimeBindingFor,realtimeModelOf,serveGeminiLiveSocket});
65
+ `)),c.end()})}}function Do(t){let{clients:e,apiKey:n}=t,r=(0,$o.createServer)(Aa(t)),o=kr(r,{clients:e,apiKey:n,statusOf:t.statusOf,operatorLog:t.operatorLog}),i=_t(r,{resolver:Kt(e,n,t.realtimeCompanions),operatorLog:t.operatorLog}),s=r.close.bind(r);return r.close=(a=>(o.close(),i(),s(a))),Ut(r,{clients:e,apiKey:n}),r}0&&(module.exports={GEMINI_LIVE_PATH,OPENAI_REALTIME_PATH,OpenAIRealtimeConnection,ResumptionRegistry,SessionGoneError,UnknownModelError,VIDEO_OUT_SETUP_KEY,attachGeminiLive,attachOpenAIRealtime,createOpenAIProxy,fixedClientsResolver,realtimeBindingFor,realtimeModelOf,serveGeminiLiveSocket});