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