@urun-sh/openai 0.5.4 → 0.5.5

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/proxy/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as k,b as $,c as h,d as C,e as U,f as N,g as L,h as O,i as I,j as G,k as E,l as _,m,o as W,p as A,q as j,r as B,s as D,t as K,u as v,v as M,w as F,x as J}from"../chunk-RQBD4OAA.js";import"../chunk-K23AZPI4.js";import{b as T}from"../chunk-VNM4M4P3.js";import"../chunk-GBBY3PCZ.js";import"../chunk-4MSBS7M6.js";import"../chunk-5NXM4IO3.js";import{g as R}from"../chunk-CWJRDBDC.js";import"../chunk-OI2OY32M.js";import{c as w}from"../chunk-YSFSRI3D.js";w();import{spawn as Q}from"child_process";import{appendFileSync as H,createWriteStream as ae,existsSync as ie,mkdirSync as se}from"fs";import le from"path";import t from"process";w();import{ensureNodeWebRTC as re,nodeWebRTCUnavailableReason as ne}from"@urun-sh/core/internal";var oe={ensureWebRTC:re,webrtcUnavailableReason:ne,audioBackend:R};async function Y(e=oe){try{await e.ensureWebRTC()}catch(n){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(n)}`}}let i=e.webrtcUnavailableReason();if(i)return{ok:!1,reason:`${i} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(n){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(n)}`}}return{ok:!0,reason:null}}function ue(e,i){let n=(e.URUN_CATALOG_URL??"").trim(),l=n?W(n,"URUN_CATALOG_URL"):"",o=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!o?(i(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
2
+ import{a as k,b as $,c as h,d as C,e as U,f as N,g as L,h as O,i as I,j as G,k as E,l as _,m,o as W,p as A,q as j,r as B,s as D,t as K,u as v,v as M,w as F,x as J}from"../chunk-I2Q3B3OG.js";import"../chunk-K23AZPI4.js";import{g as T}from"../chunk-QVF7NF7G.js";import"../chunk-GBBY3PCZ.js";import"../chunk-DMD5UENK.js";import"../chunk-5NXM4IO3.js";import{g as R}from"../chunk-CWJRDBDC.js";import"../chunk-OI2OY32M.js";import{c as w}from"../chunk-YSFSRI3D.js";w();import{spawn as Q}from"child_process";import{appendFileSync as H,createWriteStream as ae,existsSync as ie,mkdirSync as se}from"fs";import le from"path";import t from"process";w();import{ensureNodeWebRTC as re,nodeWebRTCUnavailableReason as ne}from"@urun-sh/core/internal";var oe={ensureWebRTC:re,webrtcUnavailableReason:ne,audioBackend:R};async function Y(e=oe){try{await e.ensureWebRTC()}catch(n){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(n)}`}}let i=e.webrtcUnavailableReason();if(i)return{ok:!1,reason:`${i} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(n){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(n)}`}}return{ok:!0,reason:null}}function ue(e,i){let n=(e.URUN_CATALOG_URL??"").trim(),l=n?W(n,"URUN_CATALOG_URL"):"",o=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!o?(i(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
3
3
  `),null):{catalogUrl:l,anonKey:o}}function ce(e){return k({baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:ue(t.env,i=>t.stderr.write(i))})}async function V(e,i,n){let l=Q(e,i,{stdio:"inherit",env:n});return new Promise(o=>{l.once("exit",a=>o(a??1)),l.once("error",a=>{t.stderr.write(`failed to launch ${e}: ${String(a)}
4
4
  `),o(127)})})}function q(){return I(t.env,import.meta.url,ie)}function X(e){for(let[i,n]of Object.entries(C(e)))t.stdout.write(`export ${i}=${n}
5
5
  `)}async function z(e,i){let n=m(t.env),l=i?A(n):void 0,o=ce(n),a=T({clients:$(o),identity:l});try{await new Promise((s,d)=>{a.once("error",d),a.listen(e,"127.0.0.1",s)})}catch(s){throw await o.closeAll().catch(()=>{}),s.code==="EADDRINUSE"?new Error(J(e,await j(e))):s}let u=a.address().port;return i&&(t.stdout.write(`urun openai proxy listening on http://127.0.0.1:${u}/v1
@@ -1,41 +1,50 @@
1
- "use strict";var _e=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var it=Object.prototype.hasOwnProperty;var at=(e,n)=>{for(var t in n)_e(e,t,{get:n[t],enumerable:!0})},ut=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of st(n))!it.call(e,r)&&r!==t&&_e(e,r,{get:()=>n[r],enumerable:!(o=rt(n,r))||o.enumerable});return e};var ct=e=>ut(_e({},"__esModule",{value:!0}),e);var qt={};at(qt,{GEMINI_LIVE_PATH:()=>fe,VIDEO_OUT_SETUP_KEY:()=>j,createOpenAIProxy:()=>ot});module.exports=ct(qt);var tt=require("http");var ze=require("crypto"),Ye=require("ws");var q=class extends Error{},re=class extends Error{};var le=require("@urun-sh/core");var Ce="urun.videoOut.v2-ws";var fe="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",pt=1007,Le=1008,J=1011,ke=1008,a=class extends Error{constructor(t,o=pt){super(t);this.closeCode=o}closeCode},R=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,de=["setup","clientContent","realtimeInput","toolResponse"];function $e(e){let n;try{n=JSON.parse(e)}catch{throw new a("client message is not valid JSON")}let t=R(n);if(!t)throw new a("client message must be a JSON object");let o=de.filter(l=>t[l]!==void 0),r=Object.keys(t).filter(l=>!de.includes(l));if(r.length>0)throw new a(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${de.join(", ")}`);if(o.length!==1)throw new a(`client message must contain exactly one of ${de.join(", ")} (got ${o.length})`);let s=o[0],i=R(t[s]);if(!i)throw new a(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Ne(e,n){if(typeof e=="string")return e;let t=R(e),o=t?t.parts:void 0;if(!Array.isArray(o))throw new a(`${n}: expected a Content with a parts array`);let r=[];for(let s of o){let i=R(s);if(i&&typeof i.text=="string"){r.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new a(`${n}: 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 a(`${n}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new a(`${n}: unsupported part ${JSON.stringify(s)}`)}return r.join(`
2
- `)}var ft={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},j="urun.videoOut";function Me(e){return{framing:Ce,codec:e}}function Ue(e){let{seq:n,ptsUs:t,codec:o,key:r}=e.header;return{[j]:{v:1,seq:n,ptsUs:t,codec:o,key:r,data:Buffer.from(e.au).toString("base64")}}}var mt={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},gt=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",j],Pe=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function ht(e){let n=R(e);if(!n)throw new a("setup.realtimeInputConfig must be an object");for(let r of Object.keys(n))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new a(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let t=R(n.automaticActivityDetection);if(n.automaticActivityDetection!==void 0&&!t)throw new a("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(t??{}))if(r!=="disabled")throw new a(`automaticActivityDetection.${r} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(t?.disabled!==!0)throw new a("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let o="START_OF_ACTIVITY_INTERRUPTS";if(n.activityHandling!==void 0){if(!Pe.includes(n.activityHandling))throw new a(`unsupported activityHandling ${JSON.stringify(n.activityHandling)} \u2014 expected one of ${Pe.join(", ")}`);o=n.activityHandling}return{manualActivity:!0,activityHandling:o}}var yt=["temperature","maxOutputTokens","responseModalities"];function De(e){for(let[f,m]of Object.entries(mt))if(e[f]!==void 0)throw new a(m);for(let f of Object.keys(e))if(!gt.includes(f))throw new a(`unsupported setup field "${f}"`);if(typeof e.model!="string"||e.model.length===0)throw new a('setup.model is required (format "models/{model}")');let n=e.model.replace(/^models\//,""),t,o,r=!1,s=R(e.generationConfig);if(e.generationConfig!==void 0&&!s)throw new a("setup.generationConfig must be an object");if(s){for(let f of Object.keys(s))if(!yt.includes(f))throw new a(`unsupported generationConfig field "${f}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new a("generationConfig.temperature must be a number");t=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new a("generationConfig.maxOutputTokens must be a number");o=s.maxOutputTokens}if(s.responseModalities!==void 0){let f=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let m of f){let h=String(m).toUpperCase();if(h==="AUDIO"){r=!0;continue}if(h!=="TEXT")throw new a(`responseModalities ${JSON.stringify(m)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge rt-audio-out lane)`)}}}let i=[];e.systemInstruction!==void 0&&i.push({role:"system",content:Ne(e.systemInstruction,"setup.systemInstruction")});let l;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new a("setup.tools must be an array");l=[];for(let f of e.tools){let m=R(f);if(!m)throw new a("setup.tools entries must be objects");for(let h of Object.keys(m))if(h!=="functionDeclarations")throw new a(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(m.functionDeclarations))throw new a("tool.functionDeclarations must be an array");for(let h of m.functionDeclarations){let y=R(h);if(!y||typeof y.name!="string")throw new a("functionDeclarations entries require a string name");l.push({type:"function",name:y.name,description:y.description,parameters:y.parameters})}}l.length===0&&(l=void 0)}let g={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let f=R(e.sessionResumption);if(!f)throw new a("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let m of Object.keys(f))if(m!=="handle")throw new a(`unsupported sessionResumption field "${m}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(f.handle!==void 0&&(typeof f.handle!="string"||f.handle.length===0))throw new a("sessionResumption.handle must be a non-empty string when present");g={enabled:!0,handle:typeof f.handle=="string"?f.handle:null}}let d=e.realtimeInputConfig===void 0?ft:ht(e.realtimeInputConfig),p=!1;if(e[j]!==void 0){if(!R(e[j]))throw new a(`setup["${j}"] must be an object (the v1 opt-in is {})`);p=!0}return{model:n,systemItems:i,tools:l,temperature:t,maxOutputTokens:o,audioModality:r,activity:d,sessionResumption:g,videoOut:p}}function Ve(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function Be(e){let n=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(n*1e3)/1e3}s`}}}function He(e){for(let o of Object.keys(e))if(o!=="turns"&&o!=="turnComplete")throw new a(`unsupported clientContent field "${o}"`);let n=e.turns===void 0?[]:e.turns;if(!Array.isArray(n))throw new a("clientContent.turns must be an array");let t=[];for(let o of n){let r=R(o);if(!r)throw new a("clientContent.turns entries must be Content objects");let s=r.role===void 0?"user":String(r.role).toLowerCase();if(s!=="user"&&s!=="model")throw new a(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);t.push({role:s==="model"?"assistant":"user",content:Ne(r,"clientContent.turns")})}return{items:t,turnComplete:e.turnComplete===!0}}var pe=16e3,Fe=24e3,wt=`audio/pcm;rate=${Fe}`,qe=Buffer.alloc(960).toString("base64");function _t(e,n,t){if(n===t)return e;let o=Math.floor(e.length*t/n),r=new Int16Array(o),s=n/t,i=e.length-1;for(let l=0;l<o;l++){let g=l*s,d=Math.floor(g);if(d>=i){r[l]=e[i];continue}let p=g-d;r[l]=Math.round(e[d]+(e[d+1]-e[d])*p)}return r}function kt(e){let n=R(e);if(!n)throw new a("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(n.mimeType))throw new a(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(n.mimeType)}`);if(typeof n.data!="string"||n.data.length===0)throw new a("realtimeInput.video.data must be non-empty base64");let t=Buffer.from(n.data,"base64");if(t.length<3||t[0]!==255||t[1]!==216)throw new a("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(t)}function vt(e){let n=R(e);if(!n)throw new a("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(n.mimeType))throw new a(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(n.mimeType)}`);let t=/;\s*rate=(\d+)/.exec(n.mimeType);if(t&&Number(t[1])!==pe)throw new a(`realtimeInput.audio.mimeType declares rate=${t[1]} \u2014 the Live spec input format is ${pe} Hz (audio/pcm;rate=${pe})`);if(typeof n.data!="string"||n.data.length===0)throw new a("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(n.data,"base64");if(o.length===0||o.length%2!==0)throw new a(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let r=new Int16Array(o.length/2);for(let i=0;i<r.length;i++)r[i]=o.readInt16LE(i*2);let s=_t(r,pe,Fe);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function je(e){if(e.mediaChunks!==void 0)throw new a('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(e.activityStart!==void 0||e.activityEnd!==void 0){if(Object.keys(e).length!==1||e.activityStart!==void 0&&e.activityEnd!==void 0)throw new a("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let r=e.activityStart!==void 0?"activityStart":"activityEnd",s=R(e[r]);if(!s||Object.keys(s).length!==0)throw new a(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let n=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(e))if(!n.includes(o))throw new a(`unsupported realtimeInput field "${o}"`);let t=n.filter(o=>e[o]!==void 0);if(t.length!==1)throw new a(`realtimeInput must carry exactly one of ${n.join(", ")} (got ${t.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:vt(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:kt(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new a("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new a("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function Je(e){for(let n of Object.keys(e))if(n!=="functionResponses")throw new a(`unsupported toolResponse field "${n}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new a("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(n=>{let t=R(n);if(!t||typeof t.id!="string"||t.id.length===0)throw new a("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:t.id,output:JSON.stringify(t.response??null)}})}function We(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function Ge(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:wt,data:e}}]}}}}function Ke(e){let n=R(e)??{},t=Array.isArray(n.output)?n.output:[],o=[],r=[],s=typeof n.output_text=="string"?n.output_text:"";if(!s)for(let d of t){let p=R(d);if(!(p?.type!=="message"||!Array.isArray(p.content)))for(let f of p.content){let m=R(f);m?.type==="output_text"&&typeof m.text=="string"&&(s+=m.text)}}s&&r.push({role:"assistant",content:s});for(let d of t){let p=R(d);if(p?.type!=="function_call")continue;if(typeof p.call_id!="string"||typeof p.name!="string")throw new a(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,J);let f=typeof p.arguments=="string"&&p.arguments.length>0?p.arguments:"{}",m;try{m=JSON.parse(f)}catch{throw new a(`upstream function_call arguments are not valid JSON: ${f}`,J)}o.push({id:p.call_id,name:p.name,args:m}),r.push({type:"function_call",call_id:p.call_id,name:p.name,arguments:f})}let i=[];o.length>0&&i.push({toolCall:{functionCalls:o}}),i.push({serverContent:{generationComplete:!0}});let l=R(n.usage),g={serverContent:{turnComplete:!0}};if(l){let d={};typeof l.input_tokens=="number"&&(d.promptTokenCount=l.input_tokens),typeof l.output_tokens=="number"&&(d.responseTokenCount=l.output_tokens),typeof l.total_tokens=="number"&&(d.totalTokenCount=l.total_tokens),Object.keys(d).length>0&&(g.usageMetadata=d)}return i.push(g),{messages:i,assistantItems:r}}var xt=256,ve=class{snapshots=new Map;store(n,t){for(this.snapshots.set(n,t);this.snapshots.size>xt;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(n){return this.snapshots.get(n)}},se=e=>e.slice(0,120),xe=class{constructor(n,t,o){this.ws=n;this.clients=t;this.registry=o;n.on("message",r=>this.onMessage(r)),n.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.()})}ws;clients;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;send(n){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(n))}fail(n){if(n instanceof q){this.ws.close(Le,se(n.message));return}if(n instanceof re){this.ws.close(ke,se(n.message));return}if(n instanceof a){this.ws.close(n.closeCode,se(n.message));return}this.ws.close(J,se(String(n instanceof Error?n.message:n)))}onMessage(n){try{let t=$e(typeof n=="string"?n:Buffer.concat(Array.isArray(n)?n:[n]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(r=>this.fail(r));return}if(!this.config)throw new a(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(t.kind==="clientContent"){let{items:r,turnComplete:s}=He(t.clientContent);this.transcript.push(...r),s&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let r=je(t.realtimeInput);if(r.kind==="activityStart"||r.kind==="activityEnd"){this.onActivity(r.kind,o);return}if(r.kind==="text"){this.transcript.push({role:"user",content:r.text}),this.enqueue(()=>this.runTurn());return}if(r.kind==="video"){this.appendVideoFrame(r.jpegFrame);return}this.appendAudio(r.kind==="audio"?r.base64Pcm24k:qe);return}this.transcript.push(...Je(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(n){if(this.config)throw new a("setup may only be sent once, as the first client message");let t=De(n),o=t.sessionResumption.handle;if(o!==null){let s=this.registry.get(o);if(!s)throw new a("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",ke);if(s.model!==t.model)throw new a(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new a("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");this.transcript=[...s.transcript],this.proxyHandle=s.proxyHandle,this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i)))}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...t.systemItems);this.config=t;let r={};if(t.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,t.model),l=i.onOutputFrame(d=>this.send(Ue(d))),g=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{l(),g()},r[j]=Me(i.codec)}}this.send({setupComplete:r}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let n=this.config;if(!n)throw new a("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new a("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",J);return this.audio=(async()=>{let o=await t.call(this.clients,n.model);return this.detachAudio=o.onOutputAudio(r=>this.send(Ge(r))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(n){this.ensureAudioLane().then(t=>t.appendInputAudio(n)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let n=this.config;if(!n)throw new a("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new a("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",J);return this.video=Promise.resolve(t.call(this.clients,n.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(n){this.ensureVideoLane().then(t=>t.sendInputFrame(n)).catch(t=>this.fail(t))}onActivity(n,t){if(!t.activity.manualActivity)throw new a(`realtimeInput.${n} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(n==="activityStart"){if(this.activityOpen)throw new a("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new a("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(n){this.queue=this.queue.then(n,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let n=this.config;if(!n?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(n.model);this.proxyHandle=t;let o=(0,ze.randomUUID)();this.registry.store(o,{model:n.model,proxyHandle:t,transcript:[...this.transcript]}),this.send(Ve(o))}async handleUpstreamEnd(n){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Be(n.timeLeftMs)),this.ws.close(J,se(`upstream session ended: ${n.reason}`))}async runTurn(){let n=this.config;if(!n||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let o=await this.clients.createResponse({model:n.model,input:[...this.transcript],stream:!0,tools:n.tools,temperature:n.temperature,max_output_tokens:n.maxOutputTokens}),r,s=!1;for await(let g of o){if(t.interrupted)break;let d=g;if(d.type==="error")throw new a(`upstream error: ${JSON.stringify(d)}`,J);if(d.type==="response.completed"){r=d.response,s=!0;continue}let p=We(d);p&&this.send(p)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new a("upstream produced no response.completed event",J);let{messages:i,assistantItems:l}=Ke(r);this.transcript.push(...l);for(let g of i)this.send(g);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},bt=(e,n)=>{let t=e.headers["x-goog-api-key"];if(typeof t=="string")return t;let o=e.headers.authorization;return typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):n.searchParams.get("key")??void 0};function Xe(e,n){let t=new Ye.WebSocketServer({noServer:!0}),o=new ve;e.on("upgrade",(r,s,i)=>{let l=new URL(r.url??"/","http://localhost");if(l.pathname!==fe){s.write(`HTTP/1.1 404 Not Found\r
1
+ "use strict";var He=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var qt=Object.prototype.hasOwnProperty;var Ht=(n,e)=>{for(var t in e)He(n,t,{get:e[t],enumerable:!0})},Jt=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jt(e))!qt.call(n,s)&&s!==t&&He(n,s,{get:()=>e[s],enumerable:!(o=Vt(e,s))||o.enumerable});return n};var Wt=n=>Jt(He({},"__esModule",{value:!0}),n);var Hn={};Ht(Hn,{GEMINI_LIVE_PATH:()=>Ee,OPENAI_REALTIME_PATH:()=>qe,OpenAIRealtimeConnection:()=>le,ResumptionRegistry:()=>pe,SessionGoneError:()=>X,UnknownModelError:()=>V,VIDEO_OUT_SETUP_KEY:()=>Q,attachGeminiLive:()=>Pe,attachOpenAIRealtime:()=>it,createOpenAIProxy:()=>Nt,serveGeminiLiveSocket:()=>Ot});module.exports=Wt(Hn);var Lt=require("http");var At=require("crypto"),St=require("ws");var V=class extends Error{},X=class extends Error{};var Se=require("@urun-sh/core");var at="urun.videoOut.v2-ws";var Ee="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Kt=1007,dt=1008,Z=1011,Te=1008,m=class extends Error{constructor(t,o=Kt){super(t);this.closeCode=o}closeCode},E=n=>typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null,Oe=["setup","clientContent","realtimeInput","toolResponse"];function lt(n){let e;try{e=JSON.parse(n)}catch{throw new m("client message is not valid JSON")}let t=E(e);if(!t)throw new m("client message must be a JSON object");let o=Oe.filter(a=>t[a]!==void 0),s=Object.keys(t).filter(a=>!Oe.includes(a));if(s.length>0)throw new m(`unknown client message field(s) ${JSON.stringify(s)} \u2014 expected exactly one of ${Oe.join(", ")}`);if(o.length!==1)throw new m(`client message must contain exactly one of ${Oe.join(", ")} (got ${o.length})`);let i=o[0],r=E(t[i]);if(!r)throw new m(`"${i}" must be a JSON object`);return{kind:i,[i]:r}}function ct(n,e){if(typeof n=="string")return n;let t=E(n),o=t?t.parts:void 0;if(!Array.isArray(o))throw new m(`${e}: expected a Content with a parts array`);let s=[];for(let i of o){let r=E(i);if(r&&typeof r.text=="string"){s.push(r.text);continue}throw r&&(r.inlineData!==void 0||r.fileData!==void 0)?new m(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):r&&(r.functionCall!==void 0||r.functionResponse!==void 0)?new m(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new m(`${e}: unsupported part ${JSON.stringify(i)}`)}return s.join(`
2
+ `)}var Yt={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Q="urun.videoOut";function pt(n){return{framing:at,codec:n}}function ft(n){let{seq:e,ptsUs:t,codec:o,key:s}=n.header;return{[Q]:{v:1,seq:e,ptsUs:t,codec:o,key:s,data:Buffer.from(n.au).toString("base64")}}}var Xt={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Qt=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Q],ut=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Zt(n){let e=E(n);if(!e)throw new m("setup.realtimeInputConfig must be an object");for(let s of Object.keys(e))if(!(s==="automaticActivityDetection"||s==="activityHandling"))throw new m(s==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${s}"`);let t=E(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!t)throw new m("realtimeInputConfig.automaticActivityDetection must be an object");for(let s of Object.keys(t??{}))if(s!=="disabled")throw new m(`automaticActivityDetection.${s} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(t?.disabled!==!0)throw new m("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let o="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!ut.includes(e.activityHandling))throw new m(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${ut.join(", ")}`);o=e.activityHandling}return{manualActivity:!0,activityHandling:o}}var en=["temperature","maxOutputTokens","responseModalities"];function mt(n){for(let[l,f]of Object.entries(Xt))if(n[l]!==void 0)throw new m(f);for(let l of Object.keys(n))if(!Qt.includes(l))throw new m(`unsupported setup field "${l}"`);if(typeof n.model!="string"||n.model.length===0)throw new m('setup.model is required (format "models/{model}")');let e=n.model.replace(/^models\//,""),t,o,s=!1,i=E(n.generationConfig);if(n.generationConfig!==void 0&&!i)throw new m("setup.generationConfig must be an object");if(i){for(let l of Object.keys(i))if(!en.includes(l))throw new m(`unsupported generationConfig field "${l}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new m("generationConfig.temperature must be a number");t=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new m("generationConfig.maxOutputTokens must be a number");o=i.maxOutputTokens}if(i.responseModalities!==void 0){let l=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let f of l){let h=String(f).toUpperCase();if(h==="AUDIO"){s=!0;continue}if(h!=="TEXT")throw new m(`responseModalities ${JSON.stringify(f)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge rt-audio-out lane)`)}}}let r=[];n.systemInstruction!==void 0&&r.push({role:"system",content:ct(n.systemInstruction,"setup.systemInstruction")});let a;if(n.tools!==void 0){if(!Array.isArray(n.tools))throw new m("setup.tools must be an array");a=[];for(let l of n.tools){let f=E(l);if(!f)throw new m("setup.tools entries must be objects");for(let h of Object.keys(f))if(h!=="functionDeclarations")throw new m(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new m("tool.functionDeclarations must be an array");for(let h of f.functionDeclarations){let w=E(h);if(!w||typeof w.name!="string")throw new m("functionDeclarations entries require a string name");a.push({type:"function",name:w.name,description:w.description,parameters:w.parameters})}}a.length===0&&(a=void 0)}let d={enabled:!1,handle:null};if(n.sessionResumption!==void 0){let l=E(n.sessionResumption);if(!l)throw new m("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(l))if(f!=="handle")throw new m(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(l.handle!==void 0&&(typeof l.handle!="string"||l.handle.length===0))throw new m("sessionResumption.handle must be a non-empty string when present");d={enabled:!0,handle:typeof l.handle=="string"?l.handle:null}}let u=n.realtimeInputConfig===void 0?Yt:Zt(n.realtimeInputConfig),c=!1;if(n[Q]!==void 0){if(!E(n[Q]))throw new m(`setup["${Q}"] must be an object (the v1 opt-in is {})`);c=!0}return{model:e,systemItems:r,tools:a,temperature:t,maxOutputTokens:o,audioModality:s,activity:u,sessionResumption:d,videoOut:c}}function ht(n){return{sessionResumptionUpdate:{newHandle:n,resumable:!0}}}function gt(n){let e=Math.max(0,n??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function yt(n){for(let o of Object.keys(n))if(o!=="turns"&&o!=="turnComplete")throw new m(`unsupported clientContent field "${o}"`);let e=n.turns===void 0?[]:n.turns;if(!Array.isArray(e))throw new m("clientContent.turns must be an array");let t=[];for(let o of e){let s=E(o);if(!s)throw new m("clientContent.turns entries must be Content objects");let i=s.role===void 0?"user":String(s.role).toLowerCase();if(i!=="user"&&i!=="model")throw new m(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(s.role)})`);t.push({role:i==="model"?"assistant":"user",content:ct(s,"clientContent.turns")})}return{items:t,turnComplete:n.turnComplete===!0}}var Ie=16e3,_t=24e3,tn=`audio/pcm;rate=${_t}`,wt=Buffer.alloc(960).toString("base64");function nn(n,e,t){if(e===t)return n;let o=Math.floor(n.length*t/e),s=new Int16Array(o),i=e/t,r=n.length-1;for(let a=0;a<o;a++){let d=a*i,u=Math.floor(d);if(u>=r){s[a]=n[r];continue}let c=d-u;s[a]=Math.round(n[u]+(n[u+1]-n[u])*c)}return s}function on(n){let e=E(n);if(!e)throw new m("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new m(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new m("realtimeInput.video.data must be non-empty base64");let t=Buffer.from(e.data,"base64");if(t.length<3||t[0]!==255||t[1]!==216)throw new m("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(t)}function sn(n){let e=E(n);if(!e)throw new m("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new m(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let t=/;\s*rate=(\d+)/.exec(e.mimeType);if(t&&Number(t[1])!==Ie)throw new m(`realtimeInput.audio.mimeType declares rate=${t[1]} \u2014 the Live spec input format is ${Ie} Hz (audio/pcm;rate=${Ie})`);if(typeof e.data!="string"||e.data.length===0)throw new m("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(e.data,"base64");if(o.length===0||o.length%2!==0)throw new m(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let s=new Int16Array(o.length/2);for(let r=0;r<s.length;r++)s[r]=o.readInt16LE(r*2);let i=nn(s,Ie,_t);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function vt(n){if(n.mediaChunks!==void 0)throw new m('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(n.activityStart!==void 0||n.activityEnd!==void 0){if(Object.keys(n).length!==1||n.activityStart!==void 0&&n.activityEnd!==void 0)throw new m("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let s=n.activityStart!==void 0?"activityStart":"activityEnd",i=E(n[s]);if(!i||Object.keys(i).length!==0)throw new m(`realtimeInput.${s} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:s}}let e=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(n))if(!e.includes(o))throw new m(`unsupported realtimeInput field "${o}"`);let t=e.filter(o=>n[o]!==void 0);if(t.length!==1)throw new m(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${t.length})`);if(n.audio!==void 0)return{kind:"audio",base64Pcm24k:sn(n.audio)};if(n.video!==void 0)return{kind:"video",jpegFrame:on(n.video)};if(n.audioStreamEnd!==void 0){if(n.audioStreamEnd!==!0)throw new m("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof n.text!="string"||n.text.length===0)throw new m("realtimeInput.text must be a non-empty string");return{kind:"text",text:n.text}}function kt(n){for(let e of Object.keys(n))if(e!=="functionResponses")throw new m(`unsupported toolResponse field "${e}"`);if(!Array.isArray(n.functionResponses)||n.functionResponses.length===0)throw new m("toolResponse.functionResponses must be a non-empty array");return n.functionResponses.map(e=>{let t=E(e);if(!t||typeof t.id!="string"||t.id.length===0)throw new m("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:t.id,output:JSON.stringify(t.response??null)}})}function bt(n){return n.type!=="response.output_text.delta"||typeof n.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:n.delta}]}}}}function xt(n){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:tn,data:n}}]}}}}function Rt(n){let e=E(n)??{},t=Array.isArray(e.output)?e.output:[],o=[],s=[],i=typeof e.output_text=="string"?e.output_text:"";if(!i)for(let u of t){let c=E(u);if(!(c?.type!=="message"||!Array.isArray(c.content)))for(let l of c.content){let f=E(l);f?.type==="output_text"&&typeof f.text=="string"&&(i+=f.text)}}i&&s.push({role:"assistant",content:i});for(let u of t){let c=E(u);if(c?.type!=="function_call")continue;if(typeof c.call_id!="string"||typeof c.name!="string")throw new m(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,Z);let l=typeof c.arguments=="string"&&c.arguments.length>0?c.arguments:"{}",f;try{f=JSON.parse(l)}catch{throw new m(`upstream function_call arguments are not valid JSON: ${l}`,Z)}o.push({id:c.call_id,name:c.name,args:f}),s.push({type:"function_call",call_id:c.call_id,name:c.name,arguments:l})}let r=[];o.length>0&&r.push({toolCall:{functionCalls:o}}),r.push({serverContent:{generationComplete:!0}});let a=E(e.usage),d={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(d.usageMetadata=u)}return r.push(d),{messages:r,assistantItems:s}}var rn=256,pe=class{snapshots=new Map;store(e,t,o){for(this.snapshots.set(`${e}\0${t}`,o);this.snapshots.size>rn;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},an="local",we=n=>n.slice(0,120),Ce=class{constructor(e,t,o){this.ws=e;this.call=t;this.registry=o;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof V){this.ws.close(dt,we(e.message));return}if(e instanceof X){this.ws.close(Te,we(e.message));return}if(e instanceof m){this.ws.close(e.closeCode,we(e.message));return}this.ws.close(Z,we(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=lt(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new m(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:i}=yt(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=vt(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,o);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:wt);return}this.transcript.push(...kt(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new m("setup may only be sent once, as the first client message");let t=mt(e),o=t.sessionResumption.handle;if(o!==null){let i=this.registry.get(this.scope,o);if(!i)throw new m("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Te);if(i.model!==t.model)throw new m(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new m("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(o)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new m(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Te);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let r=await i.call(this.clients,t.model),a=r.onOutputFrame(u=>this.send(ft(u))),d=r.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),d()},s[Q]=pt(r.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new m("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new m("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",Z);return this.audio=(async()=>{let o=await t.call(this.clients,e.model);return this.detachAudio=o.onOutputAudio(s=>this.send(xt(s))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new m("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new m("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Z);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new m(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new m("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new m("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let o=(0,At.randomUUID)();this.registry.store(this.scope,o,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(o),this.send(ht(o))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(gt(e.timeLeftMs)),this.ws.close(Z,we(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let o=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,i=!1;for await(let d of o){if(t.interrupted)break;let u=d;if(u.type==="error")throw new m(`upstream error: ${JSON.stringify(u)}`,Z);if(u.type==="response.completed"){s=u.response,i=!0;continue}let c=bt(u);c&&this.send(c)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new m("upstream produced no response.completed event",Z);let{messages:r,assistantItems:a}=Rt(s);this.transcript.push(...a);for(let d of r)this.send(d);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},ie=class extends Error{constructor(t,o){super(o);this.status=t;this.name="UpgradeAuthError"}status};function un(n,e,t){let o=new Set;(d=>{if(typeof d=="string")d!==""&&o.add(d);else if(Array.isArray(d))for(let u of d)u!==""&&o.add(u)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&o.add(i.slice(7));let r=e.searchParams.get("key")??void 0;if(r!==void 0&&r!==""&&o.add(r),o.size>1)throw new ie(401,`contradictory credentials: ${o.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&r!==void 0&&r!=="")throw new ie(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let d of o)a=d;if(a===void 0&&t)throw new ie(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Pe(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let o=new St.WebSocketServer({noServer:!0}),s=new pe;n.on("upgrade",(r,a,d)=>{let u=new URL(r.url??"/","http://localhost");u.pathname===Ee&&(a.on("error",()=>{}),(async()=>{let c=un(r,u,t),l;if(e.authenticate)l=await e.authenticate(c,r);else{if(e.apiKey!==void 0&&c!==e.apiKey)throw new ie(401,"invalid local proxy api key");l={clients:e.clients,scope:an}}o.handleUpgrade(r,a,d,f=>{new Ce(f,l,s)})})().catch(c=>{let l=502;(c instanceof ie||typeof c=="object"&&c!==null&&"status"in c&&typeof c.status=="number")&&(l=c.status);let f=l===401?"Unauthorized":l===403?"Forbidden":l===502?"Bad Gateway":"Internal Server Error",h=c instanceof Error?c.message:String(c);a.destroyed||(a.write(`HTTP/1.1 ${l} ${f}\r
3
3
  Connection: close\r
4
4
  \r
5
- no WS route for ${l.pathname}`),s.destroy();return}if(n.apiKey&&bt(r,l)!==n.apiKey){s.write(`HTTP/1.1 401 Unauthorized\r
5
+ ${h}\r
6
+ `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let r of o.clients)r.close(1001,"server closing");await new Promise((r,a)=>o.close(d=>d===void 0?r():a(d)))})(),i)}function Ot(n,e,t=new pe){new Ce(n,e,t)}var oe=require("ws");function me(n){return typeof n.model!="string"||!n.model.trim()?"(default)":n.model.trim().slice(0,128)}var re=class n{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,t,o){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=t,this.naiveInBytes+=o}modelEntry(e){let t=this.models[e];if(t)return t;let o=Object.keys(this.models).length>=256?"(other)":e;return this.models[o]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,t){let o=this,s=performance.now(),i=null,r=0;return(async function*(){for await(let d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift()),r+=1,o.tokensOut+=1,o.charsOut+=d.delta.length,t!==void 0&&(o.modelEntry(t).tokens_out+=1)),yield d;let a=(performance.now()-(i??s))/1e3;r>0&&a>0&&(o.tokRates.push(r/a),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let t=[...e].sort((o,s)=>o-s);return t[Math.floor(t.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((t,o)=>t+o,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:n.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:n.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},dn=256;function ln(n){if(typeof n=="string")return[{role:"user",content:n}];if(Array.isArray(n))return n;throw new Error("responses input must be a string or an array of messages/items")}var ae=class extends Error{},fe=class{conversations=new Map;thread(e,t){let o=ln(t);if(e==null)return o;let s=this.conversations.get(String(e));if(!s)throw new ae(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...s,...o]}remember(e,t,o,s=!0){this.conversations.set(e,[...t,...o]);for(let i of this.conversations.keys()){if(this.conversations.size<=dn)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},It=new WeakMap;function ve(n){let e=It.get(n);return e||(e=new fe,It.set(n,e)),e}function he(n){let e=n?.output;return Array.isArray(e)?e.filter(t=>t.type==="function_call"):[]}function ne(n){return n.find(e=>e.type==="response.completed")?.response??null}function ge(n){return n.type!=="response.function_call_arguments.delta"||typeof n.tool_index!="number"?null:{tool_index:n.tool_index,call_id:typeof n.call_id=="string"?n.call_id:void 0,name:typeof n.name=="string"?n.name:void 0,delta:typeof n.delta=="string"?n.delta:""}}var te=class{calls=new Map;add(e){let t=this.calls.get(e.tool_index),o=!t;return t||(t={args:""},this.calls.set(e.tool_index,t)),e.call_id&&(t.id=e.call_id),e.name&&(t.name=e.name),t.args+=e.delta,{call:t,isNew:o}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,t])=>({type:"function_call",call_id:t.id??`call_${e}`,name:t.name??"",arguments:t.args}))}},cn=["<tool_call>","<function="];function pn(n){return cn.find(e=>n.includes(e))}function ue(n,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${n}" (see catalog parser_defaults)`}function de(n,e,t){if(!(!n||e>0))return pn(t)}function Je(n,e){let t=e?.output_text;return typeof t=="string"?t:n.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}function fn(n){let e=n?.output;if(!Array.isArray(e))return[];let t=[];for(let o of e){if(o===null||typeof o!="object")continue;let s=o;s.type==="message"?t.push({role:"assistant",content:s.content??""}):s.type==="function_call"&&t.push({type:"function_call",call_id:s.call_id,name:s.name,arguments:s.arguments})}return t}function We(n,e){let t=fn(n);return t.length>0?t:e?[{role:"assistant",content:e}]:[]}var H=class extends Error{constructor(t,o,s=400,i){super(t);this.code=o;this.status=s;this.param=i}code;status;param};function ye(n,e){try{return n.thread(e.previous_response_id,e.input)}catch(t){throw t instanceof ae?new H(t.message,"previous_response_not_found",400,"previous_response_id"):new H(String(t instanceof Error?t.message:t),"invalid_input")}}async function Ge(n,e,t,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new H("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return n.createResponse({model:e.model,input:t,stream:o,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{}})}async function ke(n){let{body:e,clients:t,store:o,stats:s}=n,i=ye(o,e);e.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let r=`resp_${Math.random().toString(36).slice(2,14)}`,a=n.remember??e.store!==!1,d=e.store!==!1,u=me(e);s.model(u);let c=Array.isArray(e.tools)&&e.tools.length>0,l=await Ge(t,e,i,!0);return{responseId:r,events:mn({events:l,conversation:i,responseId:r,modelKey:u,requestHadTools:c,remember:a,persist:d,store:o,stats:s})}}async function*mn(n){let{events:e,conversation:t,responseId:o,modelKey:s,requestHadTools:i,remember:r,persist:a,store:d,stats:u}=n,c=[],l=b=>b.response&&typeof b.response=="object"?{...b,response:{...b.response,id:o}}:b,f=`item_${o.slice(5)}`,h=`rs_${o.slice(5)}`,w=!1,v=!1,y=0;function*x(){w||(w=!0,yield{type:"response.created",response:{id:o,object:"response",status:"in_progress"}})}let R=!1,U=0,T="";function*N(){R&&(R=!1,yield{type:"response.reasoning_text.done",item_id:h,output_index:U,content_index:0,text:T},yield{type:"response.output_item.done",output_index:U,item:{id:h,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:T}],status:"completed"}})}let p=!1,k=0,L="";function*I(b){p&&(p=!1,yield{type:"response.output_text.done",item_id:f,output_index:k,content_index:0,text:L},yield{type:"response.content_part.done",item_id:f,output_index:k,content_index:0,part:{type:"output_text",text:L}},yield{type:"response.output_item.done",output_index:k,item:{id:f,type:"message",role:"assistant",status:b,content:[{type:"output_text",text:L}]}})}let D=new te,C=null,G=-1;function*$(b){if(!C)return;let S=C;C=null,yield{type:"response.function_call_arguments.done",item_id:S.fcId,output_index:S.outputIndex,arguments:S.args},yield{type:"response.output_item.done",output_index:S.outputIndex,item:{id:S.fcId,type:"function_call",call_id:S.callId??S.fcId,name:S.name??"",arguments:S.args,status:b}}}let B=!1;for await(let b of u.track(e,s)){c.push(b);let S=String(b.type??"");if(S==="response.created"||S==="response.in_progress"){w=!0,yield l(b);continue}if(S==="response.output_item.added"){v=!0,yield l(b);continue}if(S==="response.reasoning_text.delta"&&!v){yield*x(),R||(R=!0,U=y++,yield{type:"response.output_item.added",output_index:U,item:{id:h,type:"reasoning",summary:[],content:[],status:"in_progress"}}),T+=String(b.delta??""),yield{type:"response.reasoning_text.delta",item_id:h,output_index:U,content_index:0,delta:b.delta};continue}if(S==="response.output_text.delta"&&!v){yield*x(),yield*N(),p||(p=!0,k=y++,yield{type:"response.output_item.added",output_index:k,item:{id:f,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:f,output_index:k,content_index:0,part:{type:"output_text",text:""}}),L+=String(b.delta??""),yield{type:S,item_id:f,output_index:k,content_index:0,delta:b.delta};continue}let P=v?null:ge(b);if(P){if(yield*x(),yield*N(),yield*I("completed"),D.add(P),P.tool_index!==G){yield*$("completed"),G=P.tool_index;let Y=y++;C={fcId:`fc_${o.slice(5)}_${P.tool_index}`,outputIndex:Y,callId:P.call_id,name:P.name,args:""},yield{type:"response.output_item.added",output_index:Y,item:{id:C.fcId,type:"function_call",call_id:C.callId??C.fcId,name:C.name??"",arguments:"",status:"in_progress"}}}C&&(P.call_id&&(C.callId=P.call_id),P.name&&(C.name=P.name),C.args+=P.delta,yield{type:"response.function_call_arguments.delta",item_id:C.fcId,output_index:C.outputIndex,delta:P.delta});continue}if(S==="response.completed"&&!v){let Y=he(b.response),Ae=de(i,D.size+Y.length,L);if(Ae){B=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ue(s,Ae)}};break}if(yield*N(),yield*I("completed"),yield*$("completed"),D.size===0)for(let ee of Y){let z=y++,ce=ee.id??ee.call_id??`fc_${z}`,se=ee.arguments??"",O={id:ce,type:"function_call",call_id:ee.call_id??ce,name:ee.name??""};yield{type:"response.output_item.added",output_index:z,item:{...O,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:ce,output_index:z,delta:se},yield{type:"response.function_call_arguments.done",item_id:ce,output_index:z,arguments:se},yield{type:"response.output_item.done",output_index:z,item:{...O,arguments:se,status:"completed"}}}yield l(b);continue}yield l(b)}if(yield*N(),yield*I("incomplete"),yield*$("incomplete"),r&&!B){let b=ne(c);d.remember(o,t,We(b,Je(c,b)),a)}}var hn="/v1/responses",gn=64*1024*1024,yn=8*1024*1024,_n=16,Et=32,Tt=3600*1e3,wn=/^[A-Za-z0-9._-]{1,256}$/;function j(n,e,t){return{type:"error",status:n,...t!==void 0?{stream_id:t}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var vn=j(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function Ye(){let n,e;return{promise:new Promise((o,s)=>{n=o,e=s}),resolve:n,reject:e}}async function kn(n){for(;n.bufferedAmount>yn&&n.readyState===oe.WebSocket.OPEN;){let{promise:e,resolve:t}=Ye();setTimeout(t,5),await e}}var ze=class extends fe{constructor(t){super();this.shared=t}shared;thread(t,o){if(t==null)return super.thread(t,o);try{return super.thread(t,o)}catch(s){if(!(s instanceof ae))throw s;return this.shared.thread(t,o)}}remember(t,o,s,i=!0){i?this.shared.remember(t,o,s):super.remember(t,o,s)}forget(t){super.forget(t),this.shared.forget(t)}},Ke=class{constructor(e,t,o,s){this.ws=e;this.clients=t;this.stats=o;this.statusOf=s;this.store=new ze(ve(t)),e.on("message",(r,a)=>this.onMessage(r,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(j(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Tt/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Tt).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,t){if(this.closed)return;if(t){this.sendFrame(j(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let o;try{o=JSON.parse(e.toString())}catch{this.sendFrame(j(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(o===null||typeof o!="object"||Array.isArray(o)){this.sendFrame(j(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let s=o;if(s.type!=="response.create"){this.sendFrame(j(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(s.type??null)}; only "response.create" is supported`}));return}if("stream"in s){this.sendFrame(j(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in s){this.sendFrame(j(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(s.stream_id!==void 0){if(typeof s.stream_id!="string"||!wn.test(s.stream_id)){this.sendFrame(vn);return}if(i=s.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=Et){this.sendFrame(j(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Et}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let r=s.generate===!1?()=>this.runWarmup(s,i):()=>this.runTurn(s,i),a=i??"",d=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,d.then(r).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,t){if(!this.closed){await this.acquire();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await ke({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0})}catch(r){this.failTurn(r,t,e);return}this.laneOfResponse.set(s.responseId,t??null);let i=s.events;this.activeTurns.add(i);try{for await(let r of i){if(this.closed||this.ws.readyState!==oe.WebSocket.OPEN)break;this.send(r,t),await kn(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,t,e)}finally{this.release()}}}runWarmup(e,t){if(this.closed)return;let o=`resp_${Math.random().toString(36).slice(2,14)}`;try{let s=ye(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,t??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},t)}catch(s){this.failTurn(s,t,e)}}failTurn(e,t,o){this.sendFrame(this.errorFrameOf(e,t));let s=o.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(t??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,t){let o=String(e instanceof Error?e.message:e);if(e instanceof H)return j(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},t);if(e instanceof V)return j(404,{type:"invalid_request_error",code:"model_not_found",message:o},t);if(e instanceof X)return j(503,{type:"upstream_error",code:"session_gone",message:o},t);let s=this.statusOf?.(e)??null;return s?j(s.status,{type:s.openaiType,message:o},t):j(500,{type:"upstream_error",message:o},t)}async acquire(){for(;this.active>=_n;){let{promise:e,resolve:t}=Ye();this.waiters.push(t),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,t){if(this.closed||this.ws.readyState!==oe.WebSocket.OPEN)return;let o=t===void 0?e:{...e,stream_id:t};this.ws.send(JSON.stringify(o))}sendFrame(e){this.closed||this.ws.readyState!==oe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Me(n,e,t){let o=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",s=`${t}\r
7
+ `;n.end(`HTTP/1.1 ${e} ${o}\r
6
8
  Connection: close\r
9
+ Content-Type: text/plain; charset=utf-8\r
10
+ Content-Length: ${Buffer.byteLength(s)}\r
7
11
  \r
8
- invalid local proxy api key`),s.destroy();return}t.handleUpgrade(r,s,i,g=>{new xe(g,n.clients,o)})})}var Ae=class e{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(n,t,o){this.requests[n]=(this.requests[n]??0)+1,this.localInBytes+=t,this.naiveInBytes+=o}modelEntry(n){let t=this.models[n];if(t)return t;let o=Object.keys(this.models).length>=Rt?"(other)":n;return this.models[o]??={requests:0,tokens_out:0}}model(n){this.modelEntry(n).requests+=1}track(n,t){let o=this,r=performance.now(),s=null,i=0;return(async function*(){for await(let g of n)g.type==="response.output_text.delta"&&typeof g.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-r),o.ttftMs.length>512&&o.ttftMs.shift()),i+=1,o.tokensOut+=1,o.charsOut+=g.delta.length,t!==void 0&&(o.modelEntry(t).tokens_out+=1)),yield g;let l=(performance.now()-(s??r))/1e3;i>0&&l>0&&(o.tokRates.push(i/l),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(n){if(!n.length)return null;let t=[...n].sort((o,r)=>o-r);return t[Math.floor(t.length/2)]}snapshot(){let n=Object.values(this.requests).reduce((t,o)=>t+o,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:e.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:e.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:n},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}}}};function Oe(e){e.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function U(e,n,t){e.writeHead(n,{"content-type":"application/json"}),e.end(JSON.stringify(t))}function W(e,n,t,o="invalid_request_error"){U(e,n,{error:{message:t,type:o}})}function B(e,n,t,o){U(e,n,{type:"error",error:{type:t,message:o}})}function Ee(e,n,t){if(n==="anthropic"){U(e,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}U(e,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var Rt=256,At=128;function Ie(e){return typeof e.model!="string"||!e.model.trim()?"(default)":e.model.trim().slice(0,At)}var Qe=64*1024*1024,me=class extends Error{};async function St(e){let n=[],t=0;for await(let r of e){if(t+=r.length,t>Qe)throw new me(`request body exceeds ${Qe} bytes`);n.push(r)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Q(e,n,t,o){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:n,choices:[{index:0,delta:t,finish_reason:o}]}}var Ot=256;function Et(e){if(typeof e=="string")return[{role:"user",content:e}];if(Array.isArray(e))return e;throw new Error("responses input must be a string or an array of messages/items")}var Se=class{conversations=new Map;thread(n,t){let o=Et(t);if(n==null)return o;let r=this.conversations.get(String(n));if(!r)throw new Error(`unknown previous_response_id ${String(n)} (proxy restarts drop stored responses)`);return[...r,...o]}remember(n,t,o){this.conversations.set(n,[...t,{role:"assistant",content:o}]);for(let r of this.conversations.keys()){if(this.conversations.size<=Ot)break;this.conversations.delete(r)}}};function ie(e){let n=e?.output;return Array.isArray(n)?n.filter(t=>t.type==="function_call"):[]}function z(e){return e.find(n=>n.type==="response.completed")?.response??null}function ge(e){let n=e?.usage;if(!n||typeof n!="object")return null;let t=i=>typeof i=="number"&&Number.isFinite(i)&&i>=0?i:0,o=t(n.input_tokens),r=t(n.output_tokens);if(o===0&&r===0)return null;let s=t(n.total_tokens)||o+r;return{input_tokens:o,output_tokens:r,total_tokens:s}}function Ze(e){let n=ge(e);return n?{prompt_tokens:n.input_tokens,completion_tokens:n.output_tokens,total_tokens:n.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function nt(e){let n=e?.output;if(!Array.isArray(n))return"";let t="";for(let o of n)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let r of o.content)r.type==="reasoning_text"&&(t+=String(r.text??""));return t}function ae(e){return e.type!=="response.function_call_arguments.delta"||typeof e.tool_index!="number"?null:{tool_index:e.tool_index,call_id:typeof e.call_id=="string"?e.call_id:void 0,name:typeof e.name=="string"?e.name:void 0,delta:typeof e.delta=="string"?e.delta:""}}var Y=class{calls=new Map;add(n){let t=this.calls.get(n.tool_index),o=!t;return t||(t={args:""},this.calls.set(n.tool_index,t)),n.call_id&&(t.id=n.call_id),n.name&&(t.name=n.name),t.args+=n.delta,{call:t,isNew:o}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([n,t])=>({type:"function_call",call_id:t.id??`call_${n}`,name:t.name??"",arguments:t.args}))}},It=["<tool_call>","<function="];function Tt(e){return It.find(n=>e.includes(n))}function Z(e,n){return`serving row emitted a prose tool call (literal ${JSON.stringify(n)} 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 "${e}" (see catalog parser_defaults)`}function ee(e,n,t){if(!(!e||n>0))return Tt(t)}function Ct(e){if(Array.isArray(e))return e.map(n=>{let t=n.function;return!t||typeof t!="object"?n:{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}})}var he=class extends Error{};function Pt(e,n){return Array.isArray(n)?n.map(t=>{let o=t;if(o.type==="text")return{type:e==="assistant"?"output_text":"input_text",text:o.text};if(o.type==="image_url"){let r=o.image_url??{};return{type:"input_image",image_url:r.url,detail:r.detail}}throw new he(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):n}function Lt(e){let n=[];for(let t of e){if(t.role==="tool"){n.push({type:"function_call_output",call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:JSON.stringify(t.content??"")});continue}if(t.role==="assistant"&&Array.isArray(t.tool_calls)){typeof t.content=="string"&&t.content&&n.push({role:"assistant",content:t.content});for(let o of t.tool_calls){let r=o.function??{};n.push({type:"function_call",call_id:o.id,name:r.name,arguments:r.arguments})}continue}n.push({...t,content:Pt(t.role,t.content)})}return n}function be(e){return ie(e).map((n,t)=>({index:t,id:n.call_id??n.id??`call_${t}`,type:"function",function:{name:n.name??"",arguments:n.arguments??"{}"}}))}function et(e,n){let t=n?.output_text;return typeof t=="string"?t:e.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}async function $t(e,n,t,o,r){let s=e.stream===!0,i;try{i=t.thread(e.previous_response_id,e.input)}catch(u){W(o,400,String(u instanceof Error?u.message:u));return}e.previous_response_id!=null&&(r.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let l=`resp_${Math.random().toString(36).slice(2,14)}`,g=e.store!==!1,d=Ie(e);r.model(d);let p=Array.isArray(e.tools)&&e.tools.length>0,f;try{f=await n.createResponse({model:e.model,input:i,stream:s,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,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}:{}})}catch(u){if(u instanceof q){Ee(o,"openai",u);return}throw u}let m=[];if(s){Oe(o);let u=w=>{o.write(`event: ${String(w.type??"message")}
9
- data: ${JSON.stringify(w)}
12
+ ${s}`)}function Ct(n,e){let t=new oe.WebSocketServer({noServer:!0,maxPayload:gn}),o=new re,s=new Set,i=new Set,r=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,d=!1,u=(c,l,f)=>{let h;try{h=new URL(c.url??"/","http://localhost")}catch{Me(l,400,"malformed upgrade URL");return}if(l.on("error",()=>l.destroy()),l.on("close",()=>r.delete(l)),h.pathname!==hn){r.add(l);return}i.add(l);let w=!1;(async()=>{if(e.apiKey&&(c.headers.authorization??"")!==`Bearer ${e.apiKey}`){Me(l,401,"invalid local proxy api key");return}let v;try{v=await a(c)}catch(y){let x=e.statusOf?.(y)??null;Me(l,x?.status??500,"upstream resolver rejected the connection");return}d||l.destroyed||(w=!0,t.handleUpgrade(c,l,f,y=>{i.delete(l),s.add(y),y.on("close",()=>s.delete(y));try{new Ke(y,v,o,e.statusOf)}catch{s.delete(y),y.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!w&&!l.destroyed&&Me(l,500,"responses websocket upgrade failed")}).finally(()=>i.delete(l))};return n.on("upgrade",u),{stats:o,close:()=>{let{promise:c,resolve:l}=Ye();if(d)return l(),c;d=!0,n.off("upgrade",u);for(let h of i)h.destroy();i.clear();for(let h of r)h.destroy();r.clear();for(let h of s)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of s)h.readyState!==oe.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),t.close(()=>{clearTimeout(f),l()}),c}}}function Ze(n){n.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function W(n,e,t){n.writeHead(e,{"content-type":"application/json"}),n.end(JSON.stringify(t))}function J(n,e,t,o="invalid_request_error"){W(n,e,{error:{message:t,type:o}})}function K(n,e,t,o){W(n,e,{type:"error",error:{type:t,message:o}})}function Le(n,e,t){if(e==="anthropic"){W(n,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}W(n,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var Pt=64*1024*1024,$e=class extends Error{};async function bn(n){let e=[],t=0;for await(let s of n){if(t+=s.length,t>Pt)throw new $e(`request body exceeds ${Pt} bytes`);e.push(s)}let o=Buffer.concat(e).toString("utf8");return o?JSON.parse(o):{}}function _e(n,e,t,o){return{id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:t,finish_reason:o}]}}function Ne(n){let e=n?.usage;if(!e||typeof e!="object")return null;let t=r=>typeof r=="number"&&Number.isFinite(r)&&r>=0?r:0,o=t(e.input_tokens),s=t(e.output_tokens);if(o===0&&s===0)return null;let i=t(e.total_tokens)||o+s;return{input_tokens:o,output_tokens:s,total_tokens:i}}function Mt(n){let e=Ne(n);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function $t(n){let e=n?.output;if(!Array.isArray(e))return"";let t="";for(let o of e)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let s of o.content)s.type==="reasoning_text"&&(t+=String(s.text??""));return t}function xn(n){if(Array.isArray(n))return n.map(e=>{let t=e.function;return!t||typeof t!="object"?e:{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}})}var Ue=class extends Error{};function Rn(n,e){return Array.isArray(e)?e.map(t=>{let o=t;if(o.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:o.text};if(o.type==="image_url"){let s=o.image_url??{};return{type:"input_image",image_url:s.url,detail:s.detail}}throw new Ue(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function An(n){let e=[];for(let t of n){if(t.role==="tool"){e.push({type:"function_call_output",call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:JSON.stringify(t.content??"")});continue}if(t.role==="assistant"&&Array.isArray(t.tool_calls)){typeof t.content=="string"&&t.content&&e.push({role:"assistant",content:t.content});for(let o of t.tool_calls){let s=o.function??{};e.push({type:"function_call",call_id:o.id,name:s.name,arguments:s.arguments})}continue}e.push({...t,content:Rn(t.role,t.content)})}return e}function Xe(n){return he(n).map((e,t)=>({index:t,id:e.call_id??e.id??`call_${t}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function Sn(n,e,t,o,s){if(n.stream===!0){let y;try{y=await ke({body:n,clients:e,store:t,stats:s})}catch(x){if(x instanceof V){Le(o,"openai",x);return}if(x instanceof H){J(o,x.status,x.message);return}throw x}Ze(o);for await(let x of y.events)o.write(`event: ${String(x.type??"message")}
13
+ data: ${JSON.stringify(x)}
10
14
 
11
- `)},S=w=>w.response&&typeof w.response=="object"?{...w,response:{...w.response,id:l}}:w,E=`item_${l.slice(5)}`,$=`rs_${l.slice(5)}`,P=!1,N=!1,c=0,x=()=>{P||(P=!0,u({type:"response.created",response:{id:l,object:"response",status:"in_progress"}}))},D=!1,C=0,M="",V=()=>{D&&(D=!1,u({type:"response.reasoning_text.done",item_id:$,output_index:C,content_index:0,text:M}),u({type:"response.output_item.done",output_index:C,item:{id:$,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:M}],status:"completed"}}))},L=!1,v=0,O="",H=w=>{L&&(L=!1,u({type:"response.output_text.done",item_id:E,output_index:v,content_index:0,text:O}),u({type:"response.content_part.done",item_id:E,output_index:v,content_index:0,part:{type:"output_text",text:O}}),u({type:"response.output_item.done",output_index:v,item:{id:E,type:"message",role:"assistant",status:w,content:[{type:"output_text",text:O}]}}))},F=new Y,b=null,X=-1,te=w=>{if(!b)return;let A=b;b=null,u({type:"response.function_call_arguments.done",item_id:A.fcId,output_index:A.outputIndex,arguments:A.args}),u({type:"response.output_item.done",output_index:A.outputIndex,item:{id:A.fcId,type:"function_call",call_id:A.callId??A.fcId,name:A.name??"",arguments:A.args,status:w}})},ne=!1;for await(let w of r.track(f,d)){m.push(w);let A=String(w.type??"");if(A==="response.created"||A==="response.in_progress"){P=!0,u(S(w));continue}if(A==="response.output_item.added"){N=!0,u(S(w));continue}if(A==="response.reasoning_text.delta"&&!N){x(),D||(D=!0,C=c++,u({type:"response.output_item.added",output_index:C,item:{id:$,type:"reasoning",summary:[],content:[],status:"in_progress"}})),M+=String(w.delta??""),u({type:"response.reasoning_text.delta",item_id:$,output_index:C,content_index:0,delta:w.delta});continue}if(A==="response.output_text.delta"&&!N){x(),V(),L||(L=!0,v=c++,u({type:"response.output_item.added",output_index:v,item:{id:E,type:"message",role:"assistant",status:"in_progress",content:[]}}),u({type:"response.content_part.added",item_id:E,output_index:v,content_index:0,part:{type:"output_text",text:""}})),O+=String(w.delta??""),u({type:A,item_id:E,output_index:v,content_index:0,delta:w.delta});continue}let I=N?null:ae(w);if(I){if(x(),V(),H("completed"),F.add(I),I.tool_index!==X){te("completed"),X=I.tool_index;let _=c++;b={fcId:`fc_${l.slice(5)}_${I.tool_index}`,outputIndex:_,callId:I.call_id,name:I.name,args:""},u({type:"response.output_item.added",output_index:_,item:{id:b.fcId,type:"function_call",call_id:b.callId??b.fcId,name:b.name??"",arguments:"",status:"in_progress"}})}b&&(I.call_id&&(b.callId=I.call_id),I.name&&(b.name=I.name),b.args+=I.delta,u({type:"response.function_call_arguments.delta",item_id:b.fcId,output_index:b.outputIndex,delta:I.delta}));continue}if(A==="response.completed"&&!N){let _=ie(w.response),T=ee(p,F.size+_.length,O);if(T){ne=!0,u({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Z(d,T)}});break}V(),H("completed"),te("completed"),F.size===0&&_.forEach(G=>{let oe=c++,ce=G.id??G.call_id??`fc_${oe}`,we=G.arguments??"",Te={id:ce,type:"function_call",call_id:G.call_id??ce,name:G.name??""};u({type:"response.output_item.added",output_index:oe,item:{...Te,arguments:"",status:"in_progress"}}),u({type:"response.function_call_arguments.delta",item_id:ce,output_index:oe,delta:we}),u({type:"response.function_call_arguments.done",item_id:ce,output_index:oe,arguments:we}),u({type:"response.output_item.done",output_index:oe,item:{...Te,arguments:we,status:"completed"}})}),u(S(w));continue}u(S(w))}V(),H("incomplete"),te("incomplete"),g&&!ne&&t.remember(l,i,et(m,z(m))),o.write(`data: [DONE]
15
+ `);o.write(`data: [DONE]
12
16
 
13
- `),o.end();return}let h=null;for await(let u of r.track(f,d)){if(m.push(u),u.type==="error"){W(o,502,JSON.stringify(u),"upstream_error");return}u.type==="response.completed"&&(h=u.response)}if(h==null){W(o,502,"upstream produced no response.completed event","upstream_error");return}let y=et(m,h),k=ee(p,ie(h).length,y);if(k){W(o,502,Z(d,k),"upstream_error");return}g&&t.remember(l,i,y),U(o,200,{...h,id:l})}async function Nt(e,n,t,o){let r=e.messages;if(!Array.isArray(r)){W(t,400,"chat/completions requires a messages array");return}let s=String(e.model??"urun"),i=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,l;try{l=Lt(r)}catch(c){if(c instanceof he){W(t,400,c.message);return}throw c}let g=Ie(e);o.model(g);let d=Array.isArray(e.tools)&&e.tools.length>0,p;try{p=await n.createResponse({model:e.model,input:l,stream:!0,tools:Ct(e.tools),tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,max_output_tokens:e.max_completion_tokens??e.max_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{}})}catch(c){if(c instanceof q){Ee(t,"openai",c);return}throw c}if(e.stream===!0){Oe(t);let c=[],x=new Y,D="";t.write(`data: ${JSON.stringify(Q(i,s,{role:"assistant"},null))}
17
+ `),o.end();return}let r;try{r=ye(t,n)}catch(y){if(y instanceof H){J(o,y.status,y.message);return}throw y}n.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(r))-Buffer.byteLength(JSON.stringify(n.input)));let a=`resp_${Math.random().toString(36).slice(2,14)}`,d=n.store!==!1,u=me(n);s.model(u);let c=Array.isArray(n.tools)&&n.tools.length>0,l;try{l=await Ge(e,n,r,!1)}catch(y){if(y instanceof V){Le(o,"openai",y);return}if(y instanceof H){J(o,y.status,y.message);return}throw y}let f=[],h=null;for await(let y of s.track(l,u)){if(f.push(y),y.type==="error"){J(o,502,JSON.stringify(y),"upstream_error");return}y.type==="response.completed"&&(h=y.response)}if(h==null){J(o,502,"upstream produced no response.completed event","upstream_error");return}let w=Je(f,h),v=de(c,he(h).length,w);if(v){J(o,502,ue(u,v),"upstream_error");return}d&&t.remember(a,r,We(h,w),d),W(o,200,{...h,id:a})}async function On(n,e,t,o){let s=n.messages;if(!Array.isArray(s)){J(t,400,"chat/completions requires a messages array");return}let i=String(n.model??"urun"),r=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,a;try{a=An(s)}catch(p){if(p instanceof Ue){J(t,400,p.message);return}throw p}let d=me(n);o.model(d);let u=Array.isArray(n.tools)&&n.tools.length>0,c;try{c=await e.createResponse({model:n.model,input:a,stream:!0,tools:xn(n.tools),tool_choice:n.tool_choice,temperature:n.temperature,top_p:n.top_p,stop:n.stop,max_output_tokens:n.max_completion_tokens??n.max_tokens,...n.reasoning_effort!==void 0?{reasoning_effort:n.reasoning_effort}:{},...n.chat_template_kwargs!==void 0?{chat_template_kwargs:n.chat_template_kwargs}:{}})}catch(p){if(p instanceof V){Le(t,"openai",p);return}throw p}if(n.stream===!0){Ze(t);let p=[],k=new te,L="";t.write(`data: ${JSON.stringify(_e(r,i,{role:"assistant"},null))}
14
18
 
15
- `);for await(let v of o.track(p,g)){c.push(v);let O=ae(v);if(v.type==="response.output_text.delta"&&typeof v.delta=="string")D+=v.delta,t.write(`data: ${JSON.stringify(Q(i,s,{content:v.delta},null))}
19
+ `);for await(let $ of o.track(c,d)){p.push($);let B=ge($);if($.type==="response.output_text.delta"&&typeof $.delta=="string")L+=$.delta,t.write(`data: ${JSON.stringify(_e(r,i,{content:$.delta},null))}
16
20
 
17
- `);else if(v.type==="response.reasoning_text.delta"&&typeof v.delta=="string")t.write(`data: ${JSON.stringify(Q(i,s,{reasoning_content:v.delta},null))}
21
+ `);else if($.type==="response.reasoning_text.delta"&&typeof $.delta=="string")t.write(`data: ${JSON.stringify(_e(r,i,{reasoning_content:$.delta},null))}
18
22
 
19
- `);else if(O){let{call:H,isNew:F}=x.add(O),b=F?{index:O.tool_index,id:H.id??`call_${O.tool_index}`,type:"function",function:{name:H.name??"",arguments:O.delta}}:{index:O.tool_index,function:{arguments:O.delta}};t.write(`data: ${JSON.stringify(Q(i,s,{tool_calls:[b]},null))}
23
+ `);else if(B){let{call:b,isNew:S}=k.add(B),P=S?{index:B.tool_index,id:b.id??`call_${B.tool_index}`,type:"function",function:{name:b.name??"",arguments:B.delta}}:{index:B.tool_index,function:{arguments:B.delta}};t.write(`data: ${JSON.stringify(_e(r,i,{tool_calls:[P]},null))}
20
24
 
21
- `)}else if(v.type==="error"){t.write(`data: ${JSON.stringify({error:v})}
25
+ `)}else if($.type==="error"){t.write(`data: ${JSON.stringify({error:$})}
22
26
 
23
- `),t.end();return}}let C=be(z(c)),M=ee(d,x.size+C.length,D);if(M){t.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Z(g,M)}})}
27
+ `),t.end();return}}let I=Xe(ne(p)),D=de(u,k.size+I.length,L);if(D){t.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ue(d,D)}})}
24
28
 
25
- `),t.end();return}x.size===0&&C.length>0&&t.write(`data: ${JSON.stringify(Q(i,s,{tool_calls:C},null))}
29
+ `),t.end();return}k.size===0&&I.length>0&&t.write(`data: ${JSON.stringify(_e(r,i,{tool_calls:I},null))}
26
30
 
27
- `);let V=x.size>0||C.length>0;t.write(`data: ${JSON.stringify(Q(i,s,{},V?"tool_calls":"stop"))}
31
+ `);let C=k.size>0||I.length>0;t.write(`data: ${JSON.stringify(_e(r,i,{},C?"tool_calls":"stop"))}
28
32
 
29
- `),ge(z(c))&&t.write(`data: ${JSON.stringify({id:i,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s,choices:[],usage:Ze(z(c))})}
33
+ `),Ne(ne(p))&&t.write(`data: ${JSON.stringify({id:r,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:i,choices:[],usage:Mt(ne(p))})}
30
34
 
31
35
  `),t.write(`data: [DONE]
32
36
 
33
- `),t.end();return}let f="",m="",h=[],y=new Y;for await(let c of o.track(p,g)){h.push(c),c.type==="response.output_text.delta"&&typeof c.delta=="string"&&(f+=c.delta),c.type==="response.reasoning_text.delta"&&typeof c.delta=="string"&&(m+=c.delta);let x=ae(c);if(x&&y.add(x),c.type==="error"){W(t,502,JSON.stringify(c),"upstream_error");return}}let k=z(h),u=be(k),S=u.length>0?u:be({output:y.items()}),E=ee(d,S.length,f);if(E){W(t,502,Z(g,E),"upstream_error");return}let $=S.map(({index:c,...x})=>x),P={role:"assistant",content:f||null},N=m||nt(k);N&&(P.reasoning_content=N),$.length>0&&(P.tool_calls=$),U(t,200,{id:i,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:s,choices:[{index:0,message:P,finish_reason:$.length>0?"tool_calls":"stop"}],usage:Ze(k)})}function Mt(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>n.type==="text").map(n=>String(n.text??"")).join(""):""}var ue=class extends Error{};function ye(e){return new ue(`unsupported anthropic content block type "${e}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Ut(e){if(Array.isArray(e))return e.map(n=>{let t=n;return{type:"function",name:t.name,description:t.description,parameters:t.input_schema}})}function Dt(e){if(e==null)return;let n=e.type;if(n==="auto")return"auto";if(n==="none")return"none";if(n==="any")return"required";if(n==="tool")return{type:"function",name:e.name};throw new ue(`unsupported anthropic tool_choice type ${JSON.stringify(String(n))} \u2014 the proxy maps auto, none, any and tool`)}function Vt(e){if(typeof e=="string")return e;if(e==null)return"";if(!Array.isArray(e))throw ye(typeof e);let n="";for(let t of e){let o=String(t.type??"");if(o!=="text")throw ye(`tool_result > ${o}`);n+=String(t.text??"")}return n}function Bt(e){let{role:n,content:t}=e;if(typeof t=="string")return[{role:n,content:t}];if(t==null)return[];if(!Array.isArray(t))throw ye(typeof t);let o=[],r="",s=()=>{r&&(o.push({role:n,content:r}),r="")};for(let i of t){let l=String(i.type??"");if(l==="text")r+=String(i.text??"");else if(l==="tool_use")s(),o.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(l==="tool_result")s(),o.push({type:"function_call_output",call_id:i.tool_use_id,output:Vt(i.content)});else{if(l==="thinking"||l==="redacted_thinking")continue;throw ye(l)}}return s(),o}function Re(e){return ie(e).map((n,t)=>{let o;try{o=JSON.parse(n.arguments||"{}")}catch{throw new Error(`upstream function_call "${n.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:n.call_id??n.id??`toolu_${t}`,name:n.name??"",input:o}})}async function Ht(e,n,t,o){let r=e.messages;if(!Array.isArray(r)){B(t,400,"invalid_request_error","messages requires a messages array");return}if(typeof e.max_tokens!="number"||!Number.isInteger(e.max_tokens)||e.max_tokens<1){B(t,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(e.top_k!==void 0){B(t,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(e.stop_sequences!==void 0&&(!Array.isArray(e.stop_sequences)||e.stop_sequences.some(c=>typeof c!="string"))){B(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let s=String(e.model??"urun"),i=`msg_${Math.random().toString(36).slice(2,14)}`,l=[],g;try{e.system&&l.push({role:"system",content:Mt(e.system)});for(let c of r)l.push(...Bt(c));g=Dt(e.tool_choice)}catch(c){if(c instanceof ue){B(t,400,"invalid_request_error",c.message);return}throw c}let d=Ie(e);o.model(d);let p=Array.isArray(e.tools)&&e.tools.length>0,f;try{f=await n.createResponse({model:e.model,input:l,stream:!0,tools:Ut(e.tools),tool_choice:g,temperature:e.temperature,max_output_tokens:e.max_tokens,top_p:e.top_p,stop:e.stop_sequences})}catch(c){if(c instanceof q){Ee(t,"anthropic",c);return}throw c}let m=(c,x)=>{t.destroyed||t.write(`event: ${c}
34
- data: ${JSON.stringify({type:c,...x})}
37
+ `),t.end();return}let l="",f="",h=[],w=new te;for await(let p of o.track(c,d)){h.push(p),p.type==="response.output_text.delta"&&typeof p.delta=="string"&&(l+=p.delta),p.type==="response.reasoning_text.delta"&&typeof p.delta=="string"&&(f+=p.delta);let k=ge(p);if(k&&w.add(k),p.type==="error"){J(t,502,JSON.stringify(p),"upstream_error");return}}let v=ne(h),y=Xe(v),x=y.length>0?y:Xe({output:w.items()}),R=de(u,x.length,l);if(R){J(t,502,ue(d,R),"upstream_error");return}let U=x.map(({index:p,...k})=>k),T={role:"assistant",content:l||null},N=f||$t(v);N&&(T.reasoning_content=N),U.length>0&&(T.tool_calls=U),W(t,200,{id:r,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:i,choices:[{index:0,message:T,finish_reason:U.length>0?"tool_calls":"stop"}],usage:Mt(v)})}function In(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var be=class extends Error{};function Be(n){return new be(`unsupported anthropic content block type "${n}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function En(n){if(Array.isArray(n))return n.map(e=>{let t=e;return{type:"function",name:t.name,description:t.description,parameters:t.input_schema}})}function Tn(n){if(n==null)return;let e=n.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:n.name};throw new be(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Cn(n){if(typeof n=="string")return n;if(n==null)return"";if(!Array.isArray(n))throw Be(typeof n);let e="";for(let t of n){let o=String(t.type??"");if(o!=="text")throw Be(`tool_result > ${o}`);e+=String(t.text??"")}return e}function Pn(n){let{role:e,content:t}=n;if(typeof t=="string")return[{role:e,content:t}];if(t==null)return[];if(!Array.isArray(t))throw Be(typeof t);let o=[],s="",i=()=>{s&&(o.push({role:e,content:s}),s="")};for(let r of t){let a=String(r.type??"");if(a==="text")s+=String(r.text??"");else if(a==="tool_use")i(),o.push({type:"function_call",call_id:r.id,name:r.name,arguments:JSON.stringify(r.input??{})});else if(a==="tool_result")i(),o.push({type:"function_call_output",call_id:r.tool_use_id,output:Cn(r.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Be(a)}}return i(),o}function Qe(n){return he(n).map((e,t)=>{let o;try{o=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${t}`,name:e.name??"",input:o}})}async function Mn(n,e,t,o){let s=n.messages;if(!Array.isArray(s)){K(t,400,"invalid_request_error","messages requires a messages array");return}if(typeof n.max_tokens!="number"||!Number.isInteger(n.max_tokens)||n.max_tokens<1){K(t,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(n.top_k!==void 0){K(t,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(n.stop_sequences!==void 0&&(!Array.isArray(n.stop_sequences)||n.stop_sequences.some(p=>typeof p!="string"))){K(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(n.model??"urun"),r=`msg_${Math.random().toString(36).slice(2,14)}`,a=[],d;try{n.system&&a.push({role:"system",content:In(n.system)});for(let p of s)a.push(...Pn(p));d=Tn(n.tool_choice)}catch(p){if(p instanceof be){K(t,400,"invalid_request_error",p.message);return}throw p}let u=me(n);o.model(u);let c=Array.isArray(n.tools)&&n.tools.length>0,l;try{l=await e.createResponse({model:n.model,input:a,stream:!0,tools:En(n.tools),tool_choice:d,temperature:n.temperature,max_output_tokens:n.max_tokens,top_p:n.top_p,stop:n.stop_sequences})}catch(p){if(p instanceof V){Le(t,"anthropic",p);return}throw p}let f=(p,k)=>{t.destroyed||t.write(`event: ${p}
38
+ data: ${JSON.stringify({type:p,...k})}
35
39
 
36
- `)};if(e.stream===!0){let c=o.track(f,d);Oe(t),m("message_start",{message:{id:i,type:"message",role:"assistant",content:[],model:s,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let x=0,D="",C=0,M="none",V=()=>M,L=-1,v=-1,O=new Y,H=[],F=()=>{M!=="none"&&(M="none",m("content_block_stop",{index:L}))},b=(_,T)=>{F(),M=_,L=C++,m("content_block_start",{index:L,content_block:T})};for await(let _ of c){if(t.destroyed)break;H.push(_);let T=ae(_);if(_.type==="response.reasoning_text.delta"&&typeof _.delta=="string")V()!=="thinking"&&b("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:L,delta:{type:"thinking_delta",thinking:_.delta}});else if(_.type==="response.output_text.delta"&&typeof _.delta=="string")V()!=="text"&&b("text",{type:"text",text:""}),x+=1,D+=_.delta,m("content_block_delta",{index:L,delta:{type:"text_delta",text:_.delta}});else if(T){let{call:G}=O.add(T);(V()!=="tool"||T.tool_index!==v)&&(v=T.tool_index,b("tool",{type:"tool_use",id:G.id??`call_${T.tool_index}`,name:G.name??"",input:{}})),T.delta&&m("content_block_delta",{index:L,delta:{type:"input_json_delta",partial_json:T.delta}})}else if(_.type==="error"){m("error",{error:{type:"api_error",message:JSON.stringify(_)}}),t.end();return}}if(t.destroyed)return;let X=z(H),te=ie(X),ne=ee(p,O.size+te.length,D);if(ne){m("error",{error:{type:"api_error",message:Z(d,ne)}}),t.end();return}F();let w=[];if(O.size===0)try{w=Re(X)}catch(_){m("error",{error:{type:"api_error",message:String(_ instanceof Error?_.message:_)}}),t.end();return}C===0&&w.length===0&&(b("text",{type:"text",text:""}),F()),w.forEach(_=>{let T=C++;m("content_block_start",{index:T,content_block:{..._,input:{}}}),m("content_block_delta",{index:T,delta:{type:"input_json_delta",partial_json:JSON.stringify(_.input??{})}}),m("content_block_stop",{index:T})});let A=O.size>0||w.length>0,I=ge(X);m("message_delta",{delta:{stop_reason:A?"tool_use":"end_turn"},usage:I?{input_tokens:I.input_tokens,output_tokens:I.output_tokens}:{output_tokens:x}}),m("message_stop",{}),t.end();return}let h="",y="",k=[],u=new Y;for await(let c of o.track(f,d)){k.push(c),c.type==="response.output_text.delta"&&typeof c.delta=="string"&&(h+=c.delta),c.type==="response.reasoning_text.delta"&&typeof c.delta=="string"&&(y+=c.delta);let x=ae(c);if(x&&u.add(x),c.type==="error"){B(t,502,"api_error",JSON.stringify(c));return}if(t.destroyed)break}if(t.destroyed)return;let S=z(k),E;try{E=Re(S),E.length===0&&u.size>0&&(E=Re({output:u.items()}))}catch(c){B(t,502,"api_error",String(c instanceof Error?c.message:c));return}let $=ee(p,E.length,h);if($){B(t,502,"api_error",Z(d,$));return}let P=[],N=y||nt(S);N&&P.push({type:"thinking",thinking:N}),(h||E.length===0)&&P.push({type:"text",text:h}),P.push(...E),U(t,200,{id:i,type:"message",role:"assistant",content:P,model:s,stop_reason:E.length>0?"tool_use":"end_turn",usage:ge(S)??{input_tokens:0,output_tokens:0}})}function Ft(e){let{clients:n,apiKey:t,identity:o,statusOf:r}=e,s=typeof n=="function"?n:()=>n,i=new WeakMap,l=d=>{let p=i.get(d);return p||(p=new Se,i.set(d,p)),p},g=new Ae;return(d,p)=>{let f=new URL(d.url??"/","http://localhost"),m=f.pathname==="/v1/messages"||f.pathname.startsWith("/v1/messages/"),h=(y,k,u,S)=>m?B(p,y,S,k):W(p,y,k,u);(async()=>{if(d.method==="GET"&&f.pathname==="/healthz"){U(p,200,{ok:!0});return}if(d.method==="GET"&&f.pathname==="/stats"){U(p,200,o?{identity:o,...g.snapshot()}:g.snapshot());return}if(t&&(d.headers.authorization??"")!==`Bearer ${t}`){h(401,"invalid local proxy api key","authentication_error","authentication_error");return}let y=await s(d);if(d.method==="GET"&&f.pathname==="/v1/models"){if(f.searchParams.get("format")==="openrouter"){if(!y.openRouterModels){h(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}U(p,200,await y.openRouterModels());return}U(p,200,await y.listModels());return}if(d.method!=="POST"){h(404,`no route for ${d.method} ${f.pathname}`,"invalid_request_error","not_found_error");return}let k;try{k=await St(d)}catch(S){if(S instanceof me){h(413,S.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let u=Buffer.byteLength(JSON.stringify(k));if(f.pathname==="/v1/responses"){g.request("responses",u,u),await $t(k,y,l(y),p,g);return}if(f.pathname==="/v1/chat/completions"){g.request("chat_completions",u,u),await Nt(k,y,p,g);return}if(f.pathname==="/v1/messages"){g.request("messages",u,u),await Ht(k,y,p,g);return}if(f.pathname==="/v1/messages/count_tokens"){g.request("count_tokens",u,u),B(p,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}h(404,`no route for POST ${f.pathname}`,"invalid_request_error","not_found_error")})().catch(y=>{let k=String(y instanceof Error?y.message:y);if(!p.headersSent){let u=r?.(y)??null;if(u){h(u.status,k,u.openaiType,u.anthropicType);return}h(500,k,"proxy_error","api_error");return}p.destroyed||(m?p.write(`event: error
37
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:k}})}
40
+ `)};if(n.stream===!0){let p=o.track(l,u);Ze(t),f("message_start",{message:{id:r,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let k=0,L="",I=0,D="none",C=()=>D,G=-1,$=-1,B=new te,b=[],S=()=>{D!=="none"&&(D="none",f("content_block_stop",{index:G}))},P=(O,q)=>{S(),D=O,G=I++,f("content_block_start",{index:G,content_block:q})};for await(let O of p){if(t.destroyed)break;b.push(O);let q=ge(O);if(O.type==="response.reasoning_text.delta"&&typeof O.delta=="string")C()!=="thinking"&&P("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:G,delta:{type:"thinking_delta",thinking:O.delta}});else if(O.type==="response.output_text.delta"&&typeof O.delta=="string")C()!=="text"&&P("text",{type:"text",text:""}),k+=1,L+=O.delta,f("content_block_delta",{index:G,delta:{type:"text_delta",text:O.delta}});else if(q){let{call:rt}=B.add(q);(C()!=="tool"||q.tool_index!==$)&&($=q.tool_index,P("tool",{type:"tool_use",id:rt.id??`call_${q.tool_index}`,name:rt.name??"",input:{}})),q.delta&&f("content_block_delta",{index:G,delta:{type:"input_json_delta",partial_json:q.delta}})}else if(O.type==="error"){f("error",{error:{type:"api_error",message:JSON.stringify(O)}}),t.end();return}}if(t.destroyed)return;let Y=ne(b),Ae=he(Y),ee=de(c,B.size+Ae.length,L);if(ee){f("error",{error:{type:"api_error",message:ue(u,ee)}}),t.end();return}S();let z=[];if(B.size===0)try{z=Qe(Y)}catch(O){f("error",{error:{type:"api_error",message:String(O instanceof Error?O.message:O)}}),t.end();return}I===0&&z.length===0&&(P("text",{type:"text",text:""}),S()),z.forEach(O=>{let q=I++;f("content_block_start",{index:q,content_block:{...O,input:{}}}),f("content_block_delta",{index:q,delta:{type:"input_json_delta",partial_json:JSON.stringify(O.input??{})}}),f("content_block_stop",{index:q})});let ce=B.size>0||z.length>0,se=Ne(Y);f("message_delta",{delta:{stop_reason:ce?"tool_use":"end_turn"},usage:se?{input_tokens:se.input_tokens,output_tokens:se.output_tokens}:{output_tokens:k}}),f("message_stop",{}),t.end();return}let h="",w="",v=[],y=new te;for await(let p of o.track(l,u)){v.push(p),p.type==="response.output_text.delta"&&typeof p.delta=="string"&&(h+=p.delta),p.type==="response.reasoning_text.delta"&&typeof p.delta=="string"&&(w+=p.delta);let k=ge(p);if(k&&y.add(k),p.type==="error"){K(t,502,"api_error",JSON.stringify(p));return}if(t.destroyed)break}if(t.destroyed)return;let x=ne(v),R;try{R=Qe(x),R.length===0&&y.size>0&&(R=Qe({output:y.items()}))}catch(p){K(t,502,"api_error",String(p instanceof Error?p.message:p));return}let U=de(c,R.length,h);if(U){K(t,502,"api_error",ue(u,U));return}let T=[],N=w||$t(x);N&&T.push({type:"thinking",thinking:N}),(h||R.length===0)&&T.push({type:"text",text:h}),T.push(...R),W(t,200,{id:r,type:"message",role:"assistant",content:T,model:i,stop_reason:R.length>0?"tool_use":"end_turn",usage:Ne(x)??{input_tokens:0,output_tokens:0}})}function Ln(n){let{clients:e,apiKey:t,identity:o,statusOf:s}=n,i=typeof e=="function"?e:()=>e,r=new re;return(a,d)=>{let u=new URL(a.url??"/","http://localhost"),c=u.pathname==="/v1/messages"||u.pathname.startsWith("/v1/messages/"),l=(f,h,w,v)=>c?K(d,f,v,h):J(d,f,h,w);(async()=>{if(a.method==="GET"&&u.pathname==="/healthz"){W(d,200,{ok:!0});return}if(a.method==="GET"&&u.pathname==="/stats"){W(d,200,o?{identity:o,...r.snapshot()}:r.snapshot());return}if(t&&(a.headers.authorization??"")!==`Bearer ${t}`){l(401,"invalid local proxy api key","authentication_error","authentication_error");return}let f=await i(a);if(a.method==="GET"&&u.pathname==="/v1/models"){if(u.searchParams.get("format")==="openrouter"){if(!f.openRouterModels){l(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}W(d,200,await f.openRouterModels());return}W(d,200,await f.listModels());return}if(a.method!=="POST"){l(404,`no route for ${a.method} ${u.pathname}`,"invalid_request_error","not_found_error");return}let h;try{h=await bn(a)}catch(v){if(v instanceof $e){l(413,v.message,"request_too_large","request_too_large");return}l(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let w=Buffer.byteLength(JSON.stringify(h));if(u.pathname==="/v1/responses"){r.request("responses",w,w),await Sn(h,f,ve(f),d,r);return}if(u.pathname==="/v1/chat/completions"){r.request("chat_completions",w,w),await On(h,f,d,r);return}if(u.pathname==="/v1/messages"){r.request("messages",w,w),await Mn(h,f,d,r);return}if(u.pathname==="/v1/messages/count_tokens"){r.request("count_tokens",w,w),K(d,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}l(404,`no route for POST ${u.pathname}`,"invalid_request_error","not_found_error")})().catch(f=>{let h=String(f instanceof Error?f.message:f);if(!d.headersSent){let w=s?.(f)??null;if(w){l(w.status,h,w.openaiType,w.anthropicType);return}l(500,h,"proxy_error","api_error");return}d.destroyed||(c?d.write(`event: error
41
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:h}})}
38
42
 
39
- `):p.write(`data: ${JSON.stringify({error:{message:k,type:"upstream_error"}})}
43
+ `):d.write(`data: ${JSON.stringify({error:{message:h,type:"upstream_error"}})}
40
44
 
41
- `)),p.end()})}}function ot(e){let{clients:n,apiKey:t}=e,o=(0,tt.createServer)(Ft(e));return Xe(o,{clients:n,apiKey:t}),o}0&&(module.exports={GEMINI_LIVE_PATH,VIDEO_OUT_SETUP_KEY,createOpenAIProxy});
45
+ `)),d.end()})}}function Nt(n){let{clients:e,apiKey:t}=n,o=(0,Lt.createServer)(Ln(n)),s=Ct(o,{clients:e,apiKey:t,statusOf:n.statusOf}),i=o.close.bind(o);return o.close=(r=>(s.close(),i(r))),Pe(o,{clients:e,apiKey:t}),o}var Ft=require("ws");var Bt=require("crypto");function g(n){return`${n}_${(0,Bt.randomUUID)().replace(/-/g,"").slice(0,24)}`}var De=4*1024*1024,et=8*1024*1024,Fe=512,Ve=20*1024*1024;function M(n,e,t){return{type:"invalid_request_error",code:n,message:e,param:t??null}}function Re(n,e){return{type:"server_error",code:n,message:e}}function A(n){return{type:"error",event_id:g("event"),error:n}}function tt(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var _=class extends Error{constructor(t,o,s="invalid_value"){super(t);this.param=o;this.code=s;this.name="SessionUpdateError"}param;code},$n={model:!0,instructions:!0,modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Nn={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Un={format:!0,voice:!0,speed:!0};function Ut(n,e){let t=n;if(!t||typeof t!="object"||t.type!=="audio/pcm"||t.rate!==void 0&&t.rate!==24e3)throw new _(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function xe(n,e,t){if(!n||typeof n!="object"||Array.isArray(n))throw new _("session must be an object","session","invalid_request");let o=n,s=Object.keys(o).filter(r=>!(r in $n));if(s.length>0)throw new _(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");let i={...e,outputModalities:[...e.outputModalities]};for(let[r,a]of Object.entries(o))switch(r){case"model":if(a!==null&&typeof a!="string")throw new _("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new _("instructions must be a string or null","instructions");i.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new _("modalities must be a non-empty array","modalities");let d=[];for(let u of a){if(u!=="text"&&u!=="audio")throw new _(`modality ${JSON.stringify(u)} is not "text" or "audio"`,"modalities");if(u==="audio"&&!t.voice)throw new _('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");d.includes(u)||d.push(u)}i.outputModalities=d;break}case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new _("voice must be a string or null","voice");if(!t.voice)throw new _("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new _(`${r} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,r);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new _("temperature must be a finite number or null","temperature");i.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new _(`${r} must be a positive integer, "inf" or null`,r);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new _("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new _("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!t.turns)throw new _("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let d=a;if(!d||typeof d!="object"||Array.isArray(d))throw new _("turn_detection must be an object or null","turn_detection");let u=String(d.type??"");if(u!=="server_vad"&&u!=="semantic_vad")throw new _(`turn_detection.type ${JSON.stringify(d.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");i.turnDetection={createResponse:d.create_response!==!1,interruptResponse:d.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!t.turns)throw new _("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new _("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new _(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new _("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let d=a;if(!d||typeof d!="object"||Array.isArray(d))throw new _("audio must be an object or null","audio");if(d.input!==void 0&&d.input!==null){let u=d.input;if(!u||typeof u!="object"||Array.isArray(u))throw new _("audio.input must be an object","audio.input");for(let c of Object.keys(u))if(!(c in Nn))throw new _(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(u.format!==void 0&&Ut(u.format,"audio.input.format"),u.transcription!==null&&u.transcription!==void 0){let c=xe({input_audio_transcription:u.transcription},i,t);i.inputAudioTranscription=c.inputAudioTranscription}if(u.turn_detection!==null&&u.turn_detection!==void 0){let c=xe({turn_detection:u.turn_detection},i,t);i.turnDetection=c.turnDetection}if(u.noise_reduction!==null&&u.noise_reduction!==void 0)throw new _("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(d.output!==void 0&&d.output!==null){let u=d.output;if(!u||typeof u!="object"||Array.isArray(u))throw new _("audio.output must be an object","audio.output");for(let c of Object.keys(u))if(!(c in Un))throw new _(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(u.format!==void 0&&Ut(u.format,"audio.output.format"),u.speed!==void 0)throw new _("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(u.voice!==void 0)if(u.voice===null)delete i.voice;else{if(typeof u.voice!="string")throw new _("audio.output.voice must be a string or null","audio.output.voice");if(!t.voice)throw new _("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=u.voice}u.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function je(n,e){return{id:e,object:"realtime.session",model:n.model??null,instructions:n.instructions??"",modalities:[...n.outputModalities],voice:n.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:n.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:n.turnDetection?{type:"server_vad",create_response:n.turnDetection.createResponse,interrupt_response:n.turnDetection.interruptResponse}:null,temperature:n.temperature??null,max_response_output_tokens:n.maxOutputTokens??"inf",tool_choice:n.toolChoice??"auto",tools:n.tools??[],metadata:n.metadata??null}}function nt(n,e){let t=n;if(!t||typeof t!="object")throw new _("item must be an object","item","invalid_request");if(t.type==="function_call_output"){if(typeof t.call_id!="string"||typeof t.output!="string")throw new _("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof t.id=="string"?t.id:g("item"),type:"function_call_output",callId:t.call_id,output:t.output}}if(t.type==="message"){let o=t.role;if(o!=="user"&&o!=="assistant"&&o!=="system")throw new _('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(t.content))throw new _("message item content must be an array","item.content","invalid_request");let s=[];for(let i of t.content){let r=i;if(!r||typeof r!="object")throw new _("content part must be an object","item.content","invalid_request");if(r.type==="input_text"||o==="assistant"&&r.type==="output_text"){if(typeof r.text!="string")throw new _(`${String(r.type)} part requires string text`,"item.content.text","invalid_request");s.push({type:r.type,text:r.text});continue}if(r.type==="input_audio"){if(!e)throw new _("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof r.audio!="string")throw new _("input_audio part requires base64 audio","item.content.audio","invalid_request");s.push({type:"input_audio",...typeof r.transcript=="string"?{transcript:r.transcript}:{}});continue}throw new _(`content part type ${String(r.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof t.id=="string"?t.id:g("item"),type:"message",role:o,content:s}}throw new _(`item type ${String(t.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function ot(n){let e=[],t=!1;for(let o of n){if(o.type==="function_call"){e.push({type:"function_call",call_id:o.callId,name:o.name,arguments:o.arguments??"{}"});continue}if(o.type==="function_call_output"){e.push({type:"function_call_output",call_id:o.callId,output:o.output});continue}let s=[];for(let i of o.content??[]){if(i.type==="input_text"||i.type==="output_text"){s.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let r=i.transcript;if(typeof r=="string"&&r.trim().length>0){s.push({type:"input_text",text:r});continue}t=!0;continue}}e.push({role:o.role,content:s})}return{input:e,sawAudioOnlyItem:t}}var Bn=1001,Dn=1011,Dt=n=>n.slice(0,120),Fn=/^[A-Za-z0-9+/=]*$/,le=class{id=g("conn");ws;binding;onClosed;config=tt();sessionId=g("sess");conversationId=g("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnTranscript={open:!1,text:""};lastCommittedTranscript=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.ws.on("message",t=>{this.onMessage(t)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:g("event"),session:je(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:g("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let t=this.binding.turns;(async()=>{try{for await(let o of t()){if(this.closed||e.signal.aborted)return;this.onTurnEvent(o)}}catch(o){!this.closed&&!e.signal.aborted&&this.send(A(Re("turn_lane_fault",`the backend turn/transcript lane failed: ${o instanceof Error?o.message:String(o)}`)))}})()}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let t=typeof e.text=="string"?e.text:"";if(t.length===0)return;this.turnTranscript.open=!0,this.turnTranscript.text+=t,this.config.inputAudioTranscription&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:g("event"),item_id:"input_audio_turn",content_index:0,delta:t});return}case"turn_start":{this.turnTranscript={open:!0,text:this.turnTranscript.text},this.send({type:"input_audio_buffer.speech_started",event_id:g("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let t=this.turnTranscript.text.trim(),o=t.length>0?t:null;this.turnTranscript={open:!1,text:""},this.lastCommittedTranscript=o,this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let s=g("item"),i=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...o!==null?{transcript:o}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:g("event"),previous_item_id:i,item_id:s}),this.send({type:"conversation.item.created",event_id:g("event"),previous_item_id:i,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:g("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.inputAudioTranscription&&o!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:g("event"),item_id:s,content_index:0,transcript:o}),this.config.turnDetection?.createResponse&&!this.inFlight&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let t;try{t=e.toString()}catch{this.fail(M("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(t,"utf8")>De){this.fail(M("frame_too_large",`frame exceeds the ${De}-byte limit`),"invalid_frame");return}let o;try{o=JSON.parse(t)}catch{this.fail(M("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof o.type!="string"||o.type.length===0){this.fail(M("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(o)}catch(s){let i=s;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(A({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}this.fail(Re(null,s instanceof Error?s.message:String(s)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=xe(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0}),this.send({type:"session.updated",event_id:g("event"),session:je(this.config,this.sessionId)});return;case"conversation.item.create":{let t=nt(e.item,this.binding.voice),o=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(t),this.send({type:"conversation.item.created",event_id:g("event"),previous_item_id:o,item:this.itemToProtocol(t)});return}case"conversation.item.delete":{let t=this.items.findIndex(o=>o.id===e.item_id);if(t<0){this.send(A(M("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(t,1),this.send({type:"conversation.item.deleted",event_id:g("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let t=this.items.find(o=>o.id===e.item_id);if(!t){this.send(A(M("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:g("event"),item:this.itemToProtocol(t)});return}case"conversation.item.truncate":{let t=this.items.find(o=>o.id===e.item_id);if(!t||t.type!=="message"||t.role!=="assistant"){this.send(A(M("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}t.truncated=!0,this.send({type:"conversation.item.truncated",event_id:g("event"),item_id:t.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(A(M("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Fn.test(e.audio)){this.send(A(M("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioBytes.length+t>Ve){this.send(A(M("buffer_full",`uncommitted input audio exceeds the ${Ve}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=t;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.send({type:"input_audio_buffer.cleared",event_id:g("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(A(M("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let t=this.takeTurnTranscript();t===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let o=g("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...t!==null?{transcript:t}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:g("event"),previous_item_id:s,item_id:o}),this.send({type:"conversation.item.created",event_id:g("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])});return}case"output_audio_buffer.clear":{this.send(A(M("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(A(M("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(A(M("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,t=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(t.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");t.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(A({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}upstreamStream(e,t){let o=this.binding.session;if(o&&typeof o.sendResponseCreate=="function")return o.sendResponseCreate(e,e.input??[],t);let s=this.binding.clients;if(s&&typeof s.createResponse=="function")return s.createResponse(e);throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(A(M("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let t=e??{};if(t.modalities!==void 0){if(!Array.isArray(t.modalities)||t.modalities.some(v=>v!=="text"&&v!=="audio")){this.send(A(M("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(t.modalities.includes("audio")&&!this.ensureVoice())return}if(t.input!==void 0){this.send(A(M("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let o=g("req"),s=`resp_${o}`;this.activeResponseId=s;let i=this.items.length,{input:r,sawAudioOnlyItem:a}=ot(this.items),d=typeof t.instructions=="string"?t.instructions:this.config.instructions,u=typeof t.temperature=="number"?t.temperature:this.config.temperature,c=t.max_output_tokens??this.config.maxOutputTokens,l=c==="inf"||c===void 0?void 0:c,f=t.tools!==void 0?t.tools:this.config.tools,h=t.tool_choice!==void 0?t.tool_choice:this.config.toolChoice,w={input:r,stream:!0,...this.config.model?{model:this.config.model}:{},...d!==void 0?{instructions:d}:{},...u!==void 0?{temperature:u}:{},...l!==void 0?{max_output_tokens:l}:{},...f!==void 0?{tools:f}:{},...h!==void 0?{tool_choice:h}:{}};for(let v of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(v);this.inFlight=(async()=>{let v=[],y=T=>{this.responseFlushed?this.send(T):v.push(T)},x=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:g("event"),response:this.responseObject(s,"in_progress")}),this.send({type:"response.in_progress",event_id:g("event"),response:this.responseObject(s,"in_progress")});for(let T of v)this.send(T);v.length=0,this.responseFlushed=!0}},R={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},U=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let T;try{T=this.upstreamStream(w,o)}catch(N){this.emitUpstreamFault(N,s);return}try{for await(let N of T){if(this.cancelled)break;let p=N;if(p.type==="error"){let k=this.upstreamErrorBody(p);this.responseFlushed?this.send(A(k)):this.send({type:"response.failed",event_id:g("event"),response:this.failedResponse(s,k)});return}if(p.type==="response.output_text.delta"&&typeof p.delta=="string"){x(),R.messageOpen||(this.beginMessageItem(s,R.nextOutputIndex++),R.messageOpen=!0),y({type:"response.output_text.delta",event_id:g("event"),item_id:`${s}_msg_0`,response_id:s,output_index:0,content_index:0,delta:p.delta}),R.messageText+=p.delta;continue}if(p.type==="response.function_call_arguments.delta"){x();let k=typeof p.delta=="string"?p.delta:"",L=typeof p.call_id=="string"&&p.call_id.length>0?p.call_id:`${s}_fc_${R.nextOutputIndex}`,I=R.tools.get(L);if(!I){let D=typeof p.name=="string"&&p.name.length>0?p.name:void 0;I={outputIndex:R.nextOutputIndex++,name:D,args:""},R.tools.set(L,I),y({type:"response.output_item.added",event_id:g("event"),response_id:s,output_index:I.outputIndex,item:{id:L,object:"realtime.item",type:"function_call",call_id:L,name:D??"",arguments:"",status:"in_progress"}})}typeof p.name=="string"&&p.name.length>0&&(I.name=p.name),I.args+=k,y({type:"response.function_call_arguments.delta",event_id:g("event"),item_id:L,response_id:s,output_index:I.outputIndex,call_id:L,name:I.name??"",delta:k});continue}if(p.type==="response.completed"){U=p.response??null;continue}}}catch(N){this.emitUpstreamFault(N,s);return}if(this.cancelled)return;this.closeOpenItems(s,R,i),x(),this.send({type:"response.done",event_id:g("event"),response:this.doneResponse(s,i,U)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,t){if(this.cancelled)return;if(this.activeResponseId!==e){!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(A({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:g("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:g("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let o=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:g("event"),item_id:o,response_id:e,output_index:0,content_index:0,delta:t})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,t){let o=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:g("event"),response_id:e,output_index:t,item:{id:o,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:g("event"),item_id:o,response_id:e,output_index:t,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let t=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:g("event"),response_id:e,output_index:0,item:{id:t,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:g("event"),item_id:t,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,t,o){if(t.messageOpen||this.messageItemOpenForAudio){let s=`${e}_msg_0`,i=this.messageItemOpenForAudio;i&&this.send({type:"response.output_audio.done",event_id:g("event"),item_id:s,response_id:e,output_index:0,content_index:0}),t.messageText.length>0&&this.send({type:"response.output_text.done",event_id:g("event"),item_id:s,response_id:e,output_index:0,content_index:0,text:t.messageText}),this.send({type:"response.content_part.done",event_id:g("event"),item_id:s,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:""}:{type:"output_text",text:t.messageText}});let r=[];i&&r.push({type:"output_audio"}),t.messageText.length>0&&r.push({type:"output_text",text:t.messageText});let a={id:s,type:"message",role:"assistant",content:r};this.pushItem(a),this.send({type:"response.output_item.done",event_id:g("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[s,i]of t.tools){let r=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:g("event"),item_id:s,response_id:e,output_index:i.outputIndex,call_id:s,name:i.name??"",arguments:r});let a={id:s,type:"function_call",callId:s,name:i.name,arguments:r};this.pushItem(a),this.send({type:"response.output_item.done",event_id:g("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,t,o){return{id:e,object:"realtime.response",status:t,conversation_id:this.conversationId,usage:null,...o??{}}}failedResponse(e,t){return this.responseObject(e,"failed",{status_details:{error:{code:t.code,message:t.message}}})}doneResponse(e,t,o){let s=o&&typeof o.usage=="object"&&o.usage!==null?o.usage:null,i=[];for(let r=t;r<this.items.length;r++)i.push(this.itemToProtocol(this.items[r]));return this.responseObject(e,"completed",{output:i,usage:s?{input_tokens:typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0,output_tokens:typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0,total_tokens:typeof s.total_tokens=="number"&&Number.isFinite(s.total_tokens)?s.total_tokens:(typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0)+(typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let t=e.error,o=t&&typeof t.message=="string"?t.message:JSON.stringify(e);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:o}}emitUpstreamFault(e,t){if(this.cancelled)return;let o=Re(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(A(o)):this.send({type:"response.failed",event_id:g("event"),response:this.failedResponse(t,o)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(A(M("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let t=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:g("event"),response:this.responseObject(t,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Fe&&(this.items.shift(),this.send(A({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Fe} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let t={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...t,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...t,type:"function_call_output",call_id:e.callId,output:e.output};let o=(e.content??[]).map(s=>s.type==="input_text"||s.type==="output_text"?{type:s.type,text:s.text}:s.type==="input_audio"?{type:"input_audio",...s.transcript?{transcript:s.transcript}:{}}:{type:"output_audio",transcript:s.transcript??""});return{...t,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:o}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>et){this.ws.close(Bn,Dt("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,t){this.send(A(e)),this.ws.close(Dn,Dt(t)),this.teardown(t)}teardown(e){if(!this.closed){this.closed=!0,this.turnLaneAbort?.abort(),this.turnLaneAbort=null,this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null;try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this),Vn(this.id,e)}}},st=[];function Vn(n,e){st.push({id:n,reason:e}),st.length>256&&st.shift()}var qe="/v1/realtime",jn=n=>n.slice(0,120);function qn(n,e,t){let o=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";n.write(`HTTP/1.1 ${e} ${o}\r
46
+ Connection: close\r
47
+ Content-Type: text/plain\r
48
+ \r
49
+ ${jn(t)}\r
50
+ `),n.destroy()}function it(n,e){let t=new Ft.WebSocketServer({noServer:!0}),o=new Set;return n.on("upgrade",(s,i,r)=>{if(new URL(s.url??"/","http://localhost").pathname!==qe)return;o.add(i),i.on("close",()=>{o.delete(i)});let d=c=>{let l=c,f=l.session!=null&&typeof l.session.sendResponseCreate=="function",h=l.clients!=null&&typeof l.clients.createResponse=="function";if(!f&&!h)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((w,v)=>{t.handleUpgrade(s,i,r,y=>{try{new le({ws:y,binding:c}),w()}catch(x){v(x)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(s).then(d).catch(c=>{let l=c&&typeof c=="object"&&typeof c.status=="number"?c.status:502,f=c instanceof Error?c.message:String(c);i.destroyed||qn(i,l,f)}).finally(()=>{o.delete(i)})}),async()=>{let s=Date.now()+5e3;for(;o.size>0&&Date.now()<s;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>t.close(()=>i()))}}0&&(module.exports={GEMINI_LIVE_PATH,OPENAI_REALTIME_PATH,OpenAIRealtimeConnection,ResumptionRegistry,SessionGoneError,UnknownModelError,VIDEO_OUT_SETUP_KEY,attachGeminiLive,attachOpenAIRealtime,createOpenAIProxy,serveGeminiLiveSocket});