@urun-sh/openai 0.6.38 → 0.6.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-B26FENQ3.js → chunk-BWYY4IPR.js} +1 -1
- package/dist/chunk-G5VRFFBE.js +64 -0
- package/dist/chunk-G7CSAISC.js +1 -0
- package/dist/{chunk-7AI75MPZ.js → chunk-HPUX2H65.js} +6 -6
- package/dist/{chunk-5MH6NSR2.js → chunk-L4QBHSVY.js} +1 -1
- package/dist/chunk-L6CT7ZVO.js +23 -0
- package/dist/chunk-PT5N7AY7.js +2 -0
- package/dist/{chunk-3JWYIKHM.js → chunk-QTHFMDZY.js} +1 -1
- package/dist/chunk-Z3QCHKJB.js +1 -0
- package/dist/{composite-ClDE3ViI.d.ts → composite-B--rGI5m.d.ts} +8 -2
- package/dist/{composite-F94H40CD.d.cts → composite-B-F2J0NK.d.cts} +40 -2
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +2 -2
- package/dist/gemini-live.d.ts +2 -2
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +48 -48
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +46 -46
- package/dist/hosted/index.d.cts +3 -3
- package/dist/hosted/index.d.ts +3 -3
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +55 -55
- package/dist/pooler/bin.cjs +7 -7
- package/dist/pooler/bin.js +25 -25
- package/dist/proxy/cli.cjs +51 -51
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +26 -26
- package/dist/proxy/index.d.cts +35 -5
- package/dist/proxy/index.d.ts +11 -5
- package/dist/proxy/index.js +1 -1
- package/dist/{translator-Ddd65sXR.d.ts → translator-BqpmZ-vh.d.ts} +1 -1
- package/dist/{translator-CO8W_hmJ.d.cts → translator-Dox25ky9.d.cts} +1 -1
- package/dist/{video-out-BsuLqlID.d.cts → video-out-DnCKUUO2.d.cts} +13 -0
- package/dist/{video-out-Cawtm7SF.d.ts → video-out-REmiQMBJ.d.ts} +7 -0
- package/package.json +3 -3
- package/dist/chunk-6M5JK4YC.js +0 -1
- package/dist/chunk-UQV3ZXCW.js +0 -2
- package/dist/chunk-YOFTYCYH.js +0 -64
- package/dist/chunk-ZA2LMA3I.js +0 -23
package/dist/proxy/index.cjs
CHANGED
|
@@ -1,64 +1,64 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}var Wo={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 Ko={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},zo=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Se],jn=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Yo(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 Xo=["temperature","maxOutputTokens","responseModalities"];function Kn(t){for(let[c,p]of Object.entries(Ko))if(t[c]!==void 0)throw new S(p);for(let c of Object.keys(t))if(!zo.includes(c))throw new S(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new S('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,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(!Xo.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?Wo:Yo(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,Qo=`audio/pcm;rate=${Qn}`,Zn=Buffer.alloc(960).toString("base64");function Zo(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 es(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 ts(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=Zo(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:ts(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:es(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:Qo,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 ns=256,Ve=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>ns;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},rs="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 os(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=os(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:rs}}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
|
|
1
|
+
"use strict";var No=Object.create;var Et=Object.defineProperty;var Uo=Object.getOwnPropertyDescriptor;var Do=Object.getOwnPropertyNames;var Fo=Object.getPrototypeOf,qo=Object.prototype.hasOwnProperty;var Bo=(t,e)=>{for(var n in e)Et(t,n,{get:e[n],enumerable:!0})},qn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Do(e))!qo.call(t,o)&&o!==n&&Et(t,o,{get:()=>e[o],enumerable:!(r=Uo(e,o))||r.enumerable});return t};var Bn=(t,e,n)=>(n=t!=null?No(Fo(t)):{},qn(e||!t||!t.__esModule?Et(n,"default",{value:t,enumerable:!0}):n,t)),jo=t=>qn(Et({},"__esModule",{value:!0}),t);var xa={};Bo(xa,{GEMINI_LIVE_PATH:()=>$t,OPENAI_REALTIME_PATH:()=>gt,OpenAIRealtimeConnection:()=>qe,ResumptionRegistry:()=>Ge,SessionGoneError:()=>Y,UnknownModelError:()=>F,VIDEO_OUT_SETUP_KEY:()=>Se,attachGeminiLive:()=>Nt,attachOpenAIRealtime:()=>yt,createOpenAIProxy:()=>Lo,fixedClientsResolver:()=>Gt,realtimeBindingFor:()=>On,realtimeModelOf:()=>In,serveGeminiLiveSocket:()=>ur});module.exports=jo(xa);var To=require("http");var sr=require("crypto"),ar=require("ws");var Go=require("crypto");var at=class extends Error{};var ut="/partners/openrouter/models";var It=class extends Error{name="ModelCreatedError"};var F=class extends Error{},Y=class extends Error{};var dn=256e3;var Ot=require("@urun-sh/core");var jn="urun.videoOut.v2-ws";var $t="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Wo=1007,Jn=1008,ke=1011,Mt=1008,S=class extends Error{constructor(n,r=Wo){super(n);this.closeCode=r}closeCode},Z=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Tt=["setup","clientContent","realtimeInput","toolResponse"];function Vn(t){let e;try{e=JSON.parse(t)}catch{throw new S("client message is not valid JSON")}let n=Z(e);if(!n)throw new S("client message must be a JSON object");let r=Tt.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Tt.includes(a));if(o.length>0)throw new S(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Tt.join(", ")}`);if(r.length!==1)throw new S(`client message must contain exactly one of ${Tt.join(", ")} (got ${r.length})`);let i=r[0],s=Z(n[i]);if(!s)throw new S(`"${i}" must be a JSON object`);return{kind:i,[i]:s}}function Gn(t,e){if(typeof t=="string")return t;let n=Z(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new S(`${e}: expected a Content with a parts array`);let o=[];for(let i of r){let s=Z(i);if(s&&typeof s.text=="string"){o.push(s.text);continue}throw s&&(s.inlineData!==void 0||s.fileData!==void 0)?new S(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):s&&(s.functionCall!==void 0||s.functionResponse!==void 0)?new S(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new S(`${e}: unsupported part ${JSON.stringify(i)}`)}return o.join(`
|
|
2
|
+
`)}var Ko={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Se="urun.videoOut";function Wn(t){return{framing:jn,codec:t}}function Kn(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Se]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var zo={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Yo=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Se],Hn=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Xo(t){let e=Z(t);if(!e)throw new S("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new S(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=Z(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new S("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new S(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new S("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!Hn.includes(e.activityHandling))throw new S(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Hn.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Qo=["temperature","maxOutputTokens","responseModalities"];function zn(t){for(let[c,p]of Object.entries(zo))if(t[c]!==void 0)throw new S(p);for(let c of Object.keys(t))if(!Yo.includes(c))throw new S(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new S('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,i=Z(t.generationConfig);if(t.generationConfig!==void 0&&!i)throw new S("setup.generationConfig must be an object");if(i){for(let c of Object.keys(i))if(!Qo.includes(c))throw new S(`unsupported generationConfig field "${c}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new S("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new S("generationConfig.maxOutputTokens must be a number");r=i.maxOutputTokens}if(i.responseModalities!==void 0){let c=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let p of c){let m=String(p).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="TEXT")throw new S(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let s=[];t.systemInstruction!==void 0&&s.push({role:"system",content:Gn(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new S("setup.tools must be an array");a=[];for(let c of t.tools){let p=Z(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=Z(m);if(!f||typeof f.name!="string")throw new S("functionDeclarations entries require a string name");a.push({type:"function",name:f.name,description:f.description,parameters:f.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=Z(t.sessionResumption);if(!c)throw new S("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new S(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new S("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let l=t.realtimeInputConfig===void 0?Ko:Xo(t.realtimeInputConfig),d=!1;if(t[Se]!==void 0){if(!Z(t[Se]))throw new S(`setup["${Se}"] 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 Yn(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Xn(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Qn(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new S(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new S("clientContent.turns must be an array");let n=[];for(let r of e){let o=Z(r);if(!o)throw new S("clientContent.turns entries must be Content objects");let i=o.role===void 0?"user":String(o.role).toLowerCase();if(i!=="user"&&i!=="model")throw new S(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:i==="model"?"assistant":"user",content:Gn(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Pt=16e3,Zn=24e3,Zo=`audio/pcm;rate=${Zn}`,er=Buffer.alloc(960).toString("base64");function ei(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),i=e/n,s=t.length-1;for(let a=0;a<r;a++){let u=a*i,l=Math.floor(u);if(l>=s){o[a]=t[s];continue}let d=u-l;o[a]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function ti(t){let e=Z(t);if(!e)throw new S("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new S(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new S("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new S("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function ni(t){let e=Z(t);if(!e)throw new S("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new S(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==Pt)throw new S(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Pt} Hz (audio/pcm;rate=${Pt})`);if(typeof e.data!="string"||e.data.length===0)throw new S("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new S(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let s=0;s<o.length;s++)o[s]=r.readInt16LE(s*2);let i=ei(o,Pt,Zn);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function tr(t){if(t.mediaChunks!==void 0)throw new S('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new S("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",i=Z(t[o]);if(!i||Object.keys(i).length!==0)throw new S(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new S(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new S(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:ni(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:ti(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new S("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new S("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function nr(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new S(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new S("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=Z(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new S("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function rr(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function or(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Zo,data:t}}]}}}}function ir(t){let e=Z(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],i=typeof e.output_text=="string"?e.output_text:"";if(!i)for(let l of n){let d=Z(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=Z(c);p?.type==="output_text"&&typeof p.text=="string"&&(i+=p.text)}}i&&o.push({role:"assistant",content:i});for(let l of n){let d=Z(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new S(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,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 s=[];r.length>0&&s.push({toolCall:{functionCalls:r}}),s.push({serverContent:{generationComplete:!0}});let a=Z(e.usage),u={serverContent:{turnComplete:!0}};if(a){let l={};typeof a.input_tokens=="number"&&(l.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(l.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(l.totalTokenCount=a.total_tokens),Object.keys(l).length>0&&(u.usageMetadata=l)}return s.push(u),{messages:s,assistantItems:o}}var ri=256,Ge=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>ri;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},oi="local",lt=t=>t.slice(0,120),Lt=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof F){this.ws.close(Jn,lt(e.message));return}if(e instanceof Y){this.ws.close(Mt,lt(e.message));return}if(e instanceof S){this.ws.close(e.closeCode,lt(e.message));return}this.ws.close(ke,lt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Vn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new S(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:i}=Qn(n.clientContent);this.transcript.push(...o),i&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=tr(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:er);return}this.transcript.push(...nr(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new S("setup may only be sent once, as the first client message");let n=zn(e),r=n.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new S("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Mt);if(i.model!==n.model)throw new S(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new S("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==i.proxyHandle)throw new S(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Mt);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let i=this.clients.openVideoOut;if(i){let s=await i.call(this.clients,n.model),a=s.onOutputFrame(l=>this.send(Kn(l))),u=s.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[Se]=Wn(s.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new S("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new S("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",ke);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(or(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new S("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new S("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",ke);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new S(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new S("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new S("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,sr.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Yn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Xn(e.timeLeftMs)),this.ws.close(ke,lt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,i=!1;for await(let u of r){if(n.interrupted)break;let l=u;if(l.type==="error")throw new S(`upstream error: ${JSON.stringify(l)}`,ke);if(l.type==="response.completed"){o=l.response,i=!0;continue}let d=rr(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new S("upstream produced no response.completed event",ke);let{messages:s,assistantItems:a}=ir(o);this.transcript.push(...a);for(let u of s)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ce=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function ii(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let i=t.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let s=e.searchParams.get("key")??void 0;if(s!==void 0&&s!==""&&r.add(s),r.size>1)throw new Ce(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&s!==void 0&&s!=="")throw new Ce(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new Ce(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Nt(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new ar.WebSocketServer({noServer:!0}),o=new Ge;t.on("upgrade",(s,a,u)=>{let l=new URL(s.url??"/","http://localhost");l.pathname===$t&&(a.on("error",()=>{}),(async()=>{let d=ii(s,l,n),c;if(e.authenticate)c=await e.authenticate(d,s);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Ce(401,"invalid local proxy api key");c={clients:e.clients,scope:oi}}r.handleUpgrade(s,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
5
|
${m}\r
|
|
6
|
-
`),a.destroy())}))});let
|
|
7
|
-
`}var ss=256,is=128;function oe(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,is)}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>=ss?"(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}}}},as=256;function us(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=us(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<=as)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},gr=new WeakMap;function pt(t){let e=gr.get(t);return e||(e=new Ge,gr.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}))}},ls=["<tool_call>","<function="];function ds(t){return ls.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 ds(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 cs(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=cs(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 hr(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}:{},...hr(e)!==void 0?{response_format:hr(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:gs({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function ps(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?ms(o[i++],u):u),...fs(r,n)]}function fs(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 ms(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*gs(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=[],h=(M,B)=>{y.push({output_index:M,item:B})},g=!1,_=0,v="",E=0,b="";function*A(){if(!g)return;g=!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},h(_,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},h(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},h(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(),g||(g=!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},h(fe,Dn)}let V=ps(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 ys=[/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 he(t){return!ys.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?he(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: ${ge(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&he(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${ge(e)}`),`the ${t} upstream failed while serving this request`)}function be(t){let e=t?.message;return typeof e=="string"&&e.length>0&&he(e)?e:null}function ge(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var _s="/v1/responses",ws=64*1024*1024,vs=8*1024*1024,bs=16,_r=32,wr=3600*1e3,Ss=/^[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 ks=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 gn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function xs(t){for(;t.bufferedAmount>vs&&t.readyState===Ie.WebSocket.OPEN;){let{promise:e,resolve:n}=gn();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"||!Ss.test(o.stream_id)){this.sendFrame(ks);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 xs(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:ge(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>=bs;){let{promise:e,resolve:n}=gn();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
|
|
6
|
+
`),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let s of r.clients)s.close(1001,"server closing");await new Promise((s,a)=>r.close(u=>u===void 0?s():a(u)))})(),i)}function ur(t,e,n=new Ge){new Lt(t,e,n)}var Ie=require("ws");var lr=require("crypto"),dr="Inference-Id";function dt(){return(0,lr.randomUUID)()}function cn(t){return t==="/v1"||t.startsWith("/v1/")}function cr(t,e){if(!cn(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function ct(t){return`resp_${t}`}function pr(t){return`chatcmpl-${t}`}function fr(t){return`msg_${t}`}function de(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function mr(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function hr(t){return`${JSON.stringify(t)}
|
|
7
|
+
`}var si=256,ai=128;function oe(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,ai)}var $e=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=si?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,i=performance.now(),s=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-i),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=s-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let u=(performance.now()-(s??i))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},ui=256;function li(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var Me=class extends Error{},We=class{conversations=new Map;thread(e,n){let r=li(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Me(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let i of this.conversations.keys()){if(this.conversations.size<=ui)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},gr=new WeakMap;function pt(t){let e=gr.get(t);return e||(e=new We,gr.set(t,e)),e}function Ke(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function we(t){return t.find(e=>e.type==="response.completed")?.response??null}function ze(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var Ee=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},di=["<tool_call>","<function="];function ci(t){return di.find(e=>t.includes(e))}function Le(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function Ne(t,e,n){if(!(!t||e>0))return ci(n)}function Ye(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function xe(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function pi(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function pn(t,e){let n=pi(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ce=class extends Error{constructor(n,r,o=400,i){super(n);this.code=r;this.status=o;this.param=i}code;status;param};function Xe(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Me?new ce(n.message,"previous_response_not_found",400,"previous_response_id"):new ce(String(n instanceof Error?n.message:n),"invalid_input")}}function yr(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function fn(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ce("instructions must be a string","invalid_instructions");let i=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...i!==void 0?{instructions:i}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...yr(e)!==void 0?{response_format:yr(e)}:{}},o)}async function ft(t){let{body:e,clients:n,store:r,stats:o}=t,i=Xe(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let s=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,l=oe(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await fn(n,e,i,!0,c?de(c):void 0);return{responseId:s,events:gi({events:p,conversation:i,responseId:s,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function fi(t,e){let n=[...t].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=n.filter(u=>u.type==="message").length===o.length,s=0;return[...n.map(u=>u.type==="message"&&i?hi(o[s++],u):u),...mi(r,n)]}function mi(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),i=e.filter(l=>l.type==="function_call"),s=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=i.length===s,u=new Set(i.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!u.has(o(d)):!0})}function hi(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(n);if(i===void 0)return e;let s={...t};return s.id=e.id,t.role===void 0&&(s.role=e.role),t.status===void 0&&(s.status=e.status),s.content=r.map(a=>n(a)?{...a,text:i.text}:a),s}async function*gi(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:i,remember:s,persist:a,store:u,stats:l}=t,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 z=new Ee,H=null,Ae=-1;function*X(M){if(!H)return;let B=H;H=null,yield{type:"response.function_call_arguments.done",item_id:B.fcId,output_index:B.outputIndex,arguments:B.args};let V={id:B.fcId,type:"function_call",call_id:B.callId??B.fcId,name:B.name??"",arguments:B.args,status:M};yield{type:"response.output_item.done",output_index:B.outputIndex,item:V},g(B.outputIndex,V)}let re=!1;for await(let M of l.track(e,o,t.turn)){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 V=f?null:ze(M);if(V){if(yield*R(),yield*A(),yield*D("completed"),z.add(V),V.tool_index!==Ae){yield*X("completed"),Ae=V.tool_index;let Te=k++;H={fcId:`fc_${r.slice(5)}_${V.tool_index}`,outputIndex:Te,callId:V.call_id,name:V.name,args:""},yield{type:"response.output_item.added",output_index:Te,item:{id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:"",status:"in_progress"}}}H&&(V.call_id&&(H.callId=V.call_id),V.name&&(H.name=V.name),H.args+=V.delta,yield{type:"response.function_call_arguments.delta",item_id:H.fcId,output_index:H.outputIndex,delta:V.delta});continue}if(B==="response.completed"&&!f){let Te=Ke(M.response),Je=Ne(i,z.size+Te.length,q);if(Je){re=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Le(o,Je)}};break}if(yield*A(),yield*D("completed"),yield*X("completed"),z.size===0)for(let Q of Te){let fe=k++,Pe=Q.id??Q.call_id??`fc_${fe}`,ln=Q.arguments??"",Dn={id:Pe,type:"function_call",call_id:Q.call_id??Pe,name:Q.name??""};yield{type:"response.output_item.added",output_index:fe,item:{...Dn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Pe,output_index:fe,delta:ln},yield{type:"response.function_call_arguments.done",item_id:Pe,output_index:fe,arguments:ln};let Fn={...Dn,arguments:ln,status:"completed"};yield{type:"response.output_item.done",output_index:fe,item:Fn},g(fe,Fn)}let G=fi(y,M.response);yield G.length>0?c({...M,response:{...M.response,output:G}}):c(M);continue}yield c(M)}if(yield*A(),yield*D("incomplete"),yield*X("incomplete"),s&&!re){let M=we(d);u.remember(r,n,pn(M,Ye(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 Qe=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}};var me=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}};var yi=require("@urun-sh/core"),Ue=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}};var _i=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ge(t){return!_i.some(e=>e.test(t))}function ye(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function ue(t,e){if(t instanceof Y)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=_r(t);return n||{message:ye(e?.inferenceId??null),redacted:!0}}function _r(t){return t instanceof It?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof at?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof F?{message:t.message,redacted:!1}:t instanceof ve?{message:t.message,redacted:!1}:t instanceof Qe?{message:t.message,redacted:!1}:t instanceof Ue?ge(t.message)?{message:t.message,redacted:!1}:null:t instanceof me?{message:t.message,redacted:!1}:t instanceof ae?{message:t.message,redacted:!1}:null}function Ze(t,e,n){let r=n??(s=>console.error(s)),o=_r(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${he(e)}`),`the ${t} upstream failed: ${o.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ge(i)?`the ${t} upstream failed: ${i}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${he(e)}`),`the ${t} upstream failed while serving this request`)}function be(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ge(e)?e:null}function he(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var wi="/v1/responses",vi=64*1024*1024,bi=8*1024*1024,Si=16,wr=32,vr=3600*1e3,ki=/^[A-Za-z0-9._-]{1,256}$/;function ie(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var xi=ie(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function gn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Ri(t){for(;t.bufferedAmount>bi&&t.readyState===Ie.WebSocket.OPEN;){let{promise:e,resolve:n}=gn();setTimeout(n,5),await e}}var mn=class extends We{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof Me))throw o;return this.shared.thread(n,r)}}remember(n,r,o,i=!0){i?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},hn=class{constructor(e,n,r,o,i){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=i;this.store=new mn(pt(n)),e.on("message",(a,u)=>this.onMessage(a,u)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ie(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${vr/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},vr).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(ie(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(ie(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(ie(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(ie(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(ie(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(ie(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!ki.test(o.stream_id)){this.sendFrame(xi);return}if(i=o.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=wr){this.sendFrame(ie(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${wr}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let s=o.generate===!1?()=>this.runWarmup(o,i):()=>this.runTurn(o,i),a=i??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(s).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=dt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let i;try{i=await ft({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:ct(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(i.responseId,n??null);let s=i.events;this.activeTurns.add(s);try{for await(let a of s){if(this.closed||this.ws.readyState!==Ie.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Ri(this.ws)}}finally{this.activeTurns.delete(s)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=dt(),o=ct(r);try{let i=Xe(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,i,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(i){this.failTurn(i,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let i=r.previous_response_id;typeof i=="string"&&this.laneOfResponse.get(i)===(n??null)&&(this.store.forget(i),this.laneOfResponse.delete(i))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:he(e);if(e instanceof ce)return ie(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof F)return ie(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof Y){let a=ue(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ie(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let i=this.statusOf?.(e)??null;if(i)return i.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${i.operatorDetail}`),ie(i.status,{type:i.openaiType,message:o},n);let s=ue(e,{inferenceId:r});return s.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ie(500,{type:"upstream_error",message:s.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,i=o?.type??"upstream_error",s=be(o),a=s??ye(r);return s===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),ie(i==="invalid_request_error"?400:502,{type:i,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=Si;){let{promise:e,resolve:n}=gn();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 vr(t,e){let n=new Ie.WebSocketServer({noServer:!0,maxPayload:ws}),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!==_s){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}=gn();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"),Rs={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},As={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=As[t.code];return e?`${n} (${e})`:n}function Dt(t){if(t==null)return null;let e=Rs[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 Es=qn(require("os"),1),Is=qn(require("path"),1),Os=require("url"),Ts=require("util");var Ps=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Cs(t){let e=t?.code;return typeof e=="string"&&Ps.has(e)}function De(t,e){try{return t.write(e),!0}catch(n){if(Cs(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,hn=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},$s={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},Ms={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ls={format:!0,voice:!0,speed:!0};function Ns(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 Us=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:Us})}function gt(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 $s));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(!Ns(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 Ms))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=gt({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=gt({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 Ls))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 Ds=1001,Fs=1011,xr=t=>t.slice(0,120),qs=/^[A-Za-z0-9+/=]*$/,Bs=2;function js(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Bs)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=gt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(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(!qs.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 h of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(h);this.inFlight=(async()=>{let h=[],g=b=>{this.responseFlushed?this.send(b):h.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 h)this.send(b);h.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")&&g({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,g({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"};g({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,g({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(js(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&&he(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: ${ge(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>hn){this.ws.close(Ds,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: ${ge(e)}`),r.message}fail(e,n){this.send(G(e)),this.ws.close(Fs,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 ht="/v1/realtime",Hs=t=>t.slice(0,120);function Js(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 br(t,e){let n=new Ie.WebSocketServer({noServer:!0,maxPayload:vi}),r=new $e,o=new Set,i=new Set,s=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(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",()=>s.delete(c)),m.pathname!==wi){s.add(c);return}i.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=>{i.delete(c),o.add(R),R.on("close",()=>o.delete(R));try{new hn(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(()=>i.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=gn();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let m of i)m.destroy();i.clear();for(let m of s)m.destroy();s.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==Ie.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var kn=require("@urun-sh/core");var Sr=require("@urun-sh/core"),Ai={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Ei={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function mt(t,e){let n=Ei[t.code];return e?`${n} (${e})`:n}function Dt(t){if(t==null)return null;let e=Ai[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Ft(t){if(t.kind==="create-failed")return Dt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Sr.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Dt(e?"cold_start_exceeded":"queue_timeout")}var Ii=Bn(require("os"),1),Oi=Bn(require("path"),1),Ti=require("url"),Pi=require("util");var Ci=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function $i(t){let e=t?.code;return typeof e=="string"&&Ci.has(e)}function De(t,e){try{return t.write(e),!0}catch(n){if($i(n))return!1;throw n}}var Ir=require("ws");var Er=require("@urun-sh/core");var xr=require("crypto");function O(t){return`${t}_${(0,xr.randomUUID)().replace(/-/g,"").slice(0,24)}`}var qt=4*1024*1024,yn=8*1024*1024,Bt=512,jt=20*1024*1024;function W(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Fe(t,e){return{type:"server_error",code:t,message:e}}function j(t){return{type:"error",event_id:O("event"),error:t}}function _n(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var P=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Mi={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Li={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ni={format:!0,voice:!0,speed:!0};function Ui(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function et(t,e){if(!Array.isArray(t)||t.length===0)throw new P(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new P(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function kr(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new P(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Di=10;function wn(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Di})}function ht(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new P("session must be an object","session","invalid_request");let o=t,i=Object.keys(o).filter(a=>!(a in Mi));if(i.length>0)throw new P(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=et(o.modalities,"modalities"),u=et(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new P("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let s={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(o))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new P(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new P(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!n.turns)throw new P('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");s.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new P(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=et(u,a);for(let 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");s.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Ui(u))throw new P(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new P("model must be a string or null","model");s.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new P("instructions must be a string or null","instructions");s.instructions=wn(u??void 0)??void 0;break;case"voice":if(u===null){delete s.voice;break}if(typeof u!="string")throw new P("voice must be a string or null","voice");if(!n.voice)throw new P("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new P(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new P("temperature must be a finite number or null","temperature");s.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new P(`${a} must be a positive integer, "inf" or null`,a);s.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new P("tools must be an array","tools");s.tools=u;break;case"tool_choice":s.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new P("metadata must be an object or null","metadata");s.metadata=u??null;break;case"turn_detection":{if(u===null){s.turnDetection=null;break}if(!n.turns)throw new P("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new P("turn_detection must be an object or null","turn_detection");let 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")}s.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new P("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new P("input_audio_transcription must be an object or null","input_audio_transcription");for(let 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")}s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new P("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new P("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let 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 Li))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&kr(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=ht({input_audio_transcription:d.transcription},s,n,r);s.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=ht({turn_detection:d.turn_detection},s,n,r);s.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 Ni))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&kr(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 s.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");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function Ht(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function vn(t,e){let n=t;if(!n||typeof n!="object")throw new P("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new P("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:O("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new P('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new P("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new P("content part must be an object","item.content","invalid_request");if(s.type==="input_text"||r==="assistant"&&s.type==="output_text"){if(typeof s.text!="string")throw new P(`${String(s.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){if(!e)throw new P("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof s.audio!="string")throw new P("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}if(s.type==="input_image"){if(r!=="user")throw new P("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof s.image_url=="string"?s.image_url:s.image_url?.url;if(typeof a!="string"||a.length===0)throw new P("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new P("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof s.detail=="string"?s.detail:void 0;o.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new P(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:O("item"),type:"message",role:r,content:o}}throw new P(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Jt(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let s=i.transcript;if(typeof s=="string"&&s.trim().length>0){o.push({type:"input_text",text:s});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Fi=1001,qi=1011,Rr=t=>t.slice(0,120),Bi=/^[A-Za-z0-9+/=]*$/,ji=2;function Hi(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ji)return!1;return!0}var qe=class{id=O("conn");ws;binding;onClosed;operatorLog;config=_n();sessionId=O("sess");conversationId=O("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:O("event"),session:Ht(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:O("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof Y&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,o):this.send(j(Fe("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:O("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(i=>i.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:O("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:O("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:O("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),i=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let s=O("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:O("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:s,content_index:0,transcript:i}),this.emitItemDone(s),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(W("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>qt){this.fail(W("frame_too_large",`frame exceeds the ${qt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(W("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(W("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let i=o;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(j({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}this.fail(Fe(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=ht(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(j(W("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:O("event"),session:Ht(this.config,this.sessionId)});return}case"conversation.item.create":{let n=vn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(j(W("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:O("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(j(W("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:O("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(j(W("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:O("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(j(W("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Bi.test(e.audio)){this.send(j(W("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>jt){this.send(j(W("buffer_full",`uncommitted input audio exceeds the ${jt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:O("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(j(W("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=O("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:O("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:r,content_index:0,transcript:i}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(j(W("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(j(W("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(j(W("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(j(W("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(j({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:i,input:s,...a}=e;return await o.createResponse({...a,input:s})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(j(W("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?et(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?et(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new P("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(j(W("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let s=O("req"),a=`resp_${s}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:Jt(this.items),c=wn(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,s)}catch(I){this.upstreamTurnFault(I,a);return}try{for await(let I of x){if(this.cancelled)break;let w=I;if(w.type==="error"){let C=this.upstreamErrorBody(w);this.responseFlushed?this.send(j(C)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(a,C)});return}if(w.type==="response.output_text.delta"&&typeof w.delta=="string"){_(),v.messageOpen||(this.beginMessageItem(a,v.nextOutputIndex++),v.messageOpen=!0),this.config.outputModalities.includes("text")&&h({type:"response.output_text.delta",event_id:O("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:w.delta}),this.turnOutputIsAudio()&&(v.transcriptDelta=!0,h({type:"response.output_audio_transcript.delta",event_id:O("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:w.delta})),v.messageText+=w.delta;continue}if(w.type==="response.function_call_arguments.delta"){_();let C=typeof w.delta=="string"?w.delta:"",q=typeof w.call_id=="string"&&w.call_id.length>0?w.call_id:`${a}_fc_${v.nextOutputIndex}`,D=v.tools.get(q);if(!D){let z=typeof w.name=="string"&&w.name.length>0?w.name:void 0;D={outputIndex:v.nextOutputIndex++,name:z,args:""},v.tools.set(q,D);let H={id:q,object:"realtime.item",type:"function_call",call_id:q,name:z??"",arguments:"",status:"in_progress"};h({type:"response.output_item.added",event_id:O("event"),response_id:a,output_index:D.outputIndex,item:H}),this.emitAssistantItemAdded(H)}typeof w.name=="string"&&w.name.length>0&&(D.name=w.name),D.args+=C,h({type:"response.function_call_arguments.delta",event_id:O("event"),item_id:q,response_id:a,output_index:D.outputIndex,call_id:q,name:D.name??"",delta:C});continue}if(w.type==="response.completed"){E=w.response??null;continue}}}catch(I){this.upstreamTurnFault(I,a);return}if(this.cancelled)return;this.closeOpenItems(a,v,l),_(),this.send({type:"response.done",event_id:O("event"),response:this.doneResponse(a,l,E)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Hi(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(j({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:O("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:O("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:O("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:O("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:O("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:O("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:O("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,i=this.messageItemOpenForAudio,s=this.config.outputModalities.includes("text"),a=n.messageText;i?(this.send({type:"response.output_audio_transcript.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&s&&this.send({type:"response.output_text.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let u=[];i&&u.push({type:"output_audio",transcript:a}),n.messageText.length>0&&u.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:O("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,i]of n.tools){let s=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:O("event"),item_id:o,response_id:e,output_index:i.outputIndex,call_id:o,name:i.name??"",arguments:s});let a={id:o,type:"function_call",callId:o,name:i.name,arguments:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:O("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let s=n;s<this.items.length;s++)i.push(this.itemToProtocol(this.items[s]));return this.responseObject(e,"completed",{output:i,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=be(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??ye(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&ge(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${he(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Fe("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof Y){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Er.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Fe(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(j(r)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(j(W("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:O("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Bt&&(this.items.shift(),this.send(j({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Bt} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(j(W("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>dn){this.send(j(W("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${dn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(j(W("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(o))).catch(i=>this.send(j(Fe(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>yn){this.ws.close(Fi,Rr("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=ue(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${he(e)}`),r.message}fail(e,n){this.send(j(e)),this.ws.close(qi,Rr(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>Ar(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Ar(this.id,e)}},bn=[];function Ar(t,e){bn.push({id:t,reason:e}),bn.length>256&&bn.shift()}var gt="/v1/realtime",Ji=t=>t.slice(0,120);function Vi(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
14
14
|
Connection: close\r
|
|
15
15
|
Content-Type: text/plain\r
|
|
16
16
|
\r
|
|
17
|
-
${
|
|
18
|
-
`),t.destroy()}function
|
|
19
|
-
`}function Gs(t){De(process.stdout,t)}function Ws(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!==ht)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=O("rtup"),l=Ws(o),d=v=>{(e.log??Gs)(Vs(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)},h=v=>{d({stage:"close",conn:u,model:l,...v})},g=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)=>{h({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){h({while:"queued",...E===void 0?{}:{session:E},reason:p??"client socket closed",release_failed:b instanceof Error?b.message:String(b)});return}h({while:"queued",...E===void 0?{}:{session:E},reason:p??"client socket closed",released:!0}),s.destroy();return}y(),await g(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;h({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:T,status:A}}),s.destroyed||Js(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},Ks=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,zs=/\s/;function Ys(t){return Ks.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&&Ys(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(zs.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}),Zs='"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: ${Zs}`);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,ei({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*ei(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,h=new Promise((I,w)=>{n&&n.addEventListener("abort",()=>w(new Vt),{once:!0})}),g=()=>m||n?.aborted===!0,_=async I=>{if(g())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,h])}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&&!g();){let I=R.shift();await _(I)}},E=I=>{if(I===""||g()||(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(g())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 ti(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var ni='"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: ${ni}`);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=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(d){throw d instanceof ae?le(503,d.message):d}let a=`conn_${(0,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,ti(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=ri(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}=ai(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 ri(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)si(o,r,e);return oi(r)}function oi(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
|
|
17
|
+
${Ji(n)}\r
|
|
18
|
+
`),t.destroy()}function Gi(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
|
|
19
|
+
`}function Wi(t){De(process.stdout,t)}function Ki(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Sn(t){return t.audioSession?.audio.sessionId??void 0}function yt(t,e){let n=new Ir.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==gt)return;r.add(i),i.on("close",()=>{r.delete(i)});let u=O("rtup"),l=Ki(o),d=v=>{(e.log??Wi)(Gi(v))};d({stage:"accept",conn:u,model:l}),i.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}`);i.once("close",f),i.once("end",k),i.once("error",R);let y=()=>{i.removeListener("close",f),i.removeListener("end",k),i.removeListener("error",R)},g=v=>{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,i,s,I=>{try{new qe({ws:I,binding:v,operatorLog:e.operatorLog,onClosed:(w,C)=>{g({while:"live",reason:C.reason})}}),d({stage:"admit",conn:u,model:l,...Sn(v)===void 0?{}:{session:Sn(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=Sn(v);try{await v.release?.()}catch(b){g({while:"queued",...E===void 0?{}:{session:E},reason:p??"client socket closed",release_failed:b instanceof Error?b.message:String(b)});return}g({while:"queued",...E===void 0?{}:{session:E},reason:p??"client socket closed",released:!0}),i.destroy();return}y(),await h(v)}).catch(v=>{let E=v instanceof kn.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 kn.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}}),i.destroyed||Vi(i,A,x)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}var $r=require("crypto");var Rn="x-urun-profile",_t="voice";var se=class extends Error{status=400},zi=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Yi=/\s/;function Xi(t){return zi.test(t)}function xn(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new se(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Or(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new se(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new se(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new se(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function Tr(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new se(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let l=n.trim();if(l==="")throw new se(`the ${Rn} header is empty \u2014 the only profile this lane accepts is "${_t}" (omit the header for the ordinary lane)`);if(l!==_t)throw new se(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${_t}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==_t)throw new se(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${_t}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new se("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new se("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Or(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Or(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:xn(u,"sentence_flush",!0),includeReasoning:xn(u,"include_reasoning",!1),metadata:xn(u,"metadata",!1)}}var tt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&Xi(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(Yi.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};var Re=(t,e)=>Object.assign(new Error(e),{status:t}),es='"transcription" (a transcription session), or no intent at all (the realtime voice session)',En=(t,e,n)=>new Y(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),An=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof F?Re(404,n.message):n}};async function Pr(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Re(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${es}`);if(o==="transcription")throw Re(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw Re(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw Re(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(m){throw m instanceof F?Re(404,m.message):m}if(!p)throw Re(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(m){throw m instanceof F?Re(404,m.message):m}if(p!=="stt")throw Re(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let i=await An(t,n.stt),s=await An(t,e),a=await An(t,n.tts),u=await t.openAudioOn(i,r),l=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,ts({clients:t,chatHandle:s,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(i,p)}catch(m){throw m instanceof Y?En("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function Cr(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Vt=class extends Error{};async function*ts(t,e,n,r){let{clients:o,chatHandle:i,ttsHandle:s,chatModel:a,companions:u}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...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(s,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:I}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(q){throw q instanceof Y?En("tts",u.tts,q):q}let C=w[Symbol.asyncIterator]();k=C;try{for(;;){let q=C.next(),D;try{D=await Promise.race([q,g])}catch(H){if(q.catch(()=>{}),H instanceof Vt)return;throw H}if(D.done)return;let z=D.value;if(z.type==="error"){let H=z.error&&typeof z.error.message=="string"?z.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${H}`)}if(z.type==="response.completed")return}}finally{k===C&&(k=null)}},v=async()=>{for(;R.length>0&&!h();){let I=R.shift();await _(I)}},E=I=>{if(I===""||h()||(R.push(I),y!==null))return;let w=v();y=w,w.then(()=>{y===w&&(y=null)},C=>{y===w&&(y=null),f??=C})},b=()=>{m=!0,R.length=0;let I=k;if(k=null,I){let w=I.return?.();w&&w.catch(()=>{})}},A=async()=>{for(;R.length>0||y!==null;){let I=y;if(I===null){await _(R.shift());continue}await I}},T=p?new tt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},I=>E(I)):null,x=null;try{let I;try{I=await o.createResponseOn(i,d)}catch(w){throw w instanceof Y?En("chat",a,w):w}for await(let w of I){if(h())return;let C=w;if(C.type==="error"){yield w;return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){yield w,T?.push(C.delta);continue}if(C.type==="response.function_call_arguments.delta"){T?.flush(),yield w;continue}if(C.type==="response.completed"){x=w.response;continue}}T?.flush(),T?.dispose(),p&&await A(),x!==null&&(yield{type:"response.completed",response:x})}finally{T?.dispose(),b();try{if(f instanceof Y)throw f}finally{r?.()}}}var le=(t,e)=>Object.assign(new Error(e),{status:t});function In(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ns(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var rs='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function On(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(c){throw c instanceof F?le(404,c.message):c}if(!o){let c=null;if(t.realtimeCompanionsFor)try{c=await t.realtimeCompanionsFor(e)}catch(p){throw p instanceof F?le(404,p.message):p}if(c!==null)return await Pr(t,e,c,n,r);throw le(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw le(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(c){throw c instanceof F?le(404,c.message):c}if(i&&!t.openTurnsOn)throw le(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let c;try{c=await t.transcriptStreamFor(e)}catch(p){throw p instanceof F?le(404,p.message):p}if(c!=="stt")throw le(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(c)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw le(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${rs}`);if(r==="transcription"&&!i)throw le(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let s;try{s=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(c){throw c instanceof ae?le(503,c.message):c}let a=`conn_${(0,$r.randomUUID)()}`,l={audio:await t.openAudioOn(s,n,a).catch(c=>{throw t.releaseSessionHandle?.(s),c})},d={clients:{createResponse:async c=>await t.createResponseOn(s,c,a)},voice:o,audioSession:l};return t.openVideoOn&&(d.video=()=>t.openVideoOn(s,n)),i&&(d.turns=c=>t.openTurnsOn(s,c)),r==="transcription"&&(d.intent="transcription"),t.releaseSessionHandle&&(d.release=()=>t.releaseSessionHandle(s)),e!==void 0&&(d.model=e),d}function Gt(t,e,n){let r=Cr(t,n);return{resolve:async(o,i)=>{if(e!==void 0){let s=o.headers.authorization,a=typeof s=="string"?s.trim():"",u=a.startsWith("Bearer ")?a.slice(7).trim():"";if(u===""||u!==e)throw le(401,"invalid local proxy api key")}return On(r,In(o),i,ns(o))}}}var $=class extends Error{},pe=class extends Error{};function ee(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function 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 Mr(t,e){if(!ee(t))throw new $("decisions requires a JSON object body");nt(t.prompt_cache_key,"prompt_cache_key"),nt(t.prompt_cache_options,"prompt_cache_options"),nt(t.safety_identifier,"safety_identifier");let n=[],r=os(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new $("decisions requires a questions array of 1 to 400 questions");let i={},s=[],a=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=us(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),i[c.key]=d,s.push(c)}let u={model:e,state:r,questions:i};return n.length>0&&(u.media=n),{systemone:u,specs:s}}function os(t,e){if(typeof t=="string")return t;if(!ee(t)&&!Array.isArray(t))throw new $("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)ss(o,r,e);return is(r)}function is(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
|
|
20
20
|
|
|
21
|
-
`)}function
|
|
21
|
+
`)}function ss(t,e,n){if(!ee(t))throw new $("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){as(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let i=t.output;if(typeof i=="string"){e.push({text:i});return}if(Array.isArray(i)){Lr(i,e,n,void 0,!1);return}throw new $(`${o} output must be a string or an array of parts`)}default:throw new $(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function as(t,e,n,r){e==="assistant"&&nt(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new $(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let i of o){if(!ee(i))throw new $("decisions assistant message parts must be JSON objects");if(i.type==="output_text"&&typeof i.text=="string")n.push({role:e,text:i.text});else if(i.type==="refusal"&&typeof i.refusal=="string")n.push({role:e,text:`[refusal] ${i.refusal}`});else throw new $(`unsupported decisions assistant message part type ${JSON.stringify(i.type??null)}`)}return}Lr(o,n,r,e)}function Lr(t,e,n,r,o=!0){for(let i of t){if(!ee(i))throw new $("decisions content parts must be JSON objects");switch(nt(i.prompt_cache_breakpoint,"prompt_cache_breakpoint"),i.type){case"input_text":{if(typeof i.text!="string")throw new $("input_text requires a string text");e.push({role:r,text:i.text});break}case"input_json":{if(!o)throw new $("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let s=i.data;if(!ee(s)&&!(Array.isArray(s)&&s.every(ee)))throw new $("input_json data must be an object or an array of objects");e.push({role:r,json:s});break}case"input_image":{n.push(Nr(i));break}default:throw new $(`unsupported decisions content part type ${JSON.stringify(i.type??null)}`)}}}function Nr(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new $("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new $("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new $("input_image data URL carries no image data");let i=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(i?o.length%4!==0:o.length%4===1))throw new $("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let s=t.detail;if(s!=null&&s!=="low"&&s!=="high"&&s!=="auto"&&s!=="original")throw new $("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(s==="low"||s==="high")&&(a.detail=s),a}function us(t,e,n,r){if(!ee(t))throw new $(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new $(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let i=t.name;if(i!==void 0&&typeof i!="string")throw new $(`questions[${e}] name must be a string`);let s=i??null,a=s??`q${e}`,u=ls(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:u,options:[["no","the condition is not true"],["yes","the condition is true"]]},spec:{type:o,key:a,name:s}};case"choice":{let l=t.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new $(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let 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:s,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:s,levelLabels:d,scoreCriteria:c}}}}}function ls(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new $(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let i of t){if(!ee(i))throw new $(`questions[${e}] instruction parts must be JSON objects`);switch(nt(i.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),i.type){case"input_text":{if(typeof i.text!="string")throw new $(`questions[${e}] input_text requires a string text`);o.push(i.text);break}case"input_image":{if(n>1)throw new $(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(Nr(i));break}case"input_json":{let s=i.data;if(!ee(s)&&!(Array.isArray(s)&&s.every(ee)))throw new $(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(s));break}default:throw new $(`unsupported decisions instruction part type ${JSON.stringify(i.type??null)}`)}}return o.join(`
|
|
22
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}},li=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&&he(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 di={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(!di[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 ci={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??li;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(!ci[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,pi=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 fi(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 mi=2;function gi(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>mi)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 yi(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 _i(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 yi(e,async()=>{if(i?.()===!0)return null;let p=!1,m=!1,f=!1,k,R=new Promise(A=>{k=A}),y=[],h=()=>{m&&!f&&y.length>=o.quietRunFrames&&(f=!0,k())},g=e.onOutputAudio(A=>{let T=Buffer.from(A,"base64");if(T.byteLength===0)return;let x=gi(T);if(!p){if(x)return;p=!0}if(x){y.push(T),h();return}for(let I of y)c(I);y.length=0,c(T),h()}),_=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&&he(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?.(_),h(),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 _i(t,n,b,s.returnBoundMs),A}finally{v!==void 0&&clearTimeout(v),E!==void 0&&clearTimeout(E),g()}})}function wi(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 vi(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 bi={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Si="wav, pcm";async function uo(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??pi,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(!bi[_])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 ${Si} \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 fi(n.turn,n.clients,d);let y=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",y,y),!await vi(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 h;try{h=await n.clients.speechSessionHandle(d)}catch(_){throw qe(_,r)}let g;try{g=await n.clients.openAudioOn(h)}catch(_){throw qe(_,r)}n.turn&&(n.turn.sessionId=g.sessionId);try{if(f==="wav"){let _=[],v=await ro(n.clients,g,h,{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 _=wi(e,n.turn,i,m===void 0),v;try{v=await ro(n.clients,g,h,{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",ki=16*1024*1024,xi=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 Ri(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 Ai(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 Ei(t,e){t&&(t.outputUnits=e.seconds)}async function Ii(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&&he(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 Oi(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 Ti=new Set(["file","model","language","response_format"]);async function mo(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??xi,s=n.maxAudioPartBytes??ki;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(h){throw h instanceof te?new W(413,h.message):new W(400,String(h instanceof Error?h.message:h))}let u=new Map;for(let h of a.keys()){if(!Ti.has(h))throw new W(400,`form field "${h}" 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.`,h);u.set(h,(u.get(h)??0)+1)}for(let[h,g]of u)if(g>1)throw new W(400,`form field "${h}" 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`,h);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=Ri(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 Ai(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",k.length,k.length),!await Oi(n.transcriptionModels,d,e,r))return;let y=[{type:"input_audio",input_audio:{data:Buffer.from(k).toString("base64"),format:"wav"}}];try{let h=await Ii(n.clients,d,y,p,n.turn?de(n.turn):void 0,n.turn,r);Ei(n.turn,R),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:h}))}catch(h){throw fo(h,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 ho="/v1/usage/requests",go=1e4,Pi=/^[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>go)throw new Oe(`"${e}" carries ${n.length} ids; at most ${go} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!Pi.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 Ci(t){return Pn(t,"requestIds")}function $i(t){return t>=200&&t<=399}function Mi(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&$i(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=Ci(t),r=await e(n);return nn(r,n),Mi(r)}var Li={"/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 Ni(t){return Li[t]??null}var ko=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Ui(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Di(t){return t==="surface"}function Fi(t){let e=t?.ledgerFailureReason;return ko.includes(e)?e:"unknown"}var qi=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],vo=["priced","unpriced"],Bi={written:vo,already_written:vo,skipped:qi,failed:ko},cd=Object.entries(Bi).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function ji(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Hi(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 Ji=256,bo=4096,St=12e4,Vi=250,Gi=8e3,kt=[],So=new Set,xt=0,bt=!1;var Wi=new Set;function Ki(){return xt===0&&kt.length===0}function zi(){if(Ki()){bt=!1;for(let t of[...Wi])t()}}function xo(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
24
|
-
`}function Yi(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??Yi,o=Ni(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:Hi(e),completed_at:e.ts,billable_outcome:ji(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<Ji&&(xt+=1,Xi())}async function Xi(){try{for(;;){let t=Qi();if(t===void 0)return;So.add(t);try{await Zi(t)}finally{So.delete(t)}}}finally{xt-=1,zi()}}function Qi(){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 Zi(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=Ui(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=Fi(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(Di(i)&&a<St){if(await ta(ea(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 ea(t){return Math.min(Gi,Vi*2**Math.max(0,t-1))}function ta(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 na(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 ra=64*1024*1024,Rt=class extends Error{};async function Eo(t,e=ra){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:oa(t)},completion_tokens_details:{reasoning_tokens:0}}}function oa(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function sa(t,e){let n=To(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function ia(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 aa(t,e){let n=ia(e);n&&(t.timing=n),t.outputSeconds=xe(e)}function je(t,e){sa(t,e),aa(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 ua(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 la(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 da(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:la(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 ca(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 h;try{h=await ft({body:t,clients:e,store:n,stats:o,responseId:a,turn: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}Ln(r);for await(let g of h.events){if(g.type==="error"){s.streamError=!0;let _=g.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(g)}`),r.write(`event: error
|
|
23
|
+
`)}function Ur(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 i=n[o.key];if(!ee(i)||i.skipped===!0){r.push({type:"refusal",name:o.name});continue}let s=ee(i.probabilities)?i.probabilities:{};switch(o.type){case"predicate":{let a=Wt(s.yes),u=Wt(s.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=i.choice;if(typeof u!="string")throw new pe(`the choice answer for "${o.key}" carries no string choice`);let l=a.findIndex(p=>String(p)===u);if(l===-1)throw new pe(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(u)})`);let d=Kt(i.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(s[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(i.score);if(l===null)throw new pe(`the score answer for "${o.key}" carries no numeric score to translate`);let d=Kt(i.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(s[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 i of t){let s=i;if(o+=s.length,o>e)throw new te(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function Yt(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(s){try{let a=await n.next();if(a.done){s.close();return}if(r+=a.value.length,r>e){s.error(new te(`request body exceeds the ${e}-byte limit`));return}s.enqueue(a.value)}catch(a){s.error(a)}},cancel(){n.return?.()}}),i;try{let s=new Headers;for(let[l,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 te?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var Dr="/v1/images/generations",Xt="/v1/images/edits";function Fr(t){return t===Dr||t===Xt}var qr="/v1/images/models";async function Br(t,e,n){if(t){if(t.model=oe({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var N=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},ds=16*1024*1024,jr=64*1024*1024;function Hr(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function wt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function Jr(t,e,n,r,o,i){let s=i??(f=>console.error(f)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),u=null;for await(let f of a){if(f.type==="error"){let k=f.error??{},R=typeof k.message=="string"&&k.message.length>0&&ge(k.message)?k.message:null;throw R===null?(s(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(f)}`),new N(502,"the image upstream failed while serving this request")):new N(502,`image upstream error: ${R}`)}if(f.type==="response.completed"){u=f.response??null;break}}if(u===null)throw new N(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=xe(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new N(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(Hr(p)===null)throw new N(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function Vr(t,e){if(t instanceof N)return t;if(t instanceof ve)throw t;return t instanceof F?new N(404,t.message):new N(502,Ze("image",t,e))}async function Gr(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return wt(r,new N(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Wr(t,e){t&&(t.outputUnits=e.images.length)}function Kr(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var cs={model:!0,prompt:!0,response_format:!0,n:!0};async function zr(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??jr;try{if(t.method!=="POST")throw new N(405,`${String(t.method)} is not supported on ${Dr}`);let i;try{i=JSON.parse((await 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(i===null||typeof i!="object"||Array.isArray(i))throw new N(400,"request body must be a JSON object");let s=i;for(let p of Object.keys(s))if(!cs[p])throw new N(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let a=s.prompt;if(typeof a!="string"||a.trim().length===0)throw new N(400,"prompt is required and must be a non-empty string","prompt");let u=s.model===void 0?void 0:s.model;if(u!==void 0&&typeof u!="string")throw new N(400,"model must be a string","model");await Br(n.turn,n.clients,u);let l=s.n??1;if(l!==1)throw new N(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.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 Gr(n.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Jr(n.clients,u,c,n.turn?de(n.turn):void 0,n.turn,r);Wr(n.turn,p),Kr(e,p)}catch(p){throw Vr(p,r)}}catch(i){if(i instanceof te){wt(e,new N(413,i.message));return}if(i instanceof N){wt(e,i);return}throw i}}var ps={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Yr(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??jr,i=n.maxImagePartBytes??ds;try{if(t.method!=="POST")throw new N(405,`${String(t.method)} is not supported on ${Xt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new N(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let a;try{a=await 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 Br(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(!ps[f])throw new N(400,`form field "${f}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,f);let p=[];for(let f of["image","image[]"])for(let k of a.getAll(f)){if(!(k instanceof File))throw new N(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",f);if(k.size>i)throw new N(413,`image part exceeds the ${i}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let R=new Uint8Array(await k.arrayBuffer()),y=Hr(R);if(y===null)throw new N(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",f);p.push({bytes:R,mime:y})}if(p.length===0)throw new N(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await Gr(n.imageModels,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 Jr(n.clients,d,m,n.turn?de(n.turn):void 0,n.turn,r);Wr(n.turn,f),Kr(e,f)}catch(f){throw Vr(f,r)}}catch(s){if(s instanceof te){wt(e,new N(413,s.message));return}if(s instanceof N){wt(e,s);return}throw s}}var vt="/v1/audio/speech";function io(t){return t===vt}var Xr=4096,Qr=18e4,Zr=5e3,fs=64*1024*1024,eo=8,to=5,no=1024*1024,rt="voice_applied",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 Tn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var 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 ao(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 ms(t,e,n){if(t){if(t.model=oe({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function uo(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var hs=2;function gs(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>hs)return!1;return!0}function ys(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var ro=new WeakMap,Qt=new WeakMap;function _s(t,e){let n=Qt.get(t)??0;if(n>=eo)throw new L(503,`this model's speech queue is full \u2014 ${eo} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${to}s`,void 0,to);Qt.set(t,n+1);let r=ro.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return ro.set(t,i),(async()=>{await r;try{return await e()}finally{Qt.set(t,(Qt.get(t)??1)-1),o()}})()}async function ws(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new L(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(s){if(!(s instanceof Y))throw s}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),i;await Promise.race([o,new Promise(s=>{i=setTimeout(s,r)})]).finally(()=>{i!==void 0&&clearTimeout(i)})}function Be(t,e){if(t instanceof L)return t;if(t instanceof ve)throw t;return t instanceof F?new L(404,t.message):new L(502,Ze("speech",t,e))}async function oo(t,e,n,r,o,i,s,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return _s(e,async()=>{if(s?.()===!0)return null;let p=!1,m=!1,f=!1,k,R=new Promise(A=>{k=A}),y=[],g=()=>{m&&!f&&y.length>=o.quietRunFrames&&(f=!0,k())},h=e.onOutputAudio(A=>{let T=Buffer.from(A,"base64");if(T.byteLength===0)return;let x=gs(T);if(!p){if(x)return;p=!0}if(x){y.push(T),g();return}for(let I of y)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,i.capMs)}),x=!1;for(;;){let w=b.next(),C=await Promise.race([w,T]);if(C===void 0){x=!0,w.catch(()=>{});break}if(C.done)break;let q=C.value;if(q.type==="error"){let D=q.error??{};await b.return?.();let z=typeof D.message=="string"&&D.message.length>0&&ge(D.message)?D.message:null;throw z===null?(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: ${z}`)}if(q.type==="response.completed"){_=q.response??null,m=!0,u?.(_),g(),await b.return?.();break}}if(clearTimeout(E),x)throw new L(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(_===null)throw new L(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let I=!1;if(await Promise.race([R,new Promise(w=>{v=setTimeout(()=>{I=!0,w()},o.capMs)})]),v!==void 0&&clearTimeout(v),r.voice!==void 0){let w=_[rt];if(typeof w!="string"||w!==r.voice){let C=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof w=="string"?`${rt} ${JSON.stringify(w)}`:`no ${rt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw f?new 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 ws(t,n,b,i.returnBoundMs),A}finally{v!==void 0&&clearTimeout(v),E!==void 0&&clearTimeout(E),h()}})}function vs(t,e,n,r){let o=!1,i=0,s=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Zt)),t.write(a,u=>{u||(i+=a.byteLength,uo(e,i))}),t.writableLength>no&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${no} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let u=a[rt];if(typeof u=="string"){if(!so(u))throw ao(u);t.addTrailers({[Zt]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:s}}async function bs(t,e,n,r){let o;try{o=await t(e)}catch(i){throw Be(i,r)}return o?!0:(Tn(n,new L(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Ss={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},ks="wav, pcm";async function lo(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??fs,i=!1;e.once("close",()=>{i=!0});let s=()=>i||e.destroyed;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${vt}`);let a;try{a=JSON.parse((await 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(!Ss[_])throw new L(400,`request field "${_}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,_);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new L(400,"input is required and must be a non-empty string","input");if(l.length>Xr)throw new L(400,`input is ${l.length} chars \u2014 over the ${Xr}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let 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 Be(_,r)}if(p.defect!==null)throw new L(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof 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 ${ks} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new L(400,"stream_format, when present, must be a string","stream_format");let k=u.speed;if(k!==void 0){if(typeof k!="number"||!Number.isFinite(k))throw new L(400,"speed, when present, must be a number","speed");if(k!==1)throw new L(400,`speed=${JSON.stringify(k)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let R=u.instructions;if(R!==void 0){if(typeof R!="string")throw new L(400,"instructions, when present, must be a string","instructions");if(R.trim().length>0)throw new L(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await ms(n.turn,n.clients,d);let y=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",y,y),!await bs(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(s())return;let g;try{g=await n.clients.speechSessionHandle(d)}catch(_){throw Be(_,r)}let h;try{h=await n.clients.openAudioOn(g)}catch(_){throw Be(_,r)}n.turn&&(n.turn.sessionId=h.sessionId);try{if(f==="wav"){let _=[],v=await oo(n.clients,h,g,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Qr,returnBoundMs:n.turnReturnBoundMs??Zr},s,b=>_.push(b),b=>{n.turn&&(n.turn.outputSeconds=xe(b))},r);if(v===null||s())return;let E=Buffer.concat(_);if(m===void 0){let b=v[rt];if(typeof b=="string"){if(!so(b))throw ao(b);e.setHeader(Zt,b)}}uo(n.turn,E.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([ys(E.byteLength),E]))}else{let _=vs(e,n.turn,s,m===void 0),v;try{v=await oo(n.clients,h,g,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Qr,returnBoundMs:n.turnReturnBoundMs??Zr},s,_.sink,E=>{n.turn&&(n.turn.outputSeconds=xe(E))},r)}catch(E){let b=Be(E,r);if(!_.started())throw b;n.turn&&(n.turn.streamError=!0),_.fail(b);return}if(v===null)return;try{await _.finish(v)}catch(E){let b=Be(E,r);n.turn&&(n.turn.streamError=!0),_.fail(b);return}}}catch(_){throw Be(_,r)}}catch(a){if(a instanceof te){Tn(e,new L(413,a.message));return}if(a instanceof L){Tn(e,a);return}throw a}}var tn="/v1/audio/transcriptions";function co(t){return t===tn}var po="/v1/audio/models",xs=16*1024*1024,Rs=64*1024*1024,K=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Pn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function fo(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function As(t){if(!fo(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),s=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,l=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,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 Es(t,e,n){if(t){if(t.model=oe({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Is(t,e){t&&(t.outputUnits=e.seconds)}async function Os(t,e,n,r,o,i,s){let a=s??(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 K(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new K(m==="invalid_request_error"?400:502,`transcription upstream error: ${f}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new K(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return i&&(i.outputSeconds=xe(d)),Ye(l,d)}function mo(t,e){if(t instanceof K)return t;if(t instanceof ve)throw t;return t instanceof F?new K(404,t.message):new K(502,Ze("transcription",t,e))}async function Ts(t,e,n,r){let o;try{o=await t(e)}catch(i){throw mo(i,r)}return o?!0:(Pn(n,new K(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Ps=new Set(["file","model","language","response_format"]);async function ho(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Rs,i=n.maxAudioPartBytes??xs;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${tn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new K(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let a;try{a=await Yt(t,o)}catch(g){throw g instanceof te?new K(413,g.message):new K(400,String(g instanceof Error?g.message:g))}let u=new Map;for(let g of a.keys()){if(!Ps.has(g))throw new K(400,`form field "${g}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,g);u.set(g,(u.get(g)??0)+1)}for(let[g,h]of u)if(h>1)throw new K(400,`form field "${g}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,g);let l=a.get("model");if(l!==null&&typeof l!="string")throw new K(400,"model must be a string field","model");let d=l===null?void 0:l,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new K(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 K(400,`response_format ${JSON.stringify(m)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let f=a.get("file");if(!(f instanceof File))throw new K(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(f.size>i)throw new K(413,`file part exceeds the ${i}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let k=new Uint8Array(await f.arrayBuffer());if(!fo(k))throw new K(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let R=As(k);if(R===null)throw new K(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Es(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",k.length,k.length),!await Ts(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 Os(n.clients,d,y,p,n.turn?de(n.turn):void 0,n.turn,r);Is(n.turn,R),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:g}))}catch(g){throw mo(g,r)}}catch(s){if(s instanceof te){Pn(e,new K(413,s.message));return}if(s instanceof K){Pn(e,s);return}throw s}}var yo="/v1/usage/requests",go=1e4,Cs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Oe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},ot=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var _o=1024*1024;function Cn(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Oe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Oe(`"${e}" must be an array of uuid strings`);if(n.length>go)throw new Oe(`"${e}" carries ${n.length} ids; at most ${go} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let i of n){if(typeof i!="string"||!Cs.test(i))throw new Oe(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(i)||(o.add(i),r.push(i))}return r}function wo(t){return Cn(t,"inference_ids")}function nn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let i=t[o];if(!n.has(i.inference_id))throw new ot(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(i.inference_id))throw new ot(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(i.inference_id)}}var an=require("@urun-sh/core");var $n="/partners/huggingface/v1/billing/requests";function $s(t){return Cn(t,"requestIds")}function Ms(t){return t>=200&&t<=399}function Ls(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Ms(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function vo(t,e){let n=$s(t),r=await e(n);return nn(r,n),Ls(r)}var Ns={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Us(t){return Ns[t]??null}var xo=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Ds(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Fs(t){return t==="surface"}function qs(t){let e=t?.ledgerFailureReason;return xo.includes(e)?e:"unknown"}var Bs=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],bo=["priced","unpriced"],js={written:bo,already_written:bo,skipped:Bs,failed:xo},fd=Object.entries(js).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Hs(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Js(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var Vs=256,So=4096,St=12e4,Gs=250,Ws=8e3,kt=[],ko=new Set,xt=0,bt=!1;var Ks=new Set;function zs(){return xt===0&&kt.length===0}function Ys(){if(zs()){bt=!1;for(let t of[...Ks])t()}}function Ro(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
24
|
+
`}function Xs(t){De(process.stdout,t)}function Ao(t,e){try{t(e)}catch{}}function Eo(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Xs,o=Us(e.path);if(o===null)return;let i=d=>{try{n.observe(d)}catch{}},s=(d,c)=>{i({outcome:"skipped",reason:d}),Ao(r,Ro("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:Js(e),completed_at:e.ts,billable_outcome:Hs(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(kt.length>=So){s("queue_full",`${kt.length} ledger writes are already waiting (capacity ${So}, ${xt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}kt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),xt<Vs&&(xt+=1,Qs())}async function Qs(){try{for(;;){let t=Zs();if(t===void 0)return;ko.add(t);try{await ea(t)}finally{ko.delete(t)}}}finally{xt-=1,Ys()}}function Zs(){let t=Date.now();for(;;){let e=kt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<St)return e;it(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${St}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function ea(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);it(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let i=Ds(o);if(i!==null){it(t,{outcome:"already_written",reason:i.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:i.cost_nano_usd,price_version:i.price_version,attempts:t.attempts});return}let s=qs(o),a=Date.now()-t.queuedAt;if(bt){it(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Fs(s)&&a<St){if(await na(ta(t.attempts)),bt||Date.now()-t.queuedAt>=St){let u=Date.now()-t.queuedAt;it(t,{outcome:"failed",reason:bt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:bt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${St}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}it(t,{outcome:"failed",reason:s},{event:"inference_ledger_write_failed",reason:s,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function ta(t){return Math.min(Ws,Gs*2**Math.max(0,t-1))}function na(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function it(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Ao(t.report,Ro(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function Nn(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function ra(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function ne(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function J(t,e,n,r="invalid_request_error",o){ne(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Un(t,e,n){let r=e.error,o=r?.type??"upstream_error",i=n?.operatorError??(d=>console.error(d)),s=be(r),a=s??ye(n?.inferenceId??null);s===null&&i(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let u=r?.code??null,l=o==="invalid_request_error"?400:u==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),ne(t,l,{error:{message:a,type:o,code:u}})}function _e(t,e,n,r){ne(t,e,{type:"error",error:{type:n,message:r}})}function st(t,e,n){if(e==="anthropic"){ne(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ne(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var oa=64*1024*1024,Rt=class extends Error{};async function Io(t,e=oa){let n=[],r=0;for await(let i of t){if(r+=i.length,r>e)throw new Rt(`request body exceeds ${e} bytes`);n.push(i)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function je(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function Po(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),i=r(n.output_tokens),s=u=>u??0,a=r(n.total_tokens)??s(o)+s(i);if(s(o)>0||s(i)>0){let u={input_tokens:s(o),output_tokens:s(i),total_tokens:a};return o===null||i===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function rn(t){let e=Po(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Oo(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:ia(t)},completion_tokens_details:{reasoning_tokens:0}}}function ia(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function sa(t,e){let n=Po(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function aa(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let l=n[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),i=r("prefill_ms"),s=r("decode_ms"),a=r("total_ms");return o===null||i===null||s===null||a===null?null:{queue_ms:o,prefill_ms:i,decode_ms:s,total_ms:a}}function ua(t,e){let n=aa(e);n&&(t.timing=n),t.outputSeconds=xe(e)}function He(t,e){sa(t,e),ua(t,e)}async function 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 Co(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function la(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var on=class extends Error{};function da(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new on(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function ca(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:da(n.role,n.content)})}return e}function Mn(t){return Ke(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function pa(t,e,n,r,o,i,s){let a=ct(i.id),u=t.stream===!0;if(i.model=oe(t),i.stream=u,await un(i,e,typeof t.model=="string"?t.model:void 0),u){let g;try{g=await ft({body:t,clients:e,store:n,stats:o,responseId:a,turn:i})}catch(h){if(h instanceof F){st(r,"openai",h);return}if(h instanceof ce){J(r,h.status,h.message);return}if(h instanceof me||h instanceof ae){r.setHeader("retry-after","2"),J(r,503,h.message,"capacity_error");return}throw h}Nn(r);for await(let h of g.events){if(h.type==="error"){i.streamError=!0;let _=h.error,v=be(_),E=v??ye(i.id);v===null&&s(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(h)}`),r.write(`event: error
|
|
25
25
|
data: ${JSON.stringify({error:{message:E,type:_?.type??"upstream_error",code:_?.code??null}})}
|
|
26
26
|
|
|
27
|
-
`),r.end();return}
|
|
28
|
-
data: ${JSON.stringify(
|
|
27
|
+
`),r.end();return}h.type==="response.completed"&&He(i,h.response),r.write(`event: ${String(h.type??"message")}
|
|
28
|
+
data: ${JSON.stringify(h)}
|
|
29
29
|
|
|
30
30
|
`)}r.write(`data: [DONE]
|
|
31
31
|
|
|
32
|
-
`),r.end();return}let l;try{l=
|
|
32
|
+
`),r.end();return}let l;try{l=Xe(n,t)}catch(g){if(g instanceof ce){J(r,g.status,g.message);return}throw g}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=oe(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await fn(e,t,l,!1,de(i))}catch(g){if(g instanceof F){st(r,"openai",g);return}if(g instanceof ce){J(r,g.status,g.message);return}if(g instanceof me||g instanceof ae){r.setHeader("retry-after","2"),J(r,503,g.message,"capacity_error");return}throw g}let f=[],k=null;for await(let g of o.track(m,c,i)){if(f.push(g),g.type==="error"){Un(r,g,{inferenceId:i.id,operatorError:s});return}g.type==="response.completed"&&(k=g.response)}if(k==null){J(r,502,"upstream produced no response.completed event","upstream_error");return}He(i,k);let R=Ye(f,k),y=Ne(p,Ke(k).length,R);if(y){J(r,502,Le(c,y),"upstream_error");return}d&&n.remember(a,l,pn(k,R),d),ne(r,200,{...k,id:a})}async function fa(t,e,n,r,o,i,s){let a=t.messages;if(!Array.isArray(a)){J(n,400,"chat/completions requires a messages array");return}let u;try{u=Tr(i,t)}catch(x){if(x instanceof se){J(n,x.status,x.message);return}throw x}let l=String(t.model??"urun"),d=pr(o.id),c;try{c=ca(a)}catch(x){if(x instanceof on){J(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:la(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},de(o))}catch(x){if(x instanceof F){st(n,"openai",x);return}if(x instanceof me||x instanceof ae){n.setHeader("retry-after","2"),J(n,503,x.message,"capacity_error");return}throw x}if(t.stream===!0){u?ra(n):Nn(n);let x=[],I=new Ee,w="",C=u?new tt(u,D=>{n.write(`data: ${JSON.stringify(je(d,l,{content:D},null))}
|
|
33
33
|
|
|
34
34
|
`)}):null,q=D=>{C?.flush(),n.write(D),n.end()};try{u?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
|
|
35
35
|
|
|
36
|
-
`),n.write(`data: ${JSON.stringify(
|
|
36
|
+
`),n.write(`data: ${JSON.stringify(je(d,l,{role:"assistant"},null))}
|
|
37
37
|
|
|
38
|
-
`);for await(let
|
|
38
|
+
`);for await(let X of r.track(f,p,o)){x.push(X);let re=ze(X);if(X.type==="response.output_text.delta"&&typeof X.delta=="string")w+=X.delta,C?C.push(X.delta):n.write(`data: ${JSON.stringify(je(d,l,{content:X.delta},null))}
|
|
39
39
|
|
|
40
|
-
`);else if(
|
|
40
|
+
`);else if(X.type==="response.reasoning_text.delta"&&typeof X.delta=="string")(!u||u.includeReasoning)&&n.write(`data: ${JSON.stringify(je(d,l,{reasoning_content:X.delta},null))}
|
|
41
41
|
|
|
42
|
-
`);else if(re){C?.flush();let{call:M,isNew:B}=I.add(re),
|
|
42
|
+
`);else if(re){C?.flush();let{call:M,isNew:B}=I.add(re),V=B?{index:re.tool_index,id:M.id??`call_${re.tool_index}`,type:"function",function:{name:M.name??"",arguments:re.delta}}:{index:re.tool_index,function:{arguments:re.delta}};n.write(`data: ${JSON.stringify(je(d,l,{tool_calls:[V]},null))}
|
|
43
43
|
|
|
44
|
-
`)}else if(
|
|
44
|
+
`)}else if(X.type==="error"){o.streamError=!0;let M=X.error??{},B=be(M),V=B??ye(o.id);B===null&&s(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(X)}`),q(`data: ${JSON.stringify({error:{message:V,type:M.type??"upstream_error",code:M.code??null}})}
|
|
45
45
|
|
|
46
|
-
`);return}}let D
|
|
46
|
+
`);return}}let D=Mn(we(x)),z=Ne(m,I.size+D.length,w);if(z){o.streamError=!0,q(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Le(p,z)}})}
|
|
47
47
|
|
|
48
|
-
`);return}C?.flush(),I.size===0&&D.length>0&&n.write(`data: ${JSON.stringify(
|
|
48
|
+
`);return}C?.flush(),I.size===0&&D.length>0&&n.write(`data: ${JSON.stringify(je(d,l,{tool_calls:D},null))}
|
|
49
49
|
|
|
50
|
-
`);let
|
|
50
|
+
`);let H=I.size>0||D.length>0;n.write(`data: ${JSON.stringify(je(d,l,{},H?"tool_calls":"stop"))}
|
|
51
51
|
|
|
52
|
-
`);let Ae=rn(we(x));
|
|
52
|
+
`);let Ae=rn(we(x));He(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:Oo(we(x))})}
|
|
53
53
|
|
|
54
54
|
`),n.write(`data: [DONE]
|
|
55
55
|
|
|
56
|
-
`),n.end();return}finally{C?.flush(),C?.dispose()}}let k="",R="",y=[],
|
|
56
|
+
`),n.end();return}finally{C?.flush(),C?.dispose()}}let k="",R="",y=[],g=new Ee;for await(let x of r.track(f,p,o)){y.push(x),x.type==="response.output_text.delta"&&typeof x.delta=="string"&&(k+=x.delta),x.type==="response.reasoning_text.delta"&&typeof x.delta=="string"&&(R+=x.delta);let I=ze(x);if(I&&g.add(I),x.type==="error"){Un(n,x,{inferenceId:o.id,operatorError:s});return}}let h=we(y);He(o,h);let _=Mn(h),v=_.length>0?_:Mn({output:g.items()}),E=Ne(m,v.length,k);if(E){J(n,502,Le(p,E),"upstream_error");return}let b=v.map(({index:x,...I})=>I),A={role:"assistant",content:k||null},T=R||Co(h);T&&(A.reasoning_content=T),b.length>0&&(A.tool_calls=b),ne(n,200,{id: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:Oo(h)})}var $o="sense-latest";async function ma(t,e,n,r,o,i){if(t===null||typeof t!="object"||Array.isArray(t)){J(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:$o,a=oe({model:s});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){J(n,400,"systemone requires a state (string or JSON structure)");return}let u=t.questions;if(u===null||typeof u!="object"||Array.isArray(u)||Object.keys(u).length===0){J(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){J(n,400,"systemone media, when present, must be an array");return}let l=await Mo(t,s,a,e,n,r,o,i);l!==null&&ne(n,200,l.answer)}async function Mo(t,e,n,r,o,i,s,a){let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};s.decision=u;let l=performance.now();i.model(n),await un(s,r,e),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},de(s))}catch(y){if(y instanceof F)return st(o,"openai",y),null;if(y instanceof me||y instanceof ae)return o.setHeader("retry-after","2"),J(o,503,y.message,"capacity_error"),null;throw y}u.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let y of i.track(d,n,s))if(m===null&&(m=performance.now(),u.first_event_ms=Math.round(m-c)),p.push(y),y.type==="error")return Un(o,y,{inferenceId:s.id,operatorError:a}),null}catch(y){if(y instanceof F)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),st(o,"openai",y),null;if(y instanceof me||y instanceof ae)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),o.setHeader("retry-after","2"),J(o,503,y.message,"capacity_error"),null;throw m!==null&&(u.stream_ms=Math.round(performance.now()-m)),y}m!==null&&(u.stream_ms=Math.round(performance.now()-m));let f=we(p);if(f==null)return J(o,502,"upstream produced no response.completed event","upstream_error"),null;He(s,f);let k=Ye(p,f),R;try{R=JSON.parse(k)}catch{return J(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(R===null||typeof R!="object"||Array.isArray(R))return J(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof R=="object"&&R!==null&&!Array.isArray(R)&&"timing"in R){let y=R.timing;if(typeof y=="object"&&y!==null&&!Array.isArray(y)&&"question_fwd_ms"in y&&"head_ms"in y){let g=h=>typeof h=="number"&&Number.isFinite(h)&&h>=0?Math.round(h):null;u.question_fwd_ms=g(y.question_fwd_ms),u.head_ms=g(y.head_ms)}}return{answer:R,completed:f}}async function ha(t,e,n,r,o,i){if(t===null||typeof t!="object"||Array.isArray(t)){J(n,400,"decisions requires a JSON object body");return}let s=typeof t.model=="string"&&t.model?t.model:$o,a=oe({model:s});o.model=a,o.stream=!1;let u;try{u=Mr(t,s)}catch(p){if(p instanceof $){J(n,400,p.message);return}throw p}let l=await Mo(u.systemone,s,a,e,n,r,o,i);if(l===null)return;let d;try{d=Ur(u.specs,l.answer)}catch(p){if(p instanceof pe){J(n,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;ne(n,200,{model:s,answers:d,...c===void 0?{}:{usage:c}})}function ga(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var At=class extends Error{};function sn(t){return new At(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function ya(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function _a(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new At(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function wa(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw 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 va(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw sn(typeof n);let r=[],o="",i=()=>{o&&(r.push({role:e,content:o}),o="")};for(let s of n){let a=String(s.type??"");if(a==="text")o+=String(s.text??"");else if(a==="tool_use")i(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});else if(a==="tool_result")i(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:wa(s.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw sn(a)}}return i(),r}function Ln(t){return Ke(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function ba(t,e,n,r,o,i){let s=t.messages;if(!Array.isArray(s)){_e(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){_e(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){_e(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(A=>typeof A!="string"))){_e(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),u=fr(o.id),l=[],d;try{t.system&&l.push({role:"system",content:ga(t.system)});for(let A of s)l.push(...va(A));d=_a(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:ya(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){st(n,"anthropic",A);return}if(A instanceof me||A instanceof ae){n.setHeader("retry-after","2"),_e(n,503,"capacity_error",A.message);return}throw A}let f=(A,T)=>{n.destroyed||n.write(`event: ${A}
|
|
57
57
|
data: ${JSON.stringify({type:A,...T})}
|
|
58
58
|
|
|
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=[],h=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&&h.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 g=we(y);je(o,g);let _;try{_=Mn(g),_.length===0&&h.size>0&&(_=Mn({output:h.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(g);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(g)??{input_tokens:0,output_tokens:0}})}function ba(t){De(process.stdout,t)}function Sa(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??ba,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=(g,_,v,E,b)=>m?_e(c,g,E,_):H(c,g,_,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 g=fr({turn:y,method:d.method??"",path:p.pathname,res:c});i(mr(g)),u?.(g),Ao({record:g,ledger:t.ledger??null,req:d})}));let h=()=>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 g=p.pathname===ho?"canonical":p.pathname===Cn?"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 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(g==="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:h(),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:h(),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:h(),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 ca(v,_,pt(_),c,l,h(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",E,E),await pa(v,_,c,l,h(),d.headers[xn],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",E,E),await fa(v,_,c,l,h(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",E,E),await ma(v,_,c,l,h(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",E,E),await va(v,_,c,l,h(),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(g=>{let _=String(g instanceof Error?g.message:g);if(!c.headersSent){let b=o?.(g)??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(g instanceof an.SessionAllocationError){let T=Dt(g.code);if(T){let x=g.retryAfterSeconds??(T.status===429?30:void 0);x!==void 0&&c.setHeader("Retry-After",String(x)),f(T.status,mt(T,g.code??void 0),T.openaiType,T.anthropicType,T.code);return}}if(g instanceof an.SessionFailedError){let T=Ft(g);if(T){let x=T.status===429?30:void 0;x!==void 0&&c.setHeader("Retry-After",String(x)),f(T.status,mt(T,g.status.sessionId?`session ${g.status.sessionId}`:void 0),T.openaiType,T.anthropicType,T.code);return}}if(g instanceof ot){f(502,_,"upstream_error","api_error");return}if(g instanceof Ue){g.retryable&&c.setHeader("Retry-After","1");let T=ue(g,{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: ${g instanceof Error?`${g.name}: ${g.message}`:ge(g)}`),f(502,T.message,"upstream_error","api_error",g.code);return}if(g instanceof Xe){c.setHeader("Retry-After",String(g.retryAfterSeconds)),f(g.status,_,g.status===429?"capacity_error":"upstream_error",g.status===429?"rate_limit_error":"overloaded_error",g.code);return}let A=ue(g,{inferenceId:y?.id??null});A.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:ge(g)}`),f(500,A.message,"proxy_error","api_error","proxy_error");return}y&&(y.streamError=!0);let v=g instanceof Ue?g.code:null,E=ue(g,{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: ${g instanceof Error?`${g.name}: ${g.message}`:ge(g)}`),c.destroyed||(m?c.write(`event: error
|
|
59
|
+
`)};if(t.stream===!0){let A=r.track(m,c,o);Nn(n),f("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let T=0,x="",I=0,w="none",C=()=>w,q=-1,D=-1,z=new Ee,H=[],Ae=()=>{w!=="none"&&(w="none",f("content_block_stop",{index:q}))},X=(G,Q)=>{Ae(),w=G,q=I++,f("content_block_start",{index:q,content_block:Q})};for await(let G of A){if(n.destroyed)break;H.push(G);let Q=ze(G);if(G.type==="response.reasoning_text.delta"&&typeof G.delta=="string")C()!=="thinking"&&X("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:q,delta:{type:"thinking_delta",thinking:G.delta}});else if(G.type==="response.output_text.delta"&&typeof G.delta=="string")C()!=="text"&&X("text",{type:"text",text:""}),T+=1,x+=G.delta,f("content_block_delta",{index:q,delta:{type:"text_delta",text:G.delta}});else if(Q){let{call:fe}=z.add(Q);(C()!=="tool"||Q.tool_index!==D)&&(D=Q.tool_index,X("tool",{type:"tool_use",id:fe.id??`call_${Q.tool_index}`,name:fe.name??"",input:{}})),Q.delta&&f("content_block_delta",{index:q,delta:{type:"input_json_delta",partial_json:Q.delta}})}else if(G.type==="error"){o.streamError=!0;let fe=G.error,Pe=be(fe);Pe===null&&i(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(G)}`),f("error",{error:{type:"api_error",message:Pe??ye(o.id)}}),n.end();return}}if(n.destroyed)return;let re=we(H),M=Ke(re),B=Ne(p,z.size+M.length,x);if(B){o.streamError=!0,f("error",{error:{type:"api_error",message:Le(c,B)}}),n.end();return}Ae();let V=[];if(z.size===0)try{V=Ln(re)}catch(G){o.streamError=!0;let Q=ue(G,{inferenceId:o.id});Q.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(G instanceof Error?G.message:G)}`),f("error",{error:{type:"api_error",message:Q.message}}),n.end();return}I===0&&V.length===0&&(X("text",{type:"text",text:""}),Ae()),V.forEach(G=>{let Q=I++;f("content_block_start",{index:Q,content_block:{...G,input:{}}}),f("content_block_delta",{index:Q,delta:{type:"input_json_delta",partial_json:JSON.stringify(G.input??{})}}),f("content_block_stop",{index:Q})});let Te=z.size>0||V.length>0,Je=rn(re);He(o,re),f("message_delta",{delta:{stop_reason:Te?"tool_use":"end_turn"},usage:Je?{input_tokens:Je.input_tokens,output_tokens:Je.output_tokens}:{output_tokens:T}}),f("message_stop",{}),n.end();return}let k="",R="",y=[],g=new Ee;for await(let A of r.track(m,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=ze(A);if(T&&g.add(T),A.type==="error"){let x=A.error,I=x?.type==="invalid_request_error",w=be(x);w===null&&i(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(A)}`),_e(n,I?400:502,I?"invalid_request_error":"api_error",w??ye(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let h=we(y);He(o,h);let _;try{_=Ln(h),_.length===0&&g.size>0&&(_=Ln({output:g.items()}))}catch(A){let T=ue(A,{inferenceId:o.id});T.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(A instanceof Error?A.message:A)}`),_e(n,502,"api_error",T.message);return}let v=Ne(p,_.length,k);if(v){_e(n,502,"api_error",Le(c,v));return}let E=[],b=R||Co(h);b&&E.push({type:"thinking",thinking:b}),(k||_.length===0)&&E.push({type:"text",text:k}),E.push(..._),ne(n,200,{id:u,type:"message",role:"assistant",content:E,model:a,stop_reason:_.length>0?"tool_use":"end_turn",usage:rn(h)??{input_tokens:0,output_tokens:0}})}function Sa(t){De(process.stdout,t)}function ka(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,i=typeof e=="function"?e:()=>e,s=t.requestLog??Sa,a=t.operatorLog??(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,_):J(c,h,_,v,b),k=cn(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(dr,y.id),c.once("close",()=>{let h=mr({turn:y,method:d.method??"",path:p.pathname,res:c});s(hr(h)),u?.(h),Eo({record:h,ledger:t.ledger??null,req:d})}));let g=()=>cr(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===yo?"canonical":p.pathname===$n?"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 Io(d,_o)}catch(w){if(w instanceof Rt){f(413,w.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let x=w=>b.lookup(A,w),I;try{if(h==="canonical"){let w=wo(T),C=await x(w);nn(C,w),I={requests:C}}else I=await vo(T,x)}catch(w){if(w instanceof Oe){f(w.status,w.message,"invalid_request_error","invalid_request_error");return}throw w}ne(c,200,I);return}if(d.method==="GET"&&p.pathname===ut){let b=await i(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 ${$n} and GET ${ut}`,"invalid_request_error","not_found_error");return}let _=await i(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===qr){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(Fr(p.pathname)){if(!_.supportsImages){f(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let b={clients:_,imageModels:_.supportsImages,stats:l,turn:g(),operatorLog:a};p.pathname===Xt?await Yr(d,c,b):await zr(d,c,b);return}if(d.method==="GET"&&p.pathname===po){if(!_.listSpeechToTextModels){f(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ne(c,200,await _.listSpeechToTextModels());return}if(co(p.pathname)){if(!_.supportsTranscription){f(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${tn}`,"not_implemented","not_implemented_error");return}let b={clients:_,transcriptionModels:_.supportsTranscription,stats:l,turn:g(),operatorLog:a};await ho(d,c,b);return}if(io(p.pathname)){if(!_.supportsSpeech){f(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${vt}`,"not_implemented","not_implemented_error");return}let b={clients:_,speechModels:_.supportsSpeech,stats:l,turn:g(),operatorLog:a};await lo(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 Io(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 pa(v,_,pt(_),c,l,g(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",E,E),await fa(v,_,c,l,g(),d.headers[Rn],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",E,E),await ma(v,_,c,l,g(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",E,E),await ha(v,_,c,l,g(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",E,E),await ba(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 Qe){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
|
|
60
60
|
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:E.message}})}
|
|
61
61
|
|
|
62
62
|
`):c.write(`data: ${JSON.stringify({error:{message:E.message,type:"upstream_error",code:v}})}
|
|
63
63
|
|
|
64
|
-
`)),c.end()})}}function
|
|
64
|
+
`)),c.end()})}}function Lo(t){let{clients:e,apiKey:n}=t,r=(0,To.createServer)(ka(t)),o=br(r,{clients:e,apiKey:n,statusOf:t.statusOf,operatorLog:t.operatorLog}),i=yt(r,{resolver:Gt(e,n,t.realtimeCompanions),operatorLog:t.operatorLog}),s=r.close.bind(r);return r.close=(a=>(o.close(),i(),s(a))),Nt(r,{clients:e,apiKey:n}),r}0&&(module.exports={GEMINI_LIVE_PATH,OPENAI_REALTIME_PATH,OpenAIRealtimeConnection,ResumptionRegistry,SessionGoneError,UnknownModelError,VIDEO_OUT_SETUP_KEY,attachGeminiLive,attachOpenAIRealtime,createOpenAIProxy,fixedClientsResolver,realtimeBindingFor,realtimeModelOf,serveGeminiLiveSocket});
|