@urun-sh/openai 0.6.35 → 0.6.36
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.
- package/dist/{ResponsesClient-_OZERUjH.d.cts → ResponsesClient-6QsC7NPJ.d.cts} +4 -1
- package/dist/{ResponsesClient-CSSrOYD8.d.ts → ResponsesClient-gfg7qUoE.d.ts} +4 -1
- package/dist/chunk-4NMMWAKD.js +1 -0
- package/dist/chunk-EPG5XWHE.js +64 -0
- package/dist/{chunk-ETX6IX25.js → chunk-GX243AIV.js} +1 -1
- package/dist/chunk-KKCUIOL4.js +1 -0
- package/dist/{chunk-ITPXS7D4.js → chunk-KXKTXZKG.js} +1 -1
- package/dist/chunk-OEITGJY2.js +2 -0
- package/dist/chunk-T6RD7TSR.js +23 -0
- package/dist/{composite-DGytPb8F.d.cts → composite-C6Gw4HfK.d.cts} +4 -4
- package/dist/gemini-live.cjs +1 -1
- package/dist/gemini-live.d.cts +10 -1
- package/dist/gemini-live.d.ts +3 -1
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +57 -47
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +53 -43
- package/dist/hosted/index.d.cts +2 -2
- package/dist/hosted/index.d.ts +2 -2
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +4 -4
- package/dist/pi-extension/index.d.cts +1 -1
- package/dist/pi-extension/index.d.ts +1 -1
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +51 -51
- package/dist/pooler/bin.cjs +20 -20
- package/dist/pooler/bin.js +24 -24
- package/dist/proxy/cli.cjs +58 -54
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/conformance-probe.cjs +1 -1
- package/dist/proxy/conformance-probe.js +1 -1
- package/dist/proxy/index.cjs +33 -29
- package/dist/proxy/index.d.cts +2 -2
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-5VMB5HKE.js +0 -17
- package/dist/chunk-EV4DZCHN.js +0 -1
- package/dist/chunk-LOPBORFM.js +0 -60
- package/dist/chunk-PAYCMH5F.js +0 -1
- package/dist/chunk-UO6N5FH7.js +0 -2
- /package/dist/{composite-D4oZXeX4.d.ts → composite-DAZrZyLN.d.ts} +0 -0
package/dist/proxy/index.cjs
CHANGED
|
@@ -1,60 +1,64 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}var $o={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},we="urun.videoOut";function Bn(t){return{framing:Ln,codec:t}}function qn(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[we]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Lo={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},No=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",we],Nn=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Uo(t){let e=X(t);if(!e)throw new b("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new b(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=X(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new b("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new b(`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 b("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(!Nn.includes(e.activityHandling))throw new b(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Nn.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Do=["temperature","maxOutputTokens","responseModalities"];function jn(t){for(let[c,p]of Object.entries(Lo))if(t[c]!==void 0)throw new b(p);for(let c of Object.keys(t))if(!No.includes(c))throw new b(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new b('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,i=X(t.generationConfig);if(t.generationConfig!==void 0&&!i)throw new b("setup.generationConfig must be an object");if(i){for(let c of Object.keys(i))if(!Do.includes(c))throw new b(`unsupported generationConfig field "${c}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new b("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new b("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 h=String(p).toUpperCase();if(h==="AUDIO"){o=!0;continue}if(h!=="TEXT")throw new b(`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:Fn(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new b("setup.tools must be an array");a=[];for(let c of t.tools){let p=X(c);if(!p)throw new b("setup.tools entries must be objects");for(let h of Object.keys(p))if(h!=="functionDeclarations")throw new b(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new b("tool.functionDeclarations must be an array");for(let h of p.functionDeclarations){let f=X(h);if(!f||typeof f.name!="string")throw new b("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 c=X(t.sessionResumption);if(!c)throw new b("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new b(`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 b("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?$o:Uo(t.realtimeInputConfig),d=!1;if(t[we]!==void 0){if(!X(t[we]))throw new b(`setup["${we}"] 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 Hn(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Vn(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Gn(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new b(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new b("clientContent.turns must be an array");let n=[];for(let r of e){let o=X(r);if(!o)throw new b("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 b(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:i==="model"?"assistant":"user",content:Fn(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Et=16e3,Jn=24e3,Fo=`audio/pcm;rate=${Jn}`,Wn=Buffer.alloc(960).toString("base64");function Bo(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 qo(t){let e=X(t);if(!e)throw new b("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new b(`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 b("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 b("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function jo(t){let e=X(t);if(!e)throw new b("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new b(`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])!==Et)throw new b(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Et} Hz (audio/pcm;rate=${Et})`);if(typeof e.data!="string"||e.data.length===0)throw new b("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 b(`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=Bo(o,Et,Jn);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function Kn(t){if(t.mediaChunks!==void 0)throw new b('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 b("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",i=X(t[o]);if(!i||Object.keys(i).length!==0)throw new b(`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 b(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new b(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:jo(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:qo(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new b("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new b("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function zn(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new b(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new b("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=X(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new b("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 Yn(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Xn(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Fo,data:t}}]}}}}function Qn(t){let e=X(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=X(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=X(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=X(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new b(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,ve);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new b(`upstream function_call arguments are not valid JSON: ${c}`,ve)}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=X(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 Ho=256,je=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Ho;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Vo="local",it=t=>t.slice(0,120),Pt=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 D){this.ws.close(Un,it(e.message));return}if(e instanceof K){this.ws.close(Ot,it(e.message));return}if(e instanceof b){this.ws.close(e.closeCode,it(e.message));return}this.ws.close(ve,it(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Dn(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 b(`"${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}=Gn(n.clientContent);this.transcript.push(...o),i&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Kn(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:Wn);return}this.transcript.push(...zn(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new b("setup may only be sent once, as the first client message");let n=jn(e),r=n.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new b("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",Ot);if(i.model!==n.model)throw new b(`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 b("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 b(`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`,Ot);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(qn(l))),u=s.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[we]=Bn(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 b("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new b("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",ve);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Xn(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 b("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new b("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",ve);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 b(`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 b("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 b("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,Zn.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Hn(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(Vn(e.timeLeftMs)),this.ws.close(ve,it(`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 b(`upstream error: ${JSON.stringify(l)}`,ve);if(l.type==="response.completed"){o=l.response,i=!0;continue}let d=Yn(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new b("upstream produced no response.completed event",ve);let{messages:s,assistantItems:a}=Qn(o);this.transcript.push(...a);for(let u of s)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Te=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Go(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 Te(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&s!==void 0&&s!=="")throw new Te(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new Te(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Ct(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 er.WebSocketServer({noServer:!0}),o=new je;t.on("upgrade",(s,a,u)=>{let l=new URL(s.url??"/","http://localhost");l.pathname===Tt&&(a.on("error",()=>{}),(async()=>{let d=Go(s,l,n),c;if(e.authenticate)c=await e.authenticate(d,s);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Te(401,"invalid local proxy api key");c={clients:e.clients,scope:Vo}}r.handleUpgrade(s,a,u,p=>{new Pt(p,c,o)})})().catch(d=>{let c=502;(d instanceof Te||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",h=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
|
|
1
|
+
"use strict";var Lo=Object.create;var Et=Object.defineProperty;var No=Object.getOwnPropertyDescriptor;var Uo=Object.getOwnPropertyNames;var Do=Object.getPrototypeOf,Fo=Object.prototype.hasOwnProperty;var qo=(t,e)=>{for(var n in e)Et(t,n,{get:e[n],enumerable:!0})},Fn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Uo(e))!Fo.call(t,o)&&o!==n&&Et(t,o,{get:()=>e[o],enumerable:!(r=No(e,o))||r.enumerable});return t};var qn=(t,e,n)=>(n=t!=null?Lo(Do(t)):{},Fn(e||!t||!t.__esModule?Et(n,"default",{value:t,enumerable:!0}):n,t)),Bo=t=>Fn(Et({},"__esModule",{value:!0}),t);var Sa={};qo(Sa,{GEMINI_LIVE_PATH:()=>$t,OPENAI_REALTIME_PATH:()=>gt,OpenAIRealtimeConnection:()=>Fe,ResumptionRegistry:()=>Ve,SessionGoneError:()=>z,UnknownModelError:()=>F,VIDEO_OUT_SETUP_KEY:()=>Se,attachGeminiLive:()=>Nt,attachOpenAIRealtime:()=>yt,createOpenAIProxy:()=>Mo,fixedClientsResolver:()=>Gt,realtimeBindingFor:()=>In,realtimeModelOf:()=>En,serveGeminiLiveSocket:()=>ar});module.exports=Bo(Sa);var Oo=require("http");var sr=require("crypto"),ir=require("ws");var at=class extends Error{};var ut="/partners/openrouter/models";var It=class extends Error{name="ModelCreatedError"};var F=class extends Error{},z=class extends Error{};var Ot=require("@urun-sh/core");var Bn="urun.videoOut.v2-ws";var $t="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Vo=1007,Hn=1008,ke=1011,Mt=1008,S=class extends Error{constructor(n,r=Vo){super(n);this.closeCode=r}closeCode},Q=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Tt=["setup","clientContent","realtimeInput","toolResponse"];function Jn(t){let e;try{e=JSON.parse(t)}catch{throw new S("client message is not valid JSON")}let n=Q(e);if(!n)throw new S("client message must be a JSON object");let r=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 s=r[0],i=Q(n[s]);if(!i)throw new S(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Vn(t,e){if(typeof t=="string")return t;let n=Q(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new S(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=Q(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new S(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new S(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new S(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
|
|
2
|
+
`)}var Go={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Se="urun.videoOut";function Gn(t){return{framing:Bn,codec:t}}function Wn(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 Wo={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ko=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Se],jn=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function zo(t){let e=Q(t);if(!e)throw new S("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new S(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=Q(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new S("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new S(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new S("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!jn.includes(e.activityHandling))throw new S(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${jn.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Yo=["temperature","maxOutputTokens","responseModalities"];function Kn(t){for(let[c,p]of Object.entries(Wo))if(t[c]!==void 0)throw new S(p);for(let c of Object.keys(t))if(!Ko.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,s=Q(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new S("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Yo.includes(c))throw new S(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new S("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new S("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of c){let m=String(p).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="TEXT")throw new S(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:Vn(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=Q(c);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=Q(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 c=Q(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?Go:zo(t.realtimeInputConfig),d=!1;if(t[Se]!==void 0){if(!Q(t[Se]))throw new S(`setup["${Se}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:u,videoOut:d}}function zn(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Yn(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Xn(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new S(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new S("clientContent.turns must be an array");let n=[];for(let r of e){let o=Q(r);if(!o)throw new S("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new S(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Vn(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Pt=16e3,Qn=24e3,Xo=`audio/pcm;rate=${Qn}`,Zn=Buffer.alloc(960).toString("base64");function Qo(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let u=a*s,l=Math.floor(u);if(l>=i){o[a]=t[i];continue}let d=u-l;o[a]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function Zo(t){let e=Q(t);if(!e)throw new S("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new S(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new S("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new S("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function es(t){let e=Q(t);if(!e)throw new S("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new S(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==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 i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=Qo(o,Pt,Qn);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function er(t){if(t.mediaChunks!==void 0)throw new S('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new S("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=Q(t[o]);if(!s||Object.keys(s).length!==0)throw new S(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new S(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new S(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:es(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Zo(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 tr(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new S(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new S("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=Q(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new S("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function nr(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function rr(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Xo,data:t}}]}}}}function or(t){let e=Q(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let l of n){let d=Q(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=Q(c);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let l of n){let d=Q(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)}`,ke);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}`,ke)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=Q(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 i.push(u),{messages:i,assistantItems:o}}var ts=256,Ve=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>ts;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},ns="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(Hn,lt(e.message));return}if(e instanceof z){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=Jn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new S(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=Xn(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=er(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:Zn);return}this.transcript.push(...tr(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=Kn(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new S("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Mt);if(s.model!==n.model)throw new S(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new S("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new S(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Mt);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(l=>this.send(Wn(l))),u=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[Se]=Gn(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new S("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new S("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",ke);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(rr(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(zn(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(Yn(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,s=!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,s=!0;continue}let d=nr(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new S("upstream produced no response.completed event",ke);let{messages:i,assistantItems:a}=or(o);this.transcript.push(...a);for(let u of i)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 rs(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 s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new 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&&i!==void 0&&i!=="")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 ir.WebSocketServer({noServer:!0}),o=new Ve;t.on("upgrade",(i,a,u)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===$t&&(a.on("error",()=>{}),(async()=>{let d=rs(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Ce(401,"invalid local proxy api key");c={clients:e.clients,scope:ns}}r.handleUpgrade(i,a,u,p=>{new Lt(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",m=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
|
-
${
|
|
6
|
-
`),a.destroy())}))});let
|
|
7
|
-
`}var Jo=256,Wo=128;function re(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Wo)}var Oe=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>=Jo?"(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}}}},Ko=256;function zo(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 Pe=class extends Error{},He=class{conversations=new Map;thread(e,n){let r=zo(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Pe(`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<=Ko)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},dr=new WeakMap;function ut(t){let e=dr.get(t);return e||(e=new He,dr.set(t,e)),e}function Ve(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function he(t){return t.find(e=>e.type==="response.completed")?.response??null}function Ge(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 xe=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}))}},Yo=["<tool_call>","<function="];function Xo(t){return Yo.find(e=>t.includes(e))}function Ce(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 Me(t,e,n){if(!(!t||e>0))return Xo(n)}function Je(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 be(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Qo(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 on(t,e){let n=Qo(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var de=class extends Error{constructor(n,r,o=400,i){super(n);this.code=r;this.status=o;this.param=i}code;status;param};function We(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Pe?new de(n.message,"previous_response_not_found",400,"previous_response_id"):new de(String(n instanceof Error?n.message:n),"invalid_input")}}function lr(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function sn(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new de("instructions must be a string","invalid_instructions");let 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}:{},...lr(e)!==void 0?{response_format:lr(e)}:{}},o)}async function dt(t){let{body:e,clients:n,store:r,stats:o}=t,i=We(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=re(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await sn(n,e,i,!0,c?ue(c):void 0);return{responseId:s,events:ni({events:p,conversation:i,responseId:s,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function Zo(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?ti(o[s++],u):u),...ei(r,n)]}function ei(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 ti(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*ni(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:i,remember:s,persist:a,store:u,stats:l}=t,d=[],c=M=>M.response&&typeof M.response=="object"?{...M,response:{...M.response,id:r}}:M,p=`item_${r.slice(5)}`,h=!1,f=!1,k=0;function*P(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let x=[],m=(M,B)=>{x.push({output_index:M,item:B})},g=!1,y=0,w="",E=0,v="";function*R(){if(!g)return;g=!1,yield{type:"response.reasoning_text.done",item_id:w,output_index:y,content_index:0,text:v};let M={id:w,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:v}],status:"completed"};yield{type:"response.output_item.done",output_index:y,item:M},m(y,M),v=""}let T=!1,S=0,A="",_=0,C="",F="";function*U(M){if(!T)return;T=!1,yield{type:"response.output_text.done",item_id:A,output_index:S,content_index:0,text:C},yield{type:"response.content_part.done",item_id:A,output_index:S,content_index:0,part:{type:"output_text",text:C}};let B={id:A,type:"message",role:"assistant",status:M,content:[{type:"output_text",text:C}]};yield{type:"response.output_item.done",output_index:S,item:B},m(S,B),C=""}let W=new xe,q=null,ke=-1;function*z(M){if(!q)return;let B=q;q=null,yield{type:"response.function_call_arguments.done",item_id:B.fcId,output_index:B.outputIndex,arguments:B.args};let j={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:j},m(B.outputIndex,j)}let te=!1;for await(let M of l.track(e,o,t.turn)){d.push(M);let B=String(M.type??"");if(B==="response.created"||B==="response.in_progress"){h=!0,yield c(M);continue}if(B==="response.output_item.added"){f=!0,yield c(M);continue}if(B==="response.reasoning_text.delta"&&!f){yield*P(),g||(g=!0,y=k++,E+=1,w=E===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${E}`,yield{type:"response.output_item.added",output_index:y,item:{id:w,type:"reasoning",summary:[],content:[],status:"in_progress"}}),v+=String(M.delta??""),yield{type:"response.reasoning_text.delta",item_id:w,output_index:y,content_index:0,delta:M.delta};continue}if(B==="response.output_text.delta"&&!f){yield*P(),yield*R(),T||(T=!0,S=k++,_+=1,A=_===1?p:`${p}_${_}`,yield{type:"response.output_item.added",output_index:S,item:{id:A,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:A,output_index:S,content_index:0,part:{type:"output_text",text:""}}),C+=String(M.delta??""),F+=String(M.delta??""),yield{type:B,item_id:A,output_index:S,content_index:0,delta:M.delta};continue}let j=f?null:Ge(M);if(j){if(yield*P(),yield*R(),yield*U("completed"),W.add(j),j.tool_index!==ke){yield*z("completed"),ke=j.tool_index;let Ee=k++;q={fcId:`fc_${r.slice(5)}_${j.tool_index}`,outputIndex:Ee,callId:j.call_id,name:j.name,args:""},yield{type:"response.output_item.added",output_index:Ee,item:{id:q.fcId,type:"function_call",call_id:q.callId??q.fcId,name:q.name??"",arguments:"",status:"in_progress"}}}q&&(j.call_id&&(q.callId=j.call_id),j.name&&(q.name=j.name),q.args+=j.delta,yield{type:"response.function_call_arguments.delta",item_id:q.fcId,output_index:q.outputIndex,delta:j.delta});continue}if(B==="response.completed"&&!f){let Ee=Ve(M.response),Be=Me(i,W.size+Ee.length,F);if(Be){te=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Ce(o,Be)}};break}if(yield*R(),yield*U("completed"),yield*z("completed"),W.size===0)for(let Y of Ee){let le=k++,Ie=Y.id??Y.call_id??`fc_${le}`,nn=Y.arguments??"",Pn={id:Ie,type:"function_call",call_id:Y.call_id??Ie,name:Y.name??""};yield{type:"response.output_item.added",output_index:le,item:{...Pn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Ie,output_index:le,delta:nn},yield{type:"response.function_call_arguments.done",item_id:Ie,output_index:le,arguments:nn};let Cn={...Pn,arguments:nn,status:"completed"};yield{type:"response.output_item.done",output_index:le,item:Cn},m(le,Cn)}let H=Zo(x,M.response);yield H.length>0?c({...M,response:{...M.response,output:H}}):c(M);continue}yield c(M)}if(yield*R(),yield*U("incomplete"),yield*z("incomplete"),s&&!te){let M=he(d);u.remember(r,n,on(M,Je(d,M)),a)}}var ye=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ie=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Ke=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 ce=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}};var ri=require("@urun-sh/core"),$e=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 oi=[/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 fe(t){return!oi.some(e=>e.test(t))}function me(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 se(t,e){if(t instanceof K)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=cr(t);return n||{message:me(e?.inferenceId??null),redacted:!0}}function cr(t){return t instanceof xt?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof rt?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof D?{message:t.message,redacted:!1}:t instanceof ye?{message:t.message,redacted:!1}:t instanceof Ke?{message:t.message,redacted:!1}:t instanceof $e?fe(t.message)?{message:t.message,redacted:!1}:null:t instanceof ce?{message:t.message,redacted:!1}:t instanceof ie?{message:t.message,redacted:!1}:null}function ze(t,e,n){let r=n??(s=>console.error(s)),o=cr(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${pe(e)}`),`the ${t} upstream failed: ${o.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&fe(i)?`the ${t} upstream failed: ${i}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${pe(e)}`),`the ${t} upstream failed while serving this request`)}function _e(t){let e=t?.message;return typeof e=="string"&&e.length>0&&fe(e)?e:null}function pe(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var ii="/v1/responses",si=64*1024*1024,ai=8*1024*1024,ui=16,pr=32,fr=3600*1e3,di=/^[A-Za-z0-9._-]{1,256}$/;function ne(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var li=ne(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 dn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function ci(t){for(;t.bufferedAmount>ai&&t.readyState===Re.WebSocket.OPEN;){let{promise:e,resolve:n}=dn();setTimeout(n,5),await e}}var an=class extends He{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 Pe))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)}},un=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 an(ut(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(ne(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${fr/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},fr).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(ne(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(ne(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(ne(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(ne(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(ne(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(ne(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"||!di.test(o.stream_id)){this.sendFrame(li);return}if(i=o.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=pr){this.sendFrame(ne(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${pr}). 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=st();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let i;try{i=await dt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:at(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!==Re.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await ci(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=st(),o=at(r);try{let i=We(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:pe(e);if(e instanceof de)return ne(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof D)return ne(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof K){let a=se(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}`),ne(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}`),ne(i.status,{type:i.openaiType,message:o},n);let s=se(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}`),ne(500,{type:"upstream_error",message:s.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,i=o?.type??"upstream_error",s=_e(o),a=s??me(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)}`),ne(i==="invalid_request_error"?400:502,{type:i,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=ui;){let{promise:e,resolve:n}=dn();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!==Re.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!==Re.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Mt(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
5
|
+
${m}\r
|
|
6
|
+
`),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}function ar(t,e,n=new Ve){new Lt(t,e,n)}var Ie=require("ws");var ur=require("crypto"),lr="Inference-Id";function dt(){return(0,ur.randomUUID)()}function dn(t){return t==="/v1"||t.startsWith("/v1/")}function dr(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 cr(t){return`chatcmpl-${t}`}function pr(t){return`msg_${t}`}function de(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function fr(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 mr(t){return`${JSON.stringify(t)}
|
|
7
|
+
`}var os=256,ss=128;function oe(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,ss)}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>=os?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},is=256;function as(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{},Ge=class{conversations=new Map;thread(e,n){let r=as(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 s of this.conversations.keys()){if(this.conversations.size<=is)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},hr=new WeakMap;function pt(t){let e=hr.get(t);return e||(e=new Ge,hr.set(t,e)),e}function We(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 Ke(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}))}},us=["<tool_call>","<function="];function ls(t){return us.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 ls(n)}function ze(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 ds(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=ds(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ce=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Ye(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 gr(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 s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...gr(e)!==void 0?{response_format:gr(e)}:{}},o)}async function ft(t){let{body:e,clients:n,store:r,stats:o}=t,s=Ye(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,l=oe(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await pn(n,e,s,!0,c?de(c):void 0);return{responseId:i,events:ms({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function cs(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"),s=n.filter(u=>u.type==="message").length===o.length,i=0;return[...n.map(u=>u.type==="message"&&s?fs(o[i++],u):u),...ps(r,n)]}function ps(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??""),s=e.filter(l=>l.type==="function_call"),i=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=s.length===i,u=new Set(s.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 fs(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*ms(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:l}=t,d=[],c=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 K=new Ee,j=null,Ae=-1;function*Y(M){if(!j)return;let B=j;j=null,yield{type:"response.function_call_arguments.done",item_id:B.fcId,output_index:B.outputIndex,arguments:B.args};let J={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:J},g(B.outputIndex,J)}let re=!1;for await(let M of l.track(e,o,t.turn)){d.push(M);let B=String(M.type??"");if(B==="response.created"||B==="response.in_progress"){m=!0,yield c(M);continue}if(B==="response.output_item.added"){f=!0,yield c(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 J=f?null:Ke(M);if(J){if(yield*R(),yield*A(),yield*D("completed"),K.add(J),J.tool_index!==Ae){yield*Y("completed"),Ae=J.tool_index;let Te=k++;j={fcId:`fc_${r.slice(5)}_${J.tool_index}`,outputIndex:Te,callId:J.call_id,name:J.name,args:""},yield{type:"response.output_item.added",output_index:Te,item:{id:j.fcId,type:"function_call",call_id:j.callId??j.fcId,name:j.name??"",arguments:"",status:"in_progress"}}}j&&(J.call_id&&(j.callId=J.call_id),J.name&&(j.name=J.name),j.args+=J.delta,yield{type:"response.function_call_arguments.delta",item_id:j.fcId,output_index:j.outputIndex,delta:J.delta});continue}if(B==="response.completed"&&!f){let Te=We(M.response),He=Ne(s,K.size+Te.length,q);if(He){re=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Le(o,He)}};break}if(yield*A(),yield*D("completed"),yield*Y("completed"),K.size===0)for(let X of Te){let fe=k++,Pe=X.id??X.call_id??`fc_${fe}`,ln=X.arguments??"",Un={id:Pe,type:"function_call",call_id:X.call_id??Pe,name:X.name??""};yield{type:"response.output_item.added",output_index:fe,item:{...Un,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Pe,output_index:fe,delta:ln},yield{type:"response.function_call_arguments.done",item_id:Pe,output_index:fe,arguments:ln};let Dn={...Un,arguments:ln,status:"completed"};yield{type:"response.output_item.done",output_index:fe,item:Dn},g(fe,Dn)}let V=cs(y,M.response);yield V.length>0?c({...M,response:{...M.response,output:V}}):c(M);continue}yield c(M)}if(yield*A(),yield*D("incomplete"),yield*Y("incomplete"),i&&!re){let M=we(d);u.remember(r,n,cn(M,ze(d,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 Xe=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 hs=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 gs=[/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!gs.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 z)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=yr(t);return n||{message:ye(e?.inferenceId??null),redacted:!0}}function yr(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 Xe?{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 Qe(t,e,n){let r=n??(i=>console.error(i)),o=yr(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 s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&ge(s)?`the ${t} upstream failed: ${s}`:(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 ys="/v1/responses",_s=64*1024*1024,ws=8*1024*1024,vs=16,_r=32,wr=3600*1e3,bs=/^[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 Ss=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 hn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function ks(t){for(;t.bufferedAmount>ws&&t.readyState===Ie.WebSocket.OPEN;){let{promise:e,resolve:n}=hn();setTimeout(n,5),await e}}var fn=class extends Ge{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,s=!0){s?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,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;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(se(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${wr/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},wr).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 s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!bs.test(o.stream_id)){this.sendFrame(Ss);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=_r){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 (${_r}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=dt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=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(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let a of i){if(this.closed||this.ws.readyState!==Ie.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await ks(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=dt(),o=ct(r);try{let s=Ye(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:he(e);if(e instanceof ce)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 F)return se(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof z){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}`),se(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),se(s.status,{type:s.openaiType,message:o},n);let i=ue(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),se(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=be(o),a=i??ye(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),se(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=vs;){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
|
|
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 mr(t,e){let n=new Re.WebSocketServer({noServer:!0,maxPayload:si}),r=new Oe,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 h;try{h=new URL(d.url??"/","http://localhost")}catch{Mt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>s.delete(c)),h.pathname!==ii){s.add(c);return}i.add(c);let f=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Mt(c,401,"invalid local proxy api key");return}let k;try{k=await a(d)}catch(P){let x=e.statusOf?.(P)??null;Mt(c,x?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(f=!0,n.handleUpgrade(d,c,p,P=>{i.delete(c),o.add(P),P.on("close",()=>o.delete(P));try{new un(P,k,r,e.statusOf,e.operatorLog??(x=>console.error(x)))}catch{o.delete(P),P.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!f&&!c.destroyed&&Mt(c,500,"responses websocket upgrade failed")}).finally(()=>i.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=dn();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let h of i)h.destroy();i.clear();for(let h of s)h.destroy();s.clear();for(let h of o)h.close(1001,"server shutting down");let p=setTimeout(()=>{for(let h of o)h.readyState!==Re.WebSocket.CLOSED&&h.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var hn=require("@urun-sh/core");var gr=require("@urun-sh/core"),pi={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},fi={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 lt(t,e){let n=fi[t.code];return e?`${n} (${e})`:n}function $t(t){if(t==null)return null;let e=pi[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 Lt(t){if(t.kind==="create-failed")return $t(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=gr.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return $t(e?"cold_start_exceeded":"queue_timeout")}var mi=$n(require("os"),1),gi=$n(require("path"),1),hi=require("url"),yi=require("util");var _i=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function wi(t){let e=t?.code;return typeof e=="string"&&_i.has(e)}function Le(t,e){try{return t.write(e),!0}catch(n){if(wi(n))return!1;throw n}}var br=require("ws");var vr=require("@urun-sh/core");var yr=require("crypto");function I(t){return`${t}_${(0,yr.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Nt=4*1024*1024,ln=8*1024*1024,Ut=512,Dt=20*1024*1024;function Q(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Xe(t,e){return{type:"server_error",code:t,message:e}}function V(t){return{type:"error",event_id:I("event"),error:t}}function cn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var O=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},vi={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},bi={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Si={format:!0,voice:!0,speed:!0};function ki(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function Ye(t,e){if(!Array.isArray(t)||t.length===0)throw new O(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new O(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function hr(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new O(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var xi=10;function pn(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:xi})}function ct(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new O("session must be an object","session","invalid_request");let o=t,i=Object.keys(o).filter(a=>!(a in vi));if(i.length>0)throw new O(`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=Ye(o.modalities,"modalities"),u=Ye(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new O("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 O(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new O(`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 O('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");s.type=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 O(`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=Ye(u,a);for(let d of l)if(d==="audio"&&!n.voice)throw new O('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");s.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!ki(u))throw new O(`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 O("model must be a string or null","model");s.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new O("instructions must be a string or null","instructions");s.instructions=pn(u??void 0)??void 0;break;case"voice":if(u===null){delete s.voice;break}if(typeof u!="string")throw new O("voice must be a string or null","voice");if(!n.voice)throw new O("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new O(`${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 O("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 O(`${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 O("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 O("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 O("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new O("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new O(`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,h]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new O(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(h!=null&&h!==c[p])throw new O(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}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 O("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new O("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 O(`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 O(`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 O("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new O("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new O("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in bi))throw new O(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&hr(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=ct({input_audio_transcription:d.transcription},s,n,r);s.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=ct({turn_detection:d.turn_detection},s,n,r);s.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new O("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new O("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Si))throw new O(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&hr(d.format,"audio.output.format"),d.speed!==void 0)throw new O("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new O("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new O("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function Ft(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 fn(t,e){let n=t;if(!n||typeof n!="object")throw new O("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new O("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:I("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new O('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new O("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new O("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 O(`${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 O("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 O("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}throw new O(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:I("item"),type:"message",role:r,content:o}}throw new O(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Bt(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 Ri=1001,Ai=1011,_r=t=>t.slice(0,120),Ei=/^[A-Za-z0-9+/=]*$/,Ii=2;function Ti(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Ii)return!1;return!0}var Ne=class{id=I("conn");ws;binding;onClosed;operatorLog;config=cn();sessionId=I("sess");conversationId=I("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:I("event"),session:Ft(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:I("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 K&&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(Xe("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:I("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:I("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:I("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:I("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:I("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:I("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:I("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:I("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=I("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:I("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.added",event_id:I("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:I("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:I("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(Q("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Nt){this.fail(Q("frame_too_large",`frame exceeds the ${Nt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(Q("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Q("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let 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(Xe(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=ct(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(Q("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:I("event"),session:Ft(this.config,this.sessionId)});return}case"conversation.item.create":{let n=fn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.added",event_id:I("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(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:I("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(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:I("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(Q("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:I("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(Q("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Ei.test(e.audio)){this.send(V(Q("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>Dt){this.send(V(Q("buffer_full",`uncommitted input audio exceeds the ${Dt}-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:I("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(V(Q("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=I("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:I("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:I("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:I("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:I("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(Q("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(V(Q("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(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(V(Q("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(V({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let 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(Q("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?Ye(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?Ye(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 O("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(Q("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let s=I("req"),a=`resp_${s}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:Bt(this.items),c=pn(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,h=n.max_output_tokens??this.config.maxOutputTokens,f=h==="inf"||h===void 0?void 0:h,k=n.tools!==void 0?n.tools:this.config.tools,P=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,x={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...f!==void 0?{max_output_tokens:f}:{},...k!==void 0?{tools:k}:{},...P!==void 0?{tool_choice:P}:{}};if(!(u&&!this.ensureVoice())){for(let m of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(m);this.inFlight=(async()=>{let m=[],g=v=>{this.responseFlushed?this.send(v):m.push(v)},y=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:I("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:I("event"),response:this.responseObject(a,"in_progress")});for(let v of m)this.send(v);m.length=0,this.responseFlushed=!0}},w={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},E=null;try{if(u){if(this.pendingTranscriptItemId!==null&&(await new Promise(A=>{this.pendingTranscriptSettled=A}),this.cancelled||this.closed))return;l=this.items.length,d=Bt(this.items)}let{input:v,sawAudioOnlyItem:R}=d??{input:[],sawAudioOnlyItem:!1},T={...x,input:v,...u?this.compositeTurnAsk(n):{}};R&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let S;try{S=await this.upstreamStream(T,s)}catch(A){this.upstreamTurnFault(A,a);return}try{for await(let A of S){if(this.cancelled)break;let _=A;if(_.type==="error"){let C=this.upstreamErrorBody(_);this.responseFlushed?this.send(V(C)):this.send({type:"response.failed",event_id:I("event"),response:this.failedResponse(a,C)});return}if(_.type==="response.output_text.delta"&&typeof _.delta=="string"){y(),w.messageOpen||(this.beginMessageItem(a,w.nextOutputIndex++),w.messageOpen=!0),this.config.outputModalities.includes("text")&&g({type:"response.output_text.delta",event_id:I("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:_.delta}),this.turnOutputIsAudio()&&(w.transcriptDelta=!0,g({type:"response.output_audio_transcript.delta",event_id:I("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:_.delta})),w.messageText+=_.delta;continue}if(_.type==="response.function_call_arguments.delta"){y();let C=typeof _.delta=="string"?_.delta:"",F=typeof _.call_id=="string"&&_.call_id.length>0?_.call_id:`${a}_fc_${w.nextOutputIndex}`,U=w.tools.get(F);if(!U){let W=typeof _.name=="string"&&_.name.length>0?_.name:void 0;U={outputIndex:w.nextOutputIndex++,name:W,args:""},w.tools.set(F,U);let q={id:F,object:"realtime.item",type:"function_call",call_id:F,name:W??"",arguments:"",status:"in_progress"};g({type:"response.output_item.added",event_id:I("event"),response_id:a,output_index:U.outputIndex,item:q}),this.emitAssistantItemAdded(q)}typeof _.name=="string"&&_.name.length>0&&(U.name=_.name),U.args+=C,g({type:"response.function_call_arguments.delta",event_id:I("event"),item_id:F,response_id:a,output_index:U.outputIndex,call_id:F,name:U.name??"",delta:C});continue}if(_.type==="response.completed"){E=_.response??null;continue}}}catch(A){this.upstreamTurnFault(A,a);return}if(this.cancelled)return;this.closeOpenItems(a,w,l),y(),this.send({type:"response.done",event_id:I("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(Ti(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:I("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:I("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:I("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:I("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:I("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:I("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:I("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:I("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:I("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:I("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:I("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:I("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:I("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:I("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:I("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:I("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=_e(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??me(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&fe(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: ${pe(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(Xe("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof K){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof vr.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Xe(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(V(r)):this.send({type:"response.failed",event_id:I("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(V(Q("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:I("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Ut&&(this.items.shift(),this.send(V({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Ut} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>ln){this.ws.close(Ri,_r("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=se(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${pe(e)}`),r.message}fail(e,n){this.send(V(e)),this.ws.close(Ai,_r(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=>wr(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),wr(this.id,e)}},mn=[];function wr(t,e){mn.push({id:t,reason:e}),mn.length>256&&mn.shift()}var pt="/v1/realtime",Oi=t=>t.slice(0,120);function Pi(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 vr(t,e){let n=new Ie.WebSocketServer({noServer:!0,maxPayload:_s}),r=new $e,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{Ut(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==ys){i.add(c);return}s.add(c);let f=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ut(c,401,"invalid local proxy api key");return}let k;try{k=await a(d)}catch(R){let y=e.statusOf?.(R)??null;Ut(c,y?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(f=!0,n.handleUpgrade(d,c,p,R=>{s.delete(c),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&&!c.destroyed&&Ut(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=hn();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let m of s)m.destroy();s.clear();for(let m of i)m.destroy();i.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==Ie.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Sn=require("@urun-sh/core");var br=require("@urun-sh/core"),xs={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},Rs={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=Rs[t.code];return e?`${n} (${e})`:n}function Dt(t){if(t==null)return null;let e=xs[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)>=br.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Dt(e?"cold_start_exceeded":"queue_timeout")}var As=qn(require("os"),1),Es=qn(require("path"),1),Is=require("url"),Os=require("util");var Ts=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Ps(t){let e=t?.code;return typeof e=="string"&&Ts.has(e)}function De(t,e){try{return t.write(e),!0}catch(n){if(Ps(n))return!1;throw n}}var Er=require("ws");var Ar=require("@urun-sh/core");var kr=require("crypto");function O(t){return`${t}_${(0,kr.randomUUID)().replace(/-/g,"").slice(0,24)}`}var qt=4*1024*1024,gn=8*1024*1024,Bt=512,jt=20*1024*1024;function Z(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function et(t,e){return{type:"server_error",code:t,message:e}}function G(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},Cs={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},$s={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ms={format:!0,voice:!0,speed:!0};function Ls(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function Ze(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 Sr(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 Ns=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:Ns})}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,s=Object.keys(o).filter(a=>!(a in Cs));if(s.length>0)throw new P(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=Ze(o.modalities,"modalities"),u=Ze(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 i={...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");i.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=Ze(u,a);for(let d of l)if(d==="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");i.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Ls(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");i.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new P("instructions must be a string or null","instructions");i.instructions=_n(u??void 0)??void 0;break;case"voice":if(u===null){delete i.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");i.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");i.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);i.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new P("tools must be an array","tools");i.tools=u;break;case"tool_choice":i.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");i.metadata=u??null;break;case"turn_detection":{if(u===null){i.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 d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new P(`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,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))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!==c[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")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){i.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 d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new P(`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 P(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(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 d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new P("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in $s))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Sr(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=ht({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=ht({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.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 d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new P("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Ms))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Sr(d.format,"audio.output.format"),d.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(d.voice!==void 0)if(d.voice===null)delete i.voice;else{if(typeof d.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");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}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 s of n.content){let i=s;if(!i||typeof i!="object")throw new P("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new P(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new P("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new P("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new P(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id: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 s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Us=1001,Ds=1011,xr=t=>t.slice(0,120),Fs=/^[A-Za-z0-9+/=]*$/,qs=2;function Bs(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>qs)return!1;return!0}var Fe=class{id=O("conn");ws;binding;onClosed;operatorLog;config=yn();sessionId=O("sess");conversationId=O("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id: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 z&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(G(et("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id: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(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id: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(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id: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 i=O("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:O("event"),previous_item_id:a,item_id:i}),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:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(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 s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(G({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(et(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=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(G(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: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.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(G(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: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(G(Z("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(G(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: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(G(Z("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Fs.test(e.audio)){this.send(G(Z("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(G(Z("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(G(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=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 s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(G(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(G(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(G(Z("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(G(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(G({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(G(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?Ze(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?Ze(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(G(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 i=O("req"),a=`resp_${i}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:Jt(this.items),c=_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}:{},...c!==void 0?{instructions:c}:{},...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,d=Jt(this.items)}let{input:b,sawAudioOnlyItem:A}=d??{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,i)}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(G(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 K=typeof w.name=="string"&&w.name.length>0?w.name:void 0;D={outputIndex:v.nextOutputIndex++,name:K,args:""},v.tools.set(q,D);let j={id:q,object:"realtime.item",type:"function_call",call_id:q,name:K??"",arguments:"",status:"in_progress"};h({type:"response.output_item.added",event_id:O("event"),response_id:a,output_index:D.outputIndex,item:j}),this.emitAssistantItemAdded(j)}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(Bs(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(G({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`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(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&&i&&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:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let u=[];s&&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,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:O("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:O("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=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(et("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof z){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Ar.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=et(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(G(r)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(G(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:O("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Bt&&(this.items.shift(),this.send(G({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`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>gn){this.ws.close(Us,xr("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(G(e)),this.ws.close(Ds,xr(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=>Rr(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Rr(this.id,e)}},vn=[];function Rr(t,e){vn.push({id:t,reason:e}),vn.length>256&&vn.shift()}var gt="/v1/realtime",js=t=>t.slice(0,120);function Hs(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
|
-
${
|
|
18
|
-
`),t.destroy()}function
|
|
19
|
-
`}function Mi(t){Le(process.stdout,t)}function $i(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function gn(t){return t.audioSession?.audio.sessionId??void 0}function ft(t,e){let n=new br.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==pt)return;r.add(i),i.on("close",()=>{r.delete(i)});let u=I("rtup"),l=$i(o),d=w=>{(e.log??Mi)(Ci(w))};d({stage:"accept",conn:u,model:l}),i.resume();let c=new AbortController,p=null,h=w=>{p??=w,c.abort(new Error(p))},f=()=>h("client socket closed"),k=()=>h("client socket closed (half-close)"),P=w=>h(`client socket error: ${w.message}`);i.once("close",f),i.once("end",k),i.once("error",P);let x=()=>{i.removeListener("close",f),i.removeListener("end",k),i.removeListener("error",P)},m=w=>{d({stage:"close",conn:u,model:l,...w})},g=w=>{let E=w,v=E.session!=null&&typeof E.session.sendResponseCreate=="function",R=E.clients!=null&&typeof E.clients.createResponse=="function";if(!v&&!R)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((T,S)=>{n.handleUpgrade(o,i,s,A=>{try{new Ne({ws:A,binding:w,operatorLog:e.operatorLog,onClosed:(_,C)=>{m({while:"live",reason:C.reason})}}),d({stage:"admit",conn:u,model:l,...gn(w)===void 0?{}:{session:gn(w)}}),T()}catch(_){S(_)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async w=>{if(c.signal.aborted){x();let E=gn(w);try{await w.release?.()}catch(v){m({while:"queued",...E===void 0?{}:{session:E},reason:p??"client socket closed",release_failed:v instanceof Error?v.message:String(v)});return}m({while:"queued",...E===void 0?{}:{session:E},reason:p??"client socket closed",released:!0}),i.destroy();return}x(),await g(w)}).catch(w=>{let E=w instanceof hn.SessionFailedError?Lt(w):null,v=null;if(w!==null&&typeof w=="object"&&"status"in w){let A=w.status;typeof A=="number"&&(v=A)}let R=v??E?.status??502,T=w instanceof Error?w.message:String(w),S=v!==null?T:E!==null?lt(E,w instanceof hn.SessionFailedError&&w.status.sessionId?`session ${w.status.sessionId}`:void 0):se(w).message;m({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:T,status:R}}),i.destroyed||Pi(i,R,S)}).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 Ar=require("crypto");var _n="x-urun-profile",mt="voice";var oe=class extends Error{status=400},Li=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Ni=/\s/;function Ui(t){return Li.test(t)}function yn(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new oe(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Sr(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 oe(`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 oe(`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 oe(`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 kr(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 oe(`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 oe(`the ${_n} header is empty \u2014 the only profile this lane accepts is "${mt}" (omit the header for the ordinary lane)`);if(l!==mt)throw new oe(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${mt}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==mt)throw new oe(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${mt}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new oe("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 oe("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:Sr(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:Sr(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:yn(u,"sentence_flush",!0),includeReasoning:yn(u,"include_reasoning",!1),metadata:yn(u,"metadata",!1)}}var Qe=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&&Ui(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(Ni.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 Se=(t,e)=>Object.assign(new Error(e),{status:t}),Bi='"transcription" (a transcription session), or no intent at all (the realtime voice session)',vn=(t,e,n)=>new K(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),wn=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof D?Se(404,n.message):n}};async function xr(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Se(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Bi}`);if(o==="transcription")throw Se(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 Se(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 Se(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(h){throw h instanceof D?Se(404,h.message):h}if(!p)throw Se(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(h){throw h instanceof D?Se(404,h.message):h}if(p!=="stt")throw Se(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 wn(t,n.stt),s=await wn(t,e),a=await wn(t,n.tts),u=await t.openAudioOn(i,r),l=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let h=new AbortController;return d=h,qi({clients:t,chatHandle:s,ttsHandle:a,chatModel:e,companions:n},p,h.signal,()=>{d===h&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(i,p)}catch(h){throw h instanceof K?vn("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function Rr(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var qt=class extends Error{};async function*qi(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"),h=!1,f=null,k=null,P=[],x=null,m=new Promise((A,_)=>{n&&n.addEventListener("abort",()=>_(new qt),{once:!0})}),g=()=>h||n?.aborted===!0,y=async A=>{if(g())return;let _;try{_=await o.createResponseOn(s,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:A}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(F){throw F instanceof K?vn("tts",u.tts,F):F}let C=_[Symbol.asyncIterator]();k=C;try{for(;;){let F=C.next(),U;try{U=await Promise.race([F,m])}catch(q){if(F.catch(()=>{}),q instanceof qt)return;throw q}if(U.done)return;let W=U.value;if(W.type==="error"){let q=W.error&&typeof W.error.message=="string"?W.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${q}`)}if(W.type==="response.completed")return}}finally{k===C&&(k=null)}},w=async()=>{for(;P.length>0&&!g();){let A=P.shift();await y(A)}},E=A=>{if(A===""||g()||(P.push(A),x!==null))return;let _=w();x=_,_.then(()=>{x===_&&(x=null)},C=>{x===_&&(x=null),f??=C})},v=()=>{h=!0,P.length=0;let A=k;if(k=null,A){let _=A.return?.();_&&_.catch(()=>{})}},R=async()=>{for(;P.length>0||x!==null;){let A=x;if(A===null){await y(P.shift());continue}await A}},T=p?new Qe({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},A=>E(A)):null,S=null;try{let A;try{A=await o.createResponseOn(i,d)}catch(_){throw _ instanceof K?vn("chat",a,_):_}for await(let _ of A){if(g())return;let C=_;if(C.type==="error"){yield _;return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){yield _,T?.push(C.delta);continue}if(C.type==="response.function_call_arguments.delta"){T?.flush(),yield _;continue}if(C.type==="response.completed"){S=_.response;continue}}T?.flush(),T?.dispose(),p&&await R(),S!==null&&(yield{type:"response.completed",response:S})}finally{T?.dispose(),v();try{if(f instanceof K)throw f}finally{r?.()}}}var ae=(t,e)=>Object.assign(new Error(e),{status:t});function bn(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ji(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Hi='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Sn(t,e,n,r){if(!t.supportsAudio)throw ae(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 D?ae(404,d.message):d}if(!o){let d=null;if(t.realtimeCompanionsFor)try{d=await t.realtimeCompanionsFor(e)}catch(c){throw c instanceof D?ae(404,c.message):c}if(d!==null)return await xr(t,e,d,n,r);throw ae(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 ae(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 D?ae(404,d.message):d}if(i&&!t.openTurnsOn)throw ae(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(c){throw c instanceof D?ae(404,c.message):c}if(d!=="stt")throw ae(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 ae(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Hi}`);if(r==="transcription"&&!i)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)`);let s;try{s=await t.sessionHandle(e)}catch(d){throw d instanceof ie?ae(503,d.message):d}let a=`conn_${(0,Ar.randomUUID)()}`,u={audio:await t.openAudioOn(s,n,a)},l={clients:{createResponse:async d=>await t.createResponseOn(s,d,a)},voice:o,audioSession:u};return i&&(l.turns=d=>t.openTurnsOn(s,d)),r==="transcription"&&(l.intent="transcription"),t.releaseSessionHandle&&(l.release=()=>t.releaseSessionHandle(s)),e!==void 0&&(l.model=e),l}function jt(t,e,n){let r=Rr(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 ae(401,"invalid local proxy api key")}return Sn(r,bn(o),i,ji(o))}}}var Z=class extends Error{};async function Ht(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Z(`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 Z(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function Vt(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 Z(`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 Z?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var Er="/v1/images/generations",Gt="/v1/images/edits";function Ir(t){return t===Er||t===Gt}var Tr="/v1/images/models";async function Or(t,e,n){if(t){if(t.model=re({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var L=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Vi=16*1024*1024,Pr=64*1024*1024;function Cr(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 gt(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 Mr(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??{},P=typeof k.message=="string"&&k.message.length>0&&fe(k.message)?k.message:null;throw P===null?(s(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(f)}`),new L(502,"the image upstream failed while serving this request")):new L(502,`image upstream error: ${P}`)}if(f.type==="response.completed"){u=f.response??null;break}}if(u===null)throw new L(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=be(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new L(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(Cr(p)===null)throw new L(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 $r(t,e){if(t instanceof L)return t;if(t instanceof ye)throw t;return t instanceof D?new L(404,t.message):new L(502,ze("image",t,e))}async function Lr(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 gt(r,new L(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Nr(t,e){t&&(t.outputUnits=e.images.length)}function Ur(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 Gi={model:!0,prompt:!0,response_format:!0,n:!0};async function Dr(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Pr;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${Er}`);let i;try{i=JSON.parse((await Ht(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof Z?new L(413,p.message):new L(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new L(400,"request body must be a JSON object");let s=i;for(let p of Object.keys(s))if(!Gi[p])throw new L(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let a=s.prompt;if(typeof a!="string"||a.trim().length===0)throw new L(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 L(400,"model must be a string","model");await Or(n.turn,n.clients,u);let l=s.n??1;if(l!==1)throw new L(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 L(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",a.length,a.length),!await Lr(n.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Mr(n.clients,u,c,n.turn?ue(n.turn):void 0,n.turn,r);Nr(n.turn,p),Ur(e,p)}catch(p){throw $r(p,r)}}catch(i){if(i instanceof Z){gt(e,new L(413,i.message));return}if(i instanceof L){gt(e,i);return}throw i}}var Ji={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Fr(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Pr,i=n.maxImagePartBytes??Vi;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${Gt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new L(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let a;try{a=await Vt(t,o)}catch(f){throw f instanceof Z?new L(413,f.message):new L(400,String(f instanceof Error?f.message:f))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new L(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 L(400,"model must be a string field","model");let d=l===null?void 0:l;await Or(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new L(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 f of a.keys())if(!Ji[f])throw new L(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 L(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 L(413,`image part exceeds the ${i}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let P=new Uint8Array(await k.arrayBuffer()),x=Cr(P);if(x===null)throw new L(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",f);p.push({bytes:P,mime:x})}if(p.length===0)throw new L(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await Lr(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:u}];for(let{bytes:f,mime:k}of p)h.push({type:"input_image",image_url:`data:${k};base64,${Buffer.from(f).toString("base64")}`});try{let f=await Mr(n.clients,d,h,n.turn?ue(n.turn):void 0,n.turn,r);Nr(n.turn,f),Ur(e,f)}catch(f){throw $r(f,r)}}catch(s){if(s instanceof Z){gt(e,new L(413,s.message));return}if(s instanceof L){gt(e,s);return}throw s}}var ht="/v1/audio/speech";function Kr(t){return t===ht}var Br=4096,qr=18e4,jr=5e3,Wi=64*1024*1024,Hr=8,Vr=5,Gr=1024*1024,Ze="voice_applied",Wt="X-Urun-Voice-Applied",$=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function kn(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 Kt=class extends ${constructor(e){super(502,e)}};function zr(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 Yr(t){return new $(502,`the runtime's ${Ze} receipt ${JSON.stringify(t)} cannot be relayed as the ${Wt} 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 Ki(t,e,n){if(t){if(t.model=re({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Xr(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var zi=2;function Yi(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>zi)return!1;return!0}function Xi(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 Jr=new WeakMap,Jt=new WeakMap;function Qi(t,e){let n=Jt.get(t)??0;if(n>=Hr)throw new $(503,`this model's speech queue is full \u2014 ${Hr} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Vr}s`,void 0,Vr);Jt.set(t,n+1);let r=Jr.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return Jr.set(t,i),(async()=>{await r;try{return await e()}finally{Jt.set(t,(Jt.get(t)??1)-1),o()}})()}async function Zi(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new $(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 K))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 Ue(t,e){if(t instanceof $)return t;if(t instanceof ye)throw t;return t instanceof D?new $(404,t.message):new $(502,ze("speech",t,e))}async function Wr(t,e,n,r,o,i,s,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return Qi(e,async()=>{if(s?.()===!0)return null;let p=!1,h=!1,f=!1,k,P=new Promise(R=>{k=R}),x=[],m=()=>{h&&!f&&x.length>=o.quietRunFrames&&(f=!0,k())},g=e.onOutputAudio(R=>{let T=Buffer.from(R,"base64");if(T.byteLength===0)return;let S=Yi(T);if(!p){if(S)return;p=!0}if(S){x.push(T),m();return}for(let A of x)c(A);x.length=0,c(T),m()}),y=null,w,E,v;try{v=(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(_=>{E=setTimeout(_,i.capMs)}),S=!1;for(;;){let _=v.next(),C=await Promise.race([_,T]);if(C===void 0){S=!0,_.catch(()=>{});break}if(C.done)break;let F=C.value;if(F.type==="error"){let U=F.error??{};await v.return?.();let W=typeof U.message=="string"&&U.message.length>0&&fe(U.message)?U.message:null;throw W===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(F)}`),new $(502,"the speech upstream failed while serving this request")):new $(502,`speech upstream error: ${W}`)}if(F.type==="response.completed"){y=F.response??null,h=!0,u?.(y),m(),await v.return?.();break}}if(clearTimeout(E),S)throw new $(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(y===null)throw new $(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let A=!1;if(await Promise.race([P,new Promise(_=>{w=setTimeout(()=>{A=!0,_()},o.capMs)})]),w!==void 0&&clearTimeout(w),r.voice!==void 0){let _=y[Ze];if(typeof _!="string"||_!==r.voice){let C=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof _=="string"?`${Ze} ${JSON.stringify(_)}`:`no ${Ze} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw f?new Kt(C):new $(502,C)}}if(!p)throw new $(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(A&&!f&&x.length<1)throw new $(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return y}catch(R){throw R instanceof Kt||await Zi(t,n,v,i.returnBoundMs),R}finally{w!==void 0&&clearTimeout(w),E!==void 0&&clearTimeout(E),g()}})}function es(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",Wt)),t.write(a,u=>{u||(i+=a.byteLength,Xr(e,i))}),t.writableLength>Gr&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${Gr} 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[Ze];if(typeof u=="string"){if(!zr(u))throw Yr(u);t.addTrailers({[Wt]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:s}}async function ts(t,e,n,r){let o;try{o=await t(e)}catch(i){throw Ue(i,r)}return o?!0:(kn(n,new $(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 ns={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},rs="wav, pcm";async function Qr(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??Wi,i=!1;e.once("close",()=>{i=!0});let s=()=>i||e.destroyed;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${ht}`);let a;try{a=JSON.parse((await Ht(t,o)).toString("utf8")||"{}")}catch(y){throw y instanceof Z?new $(413,y.message):new $(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new $(400,"request body must be a JSON object");let u=a;for(let y of Object.keys(u))if(!ns[y])throw new $(400,`request field "${y}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,y);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new $(400,"input is required and must be a non-empty string","input");if(l.length>Br)throw new $(400,`input is ${l.length} chars \u2014 over the ${Br}-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 $(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new $(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new $(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 ${ht} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(y){throw Ue(y,r)}if(p.defect!==null)throw new $(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let h=typeof c=="string"?c:void 0;if(h!==void 0&&p.published.length>0&&!p.published.includes(h))throw new $(400,`voice ${JSON.stringify(h)} 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 $(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 ${rs} \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 $(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 $(400,"speed, when present, must be a number","speed");if(k!==1)throw new $(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 P=u.instructions;if(P!==void 0){if(typeof P!="string")throw new $(400,"instructions, when present, must be a string","instructions");if(P.trim().length>0)throw new $(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 Ki(n.turn,n.clients,d);let x=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",x,x),!await ts(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new $(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 $(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 $(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let m;try{m=await n.clients.speechSessionHandle(d)}catch(y){throw Ue(y,r)}let g;try{g=await n.clients.openAudioOn(m)}catch(y){throw Ue(y,r)}n.turn&&(n.turn.sessionId=g.sessionId);try{if(f==="wav"){let y=[],w=await Wr(n.clients,g,m,{model:d,text:l,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??qr,returnBoundMs:n.turnReturnBoundMs??jr},s,v=>y.push(v),v=>{n.turn&&(n.turn.outputSeconds=be(v))},r);if(w===null||s())return;let E=Buffer.concat(y);if(h===void 0){let v=w[Ze];if(typeof v=="string"){if(!zr(v))throw Yr(v);e.setHeader(Wt,v)}}Xr(n.turn,E.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Xi(E.byteLength),E]))}else{let y=es(e,n.turn,s,h===void 0),w;try{w=await Wr(n.clients,g,m,{model:d,text:l,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??qr,returnBoundMs:n.turnReturnBoundMs??jr},s,y.sink,E=>{n.turn&&(n.turn.outputSeconds=be(E))},r)}catch(E){let v=Ue(E,r);if(!y.started())throw v;n.turn&&(n.turn.streamError=!0),y.fail(v);return}if(w===null)return;try{await y.finish(w)}catch(E){let v=Ue(E,r);n.turn&&(n.turn.streamError=!0),y.fail(v);return}}}catch(y){throw Ue(y,r)}}catch(a){if(a instanceof Z){kn(e,new $(413,a.message));return}if(a instanceof $){kn(e,a);return}throw a}}var zt="/v1/audio/transcriptions";function Zr(t){return t===zt}var eo="/v1/audio/models",os=16*1024*1024,is=64*1024*1024,G=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function xn(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 to(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 ss(t){if(!to(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 as(t,e,n){if(t){if(t.model=re({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function us(t,e){t&&(t.outputUnits=e.seconds)}async function ds(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??{},h=typeof p.type=="string"?p.type:"upstream_error",f=typeof p.message=="string"&&p.message.length>0&&fe(p.message)?p.message:null;throw f===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new G(h==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new G(h==="invalid_request_error"?400:502,`transcription upstream error: ${f}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new G(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return i&&(i.outputSeconds=be(d)),Je(l,d)}function no(t,e){if(t instanceof G)return t;if(t instanceof ye)throw t;return t instanceof D?new G(404,t.message):new G(502,ze("transcription",t,e))}async function ls(t,e,n,r){let o;try{o=await t(e)}catch(i){throw no(i,r)}return o?!0:(xn(n,new G(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 cs=new Set(["file","model","language","response_format"]);async function ro(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??is,i=n.maxAudioPartBytes??os;try{if(t.method!=="POST")throw new G(405,`${String(t.method)} is not supported on ${zt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new G(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let a;try{a=await Vt(t,o)}catch(m){throw m instanceof Z?new G(413,m.message):new G(400,String(m instanceof Error?m.message:m))}let u=new Map;for(let m of a.keys()){if(!cs.has(m))throw new G(400,`form field "${m}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,m);u.set(m,(u.get(m)??0)+1)}for(let[m,g]of u)if(g>1)throw new G(400,`form field "${m}" 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`,m);let l=a.get("model");if(l!==null&&typeof l!="string")throw new G(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 G(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,h=a.get("response_format")??"json";if(h!=="json")throw new G(400,`response_format ${JSON.stringify(h)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let f=a.get("file");if(!(f instanceof File))throw new G(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 G(413,`file part exceeds the ${i}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let k=new Uint8Array(await f.arrayBuffer());if(!to(k))throw new G(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 P=ss(k);if(P===null)throw new G(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 as(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",k.length,k.length),!await ls(n.transcriptionModels,d,e,r))return;let x=[{type:"input_audio",input_audio:{data:Buffer.from(k).toString("base64"),format:"wav"}}];try{let m=await ds(n.clients,d,x,p,n.turn?ue(n.turn):void 0,n.turn,r);us(n.turn,P),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:m}))}catch(m){throw no(m,r)}}catch(s){if(s instanceof Z){xn(e,new G(413,s.message));return}if(s instanceof G){xn(e,s);return}throw s}}var io="/v1/usage/requests",oo=1e4,ps=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ae=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},et=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var so=1024*1024;function Rn(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Ae(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Ae(`"${e}" must be an array of uuid strings`);if(n.length>oo)throw new Ae(`"${e}" carries ${n.length} ids; at most ${oo} 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"||!ps.test(i))throw new Ae(`"${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 ao(t){return Rn(t,"inference_ids")}function Yt(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 et(`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 et(`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 en=require("@urun-sh/core");var An="/partners/huggingface/v1/billing/requests";function fs(t){return Rn(t,"requestIds")}function ms(t){return t>=200&&t<=399}function gs(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 uo(t,e){let n=fs(t),r=await e(n);return Yt(r,n),gs(r)}var hs={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function ys(t){return hs[t]??null}var fo=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function _s(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function ws(t){return t==="surface"}function vs(t){let e=t?.ledgerFailureReason;return fo.includes(e)?e:"unknown"}var bs=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],lo=["priced","unpriced"],Ss={written:lo,already_written:lo,skipped:bs,failed:fo},Hd=Object.entries(Ss).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function ks(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function xs(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 Rs=256,co=4096,_t=12e4,As=250,Es=8e3,wt=[],po=new Set,vt=0,yt=!1;var Is=new Set;function Ts(){return vt===0&&wt.length===0}function Os(){if(Ts()){yt=!1;for(let t of[...Is])t()}}function mo(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
20
|
-
`}function Ps(t){Le(process.stdout,t)}function go(t,e){try{t(e)}catch{}}function ho(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Ps,o=ys(e.path);if(o===null)return;let i=d=>{try{n.observe(d)}catch{}},s=(d,c)=>{i({outcome:"skipped",reason:d}),go(r,mo("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:xs(e),completed_at:e.ts,billable_outcome:ks(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(wt.length>=co){s("queue_full",`${wt.length} ledger writes are already waiting (capacity ${co}, ${vt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}wt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),vt<Rs&&(vt+=1,Cs())}async function Cs(){try{for(;;){let t=Ms();if(t===void 0)return;po.add(t);try{await $s(t)}finally{po.delete(t)}}}finally{vt-=1,Os()}}function Ms(){let t=Date.now();for(;;){let e=wt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<_t)return e;tt(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 ${_t}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function $s(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);tt(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=_s(o);if(i!==null){tt(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=vs(o),a=Date.now()-t.queuedAt;if(yt){tt(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(ws(s)&&a<_t){if(await Ns(Ls(t.attempts)),yt||Date.now()-t.queuedAt>=_t){let u=Date.now()-t.queuedAt;tt(t,{outcome:"failed",reason:yt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:yt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${_t}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}tt(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 Ls(t){return Math.min(Es,As*2**Math.max(0,t-1))}function Ns(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function tt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;go(t.report,mo(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function Tn(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Us(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 ee(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){ee(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function On(t,e,n){let r=e.error,o=r?.type??"upstream_error",i=n?.operatorError??(d=>console.error(d)),s=_e(r),a=s??me(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"),ee(t,l,{error:{message:a,type:o,code:u}})}function ge(t,e,n,r){ee(t,e,{type:"error",error:{type:n,message:r}})}function nt(t,e,n){if(e==="anthropic"){ee(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ee(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Ds=64*1024*1024,bt=class extends Error{};async function yo(t,e=Ds){let n=[],r=0;for await(let i of t){if(r+=i.length,r>e)throw new bt(`request body exceeds ${e} bytes`);n.push(i)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function De(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 vo(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 Xt(t){let e=vo(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function _o(t){let e=Xt(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Fs(t,e){let n=vo(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Bs(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 qs(t,e){let n=Bs(e);n&&(t.timing=n),t.outputSeconds=be(e)}function Fe(t,e){Fs(t,e),qs(t,e)}async function tn(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function bo(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 js(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 Qt=class extends Error{};function Hs(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 Qt(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Vs(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:Hs(n.role,n.content)})}return e}function En(t){return Ve(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 Gs(t,e,n,r,o,i,s){let a=at(i.id),u=t.stream===!0;if(i.model=re(t),i.stream=u,await tn(i,e,typeof t.model=="string"?t.model:void 0),u){let m;try{m=await dt({body:t,clients:e,store:n,stats:o,responseId:a,turn:i})}catch(g){if(g instanceof D){nt(r,"openai",g);return}if(g instanceof de){J(r,g.status,g.message);return}if(g instanceof ce||g instanceof ie){r.setHeader("retry-after","2"),J(r,503,g.message,"capacity_error");return}throw g}Tn(r);for await(let g of m.events){if(g.type==="error"){i.streamError=!0;let y=g.error,w=_e(y),E=w??me(i.id);w===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
|
|
21
|
-
data: ${JSON.stringify({error:{message:E,type:y?.type??"upstream_error",code:y?.code??null}})}
|
|
17
|
+
${js(n)}\r
|
|
18
|
+
`),t.destroy()}function Js(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
|
|
19
|
+
`}function Vs(t){De(process.stdout,t)}function Gs(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 Er.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==gt)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=O("rtup"),l=Gs(o),d=v=>{(e.log??Vs)(Js(v))};d({stage:"accept",conn:u,model:l}),s.resume();let c=new AbortController,p=null,m=v=>{p??=v,c.abort(new Error(p))},f=()=>m("client socket closed"),k=()=>m("client socket closed (half-close)"),R=v=>m(`client socket error: ${v.message}`);s.once("close",f),s.once("end",k),s.once("error",R);let y=()=>{s.removeListener("close",f),s.removeListener("end",k),s.removeListener("error",R)},g=v=>{d({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,s,i,I=>{try{new Fe({ws:I,binding:v,operatorLog:e.operatorLog,onClosed:(w,C)=>{g({while:"live",reason:C.reason})}}),d({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,c.signal).then(async v=>{if(c.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}),s.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",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:T,status:A}}),s.destroyed||Hs(s,A,x)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}var Cr=require("crypto");var xn="x-urun-profile",_t="voice";var ie=class extends Error{status=400},Ws=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Ks=/\s/;function zs(t){return Ws.test(t)}function kn(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ie(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Ir(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new ie(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new ie(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new ie(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function Or(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new ie(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let l=n.trim();if(l==="")throw new ie(`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 ie(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${_t}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==_t)throw new ie(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${_t}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new ie("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new ie("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Ir(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:Ir(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&&zs(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(Ks.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}),Qs='"transcription" (a transcription session), or no intent at all (the realtime voice session)',An=(t,e,n)=>new z(`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 Tr(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: ${Qs}`);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 s=await Rn(t,n.stt),i=await Rn(t,e),a=await Rn(t,n.tts),u=await t.openAudioOn(s,r),l=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,Zs({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(m){throw m instanceof z?An("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function Pr(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Vt=class extends Error{};async function*Zs(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,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"),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(i,{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 z?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(j){if(q.catch(()=>{}),j instanceof Vt)return;throw j}if(D.done)return;let K=D.value;if(K.type==="error"){let j=K.error&&typeof K.error.message=="string"?K.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${j}`)}if(K.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(s,d)}catch(w){throw w instanceof z?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 z)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 ei(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var ti='"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(c){throw c instanceof F?le(404,c.message):c}if(d!==null)return await Tr(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 s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(d){throw d instanceof F?le(404,d.message):d}if(s&&!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(s&&t.transcriptStreamFor){let d;try{d=await t.transcriptStreamFor(e)}catch(c){throw c instanceof F?le(404,c.message):c}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: ${ti}`);if(r==="transcription"&&!s)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 i;try{i=await t.sessionHandle(e)}catch(d){throw d instanceof ae?le(503,d.message):d}let a=`conn_${(0,Cr.randomUUID)()}`,u={audio:await t.openAudioOn(i,n,a)},l={clients:{createResponse:async d=>await t.createResponseOn(i,d,a)},voice:o,audioSession:u};return s&&(l.turns=d=>t.openTurnsOn(i,d)),r==="transcription"&&(l.intent="transcription"),t.releaseSessionHandle&&(l.release=()=>t.releaseSessionHandle(i)),e!==void 0&&(l.model=e),l}function Gt(t,e,n){let r=Pr(t,n);return{resolve:async(o,s)=>{if(e!==void 0){let i=o.headers.authorization,a=typeof i=="string"?i.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),s,ei(o))}}}var $=class extends Error{},pe=class extends Error{};function ee(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Kt(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 Wt(t){let e=Kt(t);return e!==null&&e<=1?e:null}function $r(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=ni(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 s={},i=[],a=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=ii(o[l],l,o.length,n);if(a.has(c.key))throw new $(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),s[c.key]=d,i.push(c)}let u={model:e,state:r,questions:s};return n.length>0&&(u.media=n),{systemone:u,specs:i}}function ni(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)oi(o,r,e);return ri(r)}function ri(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
|
|
22
20
|
|
|
23
|
-
`),r.
|
|
24
|
-
|
|
21
|
+
`)}function oi(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"){si(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let s=t.output;if(typeof s=="string"){e.push({text:s});return}if(Array.isArray(s)){Mr(s,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 si(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 s of o){if(!ee(s))throw new $("decisions assistant message parts must be JSON objects");if(s.type==="output_text"&&typeof s.text=="string")n.push({role:e,text:s.text});else if(s.type==="refusal"&&typeof s.refusal=="string")n.push({role:e,text:`[refusal] ${s.refusal}`});else throw new $(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}Mr(o,n,r,e)}function Mr(t,e,n,r,o=!0){for(let s of t){if(!ee(s))throw new $("decisions content parts must be JSON objects");switch(nt(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new $("input_text requires a string text");e.push({role:r,text:s.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 i=s.data;if(!ee(i)&&!(Array.isArray(i)&&i.every(ee)))throw new $("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(Lr(s));break}default:throw new $(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function Lr(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 s=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(s?o.length%4!==0:o.length%4===1))throw new $("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=t.detail;if(i!=null&&i!=="low"&&i!=="high"&&i!=="auto"&&i!=="original")throw new $("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(a.detail=i),a}function ii(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 s=t.name;if(s!==void 0&&typeof s!="string")throw new $(`questions[${e}] name must be a string`);let i=s??null,a=i??`q${e}`,u=ai(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:u,options:[["no","the condition is not true"],["yes","the condition is true"]]},spec:{type:o,key:a,name:i}};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 d=[],c=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(c.has(y))throw new $(`questions[${e}] has duplicate choice value ${JSON.stringify(y)} (choices must be unique)`);c.add(y);let g=k.description;if(g!==void 0&&typeof g!="string")throw new $(`questions[${e}] choice description must be a string`);d.push(R),p.push(g)}let m=l.map((k,R)=>({name:String(d[R]),description:p[R]??String(d[R])}));return{entry:{kind:"choice",prompt:u,options:m},spec:{type:o,key:a,name:i,choiceValues:d}}}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 d=[],c=[];for(let m of l){if(!ee(m)||typeof m.label!="string")throw new $(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new $(`questions[${e}] has duplicate level label ${JSON.stringify(m.label)}`);d.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(c.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`);c.push(k)}return{entry:{kind:"score",prompt:u,criteria:c},spec:{type:o,key:a,name:i,levelLabels:d,scoreCriteria:c}}}}}function ai(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 s of t){if(!ee(s))throw new $(`questions[${e}] instruction parts must be JSON objects`);switch(nt(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new $(`questions[${e}] input_text requires a string text`);o.push(s.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(Lr(s));break}case"input_json":{let i=s.data;if(!ee(i)&&!(Array.isArray(i)&&i.every(ee)))throw new $(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new $(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
|
|
22
|
+
|
|
23
|
+
`)}function Nr(t,e){if(!ee(e))throw new pe("decision answer was not a JSON object");let n=e.choices;if(!ee(n))throw new pe("decision answer carried no choices object");let r=[];for(let o of t){let s=n[o.key];if(!ee(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=ee(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let a=Wt(i.yes),u=Wt(i.no),l=a??(u!==null?1-u:null);if(l===null)throw new pe(`the predicate answer for "${o.key}" carries neither a yes nor a no probability to translate`);r.push({type:"predicate",name:o.name,probability:l});continue}case"choice":{let a=o.choiceValues??[],u=s.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 d=Kt(s.confidence);if(d===null)throw new pe(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let m=Wt(i[String(p)]);m!==null&&c.push({value:p,probability:m})}r.push({type:"choice",name:o.name,choice:a[l],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],u=o.scoreCriteria??[],l=Kt(s.score);if(l===null)throw new pe(`the score answer for "${o.key}" carries no numeric score to translate`);let d=Kt(s.confidence);if(d===null)throw new pe(`the score answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p=0;p<a.length;p++){let m=Wt(i[u[p]]);m!==null&&c.push({value:p,label:a[p],probability:m})}r.push({type:"score",name:o.name,score:l,confidence:d,probabilities:c});continue}}}return r}var te=class extends Error{};async function zt(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 s of t){let i=s;if(o+=i.length,o>e)throw new te(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function Yt(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new te(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")i.set(l,d);else if(Array.isArray(d))for(let c of d)i.append(l,c);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof te?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Ur="/v1/images/generations",Xt="/v1/images/edits";function Dr(t){return t===Ur||t===Xt}var Fr="/v1/images/models";async function qr(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}},ui=16*1024*1024,Br=64*1024*1024;function jr(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 Hr(t,e,n,r,o,s){let i=s??(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?(i(`[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 d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(jr(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 d.push(c),{images:d}}function Jr(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,Qe("image",t,e))}async function Vr(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 Gr(t,e){t&&(t.outputUnits=e.images.length)}function Wr(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 li={model:!0,prompt:!0,response_format:!0,n:!0};async function Kr(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Br;try{if(t.method!=="POST")throw new N(405,`${String(t.method)} is not supported on ${Ur}`);let s;try{s=JSON.parse((await zt(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(s===null||typeof s!="object"||Array.isArray(s))throw new N(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!li[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=i.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=i.model===void 0?void 0:i.model;if(u!==void 0&&typeof u!="string")throw new N(400,"model must be a string","model");await qr(n.turn,n.clients,u);let l=i.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 d=i.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");if(n.stats?.request("images_generations",a.length,a.length),!await Vr(n.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Hr(n.clients,u,c,n.turn?de(n.turn):void 0,n.turn,r);Gr(n.turn,p),Wr(e,p)}catch(p){throw Jr(p,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 di={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function zr(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Br,s=n.maxImagePartBytes??ui;try{if(t.method!=="POST")throw new N(405,`${String(t.method)} is not supported on ${Xt}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new N(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await Yt(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 d=l===null?void 0:l;await qr(n.turn,n.clients,d);let c=a.get("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");for(let f of a.keys())if(!di[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>s)throw new N(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let R=new Uint8Array(await k.arrayBuffer()),y=jr(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 Vr(n.imageModels,d,"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 Hr(n.clients,d,m,n.turn?de(n.turn):void 0,n.turn,r);Gr(n.turn,f),Wr(e,f)}catch(f){throw Jr(f,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 vt="/v1/audio/speech";function oo(t){return t===vt}var Yr=4096,Xr=18e4,Qr=5e3,ci=64*1024*1024,Zr=8,eo=5,to=1024*1024,rt="voice_applied",Zt="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 On(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 en=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 io(t){return new L(502,`the runtime's ${rt} receipt ${JSON.stringify(t)} cannot be relayed as the ${Zt} 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 pi(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 ao(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var fi=2;function mi(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>fi)return!1;return!0}function hi(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 no=new WeakMap,Qt=new WeakMap;function gi(t,e){let n=Qt.get(t)??0;if(n>=Zr)throw new L(503,`this model's speech queue is full \u2014 ${Zr} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${eo}s`,void 0,eo);Qt.set(t,n+1);let r=no.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return no.set(t,s),(async()=>{await r;try{return await e()}finally{Qt.set(t,(Qt.get(t)??1)-1),o()}})()}async function yi(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new L(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof z))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function qe(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,Qe("speech",t,e))}async function ro(t,e,n,r,o,s,i,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return gi(e,async()=>{if(i?.()===!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=mi(T);if(!p){if(x)return;p=!0}if(x){y.push(T),g();return}for(let I of y)c(I);y.length=0,c(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,s.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 K=typeof D.message=="string"&&D.message.length>0&&ge(D.message)?D.message:null;throw K===null?(d(`[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: ${K}`)}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 ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(_===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 en(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 en||await yi(t,n,b,s.returnBoundMs),A}finally{v!==void 0&&clearTimeout(v),E!==void 0&&clearTimeout(E),h()}})}function _i(t,e,n,r){let o=!1,s=0,i=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Zt)),t.write(a,u=>{u||(s+=a.byteLength,ao(e,s))}),t.writableLength>to&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${to} 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 io(u);t.addTrailers({[Zt]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:i}}async function wi(t,e,n,r){let o;try{o=await t(e)}catch(s){throw qe(s,r)}return o?!0:(On(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 vi={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},bi="wav, pcm";async function uo(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??ci,s=!1;e.once("close",()=>{s=!0});let i=()=>s||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 zt(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(!vi[_])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>Yr)throw new L(400,`input is ${l.length} chars \u2014 over the ${Yr}-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 L(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.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(d)}catch(_){throw qe(_,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 c=="string"?c: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 ${bi} \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 pi(n.turn,n.clients,d);let y=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",y,y),!await wi(n.speechModels,d,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(i())return;let g;try{g=await n.clients.speechSessionHandle(d)}catch(_){throw qe(_,r)}let h;try{h=await n.clients.openAudioOn(g)}catch(_){throw qe(_,r)}n.turn&&(n.turn.sessionId=h.sessionId);try{if(f==="wav"){let _=[],v=await ro(n.clients,h,g,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Xr,returnBoundMs:n.turnReturnBoundMs??Qr},i,b=>_.push(b),b=>{n.turn&&(n.turn.outputSeconds=xe(b))},r);if(v===null||i())return;let E=Buffer.concat(_);if(m===void 0){let b=v[rt];if(typeof b=="string"){if(!so(b))throw io(b);e.setHeader(Zt,b)}}ao(n.turn,E.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([hi(E.byteLength),E]))}else{let _=_i(e,n.turn,i,m===void 0),v;try{v=await ro(n.clients,h,g,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Xr,returnBoundMs:n.turnReturnBoundMs??Qr},i,_.sink,E=>{n.turn&&(n.turn.outputSeconds=xe(E))},r)}catch(E){let b=qe(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=qe(E,r);n.turn&&(n.turn.streamError=!0),_.fail(b);return}}}catch(_){throw qe(_,r)}}catch(a){if(a instanceof te){On(e,new L(413,a.message));return}if(a instanceof L){On(e,a);return}throw a}}var tn="/v1/audio/transcriptions";function lo(t){return t===tn}var co="/v1/audio/models",Si=16*1024*1024,ki=64*1024*1024,W=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Tn(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 po(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 xi(t){if(!po(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(s==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,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(s==="data"){let u=t.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Ri(t,e,n){if(t){if(t.model=oe({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Ai(t,e){t&&(t.outputUnits=e.seconds)}async function Ei(t,e,n,r,o,s,i){let a=i??(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??{},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(c)}`),new W(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new W(m==="invalid_request_error"?400:502,`transcription upstream error: ${f}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new W(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=xe(d)),ze(l,d)}function fo(t,e){if(t instanceof W)return t;if(t instanceof ve)throw t;return t instanceof F?new W(404,t.message):new W(502,Qe("transcription",t,e))}async function Ii(t,e,n,r){let o;try{o=await t(e)}catch(s){throw fo(s,r)}return o?!0:(Tn(n,new W(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Oi=new Set(["file","model","language","response_format"]);async function mo(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??ki,s=n.maxAudioPartBytes??Si;try{if(t.method!=="POST")throw new W(405,`${String(t.method)} is not supported on ${tn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new W(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await Yt(t,o)}catch(g){throw g instanceof te?new W(413,g.message):new W(400,String(g instanceof Error?g.message:g))}let u=new Map;for(let g of a.keys()){if(!Oi.has(g))throw new W(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 W(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 W(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 W(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,m=a.get("response_format")??"json";if(m!=="json")throw new W(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 W(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(f.size>s)throw new W(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let k=new Uint8Array(await f.arrayBuffer());if(!po(k))throw new W(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let R=xi(k);if(R===null)throw new W(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Ri(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",k.length,k.length),!await Ii(n.transcriptionModels,d,e,r))return;let y=[{type:"input_audio",input_audio:{data:Buffer.from(k).toString("base64"),format:"wav"}}];try{let g=await Ei(n.clients,d,y,p,n.turn?de(n.turn):void 0,n.turn,r);Ai(n.turn,R),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:g}))}catch(g){throw fo(g,r)}}catch(i){if(i instanceof te){Tn(e,new W(413,i.message));return}if(i instanceof W){Tn(e,i);return}throw i}}var go="/v1/usage/requests",ho=1e4,Ti=/^[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 yo=1024*1024;function Pn(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>ho)throw new Oe(`"${e}" carries ${n.length} ids; at most ${ho} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!Ti.test(s))throw new Oe(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function _o(t){return Pn(t,"inference_ids")}function nn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new 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(s.inference_id))throw new ot(`the usage surface returned ${s.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(s.inference_id)}}var an=require("@urun-sh/core");var Cn="/partners/huggingface/v1/billing/requests";function Pi(t){return Pn(t,"requestIds")}function Ci(t){return t>=200&&t<=399}function $i(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Ci(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function wo(t,e){let n=Pi(t),r=await e(n);return nn(r,n),$i(r)}var Mi={"/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 Li(t){return Mi[t]??null}var ko=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Ni(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Ui(t){return t==="surface"}function Di(t){let e=t?.ledgerFailureReason;return ko.includes(e)?e:"unknown"}var Fi=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],vo=["priced","unpriced"],qi={written:vo,already_written:vo,skipped:Fi,failed:ko},dd=Object.entries(qi).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Bi(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function ji(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 Hi=256,bo=4096,St=12e4,Ji=250,Vi=8e3,kt=[],So=new Set,xt=0,bt=!1;var Gi=new Set;function Wi(){return xt===0&&kt.length===0}function Ki(){if(Wi()){bt=!1;for(let t of[...Gi])t()}}function xo(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
24
|
+
`}function zi(t){De(process.stdout,t)}function Ro(t,e){try{t(e)}catch{}}function Ao(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??zi,o=Li(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),Ro(r,xo("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:ji(e),completed_at:e.ts,billable_outcome:Bi(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>=bo){i("queue_full",`${kt.length} ledger writes are already waiting (capacity ${bo}, ${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<Hi&&(xt+=1,Yi())}async function Yi(){try{for(;;){let t=Xi();if(t===void 0)return;So.add(t);try{await Qi(t)}finally{So.delete(t)}}}finally{xt-=1,Ki()}}function Xi(){let t=Date.now();for(;;){let e=kt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<St)return e;st(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 Qi(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);st(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=Ni(o);if(s!==null){st(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=Di(o),a=Date.now()-t.queuedAt;if(bt){st(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(Ui(i)&&a<St){if(await ea(Zi(t.attempts)),bt||Date.now()-t.queuedAt>=St){let u=Date.now()-t.queuedAt;st(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}st(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Zi(t){return Math.min(Vi,Ji*2**Math.max(0,t-1))}function ea(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function st(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Ro(t.report,xo(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function Ln(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function ta(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 H(t,e,n,r="invalid_request_error",o){ne(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Nn(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=be(r),a=i??ye(n?.inferenceId??null);i===null&&s(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let 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 it(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 na=64*1024*1024,Rt=class extends Error{};async function Eo(t,e=na){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Rt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Be(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 To(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function rn(t){let e=To(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Io(t){let e=rn(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:ra(t)},completion_tokens_details:{reasoning_tokens:0}}}function ra(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 oa(t,e){let n=To(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function sa(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"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function ia(t,e){let n=sa(e);n&&(t.timing=n),t.outputSeconds=xe(e)}function je(t,e){oa(t,e),ia(t,e)}async function un(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 Po(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 aa(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 on=class extends Error{};function ua(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 on(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function la(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:ua(n.role,n.content)})}return e}function $n(t){return We(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 da(t,e,n,r,o,s,i){let a=ct(s.id),u=t.stream===!0;if(s.model=oe(t),s.stream=u,await un(s,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:s})}catch(h){if(h instanceof F){it(r,"openai",h);return}if(h instanceof ce){H(r,h.status,h.message);return}if(h instanceof me||h instanceof ae){r.setHeader("retry-after","2"),H(r,503,h.message,"capacity_error");return}throw h}Ln(r);for await(let h of g.events){if(h.type==="error"){s.streamError=!0;let _=h.error,v=be(_),E=v??ye(s.id);v===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(h)}`),r.write(`event: error
|
|
25
|
+
data: ${JSON.stringify({error:{message:E,type:_?.type??"upstream_error",code:_?.code??null}})}
|
|
26
|
+
|
|
27
|
+
`),r.end();return}h.type==="response.completed"&&je(s,h.response),r.write(`event: ${String(h.type??"message")}
|
|
28
|
+
data: ${JSON.stringify(h)}
|
|
25
29
|
|
|
26
30
|
`)}r.write(`data: [DONE]
|
|
27
31
|
|
|
28
|
-
`),r.end();return}let l;try{l=
|
|
32
|
+
`),r.end();return}let l;try{l=Ye(n,t)}catch(g){if(g instanceof ce){H(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 d=t.store!==!1,c=oe(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await pn(e,t,l,!1,de(s))}catch(g){if(g instanceof F){it(r,"openai",g);return}if(g instanceof ce){H(r,g.status,g.message);return}if(g instanceof me||g instanceof ae){r.setHeader("retry-after","2"),H(r,503,g.message,"capacity_error");return}throw g}let f=[],k=null;for await(let g of o.track(m,c,s)){if(f.push(g),g.type==="error"){Nn(r,g,{inferenceId:s.id,operatorError:i});return}g.type==="response.completed"&&(k=g.response)}if(k==null){H(r,502,"upstream produced no response.completed event","upstream_error");return}je(s,k);let R=ze(f,k),y=Ne(p,We(k).length,R);if(y){H(r,502,Le(c,y),"upstream_error");return}d&&n.remember(a,l,cn(k,R),d),ne(r,200,{...k,id:a})}async function ca(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){H(n,400,"chat/completions requires a messages array");return}let u;try{u=Or(s,t)}catch(x){if(x instanceof ie){H(n,x.status,x.message);return}throw x}let l=String(t.model??"urun"),d=cr(o.id),c;try{c=la(a)}catch(x){if(x instanceof on){H(n,400,x.message);return}throw x}let p=oe(t);r.model(p),o.model=p,o.stream=t.stream===!0,await un(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:c,stream:!0,tools:aa(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){it(n,"openai",x);return}if(x instanceof me||x instanceof ae){n.setHeader("retry-after","2"),H(n,503,x.message,"capacity_error");return}throw x}if(t.stream===!0){u?ta(n):Ln(n);let x=[],I=new Ee,w="",C=u?new tt(u,D=>{n.write(`data: ${JSON.stringify(Be(d,l,{content:D},null))}
|
|
29
33
|
|
|
30
|
-
`)}):null,
|
|
34
|
+
`)}):null,q=D=>{C?.flush(),n.write(D),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}})}
|
|
31
35
|
|
|
32
|
-
`),n.write(`data: ${JSON.stringify(
|
|
36
|
+
`),n.write(`data: ${JSON.stringify(Be(d,l,{role:"assistant"},null))}
|
|
33
37
|
|
|
34
|
-
`);for await(let
|
|
38
|
+
`);for await(let Y of r.track(f,p,o)){x.push(Y);let re=Ke(Y);if(Y.type==="response.output_text.delta"&&typeof Y.delta=="string")w+=Y.delta,C?C.push(Y.delta):n.write(`data: ${JSON.stringify(Be(d,l,{content:Y.delta},null))}
|
|
35
39
|
|
|
36
|
-
`);else if(
|
|
40
|
+
`);else if(Y.type==="response.reasoning_text.delta"&&typeof Y.delta=="string")(!u||u.includeReasoning)&&n.write(`data: ${JSON.stringify(Be(d,l,{reasoning_content:Y.delta},null))}
|
|
37
41
|
|
|
38
|
-
`);else if(
|
|
42
|
+
`);else if(re){C?.flush();let{call:M,isNew:B}=I.add(re),J=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(Be(d,l,{tool_calls:[J]},null))}
|
|
39
43
|
|
|
40
|
-
`)}else if(
|
|
44
|
+
`)}else if(Y.type==="error"){o.streamError=!0;let M=Y.error??{},B=be(M),J=B??ye(o.id);B===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(Y)}`),q(`data: ${JSON.stringify({error:{message:J,type:M.type??"upstream_error",code:M.code??null}})}
|
|
41
45
|
|
|
42
|
-
`);return}}let
|
|
46
|
+
`);return}}let D=$n(we(x)),K=Ne(m,I.size+D.length,w);if(K){o.streamError=!0,q(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Le(p,K)}})}
|
|
43
47
|
|
|
44
|
-
`);return}C?.flush(),
|
|
48
|
+
`);return}C?.flush(),I.size===0&&D.length>0&&n.write(`data: ${JSON.stringify(Be(d,l,{tool_calls:D},null))}
|
|
45
49
|
|
|
46
|
-
`);let
|
|
50
|
+
`);let j=I.size>0||D.length>0;n.write(`data: ${JSON.stringify(Be(d,l,{},j?"tool_calls":"stop"))}
|
|
47
51
|
|
|
48
|
-
`);let
|
|
52
|
+
`);let Ae=rn(we(x));je(o,we(x)),Ae&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:Io(we(x))})}
|
|
49
53
|
|
|
50
54
|
`),n.write(`data: [DONE]
|
|
51
55
|
|
|
52
|
-
`),n.end();return}finally{C?.flush(),C?.dispose()}}let k="",
|
|
53
|
-
data: ${JSON.stringify({type:
|
|
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=Ke(x);if(I&&g.add(I),x.type==="error"){Nn(n,x,{inferenceId:o.id,operatorError:i});return}}let h=we(y);je(o,h);let _=$n(h),v=_.length>0?_:$n({output:g.items()}),E=Ne(m,v.length,k);if(E){H(n,502,Le(p,E),"upstream_error");return}let b=v.map(({index:x,...I})=>I),A={role:"assistant",content:k||null},T=R||Po(h);T&&(A.reasoning_content=T),b.length>0&&(A.tool_calls=b),ne(n,200,{id:d,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:Io(h)})}var Co="sense-latest";async function pa(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){H(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:Co,a=oe({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){H(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){H(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){H(n,400,"systemone media, when present, must be an array");return}let l=await $o(t,i,a,e,n,r,o,s);l!==null&&ne(n,200,l.answer)}async function $o(t,e,n,r,o,s,i,a){let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=u;let l=performance.now();s.model(n),await un(i,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},de(i))}catch(y){if(y instanceof F)return it(o,"openai",y),null;if(y instanceof me||y instanceof ae)return o.setHeader("retry-after","2"),H(o,503,y.message,"capacity_error"),null;throw y}u.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let y of s.track(d,n,i))if(m===null&&(m=performance.now(),u.first_event_ms=Math.round(m-c)),p.push(y),y.type==="error")return Nn(o,y,{inferenceId:i.id,operatorError:a}),null}catch(y){if(y instanceof F)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),it(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"),H(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 H(o,502,"upstream produced no response.completed event","upstream_error"),null;je(i,f);let k=ze(p,f),R;try{R=JSON.parse(k)}catch{return H(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(R===null||typeof R!="object"||Array.isArray(R))return H(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 fa(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){H(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:Co,a=oe({model:i});o.model=a,o.stream=!1;let u;try{u=$r(t,i)}catch(p){if(p instanceof $){H(n,400,p.message);return}throw p}let l=await $o(u.systemone,i,a,e,n,r,o,s);if(l===null)return;let d;try{d=Nr(u.specs,l.answer)}catch(p){if(p instanceof pe){H(n,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;ne(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function ma(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 sn(t){return new At(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function ha(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 ga(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 ya(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw sn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw sn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function _a(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 sn(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:ya(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw sn(a)}}return s(),r}function Mn(t){return We(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 wa(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){_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=pr(o.id),l=[],d;try{t.system&&l.push({role:"system",content:ma(t.system)});for(let A of i)l.push(..._a(A));d=ga(t.tool_choice)}catch(A){if(A instanceof At){_e(n,400,"invalid_request_error",A.message);return}throw A}let c=oe(t);r.model(c),o.model=c,o.stream=t.stream===!0,await un(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:ha(t.tools),tool_choice:d,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){it(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})}
|
|
54
58
|
|
|
55
|
-
`)};if(t.stream===!0){let R=r.track(h,c,o);Tn(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,S="",A=0,_="none",C=()=>_,F=-1,U=-1,W=new xe,q=[],ke=()=>{_!=="none"&&(_="none",f("content_block_stop",{index:F}))},z=(H,Y)=>{ke(),_=H,F=A++,f("content_block_start",{index:F,content_block:Y})};for await(let H of R){if(n.destroyed)break;q.push(H);let Y=Ge(H);if(H.type==="response.reasoning_text.delta"&&typeof H.delta=="string")C()!=="thinking"&&z("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:F,delta:{type:"thinking_delta",thinking:H.delta}});else if(H.type==="response.output_text.delta"&&typeof H.delta=="string")C()!=="text"&&z("text",{type:"text",text:""}),T+=1,S+=H.delta,f("content_block_delta",{index:F,delta:{type:"text_delta",text:H.delta}});else if(Y){let{call:le}=W.add(Y);(C()!=="tool"||Y.tool_index!==U)&&(U=Y.tool_index,z("tool",{type:"tool_use",id:le.id??`call_${Y.tool_index}`,name:le.name??"",input:{}})),Y.delta&&f("content_block_delta",{index:F,delta:{type:"input_json_delta",partial_json:Y.delta}})}else if(H.type==="error"){o.streamError=!0;let le=H.error,Ie=_e(le);Ie===null&&i(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(H)}`),f("error",{error:{type:"api_error",message:Ie??me(o.id)}}),n.end();return}}if(n.destroyed)return;let te=he(q),M=Ve(te),B=Me(p,W.size+M.length,S);if(B){o.streamError=!0,f("error",{error:{type:"api_error",message:Ce(c,B)}}),n.end();return}ke();let j=[];if(W.size===0)try{j=In(te)}catch(H){o.streamError=!0;let Y=se(H,{inferenceId:o.id});Y.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(H instanceof Error?H.message:H)}`),f("error",{error:{type:"api_error",message:Y.message}}),n.end();return}A===0&&j.length===0&&(z("text",{type:"text",text:""}),ke()),j.forEach(H=>{let Y=A++;f("content_block_start",{index:Y,content_block:{...H,input:{}}}),f("content_block_delta",{index:Y,delta:{type:"input_json_delta",partial_json:JSON.stringify(H.input??{})}}),f("content_block_stop",{index:Y})});let Ee=W.size>0||j.length>0,Be=Xt(te);Fe(o,te),f("message_delta",{delta:{stop_reason:Ee?"tool_use":"end_turn"},usage:Be?{input_tokens:Be.input_tokens,output_tokens:Be.output_tokens}:{output_tokens:T}}),f("message_stop",{}),n.end();return}let k="",P="",x=[],m=new xe;for await(let R of r.track(h,c,o)){x.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(k+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(P+=R.delta);let T=Ge(R);if(T&&m.add(T),R.type==="error"){let S=R.error,A=S?.type==="invalid_request_error",_=_e(S);_===null&&i(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(R)}`),ge(n,A?400:502,A?"invalid_request_error":"api_error",_??me(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let g=he(x);Fe(o,g);let y;try{y=In(g),y.length===0&&m.size>0&&(y=In({output:m.items()}))}catch(R){let T=se(R,{inferenceId:o.id});T.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(R instanceof Error?R.message:R)}`),ge(n,502,"api_error",T.message);return}let w=Me(p,y.length,k);if(w){ge(n,502,"api_error",Ce(c,w));return}let E=[],v=P||bo(g);v&&E.push({type:"thinking",thinking:v}),(k||y.length===0)&&E.push({type:"text",text:k}),E.push(...y),ee(n,200,{id:u,type:"message",role:"assistant",content:E,model:a,stop_reason:y.length>0?"tool_use":"end_turn",usage:Xt(g)??{input_tokens:0,output_tokens:0}})}function ta(t){Le(process.stdout,t)}function na(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,i=typeof e=="function"?e:()=>e,s=t.requestLog??ta,a=t.operatorLog??(d=>console.error(d)),u=t.observe,l=new Oe;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),h=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),f=(g,y,w,E,v)=>h?ge(c,g,E,y):J(c,g,y,w,v),k=rn(p.pathname),P=p.pathname.startsWith("/partners/"),x=k||P?{id:st(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;x&&(c.setHeader(rr,x.id),c.once("close",()=>{let g=ar({turn:x,method:d.method??"",path:p.pathname,res:c});s(ur(g)),u?.(g),ho({record:g,ledger:t.ledger??null,req:d})}));let m=()=>or(p.pathname,x);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){ee(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){ee(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){f(401,"invalid local proxy api key","authentication_error","authentication_error");return}let g=p.pathname===io?"canonical":p.pathname===An?"huggingface":null;if(g){if(d.method!=="POST"){f(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let v=t.usage;if(!v){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 R=v.authorize(d),T;try{T=await yo(d,so)}catch(_){if(_ instanceof bt){f(413,_.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let S=_=>v.lookup(R,_),A;try{if(g==="canonical"){let _=ao(T),C=await S(_);Yt(C,_),A={requests:C}}else A=await uo(T,S)}catch(_){if(_ instanceof Ae){f(_.status,_.message,"invalid_request_error","invalid_request_error");return}throw _}ee(c,200,A);return}if(d.method==="GET"&&p.pathname===ot){let v=await i(d);if(x&&(x.org=v.tenant??null),!v.openRouterModels){f(501,`GET ${ot} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ee(c,200,await v.openRouterModels());return}if(p.pathname.startsWith("/partners/")){f(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${An} and GET ${ot}`,"invalid_request_error","not_found_error");return}let y=await i(d);if(x&&(x.org=y.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:ot}),c.end();return}ee(c,200,await y.listModels());return}if(d.method==="GET"&&p.pathname===Tr){if(!y.listImageModels){f(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ee(c,200,await y.listImageModels());return}if(Ir(p.pathname)){if(!y.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 v={clients:y,imageModels:y.supportsImages,stats:l,turn:m(),operatorLog:a};p.pathname===Gt?await Fr(d,c,v):await Dr(d,c,v);return}if(d.method==="GET"&&p.pathname===eo){if(!y.listSpeechToTextModels){f(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ee(c,200,await y.listSpeechToTextModels());return}if(Zr(p.pathname)){if(!y.supportsTranscription){f(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${zt}`,"not_implemented","not_implemented_error");return}let v={clients:y,transcriptionModels:y.supportsTranscription,stats:l,turn:m(),operatorLog:a};await ro(d,c,v);return}if(Kr(p.pathname)){if(!y.supportsSpeech){f(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${ht}`,"not_implemented","not_implemented_error");return}let v={clients:y,speechModels:y.supportsSpeech,stats:l,turn:m(),operatorLog:a};await Qr(d,c,v);return}if(d.method!=="POST"){f(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let w;try{w=await yo(d)}catch(v){if(v instanceof bt){f(413,v.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(w));if(p.pathname==="/v1/responses"){l.request("responses",E,E),await Gs(w,y,ut(y),c,l,m(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",E,E),await Js(w,y,c,l,m(),d.headers[_n],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",E,E),await Ks(w,y,c,l,m(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",E,E),await ea(w,y,c,l,m(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",E,E),ge(c,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(g=>{let y=String(g instanceof Error?g.message:g);if(!c.headersSent){let v=o?.(g)??null;if(v){v.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${v.operatorDetail}`),f(v.status,y,v.openaiType,v.anthropicType,v.code);return}if(g instanceof en.SessionAllocationError){let T=$t(g.code);if(T){let S=g.retryAfterSeconds??(T.status===429?30:void 0);S!==void 0&&c.setHeader("Retry-After",String(S)),f(T.status,lt(T,g.code??void 0),T.openaiType,T.anthropicType,T.code);return}}if(g instanceof en.SessionFailedError){let T=Lt(g);if(T){let S=T.status===429?30:void 0;S!==void 0&&c.setHeader("Retry-After",String(S)),f(T.status,lt(T,g.status.sessionId?`session ${g.status.sessionId}`:void 0),T.openaiType,T.anthropicType,T.code);return}}if(g instanceof et){f(502,y,"upstream_error","api_error");return}if(g instanceof $e){g.retryable&&c.setHeader("Retry-After","1");let T=se(g,{inferenceId:x?.id??null});T.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}`:pe(g)}`),f(502,T.message,"upstream_error","api_error",g.code);return}if(g instanceof Ke){c.setHeader("Retry-After",String(g.retryAfterSeconds)),f(g.status,y,g.status===429?"capacity_error":"upstream_error",g.status===429?"rate_limit_error":"overloaded_error",g.code);return}let R=se(g,{inferenceId:x?.id??null});R.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:pe(g)}`),f(500,R.message,"proxy_error","api_error","proxy_error");return}x&&(x.streamError=!0);let w=g instanceof $e?g.code:null,E=se(g,{inferenceId:x?.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: ${g instanceof Error?`${g.name}: ${g.message}`:pe(g)}`),c.destroyed||(h?c.write(`event: error
|
|
59
|
+
`)};if(t.stream===!0){let A=r.track(m,c,o);Ln(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,K=new Ee,j=[],Ae=()=>{w!=="none"&&(w="none",f("content_block_stop",{index:q}))},Y=(V,X)=>{Ae(),w=V,q=I++,f("content_block_start",{index:q,content_block:X})};for await(let V of A){if(n.destroyed)break;j.push(V);let X=Ke(V);if(V.type==="response.reasoning_text.delta"&&typeof V.delta=="string")C()!=="thinking"&&Y("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:q,delta:{type:"thinking_delta",thinking:V.delta}});else if(V.type==="response.output_text.delta"&&typeof V.delta=="string")C()!=="text"&&Y("text",{type:"text",text:""}),T+=1,x+=V.delta,f("content_block_delta",{index:q,delta:{type:"text_delta",text:V.delta}});else if(X){let{call:fe}=K.add(X);(C()!=="tool"||X.tool_index!==D)&&(D=X.tool_index,Y("tool",{type:"tool_use",id:fe.id??`call_${X.tool_index}`,name:fe.name??"",input:{}})),X.delta&&f("content_block_delta",{index:q,delta:{type:"input_json_delta",partial_json:X.delta}})}else if(V.type==="error"){o.streamError=!0;let fe=V.error,Pe=be(fe);Pe===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(V)}`),f("error",{error:{type:"api_error",message:Pe??ye(o.id)}}),n.end();return}}if(n.destroyed)return;let re=we(j),M=We(re),B=Ne(p,K.size+M.length,x);if(B){o.streamError=!0,f("error",{error:{type:"api_error",message:Le(c,B)}}),n.end();return}Ae();let J=[];if(K.size===0)try{J=Mn(re)}catch(V){o.streamError=!0;let X=ue(V,{inferenceId:o.id});X.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(V instanceof Error?V.message:V)}`),f("error",{error:{type:"api_error",message:X.message}}),n.end();return}I===0&&J.length===0&&(Y("text",{type:"text",text:""}),Ae()),J.forEach(V=>{let X=I++;f("content_block_start",{index:X,content_block:{...V,input:{}}}),f("content_block_delta",{index:X,delta:{type:"input_json_delta",partial_json:JSON.stringify(V.input??{})}}),f("content_block_stop",{index:X})});let Te=K.size>0||J.length>0,He=rn(re);je(o,re),f("message_delta",{delta:{stop_reason:Te?"tool_use":"end_turn"},usage:He?{input_tokens:He.input_tokens,output_tokens:He.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,c,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=Ke(A);if(T&&g.add(T),A.type==="error"){let x=A.error,I=x?.type==="invalid_request_error",w=be(x);w===null&&s(`[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);je(o,h);let _;try{_=Mn(h),_.length===0&&g.size>0&&(_=Mn({output:g.items()}))}catch(A){let T=ue(A,{inferenceId:o.id});T.redacted&&s(`[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(c,v));return}let E=[],b=R||Po(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:rn(h)??{input_tokens:0,output_tokens:0}})}function va(t){De(process.stdout,t)}function ba(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??va,a=t.operatorLog??(d=>console.error(d)),u=t.observe,l=new $e;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),f=(h,_,v,E,b)=>m?_e(c,h,E,_):H(c,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&&(c.setHeader(lr,y.id),c.once("close",()=>{let h=fr({turn:y,method:d.method??"",path:p.pathname,res:c});i(mr(h)),u?.(h),Ao({record:h,ledger:t.ledger??null,req:d})}));let g=()=>dr(p.pathname,y);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){ne(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){ne(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){f(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=p.pathname===go?"canonical":p.pathname===Cn?"huggingface":null;if(h){if(d.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(d),T;try{T=await Eo(d,yo)}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=_o(T),C=await x(w);nn(C,w),I={requests:C}}else I=await wo(T,x)}catch(w){if(w instanceof Oe){f(w.status,w.message,"invalid_request_error","invalid_request_error");return}throw w}ne(c,200,I);return}if(d.method==="GET"&&p.pathname===ut){let b=await s(d);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(c,200,await b.openRouterModels());return}if(p.pathname.startsWith("/partners/")){f(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Cn} and GET ${ut}`,"invalid_request_error","not_found_error");return}let _=await s(d);if(y&&(y.org=_.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:ut}),c.end();return}ne(c,200,await _.listModels());return}if(d.method==="GET"&&p.pathname===Fr){if(!_.listImageModels){f(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ne(c,200,await _.listImageModels());return}if(Dr(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===Xt?await zr(d,c,b):await Kr(d,c,b);return}if(d.method==="GET"&&p.pathname===co){if(!_.listSpeechToTextModels){f(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ne(c,200,await _.listSpeechToTextModels());return}if(lo(p.pathname)){if(!_.supportsTranscription){f(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${tn}`,"not_implemented","not_implemented_error");return}let b={clients:_,transcriptionModels:_.supportsTranscription,stats:l,turn:g(),operatorLog:a};await mo(d,c,b);return}if(oo(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 uo(d,c,b);return}if(d.method!=="POST"){f(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let v;try{v=await Eo(d)}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 da(v,_,pt(_),c,l,g(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",E,E),await ca(v,_,c,l,g(),d.headers[xn],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",E,E),await pa(v,_,c,l,g(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",E,E),await fa(v,_,c,l,g(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",E,E),await wa(v,_,c,l,g(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",E,E),_e(c,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(!c.headersSent){let b=o?.(h)??null;if(b){b.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.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 an.SessionAllocationError){let T=Dt(h.code);if(T){let x=h.retryAfterSeconds??(T.status===429?30:void 0);x!==void 0&&c.setHeader("Retry-After",String(x)),f(T.status,mt(T,h.code??void 0),T.openaiType,T.anthropicType,T.code);return}}if(h instanceof an.SessionFailedError){let T=Ft(h);if(T){let x=T.status===429?30:void 0;x!==void 0&&c.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&&c.setHeader("Retry-After","1");let T=ue(h,{inferenceId:y?.id??null});T.redacted&&a(`[caller-message-boundary] ${d.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 Xe){c.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] ${d.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)}`),c.destroyed||(m?c.write(`event: error
|
|
56
60
|
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:E.message}})}
|
|
57
61
|
|
|
58
|
-
`):c.write(`data: ${JSON.stringify({error:{message:E.message,type:"upstream_error",code:
|
|
62
|
+
`):c.write(`data: ${JSON.stringify({error:{message:E.message,type:"upstream_error",code:v}})}
|
|
59
63
|
|
|
60
|
-
`)),c.end()})}}function
|
|
64
|
+
`)),c.end()})}}function Mo(t){let{clients:e,apiKey:n}=t,r=(0,Oo.createServer)(ba(t)),o=vr(r,{clients:e,apiKey:n,statusOf:t.statusOf,operatorLog:t.operatorLog}),s=yt(r,{resolver:Gt(e,n,t.realtimeCompanions),operatorLog:t.operatorLog}),i=r.close.bind(r);return r.close=(a=>(o.close(),s(),i(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});
|