@urun-sh/openai 0.6.22 → 0.6.25

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.
@@ -1,36 +1,36 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var qa=Object.create;var So=Object.defineProperty;var Ha=Object.getOwnPropertyDescriptor;var Ga=Object.getOwnPropertyNames;var Va=Object.getPrototypeOf,Ja=Object.prototype.hasOwnProperty;var Wa=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Ka=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var za=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ga(e))!Ja.call(t,o)&&o!==n&&So(t,o,{get:()=>e[o],enumerable:!(r=Ha(e,o))||r.enumerable});return t};var ft=(t,e,n)=>(n=t!=null?qa(Va(t)):{},za(e||!t||!t.__esModule?So(n,"default",{value:t,enumerable:!0}):n,t));var x=Wa(()=>{"use strict"});var Ro=Ka(()=>{"use strict";x();var ko;(function(t){(function(e){var n=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),r=o(t);typeof n.Reflect<"u"&&(r=o(n.Reflect,r)),e(r,n),typeof n.Reflect>"u"&&(n.Reflect=t);function o(u,l){return function(d,c){Object.defineProperty(u,d,{configurable:!0,writable:!0,value:c}),l&&l(d,c)}}function i(){try{return Function("return this;")()}catch{}}function s(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return i()||s()}})(function(e,n){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",i=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",s=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",u={__proto__:[]}instanceof Array,l=!a&&!u,d={create:a?function(){return lr(Object.create(null))}:u?function(){return lr({__proto__:null})}:function(){return lr({})},has:l?function(f,g){return r.call(f,g)}:function(f,g){return g in f},get:l?function(f,g){return r.call(f,g)?f[g]:void 0}:function(f,g){return f[g]}},c=Object.getPrototypeOf(Function),_=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Ua(),m=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Da(),p=typeof WeakMap=="function"?WeakMap:Fa(),w=o?Symbol.for("@reflect-metadata:registry"):void 0,y=La(),v=$a(y);function k(f,g,b,E){if(I(b)){if(!Tt(f))throw new TypeError;if(!ho(g))throw new TypeError;return Y(f,g)}else{if(!Tt(f))throw new TypeError;if(!q(g))throw new TypeError;if(!q(E)&&!I(E)&&!X(E))throw new TypeError;return X(E)&&(E=void 0),b=be(b),le(f,g,b,E)}}e("decorate",k);function h(f,g){function b(E,U){if(!q(E))throw new TypeError;if(!I(U)&&!Ca(U))throw new TypeError;te(f,g,E,U)}return b}e("metadata",h);function A(f,g,b,E){if(!q(b))throw new TypeError;return I(E)||(E=be(E)),te(f,g,b,E)}e("defineMetadata",A);function R(f,g,b){if(!q(g))throw new TypeError;return I(b)||(b=be(b)),he(f,g,b)}e("hasMetadata",R);function S(f,g,b){if(!q(g))throw new TypeError;return I(b)||(b=be(b)),ve(f,g,b)}e("hasOwnMetadata",S);function O(f,g,b){if(!q(g))throw new TypeError;return I(b)||(b=be(b)),Te(f,g,b)}e("getMetadata",O);function j(f,g,b){if(!q(g))throw new TypeError;return I(b)||(b=be(b)),ee(f,g,b)}e("getOwnMetadata",j);function P(f,g){if(!q(f))throw new TypeError;return I(g)||(g=be(g)),de(f,g)}e("getMetadataKeys",P);function F(f,g){if(!q(f))throw new TypeError;return I(g)||(g=be(g)),Le(f,g)}e("getOwnMetadataKeys",F);function G(f,g,b){if(!q(g))throw new TypeError;if(I(b)||(b=be(b)),!q(g))throw new TypeError;I(b)||(b=be(b));var E=Pt(g,b,!1);return I(E)?!1:E.OrdinaryDeleteMetadata(f,g,b)}e("deleteMetadata",G);function Y(f,g){for(var b=f.length-1;b>=0;--b){var E=f[b],U=E(g);if(!I(U)&&!X(U)){if(!ho(U))throw new TypeError;g=U}}return g}function le(f,g,b,E){for(var U=f.length-1;U>=0;--U){var ie=f[U],ce=ie(g,b,E);if(!I(ce)&&!X(ce)){if(!q(ce))throw new TypeError;E=ce}}return E}function he(f,g,b){var E=ve(f,g,b);if(E)return!0;var U=ur(g);return X(U)?!1:he(f,U,b)}function ve(f,g,b){var E=Pt(g,b,!1);return I(E)?!1:Be(E.OrdinaryHasOwnMetadata(f,g,b))}function Te(f,g,b){var E=ve(f,g,b);if(E)return ee(f,g,b);var U=ur(g);if(!X(U))return Te(f,U,b)}function ee(f,g,b){var E=Pt(g,b,!1);if(!I(E))return E.OrdinaryGetOwnMetadata(f,g,b)}function te(f,g,b,E){var U=Pt(b,E,!0);U.OrdinaryDefineOwnMetadata(f,g,b,E)}function de(f,g){var b=Le(f,g),E=ur(f);if(E===null)return b;var U=de(E,g);if(U.length<=0)return b;if(b.length<=0)return U;for(var ie=new m,ce=[],J=0,C=b;J<C.length;J++){var M=C[J],L=ie.has(M);L||(ie.add(M),ce.push(M))}for(var $=0,W=U;$<W.length;$++){var M=W[$],L=ie.has(M);L||(ie.add(M),ce.push(M))}return ce}function Le(f,g){var b=Pt(f,g,!1);return b?b.OrdinaryOwnMetadataKeys(f,g):[]}function H(f){if(f===null)return 1;switch(typeof f){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return f===null?1:6;default:return 6}}function I(f){return f===void 0}function X(f){return f===null}function Pe(f){return typeof f=="symbol"}function q(f){return typeof f=="object"?f!==null:typeof f=="function"}function me(f,g){switch(H(f)){case 0:return f;case 1:return f;case 2:return f;case 3:return f;case 4:return f;case 5:return f}var b=g===3?"string":g===5?"number":"default",E=go(f,i);if(E!==void 0){var U=E.call(f,b);if(q(U))throw new TypeError;return U}return $e(f,b==="default"?"number":b)}function $e(f,g){if(g==="string"){var b=f.toString;if(je(b)){var E=b.call(f);if(!q(E))return E}var U=f.valueOf;if(je(U)){var E=U.call(f);if(!q(E))return E}}else{var U=f.valueOf;if(je(U)){var E=U.call(f);if(!q(E))return E}var ie=f.toString;if(je(ie)){var E=ie.call(f);if(!q(E))return E}}throw new TypeError}function Be(f){return!!f}function pt(f){return""+f}function be(f){var g=me(f,3);return Pe(g)?g:pt(g)}function Tt(f){return Array.isArray?Array.isArray(f):f instanceof Object?f instanceof Array:Object.prototype.toString.call(f)==="[object Array]"}function je(f){return typeof f=="function"}function ho(f){return typeof f=="function"}function Ca(f){switch(H(f)){case 3:return!0;case 4:return!0;default:return!1}}function ar(f,g){return f===g||f!==f&&g!==g}function go(f,g){var b=f[g];if(b!=null){if(!je(b))throw new TypeError;return b}}function yo(f){var g=go(f,s);if(!je(g))throw new TypeError;var b=g.call(f);if(!q(b))throw new TypeError;return b}function wo(f){return f.value}function _o(f){var g=f.next();return g.done?!1:g}function vo(f){var g=f.return;g&&g.call(f)}function ur(f){var g=Object.getPrototypeOf(f);if(typeof f!="function"||f===c||g!==c)return g;var b=f.prototype,E=b&&Object.getPrototypeOf(b);if(E==null||E===Object.prototype)return g;var U=E.constructor;return typeof U!="function"||U===f?g:U}function Ma(){var f;!I(w)&&typeof n.Reflect<"u"&&!(w in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(f=Na(n.Reflect));var g,b,E,U=new p,ie={registerProvider:ce,getProvider:C,setProvider:L};return ie;function ce($){if(!Object.isExtensible(ie))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case f===$:break;case I(g):g=$;break;case g===$:break;case I(b):b=$;break;case b===$:break;default:E===void 0&&(E=new m),E.add($);break}}function J($,W){if(!I(g)){if(g.isProviderFor($,W))return g;if(!I(b)){if(b.isProviderFor($,W))return g;if(!I(E))for(var Q=yo(E);;){var se=_o(Q);if(!se)return;var Ce=wo(se);if(Ce.isProviderFor($,W))return vo(Q),Ce}}}if(!I(f)&&f.isProviderFor($,W))return f}function C($,W){var Q=U.get($),se;return I(Q)||(se=Q.get(W)),I(se)&&(se=J($,W),I(se)||(I(Q)&&(Q=new _,U.set($,Q)),Q.set(W,se))),se}function M($){if(I($))throw new TypeError;return g===$||b===$||!I(E)&&E.has($)}function L($,W,Q){if(!M(Q))throw new Error("Metadata provider not registered.");var se=C($,W);if(se!==Q){if(!I(se))return!1;var Ce=U.get($);I(Ce)&&(Ce=new _,U.set($,Ce)),Ce.set(W,Q)}return!0}}function La(){var f;return!I(w)&&q(n.Reflect)&&Object.isExtensible(n.Reflect)&&(f=n.Reflect[w]),I(f)&&(f=Ma()),!I(w)&&q(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:f}),f}function $a(f){var g=new p,b={isProviderFor:function(M,L){var $=g.get(M);return I($)?!1:$.has(L)},OrdinaryDefineOwnMetadata:ce,OrdinaryHasOwnMetadata:U,OrdinaryGetOwnMetadata:ie,OrdinaryOwnMetadataKeys:J,OrdinaryDeleteMetadata:C};return y.registerProvider(b),b;function E(M,L,$){var W=g.get(M),Q=!1;if(I(W)){if(!$)return;W=new _,g.set(M,W),Q=!0}var se=W.get(L);if(I(se)){if(!$)return;if(se=new _,W.set(L,se),!f.setProvider(M,L,b))throw W.delete(L),Q&&g.delete(M),new Error("Wrong provider for target.")}return se}function U(M,L,$){var W=E(L,$,!1);return I(W)?!1:Be(W.has(M))}function ie(M,L,$){var W=E(L,$,!1);if(!I(W))return W.get(M)}function ce(M,L,$,W){var Q=E($,W,!0);Q.set(M,L)}function J(M,L){var $=[],W=E(M,L,!1);if(I(W))return $;for(var Q=W.keys(),se=yo(Q),Ce=0;;){var bo=_o(se);if(!bo)return $.length=Ce,$;var Ba=wo(bo);try{$[Ce]=Ba}catch(ja){try{vo(se)}finally{throw ja}}Ce++}}function C(M,L,$){var W=E(L,$,!1);if(I(W)||!W.delete(M))return!1;if(W.size===0){var Q=g.get(L);I(Q)||(Q.delete($),Q.size===0&&g.delete(Q))}return!0}}function Na(f){var g=f.defineMetadata,b=f.hasOwnMetadata,E=f.getOwnMetadata,U=f.getOwnMetadataKeys,ie=f.deleteMetadata,ce=new p,J={isProviderFor:function(C,M){var L=ce.get(C);return!I(L)&&L.has(M)?!0:U(C,M).length?(I(L)&&(L=new m,ce.set(C,L)),L.add(M),!0):!1},OrdinaryDefineOwnMetadata:g,OrdinaryHasOwnMetadata:b,OrdinaryGetOwnMetadata:E,OrdinaryOwnMetadataKeys:U,OrdinaryDeleteMetadata:ie};return J}function Pt(f,g,b){var E=y.getProvider(f,g);if(!I(E))return E;if(b){if(y.setProvider(f,g,v))return v;throw new Error("Illegal state.")}}function Ua(){var f={},g=[],b=(function(){function J(C,M,L){this._index=0,this._keys=C,this._values=M,this._selector=L}return J.prototype["@@iterator"]=function(){return this},J.prototype[s]=function(){return this},J.prototype.next=function(){var C=this._index;if(C>=0&&C<this._keys.length){var M=this._selector(this._keys[C],this._values[C]);return C+1>=this._keys.length?(this._index=-1,this._keys=g,this._values=g):this._index++,{value:M,done:!1}}return{value:void 0,done:!0}},J.prototype.throw=function(C){throw this._index>=0&&(this._index=-1,this._keys=g,this._values=g),C},J.prototype.return=function(C){return this._index>=0&&(this._index=-1,this._keys=g,this._values=g),{value:C,done:!0}},J})(),E=(function(){function J(){this._keys=[],this._values=[],this._cacheKey=f,this._cacheIndex=-2}return Object.defineProperty(J.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),J.prototype.has=function(C){return this._find(C,!1)>=0},J.prototype.get=function(C){var M=this._find(C,!1);return M>=0?this._values[M]:void 0},J.prototype.set=function(C,M){var L=this._find(C,!0);return this._values[L]=M,this},J.prototype.delete=function(C){var M=this._find(C,!1);if(M>=0){for(var L=this._keys.length,$=M+1;$<L;$++)this._keys[$-1]=this._keys[$],this._values[$-1]=this._values[$];return this._keys.length--,this._values.length--,ar(C,this._cacheKey)&&(this._cacheKey=f,this._cacheIndex=-2),!0}return!1},J.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=f,this._cacheIndex=-2},J.prototype.keys=function(){return new b(this._keys,this._values,U)},J.prototype.values=function(){return new b(this._keys,this._values,ie)},J.prototype.entries=function(){return new b(this._keys,this._values,ce)},J.prototype["@@iterator"]=function(){return this.entries()},J.prototype[s]=function(){return this.entries()},J.prototype._find=function(C,M){if(!ar(this._cacheKey,C)){this._cacheIndex=-1;for(var L=0;L<this._keys.length;L++)if(ar(this._keys[L],C)){this._cacheIndex=L;break}}return this._cacheIndex<0&&M&&(this._cacheIndex=this._keys.length,this._keys.push(C),this._values.push(void 0)),this._cacheIndex},J})();return E;function U(J,C){return J}function ie(J,C){return C}function ce(J,C){return[J,C]}}function Da(){var f=(function(){function g(){this._map=new _}return Object.defineProperty(g.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),g.prototype.has=function(b){return this._map.has(b)},g.prototype.add=function(b){return this._map.set(b,b),this},g.prototype.delete=function(b){return this._map.delete(b)},g.prototype.clear=function(){this._map.clear()},g.prototype.keys=function(){return this._map.keys()},g.prototype.values=function(){return this._map.keys()},g.prototype.entries=function(){return this._map.entries()},g.prototype["@@iterator"]=function(){return this.keys()},g.prototype[s]=function(){return this.keys()},g})();return f}function Fa(){var f=16,g=d.create(),b=E();return(function(){function C(){this._key=E()}return C.prototype.has=function(M){var L=U(M,!1);return L!==void 0?d.has(L,this._key):!1},C.prototype.get=function(M){var L=U(M,!1);return L!==void 0?d.get(L,this._key):void 0},C.prototype.set=function(M,L){var $=U(M,!0);return $[this._key]=L,this},C.prototype.delete=function(M){var L=U(M,!1);return L!==void 0?delete L[this._key]:!1},C.prototype.clear=function(){this._key=E()},C})();function E(){var C;do C="@@WeakMap@@"+J();while(d.has(g,C));return g[C]=!0,C}function U(C,M){if(!r.call(C,b)){if(!M)return;Object.defineProperty(C,b,{value:d.create()})}return C[b]}function ie(C,M){for(var L=0;L<M;++L)C[L]=Math.random()*255|0;return C}function ce(C){if(typeof Uint8Array=="function"){var M=new Uint8Array(C);return typeof crypto<"u"?crypto.getRandomValues(M):typeof msCrypto<"u"?msCrypto.getRandomValues(M):ie(M,C),M}return ie(new Array(C),C)}function J(){var C=ce(f);C[6]=C[6]&79|64,C[8]=C[8]&191|128;for(var M="",L=0;L<f;++L){var $=C[L];(L===4||L===6||L===8)&&(M+="-"),$<16&&(M+="0"),M+=$.toString(16).toLowerCase()}return M}}function lr(f){return f.__=void 0,delete f.__,f}})})(ko||(ko={}))});x();var Xh=ft(Ro(),1),Me=ft(require("process"),1);x();var Su=ft(require("os"),1),ku=ft(require("path"),1),Ru=require("url"),xu=require("util");x();x();var pe=class extends Error{},Ya=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Xa(t){if(typeof t!="string")return!1;let e=Ya.exec(t);if(!e)return!1;let[,n,r,o,i,s,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let u=new Date(Date.UTC(n,r-1,o,i,s,a));return u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===o&&u.getUTCHours()===i&&u.getUTCMinutes()===s&&u.getUTCSeconds()===a}function Qa(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new pe(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:i}=e;if(typeof n!="string"||n==="")throw new pe(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new pe(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let s=r.map((a,u)=>{if(a===null||typeof a!="object")throw new pe(`catalog shared endpoints[${u}] is not an object: ${JSON.stringify(a)}`);let l=a;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new pe(`catalog shared endpoints[${u}] (${JSON.stringify(l)}) has no valid "${c}"`);let d=(c,_)=>{if(l[c]!==void 0&&l[c]!==null&&!_)throw new pe(`catalog shared endpoints[${u}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};d("ready",typeof l.ready=="boolean"),d("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),d("ready_since",Xa(l.ready_since));for(let c of["model_id","variant"]){let _=l[c];if(_.includes(":"))throw new pe(`catalog shared endpoints[${u}] has "${c}" containing ":" (${JSON.stringify(_)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof l.output_free=="boolean"),l});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new pe(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(i!=null){let a=i;if(typeof i!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new pe(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(i)}`);for(let u of Object.keys(a))if(u!=="zdr"&&u!=="hipaa")throw new pe(`catalog "shared" block compliance carries "${u}" beyond the declared zdr/hipaa contract: ${JSON.stringify(i)}`)}return s.length===0?null:{shared_org_id:n,endpoints:s,...o!=null?{regions:o}:{},...i!=null?{compliance:i}:{}}}function mt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function xo(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,i=n,s=r.lastIndexOf(":");s>0&&(o=r.slice(0,s),i=r.slice(s+1));let a=t.endpoints.filter(l=>l.model_id===o);if(a.length===0)return null;if(i!==void 0){let l=a.find(d=>d.variant===i);return l?{shared_org_id:t.shared_org_id,endpoint:l}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let u=a.filter(l=>l.compat_default===!0);if(u.length!==1)throw new pe(`shared model "${o}" has ${u.length} compat_default rows (exactly one required) among variants ${a.map(l=>l.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:u[0]}}async function Eo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new pe(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Qa(await r.json())}x();function qe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}x();var xe=class extends Error{name="ModelPriceError"},dr="per_million_input_tokens",cr="per_million_output_tokens",Ao="model_id,variant,unit,price_usd,effective_at,expires_at",Oo={per_request:!0,per_minute:!0,per_output_unit:!0},Za=5e3;function eu(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new xe(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Io(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new xe(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function tu(t,e,n){return t===null?null:Io(t,e,n)}function nu(t,e){if(t===dr)return"input";if(t===cr)return"output";if(typeof t=="string"&&Object.hasOwn(Oo,t))return null;throw new xe(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${dr} | ${cr}) nor a known GPU-time unit (${Object.keys(Oo).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function ru(t,e){let n=t.reduce((o,i)=>i.effective_at>o.effective_at?i:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:n}}function pr(t,e){return`${t}\0${e}`}function ou(t){if(!Array.isArray(t))throw new xe(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new xe(`${o} is not an object: ${JSON.stringify(r)}`);let i=r;for(let l of Ao.split(","))if(!Object.hasOwn(i,l))throw new xe(`${o} has no "${l}" column: ${JSON.stringify(i)}`);let s=nu(i.unit,o);if(s===null)continue;let a=i.model_id;if(typeof a!="string"||a==="")throw new xe(`${o} has no model_id (${JSON.stringify(i)})`);let u=i.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new xe(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:s,usd:eu(i.price_usd,o),effective_at:Io(i.effective_at,o,"effective_at"),expires_at:tu(i.expires_at,o,"expires_at")})}return e}function To(t,e=Date.now(),n){let r=new Map,o=new Map;for(let u of t){if(u.effective_at>e||u.expires_at!==null&&u.expires_at<=e)continue;let l=r.get(u.model_id);l||(l=new Map,r.set(u.model_id,l),o.set(u.model_id,new Map));let d=u.variant??"",c=l.get(d);c||(c={input:[],output:[]},l.set(d,c),o.get(u.model_id).set(d,u.variant)),c[u.side].push({effective_at:u.effective_at,usd:u.usd})}let i=[],s=[];for(let[u,l]of r){let d=l.get(""),c=(_,m,p)=>{let w=_&&_.length>0?_:d?.[m];if(!w||w.length===0)return null;let y=ru(w,m);return"reason"in y?y:y.rate.usd===0?m==="output"&&p!==null&&n?.has(pr(u,p))?y.rate:{reason:`the ${m} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:y.rate};for(let[_,m]of o.get(u)){let p=l.get(_),w=c(p?.input,"input",m),y=c(p?.output,"output",m);if(w!==null&&"reason"in w){s.push({model_id:u,variant:m,reason:w.reason});continue}if(y!==null&&"reason"in y){s.push({model_id:u,variant:m,reason:y.reason});continue}w===null||y===null||i.push({model_id:u,variant:m,pricing:{input:w.usd,output:y.usd}})}}let a=(u,l)=>u.model_id.localeCompare(l.model_id)||(u.variant===null?1:0)-(l.variant===null?1:0)||(u.variant??"").localeCompare(l.variant??"");return{prices:i.sort(a),refusals:s.sort(a)}}function Ct(t,e,n){if(n.refusals.some(i=>i.model_id===t&&i.variant===e))return null;let r=n.prices.find(i=>i.model_id===t&&i.variant===e);if(r)return r.pricing;if(n.refusals.some(i=>i.model_id===t&&i.variant===null))return null;let o=n.prices.find(i=>i.model_id===t&&i.variant===null);return o?o.pricing:null}var Mt={prices:[],refusals:[]};async function Po(t){let e=t.fetchImpl??fetch,n=`${dr},${cr}`,r=await e(`${t.catalogUrl}/model_prices?select=${Ao}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Za)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return ou(await r.json())}x();var Ze="/partners/openrouter/models",iu={chat:!0,code:!0,agent:!0,vl:!0},Co={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function su(t){let e=t.toLowerCase();return Object.hasOwn(Co,e)?Co[e]:null}var Mo={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function au(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let i=Object.hasOwn(Mo,o)?Mo[o]:null;if(i===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:i,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var Lo={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},$o={2:"Llama2",3:"Llama3"};function uu(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let i=r[o];if(Object.hasOwn(Lo,i))return Lo[i];let s=r[o+1];if(i==="llama"&&s!==void 0&&Object.hasOwn($o,s))return $o[s];if(i==="phi"&&s!==void 0&&/^\d/.test(s))return"Phi"}return null}var lu=["context_length","max_model_len"];function du(t){let e=lu.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function tn(t){let e=t.map(du),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function cu(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function fr(t){if(t.length===0)return null;let e=t.map(cu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function pu(t,e){let n=e.filter(o=>qe(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return en(n);let r=e.filter(o=>qe(o.model_id)===t);return r.length>0?en(r):null}function en(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:fu(t),matches:t}:null}function fu(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}function Do(t){return 0}function Qe(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function nn(t,e,n){let r=pu(t,e);if(!r)return Qe({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:i}=r,s=tn(i),a=Ct(o.model_id,o.variant,n),u=Fo(o,i),l=fr(i);return Qe({id:t,object:"model",created:Do(o),owned_by:"urun",...s!==null?{context_length:s}:{},...a!==null?{pricing:a}:{},...u.published.length>0?{voices:[...u.published]}:{},...l!==null?{capabilities:{reasoning:l}}:{}})}var mu=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Fo(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(i=>i.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(i=>typeof i=="string")&&n.every(i=>Array.isArray(i)&&i.length===r.length&&i.every((s,a)=>s===r[a])))return{published:[...r],defect:null};let o=n.some(i=>i!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...mu],defect:o}:{published:[],defect:o}}function mr(t){let e=t.length>0?en(t):null;return e===null?{published:[],defect:null}:Fo(e.row,e.matches)}function No(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,i=n+r,s=n.length-6+(o===""?0:Number(o));return(s<=0?`0.${"0".repeat(-s)}${i}`:`${i.slice(0,s)}.${i.slice(s).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Uo(t){return{input:[{type:"prompt",unit:"token",cost_usd:No(t.input)}],output:[{type:"completion",unit:"token",cost_usd:No(t.output)}]}}function hu(t,e,n,r){if(e.length===0)return null;let o=en(e);if(!o)return null;let{row:i,matches:s}=o;if(!i.task||iu[i.task]!==!0)return null;let a=tn(s),u=Ct(i.model_id,i.variant,n),l=uu(i.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${i.model_id}:${i.variant}`,name:`${i.model_id}:${i.variant}`,created:Do(i),quantization:su(i.variant),...l!==null?{tokenizer:l}:{},description:i.description??"",hugging_face_id:i.hf_repo?i.hf_repo.split("@")[0]??i.hf_repo:"",is_ready:t.ready===!0&&u!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...u?{pricing:Uo(u).input}:{}},...i.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...u?{pricing:Uo(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Bo(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),i=t?mt(t):[];if(i.length>0){let l=i.filter(d=>d.ready===void 0);if(l.length===i.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let d=l.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let s={datacenters:au(t?.regions,o),compliance:t?.compliance??null},a=[],u=new Set;for(let l of i){let d=`${l.model_id}:${l.variant}`;if(u.has(d))continue;u.add(d);let c=hu(l,e.filter(_=>_.model_id===l.model_id&&_.variant===l.variant),n,s);c&&a.push(c)}return{data:a}}x();var jo={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},ht=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function qo(t){let e=t.t;if(typeof e!="string"||!(e in jo))throw new ht(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(jo).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function gu(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new ht(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new ht(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return qo(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new ht(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return qo(t)}function Ho(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function yu(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=s=>{r||(r=!0,e.removeEventListener("abort",i),n(s))},i=()=>o("aborted");e.addEventListener("abort",i,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function Go(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Ho(e);let i=o.next();if(e!==void 0&&await yu(i,e)==="aborted")throw i.catch(()=>{}),Ho(e);let s=await i;if(s.done)return;yield gu(s.value)}}finally{let i=o.return?.();i&&i.catch(()=>{})}}return r()}var z=class extends Error{},re=class extends Error{},gr="urs1.";function Vo(t,e){return gr+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function wu(t){if(!t.startsWith(gr))return null;try{let e=JSON.parse(Buffer.from(t.slice(gr.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function zo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Jo(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=vu(t);return e===null?[]:[e]}function hr(t,e,n,r,o){if(!o)throw new pe(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new pe(`shared model "${t}" resolved without a catalog id + variant to join on`);let i=r.filter(s=>s.model_id===e&&s.variant===n);if(i.length===0)throw new pe(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return i}function Wo(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new pe(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var Yo="shared:",Lt="speech:";function Ke(t){return t.sharedApp?Yo+t.appSlug:t.appSlug}function on(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function Je(t,e){let n=e.filter(i=>qe(`${i.model_id}-${i.variant}`)===t);if(n.length>0)return n;let r=e.filter(i=>qe(i.model_id)===t);return new Set(r.map(i=>i.variant)).size===1?r:[]}function _u(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function vu(t){let e=t.map(_u),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Ko={stt:"stt",tts:"tts"};function We(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||Ko[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?Ko[e]:null}function bu(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new Error(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var rn=6e4,sn=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;rowsCache=null;seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??rn;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}async sharedBlock(){if(!this.opts.shared)return null;let e=this.opts.appsTtlMs??rn;if(this.sharedCache&&Date.now()-this.sharedCache.at<e)return this.sharedCache.block;let n=await this.opts.shared();return this.sharedCache={at:Date.now(),block:n},n}sharedCache=null;async catalogRows(){if(!this.opts.listCatalog)return[];let e=this.opts.appsTtlMs??rn;if(this.rowsCache&&Date.now()-this.rowsCache.at<e)return this.rowsCache.rows;let n=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:n},n}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??rn;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof xe)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
2
+ "use strict";var qa=Object.create;var So=Object.defineProperty;var Ha=Object.getOwnPropertyDescriptor;var Ga=Object.getOwnPropertyNames;var Va=Object.getPrototypeOf,Wa=Object.prototype.hasOwnProperty;var Ja=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Ka=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var za=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ga(e))!Wa.call(t,o)&&o!==n&&So(t,o,{get:()=>e[o],enumerable:!(r=Ha(e,o))||r.enumerable});return t};var ft=(t,e,n)=>(n=t!=null?qa(Va(t)):{},za(e||!t||!t.__esModule?So(n,"default",{value:t,enumerable:!0}):n,t));var x=Ja(()=>{"use strict"});var Ro=Ka(()=>{"use strict";x();var ko;(function(t){(function(e){var n=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),r=o(t);typeof n.Reflect<"u"&&(r=o(n.Reflect,r)),e(r,n),typeof n.Reflect>"u"&&(n.Reflect=t);function o(u,l){return function(d,c){Object.defineProperty(u,d,{configurable:!0,writable:!0,value:c}),l&&l(d,c)}}function i(){try{return Function("return this;")()}catch{}}function s(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return i()||s()}})(function(e,n){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",i=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",s=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",u={__proto__:[]}instanceof Array,l=!a&&!u,d={create:a?function(){return lr(Object.create(null))}:u?function(){return lr({__proto__:null})}:function(){return lr({})},has:l?function(f,g){return r.call(f,g)}:function(f,g){return g in f},get:l?function(f,g){return r.call(f,g)?f[g]:void 0}:function(f,g){return f[g]}},c=Object.getPrototypeOf(Function),_=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Ua(),m=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Da(),p=typeof WeakMap=="function"?WeakMap:Fa(),w=o?Symbol.for("@reflect-metadata:registry"):void 0,y=La(),b=$a(y);function k(f,g,S,E){if(I(S)){if(!Tt(f))throw new TypeError;if(!ho(g))throw new TypeError;return Y(f,g)}else{if(!Tt(f))throw new TypeError;if(!q(g))throw new TypeError;if(!q(E)&&!I(E)&&!X(E))throw new TypeError;return X(E)&&(E=void 0),S=be(S),le(f,g,S,E)}}e("decorate",k);function h(f,g){function S(E,U){if(!q(E))throw new TypeError;if(!I(U)&&!Ca(U))throw new TypeError;te(f,g,E,U)}return S}e("metadata",h);function A(f,g,S,E){if(!q(S))throw new TypeError;return I(E)||(E=be(E)),te(f,g,S,E)}e("defineMetadata",A);function R(f,g,S){if(!q(g))throw new TypeError;return I(S)||(S=be(S)),he(f,g,S)}e("hasMetadata",R);function v(f,g,S){if(!q(g))throw new TypeError;return I(S)||(S=be(S)),ve(f,g,S)}e("hasOwnMetadata",v);function O(f,g,S){if(!q(g))throw new TypeError;return I(S)||(S=be(S)),Te(f,g,S)}e("getMetadata",O);function j(f,g,S){if(!q(g))throw new TypeError;return I(S)||(S=be(S)),ee(f,g,S)}e("getOwnMetadata",j);function P(f,g){if(!q(f))throw new TypeError;return I(g)||(g=be(g)),de(f,g)}e("getMetadataKeys",P);function F(f,g){if(!q(f))throw new TypeError;return I(g)||(g=be(g)),Le(f,g)}e("getOwnMetadataKeys",F);function G(f,g,S){if(!q(g))throw new TypeError;if(I(S)||(S=be(S)),!q(g))throw new TypeError;I(S)||(S=be(S));var E=Pt(g,S,!1);return I(E)?!1:E.OrdinaryDeleteMetadata(f,g,S)}e("deleteMetadata",G);function Y(f,g){for(var S=f.length-1;S>=0;--S){var E=f[S],U=E(g);if(!I(U)&&!X(U)){if(!ho(U))throw new TypeError;g=U}}return g}function le(f,g,S,E){for(var U=f.length-1;U>=0;--U){var ie=f[U],ce=ie(g,S,E);if(!I(ce)&&!X(ce)){if(!q(ce))throw new TypeError;E=ce}}return E}function he(f,g,S){var E=ve(f,g,S);if(E)return!0;var U=ur(g);return X(U)?!1:he(f,U,S)}function ve(f,g,S){var E=Pt(g,S,!1);return I(E)?!1:Be(E.OrdinaryHasOwnMetadata(f,g,S))}function Te(f,g,S){var E=ve(f,g,S);if(E)return ee(f,g,S);var U=ur(g);if(!X(U))return Te(f,U,S)}function ee(f,g,S){var E=Pt(g,S,!1);if(!I(E))return E.OrdinaryGetOwnMetadata(f,g,S)}function te(f,g,S,E){var U=Pt(S,E,!0);U.OrdinaryDefineOwnMetadata(f,g,S,E)}function de(f,g){var S=Le(f,g),E=ur(f);if(E===null)return S;var U=de(E,g);if(U.length<=0)return S;if(S.length<=0)return U;for(var ie=new m,ce=[],W=0,C=S;W<C.length;W++){var M=C[W],L=ie.has(M);L||(ie.add(M),ce.push(M))}for(var $=0,J=U;$<J.length;$++){var M=J[$],L=ie.has(M);L||(ie.add(M),ce.push(M))}return ce}function Le(f,g){var S=Pt(f,g,!1);return S?S.OrdinaryOwnMetadataKeys(f,g):[]}function H(f){if(f===null)return 1;switch(typeof f){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return f===null?1:6;default:return 6}}function I(f){return f===void 0}function X(f){return f===null}function Pe(f){return typeof f=="symbol"}function q(f){return typeof f=="object"?f!==null:typeof f=="function"}function me(f,g){switch(H(f)){case 0:return f;case 1:return f;case 2:return f;case 3:return f;case 4:return f;case 5:return f}var S=g===3?"string":g===5?"number":"default",E=go(f,i);if(E!==void 0){var U=E.call(f,S);if(q(U))throw new TypeError;return U}return $e(f,S==="default"?"number":S)}function $e(f,g){if(g==="string"){var S=f.toString;if(je(S)){var E=S.call(f);if(!q(E))return E}var U=f.valueOf;if(je(U)){var E=U.call(f);if(!q(E))return E}}else{var U=f.valueOf;if(je(U)){var E=U.call(f);if(!q(E))return E}var ie=f.toString;if(je(ie)){var E=ie.call(f);if(!q(E))return E}}throw new TypeError}function Be(f){return!!f}function pt(f){return""+f}function be(f){var g=me(f,3);return Pe(g)?g:pt(g)}function Tt(f){return Array.isArray?Array.isArray(f):f instanceof Object?f instanceof Array:Object.prototype.toString.call(f)==="[object Array]"}function je(f){return typeof f=="function"}function ho(f){return typeof f=="function"}function Ca(f){switch(H(f)){case 3:return!0;case 4:return!0;default:return!1}}function ar(f,g){return f===g||f!==f&&g!==g}function go(f,g){var S=f[g];if(S!=null){if(!je(S))throw new TypeError;return S}}function yo(f){var g=go(f,s);if(!je(g))throw new TypeError;var S=g.call(f);if(!q(S))throw new TypeError;return S}function wo(f){return f.value}function _o(f){var g=f.next();return g.done?!1:g}function vo(f){var g=f.return;g&&g.call(f)}function ur(f){var g=Object.getPrototypeOf(f);if(typeof f!="function"||f===c||g!==c)return g;var S=f.prototype,E=S&&Object.getPrototypeOf(S);if(E==null||E===Object.prototype)return g;var U=E.constructor;return typeof U!="function"||U===f?g:U}function Ma(){var f;!I(w)&&typeof n.Reflect<"u"&&!(w in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(f=Na(n.Reflect));var g,S,E,U=new p,ie={registerProvider:ce,getProvider:C,setProvider:L};return ie;function ce($){if(!Object.isExtensible(ie))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case f===$:break;case I(g):g=$;break;case g===$:break;case I(S):S=$;break;case S===$:break;default:E===void 0&&(E=new m),E.add($);break}}function W($,J){if(!I(g)){if(g.isProviderFor($,J))return g;if(!I(S)){if(S.isProviderFor($,J))return g;if(!I(E))for(var Q=yo(E);;){var se=_o(Q);if(!se)return;var Ce=wo(se);if(Ce.isProviderFor($,J))return vo(Q),Ce}}}if(!I(f)&&f.isProviderFor($,J))return f}function C($,J){var Q=U.get($),se;return I(Q)||(se=Q.get(J)),I(se)&&(se=W($,J),I(se)||(I(Q)&&(Q=new _,U.set($,Q)),Q.set(J,se))),se}function M($){if(I($))throw new TypeError;return g===$||S===$||!I(E)&&E.has($)}function L($,J,Q){if(!M(Q))throw new Error("Metadata provider not registered.");var se=C($,J);if(se!==Q){if(!I(se))return!1;var Ce=U.get($);I(Ce)&&(Ce=new _,U.set($,Ce)),Ce.set(J,Q)}return!0}}function La(){var f;return!I(w)&&q(n.Reflect)&&Object.isExtensible(n.Reflect)&&(f=n.Reflect[w]),I(f)&&(f=Ma()),!I(w)&&q(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:f}),f}function $a(f){var g=new p,S={isProviderFor:function(M,L){var $=g.get(M);return I($)?!1:$.has(L)},OrdinaryDefineOwnMetadata:ce,OrdinaryHasOwnMetadata:U,OrdinaryGetOwnMetadata:ie,OrdinaryOwnMetadataKeys:W,OrdinaryDeleteMetadata:C};return y.registerProvider(S),S;function E(M,L,$){var J=g.get(M),Q=!1;if(I(J)){if(!$)return;J=new _,g.set(M,J),Q=!0}var se=J.get(L);if(I(se)){if(!$)return;if(se=new _,J.set(L,se),!f.setProvider(M,L,S))throw J.delete(L),Q&&g.delete(M),new Error("Wrong provider for target.")}return se}function U(M,L,$){var J=E(L,$,!1);return I(J)?!1:Be(J.has(M))}function ie(M,L,$){var J=E(L,$,!1);if(!I(J))return J.get(M)}function ce(M,L,$,J){var Q=E($,J,!0);Q.set(M,L)}function W(M,L){var $=[],J=E(M,L,!1);if(I(J))return $;for(var Q=J.keys(),se=yo(Q),Ce=0;;){var bo=_o(se);if(!bo)return $.length=Ce,$;var Ba=wo(bo);try{$[Ce]=Ba}catch(ja){try{vo(se)}finally{throw ja}}Ce++}}function C(M,L,$){var J=E(L,$,!1);if(I(J)||!J.delete(M))return!1;if(J.size===0){var Q=g.get(L);I(Q)||(Q.delete($),Q.size===0&&g.delete(Q))}return!0}}function Na(f){var g=f.defineMetadata,S=f.hasOwnMetadata,E=f.getOwnMetadata,U=f.getOwnMetadataKeys,ie=f.deleteMetadata,ce=new p,W={isProviderFor:function(C,M){var L=ce.get(C);return!I(L)&&L.has(M)?!0:U(C,M).length?(I(L)&&(L=new m,ce.set(C,L)),L.add(M),!0):!1},OrdinaryDefineOwnMetadata:g,OrdinaryHasOwnMetadata:S,OrdinaryGetOwnMetadata:E,OrdinaryOwnMetadataKeys:U,OrdinaryDeleteMetadata:ie};return W}function Pt(f,g,S){var E=y.getProvider(f,g);if(!I(E))return E;if(S){if(y.setProvider(f,g,b))return b;throw new Error("Illegal state.")}}function Ua(){var f={},g=[],S=(function(){function W(C,M,L){this._index=0,this._keys=C,this._values=M,this._selector=L}return W.prototype["@@iterator"]=function(){return this},W.prototype[s]=function(){return this},W.prototype.next=function(){var C=this._index;if(C>=0&&C<this._keys.length){var M=this._selector(this._keys[C],this._values[C]);return C+1>=this._keys.length?(this._index=-1,this._keys=g,this._values=g):this._index++,{value:M,done:!1}}return{value:void 0,done:!0}},W.prototype.throw=function(C){throw this._index>=0&&(this._index=-1,this._keys=g,this._values=g),C},W.prototype.return=function(C){return this._index>=0&&(this._index=-1,this._keys=g,this._values=g),{value:C,done:!0}},W})(),E=(function(){function W(){this._keys=[],this._values=[],this._cacheKey=f,this._cacheIndex=-2}return Object.defineProperty(W.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),W.prototype.has=function(C){return this._find(C,!1)>=0},W.prototype.get=function(C){var M=this._find(C,!1);return M>=0?this._values[M]:void 0},W.prototype.set=function(C,M){var L=this._find(C,!0);return this._values[L]=M,this},W.prototype.delete=function(C){var M=this._find(C,!1);if(M>=0){for(var L=this._keys.length,$=M+1;$<L;$++)this._keys[$-1]=this._keys[$],this._values[$-1]=this._values[$];return this._keys.length--,this._values.length--,ar(C,this._cacheKey)&&(this._cacheKey=f,this._cacheIndex=-2),!0}return!1},W.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=f,this._cacheIndex=-2},W.prototype.keys=function(){return new S(this._keys,this._values,U)},W.prototype.values=function(){return new S(this._keys,this._values,ie)},W.prototype.entries=function(){return new S(this._keys,this._values,ce)},W.prototype["@@iterator"]=function(){return this.entries()},W.prototype[s]=function(){return this.entries()},W.prototype._find=function(C,M){if(!ar(this._cacheKey,C)){this._cacheIndex=-1;for(var L=0;L<this._keys.length;L++)if(ar(this._keys[L],C)){this._cacheIndex=L;break}}return this._cacheIndex<0&&M&&(this._cacheIndex=this._keys.length,this._keys.push(C),this._values.push(void 0)),this._cacheIndex},W})();return E;function U(W,C){return W}function ie(W,C){return C}function ce(W,C){return[W,C]}}function Da(){var f=(function(){function g(){this._map=new _}return Object.defineProperty(g.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),g.prototype.has=function(S){return this._map.has(S)},g.prototype.add=function(S){return this._map.set(S,S),this},g.prototype.delete=function(S){return this._map.delete(S)},g.prototype.clear=function(){this._map.clear()},g.prototype.keys=function(){return this._map.keys()},g.prototype.values=function(){return this._map.keys()},g.prototype.entries=function(){return this._map.entries()},g.prototype["@@iterator"]=function(){return this.keys()},g.prototype[s]=function(){return this.keys()},g})();return f}function Fa(){var f=16,g=d.create(),S=E();return(function(){function C(){this._key=E()}return C.prototype.has=function(M){var L=U(M,!1);return L!==void 0?d.has(L,this._key):!1},C.prototype.get=function(M){var L=U(M,!1);return L!==void 0?d.get(L,this._key):void 0},C.prototype.set=function(M,L){var $=U(M,!0);return $[this._key]=L,this},C.prototype.delete=function(M){var L=U(M,!1);return L!==void 0?delete L[this._key]:!1},C.prototype.clear=function(){this._key=E()},C})();function E(){var C;do C="@@WeakMap@@"+W();while(d.has(g,C));return g[C]=!0,C}function U(C,M){if(!r.call(C,S)){if(!M)return;Object.defineProperty(C,S,{value:d.create()})}return C[S]}function ie(C,M){for(var L=0;L<M;++L)C[L]=Math.random()*255|0;return C}function ce(C){if(typeof Uint8Array=="function"){var M=new Uint8Array(C);return typeof crypto<"u"?crypto.getRandomValues(M):typeof msCrypto<"u"?msCrypto.getRandomValues(M):ie(M,C),M}return ie(new Array(C),C)}function W(){var C=ce(f);C[6]=C[6]&79|64,C[8]=C[8]&191|128;for(var M="",L=0;L<f;++L){var $=C[L];(L===4||L===6||L===8)&&(M+="-"),$<16&&(M+="0"),M+=$.toString(16).toLowerCase()}return M}}function lr(f){return f.__=void 0,delete f.__,f}})})(ko||(ko={}))});x();var Xh=ft(Ro(),1),Me=ft(require("process"),1);x();var Su=ft(require("os"),1),ku=ft(require("path"),1),Ru=require("url"),xu=require("util");x();x();var pe=class extends Error{},Ya=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Xa(t){if(typeof t!="string")return!1;let e=Ya.exec(t);if(!e)return!1;let[,n,r,o,i,s,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let u=new Date(Date.UTC(n,r-1,o,i,s,a));return u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===o&&u.getUTCHours()===i&&u.getUTCMinutes()===s&&u.getUTCSeconds()===a}function Qa(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new pe(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:i}=e;if(typeof n!="string"||n==="")throw new pe(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new pe(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let s=r.map((a,u)=>{if(a===null||typeof a!="object")throw new pe(`catalog shared endpoints[${u}] is not an object: ${JSON.stringify(a)}`);let l=a;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new pe(`catalog shared endpoints[${u}] (${JSON.stringify(l)}) has no valid "${c}"`);let d=(c,_)=>{if(l[c]!==void 0&&l[c]!==null&&!_)throw new pe(`catalog shared endpoints[${u}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};d("ready",typeof l.ready=="boolean"),d("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),d("ready_since",Xa(l.ready_since));for(let c of["model_id","variant"]){let _=l[c];if(_.includes(":"))throw new pe(`catalog shared endpoints[${u}] has "${c}" containing ":" (${JSON.stringify(_)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof l.output_free=="boolean"),l});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new pe(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(i!=null){let a=i;if(typeof i!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new pe(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(i)}`);for(let u of Object.keys(a))if(u!=="zdr"&&u!=="hipaa")throw new pe(`catalog "shared" block compliance carries "${u}" beyond the declared zdr/hipaa contract: ${JSON.stringify(i)}`)}return s.length===0?null:{shared_org_id:n,endpoints:s,...o!=null?{regions:o}:{},...i!=null?{compliance:i}:{}}}function mt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function xo(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,i=n,s=r.lastIndexOf(":");s>0&&(o=r.slice(0,s),i=r.slice(s+1));let a=t.endpoints.filter(l=>l.model_id===o);if(a.length===0)return null;if(i!==void 0){let l=a.find(d=>d.variant===i);return l?{shared_org_id:t.shared_org_id,endpoint:l}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let u=a.filter(l=>l.compat_default===!0);if(u.length!==1)throw new pe(`shared model "${o}" has ${u.length} compat_default rows (exactly one required) among variants ${a.map(l=>l.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:u[0]}}async function Eo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new pe(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Qa(await r.json())}x();function qe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}x();var xe=class extends Error{name="ModelPriceError"},dr="per_million_input_tokens",cr="per_million_output_tokens",Ao="model_id,variant,unit,price_usd,effective_at,expires_at",Oo={per_request:!0,per_minute:!0,per_output_unit:!0},Za=5e3;function eu(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new xe(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Io(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new xe(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function tu(t,e,n){return t===null?null:Io(t,e,n)}function nu(t,e){if(t===dr)return"input";if(t===cr)return"output";if(typeof t=="string"&&Object.hasOwn(Oo,t))return null;throw new xe(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${dr} | ${cr}) nor a known GPU-time unit (${Object.keys(Oo).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function ru(t,e){let n=t.reduce((o,i)=>i.effective_at>o.effective_at?i:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:n}}function pr(t,e){return`${t}\0${e}`}function ou(t){if(!Array.isArray(t))throw new xe(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new xe(`${o} is not an object: ${JSON.stringify(r)}`);let i=r;for(let l of Ao.split(","))if(!Object.hasOwn(i,l))throw new xe(`${o} has no "${l}" column: ${JSON.stringify(i)}`);let s=nu(i.unit,o);if(s===null)continue;let a=i.model_id;if(typeof a!="string"||a==="")throw new xe(`${o} has no model_id (${JSON.stringify(i)})`);let u=i.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new xe(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:s,usd:eu(i.price_usd,o),effective_at:Io(i.effective_at,o,"effective_at"),expires_at:tu(i.expires_at,o,"expires_at")})}return e}function To(t,e=Date.now(),n){let r=new Map,o=new Map;for(let u of t){if(u.effective_at>e||u.expires_at!==null&&u.expires_at<=e)continue;let l=r.get(u.model_id);l||(l=new Map,r.set(u.model_id,l),o.set(u.model_id,new Map));let d=u.variant??"",c=l.get(d);c||(c={input:[],output:[]},l.set(d,c),o.get(u.model_id).set(d,u.variant)),c[u.side].push({effective_at:u.effective_at,usd:u.usd})}let i=[],s=[];for(let[u,l]of r){let d=l.get(""),c=(_,m,p)=>{let w=_&&_.length>0?_:d?.[m];if(!w||w.length===0)return null;let y=ru(w,m);return"reason"in y?y:y.rate.usd===0?m==="output"&&p!==null&&n?.has(pr(u,p))?y.rate:{reason:`the ${m} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:y.rate};for(let[_,m]of o.get(u)){let p=l.get(_),w=c(p?.input,"input",m),y=c(p?.output,"output",m);if(w!==null&&"reason"in w){s.push({model_id:u,variant:m,reason:w.reason});continue}if(y!==null&&"reason"in y){s.push({model_id:u,variant:m,reason:y.reason});continue}w===null||y===null||i.push({model_id:u,variant:m,pricing:{input:w.usd,output:y.usd}})}}let a=(u,l)=>u.model_id.localeCompare(l.model_id)||(u.variant===null?1:0)-(l.variant===null?1:0)||(u.variant??"").localeCompare(l.variant??"");return{prices:i.sort(a),refusals:s.sort(a)}}function Ct(t,e,n){if(n.refusals.some(i=>i.model_id===t&&i.variant===e))return null;let r=n.prices.find(i=>i.model_id===t&&i.variant===e);if(r)return r.pricing;if(n.refusals.some(i=>i.model_id===t&&i.variant===null))return null;let o=n.prices.find(i=>i.model_id===t&&i.variant===null);return o?o.pricing:null}var Mt={prices:[],refusals:[]};async function Po(t){let e=t.fetchImpl??fetch,n=`${dr},${cr}`,r=await e(`${t.catalogUrl}/model_prices?select=${Ao}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Za)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return ou(await r.json())}x();var Ze="/partners/openrouter/models",iu={chat:!0,code:!0,agent:!0,vl:!0},Co={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function su(t){let e=t.toLowerCase();return Object.hasOwn(Co,e)?Co[e]:null}var Mo={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function au(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let i=Object.hasOwn(Mo,o)?Mo[o]:null;if(i===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:i,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var Lo={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},$o={2:"Llama2",3:"Llama3"};function uu(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let i=r[o];if(Object.hasOwn(Lo,i))return Lo[i];let s=r[o+1];if(i==="llama"&&s!==void 0&&Object.hasOwn($o,s))return $o[s];if(i==="phi"&&s!==void 0&&/^\d/.test(s))return"Phi"}return null}var lu=["context_length","max_model_len"];function du(t){let e=lu.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function tn(t){let e=t.map(du),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function cu(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function fr(t){if(t.length===0)return null;let e=t.map(cu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function pu(t,e){let n=e.filter(o=>qe(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return en(n);let r=e.filter(o=>qe(o.model_id)===t);return r.length>0?en(r):null}function en(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:fu(t),matches:t}:null}function fu(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}function Do(t){return 0}function Qe(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function nn(t,e,n){let r=pu(t,e);if(!r)return Qe({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:i}=r,s=tn(i),a=Ct(o.model_id,o.variant,n),u=Fo(o,i),l=fr(i);return Qe({id:t,object:"model",created:Do(o),owned_by:"urun",...s!==null?{context_length:s}:{},...a!==null?{pricing:a}:{},...u.published.length>0?{voices:[...u.published]}:{},...l!==null?{capabilities:{reasoning:l}}:{}})}var mu=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Fo(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(i=>i.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(i=>typeof i=="string")&&n.every(i=>Array.isArray(i)&&i.length===r.length&&i.every((s,a)=>s===r[a])))return{published:[...r],defect:null};let o=n.some(i=>i!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...mu],defect:o}:{published:[],defect:o}}function mr(t){let e=t.length>0?en(t):null;return e===null?{published:[],defect:null}:Fo(e.row,e.matches)}function No(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,i=n+r,s=n.length-6+(o===""?0:Number(o));return(s<=0?`0.${"0".repeat(-s)}${i}`:`${i.slice(0,s)}.${i.slice(s).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Uo(t){return{input:[{type:"prompt",unit:"token",cost_usd:No(t.input)}],output:[{type:"completion",unit:"token",cost_usd:No(t.output)}]}}function hu(t,e,n,r){if(e.length===0)return null;let o=en(e);if(!o)return null;let{row:i,matches:s}=o;if(!i.task||iu[i.task]!==!0)return null;let a=tn(s),u=Ct(i.model_id,i.variant,n),l=uu(i.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${i.model_id}:${i.variant}`,name:`${i.model_id}:${i.variant}`,created:Do(i),quantization:su(i.variant),...l!==null?{tokenizer:l}:{},description:i.description??"",hugging_face_id:i.hf_repo?i.hf_repo.split("@")[0]??i.hf_repo:"",is_ready:t.ready===!0&&u!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...u?{pricing:Uo(u).input}:{}},...i.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...u?{pricing:Uo(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Bo(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),i=t?mt(t):[];if(i.length>0){let l=i.filter(d=>d.ready===void 0);if(l.length===i.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let d=l.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let s={datacenters:au(t?.regions,o),compliance:t?.compliance??null},a=[],u=new Set;for(let l of i){let d=`${l.model_id}:${l.variant}`;if(u.has(d))continue;u.add(d);let c=hu(l,e.filter(_=>_.model_id===l.model_id&&_.variant===l.variant),n,s);c&&a.push(c)}return{data:a}}x();var jo={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},ht=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function qo(t){let e=t.t;if(typeof e!="string"||!(e in jo))throw new ht(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(jo).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function gu(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new ht(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new ht(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return qo(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new ht(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return qo(t)}function Ho(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function yu(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=s=>{r||(r=!0,e.removeEventListener("abort",i),n(s))},i=()=>o("aborted");e.addEventListener("abort",i,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function Go(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Ho(e);let i=o.next();if(e!==void 0&&await yu(i,e)==="aborted")throw i.catch(()=>{}),Ho(e);let s=await i;if(s.done)return;yield gu(s.value)}}finally{let i=o.return?.();i&&i.catch(()=>{})}}return r()}var z=class extends Error{},re=class extends Error{},gr="urs1.";function Vo(t,e){return gr+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function wu(t){if(!t.startsWith(gr))return null;try{let e=JSON.parse(Buffer.from(t.slice(gr.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function zo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Wo(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=vu(t);return e===null?[]:[e]}function hr(t,e,n,r,o){if(!o)throw new pe(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new pe(`shared model "${t}" resolved without a catalog id + variant to join on`);let i=r.filter(s=>s.model_id===e&&s.variant===n);if(i.length===0)throw new pe(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return i}function Jo(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new pe(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var Yo="shared:",Lt="speech:";function Ke(t){return t.sharedApp?Yo+t.appSlug:t.appSlug}function on(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function We(t,e){let n=e.filter(i=>qe(`${i.model_id}-${i.variant}`)===t);if(n.length>0)return n;let r=e.filter(i=>qe(i.model_id)===t);return new Set(r.map(i=>i.variant)).size===1?r:[]}function _u(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function vu(t){let e=t.map(_u),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Ko={stt:"stt",tts:"tts"};function Je(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||Ko[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?Ko[e]:null}function bu(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new Error(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var rn=6e4,sn=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;rowsCache=null;seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??rn;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}async sharedBlock(){if(!this.opts.shared)return null;let e=this.opts.appsTtlMs??rn;if(this.sharedCache&&Date.now()-this.sharedCache.at<e)return this.sharedCache.block;let n=await this.opts.shared();return this.sharedCache={at:Date.now(),block:n},n}sharedCache=null;async catalogRows(){if(!this.opts.listCatalog)return[];let e=this.opts.appsTtlMs??rn;if(this.rowsCache&&Date.now()-this.rowsCache.at<e)return this.rowsCache.rows;let n=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:n},n}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??rn;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof xe)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
3
3
  `),Mt}let r=To(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
4
4
  `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(pr(r.model_id,r.variant));return n}warn(e){(this.opts.warn??(r=>console.warn(r.trimEnd())))(e)}servable(e){return e.filter(n=>n.serves==="openai"&&n.deployment_status==="active").map(n=>n.app_slug)}async availableIds(){let e=this.opts.defaultApp,n=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let o of this.servable(await this.deployedApps()))n.add(o);for(let o of this.pool.keys())o.startsWith(Yo)||o.startsWith(Lt)||n.add(o);let r=[...n].filter(o=>o!==e).sort();return e===null?r:[e,...r]}async noDefaultApp(e){let n=await this.availableIds(),r=n.length>0?n.join(", "):"(none deployed)";throw new z(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${r}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${r}`)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};let o=qe(n);if(o===r)return{appSlug:r};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let i=await this.deployedApps(),s=this.servable(i);if(s.includes(o))return{appSlug:o};let a=s.filter(l=>l.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new z(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=i.find(l=>l.app_slug===o||l.app_slug.startsWith(`${o}-`));if(u)throw new z(`model "${n}" maps to app "${u.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.shared){let i=await this.sharedBlock();if(i){let s=xo(i,n);if(s)return{appSlug:s.endpoint.app_slug,fnName:s.endpoint.function,sharedApp:!0,modelId:s.endpoint.model_id,variant:s.endpoint.variant,sharedOrgId:i.shared_org_id}}}if(this.opts.listCatalog){let s=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===qe(a.model_id)||o===qe(`${a.model_id}-${a.variant}`));if(s)throw new z(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${s.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=on(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return Ke(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ke(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Lt+Ke(n))}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:on(e)}}keyOf(e){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=n(e);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(e){let{app:n,entry:r}=await this.sessionFor(e);return{app:n,handle:Vo(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Vo(n,this.keyOf(r))}}async sessionForHandle(e){let n=wu(e);if(!n)throw new re(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,i=this.pool.get(r),s=i?await i.then(a=>a,()=>null):null;if(s===null)throw new re(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(s)!==o)throw new re(`the session behind this handle (app "${r}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:r,entry:s}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(i=>i,()=>null)!==n||this.pool.get(e)!==r||(this.pool.delete(e),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),n=await this.sharedBlock(),[r,o]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),i=r.rows,s=r.ok?o:Mt;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
5
- `);let u=(n?mt(n):[]).map(l=>{let d=i.filter(y=>y.model_id===l.model_id&&y.variant===l.variant),c=tn(d),_=fr(d),m=Ct(l.model_id,l.variant,s),p=mr(d);return Qe({id:`${l.model_id}:${l.variant}`,object:"model",created:0,owned_by:"urun",...c!==null?{context_length:c}:{},...m!==null?{pricing:m}:{},...p.published.length>0?{voices:[...p.published]}:{},..._!==null?{capabilities:{reasoning:_}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(l=>nn(l,i,s)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Bo(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let i=hr(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Wo(`${r.modelId}:${r.variant}`,i).includes(n)}return Jo(Je(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?We(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:We(Je(n.appSlug,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?We(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":We(Je(n.appSlug,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?We(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":We(Je(n.appSlug,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(i=>i.model_id===n.modelId&&i.variant===n.variant):Je(n.appSlug,r);return bu(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(i=>i.model_id===n.modelId&&i.variant===n.variant):Je(n.appSlug,r);return mr(o)}async imageModelList(){let e=await this.catalogRows(),n=Mt,r=[];for(let i of await this.availableIds()){let s=Jo(Je(i,e));s.length!==0&&r.push(Qe({...nn(i,e,n),image_modes:s}))}let o=await this.sharedBlock();if(o)for(let i of mt(o)){let s=hr(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null),a=Wo(`${i.model_id}:${i.variant}`,s);if(a.length===0)continue;let u=Qe({id:`${i.model_id}:${i.variant}`,object:"model",created:0,owned_by:"urun",image_modes:a});r.push(u)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=Mt,r=[];for(let i of await this.availableIds())We(Je(i,e))==="stt"&&r.push(nn(i,e,n));let o=await this.sharedBlock();if(o)for(let i of mt(o)){let s=hr(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null);if(We(s)!=="stt")continue;let a=Qe({id:`${i.model_id}:${i.variant}`,object:"model",created:0,owned_by:"urun"});r.push(a)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};function Xo(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function un(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}var Eu=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Qo(t){let e=t?.code;return typeof e=="string"&&Eu.has(e)}function Ne(t,e){try{return t.write(e),!0}catch(n){if(Qo(n))return!1;throw n}}function Zo(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],i=s=>{Qo(s)&&(e[r]=!0);let a=s?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(s instanceof Error?s.message:s))}) \u2014 the terminal is gone; launcher output continues in this log only
5
+ `);let u=(n?mt(n):[]).map(l=>{let d=i.filter(y=>y.model_id===l.model_id&&y.variant===l.variant),c=tn(d),_=fr(d),m=Ct(l.model_id,l.variant,s),p=mr(d);return Qe({id:`${l.model_id}:${l.variant}`,object:"model",created:0,owned_by:"urun",...c!==null?{context_length:c}:{},...m!==null?{pricing:m}:{},...p.published.length>0?{voices:[...p.published]}:{},..._!==null?{capabilities:{reasoning:_}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(l=>nn(l,i,s)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Bo(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let i=hr(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Jo(`${r.modelId}:${r.variant}`,i).includes(n)}return Wo(We(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Je(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Je(We(n.appSlug,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Je(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Je(We(n.appSlug,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Je(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Je(We(n.appSlug,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(i=>i.model_id===n.modelId&&i.variant===n.variant):We(n.appSlug,r);return bu(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(i=>i.model_id===n.modelId&&i.variant===n.variant):We(n.appSlug,r);return mr(o)}async imageModelList(){let e=await this.catalogRows(),n=Mt,r=[];for(let i of await this.availableIds()){let s=Wo(We(i,e));s.length!==0&&r.push(Qe({...nn(i,e,n),image_modes:s}))}let o=await this.sharedBlock();if(o)for(let i of mt(o)){let s=hr(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null),a=Jo(`${i.model_id}:${i.variant}`,s);if(a.length===0)continue;let u=Qe({id:`${i.model_id}:${i.variant}`,object:"model",created:0,owned_by:"urun",image_modes:a});r.push(u)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=Mt,r=[];for(let i of await this.availableIds())Je(We(i,e))==="stt"&&r.push(nn(i,e,n));let o=await this.sharedBlock();if(o)for(let i of mt(o)){let s=hr(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null);if(Je(s)!=="stt")continue;let a=Qe({id:`${i.model_id}:${i.variant}`,object:"model",created:0,owned_by:"urun"});r.push(a)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};function Xo(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function un(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}var Eu=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Qo(t){let e=t?.code;return typeof e=="string"&&Eu.has(e)}function Ne(t,e){try{return t.write(e),!0}catch(n){if(Qo(n))return!1;throw n}}function Zo(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],i=s=>{Qo(s)&&(e[r]=!0);let a=s?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(s instanceof Error?s.message:s))}) \u2014 the terminal is gone; launcher output continues in this log only
6
6
  `)}catch{}};o.on("error",i),n.push([o,i])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}x();var ye=require("@prometheus-io/client"),ki=require("http");x();var Ou={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Au(t){return Ou[t]??null}var ni=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function Iu(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Tu(t){return t==="surface"}function Pu(t){let e=t?.ledgerFailureReason;return ni.includes(e)?e:"unknown"}var Cu=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ei=["priced","unpriced"],Mu={written:ei,already_written:ei,skipped:Cu,failed:ni},ri=Object.entries(Mu).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Lu(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function $u(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var Nu=256,ti=4096,$t=12e4,Uu=250,Du=8e3,He=[],yr=new Set,Nt=0,gt=!1;function oi(){return He.length}function ii(t=Date.now()){let e=He[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var ln=new Set;function si(){return Nt===0&&He.length===0}function ai(){if(si()){gt=!1;for(let t of[...ln])t()}}async function ui(t=di){return si()?!0:await new Promise(e=>{let n=null,r=()=>{ln.delete(r),n&&clearTimeout(n),e(!0)};ln.add(r),n=setTimeout(()=>{ln.delete(r),e(!1)},t),n.unref?.()})}function li(){gt=!0;let t=[...He.splice(0,He.length),...yr];for(let e of t)e.settled||et(e,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:e.attempts,error:`the proxy is shutting down and this row was still unplaced after the ${di}ms drain \u2014 the request was served and answered, and its billing row was never written`});return ai(),t.length}var di=5e3;function ci(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
7
- `}function Fu(t){Ne(process.stdout,t)}function pi(t,e){try{t(e)}catch{}}function fi(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Fu,o=Au(e.path);if(o===null)return;let i=d=>{try{n.observe(d)}catch{}},s=(d,c)=>{i({outcome:"skipped",reason:d}),pi(r,ci("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){s("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){s("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){s("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){s("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:$u(e),completed_at:e.ts,billable_outcome:Lu(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(He.length>=ti){s("queue_full",`${He.length} ledger writes are already waiting (capacity ${ti}, ${Nt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}He.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Nt<Nu&&(Nt+=1,Bu())}async function Bu(){try{for(;;){let t=ju();if(t===void 0)return;yr.add(t);try{await qu(t)}finally{yr.delete(t)}}}finally{Nt-=1,ai()}}function ju(){let t=Date.now();for(;;){let e=He.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<$t)return e;et(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${$t}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function qu(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);et(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let i=Iu(o);if(i!==null){et(t,{outcome:"already_written",reason:i.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:i.cost_nano_usd,price_version:i.price_version,attempts:t.attempts});return}let s=Pu(o),a=Date.now()-t.queuedAt;if(gt){et(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Tu(s)&&a<$t){if(await Gu(Hu(t.attempts)),gt||Date.now()-t.queuedAt>=$t){let u=Date.now()-t.queuedAt;et(t,{outcome:"failed",reason:gt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:gt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${$t}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}et(t,{outcome:"failed",reason:s},{event:"inference_ledger_write_failed",reason:s,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Hu(t){return Math.min(Du,Uu*2**Math.max(0,t-1))}function Gu(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function et(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;pi(t.report,ci(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}x();x();var cn="/v1/usage/requests",mi=1e4,Vu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ze=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},oe=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},dn=class extends oe{constructor(e){super(e),this.name="UsageWithholdingError"}},wi=1024*1024;function vr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ze(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new ze(`"${e}" must be an array of uuid strings`);if(n.length>mi)throw new ze(`"${e}" carries ${n.length} ids; at most ${mi} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let i of n){if(typeof i!="string"||!Vu.test(i))throw new ze(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(i)||(o.add(i),r.push(i))}return r}function _i(t){return vr(t,"inference_ids")}var Ju=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function yt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new oe(`${n}: ${e} is not a non-empty string (got ${_t(r)})`);return r}function wr(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new oe(`${n}: ${e} is neither null nor a non-empty string (got ${_t(r)})`);return r}function wt(t,e,n,r){let o=t[e];if(o===null)return null;let i=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(i))throw new oe(`${n}: ${e} is not a number (got ${_t(o)})`);if(r&&!Number.isSafeInteger(i))throw new oe(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(i<0)throw new oe(`${n}: ${e} is negative`);return Object.is(i,-0)?0:i}var Wu=40,hi=64,gi=600;function vi(t){let e=Object.keys(t).sort(),r=e.slice(0,Wu).map(o=>o.length>hi?`${o.slice(0,hi)}\u2026`:o).join(", ");return r.length>gi&&(r=`${r.slice(0,gi)}\u2026`),`${e.length} keys present: [${r}]`}function _t(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function _r(t){Ne(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
8
- `)}function Ku(t,e){let n;try{n=t(e)}catch{yi(t,e);return}zu(n)&&Promise.resolve(n).catch(()=>{yi(t,e)})}function zu(t){return typeof t?.then=="function"}function yi(t,e){if(t!==_r)try{_r(e)}catch{}}function bi(t,e=_r){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?vi(t):_t(t);throw new oe(`the usage surface answered without a "requests" array: got ${_t(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let i=`usage.requests[${o}]`;try{r.push(Yu(n[o],i))}catch(s){if(s instanceof dn||!(s instanceof oe))throw s;Ku(e,{where:i,reason:s.message})}}if(n.length>0&&r.length===0)throw new oe(`the usage surface returned ${n.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function Yu(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new oe(`${e} is not an object: got ${_t(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new dn(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let o of Ju)if(!Object.hasOwn(n,o))throw new oe(`${e} has no "${o}" column (${vi(n)})`);let r=wt(n,"http_status",e,!0);if(r===null)throw new oe(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:yt(n,"inference_id",e),model_id:yt(n,"model_id",e),identity_kind:yt(n,"identity_kind",e),variant:wr(n,"variant",e),task:yt(n,"task",e),http_status:r,started_at:yt(n,"started_at",e),completed_at:yt(n,"completed_at",e),prompt_tokens:wt(n,"prompt_tokens",e,!0),completion_tokens:wt(n,"completion_tokens",e,!0),output_units:wt(n,"output_units",e,!1),output_minutes:wt(n,"output_minutes",e,!1),cost_nano_usd:wt(n,"cost_nano_usd",e,!0),price_version:wr(n,"price_version",e),priced_at:wr(n,"priced_at",e)}}function pn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let i=t[o];if(!n.has(i.inference_id))throw new oe(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(i.inference_id))throw new oe(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(i.inference_id)}}var Ut="/partners/huggingface/v1/billing/requests";function Xu(t){return vr(t,"requestIds")}function Qu(t){return t>=200&&t<=399}function Zu(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Qu(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Si(t,e){let n=Xu(t),r=await e(n);return pn(r,n),Zu(r)}var br=9464,fn="/metrics",mn="(other)",el="(none)",tl=64,nl=128,rl=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",cn,Ut,Ze],ol=new Set(rl);function il(t){return ol.has(t)?t:mn}function sl(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var hn=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?el:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,mn):(this.admitted.add(e),e):mn}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},gn=class{registry=new ye.Registry;modelLabel=new hn(tl);orgLabel=new hn(nl);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new ye.Counter({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new ye.Histogram({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new ye.Histogram({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new ye.Counter({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new ye.Counter({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new ye.Counter({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of ri)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ye.Gauge({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},oi()),this.ledgerQueue.set({measure:"oldest_age_seconds"},ii()/1e3)}}),this.labelCardinality=new ye.Gauge({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new ye.Counter({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),e.defaultMetrics!==!1&&(0,ye.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=il(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,i=this.modelLabel.of(e.model,r),s=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?mn:e.method,status_class:sl(e.status),stream:u,model:i,org:s}),this.duration.observe({lane:n,stream:u,model:i,org:s},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:i,org:s},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:i}),e.delivered||this.undelivered.inc({lane:n,model:i})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Ri(t){return(0,ki.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==fn){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${fn}
7
+ `}function Fu(t){Ne(process.stdout,t)}function pi(t,e){try{t(e)}catch{}}function fi(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Fu,o=Au(e.path);if(o===null)return;let i=d=>{try{n.observe(d)}catch{}},s=(d,c)=>{i({outcome:"skipped",reason:d}),pi(r,ci("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){s("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){s("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){s("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){s("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:$u(e),completed_at:e.ts,billable_outcome:Lu(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(He.length>=ti){s("queue_full",`${He.length} ledger writes are already waiting (capacity ${ti}, ${Nt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}He.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Nt<Nu&&(Nt+=1,Bu())}async function Bu(){try{for(;;){let t=ju();if(t===void 0)return;yr.add(t);try{await qu(t)}finally{yr.delete(t)}}}finally{Nt-=1,ai()}}function ju(){let t=Date.now();for(;;){let e=He.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<$t)return e;et(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${$t}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function qu(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);et(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let i=Iu(o);if(i!==null){et(t,{outcome:"already_written",reason:i.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:i.cost_nano_usd,price_version:i.price_version,attempts:t.attempts});return}let s=Pu(o),a=Date.now()-t.queuedAt;if(gt){et(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Tu(s)&&a<$t){if(await Gu(Hu(t.attempts)),gt||Date.now()-t.queuedAt>=$t){let u=Date.now()-t.queuedAt;et(t,{outcome:"failed",reason:gt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:gt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${$t}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}et(t,{outcome:"failed",reason:s},{event:"inference_ledger_write_failed",reason:s,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Hu(t){return Math.min(Du,Uu*2**Math.max(0,t-1))}function Gu(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function et(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;pi(t.report,ci(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}x();x();var cn="/v1/usage/requests",mi=1e4,Vu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ze=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},oe=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},dn=class extends oe{constructor(e){super(e),this.name="UsageWithholdingError"}},wi=1024*1024;function vr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ze(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new ze(`"${e}" must be an array of uuid strings`);if(n.length>mi)throw new ze(`"${e}" carries ${n.length} ids; at most ${mi} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let i of n){if(typeof i!="string"||!Vu.test(i))throw new ze(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(i)||(o.add(i),r.push(i))}return r}function _i(t){return vr(t,"inference_ids")}var Wu=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function yt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new oe(`${n}: ${e} is not a non-empty string (got ${_t(r)})`);return r}function wr(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new oe(`${n}: ${e} is neither null nor a non-empty string (got ${_t(r)})`);return r}function wt(t,e,n,r){let o=t[e];if(o===null)return null;let i=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(i))throw new oe(`${n}: ${e} is not a number (got ${_t(o)})`);if(r&&!Number.isSafeInteger(i))throw new oe(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(i<0)throw new oe(`${n}: ${e} is negative`);return Object.is(i,-0)?0:i}var Ju=40,hi=64,gi=600;function vi(t){let e=Object.keys(t).sort(),r=e.slice(0,Ju).map(o=>o.length>hi?`${o.slice(0,hi)}\u2026`:o).join(", ");return r.length>gi&&(r=`${r.slice(0,gi)}\u2026`),`${e.length} keys present: [${r}]`}function _t(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function _r(t){Ne(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
8
+ `)}function Ku(t,e){let n;try{n=t(e)}catch{yi(t,e);return}zu(n)&&Promise.resolve(n).catch(()=>{yi(t,e)})}function zu(t){return typeof t?.then=="function"}function yi(t,e){if(t!==_r)try{_r(e)}catch{}}function bi(t,e=_r){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?vi(t):_t(t);throw new oe(`the usage surface answered without a "requests" array: got ${_t(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let i=`usage.requests[${o}]`;try{r.push(Yu(n[o],i))}catch(s){if(s instanceof dn||!(s instanceof oe))throw s;Ku(e,{where:i,reason:s.message})}}if(n.length>0&&r.length===0)throw new oe(`the usage surface returned ${n.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function Yu(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new oe(`${e} is not an object: got ${_t(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new dn(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let o of Wu)if(!Object.hasOwn(n,o))throw new oe(`${e} has no "${o}" column (${vi(n)})`);let r=wt(n,"http_status",e,!0);if(r===null)throw new oe(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:yt(n,"inference_id",e),model_id:yt(n,"model_id",e),identity_kind:yt(n,"identity_kind",e),variant:wr(n,"variant",e),task:yt(n,"task",e),http_status:r,started_at:yt(n,"started_at",e),completed_at:yt(n,"completed_at",e),prompt_tokens:wt(n,"prompt_tokens",e,!0),completion_tokens:wt(n,"completion_tokens",e,!0),output_units:wt(n,"output_units",e,!1),output_minutes:wt(n,"output_minutes",e,!1),cost_nano_usd:wt(n,"cost_nano_usd",e,!0),price_version:wr(n,"price_version",e),priced_at:wr(n,"priced_at",e)}}function pn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let i=t[o];if(!n.has(i.inference_id))throw new oe(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(i.inference_id))throw new oe(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(i.inference_id)}}var Ut="/partners/huggingface/v1/billing/requests";function Xu(t){return vr(t,"requestIds")}function Qu(t){return t>=200&&t<=399}function Zu(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Qu(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Si(t,e){let n=Xu(t),r=await e(n);return pn(r,n),Zu(r)}var br=9464,fn="/metrics",mn="(other)",el="(none)",tl=64,nl=128,rl=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",cn,Ut,Ze],ol=new Set(rl);function il(t){return ol.has(t)?t:mn}function sl(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var hn=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?el:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,mn):(this.admitted.add(e),e):mn}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},gn=class{registry=new ye.Registry;modelLabel=new hn(tl);orgLabel=new hn(nl);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new ye.Counter({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new ye.Histogram({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new ye.Histogram({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new ye.Counter({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new ye.Counter({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new ye.Counter({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of ri)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ye.Gauge({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},oi()),this.ledgerQueue.set({measure:"oldest_age_seconds"},ii()/1e3)}}),this.labelCardinality=new ye.Gauge({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new ye.Counter({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),e.defaultMetrics!==!1&&(0,ye.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=il(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,i=this.modelLabel.of(e.model,r),s=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?mn:e.method,status_class:sl(e.status),stream:u,model:i,org:s}),this.duration.observe({lane:n,stream:u,model:i,org:s},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:i,org:s},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:i}),e.delivered||this.undelivered.inc({lane:n,model:i})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Ri(t){return(0,ki.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==fn){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${fn}
9
9
  `);return}let o=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(o)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
10
10
  `);return}n.end()})})}x();var Sr=require("crypto"),Ei=require("http"),kr=9465,al="x-urun-key-id",ul="x-urun-key-fingerprint",ll="urun-ratelimit-bucket:",dl="urun-ratelimit-tier:",xi="anonymous",cl=/^urun_sk_[A-Za-z0-9_-]{43}$/;function pl(t){return(0,Sr.createHash)("sha256").update(`${ll}${t}`).digest("hex")}function fl(t){return(0,Sr.createHash)("sha256").update(`${dl}${t}`).digest("hex")}function ml(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return cl.test(n)?n:null}function Oi(){return(0,Ei.createServer)((t,e)=>{let n=ml(t.headers.authorization);e.setHeader(al,n===null?xi:pl(n)),e.setHeader(ul,n===null?xi:fl(n)),e.writeHead(200),e.end()})}x();var hl=8080,Rr="serve",tt="0.0.0.0";function gl(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Ai(t=process.env){let e=(t.PORT??"").trim(),n=e===""?hl:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=Xo(un(gl(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),i=o?un(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,s=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!s!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let u=s?{catalogUrl:un(s,"URUN_CATALOG_URL"),anonKey:a}:null;return{port:n,baseUrl:r,apiUrl:i,catalog:u}}x();var Ia=require("http");x();x();var Pi="audio",xr=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(e,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let i=0;i<r;i++)o[i]=n.readInt16LE(i*2);this.source.onData(o)}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function Ci(t,e,n=1e4){let r=new xr(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Pi).attach(o);let i=await yl(t,n);return await r.startInbound(i),r}function yl(t,e){let n=t.stream(Pi);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let i,s=setTimeout(()=>{i?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=u=>{u!=null&&(clearTimeout(s),i?.(),r(u))};i=n.on?.("track",a),n.track!=null&&a(n.track)})}var Ii="rt-video-in",Ti=256e3;function Mi(t){let e=t.stream(Ii),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${Ii}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async r=>{if(r.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(r.byteLength>Ti)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Ti}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var wl=24e3,Dt=480,_l=111;async function vl(){let t=await import("opusscript"),e=t.default??t;return new e(wl,1,2048)}async function Li(){let t=await import("werift"),e=await vl();return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,i=Math.random()*4294967295>>>0,s=new Int16Array(0);return{track:n,onData:a=>{let u=new Int16Array(s.length+a.length);u.set(s,0),u.set(a,s.length);let l=0;for(;u.length-l>=Dt;){let d=u.subarray(l,l+Dt);l+=Dt;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),_=e.encode(c,Dt);o=o+1&65535,i=i+Dt>>>0;let m=new t.RtpHeader({version:2,payloadType:_l,sequenceNumber:o,timestamp:i,ssrc:r,marker:!1}),p=new t.RtpPacket(m,_);n.writeRtp(p)}s=u.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(i=>{let s;try{s=e.decode(i.payload)}catch{return}let a=new Int16Array(s.length/2);for(let u=0;u<a.length;u++)a[u]=s.readInt16LE(u*2);r.onframe?.({samples:a})}),r}}}x();var yn=require("@urun-sh/core"),Er="rt-video-out";var bl="h264";function Sl(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function kl(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(s){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(s)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;Sl(o,"decodeVideoOutRecord");let i=t.subarray(2+e);if(i.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:i.slice()}}var $i="urun.videoOut.v2-ws";function Ni(t){let e=t.stream(Er);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Er}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,i=u=>{for(let l of r)l(u)},s=!1,a=async()=>{for await(let u of e.messages()){if(!(u instanceof Uint8Array)){i(new Error(`openSessionVideoOutLane: "${Er}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=kl(u)}catch(d){i(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(l)}for(let u of o)u()};return{codec:bl,onOutputFrame:u=>(n.add(u),s||(s=!0,a().catch(l=>i(l instanceof Error?l:new Error(String(l))))),()=>n.delete(u)),onLaneError:u=>(r.add(u),()=>r.delete(u)),onEnd:u=>(o.add(u),()=>o.delete(u))}}var bn="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Rl=1007,Di=1008,Ge=1011,Sn=1008,T=class extends Error{constructor(n,r=Rl){super(n);this.closeCode=r}closeCode},ae=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,wn=["setup","clientContent","realtimeInput","toolResponse"];function Fi(t){let e;try{e=JSON.parse(t)}catch{throw new T("client message is not valid JSON")}let n=ae(e);if(!n)throw new T("client message must be a JSON object");let r=wn.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!wn.includes(a));if(o.length>0)throw new T(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${wn.join(", ")}`);if(r.length!==1)throw new T(`client message must contain exactly one of ${wn.join(", ")} (got ${r.length})`);let i=r[0],s=ae(n[i]);if(!s)throw new T(`"${i}" must be a JSON object`);return{kind:i,[i]:s}}function Bi(t,e){if(typeof t=="string")return t;let n=ae(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new T(`${e}: expected a Content with a parts array`);let o=[];for(let i of r){let s=ae(i);if(s&&typeof s.text=="string"){o.push(s.text);continue}throw s&&(s.inlineData!==void 0||s.fileData!==void 0)?new T(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):s&&(s.functionCall!==void 0||s.functionResponse!==void 0)?new T(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new T(`${e}: unsupported part ${JSON.stringify(i)}`)}return o.join(`
11
- `)}var xl={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},nt="urun.videoOut";function ji(t){return{framing:$i,codec:t}}function qi(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[nt]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var El={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ol=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",nt],Ui=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Al(t){let e=ae(t);if(!e)throw new T("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new T(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ae(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new T("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new T(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new T("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!Ui.includes(e.activityHandling))throw new T(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Ui.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Il=["temperature","maxOutputTokens","responseModalities"];function Hi(t){for(let[c,_]of Object.entries(El))if(t[c]!==void 0)throw new T(_);for(let c of Object.keys(t))if(!Ol.includes(c))throw new T(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new T('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,i=ae(t.generationConfig);if(t.generationConfig!==void 0&&!i)throw new T("setup.generationConfig must be an object");if(i){for(let c of Object.keys(i))if(!Il.includes(c))throw new T(`unsupported generationConfig field "${c}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new T("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new T("generationConfig.maxOutputTokens must be a number");r=i.maxOutputTokens}if(i.responseModalities!==void 0){let c=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let _ of c){let m=String(_).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="TEXT")throw new T(`responseModalities ${JSON.stringify(_)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let s=[];t.systemInstruction!==void 0&&s.push({role:"system",content:Bi(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new T("setup.tools must be an array");a=[];for(let c of t.tools){let _=ae(c);if(!_)throw new T("setup.tools entries must be objects");for(let m of Object.keys(_))if(m!=="functionDeclarations")throw new T(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(_.functionDeclarations))throw new T("tool.functionDeclarations must be an array");for(let m of _.functionDeclarations){let p=ae(m);if(!p||typeof p.name!="string")throw new T("functionDeclarations entries require a string name");a.push({type:"function",name:p.name,description:p.description,parameters:p.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ae(t.sessionResumption);if(!c)throw new T("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let _ of Object.keys(c))if(_!=="handle")throw new T(`unsupported sessionResumption field "${_}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new T("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let l=t.realtimeInputConfig===void 0?xl:Al(t.realtimeInputConfig),d=!1;if(t[nt]!==void 0){if(!ae(t[nt]))throw new T(`setup["${nt}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:s,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:u,videoOut:d}}function Gi(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Vi(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Ji(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new T(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new T("clientContent.turns must be an array");let n=[];for(let r of e){let o=ae(r);if(!o)throw new T("clientContent.turns entries must be Content objects");let i=o.role===void 0?"user":String(o.role).toLowerCase();if(i!=="user"&&i!=="model")throw new T(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:i==="model"?"assistant":"user",content:Bi(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var _n=16e3,Wi=24e3,Tl=`audio/pcm;rate=${Wi}`,Ki=Buffer.alloc(960).toString("base64");function Pl(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),i=e/n,s=t.length-1;for(let a=0;a<r;a++){let u=a*i,l=Math.floor(u);if(l>=s){o[a]=t[s];continue}let d=u-l;o[a]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function Cl(t){let e=ae(t);if(!e)throw new T("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new T(`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 T("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new T("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Ml(t){let e=ae(t);if(!e)throw new T("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new T(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==_n)throw new T(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${_n} Hz (audio/pcm;rate=${_n})`);if(typeof e.data!="string"||e.data.length===0)throw new T("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new T(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let s=0;s<o.length;s++)o[s]=r.readInt16LE(s*2);let i=Pl(o,_n,Wi);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function zi(t){if(t.mediaChunks!==void 0)throw new T('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new T("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",i=ae(t[o]);if(!i||Object.keys(i).length!==0)throw new T(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new T(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new T(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Ml(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Cl(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new T("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new T("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Yi(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new T(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new T("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ae(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new T("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Xi(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Qi(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Tl,data:t}}]}}}}function Zi(t){let e=ae(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],i=typeof e.output_text=="string"?e.output_text:"";if(!i)for(let l of n){let d=ae(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let _=ae(c);_?.type==="output_text"&&typeof _.text=="string"&&(i+=_.text)}}i&&o.push({role:"assistant",content:i});for(let l of n){let d=ae(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new T(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Ge);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",_;try{_=JSON.parse(c)}catch{throw new T(`upstream function_call arguments are not valid JSON: ${c}`,Ge)}r.push({id:d.call_id,name:d.name,args:_}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let s=[];r.length>0&&s.push({toolCall:{functionCalls:r}}),s.push({serverContent:{generationComplete:!0}});let a=ae(e.usage),u={serverContent:{turnComplete:!0}};if(a){let l={};typeof a.input_tokens=="number"&&(l.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(l.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(l.totalTokenCount=a.total_tokens),Object.keys(l).length>0&&(u.usageMetadata=l)}return s.push(u),{messages:s,assistantItems:o}}x();var es=require("crypto"),ts=require("ws");var Ll=256,Or=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Ll;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},$l="local",Ft=t=>t.slice(0,120),Ar=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof z){this.ws.close(Di,Ft(e.message));return}if(e instanceof re){this.ws.close(Sn,Ft(e.message));return}if(e instanceof T){this.ws.close(e.closeCode,Ft(e.message));return}this.ws.close(Ge,Ft(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Fi(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new T(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:i}=Ji(n.clientContent);this.transcript.push(...o),i&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=zi(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:Ki);return}this.transcript.push(...Yi(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new T("setup may only be sent once, as the first client message");let n=Hi(e),r=n.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new T("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",Sn);if(i.model!==n.model)throw new T(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new T("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==i.proxyHandle)throw new T(`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`,Sn);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let i=this.clients.openVideoOut;if(i){let s=await i.call(this.clients,n.model),a=s.onOutputFrame(l=>this.send(qi(l))),u=s.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[nt]=ji(s.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new T("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new T("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ge);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Qi(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new T("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new T("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ge);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new T(`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 T("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new T("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,es.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Gi(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Vi(e.timeLeftMs)),this.ws.close(Ge,Ft(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,i=!1;for await(let u of r){if(n.interrupted)break;let l=u;if(l.type==="error")throw new T(`upstream error: ${JSON.stringify(l)}`,Ge);if(l.type==="response.completed"){o=l.response,i=!0;continue}let d=Xi(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new T("upstream produced no response.completed event",Ge);let{messages:s,assistantItems:a}=Zi(o);this.transcript.push(...a);for(let u of s)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},rt=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Nl(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let i=t.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let s=e.searchParams.get("key")??void 0;if(s!==void 0&&s!==""&&r.add(s),r.size>1)throw new rt(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&s!==void 0&&s!=="")throw new rt(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new rt(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Ir(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new ts.WebSocketServer({noServer:!0}),o=new Or;t.on("upgrade",(s,a,u)=>{let l=new URL(s.url??"/","http://localhost");l.pathname===bn&&(a.on("error",()=>{}),(async()=>{let d=Nl(s,l,n),c;if(e.authenticate)c=await e.authenticate(d,s);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new rt(401,"invalid local proxy api key");c={clients:e.clients,scope:$l}}r.handleUpgrade(s,a,u,_=>{new Ar(_,c,o)})})().catch(d=>{let c=502;(d instanceof rt||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let _=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${_}\r
11
+ `)}var xl={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},nt="urun.videoOut";function ji(t){return{framing:$i,codec:t}}function qi(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[nt]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var El={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ol=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",nt],Ui=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Al(t){let e=ae(t);if(!e)throw new T("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new T(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ae(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new T("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new T(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new T("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!Ui.includes(e.activityHandling))throw new T(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Ui.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Il=["temperature","maxOutputTokens","responseModalities"];function Hi(t){for(let[c,_]of Object.entries(El))if(t[c]!==void 0)throw new T(_);for(let c of Object.keys(t))if(!Ol.includes(c))throw new T(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new T('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,i=ae(t.generationConfig);if(t.generationConfig!==void 0&&!i)throw new T("setup.generationConfig must be an object");if(i){for(let c of Object.keys(i))if(!Il.includes(c))throw new T(`unsupported generationConfig field "${c}"`);if(i.temperature!==void 0){if(typeof i.temperature!="number")throw new T("generationConfig.temperature must be a number");n=i.temperature}if(i.maxOutputTokens!==void 0){if(typeof i.maxOutputTokens!="number")throw new T("generationConfig.maxOutputTokens must be a number");r=i.maxOutputTokens}if(i.responseModalities!==void 0){let c=Array.isArray(i.responseModalities)?i.responseModalities:[i.responseModalities];for(let _ of c){let m=String(_).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="TEXT")throw new T(`responseModalities ${JSON.stringify(_)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let s=[];t.systemInstruction!==void 0&&s.push({role:"system",content:Bi(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new T("setup.tools must be an array");a=[];for(let c of t.tools){let _=ae(c);if(!_)throw new T("setup.tools entries must be objects");for(let m of Object.keys(_))if(m!=="functionDeclarations")throw new T(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(_.functionDeclarations))throw new T("tool.functionDeclarations must be an array");for(let m of _.functionDeclarations){let p=ae(m);if(!p||typeof p.name!="string")throw new T("functionDeclarations entries require a string name");a.push({type:"function",name:p.name,description:p.description,parameters:p.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ae(t.sessionResumption);if(!c)throw new T("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let _ of Object.keys(c))if(_!=="handle")throw new T(`unsupported sessionResumption field "${_}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new T("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let l=t.realtimeInputConfig===void 0?xl:Al(t.realtimeInputConfig),d=!1;if(t[nt]!==void 0){if(!ae(t[nt]))throw new T(`setup["${nt}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:s,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:u,videoOut:d}}function Gi(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Vi(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Wi(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new T(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new T("clientContent.turns must be an array");let n=[];for(let r of e){let o=ae(r);if(!o)throw new T("clientContent.turns entries must be Content objects");let i=o.role===void 0?"user":String(o.role).toLowerCase();if(i!=="user"&&i!=="model")throw new T(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:i==="model"?"assistant":"user",content:Bi(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var _n=16e3,Ji=24e3,Tl=`audio/pcm;rate=${Ji}`,Ki=Buffer.alloc(960).toString("base64");function Pl(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),i=e/n,s=t.length-1;for(let a=0;a<r;a++){let u=a*i,l=Math.floor(u);if(l>=s){o[a]=t[s];continue}let d=u-l;o[a]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function Cl(t){let e=ae(t);if(!e)throw new T("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new T(`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 T("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new T("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Ml(t){let e=ae(t);if(!e)throw new T("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new T(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==_n)throw new T(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${_n} Hz (audio/pcm;rate=${_n})`);if(typeof e.data!="string"||e.data.length===0)throw new T("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new T(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let s=0;s<o.length;s++)o[s]=r.readInt16LE(s*2);let i=Pl(o,_n,Ji);return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function zi(t){if(t.mediaChunks!==void 0)throw new T('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new T("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",i=ae(t[o]);if(!i||Object.keys(i).length!==0)throw new T(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new T(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new T(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Ml(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Cl(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new T("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new T("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Yi(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new T(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new T("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ae(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new T("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Xi(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Qi(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Tl,data:t}}]}}}}function Zi(t){let e=ae(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],i=typeof e.output_text=="string"?e.output_text:"";if(!i)for(let l of n){let d=ae(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let _=ae(c);_?.type==="output_text"&&typeof _.text=="string"&&(i+=_.text)}}i&&o.push({role:"assistant",content:i});for(let l of n){let d=ae(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new T(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Ge);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",_;try{_=JSON.parse(c)}catch{throw new T(`upstream function_call arguments are not valid JSON: ${c}`,Ge)}r.push({id:d.call_id,name:d.name,args:_}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let s=[];r.length>0&&s.push({toolCall:{functionCalls:r}}),s.push({serverContent:{generationComplete:!0}});let a=ae(e.usage),u={serverContent:{turnComplete:!0}};if(a){let l={};typeof a.input_tokens=="number"&&(l.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(l.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(l.totalTokenCount=a.total_tokens),Object.keys(l).length>0&&(u.usageMetadata=l)}return s.push(u),{messages:s,assistantItems:o}}x();var es=require("crypto"),ts=require("ws");var Ll=256,Or=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Ll;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},$l="local",Ft=t=>t.slice(0,120),Ar=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof z){this.ws.close(Di,Ft(e.message));return}if(e instanceof re){this.ws.close(Sn,Ft(e.message));return}if(e instanceof T){this.ws.close(e.closeCode,Ft(e.message));return}this.ws.close(Ge,Ft(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Fi(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new T(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:i}=Wi(n.clientContent);this.transcript.push(...o),i&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=zi(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:Ki);return}this.transcript.push(...Yi(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new T("setup may only be sent once, as the first client message");let n=Hi(e),r=n.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new T("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",Sn);if(i.model!==n.model)throw new T(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new T("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==i.proxyHandle)throw new T(`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`,Sn);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let i=this.clients.openVideoOut;if(i){let s=await i.call(this.clients,n.model),a=s.onOutputFrame(l=>this.send(qi(l))),u=s.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[nt]=ji(s.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new T("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new T("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ge);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Qi(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new T("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new T("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ge);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new T(`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 T("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new T("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,es.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Gi(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Vi(e.timeLeftMs)),this.ws.close(Ge,Ft(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,i=!1;for await(let u of r){if(n.interrupted)break;let l=u;if(l.type==="error")throw new T(`upstream error: ${JSON.stringify(l)}`,Ge);if(l.type==="response.completed"){o=l.response,i=!0;continue}let d=Xi(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new T("upstream produced no response.completed event",Ge);let{messages:s,assistantItems:a}=Zi(o);this.transcript.push(...a);for(let u of s)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},rt=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Nl(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let i=t.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let s=e.searchParams.get("key")??void 0;if(s!==void 0&&s!==""&&r.add(s),r.size>1)throw new rt(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&s!==void 0&&s!=="")throw new rt(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new rt(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Ir(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new ts.WebSocketServer({noServer:!0}),o=new Or;t.on("upgrade",(s,a,u)=>{let l=new URL(s.url??"/","http://localhost");l.pathname===bn&&(a.on("error",()=>{}),(async()=>{let d=Nl(s,l,n),c;if(e.authenticate)c=await e.authenticate(d,s);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new rt(401,"invalid local proxy api key");c={clients:e.clients,scope:$l}}r.handleUpgrade(s,a,u,_=>{new Ar(_,c,o)})})().catch(d=>{let c=502;(d instanceof rt||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let _=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${_}\r
12
12
  Connection: close\r
13
13
  \r
14
14
  ${m}\r
15
15
  `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let s of r.clients)s.close(1001,"server closing");await new Promise((s,a)=>r.close(u=>u===void 0?s():a(u)))})(),i)}x();var Xe=require("ws");x();x();var ns=require("crypto"),rs="Inference-Id";function Bt(){return(0,ns.randomUUID)()}function Tr(t){return t==="/v1"||t.startsWith("/v1/")}function os(t,e){if(!Tr(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function jt(t){return`resp_${t}`}function is(t){return`chatcmpl-${t}`}function ss(t){return`msg_${t}`}function Ee(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function as(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function us(t){return`${JSON.stringify(t)}
16
- `}var Ul=256,Dl=128;function Se(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Dl)}var ot=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=Ul?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,i=performance.now(),s=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-i),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=s-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let u=(performance.now()-(s??i))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Fl=256;function Bl(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var it=class extends Error{},vt=class{conversations=new Map;thread(e,n){let r=Bl(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new it(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let i of this.conversations.keys()){if(this.conversations.size<=Fl)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},ls=new WeakMap;function qt(t){let e=ls.get(t);return e||(e=new vt,ls.set(t,e)),e}function bt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Ue(t){return t.find(e=>e.type==="response.completed")?.response??null}function St(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var Ye=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},jl=["<tool_call>","<function="];function ql(t){return jl.find(e=>t.includes(e))}function st(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function at(t,e,n){if(!(!t||e>0))return ql(n)}function kt(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Hl(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function Pr(t,e){let n=Hl(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var Oe=class extends Error{constructor(n,r,o=400,i){super(n);this.code=r;this.status=o;this.param=i}code;status;param};function Rt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof it?new Oe(n.message,"previous_response_not_found",400,"previous_response_id"):new Oe(String(n instanceof Error?n.message:n),"invalid_input")}}function ds(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Cr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new Oe("instructions must be a string","invalid_instructions");let i=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...i!==void 0?{instructions:i}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...ds(e)!==void 0?{response_format:ds(e)}:{}},o)}async function Ht(t){let{body:e,clients:n,store:r,stats:o}=t,i=Rt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let s=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,l=Se(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,_=await Cr(n,e,i,!0,c?Ee(c):void 0);return{responseId:s,events:Wl({events:_,conversation:i,responseId:s,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function Gl(t,e){let n=[...t].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=n.filter(u=>u.type==="message").length===o.length,s=0;return[...n.map(u=>u.type==="message"&&i?Jl(o[s++],u):u),...Vl(r,n)]}function Vl(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),i=e.filter(l=>l.type==="function_call"),s=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=i.length===s,u=new Set(i.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!u.has(o(d)):!0})}function Jl(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(n);if(i===void 0)return e;let s={...t};return s.id=e.id,t.role===void 0&&(s.role=e.role),t.status===void 0&&(s.status=e.status),s.content=r.map(a=>n(a)?{...a,text:i.text}:a),s}async function*Wl(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:i,remember:s,persist:a,store:u,stats:l}=t,d=[],c=H=>H.response&&typeof H.response=="object"?{...H,response:{...H.response,id:r}}:H,_=`item_${r.slice(5)}`,m=!1,p=!1,w=0;function*y(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let v=[],k=(H,I)=>{v.push({output_index:H,item:I})},h=!1,A=0,R="",S=0,O="";function*j(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:R,output_index:A,content_index:0,text:O};let H={id:R,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:O}],status:"completed"};yield{type:"response.output_item.done",output_index:A,item:H},k(A,H),O=""}let P=!1,F=0,G="",Y=0,le="",he="";function*ve(H){if(!P)return;P=!1,yield{type:"response.output_text.done",item_id:G,output_index:F,content_index:0,text:le},yield{type:"response.content_part.done",item_id:G,output_index:F,content_index:0,part:{type:"output_text",text:le}};let I={id:G,type:"message",role:"assistant",status:H,content:[{type:"output_text",text:le}]};yield{type:"response.output_item.done",output_index:F,item:I},k(F,I),le=""}let Te=new Ye,ee=null,te=-1;function*de(H){if(!ee)return;let I=ee;ee=null,yield{type:"response.function_call_arguments.done",item_id:I.fcId,output_index:I.outputIndex,arguments:I.args};let X={id:I.fcId,type:"function_call",call_id:I.callId??I.fcId,name:I.name??"",arguments:I.args,status:H};yield{type:"response.output_item.done",output_index:I.outputIndex,item:X},k(I.outputIndex,X)}let Le=!1;for await(let H of l.track(e,o,t.turn)){d.push(H);let I=String(H.type??"");if(I==="response.created"||I==="response.in_progress"){m=!0,yield c(H);continue}if(I==="response.output_item.added"){p=!0,yield c(H);continue}if(I==="response.reasoning_text.delta"&&!p){yield*y(),h||(h=!0,A=w++,S+=1,R=S===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${S}`,yield{type:"response.output_item.added",output_index:A,item:{id:R,type:"reasoning",summary:[],content:[],status:"in_progress"}}),O+=String(H.delta??""),yield{type:"response.reasoning_text.delta",item_id:R,output_index:A,content_index:0,delta:H.delta};continue}if(I==="response.output_text.delta"&&!p){yield*y(),yield*j(),P||(P=!0,F=w++,Y+=1,G=Y===1?_:`${_}_${Y}`,yield{type:"response.output_item.added",output_index:F,item:{id:G,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:G,output_index:F,content_index:0,part:{type:"output_text",text:""}}),le+=String(H.delta??""),he+=String(H.delta??""),yield{type:I,item_id:G,output_index:F,content_index:0,delta:H.delta};continue}let X=p?null:St(H);if(X){if(yield*y(),yield*j(),yield*ve("completed"),Te.add(X),X.tool_index!==te){yield*de("completed"),te=X.tool_index;let Pe=w++;ee={fcId:`fc_${r.slice(5)}_${X.tool_index}`,outputIndex:Pe,callId:X.call_id,name:X.name,args:""},yield{type:"response.output_item.added",output_index:Pe,item:{id:ee.fcId,type:"function_call",call_id:ee.callId??ee.fcId,name:ee.name??"",arguments:"",status:"in_progress"}}}ee&&(X.call_id&&(ee.callId=X.call_id),X.name&&(ee.name=X.name),ee.args+=X.delta,yield{type:"response.function_call_arguments.delta",item_id:ee.fcId,output_index:ee.outputIndex,delta:X.delta});continue}if(I==="response.completed"&&!p){let Pe=bt(H.response),q=at(i,Te.size+Pe.length,he);if(q){Le=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:st(o,q)}};break}if(yield*j(),yield*ve("completed"),yield*de("completed"),Te.size===0)for(let $e of Pe){let Be=w++,pt=$e.id??$e.call_id??`fc_${Be}`,be=$e.arguments??"",Tt={id:pt,type:"function_call",call_id:$e.call_id??pt,name:$e.name??""};yield{type:"response.output_item.added",output_index:Be,item:{...Tt,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:pt,output_index:Be,delta:be},yield{type:"response.function_call_arguments.done",item_id:pt,output_index:Be,arguments:be};let je={...Tt,arguments:be,status:"completed"};yield{type:"response.output_item.done",output_index:Be,item:je},k(Be,je)}let me=Gl(v,H.response);yield me.length>0?c({...H,response:{...H.response,output:me}}):c(H);continue}yield c(H)}if(yield*j(),yield*ve("incomplete"),yield*de("incomplete"),s&&!Le){let H=Ue(d);u.remember(r,n,Pr(H,kt(d,H)),a)}}var $r="/v1/responses",Kl=64*1024*1024,zl=8*1024*1024,Yl=16,cs=32,ps=3600*1e3,Xl=/^[A-Za-z0-9._-]{1,256}$/;function ke(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Ql=ke(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 Nr(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Zl(t){for(;t.bufferedAmount>zl&&t.readyState===Xe.WebSocket.OPEN;){let{promise:e,resolve:n}=Nr();setTimeout(n,5),await e}}var Mr=class extends vt{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof it))throw o;return this.shared.thread(n,r)}}remember(n,r,o,i=!0){i?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},Lr=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new Mr(qt(n)),e.on("message",(s,a)=>this.onMessage(s,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ke(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${ps/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},ps).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(ke(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(ke(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(ke(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(ke(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(ke(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(ke(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Xl.test(o.stream_id)){this.sendFrame(Ql);return}if(i=o.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=cs){this.sendFrame(ke(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${cs}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let s=o.generate===!1?()=>this.runWarmup(o,i):()=>this.runTurn(o,i),a=i??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(s).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(!this.closed){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await Ht({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:jt(Bt())})}catch(s){this.failTurn(s,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let i=o.events;this.activeTurns.add(i);try{for await(let s of i){if(this.closed||this.ws.readyState!==Xe.WebSocket.OPEN)break;this.send(s,n),await Zl(this.ws)}}finally{this.activeTurns.delete(i)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=jt(Bt());try{let o=Rt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof Oe)return ke(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof z)return ke(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof re)return ke(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?ke(o.status,{type:o.openaiType,message:r},n):ke(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Yl;){let{promise:e,resolve:n}=Nr();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Xe.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Xe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function kn(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
16
+ `}var Ul=256,Dl=128;function Se(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Dl)}var ot=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=Ul?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,i=performance.now(),s=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-i),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=s-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let u=(performance.now()-(s??i))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Fl=256;function Bl(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var it=class extends Error{},vt=class{conversations=new Map;thread(e,n){let r=Bl(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new it(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let i of this.conversations.keys()){if(this.conversations.size<=Fl)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},ls=new WeakMap;function qt(t){let e=ls.get(t);return e||(e=new vt,ls.set(t,e)),e}function bt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Ue(t){return t.find(e=>e.type==="response.completed")?.response??null}function St(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var Ye=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},jl=["<tool_call>","<function="];function ql(t){return jl.find(e=>t.includes(e))}function st(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function at(t,e,n){if(!(!t||e>0))return ql(n)}function kt(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Hl(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function Pr(t,e){let n=Hl(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var Oe=class extends Error{constructor(n,r,o=400,i){super(n);this.code=r;this.status=o;this.param=i}code;status;param};function Rt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof it?new Oe(n.message,"previous_response_not_found",400,"previous_response_id"):new Oe(String(n instanceof Error?n.message:n),"invalid_input")}}function ds(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Cr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new Oe("instructions must be a string","invalid_instructions");let i=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...i!==void 0?{instructions:i}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...ds(e)!==void 0?{response_format:ds(e)}:{}},o)}async function Ht(t){let{body:e,clients:n,store:r,stats:o}=t,i=Rt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let s=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,l=Se(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,_=await Cr(n,e,i,!0,c?Ee(c):void 0);return{responseId:s,events:Jl({events:_,conversation:i,responseId:s,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function Gl(t,e){let n=[...t].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=n.filter(u=>u.type==="message").length===o.length,s=0;return[...n.map(u=>u.type==="message"&&i?Wl(o[s++],u):u),...Vl(r,n)]}function Vl(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),i=e.filter(l=>l.type==="function_call"),s=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=i.length===s,u=new Set(i.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!u.has(o(d)):!0})}function Wl(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(n);if(i===void 0)return e;let s={...t};return s.id=e.id,t.role===void 0&&(s.role=e.role),t.status===void 0&&(s.status=e.status),s.content=r.map(a=>n(a)?{...a,text:i.text}:a),s}async function*Jl(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:i,remember:s,persist:a,store:u,stats:l}=t,d=[],c=H=>H.response&&typeof H.response=="object"?{...H,response:{...H.response,id:r}}:H,_=`item_${r.slice(5)}`,m=!1,p=!1,w=0;function*y(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let b=[],k=(H,I)=>{b.push({output_index:H,item:I})},h=!1,A=0,R="",v=0,O="";function*j(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:R,output_index:A,content_index:0,text:O};let H={id:R,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:O}],status:"completed"};yield{type:"response.output_item.done",output_index:A,item:H},k(A,H),O=""}let P=!1,F=0,G="",Y=0,le="",he="";function*ve(H){if(!P)return;P=!1,yield{type:"response.output_text.done",item_id:G,output_index:F,content_index:0,text:le},yield{type:"response.content_part.done",item_id:G,output_index:F,content_index:0,part:{type:"output_text",text:le}};let I={id:G,type:"message",role:"assistant",status:H,content:[{type:"output_text",text:le}]};yield{type:"response.output_item.done",output_index:F,item:I},k(F,I),le=""}let Te=new Ye,ee=null,te=-1;function*de(H){if(!ee)return;let I=ee;ee=null,yield{type:"response.function_call_arguments.done",item_id:I.fcId,output_index:I.outputIndex,arguments:I.args};let X={id:I.fcId,type:"function_call",call_id:I.callId??I.fcId,name:I.name??"",arguments:I.args,status:H};yield{type:"response.output_item.done",output_index:I.outputIndex,item:X},k(I.outputIndex,X)}let Le=!1;for await(let H of l.track(e,o,t.turn)){d.push(H);let I=String(H.type??"");if(I==="response.created"||I==="response.in_progress"){m=!0,yield c(H);continue}if(I==="response.output_item.added"){p=!0,yield c(H);continue}if(I==="response.reasoning_text.delta"&&!p){yield*y(),h||(h=!0,A=w++,v+=1,R=v===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${v}`,yield{type:"response.output_item.added",output_index:A,item:{id:R,type:"reasoning",summary:[],content:[],status:"in_progress"}}),O+=String(H.delta??""),yield{type:"response.reasoning_text.delta",item_id:R,output_index:A,content_index:0,delta:H.delta};continue}if(I==="response.output_text.delta"&&!p){yield*y(),yield*j(),P||(P=!0,F=w++,Y+=1,G=Y===1?_:`${_}_${Y}`,yield{type:"response.output_item.added",output_index:F,item:{id:G,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:G,output_index:F,content_index:0,part:{type:"output_text",text:""}}),le+=String(H.delta??""),he+=String(H.delta??""),yield{type:I,item_id:G,output_index:F,content_index:0,delta:H.delta};continue}let X=p?null:St(H);if(X){if(yield*y(),yield*j(),yield*ve("completed"),Te.add(X),X.tool_index!==te){yield*de("completed"),te=X.tool_index;let Pe=w++;ee={fcId:`fc_${r.slice(5)}_${X.tool_index}`,outputIndex:Pe,callId:X.call_id,name:X.name,args:""},yield{type:"response.output_item.added",output_index:Pe,item:{id:ee.fcId,type:"function_call",call_id:ee.callId??ee.fcId,name:ee.name??"",arguments:"",status:"in_progress"}}}ee&&(X.call_id&&(ee.callId=X.call_id),X.name&&(ee.name=X.name),ee.args+=X.delta,yield{type:"response.function_call_arguments.delta",item_id:ee.fcId,output_index:ee.outputIndex,delta:X.delta});continue}if(I==="response.completed"&&!p){let Pe=bt(H.response),q=at(i,Te.size+Pe.length,he);if(q){Le=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:st(o,q)}};break}if(yield*j(),yield*ve("completed"),yield*de("completed"),Te.size===0)for(let $e of Pe){let Be=w++,pt=$e.id??$e.call_id??`fc_${Be}`,be=$e.arguments??"",Tt={id:pt,type:"function_call",call_id:$e.call_id??pt,name:$e.name??""};yield{type:"response.output_item.added",output_index:Be,item:{...Tt,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:pt,output_index:Be,delta:be},yield{type:"response.function_call_arguments.done",item_id:pt,output_index:Be,arguments:be};let je={...Tt,arguments:be,status:"completed"};yield{type:"response.output_item.done",output_index:Be,item:je},k(Be,je)}let me=Gl(b,H.response);yield me.length>0?c({...H,response:{...H.response,output:me}}):c(H);continue}yield c(H)}if(yield*j(),yield*ve("incomplete"),yield*de("incomplete"),s&&!Le){let H=Ue(d);u.remember(r,n,Pr(H,kt(d,H)),a)}}var $r="/v1/responses",Kl=64*1024*1024,zl=8*1024*1024,Yl=16,cs=32,ps=3600*1e3,Xl=/^[A-Za-z0-9._-]{1,256}$/;function ke(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Ql=ke(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 Nr(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Zl(t){for(;t.bufferedAmount>zl&&t.readyState===Xe.WebSocket.OPEN;){let{promise:e,resolve:n}=Nr();setTimeout(n,5),await e}}var Mr=class extends vt{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof it))throw o;return this.shared.thread(n,r)}}remember(n,r,o,i=!0){i?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},Lr=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new Mr(qt(n)),e.on("message",(s,a)=>this.onMessage(s,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ke(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${ps/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},ps).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(ke(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(ke(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(ke(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(ke(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(ke(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(ke(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Xl.test(o.stream_id)){this.sendFrame(Ql);return}if(i=o.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=cs){this.sendFrame(ke(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${cs}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let s=o.generate===!1?()=>this.runWarmup(o,i):()=>this.runTurn(o,i),a=i??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(s).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(!this.closed){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await Ht({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:jt(Bt())})}catch(s){this.failTurn(s,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let i=o.events;this.activeTurns.add(i);try{for await(let s of i){if(this.closed||this.ws.readyState!==Xe.WebSocket.OPEN)break;this.send(s,n),await Zl(this.ws)}}finally{this.activeTurns.delete(i)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=jt(Bt());try{let o=Rt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof Oe)return ke(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof z)return ke(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof re)return ke(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?ke(o.status,{type:o.openaiType,message:r},n):ke(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Yl;){let{promise:e,resolve:n}=Nr();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Xe.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Xe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function kn(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
17
17
  `;t.end(`HTTP/1.1 ${e} ${r}\r
18
18
  Connection: close\r
19
19
  Content-Type: text/plain; charset=utf-8\r
20
20
  Content-Length: ${Buffer.byteLength(o)}\r
21
21
  \r
22
- ${o}`)}function Ur(t,e){let n=new Xe.WebSocketServer({noServer:!0,maxPayload:Kl}),r=new ot,o=new Set,i=new Set,s=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,_)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{kn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>s.delete(c)),m.pathname!==$r){s.add(c);return}i.add(c);let p=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){kn(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(y){let v=e.statusOf?.(y)??null;kn(c,v?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(p=!0,n.handleUpgrade(d,c,_,y=>{i.delete(c),o.add(y),y.on("close",()=>o.delete(y));try{new Lr(y,w,r,e.statusOf)}catch{o.delete(y),y.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!p&&!c.destroyed&&kn(c,500,"responses websocket upgrade failed")}).finally(()=>i.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Nr();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let m of i)m.destroy();i.clear();for(let m of s)m.destroy();s.clear();for(let m of o)m.close(1001,"server shutting down");let _=setTimeout(()=>{for(let m of o)m.readyState!==Xe.WebSocket.CLOSED&&m.terminate()},2e3);return _.unref?.(),n.close(()=>{clearTimeout(_),c()}),d}}}x();x();var _s=require("@urun-sh/core");x();var fs=require("@urun-sh/core"),ed={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},td={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"admission is momentarily contended (lock convoy) \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function Dr(t,e){let n=td[t.code];return e?`${n} (${e})`:n}function Rn(t){if(t==null)return null;let e=ed[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function xn(t){if(t.kind==="create-failed")return Rn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=fs.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Rn(e?"cold_start_exceeded":"queue_timeout")}var vs=require("ws");x();var ws=require("@urun-sh/core");x();var hs=require("crypto");function N(t){return`${t}_${(0,hs.randomUUID)().replace(/-/g,"").slice(0,24)}`}var En=4*1024*1024,Fr=8*1024*1024,On=512,An=20*1024*1024;function ue(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function xt(t,e){return{type:"server_error",code:t,message:e}}function Z(t){return{type:"error",event_id:N("event"),error:t}}function Br(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var B=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},nd={type:!0,model:!0,instructions:!0,modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},rd={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},od={format:!0,voice:!0,speed:!0};function ms(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new B(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function Gt(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new B("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(s=>!(s in nd));if(o.length>0)throw new B(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let i={...e,outputModalities:[...e.outputModalities]};for(let[s,a]of Object.entries(r))switch(s){case"type":{if(a!=="realtime"&&a!=="transcription")throw new B(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new B(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(a==="transcription"&&!n.turns)throw new B('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=a;break}case"model":if(a!==null&&typeof a!="string")throw new B("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new B("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 B("modalities must be a non-empty array","modalities");let u=[];for(let l of a){if(l!=="text"&&l!=="audio")throw new B(`modality ${JSON.stringify(l)} is not "text" or "audio"`,"modalities");if(l==="audio"&&!n.voice)throw new B('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");u.includes(l)||u.push(l)}i.outputModalities=u;break}case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new B("voice must be a string or null","voice");if(!n.voice)throw new B("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 B(`${s} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,s);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new B("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 B(`${s} must be a positive integer, "inf" or null`,s);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new B("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 B("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new B("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 u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new B("turn_detection must be an object or null","turn_detection");let l=String(u.type??"");if(l!=="server_vad"&&l!=="semantic_vad")throw new B(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new B("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 B("input_audio_transcription must be an object or null","input_audio_transcription");for(let l of Object.keys(a))if(!["model","language","languages","prompt"].includes(l))throw new B(`input_audio_transcription field not honored by this backend: ${l} (transcription comes from the voice engine itself)`,`input_audio_transcription.${l}`,"unsupported_field");let u=a.model;if(u!=null){let l=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new B(`input_audio_transcription.model ${JSON.stringify(l)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new B("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 u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new B("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let l=u.input;if(!l||typeof l!="object"||Array.isArray(l))throw new B("audio.input must be an object","audio.input");for(let d of Object.keys(l))if(!(d in rd))throw new B(`audio.input field not supported by this backend: ${d}`,`audio.input.${d}`,"unsupported_field");if(l.format!==void 0&&ms(l.format,"audio.input.format"),l.transcription!==null&&l.transcription!==void 0){let d=Gt({input_audio_transcription:l.transcription},i,n);i.inputAudioTranscription=d.inputAudioTranscription}if(l.turn_detection!==null&&l.turn_detection!==void 0){let d=Gt({turn_detection:l.turn_detection},i,n);i.turnDetection=d.turnDetection}if(l.noise_reduction!==null&&l.noise_reduction!==void 0)throw new B("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let l=u.output;if(!l||typeof l!="object"||Array.isArray(l))throw new B("audio.output must be an object","audio.output");for(let d of Object.keys(l))if(!(d in od))throw new B(`audio.output field not supported by this backend: ${d}`,`audio.output.${d}`,"unsupported_field");if(l.format!==void 0&&ms(l.format,"audio.output.format"),l.speed!==void 0)throw new B("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(l.voice!==void 0)if(l.voice===null)delete i.voice;else{if(typeof l.voice!="string")throw new B("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new B("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=l.voice}l.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function In(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function jr(t,e){let n=t;if(!n||typeof n!="object")throw new B("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new B("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:N("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new B('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new B("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new B("content part must be an object","item.content","invalid_request");if(s.type==="input_text"||r==="assistant"&&s.type==="output_text"){if(typeof s.text!="string")throw new B(`${String(s.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){if(!e)throw new B("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof s.audio!="string")throw new B("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}throw new B(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:N("item"),type:"message",role:r,content:o}}throw new B(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function qr(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let s=i.transcript;if(typeof s=="string"&&s.trim().length>0){o.push({type:"input_text",text:s});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var id=1001,sd=1011,gs=t=>t.slice(0,120),ad=/^[A-Za-z0-9+/=]*$/,ud=2;function ld(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ud)return!1;return!0}var Vt=class{id=N("conn");ws;binding;onClosed;config=Br();sessionId=N("sess");conversationId=N("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:N("event"),session:In(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:N("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(Z(xt("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.isTranscriptionSession()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:N("event"),item_id:e,content_index:0,transcript:n})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:N("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:N("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:N("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:N("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),i=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.isTranscriptionSession()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:N("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let s=N("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:N("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.created",event_id:N("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:N("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:N("event"),item_id:s,content_index:0,transcript:i}),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(ue("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>En){this.fail(ue("frame_too_large",`frame exceeds the ${En}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ue("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ue("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let i=o;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(Z({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}this.fail(xt(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=Gt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model}),this.send({type:"session.updated",event_id:N("event"),session:In(this.config,this.sessionId)});return;case"conversation.item.create":{let n=jr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:N("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(Z(ue("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:N("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(Z(ue("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:N("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(Z(ue("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:N("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(Z(ue("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ad.test(e.audio)){this.send(Z(ue("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>An){this.send(Z(ue("buffer_full",`uncommitted input audio exceeds the ${An}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.isTranscriptionSession()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:N("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(Z(ue("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.isTranscriptionSession()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=N("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:N("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:N("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.isTranscriptionSession())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:N("event"),item_id:r,content_index:0,transcript:n});else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:N("event"),item_id:r,content_index:0,transcript:i}),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;return}case"output_audio_buffer.clear":{this.send(Z(ue("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(Z(ue("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(Z(ue("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(Z(ue("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(Z({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:i,input:s,...a}=e;return await o.createResponse({...a,input:s})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(Z(ue("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(w=>w!=="text"&&w!=="audio")){this.send(Z(ue("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(Z(ue("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=N("req"),o=`resp_${r}`;this.activeResponseId=o;let i=this.items.length,{input:s,sawAudioOnlyItem:a}=qr(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,l=typeof n.temperature=="number"?n.temperature:this.config.temperature,d=n.max_output_tokens??this.config.maxOutputTokens,c=d==="inf"||d===void 0?void 0:d,_=n.tools!==void 0?n.tools:this.config.tools,m=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,p={input:s,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...l!==void 0?{temperature:l}:{},...c!==void 0?{max_output_tokens:c}:{},..._!==void 0?{tools:_}:{},...m!==void 0?{tool_choice:m}:{}};for(let w of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(w);this.inFlight=(async()=>{let w=[],y=A=>{this.responseFlushed?this.send(A):w.push(A)},v=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:N("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:N("event"),response:this.responseObject(o,"in_progress")});for(let A of w)this.send(A);w.length=0,this.responseFlushed=!0}},k={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},h=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let A;try{A=await this.upstreamStream(p,r)}catch(R){this.upstreamTurnFault(R,o);return}try{for await(let R of A){if(this.cancelled)break;let S=R;if(S.type==="error"){let O=this.upstreamErrorBody(S);this.responseFlushed?this.send(Z(O)):this.send({type:"response.failed",event_id:N("event"),response:this.failedResponse(o,O)});return}if(S.type==="response.output_text.delta"&&typeof S.delta=="string"){v(),k.messageOpen||(this.beginMessageItem(o,k.nextOutputIndex++),k.messageOpen=!0),y({type:"response.output_text.delta",event_id:N("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:S.delta}),k.messageText+=S.delta;continue}if(S.type==="response.function_call_arguments.delta"){v();let O=typeof S.delta=="string"?S.delta:"",j=typeof S.call_id=="string"&&S.call_id.length>0?S.call_id:`${o}_fc_${k.nextOutputIndex}`,P=k.tools.get(j);if(!P){let F=typeof S.name=="string"&&S.name.length>0?S.name:void 0;P={outputIndex:k.nextOutputIndex++,name:F,args:""},k.tools.set(j,P),y({type:"response.output_item.added",event_id:N("event"),response_id:o,output_index:P.outputIndex,item:{id:j,object:"realtime.item",type:"function_call",call_id:j,name:F??"",arguments:"",status:"in_progress"}})}typeof S.name=="string"&&S.name.length>0&&(P.name=S.name),P.args+=O,y({type:"response.function_call_arguments.delta",event_id:N("event"),item_id:j,response_id:o,output_index:P.outputIndex,call_id:j,name:P.name??"",delta:O});continue}if(S.type==="response.completed"){h=S.response??null;continue}}}catch(R){this.upstreamTurnFault(R,o);return}if(this.cancelled)return;this.closeOpenItems(o,k,i),v(),this.send({type:"response.done",event_id:N("event"),response:this.doneResponse(o,i,h)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(ld(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(Z({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:N("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:N("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:N("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:N("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:N("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:N("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:N("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,i=this.messageItemOpenForAudio;i&&this.send({type:"response.output_audio.done",event_id:N("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:N("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:N("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let s=[];i&&s.push({type:"output_audio"}),n.messageText.length>0&&s.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:N("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,i]of n.tools){let s=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:N("event"),item_id:o,response_id:e,output_index:i.outputIndex,call_id:o,name:i.name??"",arguments:s});let a={id:o,type:"function_call",callId:o,name:i.name,arguments:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:N("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let s=n;s<this.items.length;s++)i.push(this.itemToProtocol(this.items[s]));return this.responseObject(e,"completed",{output:i,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(xt("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof re){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof ws.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=xt(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(Z(r)):this.send({type:"response.failed",event_id:N("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(Z(ue("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:N("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>On&&(this.items.shift(),this.send(Z({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${On} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Fr){this.ws.close(id,gs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(Z(e)),this.ws.close(sd,gs(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null;let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>ys(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ys(this.id,e)}},Hr=[];function ys(t,e){Hr.push({id:t,reason:e}),Hr.length>256&&Hr.shift()}var Jt="/v1/realtime",dd=t=>t.slice(0,120);function cd(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
22
+ ${o}`)}function Ur(t,e){let n=new Xe.WebSocketServer({noServer:!0,maxPayload:Kl}),r=new ot,o=new Set,i=new Set,s=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,_)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{kn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>s.delete(c)),m.pathname!==$r){s.add(c);return}i.add(c);let p=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){kn(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(y){let b=e.statusOf?.(y)??null;kn(c,b?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(p=!0,n.handleUpgrade(d,c,_,y=>{i.delete(c),o.add(y),y.on("close",()=>o.delete(y));try{new Lr(y,w,r,e.statusOf)}catch{o.delete(y),y.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!p&&!c.destroyed&&kn(c,500,"responses websocket upgrade failed")}).finally(()=>i.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Nr();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let m of i)m.destroy();i.clear();for(let m of s)m.destroy();s.clear();for(let m of o)m.close(1001,"server shutting down");let _=setTimeout(()=>{for(let m of o)m.readyState!==Xe.WebSocket.CLOSED&&m.terminate()},2e3);return _.unref?.(),n.close(()=>{clearTimeout(_),c()}),d}}}x();x();var _s=require("@urun-sh/core");x();var fs=require("@urun-sh/core"),ed={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},td={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"admission is momentarily contended (lock convoy) \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function Dr(t,e){let n=td[t.code];return e?`${n} (${e})`:n}function Rn(t){if(t==null)return null;let e=ed[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function xn(t){if(t.kind==="create-failed")return Rn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=fs.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Rn(e?"cold_start_exceeded":"queue_timeout")}var vs=require("ws");x();var ws=require("@urun-sh/core");x();var hs=require("crypto");function N(t){return`${t}_${(0,hs.randomUUID)().replace(/-/g,"").slice(0,24)}`}var En=4*1024*1024,Fr=8*1024*1024,On=512,An=20*1024*1024;function ue(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function xt(t,e){return{type:"server_error",code:t,message:e}}function Z(t){return{type:"error",event_id:N("event"),error:t}}function Br(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var B=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},nd={type:!0,model:!0,instructions:!0,modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},rd={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},od={format:!0,voice:!0,speed:!0};function ms(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new B(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function Gt(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new B("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(s=>!(s in nd));if(o.length>0)throw new B(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let i={...e,outputModalities:[...e.outputModalities]};for(let[s,a]of Object.entries(r))switch(s){case"type":{if(a!=="realtime"&&a!=="transcription")throw new B(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new B(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(a==="transcription"&&!n.turns)throw new B('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=a;break}case"model":if(a!==null&&typeof a!="string")throw new B("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new B("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 B("modalities must be a non-empty array","modalities");let u=[];for(let l of a){if(l!=="text"&&l!=="audio")throw new B(`modality ${JSON.stringify(l)} is not "text" or "audio"`,"modalities");if(l==="audio"&&!n.voice)throw new B('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");u.includes(l)||u.push(l)}i.outputModalities=u;break}case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new B("voice must be a string or null","voice");if(!n.voice)throw new B("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 B(`${s} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,s);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new B("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 B(`${s} must be a positive integer, "inf" or null`,s);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new B("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 B("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new B("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 u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new B("turn_detection must be an object or null","turn_detection");let l=String(u.type??"");if(l!=="server_vad"&&l!=="semantic_vad")throw new B(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new B("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 B("input_audio_transcription must be an object or null","input_audio_transcription");for(let l of Object.keys(a))if(!["model","language","languages","prompt"].includes(l))throw new B(`input_audio_transcription field not honored by this backend: ${l} (transcription comes from the voice engine itself)`,`input_audio_transcription.${l}`,"unsupported_field");let u=a.model;if(u!=null){let l=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new B(`input_audio_transcription.model ${JSON.stringify(l)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new B("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 u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new B("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let l=u.input;if(!l||typeof l!="object"||Array.isArray(l))throw new B("audio.input must be an object","audio.input");for(let d of Object.keys(l))if(!(d in rd))throw new B(`audio.input field not supported by this backend: ${d}`,`audio.input.${d}`,"unsupported_field");if(l.format!==void 0&&ms(l.format,"audio.input.format"),l.transcription!==null&&l.transcription!==void 0){let d=Gt({input_audio_transcription:l.transcription},i,n);i.inputAudioTranscription=d.inputAudioTranscription}if(l.turn_detection!==null&&l.turn_detection!==void 0){let d=Gt({turn_detection:l.turn_detection},i,n);i.turnDetection=d.turnDetection}if(l.noise_reduction!==null&&l.noise_reduction!==void 0)throw new B("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let l=u.output;if(!l||typeof l!="object"||Array.isArray(l))throw new B("audio.output must be an object","audio.output");for(let d of Object.keys(l))if(!(d in od))throw new B(`audio.output field not supported by this backend: ${d}`,`audio.output.${d}`,"unsupported_field");if(l.format!==void 0&&ms(l.format,"audio.output.format"),l.speed!==void 0)throw new B("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(l.voice!==void 0)if(l.voice===null)delete i.voice;else{if(typeof l.voice!="string")throw new B("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new B("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=l.voice}l.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function In(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function jr(t,e){let n=t;if(!n||typeof n!="object")throw new B("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new B("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:N("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new B('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new B("message item content must be an array","item.content","invalid_request");let o=[];for(let i of n.content){let s=i;if(!s||typeof s!="object")throw new B("content part must be an object","item.content","invalid_request");if(s.type==="input_text"||r==="assistant"&&s.type==="output_text"){if(typeof s.text!="string")throw new B(`${String(s.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){if(!e)throw new B("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof s.audio!="string")throw new B("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof s.transcript=="string"?{transcript:s.transcript}:{}});continue}throw new B(`content part type ${String(s.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:N("item"),type:"message",role:r,content:o}}throw new B(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function qr(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let s=i.transcript;if(typeof s=="string"&&s.trim().length>0){o.push({type:"input_text",text:s});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var id=1001,sd=1011,gs=t=>t.slice(0,120),ad=/^[A-Za-z0-9+/=]*$/,ud=2;function ld(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ud)return!1;return!0}var Vt=class{id=N("conn");ws;binding;onClosed;config=Br();sessionId=N("sess");conversationId=N("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:N("event"),session:In(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:N("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(Z(xt("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.isTranscriptionSession()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:N("event"),item_id:e,content_index:0,transcript:n})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:N("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:N("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:N("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:N("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),i=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.isTranscriptionSession()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:N("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let s=N("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:N("event"),previous_item_id:a,item_id:s}),this.send({type:"conversation.item.created",event_id:N("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:N("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:N("event"),item_id:s,content_index:0,transcript:i}),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(ue("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>En){this.fail(ue("frame_too_large",`frame exceeds the ${En}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ue("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ue("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let i=o;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(Z({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}this.fail(xt(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=Gt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model}),this.send({type:"session.updated",event_id:N("event"),session:In(this.config,this.sessionId)});return;case"conversation.item.create":{let n=jr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:N("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(Z(ue("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:N("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(Z(ue("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:N("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(Z(ue("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:N("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(Z(ue("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ad.test(e.audio)){this.send(Z(ue("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>An){this.send(Z(ue("buffer_full",`uncommitted input audio exceeds the ${An}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.isTranscriptionSession()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:N("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(Z(ue("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.isTranscriptionSession()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=N("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:N("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:N("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.isTranscriptionSession())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:N("event"),item_id:r,content_index:0,transcript:n});else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:N("event"),item_id:r,content_index:0,transcript:i}),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;return}case"output_audio_buffer.clear":{this.send(Z(ue("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(Z(ue("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(Z(ue("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(Z(ue("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(Z({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:i,input:s,...a}=e;return await o.createResponse({...a,input:s})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(Z(ue("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(w=>w!=="text"&&w!=="audio")){this.send(Z(ue("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(Z(ue("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=N("req"),o=`resp_${r}`;this.activeResponseId=o;let i=this.items.length,{input:s,sawAudioOnlyItem:a}=qr(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,l=typeof n.temperature=="number"?n.temperature:this.config.temperature,d=n.max_output_tokens??this.config.maxOutputTokens,c=d==="inf"||d===void 0?void 0:d,_=n.tools!==void 0?n.tools:this.config.tools,m=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,p={input:s,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...l!==void 0?{temperature:l}:{},...c!==void 0?{max_output_tokens:c}:{},..._!==void 0?{tools:_}:{},...m!==void 0?{tool_choice:m}:{}};for(let w of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(w);this.inFlight=(async()=>{let w=[],y=A=>{this.responseFlushed?this.send(A):w.push(A)},b=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:N("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:N("event"),response:this.responseObject(o,"in_progress")});for(let A of w)this.send(A);w.length=0,this.responseFlushed=!0}},k={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},h=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let A;try{A=await this.upstreamStream(p,r)}catch(R){this.upstreamTurnFault(R,o);return}try{for await(let R of A){if(this.cancelled)break;let v=R;if(v.type==="error"){let O=this.upstreamErrorBody(v);this.responseFlushed?this.send(Z(O)):this.send({type:"response.failed",event_id:N("event"),response:this.failedResponse(o,O)});return}if(v.type==="response.output_text.delta"&&typeof v.delta=="string"){b(),k.messageOpen||(this.beginMessageItem(o,k.nextOutputIndex++),k.messageOpen=!0),y({type:"response.output_text.delta",event_id:N("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:v.delta}),k.messageText+=v.delta;continue}if(v.type==="response.function_call_arguments.delta"){b();let O=typeof v.delta=="string"?v.delta:"",j=typeof v.call_id=="string"&&v.call_id.length>0?v.call_id:`${o}_fc_${k.nextOutputIndex}`,P=k.tools.get(j);if(!P){let F=typeof v.name=="string"&&v.name.length>0?v.name:void 0;P={outputIndex:k.nextOutputIndex++,name:F,args:""},k.tools.set(j,P),y({type:"response.output_item.added",event_id:N("event"),response_id:o,output_index:P.outputIndex,item:{id:j,object:"realtime.item",type:"function_call",call_id:j,name:F??"",arguments:"",status:"in_progress"}})}typeof v.name=="string"&&v.name.length>0&&(P.name=v.name),P.args+=O,y({type:"response.function_call_arguments.delta",event_id:N("event"),item_id:j,response_id:o,output_index:P.outputIndex,call_id:j,name:P.name??"",delta:O});continue}if(v.type==="response.completed"){h=v.response??null;continue}}}catch(R){this.upstreamTurnFault(R,o);return}if(this.cancelled)return;this.closeOpenItems(o,k,i),b(),this.send({type:"response.done",event_id:N("event"),response:this.doneResponse(o,i,h)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(ld(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(Z({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:N("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:N("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:N("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:N("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:N("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:N("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:N("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,i=this.messageItemOpenForAudio;i&&this.send({type:"response.output_audio.done",event_id:N("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:N("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:N("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let s=[];i&&s.push({type:"output_audio"}),n.messageText.length>0&&s.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:N("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,i]of n.tools){let s=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:N("event"),item_id:o,response_id:e,output_index:i.outputIndex,call_id:o,name:i.name??"",arguments:s});let a={id:o,type:"function_call",callId:o,name:i.name,arguments:s};this.pushItem(a),this.send({type:"response.output_item.done",event_id:N("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let s=n;s<this.items.length;s++)i.push(this.itemToProtocol(this.items[s]));return this.responseObject(e,"completed",{output:i,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(xt("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof re){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof ws.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=xt(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(Z(r)):this.send({type:"response.failed",event_id:N("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(Z(ue("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:N("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>On&&(this.items.shift(),this.send(Z({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${On} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Fr){this.ws.close(id,gs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(Z(e)),this.ws.close(sd,gs(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null;let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>ys(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ys(this.id,e)}},Hr=[];function ys(t,e){Hr.push({id:t,reason:e}),Hr.length>256&&Hr.shift()}var Wt="/v1/realtime",dd=t=>t.slice(0,120);function cd(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
23
23
  Connection: close\r
24
24
  Content-Type: text/plain\r
25
25
  \r
26
26
  ${dd(n)}\r
27
27
  `),t.destroy()}function pd(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
28
- `}function fd(t){Ne(process.stdout,t)}function md(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Gr(t){return t.audioSession?.audio.sessionId??void 0}function Tn(t,e){let n=new vs.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==Jt)return;r.add(i),i.on("close",()=>{r.delete(i)});let u=N("rtup"),l=md(o),d=R=>{(e.log??fd)(pd(R))};d({stage:"accept",conn:u,model:l}),i.resume();let c=new AbortController,_=null,m=R=>{_??=R,c.abort(new Error(_))},p=()=>m("client socket closed"),w=()=>m("client socket closed (half-close)"),y=R=>m(`client socket error: ${R.message}`);i.once("close",p),i.once("end",w),i.once("error",y);let v=()=>{i.removeListener("close",p),i.removeListener("end",w),i.removeListener("error",y)},k=R=>{d({stage:"close",conn:u,model:l,...R})},h=R=>{let S=R,O=S.session!=null&&typeof S.session.sendResponseCreate=="function",j=S.clients!=null&&typeof S.clients.createResponse=="function";if(!O&&!j)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((P,F)=>{n.handleUpgrade(o,i,s,G=>{try{new Vt({ws:G,binding:R,onClosed:(Y,le)=>{k({while:"live",reason:le.reason})}}),d({stage:"admit",conn:u,model:l,...Gr(R)===void 0?{}:{session:Gr(R)}}),P()}catch(Y){F(Y)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async R=>{if(c.signal.aborted){v();let S=Gr(R);try{await R.release?.()}catch(O){k({while:"queued",...S===void 0?{}:{session:S},reason:_??"client socket closed",release_failed:O instanceof Error?O.message:String(O)});return}k({while:"queued",...S===void 0?{}:{session:S},reason:_??"client socket closed",released:!0}),i.destroy();return}v(),await h(R)}).catch(R=>{let S=R instanceof _s.SessionFailedError?xn(R):null,O=null;if(R!==null&&typeof R=="object"&&"status"in R){let F=R.status;typeof F=="number"&&(O=F)}let j=O??S?.status??502,P=R instanceof Error?R.message:String(R);k({while:"queued",...c.signal.aborted?{reason:_??"client socket closed"}:{reason:P,status:j}}),i.destroyed||cd(i,j,P)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}x();x();var Bd=require("http");x();var Et=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},Wt=class extends Et{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},Vr=class extends Et{constructor(e){super("acquire_timeout",429,30,`no decision slot capacity within ${e}ms (all slots at their in-flight cap)`)}},ut=class extends Error{constructor(){super("no ready decision slot on this proxy \u2014 the request was refused fast, not fenced; retry shortly (an out-of-band slot add was submitted)"),this.name="DecisionCapacityError"}},Pn=class{constructor(e){this.opts=e;if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e5}opts;slots=[];nextIndex=0;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;slotKey(e){return`decision:${this.opts.replicaId}:${e}`}async boot(){if(!(this.closed||this.draining)){for(;this.slots.length<this.opts.min;)this.ensureSlot();await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.state="paused",e.opening=null,this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n));return}e.opening=null})())}async acquire(){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Wt;let e=this.opts.acquireTimeoutMs??6e5,n=Date.now();for(;;){let r=this.tryLease();if(r)return r;if(this.draining)throw new Wt;if(!this.slots.some(u=>u.state==="queued")&&this.slots.length<this.opts.max){this.ensureSlot();continue}let i=n+e-Date.now();if(i<=0)throw new Vr(e);let s,a={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(u=>{a.resolve=u,this.waiters.push(a)}),new Promise(u=>{s=setTimeout(u,i)})])}finally{clearTimeout(s);let u=this.waiters.indexOf(a);u!==-1&&this.waiters.splice(u,1),a.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Wt}}tryAcquireReady(){if(this.closed)return null;this.restoreMin();let e=this.tryLease();return e||(!this.slots.some(n=>n.state==="queued")&&this.slots.length<this.opts.max&&this.ensureSlot(),null)}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let i=o.session;if(typeof i!="object"||i===null||!("whenLive"in i))return!1;let s=i.whenLive;if(typeof s!="function")return!1;let a=r.entry;try{return await s.call(i,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&n--;continue}}return!1}tryLease(){this.restoreMin();let e=null;for(let i of this.slots)i.state!=="attached"||i.inFlight>=this.opts.inFlightCap||(!e||i.inFlight<e.inFlight)&&(e=i);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}restoreMin(){if(this.slots.filter(r=>r.state!=="paused").length>=this.opts.min)return;let n=this.slots.filter(r=>r.state==="paused"&&!r.opening);n.sort((r,o)=>r.slot.index-o.slot.index);for(let r of n){if(this.slots.filter(o=>o.state!=="paused").length>=this.opts.min)break;this.openRuntime(r)}}reap(){if(this.closed||this.draining)return;this.restoreMin();let e=this.now(),n=this.slots.filter(r=>r.state==="attached"&&r.inFlight===0&&r.idleSince!==null&&e-r.idleSince>=this.idleGraceMs).sort((r,o)=>(r.idleSince??0)-(o.idleSince??0)||o.slot.index-r.slot.index);for(let r of n){if(this.slots.filter(o=>o.state!=="paused").length<=this.opts.min)break;this.endSlot(r)}}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,i)=>o+i.inFlight,0),draining:this.draining}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(i=>{r=i});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};x();x();var ge=class extends Error{};async function Cn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ge(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let i of t){let s=i;if(o+=s.length,o>e)throw new ge(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function Mn(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(s){try{let a=await n.next();if(a.done){s.close();return}if(r+=a.value.length,r>e){s.error(new ge(`request body exceeds the ${e}-byte limit`));return}s.enqueue(a.value)}catch(a){s.error(a)}},cancel(){n.return?.()}}),i;try{let s=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")s.set(l,d);else if(Array.isArray(d))for(let c of d)s.append(l,c);let a={method:"POST",headers:s,body:o,duplex:"half"};i=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(s){throw s instanceof ge?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var bs="/v1/images/generations",Ln="/v1/images/edits";function Ss(t){return t===bs||t===Ln}var ks="/v1/images/models";async function Rs(t,e,n){if(t){if(t.model=Se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var K=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},hd=16*1024*1024,xs=64*1024*1024;function Es(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function Kt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function Os(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),i=null;for await(let c of o){if(c.type==="error"){let _=c.error??{};throw new K(502,`image upstream error: ${String(_.message??"upstream reported an error")}`)}if(c.type==="response.completed"){i=c.response??null;break}}if(i===null)throw new K(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let s=i.images;if(!Array.isArray(s)||s.length!==1||typeof s[0]!="string"||s[0].length===0)throw new K(502,`image upstream returned ${Array.isArray(s)?s.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],u=s[0].startsWith("data:")?s[0].slice(s[0].indexOf(";base64,")+8):s[0],l=Buffer.from(u,"base64");if(Es(l)===null)throw new K(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${l.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function As(t){return t instanceof K?t:t instanceof z?new K(404,t.message):new K(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Is(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return Kt(r,new K(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Ts(t,e){t&&(t.outputUnits=e.images.length)}function Ps(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var gd={model:!0,prompt:!0,response_format:!0,n:!0};async function Cs(t,e,n){let r=n.maxBodyBytes??xs;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${bs}`);let o;try{o=JSON.parse((await Cn(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof ge?new K(413,c.message):new K(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new K(400,"request body must be a JSON object");let i=o;for(let c of Object.keys(i))if(!gd[c])throw new K(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let s=i.prompt;if(typeof s!="string"||s.trim().length===0)throw new K(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new K(400,"model must be a string","model");await Rs(n.turn,n.clients,a);let u=i.n??1;if(u!==1)throw new K(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let l=i.response_format??"b64_json";if(l!=="b64_json")throw new K(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",s.length,s.length),!await Is(n.imageModels,a,"generation",e))return;let d=[{type:"input_text",text:s}];try{let c=await Os(n.clients,a,d,n.turn?Ee(n.turn):void 0);Ts(n.turn,c),Ps(e,c)}catch(c){throw As(c)}}catch(o){if(o instanceof ge){Kt(e,new K(413,o.message));return}if(o instanceof K){Kt(e,o);return}throw o}}var yd={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ms(t,e,n){let r=n.maxBodyBytes??xs,o=n.maxImagePartBytes??hd;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${Ln}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new K(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Mn(t,r)}catch(m){throw m instanceof ge?new K(413,m.message):new K(400,String(m instanceof Error?m.message:m))}let a=s.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new K(400,"prompt is required and must be a non-empty string field","prompt");let u=s.get("model");if(u!==null&&typeof u!="string")throw new K(400,"model must be a string field","model");let l=u===null?void 0:u;await Rs(n.turn,n.clients,l);let d=s.get("response_format")??"b64_json";if(d!=="b64_json")throw new K(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let m of s.keys())if(!yd[m])throw new K(400,`form field "${m}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,m);let c=[];for(let m of["image","image[]"])for(let p of s.getAll(m)){if(!(p instanceof File))throw new K(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(p.size>o)throw new K(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let w=new Uint8Array(await p.arrayBuffer()),y=Es(w);if(y===null)throw new K(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);c.push({bytes:w,mime:y})}if(c.length===0)throw new K(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await Is(n.imageModels,l,"edit",e))return;let _=[{type:"input_text",text:a}];for(let{bytes:m,mime:p}of c)_.push({type:"input_image",image_url:`data:${p};base64,${Buffer.from(m).toString("base64")}`});try{let m=await Os(n.clients,l,_,n.turn?Ee(n.turn):void 0);Ts(n.turn,m),Ps(e,m)}catch(m){throw As(m)}}catch(i){if(i instanceof ge){Kt(e,new K(413,i.message));return}if(i instanceof K){Kt(e,i);return}throw i}}x();var zt="/v1/audio/speech";function qs(t){return t===zt}var Ls=4096,$s=18e4,Ns=5e3,wd=64*1024*1024,Us=8,Ds=5,Fs=1024*1024,Ot="voice_applied",Nn="X-Urun-Voice-Applied",V=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Jr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Un=class extends V{constructor(e){super(502,e)}};function Hs(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Gs(t){return new V(502,`the runtime's ${Ot} receipt ${JSON.stringify(t)} cannot be relayed as the ${Nn} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function _d(t,e,n){if(t){if(t.model=Se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Vs(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var vd=2;function bd(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>vd)return!1;return!0}function Sd(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var Bs=new WeakMap,$n=new WeakMap;function kd(t,e){let n=$n.get(t)??0;if(n>=Us)throw new V(503,`this model's speech queue is full \u2014 ${Us} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Ds}s`,void 0,Ds);$n.set(t,n+1);let r=Bs.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return Bs.set(t,i),(async()=>{await r;try{return await e()}finally{$n.set(t,($n.get(t)??1)-1),o()}})()}async function Rd(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new V(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(s){if(!(s instanceof re))throw s}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),i;await Promise.race([o,new Promise(s=>{i=setTimeout(s,r)})]).finally(()=>{i!==void 0&&clearTimeout(i)})}function lt(t){return t instanceof V?t:t instanceof z?new V(404,t.message):new V(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function js(t,e,n,r,o,i,s,a){let u=a??(()=>{});return kd(e,async()=>{if(s?.()===!0)return null;let l=!1,d=!1,c=!1,_,m=new Promise(R=>{_=R}),p=[],w=()=>{d&&!c&&p.length>=o.quietRunFrames&&(c=!0,_())},y=e.onOutputAudio(R=>{let S=Buffer.from(R,"base64");if(S.byteLength===0)return;let O=bd(S);if(!l){if(O)return;l=!0}if(O){p.push(S),w();return}for(let j of p)u(j);p.length=0,u(S),w()}),v=null,k,h,A;try{A=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let S=new Promise(P=>{h=setTimeout(P,i.capMs)}),O=!1;for(;;){let P=A.next(),F=await Promise.race([P,S]);if(F===void 0){O=!0,P.catch(()=>{});break}if(F.done)break;let G=F.value;if(G.type==="error"){let Y=G.error??{};throw await A.return?.(),new V(502,`speech upstream error: ${String(Y.message??"upstream reported an error")}`)}if(G.type==="response.completed"){v=G.response??null,d=!0,w(),await A.return?.();break}}if(clearTimeout(h),O)throw new V(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(v===null)throw new V(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let j=!1;if(await Promise.race([m,new Promise(P=>{k=setTimeout(()=>{j=!0,P()},o.capMs)})]),k!==void 0&&clearTimeout(k),r.voice!==void 0){let P=v[Ot];if(typeof P!="string"||P!==r.voice){let F=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof P=="string"?`${Ot} ${JSON.stringify(P)}`:`no ${Ot} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new Un(F):new V(502,F)}}if(!l)throw new V(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(j&&!c&&p.length<1)throw new V(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return v}catch(R){throw R instanceof Un||await Rd(t,n,A,i.returnBoundMs),R}finally{k!==void 0&&clearTimeout(k),h!==void 0&&clearTimeout(h),y()}})}function xd(t,e,n,r){let o=!1,i=0,s=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Nn)),t.write(a,u=>{u||(i+=a.byteLength,Vs(e,i))}),t.writableLength>Fs&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${Fs} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let u=a[Ot];if(typeof u=="string"){if(!Hs(u))throw Gs(u);t.addTrailers({[Nn]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:s}}async function Ed(t,e,n){let r;try{r=await t(e)}catch(o){throw lt(o)}return r?!0:(Jr(n,new V(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Od={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Ad="wav, pcm";async function Js(t,e,n){let r=n.maxBodyBytes??wd,o=!1;e.once("close",()=>{o=!0});let i=()=>o||e.destroyed;try{if(t.method!=="POST")throw new V(405,`${String(t.method)} is not supported on ${zt}`);let s;try{s=JSON.parse((await Cn(t,r)).toString("utf8")||"{}")}catch(h){throw h instanceof ge?new V(413,h.message):new V(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new V(400,"request body must be a JSON object");let a=s;for(let h of Object.keys(a))if(!Od[h])throw new V(400,`request field "${h}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,h);let u=a.input;if(typeof u!="string"||u.trim().length===0)throw new V(400,"input is required and must be a non-empty string","input");if(u.length>Ls)throw new V(400,`input is ${u.length} chars \u2014 over the ${Ls}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let l=a.model===void 0?void 0:a.model;if(l!==void 0&&typeof l!="string")throw new V(400,"model must be a string","model");let d=a.voice;if(d!==void 0&&(typeof d!="string"||d.trim().length===0))throw new V(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new V(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${zt} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(l)}catch(h){throw lt(h)}if(c.defect!==null)throw new V(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let _=typeof d=="string"?d:void 0;if(_!==void 0&&c.published.length>0&&!c.published.includes(_))throw new V(400,`voice ${JSON.stringify(_)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let m=a.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new V(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Ad} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new V(400,"stream_format, when present, must be a string","stream_format");let p=a.speed;if(p!==void 0){if(typeof p!="number"||!Number.isFinite(p))throw new V(400,"speed, when present, must be a number","speed");if(p!==1)throw new V(400,`speed=${JSON.stringify(p)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let w=a.instructions;if(w!==void 0){if(typeof w!="string")throw new V(400,"instructions, when present, must be a string","instructions");if(w.trim().length>0)throw new V(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await _d(n.turn,n.clients,l);let y=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",y,y),!await Ed(n.speechModels,l,e))return;if(typeof n.clients.openAudioOn!="function")throw new V(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new V(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new V(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let v;try{v=await n.clients.speechSessionHandle(l)}catch(h){throw lt(h)}let k;try{k=await n.clients.openAudioOn(v)}catch(h){throw lt(h)}n.turn&&(n.turn.sessionId=k.sessionId);try{if(m==="wav"){let h=[],A=await js(n.clients,k,v,{model:l,text:u,..._!==void 0?{voice:_}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??$s,returnBoundMs:n.turnReturnBoundMs??Ns},i,S=>h.push(S));if(A===null||i())return;let R=Buffer.concat(h);if(_===void 0){let S=A[Ot];if(typeof S=="string"){if(!Hs(S))throw Gs(S);e.setHeader(Nn,S)}}Vs(n.turn,R.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Sd(R.byteLength),R]))}else{let h=xd(e,n.turn,i,_===void 0),A;try{A=await js(n.clients,k,v,{model:l,text:u,..._!==void 0?{voice:_}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??$s,returnBoundMs:n.turnReturnBoundMs??Ns},i,h.sink)}catch(R){let S=lt(R);if(!h.started())throw S;n.turn&&(n.turn.streamError=!0),h.fail(S);return}if(A===null)return;try{await h.finish(A)}catch(R){let S=lt(R);n.turn&&(n.turn.streamError=!0),h.fail(S);return}}}catch(h){throw lt(h)}}catch(s){if(s instanceof ge){Jr(e,new V(413,s.message));return}if(s instanceof V){Jr(e,s);return}throw s}}x();var Dn="/v1/audio/transcriptions";function Ws(t){return t===Dn}var Ks="/v1/audio/models",Id=16*1024*1024,Td=64*1024*1024,ne=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Wr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function zs(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function Pd(t){if(!zs(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),s=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,l=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:l,channels:u,bitsPerSample:d}}else if(i==="data"){let u=t.length-a;r=Math.min(s===0||s===4294967295?u:s,u)}e=a+s+s%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Cd(t,e,n){if(t){if(t.model=Se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Md(t,e){t&&(t.outputUnits=e.seconds)}async function Ld(t,e,n,r,o){let i=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),s=[],a=null;for await(let u of i){if(s.push(u),u.type==="error"){let l=u.error??{},d=typeof l.type=="string"?l.type:"upstream_error",c=String(l.message??"upstream reported an error");throw new ne(d==="invalid_request_error"?400:502,`transcription upstream error: ${c}`)}if(u.type==="response.completed"){a=u.response??null;break}}if(a===null)throw new ne(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return kt(s,a)}function Ys(t){return t instanceof ne?t:t instanceof z?new ne(404,t.message):new ne(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function $d(t,e,n){let r;try{r=await t(e)}catch(o){throw Ys(o)}return r?!0:(Wr(n,new ne(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Nd=new Set(["file","model","language","response_format"]);async function Xs(t,e,n){let r=n.maxBodyBytes??Td,o=n.maxAudioPartBytes??Id;try{if(t.method!=="POST")throw new ne(405,`${String(t.method)} is not supported on ${Dn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new ne(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Mn(t,r)}catch(v){throw v instanceof ge?new ne(413,v.message):new ne(400,String(v instanceof Error?v.message:v))}let a=new Map;for(let v of s.keys()){if(!Nd.has(v))throw new ne(400,`form field "${v}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,v);a.set(v,(a.get(v)??0)+1)}for(let[v,k]of a)if(k>1)throw new ne(400,`form field "${v}" appears ${k} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,v);let u=s.get("model");if(u!==null&&typeof u!="string")throw new ne(400,"model must be a string field","model");let l=u===null?void 0:u,d=s.get("language");if(d!==null&&(typeof d!="string"||d.trim().length===0))throw new ne(400,"language, when present, must be a non-empty string","language");let c=d===null?void 0:d,_=s.get("response_format")??"json";if(_!=="json")throw new ne(400,`response_format ${JSON.stringify(_)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let m=s.get("file");if(!(m instanceof File))throw new ne(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>o)throw new ne(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let p=new Uint8Array(await m.arrayBuffer());if(!zs(p))throw new ne(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let w=Pd(p);if(w===null)throw new ne(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Cd(n.turn,n.clients,l),n.stats?.request("audio_transcriptions",p.length,p.length),!await $d(n.transcriptionModels,l,e))return;let y=[{type:"input_audio",input_audio:{data:Buffer.from(p).toString("base64"),format:"wav"}}];try{let v=await Ld(n.clients,l,y,c,n.turn?Ee(n.turn):void 0);Md(n.turn,w),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:v}))}catch(v){throw Ys(v)}}catch(i){if(i instanceof ge){Wr(e,new ne(413,i.message));return}if(i instanceof ne){Wr(e,i);return}throw i}}var Gn=require("@urun-sh/core");x();var Kr=require("@urun-sh/core"),Ve=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},zr=33e4;function Qs(t,e=zr){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,i=new Promise((l,d)=>{o=d}),s=setTimeout(()=>o(new Fn),e),a;try{a=await Promise.race([r.next(),i])}catch(l){throw l instanceof re||l instanceof Kr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof Fn?(await r.return?.(void 0),new Ve("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new Ve("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(s)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new Ve("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var Fn=class extends Error{constructor(){super("stream idle timeout")}};function Zs(t){return t instanceof Ve?!1:t instanceof re?!0:t instanceof Kr.SessionFailedError?t.kind==="transport-failed":!1}x();var Xr="x-urun-profile",Yt="voice";var Re=class extends Error{status=400},Ud=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Dd=/\s/;function Fd(t){return Ud.test(t)}function Yr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Re(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function ea(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new Re(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new Re(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new Re(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function ta(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new Re(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let l=n.trim();if(l==="")throw new Re(`the ${Xr} header is empty \u2014 the only profile this lane accepts is "${Yt}" (omit the header for the ordinary lane)`);if(l!==Yt)throw new Re(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Yt}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==Yt)throw new Re(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${Yt}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new Re("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new Re("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:ea(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:ea(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Yr(u,"sentence_flush",!0),includeReasoning:Yr(u,"include_reasoning",!1),metadata:Yr(u,"metadata",!1)}}var Bn=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&Fd(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(Dd.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function eo(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function jd(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function we(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function fe(t,e,n,r="invalid_request_error",o){we(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function to(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);we(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function De(t,e,n,r){we(t,e,{type:"error",error:{type:n,message:r}})}function At(t,e,n){if(e==="anthropic"){we(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}we(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var qd=64*1024*1024,Xt=class extends Error{};async function na(t,e=qd){let n=[],r=0;for await(let i of t){if(r+=i.length,r>e)throw new Xt(`request body exceeds ${e} bytes`);n.push(i)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function dt(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function oa(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),i=r(n.output_tokens),s=u=>u??0,a=r(n.total_tokens)??s(o)+s(i);if(s(o)>0||s(i)>0){let u={input_tokens:s(o),output_tokens:s(i),total_tokens:a};return o===null||i===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function jn(t){let e=oa(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function ra(t){let e=jn(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Hd(t,e){let n=oa(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Gd(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let l=n[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),i=r("prefill_ms"),s=r("decode_ms"),a=r("total_ms");return o===null||i===null||s===null||a===null?null:{queue_ms:o,prefill_ms:i,decode_ms:s,total_ms:a}}function Vd(t,e){let n=Gd(e);n&&(t.timing=n)}function ct(t,e){Hd(t,e),Vd(t,e)}async function Vn(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function ia(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function Jd(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var qn=class extends Error{};function Wd(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new qn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Kd(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:Wd(n.role,n.content)})}return e}function Qr(t){return bt(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function zd(t,e,n,r,o,i){let s=jt(i.id),a=t.stream===!0;if(i.model=Se(t),i.stream=a,await Vn(i,e,typeof t.model=="string"?t.model:void 0),a){let v;try{v=await Ht({body:t,clients:e,store:n,stats:o,responseId:s,turn:i})}catch(k){if(k instanceof z){At(r,"openai",k);return}if(k instanceof Oe){fe(r,k.status,k.message);return}throw k}eo(r);for await(let k of v.events)k.type==="error"&&(i.streamError=!0),k.type==="response.completed"&&ct(i,k.response),r.write(`event: ${String(k.type??"message")}
28
+ `}function fd(t){Ne(process.stdout,t)}function md(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Gr(t){return t.audioSession?.audio.sessionId??void 0}function Tn(t,e){let n=new vs.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,i,s)=>{if(new URL(o.url??"/","http://localhost").pathname!==Wt)return;r.add(i),i.on("close",()=>{r.delete(i)});let u=N("rtup"),l=md(o),d=R=>{(e.log??fd)(pd(R))};d({stage:"accept",conn:u,model:l}),i.resume();let c=new AbortController,_=null,m=R=>{_??=R,c.abort(new Error(_))},p=()=>m("client socket closed"),w=()=>m("client socket closed (half-close)"),y=R=>m(`client socket error: ${R.message}`);i.once("close",p),i.once("end",w),i.once("error",y);let b=()=>{i.removeListener("close",p),i.removeListener("end",w),i.removeListener("error",y)},k=R=>{d({stage:"close",conn:u,model:l,...R})},h=R=>{let v=R,O=v.session!=null&&typeof v.session.sendResponseCreate=="function",j=v.clients!=null&&typeof v.clients.createResponse=="function";if(!O&&!j)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((P,F)=>{n.handleUpgrade(o,i,s,G=>{try{new Vt({ws:G,binding:R,onClosed:(Y,le)=>{k({while:"live",reason:le.reason})}}),d({stage:"admit",conn:u,model:l,...Gr(R)===void 0?{}:{session:Gr(R)}}),P()}catch(Y){F(Y)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async R=>{if(c.signal.aborted){b();let v=Gr(R);try{await R.release?.()}catch(O){k({while:"queued",...v===void 0?{}:{session:v},reason:_??"client socket closed",release_failed:O instanceof Error?O.message:String(O)});return}k({while:"queued",...v===void 0?{}:{session:v},reason:_??"client socket closed",released:!0}),i.destroy();return}b(),await h(R)}).catch(R=>{let v=R instanceof _s.SessionFailedError?xn(R):null,O=null;if(R!==null&&typeof R=="object"&&"status"in R){let F=R.status;typeof F=="number"&&(O=F)}let j=O??v?.status??502,P=R instanceof Error?R.message:String(R);k({while:"queued",...c.signal.aborted?{reason:_??"client socket closed"}:{reason:P,status:j}}),i.destroyed||cd(i,j,P)}).finally(()=>{r.delete(i)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>n.close(()=>i()))}}x();x();var Bd=require("http");x();var Et=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},Jt=class extends Et{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},Vr=class extends Et{constructor(e){super("acquire_timeout",429,30,`no decision slot capacity within ${e}ms (all slots at their in-flight cap)`)}},ut=class extends Error{lastDemandAgeMs;constructor(e){super("no ready decision slot on this proxy \u2014 the request was refused fast, not fenced; retry shortly (an out-of-band slot add was submitted)"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Pn=class{constructor(e){this.opts=e;if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}opts;slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;slotKey(e){return`decision:${this.opts.replicaId}:${e}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(){let e=this.slots.filter(n=>n.state==="paused"&&!n.opening).sort((n,r)=>n.slot.index-r.slot.index);return e.length>0?(this.openRuntime(e[0]),e[0]):this.ensureSlot()}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.state="paused",e.opening=null,this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n)),this.pump();return}e.opening=null})())}async acquire(){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Jt;this.lastDemandAt=this.now();let e=this.opts.acquireTimeoutMs??6e5,n=Date.now();for(;;){let r=this.tryLease();if(r)return r;if(this.draining)throw new Jt;if(!this.slots.some(u=>u.state==="queued")&&this.slots.length<this.opts.max){this.openForDemand();continue}let i=n+e-Date.now();if(i<=0)throw new Vr(e);let s,a={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(u=>{a.resolve=u,this.waiters.push(a)}),new Promise(u=>{s=setTimeout(u,i)})])}finally{clearTimeout(s);let u=this.waiters.indexOf(a);u!==-1&&this.waiters.splice(u,1),a.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Jt}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();return n||(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max&&this.openForDemand(),this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null)}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let i=o.session;if(typeof i!="object"||i===null||!("whenLive"in i))return!1;let s=i.whenLive;if(typeof s!="function")return!1;let a=r.entry;try{return await s.call(i,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&n--;continue}}return!1}tryLease(){let e=null;for(let i of this.slots)i.state!=="attached"||i.inFlight>=this.opts.inFlightCap||(!e||i.inFlight<e.inFlight)&&(e=i);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(r=>r.state==="attached"&&r.inFlight===0&&r.idleSince!==null&&e-r.idleSince>=this.idleGraceMs).sort((r,o)=>(r.idleSince??0)-(o.idleSince??0)||o.slot.index-r.slot.index);for(let r of n)this.endSlot(r)}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,i)=>o+i.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(i=>{r=i});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};x();x();var ge=class extends Error{};async function Cn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ge(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let i of t){let s=i;if(o+=s.length,o>e)throw new ge(`request body exceeds the ${e}-byte limit`);r.push(s)}return Buffer.concat(r)}async function Mn(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(s){try{let a=await n.next();if(a.done){s.close();return}if(r+=a.value.length,r>e){s.error(new ge(`request body exceeds the ${e}-byte limit`));return}s.enqueue(a.value)}catch(a){s.error(a)}},cancel(){n.return?.()}}),i;try{let s=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")s.set(l,d);else if(Array.isArray(d))for(let c of d)s.append(l,c);let a={method:"POST",headers:s,body:o,duplex:"half"};i=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(s){throw s instanceof ge?s:new Error(`malformed multipart body: ${String(s instanceof Error?s.message:s)}`)}return i}var bs="/v1/images/generations",Ln="/v1/images/edits";function Ss(t){return t===bs||t===Ln}var ks="/v1/images/models";async function Rs(t,e,n){if(t){if(t.model=Se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var K=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},hd=16*1024*1024,xs=64*1024*1024;function Es(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function Kt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function Os(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),i=null;for await(let c of o){if(c.type==="error"){let _=c.error??{};throw new K(502,`image upstream error: ${String(_.message??"upstream reported an error")}`)}if(c.type==="response.completed"){i=c.response??null;break}}if(i===null)throw new K(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let s=i.images;if(!Array.isArray(s)||s.length!==1||typeof s[0]!="string"||s[0].length===0)throw new K(502,`image upstream returned ${Array.isArray(s)?s.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],u=s[0].startsWith("data:")?s[0].slice(s[0].indexOf(";base64,")+8):s[0],l=Buffer.from(u,"base64");if(Es(l)===null)throw new K(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${l.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function As(t){return t instanceof K?t:t instanceof z?new K(404,t.message):new K(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Is(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return Kt(r,new K(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Ts(t,e){t&&(t.outputUnits=e.images.length)}function Ps(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var gd={model:!0,prompt:!0,response_format:!0,n:!0};async function Cs(t,e,n){let r=n.maxBodyBytes??xs;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${bs}`);let o;try{o=JSON.parse((await Cn(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof ge?new K(413,c.message):new K(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new K(400,"request body must be a JSON object");let i=o;for(let c of Object.keys(i))if(!gd[c])throw new K(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let s=i.prompt;if(typeof s!="string"||s.trim().length===0)throw new K(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new K(400,"model must be a string","model");await Rs(n.turn,n.clients,a);let u=i.n??1;if(u!==1)throw new K(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let l=i.response_format??"b64_json";if(l!=="b64_json")throw new K(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",s.length,s.length),!await Is(n.imageModels,a,"generation",e))return;let d=[{type:"input_text",text:s}];try{let c=await Os(n.clients,a,d,n.turn?Ee(n.turn):void 0);Ts(n.turn,c),Ps(e,c)}catch(c){throw As(c)}}catch(o){if(o instanceof ge){Kt(e,new K(413,o.message));return}if(o instanceof K){Kt(e,o);return}throw o}}var yd={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ms(t,e,n){let r=n.maxBodyBytes??xs,o=n.maxImagePartBytes??hd;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${Ln}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new K(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Mn(t,r)}catch(m){throw m instanceof ge?new K(413,m.message):new K(400,String(m instanceof Error?m.message:m))}let a=s.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new K(400,"prompt is required and must be a non-empty string field","prompt");let u=s.get("model");if(u!==null&&typeof u!="string")throw new K(400,"model must be a string field","model");let l=u===null?void 0:u;await Rs(n.turn,n.clients,l);let d=s.get("response_format")??"b64_json";if(d!=="b64_json")throw new K(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let m of s.keys())if(!yd[m])throw new K(400,`form field "${m}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,m);let c=[];for(let m of["image","image[]"])for(let p of s.getAll(m)){if(!(p instanceof File))throw new K(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(p.size>o)throw new K(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let w=new Uint8Array(await p.arrayBuffer()),y=Es(w);if(y===null)throw new K(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);c.push({bytes:w,mime:y})}if(c.length===0)throw new K(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await Is(n.imageModels,l,"edit",e))return;let _=[{type:"input_text",text:a}];for(let{bytes:m,mime:p}of c)_.push({type:"input_image",image_url:`data:${p};base64,${Buffer.from(m).toString("base64")}`});try{let m=await Os(n.clients,l,_,n.turn?Ee(n.turn):void 0);Ts(n.turn,m),Ps(e,m)}catch(m){throw As(m)}}catch(i){if(i instanceof ge){Kt(e,new K(413,i.message));return}if(i instanceof K){Kt(e,i);return}throw i}}x();var zt="/v1/audio/speech";function qs(t){return t===zt}var Ls=4096,$s=18e4,Ns=5e3,wd=64*1024*1024,Us=8,Ds=5,Fs=1024*1024,Ot="voice_applied",Nn="X-Urun-Voice-Applied",V=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Wr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Un=class extends V{constructor(e){super(502,e)}};function Hs(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Gs(t){return new V(502,`the runtime's ${Ot} receipt ${JSON.stringify(t)} cannot be relayed as the ${Nn} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function _d(t,e,n){if(t){if(t.model=Se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Vs(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var vd=2;function bd(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>vd)return!1;return!0}function Sd(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var Bs=new WeakMap,$n=new WeakMap;function kd(t,e){let n=$n.get(t)??0;if(n>=Us)throw new V(503,`this model's speech queue is full \u2014 ${Us} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Ds}s`,void 0,Ds);$n.set(t,n+1);let r=Bs.get(t)??Promise.resolve(),o,i=new Promise(s=>{o=s});return Bs.set(t,i),(async()=>{await r;try{return await e()}finally{$n.set(t,($n.get(t)??1)-1),o()}})()}async function Rd(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new V(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(s){if(!(s instanceof re))throw s}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),i;await Promise.race([o,new Promise(s=>{i=setTimeout(s,r)})]).finally(()=>{i!==void 0&&clearTimeout(i)})}function lt(t){return t instanceof V?t:t instanceof z?new V(404,t.message):new V(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function js(t,e,n,r,o,i,s,a){let u=a??(()=>{});return kd(e,async()=>{if(s?.()===!0)return null;let l=!1,d=!1,c=!1,_,m=new Promise(R=>{_=R}),p=[],w=()=>{d&&!c&&p.length>=o.quietRunFrames&&(c=!0,_())},y=e.onOutputAudio(R=>{let v=Buffer.from(R,"base64");if(v.byteLength===0)return;let O=bd(v);if(!l){if(O)return;l=!0}if(O){p.push(v),w();return}for(let j of p)u(j);p.length=0,u(v),w()}),b=null,k,h,A;try{A=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let v=new Promise(P=>{h=setTimeout(P,i.capMs)}),O=!1;for(;;){let P=A.next(),F=await Promise.race([P,v]);if(F===void 0){O=!0,P.catch(()=>{});break}if(F.done)break;let G=F.value;if(G.type==="error"){let Y=G.error??{};throw await A.return?.(),new V(502,`speech upstream error: ${String(Y.message??"upstream reported an error")}`)}if(G.type==="response.completed"){b=G.response??null,d=!0,w(),await A.return?.();break}}if(clearTimeout(h),O)throw new V(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(b===null)throw new V(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let j=!1;if(await Promise.race([m,new Promise(P=>{k=setTimeout(()=>{j=!0,P()},o.capMs)})]),k!==void 0&&clearTimeout(k),r.voice!==void 0){let P=b[Ot];if(typeof P!="string"||P!==r.voice){let F=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof P=="string"?`${Ot} ${JSON.stringify(P)}`:`no ${Ot} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new Un(F):new V(502,F)}}if(!l)throw new V(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(j&&!c&&p.length<1)throw new V(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return b}catch(R){throw R instanceof Un||await Rd(t,n,A,i.returnBoundMs),R}finally{k!==void 0&&clearTimeout(k),h!==void 0&&clearTimeout(h),y()}})}function xd(t,e,n,r){let o=!1,i=0,s=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Nn)),t.write(a,u=>{u||(i+=a.byteLength,Vs(e,i))}),t.writableLength>Fs&&(e&&(e.streamError=!0),s(new Error(`the streamed pcm answer's undrained buffer crossed ${Fs} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let u=a[Ot];if(typeof u=="string"){if(!Hs(u))throw Gs(u);t.addTrailers({[Nn]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:s}}async function Ed(t,e,n){let r;try{r=await t(e)}catch(o){throw lt(o)}return r?!0:(Wr(n,new V(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var Od={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Ad="wav, pcm";async function Ws(t,e,n){let r=n.maxBodyBytes??wd,o=!1;e.once("close",()=>{o=!0});let i=()=>o||e.destroyed;try{if(t.method!=="POST")throw new V(405,`${String(t.method)} is not supported on ${zt}`);let s;try{s=JSON.parse((await Cn(t,r)).toString("utf8")||"{}")}catch(h){throw h instanceof ge?new V(413,h.message):new V(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new V(400,"request body must be a JSON object");let a=s;for(let h of Object.keys(a))if(!Od[h])throw new V(400,`request field "${h}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,h);let u=a.input;if(typeof u!="string"||u.trim().length===0)throw new V(400,"input is required and must be a non-empty string","input");if(u.length>Ls)throw new V(400,`input is ${u.length} chars \u2014 over the ${Ls}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let l=a.model===void 0?void 0:a.model;if(l!==void 0&&typeof l!="string")throw new V(400,"model must be a string","model");let d=a.voice;if(d!==void 0&&(typeof d!="string"||d.trim().length===0))throw new V(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new V(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${zt} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(l)}catch(h){throw lt(h)}if(c.defect!==null)throw new V(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let _=typeof d=="string"?d:void 0;if(_!==void 0&&c.published.length>0&&!c.published.includes(_))throw new V(400,`voice ${JSON.stringify(_)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let m=a.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new V(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Ad} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new V(400,"stream_format, when present, must be a string","stream_format");let p=a.speed;if(p!==void 0){if(typeof p!="number"||!Number.isFinite(p))throw new V(400,"speed, when present, must be a number","speed");if(p!==1)throw new V(400,`speed=${JSON.stringify(p)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let w=a.instructions;if(w!==void 0){if(typeof w!="string")throw new V(400,"instructions, when present, must be a string","instructions");if(w.trim().length>0)throw new V(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await _d(n.turn,n.clients,l);let y=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",y,y),!await Ed(n.speechModels,l,e))return;if(typeof n.clients.openAudioOn!="function")throw new V(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new V(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new V(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let b;try{b=await n.clients.speechSessionHandle(l)}catch(h){throw lt(h)}let k;try{k=await n.clients.openAudioOn(b)}catch(h){throw lt(h)}n.turn&&(n.turn.sessionId=k.sessionId);try{if(m==="wav"){let h=[],A=await js(n.clients,k,b,{model:l,text:u,..._!==void 0?{voice:_}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??$s,returnBoundMs:n.turnReturnBoundMs??Ns},i,v=>h.push(v));if(A===null||i())return;let R=Buffer.concat(h);if(_===void 0){let v=A[Ot];if(typeof v=="string"){if(!Hs(v))throw Gs(v);e.setHeader(Nn,v)}}Vs(n.turn,R.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Sd(R.byteLength),R]))}else{let h=xd(e,n.turn,i,_===void 0),A;try{A=await js(n.clients,k,b,{model:l,text:u,..._!==void 0?{voice:_}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??$s,returnBoundMs:n.turnReturnBoundMs??Ns},i,h.sink)}catch(R){let v=lt(R);if(!h.started())throw v;n.turn&&(n.turn.streamError=!0),h.fail(v);return}if(A===null)return;try{await h.finish(A)}catch(R){let v=lt(R);n.turn&&(n.turn.streamError=!0),h.fail(v);return}}}catch(h){throw lt(h)}}catch(s){if(s instanceof ge){Wr(e,new V(413,s.message));return}if(s instanceof V){Wr(e,s);return}throw s}}x();var Dn="/v1/audio/transcriptions";function Js(t){return t===Dn}var Ks="/v1/audio/models",Id=16*1024*1024,Td=64*1024*1024,ne=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Jr(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function zs(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function Pd(t){if(!zs(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),s=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,l=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:l,channels:u,bitsPerSample:d}}else if(i==="data"){let u=t.length-a;r=Math.min(s===0||s===4294967295?u:s,u)}e=a+s+s%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function Cd(t,e,n){if(t){if(t.model=Se({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Md(t,e){t&&(t.outputUnits=e.seconds)}async function Ld(t,e,n,r,o){let i=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),s=[],a=null;for await(let u of i){if(s.push(u),u.type==="error"){let l=u.error??{},d=typeof l.type=="string"?l.type:"upstream_error",c=String(l.message??"upstream reported an error");throw new ne(d==="invalid_request_error"?400:502,`transcription upstream error: ${c}`)}if(u.type==="response.completed"){a=u.response??null;break}}if(a===null)throw new ne(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return kt(s,a)}function Ys(t){return t instanceof ne?t:t instanceof z?new ne(404,t.message):new ne(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function $d(t,e,n){let r;try{r=await t(e)}catch(o){throw Ys(o)}return r?!0:(Jr(n,new ne(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Nd=new Set(["file","model","language","response_format"]);async function Xs(t,e,n){let r=n.maxBodyBytes??Td,o=n.maxAudioPartBytes??Id;try{if(t.method!=="POST")throw new ne(405,`${String(t.method)} is not supported on ${Dn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new ne(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let s;try{s=await Mn(t,r)}catch(b){throw b instanceof ge?new ne(413,b.message):new ne(400,String(b instanceof Error?b.message:b))}let a=new Map;for(let b of s.keys()){if(!Nd.has(b))throw new ne(400,`form field "${b}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,b);a.set(b,(a.get(b)??0)+1)}for(let[b,k]of a)if(k>1)throw new ne(400,`form field "${b}" appears ${k} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,b);let u=s.get("model");if(u!==null&&typeof u!="string")throw new ne(400,"model must be a string field","model");let l=u===null?void 0:u,d=s.get("language");if(d!==null&&(typeof d!="string"||d.trim().length===0))throw new ne(400,"language, when present, must be a non-empty string","language");let c=d===null?void 0:d,_=s.get("response_format")??"json";if(_!=="json")throw new ne(400,`response_format ${JSON.stringify(_)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let m=s.get("file");if(!(m instanceof File))throw new ne(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>o)throw new ne(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let p=new Uint8Array(await m.arrayBuffer());if(!zs(p))throw new ne(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let w=Pd(p);if(w===null)throw new ne(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Cd(n.turn,n.clients,l),n.stats?.request("audio_transcriptions",p.length,p.length),!await $d(n.transcriptionModels,l,e))return;let y=[{type:"input_audio",input_audio:{data:Buffer.from(p).toString("base64"),format:"wav"}}];try{let b=await Ld(n.clients,l,y,c,n.turn?Ee(n.turn):void 0);Md(n.turn,w),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:b}))}catch(b){throw Ys(b)}}catch(i){if(i instanceof ge){Jr(e,new ne(413,i.message));return}if(i instanceof ne){Jr(e,i);return}throw i}}var Gn=require("@urun-sh/core");x();var Kr=require("@urun-sh/core"),Ve=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},zr=33e4;function Qs(t,e=zr){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,i=new Promise((l,d)=>{o=d}),s=setTimeout(()=>o(new Fn),e),a;try{a=await Promise.race([r.next(),i])}catch(l){throw l instanceof re||l instanceof Kr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof Fn?(await r.return?.(void 0),new Ve("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new Ve("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(s)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new Ve("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var Fn=class extends Error{constructor(){super("stream idle timeout")}};function Zs(t){return t instanceof Ve?!1:t instanceof re?!0:t instanceof Kr.SessionFailedError?t.kind==="transport-failed":!1}x();var Xr="x-urun-profile",Yt="voice";var Re=class extends Error{status=400},Ud=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Dd=/\s/;function Fd(t){return Ud.test(t)}function Yr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Re(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function ea(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new Re(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new Re(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new Re(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function ta(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new Re(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,i=o?.profile,s=!1;if(n!=null){let l=n.trim();if(l==="")throw new Re(`the ${Xr} header is empty \u2014 the only profile this lane accepts is "${Yt}" (omit the header for the ordinary lane)`);if(l!==Yt)throw new Re(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Yt}"`);s=!0}if(i!==void 0){if(typeof i!="string"||i!==Yt)throw new Re(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${Yt}"`);s=!0}if(!s)return null;if(e.stream!==!0)throw new Re("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new Re("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:ea(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:ea(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Yr(u,"sentence_flush",!0),includeReasoning:Yr(u,"include_reasoning",!1),metadata:Yr(u,"metadata",!1)}}var Bn=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&Fd(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(Dd.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function eo(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function jd(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function we(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function fe(t,e,n,r="invalid_request_error",o){we(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function to(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);we(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function De(t,e,n,r){we(t,e,{type:"error",error:{type:n,message:r}})}function At(t,e,n){if(e==="anthropic"){we(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}we(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var qd=64*1024*1024,Xt=class extends Error{};async function na(t,e=qd){let n=[],r=0;for await(let i of t){if(r+=i.length,r>e)throw new Xt(`request body exceeds ${e} bytes`);n.push(i)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function dt(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function oa(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),i=r(n.output_tokens),s=u=>u??0,a=r(n.total_tokens)??s(o)+s(i);if(s(o)>0||s(i)>0){let u={input_tokens:s(o),output_tokens:s(i),total_tokens:a};return o===null||i===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function jn(t){let e=oa(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function ra(t){let e=jn(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Hd(t,e){let n=oa(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Gd(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let l=n[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),i=r("prefill_ms"),s=r("decode_ms"),a=r("total_ms");return o===null||i===null||s===null||a===null?null:{queue_ms:o,prefill_ms:i,decode_ms:s,total_ms:a}}function Vd(t,e){let n=Gd(e);n&&(t.timing=n)}function ct(t,e){Hd(t,e),Vd(t,e)}async function Vn(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function ia(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function Wd(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var qn=class extends Error{};function Jd(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new qn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Kd(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:Jd(n.role,n.content)})}return e}function Qr(t){return bt(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function zd(t,e,n,r,o,i){let s=jt(i.id),a=t.stream===!0;if(i.model=Se(t),i.stream=a,await Vn(i,e,typeof t.model=="string"?t.model:void 0),a){let b;try{b=await Ht({body:t,clients:e,store:n,stats:o,responseId:s,turn:i})}catch(k){if(k instanceof z){At(r,"openai",k);return}if(k instanceof Oe){fe(r,k.status,k.message);return}throw k}eo(r);for await(let k of b.events)k.type==="error"&&(i.streamError=!0),k.type==="response.completed"&&ct(i,k.response),r.write(`event: ${String(k.type??"message")}
29
29
  data: ${JSON.stringify(k)}
30
30
 
31
31
  `);r.write(`data: [DONE]
32
32
 
33
- `),r.end();return}let u;try{u=Rt(n,t)}catch(v){if(v instanceof Oe){fe(r,v.status,v.message);return}throw v}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let l=t.store!==!1,d=Se(t);o.model(d);let c=Array.isArray(t.tools)&&t.tools.length>0,_;try{_=await Cr(e,t,u,!1,Ee(i))}catch(v){if(v instanceof z){At(r,"openai",v);return}if(v instanceof Oe){fe(r,v.status,v.message);return}throw v}let m=[],p=null;for await(let v of o.track(_,d,i)){if(m.push(v),v.type==="error"){to(r,v);return}v.type==="response.completed"&&(p=v.response)}if(p==null){fe(r,502,"upstream produced no response.completed event","upstream_error");return}ct(i,p);let w=kt(m,p),y=at(c,bt(p).length,w);if(y){fe(r,502,st(d,y),"upstream_error");return}l&&n.remember(s,u,Pr(p,w),l),we(r,200,{...p,id:s})}async function Yd(t,e,n,r,o,i){let s=t.messages;if(!Array.isArray(s)){fe(n,400,"chat/completions requires a messages array");return}let a;try{a=ta(i,t)}catch(P){if(P instanceof Re){fe(n,P.status,P.message);return}throw P}let u=String(t.model??"urun"),l=is(o.id),d;try{d=Kd(s)}catch(P){if(P instanceof qn){fe(n,400,P.message);return}throw P}let c=Se(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Vn(o,e,typeof t.model=="string"?t.model:void 0);let _=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:d,stream:!0,tools:Jd(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},Ee(o))}catch(P){if(P instanceof z){At(n,"openai",P);return}throw P}if(t.stream===!0){a?jd(n):eo(n);let P=[],F=new Ye,G="",Y=a?new Bn(a,he=>{n.write(`data: ${JSON.stringify(dt(l,u,{content:he},null))}
33
+ `),r.end();return}let u;try{u=Rt(n,t)}catch(b){if(b instanceof Oe){fe(r,b.status,b.message);return}throw b}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let l=t.store!==!1,d=Se(t);o.model(d);let c=Array.isArray(t.tools)&&t.tools.length>0,_;try{_=await Cr(e,t,u,!1,Ee(i))}catch(b){if(b instanceof z){At(r,"openai",b);return}if(b instanceof Oe){fe(r,b.status,b.message);return}throw b}let m=[],p=null;for await(let b of o.track(_,d,i)){if(m.push(b),b.type==="error"){to(r,b);return}b.type==="response.completed"&&(p=b.response)}if(p==null){fe(r,502,"upstream produced no response.completed event","upstream_error");return}ct(i,p);let w=kt(m,p),y=at(c,bt(p).length,w);if(y){fe(r,502,st(d,y),"upstream_error");return}l&&n.remember(s,u,Pr(p,w),l),we(r,200,{...p,id:s})}async function Yd(t,e,n,r,o,i){let s=t.messages;if(!Array.isArray(s)){fe(n,400,"chat/completions requires a messages array");return}let a;try{a=ta(i,t)}catch(P){if(P instanceof Re){fe(n,P.status,P.message);return}throw P}let u=String(t.model??"urun"),l=is(o.id),d;try{d=Kd(s)}catch(P){if(P instanceof qn){fe(n,400,P.message);return}throw P}let c=Se(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Vn(o,e,typeof t.model=="string"?t.model:void 0);let _=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:d,stream:!0,tools:Wd(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},Ee(o))}catch(P){if(P instanceof z){At(n,"openai",P);return}throw P}if(t.stream===!0){a?jd(n):eo(n);let P=[],F=new Ye,G="",Y=a?new Bn(a,he=>{n.write(`data: ${JSON.stringify(dt(l,u,{content:he},null))}
34
34
 
35
35
  `)}):null,le=he=>{Y?.flush(),n.write(he),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:l,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
36
36
 
@@ -54,20 +54,20 @@ data: ${JSON.stringify(k)}
54
54
 
55
55
  `),n.write(`data: [DONE]
56
56
 
57
- `),n.end();return}finally{Y?.flush(),Y?.dispose()}}let p="",w="",y=[],v=new Ye;for await(let P of r.track(m,c,o)){y.push(P),P.type==="response.output_text.delta"&&typeof P.delta=="string"&&(p+=P.delta),P.type==="response.reasoning_text.delta"&&typeof P.delta=="string"&&(w+=P.delta);let F=St(P);if(F&&v.add(F),P.type==="error"){to(n,P);return}}let k=Ue(y);ct(o,k);let h=Qr(k),A=h.length>0?h:Qr({output:v.items()}),R=at(_,A.length,p);if(R){fe(n,502,st(c,R),"upstream_error");return}let S=A.map(({index:P,...F})=>F),O={role:"assistant",content:p||null},j=w||ia(k);j&&(O.reasoning_content=j),S.length>0&&(O.tool_calls=S),we(n,200,{id:l,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:O,finish_reason:S.length>0?"tool_calls":"stop"}],usage:ra(k)})}var no="sense-latest";async function Xd(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){fe(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:no,s=Se({model:i});if(o.model=s,o.stream=!1,t.state===void 0||t.state===null){fe(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){fe(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){fe(n,400,"systemone media, when present, must be an array");return}let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=u;let l=performance.now();r.model(s),await Vn(o,e,i),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await e.createResponse({model:i,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},Ee(o))}catch(v){if(v instanceof z){At(n,"openai",v);return}if(v instanceof ut){n.setHeader("retry-after","2"),fe(n,503,v.message,"capacity_error");return}throw v}u.dial_ms=Math.round(performance.now()-c);let _=[],m=null;try{for await(let v of r.track(d,s,o))if(m===null&&(m=performance.now(),u.first_event_ms=Math.round(m-c)),_.push(v),v.type==="error"){to(n,v);return}}catch(v){if(v instanceof z){m!==null&&(u.stream_ms=Math.round(performance.now()-m)),At(n,"openai",v);return}if(v instanceof ut){m!==null&&(u.stream_ms=Math.round(performance.now()-m)),n.setHeader("retry-after","2"),fe(n,503,v.message,"capacity_error");return}throw m!==null&&(u.stream_ms=Math.round(performance.now()-m)),v}m!==null&&(u.stream_ms=Math.round(performance.now()-m));let p=Ue(_);if(p==null){fe(n,502,"upstream produced no response.completed event","upstream_error");return}ct(o,p);let w=kt(_,p),y;try{y=JSON.parse(w)}catch{fe(n,502,"systemone answer was not valid JSON","upstream_error");return}if(y===null||typeof y!="object"||Array.isArray(y)){fe(n,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof y=="object"&&y!==null&&!Array.isArray(y)&&"timing"in y){let v=y.timing;if(typeof v=="object"&&v!==null&&!Array.isArray(v)&&"question_fwd_ms"in v&&"head_ms"in v){let k=h=>typeof h=="number"&&Number.isFinite(h)&&h>=0?Math.round(h):null;u.question_fwd_ms=k(v.question_fwd_ms),u.head_ms=k(v.head_ms)}}we(n,200,y)}function Qd(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Qt=class extends Error{};function Hn(t){return new Qt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Zd(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function ec(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new Qt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function tc(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Hn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Hn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function nc(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw Hn(typeof n);let r=[],o="",i=()=>{o&&(r.push({role:e,content:o}),o="")};for(let s of n){let a=String(s.type??"");if(a==="text")o+=String(s.text??"");else if(a==="tool_use")i(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});else if(a==="tool_result")i(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:tc(s.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Hn(a)}}return i(),r}function Zr(t){return bt(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function rc(t,e,n,r,o){let i=t.messages;if(!Array.isArray(i)){De(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){De(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){De(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(O=>typeof O!="string"))){De(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let s=String(t.model??"urun"),a=ss(o.id),u=[],l;try{t.system&&u.push({role:"system",content:Qd(t.system)});for(let O of i)u.push(...nc(O));l=ec(t.tool_choice)}catch(O){if(O instanceof Qt){De(n,400,"invalid_request_error",O.message);return}throw O}let d=Se(t);r.model(d),o.model=d,o.stream=t.stream===!0,await Vn(o,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0,_;try{_=await e.createResponse({model:t.model,input:u,stream:!0,tools:Zd(t.tools),tool_choice:l,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},Ee(o))}catch(O){if(O instanceof z){At(n,"anthropic",O);return}throw O}let m=(O,j)=>{n.destroyed||n.write(`event: ${O}
57
+ `),n.end();return}finally{Y?.flush(),Y?.dispose()}}let p="",w="",y=[],b=new Ye;for await(let P of r.track(m,c,o)){y.push(P),P.type==="response.output_text.delta"&&typeof P.delta=="string"&&(p+=P.delta),P.type==="response.reasoning_text.delta"&&typeof P.delta=="string"&&(w+=P.delta);let F=St(P);if(F&&b.add(F),P.type==="error"){to(n,P);return}}let k=Ue(y);ct(o,k);let h=Qr(k),A=h.length>0?h:Qr({output:b.items()}),R=at(_,A.length,p);if(R){fe(n,502,st(c,R),"upstream_error");return}let v=A.map(({index:P,...F})=>F),O={role:"assistant",content:p||null},j=w||ia(k);j&&(O.reasoning_content=j),v.length>0&&(O.tool_calls=v),we(n,200,{id:l,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:O,finish_reason:v.length>0?"tool_calls":"stop"}],usage:ra(k)})}var no="sense-latest";async function Xd(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){fe(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:no,s=Se({model:i});if(o.model=s,o.stream=!1,t.state===void 0||t.state===null){fe(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){fe(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){fe(n,400,"systemone media, when present, must be an array");return}let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=u;let l=performance.now();r.model(s),await Vn(o,e,i),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await e.createResponse({model:i,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},Ee(o))}catch(b){if(b instanceof z){At(n,"openai",b);return}if(b instanceof ut){n.setHeader("retry-after","2"),fe(n,503,b.message,"capacity_error");return}throw b}u.dial_ms=Math.round(performance.now()-c);let _=[],m=null;try{for await(let b of r.track(d,s,o))if(m===null&&(m=performance.now(),u.first_event_ms=Math.round(m-c)),_.push(b),b.type==="error"){to(n,b);return}}catch(b){if(b instanceof z){m!==null&&(u.stream_ms=Math.round(performance.now()-m)),At(n,"openai",b);return}if(b instanceof ut){m!==null&&(u.stream_ms=Math.round(performance.now()-m)),n.setHeader("retry-after","2"),fe(n,503,b.message,"capacity_error");return}throw m!==null&&(u.stream_ms=Math.round(performance.now()-m)),b}m!==null&&(u.stream_ms=Math.round(performance.now()-m));let p=Ue(_);if(p==null){fe(n,502,"upstream produced no response.completed event","upstream_error");return}ct(o,p);let w=kt(_,p),y;try{y=JSON.parse(w)}catch{fe(n,502,"systemone answer was not valid JSON","upstream_error");return}if(y===null||typeof y!="object"||Array.isArray(y)){fe(n,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof y=="object"&&y!==null&&!Array.isArray(y)&&"timing"in y){let b=y.timing;if(typeof b=="object"&&b!==null&&!Array.isArray(b)&&"question_fwd_ms"in b&&"head_ms"in b){let k=h=>typeof h=="number"&&Number.isFinite(h)&&h>=0?Math.round(h):null;u.question_fwd_ms=k(b.question_fwd_ms),u.head_ms=k(b.head_ms)}}we(n,200,y)}function Qd(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Qt=class extends Error{};function Hn(t){return new Qt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Zd(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function ec(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new Qt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function tc(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Hn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Hn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function nc(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw Hn(typeof n);let r=[],o="",i=()=>{o&&(r.push({role:e,content:o}),o="")};for(let s of n){let a=String(s.type??"");if(a==="text")o+=String(s.text??"");else if(a==="tool_use")i(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});else if(a==="tool_result")i(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:tc(s.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Hn(a)}}return i(),r}function Zr(t){return bt(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function rc(t,e,n,r,o){let i=t.messages;if(!Array.isArray(i)){De(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){De(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){De(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(O=>typeof O!="string"))){De(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let s=String(t.model??"urun"),a=ss(o.id),u=[],l;try{t.system&&u.push({role:"system",content:Qd(t.system)});for(let O of i)u.push(...nc(O));l=ec(t.tool_choice)}catch(O){if(O instanceof Qt){De(n,400,"invalid_request_error",O.message);return}throw O}let d=Se(t);r.model(d),o.model=d,o.stream=t.stream===!0,await Vn(o,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0,_;try{_=await e.createResponse({model:t.model,input:u,stream:!0,tools:Zd(t.tools),tool_choice:l,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},Ee(o))}catch(O){if(O instanceof z){At(n,"anthropic",O);return}throw O}let m=(O,j)=>{n.destroyed||n.write(`event: ${O}
58
58
  data: ${JSON.stringify({type:O,...j})}
59
59
 
60
- `)};if(t.stream===!0){let O=r.track(_,d,o);eo(n),m("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:s,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let j=0,P="",F=0,G="none",Y=()=>G,le=-1,he=-1,ve=new Ye,Te=[],ee=()=>{G!=="none"&&(G="none",m("content_block_stop",{index:le}))},te=(q,me)=>{ee(),G=q,le=F++,m("content_block_start",{index:le,content_block:me})};for await(let q of O){if(n.destroyed)break;Te.push(q);let me=St(q);if(q.type==="response.reasoning_text.delta"&&typeof q.delta=="string")Y()!=="thinking"&&te("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:le,delta:{type:"thinking_delta",thinking:q.delta}});else if(q.type==="response.output_text.delta"&&typeof q.delta=="string")Y()!=="text"&&te("text",{type:"text",text:""}),j+=1,P+=q.delta,m("content_block_delta",{index:le,delta:{type:"text_delta",text:q.delta}});else if(me){let{call:$e}=ve.add(me);(Y()!=="tool"||me.tool_index!==he)&&(he=me.tool_index,te("tool",{type:"tool_use",id:$e.id??`call_${me.tool_index}`,name:$e.name??"",input:{}})),me.delta&&m("content_block_delta",{index:le,delta:{type:"input_json_delta",partial_json:me.delta}})}else if(q.type==="error"){o.streamError=!0,m("error",{error:{type:"api_error",message:JSON.stringify(q)}}),n.end();return}}if(n.destroyed)return;let de=Ue(Te),Le=bt(de),H=at(c,ve.size+Le.length,P);if(H){o.streamError=!0,m("error",{error:{type:"api_error",message:st(d,H)}}),n.end();return}ee();let I=[];if(ve.size===0)try{I=Zr(de)}catch(q){o.streamError=!0,m("error",{error:{type:"api_error",message:String(q instanceof Error?q.message:q)}}),n.end();return}F===0&&I.length===0&&(te("text",{type:"text",text:""}),ee()),I.forEach(q=>{let me=F++;m("content_block_start",{index:me,content_block:{...q,input:{}}}),m("content_block_delta",{index:me,delta:{type:"input_json_delta",partial_json:JSON.stringify(q.input??{})}}),m("content_block_stop",{index:me})});let X=ve.size>0||I.length>0,Pe=jn(de);ct(o,de),m("message_delta",{delta:{stop_reason:X?"tool_use":"end_turn"},usage:Pe?{input_tokens:Pe.input_tokens,output_tokens:Pe.output_tokens}:{output_tokens:j}}),m("message_stop",{}),n.end();return}let p="",w="",y=[],v=new Ye;for await(let O of r.track(_,d,o)){y.push(O),O.type==="response.output_text.delta"&&typeof O.delta=="string"&&(p+=O.delta),O.type==="response.reasoning_text.delta"&&typeof O.delta=="string"&&(w+=O.delta);let j=St(O);if(j&&v.add(j),O.type==="error"){let P=O.error,F=P?.type==="invalid_request_error";De(n,F?400:502,F?"invalid_request_error":"api_error",P?.message??JSON.stringify(O));return}if(n.destroyed)break}if(n.destroyed)return;let k=Ue(y);ct(o,k);let h;try{h=Zr(k),h.length===0&&v.size>0&&(h=Zr({output:v.items()}))}catch(O){De(n,502,"api_error",String(O instanceof Error?O.message:O));return}let A=at(c,h.length,p);if(A){De(n,502,"api_error",st(d,A));return}let R=[],S=w||ia(k);S&&R.push({type:"thinking",thinking:S}),(p||h.length===0)&&R.push({type:"text",text:p}),R.push(...h),we(n,200,{id:a,type:"message",role:"assistant",content:R,model:s,stop_reason:h.length>0?"tool_use":"end_turn",usage:jn(k)??{input_tokens:0,output_tokens:0}})}function oc(t){Ne(process.stdout,t)}function sa(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,i=typeof e=="function"?e:()=>e,s=t.requestLog??oc,a=t.observe,u=new ot;return(l,d)=>{let c=new URL(l.url??"/","http://localhost"),_=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),m=(k,h,A,R,S)=>_?De(d,k,R,h):fe(d,k,h,A,S),p=Tr(c.pathname),w=c.pathname.startsWith("/partners/"),y=p||w?{id:Bt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,sessionId:null,timing:null}:null;y&&(d.setHeader(rs,y.id),d.once("close",()=>{let k=as({turn:y,method:l.method??"",path:c.pathname,res:d});s(us(k)),a?.(k),fi({record:k,ledger:t.ledger??null,req:l})}));let v=()=>os(c.pathname,y);(async()=>{if(l.method==="GET"&&c.pathname==="/healthz"){we(d,200,{ok:!0});return}if(l.method==="GET"&&c.pathname==="/stats"){we(d,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(l.headers.authorization??"")!==`Bearer ${n}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let k=c.pathname===cn?"canonical":c.pathname===Ut?"huggingface":null;if(k){if(l.method!=="POST"){m(405,`${c.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let S=t.usage;if(!S){m(501,`${c.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let O=S.authorize(l),j;try{j=await na(l,wi)}catch(G){if(G instanceof Xt){m(413,G.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let P=G=>S.lookup(O,G),F;try{if(k==="canonical"){let G=_i(j),Y=await P(G);pn(Y,G),F={requests:Y}}else F=await Si(j,P)}catch(G){if(G instanceof ze){m(G.status,G.message,"invalid_request_error","invalid_request_error");return}throw G}we(d,200,F);return}if(l.method==="GET"&&c.pathname===Ze){let S=await i(l);if(y&&(y.org=S.tenant??null),!S.openRouterModels){m(501,`GET ${Ze} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}we(d,200,await S.openRouterModels());return}if(c.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${l.method} ${c.pathname} \u2014 the partner surface currently carries ${Ut} and GET ${Ze}`,"invalid_request_error","not_found_error");return}let h=await i(l);if(y&&(y.org=h.tenant??null),l.method==="GET"&&c.pathname==="/v1/models"){if(c.searchParams.get("format")==="openrouter"){d.writeHead(308,{location:Ze}),d.end();return}we(d,200,await h.listModels());return}if(l.method==="GET"&&c.pathname===ks){if(!h.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}we(d,200,await h.listImageModels());return}if(Ss(c.pathname)){if(!h.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${c.pathname}`,"not_implemented","not_implemented_error");return}let S={clients:h,imageModels:h.supportsImages,stats:u,turn:v()};c.pathname===Ln?await Ms(l,d,S):await Cs(l,d,S);return}if(l.method==="GET"&&c.pathname===Ks){if(!h.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}we(d,200,await h.listSpeechToTextModels());return}if(Ws(c.pathname)){if(!h.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Dn}`,"not_implemented","not_implemented_error");return}let S={clients:h,transcriptionModels:h.supportsTranscription,stats:u,turn:v()};await Xs(l,d,S);return}if(qs(c.pathname)){if(!h.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${zt}`,"not_implemented","not_implemented_error");return}let S={clients:h,speechModels:h.supportsSpeech,stats:u,turn:v()};await Js(l,d,S);return}if(l.method!=="POST"){m(404,`no route for ${l.method} ${c.pathname}`,"invalid_request_error","not_found_error");return}let A;try{A=await na(l)}catch(S){if(S instanceof Xt){m(413,S.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let R=Buffer.byteLength(JSON.stringify(A));if(c.pathname==="/v1/responses"){u.request("responses",R,R),await zd(A,h,qt(h),d,u,v());return}if(c.pathname==="/v1/chat/completions"){u.request("chat_completions",R,R),await Yd(A,h,d,u,v(),l.headers[Xr]);return}if(c.pathname==="/v1/systemone"){u.request("systemone",R,R),await Xd(A,h,d,u,v());return}if(c.pathname==="/v1/messages"){u.request("messages",R,R),await rc(A,h,d,u,v());return}if(c.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",R,R),De(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}m(404,`no route for POST ${c.pathname}`,"invalid_request_error","not_found_error")})().catch(k=>{let h=String(k instanceof Error?k.message:k);if(!d.headersSent){let R=o?.(k)??null;if(R){m(R.status,h,R.openaiType,R.anthropicType);return}if(k instanceof Gn.SessionAllocationError){let S=Rn(k.code);if(S){let O=k.retryAfterSeconds??(S.status===429?30:void 0);O!==void 0&&d.setHeader("Retry-After",String(O)),m(S.status,Dr(S,k.code??void 0),S.openaiType,S.anthropicType,S.code);return}}if(k instanceof Gn.SessionFailedError){let S=xn(k);if(S){let O=S.status===429?30:void 0;O!==void 0&&d.setHeader("Retry-After",String(O)),m(S.status,Dr(S,k.status.sessionId?`session ${k.status.sessionId}`:void 0),S.openaiType,S.anthropicType,S.code);return}}if(k instanceof oe){m(502,h,"upstream_error","api_error");return}if(k instanceof Ve){k.retryable&&d.setHeader("Retry-After","1"),m(502,h,"upstream_error","api_error",k.code);return}if(k instanceof Et){d.setHeader("Retry-After",String(k.retryAfterSeconds)),m(k.status,h,k.status===429?"capacity_error":"upstream_error",k.status===429?"rate_limit_error":"overloaded_error",k.code);return}m(500,h,"proxy_error","api_error","proxy_error");return}y&&(y.streamError=!0);let A=k instanceof Ve?k.code:null;d.destroyed||(_?d.write(`event: error
60
+ `)};if(t.stream===!0){let O=r.track(_,d,o);eo(n),m("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:s,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let j=0,P="",F=0,G="none",Y=()=>G,le=-1,he=-1,ve=new Ye,Te=[],ee=()=>{G!=="none"&&(G="none",m("content_block_stop",{index:le}))},te=(q,me)=>{ee(),G=q,le=F++,m("content_block_start",{index:le,content_block:me})};for await(let q of O){if(n.destroyed)break;Te.push(q);let me=St(q);if(q.type==="response.reasoning_text.delta"&&typeof q.delta=="string")Y()!=="thinking"&&te("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:le,delta:{type:"thinking_delta",thinking:q.delta}});else if(q.type==="response.output_text.delta"&&typeof q.delta=="string")Y()!=="text"&&te("text",{type:"text",text:""}),j+=1,P+=q.delta,m("content_block_delta",{index:le,delta:{type:"text_delta",text:q.delta}});else if(me){let{call:$e}=ve.add(me);(Y()!=="tool"||me.tool_index!==he)&&(he=me.tool_index,te("tool",{type:"tool_use",id:$e.id??`call_${me.tool_index}`,name:$e.name??"",input:{}})),me.delta&&m("content_block_delta",{index:le,delta:{type:"input_json_delta",partial_json:me.delta}})}else if(q.type==="error"){o.streamError=!0,m("error",{error:{type:"api_error",message:JSON.stringify(q)}}),n.end();return}}if(n.destroyed)return;let de=Ue(Te),Le=bt(de),H=at(c,ve.size+Le.length,P);if(H){o.streamError=!0,m("error",{error:{type:"api_error",message:st(d,H)}}),n.end();return}ee();let I=[];if(ve.size===0)try{I=Zr(de)}catch(q){o.streamError=!0,m("error",{error:{type:"api_error",message:String(q instanceof Error?q.message:q)}}),n.end();return}F===0&&I.length===0&&(te("text",{type:"text",text:""}),ee()),I.forEach(q=>{let me=F++;m("content_block_start",{index:me,content_block:{...q,input:{}}}),m("content_block_delta",{index:me,delta:{type:"input_json_delta",partial_json:JSON.stringify(q.input??{})}}),m("content_block_stop",{index:me})});let X=ve.size>0||I.length>0,Pe=jn(de);ct(o,de),m("message_delta",{delta:{stop_reason:X?"tool_use":"end_turn"},usage:Pe?{input_tokens:Pe.input_tokens,output_tokens:Pe.output_tokens}:{output_tokens:j}}),m("message_stop",{}),n.end();return}let p="",w="",y=[],b=new Ye;for await(let O of r.track(_,d,o)){y.push(O),O.type==="response.output_text.delta"&&typeof O.delta=="string"&&(p+=O.delta),O.type==="response.reasoning_text.delta"&&typeof O.delta=="string"&&(w+=O.delta);let j=St(O);if(j&&b.add(j),O.type==="error"){let P=O.error,F=P?.type==="invalid_request_error";De(n,F?400:502,F?"invalid_request_error":"api_error",P?.message??JSON.stringify(O));return}if(n.destroyed)break}if(n.destroyed)return;let k=Ue(y);ct(o,k);let h;try{h=Zr(k),h.length===0&&b.size>0&&(h=Zr({output:b.items()}))}catch(O){De(n,502,"api_error",String(O instanceof Error?O.message:O));return}let A=at(c,h.length,p);if(A){De(n,502,"api_error",st(d,A));return}let R=[],v=w||ia(k);v&&R.push({type:"thinking",thinking:v}),(p||h.length===0)&&R.push({type:"text",text:p}),R.push(...h),we(n,200,{id:a,type:"message",role:"assistant",content:R,model:s,stop_reason:h.length>0?"tool_use":"end_turn",usage:jn(k)??{input_tokens:0,output_tokens:0}})}function oc(t){Ne(process.stdout,t)}function sa(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,i=typeof e=="function"?e:()=>e,s=t.requestLog??oc,a=t.observe,u=new ot;return(l,d)=>{let c=new URL(l.url??"/","http://localhost"),_=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),m=(k,h,A,R,v)=>_?De(d,k,R,h):fe(d,k,h,A,v),p=Tr(c.pathname),w=c.pathname.startsWith("/partners/"),y=p||w?{id:Bt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,sessionId:null,timing:null}:null;y&&(d.setHeader(rs,y.id),d.once("close",()=>{let k=as({turn:y,method:l.method??"",path:c.pathname,res:d});s(us(k)),a?.(k),fi({record:k,ledger:t.ledger??null,req:l})}));let b=()=>os(c.pathname,y);(async()=>{if(l.method==="GET"&&c.pathname==="/healthz"){we(d,200,{ok:!0});return}if(l.method==="GET"&&c.pathname==="/stats"){we(d,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(l.headers.authorization??"")!==`Bearer ${n}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let k=c.pathname===cn?"canonical":c.pathname===Ut?"huggingface":null;if(k){if(l.method!=="POST"){m(405,`${c.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let v=t.usage;if(!v){m(501,`${c.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let O=v.authorize(l),j;try{j=await na(l,wi)}catch(G){if(G instanceof Xt){m(413,G.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let P=G=>v.lookup(O,G),F;try{if(k==="canonical"){let G=_i(j),Y=await P(G);pn(Y,G),F={requests:Y}}else F=await Si(j,P)}catch(G){if(G instanceof ze){m(G.status,G.message,"invalid_request_error","invalid_request_error");return}throw G}we(d,200,F);return}if(l.method==="GET"&&c.pathname===Ze){let v=await i(l);if(y&&(y.org=v.tenant??null),!v.openRouterModels){m(501,`GET ${Ze} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}we(d,200,await v.openRouterModels());return}if(c.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${l.method} ${c.pathname} \u2014 the partner surface currently carries ${Ut} and GET ${Ze}`,"invalid_request_error","not_found_error");return}let h=await i(l);if(y&&(y.org=h.tenant??null),l.method==="GET"&&c.pathname==="/v1/models"){if(c.searchParams.get("format")==="openrouter"){d.writeHead(308,{location:Ze}),d.end();return}we(d,200,await h.listModels());return}if(l.method==="GET"&&c.pathname===ks){if(!h.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}we(d,200,await h.listImageModels());return}if(Ss(c.pathname)){if(!h.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${c.pathname}`,"not_implemented","not_implemented_error");return}let v={clients:h,imageModels:h.supportsImages,stats:u,turn:b()};c.pathname===Ln?await Ms(l,d,v):await Cs(l,d,v);return}if(l.method==="GET"&&c.pathname===Ks){if(!h.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}we(d,200,await h.listSpeechToTextModels());return}if(Js(c.pathname)){if(!h.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Dn}`,"not_implemented","not_implemented_error");return}let v={clients:h,transcriptionModels:h.supportsTranscription,stats:u,turn:b()};await Xs(l,d,v);return}if(qs(c.pathname)){if(!h.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${zt}`,"not_implemented","not_implemented_error");return}let v={clients:h,speechModels:h.supportsSpeech,stats:u,turn:b()};await Ws(l,d,v);return}if(l.method!=="POST"){m(404,`no route for ${l.method} ${c.pathname}`,"invalid_request_error","not_found_error");return}let A;try{A=await na(l)}catch(v){if(v instanceof Xt){m(413,v.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let R=Buffer.byteLength(JSON.stringify(A));if(c.pathname==="/v1/responses"){u.request("responses",R,R),await zd(A,h,qt(h),d,u,b());return}if(c.pathname==="/v1/chat/completions"){u.request("chat_completions",R,R),await Yd(A,h,d,u,b(),l.headers[Xr]);return}if(c.pathname==="/v1/systemone"){u.request("systemone",R,R),await Xd(A,h,d,u,b());return}if(c.pathname==="/v1/messages"){u.request("messages",R,R),await rc(A,h,d,u,b());return}if(c.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",R,R),De(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}m(404,`no route for POST ${c.pathname}`,"invalid_request_error","not_found_error")})().catch(k=>{let h=String(k instanceof Error?k.message:k);if(!d.headersSent){let R=o?.(k)??null;if(R){m(R.status,h,R.openaiType,R.anthropicType);return}if(k instanceof Gn.SessionAllocationError){let v=Rn(k.code);if(v){let O=k.retryAfterSeconds??(v.status===429?30:void 0);O!==void 0&&d.setHeader("Retry-After",String(O)),m(v.status,Dr(v,k.code??void 0),v.openaiType,v.anthropicType,v.code);return}}if(k instanceof Gn.SessionFailedError){let v=xn(k);if(v){let O=v.status===429?30:void 0;O!==void 0&&d.setHeader("Retry-After",String(O)),m(v.status,Dr(v,k.status.sessionId?`session ${k.status.sessionId}`:void 0),v.openaiType,v.anthropicType,v.code);return}}if(k instanceof oe){m(502,h,"upstream_error","api_error");return}if(k instanceof Ve){k.retryable&&d.setHeader("Retry-After","1"),m(502,h,"upstream_error","api_error",k.code);return}if(k instanceof Et){d.setHeader("Retry-After",String(k.retryAfterSeconds)),m(k.status,h,k.status===429?"capacity_error":"upstream_error",k.status===429?"rate_limit_error":"overloaded_error",k.code);return}m(500,h,"proxy_error","api_error","proxy_error");return}y&&(y.streamError=!0);let A=k instanceof Ve?k.code:null;d.destroyed||(_?d.write(`event: error
61
61
  data: ${JSON.stringify({type:"error",error:{type:"api_error",message:h}})}
62
62
 
63
63
  `):d.write(`data: ${JSON.stringify({error:{message:h,type:"upstream_error",code:A}})}
64
64
 
65
- `)),d.end()})}}var Fe=(t,e)=>Object.assign(new Error(e),{status:t});function aa(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ua(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var ic='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function la(t,e,n,r){if(!t.supportsAudio)throw Fe(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(l){throw l instanceof z?Fe(404,l.message):l}if(!o)throw Fe(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw Fe(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(l){throw l instanceof z?Fe(404,l.message):l}if(i&&!t.openTurnsOn)throw Fe(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let l;try{l=await t.transcriptStreamFor(e)}catch(d){throw d instanceof z?Fe(404,d.message):d}if(l!=="stt")throw Fe(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(l)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw Fe(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ic}`);if(r==="transcription"&&!i)throw Fe(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let s=await t.sessionHandle(e),a={audio:await t.openAudioOn(s,n)},u={clients:{createResponse:async l=>await t.createResponseOn(s,l)},voice:o,audioSession:a};return i&&(u.turns=l=>t.openTurnsOn(s,l)),r==="transcription"&&(u.intent="transcription"),e!==void 0&&(u.model=e),u}x();var Wn=require("@urun-sh/core"),Ae=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},It=class extends Error{constructor(e){super(e),this.name="ControlPlaneUnavailableError"}};function Zt(t){let e=(t??"").trim();if(e==="")throw new Ae("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new Ae("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var sc=60,ac=6e4,uc=4096;function lc(t){return t===401||t===403}var Jn=class{constructor(e){this.opts=e;this.mint=e.mint??Wn.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new Ae("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<ac)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:sc})).orgId}catch(o){throw o instanceof Wn.ClientTokenError&&lc(o.status)?(this.cache.delete(e),new Ae("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new It(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new It("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=uc){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};x();var nr=require("crypto");x();var Ie=require("@urun-sh/core");x();x();x();x();function da(t,e,n,r){let o=t.response??{},i={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(i.instructions=o.instructions),Array.isArray(o.modalities)&&(i.modalities=o.modalities),typeof o.temperature=="number"&&(i.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(i.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(i.tools=o.tools),i}function ca(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}x();x();function pa(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var dc="llm-resp";async function*ro(t,e){let n=`${dc}:${e}`,r=`resp_${e}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;try{for await(let i of t.stream(n).messages()){let s=i;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let a of s.tool_calls){let u=typeof a.index=="number"?a.index:0,l=o.get(u)??{};a.id&&(l.id=a.id),a.function?.name&&(l.name=a.function.name),o.set(u,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:l.id,name:l.name,delta:a.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...s.body}};return}else if(s.t==="error"){yield pa(s);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var zn=class t{constructor(e,n=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((o,i)=>{let s=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{s(),i(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(e){e.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=ca(e,n,this.consumerId);return this.write(r),ro(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=da(e,n,r,this.consumerId);return this.write(o),ro(this.session,r)})}async writeGated(e,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var fa=0;function cc(){return fa+=1,`req_${Date.now().toString(36)}_${fa.toString(36)}`}var Yn=class{transport;constructor(e){this.transport=new zn(e)}responses={create:async e=>{let n=cc(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};x();async function ma(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}x();var ha=require("@urun-sh/core"),oo=2;function pc(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function fc(t){let e=t?.type;return e==="response.completed"||e==="error"}function ga(t){return async function(n,r){return(async function*(){for(let i=1;i<=oo;i++){let{app:s,entry:a,identity:u}=await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:u});let l=!1,d=!1;try{let c=await t.createStream(a,n);for await(let _ of c){if(fc(_)&&(l=!0),pc(_)){if(i>1)continue}else d=!0;yield _}}catch(c){if(c instanceof ha.SessionFailedError&&(c.kind==="never-live"||c.kind==="create-failed")){try{t.onAdmissionVerdict?.(s,a,c)}catch{}throw c}if(i<oo&&!d){await t.evict(s,a);continue}throw c}if(l)return;if(i<oo&&!d){await t.evict(s,a);continue}return}})()}}var va=require("crypto");x();var mc=3,hc="llm",gc=new Set(["paused","error"]);function ya(t,e){let n=t.doc(hc),r=typeof n.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let i=null,s=!1,a=new Set,u=[],l=d=>{if(!i){i=d;for(let c of[...a])c(d);a.clear()}};return r&&u.push(n.onConnectionState(d=>{s&&(d.consecutiveFailures<mc||l(new re(`the pooled session for app "${e}" is gone: its doc backhaul failed ${d.consecutiveFailures} consecutive times (last close ${d.lastCloseCode===null?"by provider liveness reap":`code ${d.lastCloseCode}`}${d.lastCloseReason?`, reason ${JSON.stringify(d.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),o&&u.push(t.onPhase(d=>{if(d.name==="live"){s=!0;return}s&&gc.has(d.name)&&l(new re(`the pooled session for app "${e}" lost its compute binding (phase "${d.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>i,onGone(d){return i?(d(i),()=>{}):(a.add(d),()=>a.delete(d))},dispose(){a.clear();for(let d of u.splice(0))d()}}}async function*io(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,i=new Promise((s,a)=>{o=e.onGone(u=>a(u))});i.catch(()=>{});try{for(;;){let s=await Promise.race([r.next(),i]);if(s.done)return;yield s.value}}finally{o?.(),r.return?.(void 0)}}var wc=1,_c=4,vc=4;function ba(t,e){let n=(s,a)=>{let u=(t[s]??"").trim();if(!u)return a;let l=Number.parseInt(u,10);if(!Number.isInteger(l)||l<1)throw new Error(`${s} must be a positive integer (got ${JSON.stringify(t[s])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):wc;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let i=n("URUN_DECISION_POOL_MAX",Math.max(o,_c));return{min:o,max:i,idleGraceMs:3e5,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",vc),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function wa(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let i=r?o(void 0,r):o();if(typeof i.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return i}function Sa(t,e,n,r){let{baseUrl:o,orgId:i,auth:s}=t,a=e.fnName??t.fnName,u=t.sessionStartOptions?.(n),l=r||u||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...u,...r}:void 0,d=w=>({session:w,responses:new Yn(w),gone:ya(w,n)});if(s.lane==="jwt"){let w=(0,Ie.App)(e.appSlug,{baseUrl:o,orgId:i,jwt:s.jwt});return d(wa(w,e.appSlug,a,l))}let{apiKey:c,gatewayUrl:_}=s,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,va.randomUUID)(),p=(0,Ie.App)(e.appSlug,{baseUrl:o,orgId:i,getAccessToken:async()=>(await(0,Ie.createClientToken)(c,{baseUrl:_,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(wa(p,e.appSlug,a,l))}function bc(t){let e=t.session.id;if(typeof e!="string"||e.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return e}function Sc(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var kc=new Set(["error","paused"]);function so(t){let{auth:e,catalog:n}=t,r=null,o=(s,a)=>{let u=Sa(t,s,a);return t.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&t.onSessionOpen(a,u.session.id),u.gone.onGone(()=>{r?.evict(a,u)}),u},i=new sn({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async s=>{if(s.gone.dispose(),t.release==="detach"){if(typeof s.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');s.session.detach();return}await s.session.end()},listApps:e.lane==="api-key"?()=>zo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>ma(n):null,listPrices:n?()=>Po(n):null,shared:e.lane==="api-key"?()=>Eo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:bc});return r=i,t.defaultApp!==null&&i.seed(t.defaultApp,o({appSlug:t.defaultApp},Ke({appSlug:t.defaultApp}))),i}function ka(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,i=new Map,s=u=>{process.stderr.write(`[decision-pool] ${u}
66
- `)},a=(u,l)=>{let d=o.get(l);if(d)return d;let c=new Pn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async _=>{let m=Sa(t,u,l,{concurrencyKey:_.concurrencyKey});return m.gone.onGone(()=>c.evict(m)),await Qn(m.session),s(`slot attached pool=${l} slot=${_.concurrencyKey} session=${m.session.id??"(no id)"}`),m},closeSlot:async _=>{_.gone.dispose(),await _.session.end()},onDetach:(_,m)=>s(`slot detached pool=${l} slot=${_.concurrencyKey} reason=${m}`)});return o.set(l,c),c};return{async boot(){if(t.defaultApp===null)return;let u={appSlug:t.defaultApp};await a(u,Ke(u)).boot()},async sessionFor(u){let l=await e.resolveTargetFor(u),d=Ke(l),c=a(l,d).tryAcquireReady();if(!c)throw new ut;let _=i.get(c.entry)??[];return _.push(c),i.set(c.entry,_),{app:d,entry:c.entry,identity:on(l)}},async warmFor(u){let l=await e.resolveTargetFor(u);await a(l,Ke(l)).boot()},end(u){let l=i.get(u)?.shift();l&&(i.get(u)?.length===0&&i.delete(u),l.release())},evict(u){for(let l of o.values())l.evict(u)},reap(){for(let u of o.values())u.reap()},async pingReady(u){for(let l of o.values())if(await l.pingReady(u))return!0;return!1},stats(){return[...o.entries()].map(([u,l])=>({poolKey:u,...l.stats()}))},async drain(u){await Promise.all([...o.values()].map(l=>l.drain({timeoutMs:u})))},async close(){await Promise.all([...o.values()].map(u=>u.close()))}}}function Rc(t){return(0,Ie.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?Ie.DEFAULT_WHEN_LIVE_TIMEOUT_MS:Ie.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:Ie.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Qn(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,{timeout:Rc(t.phase),signal:e})}async function _a(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}function Xn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function ao(t,e=Li,n,r,o=zr){let i=new WeakMap,s=new WeakMap,a=new WeakMap,u=new WeakMap,l=new WeakMap,d=p=>{let w=p.session.id;return typeof w=="string"&&w.length>0?w:null},c=p=>{let w=i.get(p);if(!w){let y={waiting:0,gone:new AbortController};l.set(p,y),w=(async()=>{if(await Qn(p.session,y.gone.signal),y.gone.signal.aborted)throw Xn(y.gone.signal);l.get(p)===y&&l.delete(p);let v=await Ci(p.session,await e());return Object.assign(v,{sessionId:p.session.id})})(),i.set(p,w),w.catch(()=>{i.get(p)===w&&i.delete(p)}),w.then(()=>{l.get(p)===y&&l.delete(p)},()=>{l.get(p)===y&&l.delete(p)})}return w},_=p=>{let w=u.get(p);return w||(w=(async()=>{let y=await c(p);return{appendInputAudio:v=>y.appendInputAudio(v),onOutputAudio:v=>y.onOutputAudio(v),sessionId:d(p)}})(),u.set(p,w),w.catch(()=>{u.get(p)===w&&u.delete(p)})),w},m=async(p,w,y)=>{if(y?.aborted){let h=l.get(p);throw(i.get(p)===void 0||h!==void 0&&h.waiting===0)&&await _a(p.session),Xn(y)}let v=w(p),k=l.get(p);return k!==void 0&&k.waiting++,y===void 0?v:new Promise((h,A)=>{let R=()=>{k!==void 0&&--k.waiting===0&&l.get(p)===k&&(k.gone.abort(),l.delete(p),i.delete(p),u.delete(p),_a(p.session).catch(()=>{})),A(Xn(y))};y.addEventListener("abort",R,{once:!0});let S=()=>y.removeEventListener("abort",R);v.then(O=>{S(),h(O)},O=>{S(),A(O)})})};return{createResponse:ga({sessionFor:r?p=>r.sessionFor(p):p=>t.sessionFor(p),sessionIdOf:p=>d(p),evict:(p,w)=>{r?r.evict(w):t.evict(p,w)},onAdmissionVerdict:(p,w,y)=>{Sc(y)&&(r?r.evict(w):t.evict(p,w),n?.(p,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(p,w)=>{try{await Qn(p.session);let y=Qs(io(await p.responses.responses.create(w),p.gone),o);if(!r)return y;let v=p;return(async function*(){try{yield*y}catch(h){throw Zs(h)&&r.evict(v),h}finally{r.end(v)}})()}catch(y){throw r&&r.end(p),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(p,w)=>t.supportsImages(p,w),listImageModels:()=>t.imageModelList(),catalogIdentity:p=>t.catalogIdentityFor(p),servingAppSlug:async p=>await t.servingAppSlugFor(p),supportsAudio:p=>t.supportsAudio(p),supportsSpeech:p=>t.supportsSpeech(p),speechVoices:p=>t.speechVoices(p),supportsTranscription:p=>t.supportsTranscription(p),transcriptStreamFor:p=>t.transcriptStreamFor(p),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(p,w)=>{let{entry:y}=await t.sessionFor(p);return await m(y,c,w)},openAudioOn:async(p,w)=>{let{entry:y}=await t.sessionForHandle(p);return await m(y,_,w)},openTurnsOn:async function*(p,w){if(w?.aborted)throw Xn(w);let{entry:y}=await t.sessionForHandle(p);yield*Go(y.session,w)},openVideo:async p=>{let{entry:w}=await t.sessionFor(p),y=s.get(w);return y||(y=Mi(w.session),s.set(w,y)),y},openVideoOut:async p=>{let{entry:w}=await t.sessionFor(p),y=a.get(w);return y||(y=Ni(w.session),a.set(w,y)),y},sessionHandle:async p=>(await t.handleFor(p)).handle,speechSessionHandle:async p=>(await t.speechHandleFor(p)).handle,evictSpeechSession:async p=>{let{app:w,entry:y}=await t.sessionForHandle(p);await t.evict(w,y)},createResponseOn:async(p,w)=>{let{entry:y}=await t.sessionForHandle(p);return await Qn(y.session),io(await y.responses.responses.create(w),y.gone)},onSessionEnd:async(p,w)=>{let{entry:y}=await t.sessionForHandle(p),v=y.session;if(typeof v.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let k=!1;return v.onPhase(h=>{if(k||!kc.has(h.name))return;k=!0;let A=v.endsAt??null;w({timeLeftMs:A?Math.max(0,A.getTime()-Date.now()):null,reason:h.reason??`session ${h.name}`})})}}}var xc=512;function uo(t){return`urun-inference-proxy-${(0,nr.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Zn=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){return Object.assign(Object.create(e),{tenant:n.orgId})}build(e){if(this.opts.build){let i=this.opts.build(e);return i.decision&&this.ensureDecisionReaper(),{router:i.router,clients:this.label(i.clients,e),decision:i.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Rr,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,release:"end",decisionPool:ba(process.env,process.env.HOSTNAME)??void 0},r=so(n),o=n.decisionPool?ka(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(ao(r,void 0,void 0,o??void 0),e),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=xc;){let o=this.tenants.entries().next();if(o.done)break;let[i,s]=o.value;this.tenants.delete(i),s.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(i=>{n.push(String(i instanceof Error?i.message:i))})];r.decision&&o.push(r.decision.close().catch(i=>{n.push(String(i instanceof Error?i.message:i))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Ra=512,Ec=1024,er=class extends Error{constructor(){super(`conversation capacity reached (${Ra} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Oc(t){return{sessionStartOptions:e=>{if(e.startsWith(Lt))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(Lt)||t.set(e,n)}}}function Ac(t,e,n,r){let o=so({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Rr,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalog,subject:n.subject,release:"detach",...Oc(r)});return{clients:ao(o),release:async()=>{await o.closeAll()}}}var tr=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${uo(e.apiKey)}:live:${n}`},o=new Map,i=this.opts.build?this.opts.build(e,r):Ac(this.opts,e,r,o);return{id:n,backhaul:i,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let i=this.build(e,n);return i.attachments=1,r.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Ra;){let e=this.byCaller.keys().next();if(e.done)throw new er;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[i,s]of r)if(!(s.attachments>0)){r.delete(i),this.dropHandleIndexFor(n,i),s.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new er;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,(0,nr.randomUUID)())),n),i={createResponse:(s,a)=>o().backhaul.clients.createResponse(s,a),catalogIdentity:s=>o().backhaul.clients.catalogIdentity(s),servingAppSlug:s=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(s)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:s=>o().backhaul.clients.sessionHandle(s),createResponseOn:(s,a)=>o().backhaul.clients.createResponseOn(s,a),onSessionEnd:(s,a)=>o().backhaul.clients.onSessionEnd(s,a)};return i.openAudio=async(s,a)=>{let u=o().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(s,a)},i.openVideo=async s=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(s)},i.openVideoOut=async s=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(s)},i.supportsAudio=async s=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(s)},i.supportsSpeech=async s=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(s)},i.speechVoices=async s=>{let a=o().backhaul.clients.speechVoices;if(a===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return a(s)},i.speechSessionHandle=async s=>{let a=o().backhaul.clients.speechSessionHandle;if(a===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return a(s)},i.openAudioOn=async(s,a)=>{let u=o().backhaul.clients.openAudioOn;if(u===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return u(s,a)},i.openTurnsOn=(s,a)=>{let u=o().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(s,a)},i.evictSpeechSession=async s=>{let a=o().backhaul.clients.evictSpeechSession;if(a===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return a(s)},i.supportsTranscription=async s=>{let a=o().backhaul.clients.supportsTranscription;if(a===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return a(s)},i.transcriptStreamFor=async s=>{let a=o().backhaul.clients.transcriptStreamFor;if(a===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return a(s)},i.listSpeechToTextModels=async()=>{let s=o().backhaul.clients.listSpeechToTextModels;if(s===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return s()},{clients:i,bindResumeHandle:s=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Ec;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(s,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async s=>{let a=this.byHandle.get(s),u=a===void 0?void 0:this.byCaller.get(a.apiKey),l=a===void 0||u===void 0?void 0:u.get(a.conversationId);if(a===void 0||l===void 0||a.apiKey!==e.apiKey)throw new re("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=l,l.attachments+=1,l.backhaul.clients},release:async()=>{if(r)return;r=!0;let s=n;n=null,s!==null&&(s.attachments-=1,!(s.attachments>0)&&await s.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};x();var rr="/inference-usage",xa=25e3;var Ic=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Ea(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Ic.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var or=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${rr}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(xa)})}catch(s){throw new oe(`the uRun usage surface (POST ${rr}) could not be reached within ${xa}ms: ${Ea(s)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new Ae("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let s=await o.text().catch(()=>null),a=s===null?"body unreadable":`${s.length}-character body`;throw new oe(`the uRun usage surface (POST ${rr}) answered HTTP ${o.status} (${a})`)}let i;try{i=await o.json()}catch(s){throw new oe(`the uRun usage surface (POST ${rr}) answered HTTP ${o.status} with a body that is not JSON: ${Ea(s)}`)}return bi(i,this.opts.onRejectedRow)}};x();var Tc="/inference-ledger",Pc=1e4,ir=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},po=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},_e=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},fo=class extends Ae{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Cc=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",lo],["output_minutes",lo],["cost_nano_usd",lo],["price_version",t=>t===null||typeof t=="string"]];function Mc(t){for(let[e,n]of Cc){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Lc(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:Mc(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function lo(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function co(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function $c(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Oa(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Nc(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&Oa(t.started_at,n.started_at)&&Oa(t.completed_at,n.completed_at)&&co(t.prompt_tokens,n.prompt_tokens)&&co(t.completion_tokens,n.completion_tokens)&&co(t.output_units,n.output_units)&&$c(t.output_minutes,n.output_minutes)}function Uc(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new _e(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new _e(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new _e(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new _e(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let i=l=>{if(!(l in n))throw new _e(`${e} answered a row with no ${l} field: ${JSON.stringify(t)}`);let d=n[l];if(d===null)return null;if(typeof d!="string")throw new _e(`${e} answered a non-string ${l}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new _e(`${e} answered a BLANK ${l} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},s=i("price_version"),a=i("unpriced_reason"),u=o!=null;if(u&&(s===null||a!==null))throw new _e(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(s!==null||a===null))throw new _e(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:s,unpriced_reason:a}}var sr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Tc}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(n),signal:AbortSignal.timeout(Pc)})}catch(u){throw new _e(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(o.status===409){let u=await o.text().catch(()=>""),l=Lc(u);throw l.status==="found"&&Nc(n,l.row)?new po(l.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):l.status==="not_in_this_org"?new ir(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new ir(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${l.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${u.slice(0,400)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new fo("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!o.ok){let u=await o.text().catch(l=>`<body unreadable: ${l instanceof Error?l.message:String(l)}>`);throw new _e(`the uRun ledger surface at ${r} answered HTTP ${o.status}: ${u.slice(0,400)}`)}let i;try{i=await o.json()}catch(u){throw new _e(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let s=i?.recorded;if(s===void 0)throw new _e(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let a=Uc(s,`the uRun ledger surface at ${r}`);if(a.inference_id!==n.inference_id)throw new _e(`the uRun ledger surface at ${r} answered for inference_id ${a.inference_id} when asked about ${n.inference_id}`);return a}};var Dc=5e3,Fc=1e3,Bc=1500,jc=3e3,qc="/api/client-tokens";function mo(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Aa(t,e,n,r){mo(t,e,{error:{message:n,type:r}})}async function Hc(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${qc}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(jc)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function Ta(t){let e=t.resolver??new Jn({gatewayUrl:t.baseUrl}),n=t.registry??new Zn({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),r=t.probeControlPlane??(()=>Hc(t.baseUrl)),o=async()=>{let h=null;for(let R of n.decisionPools()){h=R;break}if(!h)return null;let A=await h.pingReady(Bc);return{ok:A,detail:A?"a decision slot answered its session ping":"no decision slot answered its session ping"}},i=t.usageClient??new or({apiUrl:t.apiUrl}),s=t.ledgerClient??new sr({apiUrl:t.apiUrl}),a=process.env.URUN_SHARED_ORG_ID?.trim(),u=process.env.URUN_SHARED_ORG_API_KEY?.trim();a&&u&&(async()=>{try{await n.decisionWarmerFor({orgId:a,apiKey:u})?.warmFor(no)}catch(h){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(h instanceof Error?h.message:h)}
67
- `)}})();let l=new gn(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),d=async h=>e.resolve(Zt(h.headers.authorization)),c=h=>h instanceof Ae?{status:h.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:h instanceof It?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null,_=sa({clients:async h=>n.clientsFor(await d(h)),usage:{authorize:h=>Zt(h.headers.authorization),lookup:(h,A)=>i.lookup(h,A)},statusOf:c,...t.requestLog?{requestLog:t.requestLog}:{},observe:h=>l.observe(h),ledger:{write:(h,A)=>s.write(Zt(h.headers.authorization),A),observe:h=>l.observeLedger(h),...t.ledgerLog?{report:t.ledgerLog}:{}}}),m=null,p=null,w=(0,Ia.createServer)((h,A)=>{let R=new URL(h.url??"/","http://localhost");(async()=>{if(h.method==="GET"&&R.pathname==="/healthz"){mo(A,200,{ok:!0});return}if(h.method==="GET"&&R.pathname==="/readyz"){let j=Date.now();if((!m||j-m.at>=Dc)&&(m={at:j,...await r()}),!p||j-p.at>=Fc){let G=await o();p=G===null?{at:j,ok:!0,detail:null}:{at:j,ok:G.ok,detail:G.detail}}let P=(m?.ready??!1)&&p.ok,F=p.detail===null?m?.detail??"control plane not yet probed":`${m?.detail??"control plane not yet probed"}; ${p.detail}`;mo(A,P?200:503,{ok:P,control_plane:F});return}let S=R.pathname==="/v1"||R.pathname.startsWith("/v1/"),O=R.pathname.startsWith("/partners/");if(!S&&!O){Aa(A,404,`no route for ${h.method} ${R.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz and /readyz`,"invalid_request_error");return}_(h,A)})().catch(S=>{if(!A.headersSent){Aa(A,500,String(S instanceof Error?S.message:S),"proxy_error");return}A.end()})}),y=t.conversations??new tr({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),v=[Ir(w,{authenticate:async h=>{let A=await e.resolve(h),R=y.connectionFor(A);return{clients:R.clients,scope:uo(A.apiKey),onBindResumeHandle:R.bindResumeHandle,clientsForResume:R.clientsForResume,release:R.release}}}),Ur(w,{clients:async h=>n.clientsFor(await d(h)),statusOf:c}).close,Tn(w,{resolver:{resolve:async(h,A)=>{let R=await e.resolve(Zt(h.headers.authorization)),S=y.connectionFor(R),O;try{O=await la(S.clients,aa(h),A,ua(h))}catch(j){throw S.release().catch(()=>{}),j}return{...O,release:S.release}}}})];w.on("upgrade",(h,A)=>{let R=new URL(h.url??"/","http://localhost");R.pathname===bn||R.pathname===$r||R.pathname===Jt||A.destroyed||(A.write(`HTTP/1.1 404 Not Found\r
65
+ `)),d.end()})}}var Fe=(t,e)=>Object.assign(new Error(e),{status:t});function aa(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ua(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var ic='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function la(t,e,n,r){if(!t.supportsAudio)throw Fe(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(l){throw l instanceof z?Fe(404,l.message):l}if(!o)throw Fe(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw Fe(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(l){throw l instanceof z?Fe(404,l.message):l}if(i&&!t.openTurnsOn)throw Fe(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let l;try{l=await t.transcriptStreamFor(e)}catch(d){throw d instanceof z?Fe(404,d.message):d}if(l!=="stt")throw Fe(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(l)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw Fe(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ic}`);if(r==="transcription"&&!i)throw Fe(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let s=await t.sessionHandle(e),a={audio:await t.openAudioOn(s,n)},u={clients:{createResponse:async l=>await t.createResponseOn(s,l)},voice:o,audioSession:a};return i&&(u.turns=l=>t.openTurnsOn(s,l)),r==="transcription"&&(u.intent="transcription"),e!==void 0&&(u.model=e),u}x();var Jn=require("@urun-sh/core"),Ae=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},It=class extends Error{constructor(e){super(e),this.name="ControlPlaneUnavailableError"}};function Zt(t){let e=(t??"").trim();if(e==="")throw new Ae("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new Ae("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var sc=60,ac=6e4,uc=4096;function lc(t){return t===401||t===403}var Wn=class{constructor(e){this.opts=e;this.mint=e.mint??Jn.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new Ae("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<ac)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:sc})).orgId}catch(o){throw o instanceof Jn.ClientTokenError&&lc(o.status)?(this.cache.delete(e),new Ae("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new It(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new It("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=uc){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};x();var nr=require("crypto");x();var Ie=require("@urun-sh/core");x();x();x();x();function da(t,e,n,r){let o=t.response??{},i={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(i.instructions=o.instructions),Array.isArray(o.modalities)&&(i.modalities=o.modalities),typeof o.temperature=="number"&&(i.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(i.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(i.tools=o.tools),i}function ca(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}x();x();function pa(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var dc="llm-resp";async function*ro(t,e){let n=`${dc}:${e}`,r=`resp_${e}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;try{for await(let i of t.stream(n).messages()){let s=i;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let a of s.tool_calls){let u=typeof a.index=="number"?a.index:0,l=o.get(u)??{};a.id&&(l.id=a.id),a.function?.name&&(l.name=a.function.name),o.set(u,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:l.id,name:l.name,delta:a.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...s.body}};return}else if(s.t==="error"){yield pa(s);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var zn=class t{constructor(e,n=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((o,i)=>{let s=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{s(),i(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}write(e){e.session_tag=this.sessionTag,this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=ca(e,n,this.consumerId);return this.write(r),ro(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=da(e,n,r,this.consumerId);return this.write(o),ro(this.session,r)})}async writeGated(e,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var fa=0;function cc(){return fa+=1,`req_${Date.now().toString(36)}_${fa.toString(36)}`}var Yn=class{transport;constructor(e){this.transport=new zn(e)}responses={create:async e=>{let n=cc(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};x();async function ma(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}x();var ha=require("@urun-sh/core"),oo=2;function pc(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function fc(t){let e=t?.type;return e==="response.completed"||e==="error"}function ga(t){return async function(n,r){return(async function*(){for(let i=1;i<=oo;i++){let{app:s,entry:a,identity:u}=await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:u});let l=!1,d=!1;try{let c=await t.createStream(a,n);for await(let _ of c){if(fc(_)&&(l=!0),pc(_)){if(i>1)continue}else d=!0;yield _}}catch(c){if(c instanceof ha.SessionFailedError&&(c.kind==="never-live"||c.kind==="create-failed")){try{t.onAdmissionVerdict?.(s,a,c)}catch{}throw c}if(i<oo&&!d){await t.evict(s,a);continue}throw c}if(l)return;if(i<oo&&!d){await t.evict(s,a);continue}return}})()}}var va=require("crypto");x();var mc=3,hc="llm",gc=new Set(["paused","error"]);function ya(t,e){let n=t.doc(hc),r=typeof n.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let i=null,s=!1,a=new Set,u=[],l=d=>{if(!i){i=d;for(let c of[...a])c(d);a.clear()}};return r&&u.push(n.onConnectionState(d=>{s&&(d.consecutiveFailures<mc||l(new re(`the pooled session for app "${e}" is gone: its doc backhaul failed ${d.consecutiveFailures} consecutive times (last close ${d.lastCloseCode===null?"by provider liveness reap":`code ${d.lastCloseCode}`}${d.lastCloseReason?`, reason ${JSON.stringify(d.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),o&&u.push(t.onPhase(d=>{if(d.name==="live"){s=!0;return}s&&gc.has(d.name)&&l(new re(`the pooled session for app "${e}" lost its compute binding (phase "${d.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>i,onGone(d){return i?(d(i),()=>{}):(a.add(d),()=>a.delete(d))},dispose(){a.clear();for(let d of u.splice(0))d()}}}async function*io(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,i=new Promise((s,a)=>{o=e.onGone(u=>a(u))});i.catch(()=>{});try{for(;;){let s=await Promise.race([r.next(),i]);if(s.done)return;yield s.value}}finally{o?.(),r.return?.(void 0)}}var wc=1,_c=4,vc=4;function ba(t,e){let n=(s,a)=>{let u=(t[s]??"").trim();if(!u)return a;let l=Number.parseInt(u,10);if(!Number.isInteger(l)||l<1)throw new Error(`${s} must be a positive integer (got ${JSON.stringify(t[s])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):wc;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let i=n("URUN_DECISION_POOL_MAX",Math.max(o,_c));return{min:o,max:i,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",vc),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function wa(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let i=r?o(void 0,r):o();if(typeof i.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return i}function Sa(t,e,n,r){let{baseUrl:o,orgId:i,auth:s}=t,a=e.fnName??t.fnName,u=t.sessionStartOptions?.(n),l=r||u||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...u,...r}:void 0,d=w=>({session:w,responses:new Yn(w),gone:ya(w,n)});if(s.lane==="jwt"){let w=(0,Ie.App)(e.appSlug,{baseUrl:o,orgId:i,jwt:s.jwt});return d(wa(w,e.appSlug,a,l))}let{apiKey:c,gatewayUrl:_}=s,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,va.randomUUID)(),p=(0,Ie.App)(e.appSlug,{baseUrl:o,orgId:i,getAccessToken:async()=>(await(0,Ie.createClientToken)(c,{baseUrl:_,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(wa(p,e.appSlug,a,l))}function bc(t){let e=t.session.id;if(typeof e!="string"||e.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return e}function Sc(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var kc=new Set(["error","paused"]);function so(t){let{auth:e,catalog:n}=t,r=null,o=(s,a)=>{let u=Sa(t,s,a);return t.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&t.onSessionOpen(a,u.session.id),u.gone.onGone(()=>{r?.evict(a,u)}),u},i=new sn({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async s=>{if(s.gone.dispose(),t.release==="detach"){if(typeof s.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');s.session.detach();return}await s.session.end()},listApps:e.lane==="api-key"?()=>zo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>ma(n):null,listPrices:n?()=>Po(n):null,shared:e.lane==="api-key"?()=>Eo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:bc});return r=i,t.defaultApp!==null&&i.seed(t.defaultApp,o({appSlug:t.defaultApp},Ke({appSlug:t.defaultApp}))),i}function ka(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,i=new Map,s=u=>{process.stderr.write(`[decision-pool] ${u}
66
+ `)},a=(u,l)=>{let d=o.get(l);if(d)return d;let c=new Pn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async _=>{let m=Sa(t,u,l,{concurrencyKey:_.concurrencyKey});return m.gone.onGone(()=>c.evict(m)),await Qn(m.session),s(`slot attached pool=${l} slot=${_.concurrencyKey} session=${m.session.id??"(no id)"}`),m},closeSlot:async _=>{_.gone.dispose(),await _.session.end()},onDetach:(_,m)=>s(`slot detached pool=${l} slot=${_.concurrencyKey} reason=${m}`)});return o.set(l,c),c};return{async boot(){if(t.defaultApp===null)return;let u={appSlug:t.defaultApp};await a(u,Ke(u)).boot()},async sessionFor(u){let l=await e.resolveTargetFor(u),d=Ke(l),c=a(l,d).tryAcquireReady();if(!c)throw new ut(a(l,d).stats().lastMissAgeMs);let _=i.get(c.entry)??[];return _.push(c),i.set(c.entry,_),{app:d,entry:c.entry,identity:on(l)}},async warmFor(u){let l=await e.resolveTargetFor(u);await a(l,Ke(l)).boot()},end(u){let l=i.get(u)?.shift();l&&(i.get(u)?.length===0&&i.delete(u),l.release())},evict(u){for(let l of o.values())l.evict(u)},reap(){for(let u of o.values())u.reap()},async pingReady(u){for(let l of o.values())if(await l.pingReady(u))return!0;return!1},stats(){return[...o.entries()].map(([u,l])=>({poolKey:u,...l.stats()}))},async drain(u){await Promise.all([...o.values()].map(l=>l.drain({timeoutMs:u})))},async close(){await Promise.all([...o.values()].map(u=>u.close()))}}}function Rc(t){return(0,Ie.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?Ie.DEFAULT_WHEN_LIVE_TIMEOUT_MS:Ie.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:Ie.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Qn(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,{timeout:Rc(t.phase),signal:e})}async function _a(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}function Xn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function ao(t,e=Li,n,r,o=zr){let i=new WeakMap,s=new WeakMap,a=new WeakMap,u=new WeakMap,l=new WeakMap,d=p=>{let w=p.session.id;return typeof w=="string"&&w.length>0?w:null},c=p=>{let w=i.get(p);if(!w){let y={waiting:0,gone:new AbortController};l.set(p,y),w=(async()=>{if(await Qn(p.session,y.gone.signal),y.gone.signal.aborted)throw Xn(y.gone.signal);l.get(p)===y&&l.delete(p);let b=await Ci(p.session,await e());return Object.assign(b,{sessionId:p.session.id})})(),i.set(p,w),w.catch(()=>{i.get(p)===w&&i.delete(p)}),w.then(()=>{l.get(p)===y&&l.delete(p)},()=>{l.get(p)===y&&l.delete(p)})}return w},_=p=>{let w=u.get(p);return w||(w=(async()=>{let y=await c(p);return{appendInputAudio:b=>y.appendInputAudio(b),onOutputAudio:b=>y.onOutputAudio(b),sessionId:d(p)}})(),u.set(p,w),w.catch(()=>{u.get(p)===w&&u.delete(p)})),w},m=async(p,w,y)=>{if(y?.aborted){let h=l.get(p);throw(i.get(p)===void 0||h!==void 0&&h.waiting===0)&&await _a(p.session),Xn(y)}let b=w(p),k=l.get(p);return k!==void 0&&k.waiting++,y===void 0?b:new Promise((h,A)=>{let R=()=>{k!==void 0&&--k.waiting===0&&l.get(p)===k&&(k.gone.abort(),l.delete(p),i.delete(p),u.delete(p),_a(p.session).catch(()=>{})),A(Xn(y))};y.addEventListener("abort",R,{once:!0});let v=()=>y.removeEventListener("abort",R);b.then(O=>{v(),h(O)},O=>{v(),A(O)})})};return{createResponse:ga({sessionFor:r?p=>r.sessionFor(p):p=>t.sessionFor(p),sessionIdOf:p=>d(p),evict:(p,w)=>{r?r.evict(w):t.evict(p,w)},onAdmissionVerdict:(p,w,y)=>{Sc(y)&&(r?r.evict(w):t.evict(p,w),n?.(p,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(p,w)=>{try{await Qn(p.session);let y=Qs(io(await p.responses.responses.create(w),p.gone),o);if(!r)return y;let b=p;return(async function*(){try{yield*y}catch(h){throw Zs(h)&&r.evict(b),h}finally{r.end(b)}})()}catch(y){throw r&&r.end(p),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(p,w)=>t.supportsImages(p,w),listImageModels:()=>t.imageModelList(),catalogIdentity:p=>t.catalogIdentityFor(p),servingAppSlug:async p=>await t.servingAppSlugFor(p),supportsAudio:p=>t.supportsAudio(p),supportsSpeech:p=>t.supportsSpeech(p),speechVoices:p=>t.speechVoices(p),supportsTranscription:p=>t.supportsTranscription(p),transcriptStreamFor:p=>t.transcriptStreamFor(p),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(p,w)=>{let{entry:y}=await t.sessionFor(p);return await m(y,c,w)},openAudioOn:async(p,w)=>{let{entry:y}=await t.sessionForHandle(p);return await m(y,_,w)},openTurnsOn:async function*(p,w){if(w?.aborted)throw Xn(w);let{entry:y}=await t.sessionForHandle(p);yield*Go(y.session,w)},openVideo:async p=>{let{entry:w}=await t.sessionFor(p),y=s.get(w);return y||(y=Mi(w.session),s.set(w,y)),y},openVideoOut:async p=>{let{entry:w}=await t.sessionFor(p),y=a.get(w);return y||(y=Ni(w.session),a.set(w,y)),y},sessionHandle:async p=>(await t.handleFor(p)).handle,speechSessionHandle:async p=>(await t.speechHandleFor(p)).handle,evictSpeechSession:async p=>{let{app:w,entry:y}=await t.sessionForHandle(p);await t.evict(w,y)},createResponseOn:async(p,w)=>{let{entry:y}=await t.sessionForHandle(p);return await Qn(y.session),io(await y.responses.responses.create(w),y.gone)},onSessionEnd:async(p,w)=>{let{entry:y}=await t.sessionForHandle(p),b=y.session;if(typeof b.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let k=!1;return b.onPhase(h=>{if(k||!kc.has(h.name))return;k=!0;let A=b.endsAt??null;w({timeLeftMs:A?Math.max(0,A.getTime()-Date.now()):null,reason:h.reason??`session ${h.name}`})})}}}var xc=512;function uo(t){return`urun-inference-proxy-${(0,nr.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Zn=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){return Object.assign(Object.create(e),{tenant:n.orgId})}build(e){if(this.opts.build){let i=this.opts.build(e);return i.decision&&this.ensureDecisionReaper(),{router:i.router,clients:this.label(i.clients,e),decision:i.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Rr,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,release:"end",decisionPool:ba(process.env,process.env.HOSTNAME)??void 0},r=so(n),o=n.decisionPool?ka(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(ao(r,void 0,void 0,o??void 0),e),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=xc;){let o=this.tenants.entries().next();if(o.done)break;let[i,s]=o.value;this.tenants.delete(i),s.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(i=>{n.push(String(i instanceof Error?i.message:i))})];r.decision&&o.push(r.decision.close().catch(i=>{n.push(String(i instanceof Error?i.message:i))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Ra=512,Ec=1024,er=class extends Error{constructor(){super(`conversation capacity reached (${Ra} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Oc(t){return{sessionStartOptions:e=>{if(e.startsWith(Lt))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(Lt)||t.set(e,n)}}}function Ac(t,e,n,r){let o=so({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Rr,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalog,subject:n.subject,release:"detach",...Oc(r)});return{clients:ao(o),release:async()=>{await o.closeAll()}}}var tr=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${uo(e.apiKey)}:live:${n}`},o=new Map,i=this.opts.build?this.opts.build(e,r):Ac(this.opts,e,r,o);return{id:n,backhaul:i,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let i=this.build(e,n);return i.attachments=1,r.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Ra;){let e=this.byCaller.keys().next();if(e.done)throw new er;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[i,s]of r)if(!(s.attachments>0)){r.delete(i),this.dropHandleIndexFor(n,i),s.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new er;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,(0,nr.randomUUID)())),n),i={createResponse:(s,a)=>o().backhaul.clients.createResponse(s,a),catalogIdentity:s=>o().backhaul.clients.catalogIdentity(s),servingAppSlug:s=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(s)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:s=>o().backhaul.clients.sessionHandle(s),createResponseOn:(s,a)=>o().backhaul.clients.createResponseOn(s,a),onSessionEnd:(s,a)=>o().backhaul.clients.onSessionEnd(s,a)};return i.openAudio=async(s,a)=>{let u=o().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(s,a)},i.openVideo=async s=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(s)},i.openVideoOut=async s=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(s)},i.supportsAudio=async s=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(s)},i.supportsSpeech=async s=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(s)},i.speechVoices=async s=>{let a=o().backhaul.clients.speechVoices;if(a===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return a(s)},i.speechSessionHandle=async s=>{let a=o().backhaul.clients.speechSessionHandle;if(a===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return a(s)},i.openAudioOn=async(s,a)=>{let u=o().backhaul.clients.openAudioOn;if(u===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return u(s,a)},i.openTurnsOn=(s,a)=>{let u=o().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(s,a)},i.evictSpeechSession=async s=>{let a=o().backhaul.clients.evictSpeechSession;if(a===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return a(s)},i.supportsTranscription=async s=>{let a=o().backhaul.clients.supportsTranscription;if(a===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return a(s)},i.transcriptStreamFor=async s=>{let a=o().backhaul.clients.transcriptStreamFor;if(a===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return a(s)},i.listSpeechToTextModels=async()=>{let s=o().backhaul.clients.listSpeechToTextModels;if(s===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return s()},{clients:i,bindResumeHandle:s=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Ec;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(s,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async s=>{let a=this.byHandle.get(s),u=a===void 0?void 0:this.byCaller.get(a.apiKey),l=a===void 0||u===void 0?void 0:u.get(a.conversationId);if(a===void 0||l===void 0||a.apiKey!==e.apiKey)throw new re("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=l,l.attachments+=1,l.backhaul.clients},release:async()=>{if(r)return;r=!0;let s=n;n=null,s!==null&&(s.attachments-=1,!(s.attachments>0)&&await s.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};x();var rr="/inference-usage",xa=25e3;var Ic=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Ea(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Ic.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var or=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${rr}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(xa)})}catch(s){throw new oe(`the uRun usage surface (POST ${rr}) could not be reached within ${xa}ms: ${Ea(s)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new Ae("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let s=await o.text().catch(()=>null),a=s===null?"body unreadable":`${s.length}-character body`;throw new oe(`the uRun usage surface (POST ${rr}) answered HTTP ${o.status} (${a})`)}let i;try{i=await o.json()}catch(s){throw new oe(`the uRun usage surface (POST ${rr}) answered HTTP ${o.status} with a body that is not JSON: ${Ea(s)}`)}return bi(i,this.opts.onRejectedRow)}};x();var Tc="/inference-ledger",Pc=1e4,ir=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},po=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},_e=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},fo=class extends Ae{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Cc=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",lo],["output_minutes",lo],["cost_nano_usd",lo],["price_version",t=>t===null||typeof t=="string"]];function Mc(t){for(let[e,n]of Cc){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Lc(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:Mc(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function lo(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function co(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function $c(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Oa(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Nc(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&Oa(t.started_at,n.started_at)&&Oa(t.completed_at,n.completed_at)&&co(t.prompt_tokens,n.prompt_tokens)&&co(t.completion_tokens,n.completion_tokens)&&co(t.output_units,n.output_units)&&$c(t.output_minutes,n.output_minutes)}function Uc(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new _e(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new _e(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new _e(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new _e(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let i=l=>{if(!(l in n))throw new _e(`${e} answered a row with no ${l} field: ${JSON.stringify(t)}`);let d=n[l];if(d===null)return null;if(typeof d!="string")throw new _e(`${e} answered a non-string ${l}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new _e(`${e} answered a BLANK ${l} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},s=i("price_version"),a=i("unpriced_reason"),u=o!=null;if(u&&(s===null||a!==null))throw new _e(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(s!==null||a===null))throw new _e(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:s,unpriced_reason:a}}var sr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Tc}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(n),signal:AbortSignal.timeout(Pc)})}catch(u){throw new _e(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(o.status===409){let u=await o.text().catch(()=>""),l=Lc(u);throw l.status==="found"&&Nc(n,l.row)?new po(l.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):l.status==="not_in_this_org"?new ir(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new ir(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${l.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${u.slice(0,400)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new fo("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!o.ok){let u=await o.text().catch(l=>`<body unreadable: ${l instanceof Error?l.message:String(l)}>`);throw new _e(`the uRun ledger surface at ${r} answered HTTP ${o.status}: ${u.slice(0,400)}`)}let i;try{i=await o.json()}catch(u){throw new _e(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let s=i?.recorded;if(s===void 0)throw new _e(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let a=Uc(s,`the uRun ledger surface at ${r}`);if(a.inference_id!==n.inference_id)throw new _e(`the uRun ledger surface at ${r} answered for inference_id ${a.inference_id} when asked about ${n.inference_id}`);return a}};var Dc=5e3,Fc=1e3,Bc=1500,jc=3e3,qc="/api/client-tokens";function mo(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Aa(t,e,n,r){mo(t,e,{error:{message:n,type:r}})}async function Hc(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${qc}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(jc)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function Ta(t){let e=t.resolver??new Wn({gatewayUrl:t.baseUrl}),n=t.registry??new Zn({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),r=t.probeControlPlane??(()=>Hc(t.baseUrl)),o=async()=>{let h=null;for(let v of n.decisionPools()){h=v;break}if(!h)return null;let A=h.stats();if(A.some(v=>v.draining))return{ok:!1,detail:"decision pool draining"};if(A.every(v=>v.attached===0&&v.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let R=await h.pingReady(Bc);return{ok:R,detail:R?"a decision slot answered its session ping":"no decision slot answered its session ping"}},i=t.usageClient??new or({apiUrl:t.apiUrl}),s=t.ledgerClient??new sr({apiUrl:t.apiUrl}),a=process.env.URUN_SHARED_ORG_ID?.trim(),u=process.env.URUN_SHARED_ORG_API_KEY?.trim();a&&u&&(async()=>{try{await n.decisionWarmerFor({orgId:a,apiKey:u})?.warmFor(no)}catch(h){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(h instanceof Error?h.message:h)}
67
+ `)}})();let l=new gn(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),d=async h=>e.resolve(Zt(h.headers.authorization)),c=h=>h instanceof Ae?{status:h.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:h instanceof It?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null,_=sa({clients:async h=>n.clientsFor(await d(h)),usage:{authorize:h=>Zt(h.headers.authorization),lookup:(h,A)=>i.lookup(h,A)},statusOf:c,...t.requestLog?{requestLog:t.requestLog}:{},observe:h=>l.observe(h),ledger:{write:(h,A)=>s.write(Zt(h.headers.authorization),A),observe:h=>l.observeLedger(h),...t.ledgerLog?{report:t.ledgerLog}:{}}}),m=null,p=null,w=(0,Ia.createServer)((h,A)=>{let R=new URL(h.url??"/","http://localhost");(async()=>{if(h.method==="GET"&&R.pathname==="/healthz"){mo(A,200,{ok:!0});return}if(h.method==="GET"&&R.pathname==="/readyz"){let j=Date.now();if((!m||j-m.at>=Dc)&&(m={at:j,...await r()}),!p||j-p.at>=Fc){let G=await o();p=G===null?{at:j,ok:!0,detail:null}:{at:j,ok:G.ok,detail:G.detail}}let P=(m?.ready??!1)&&p.ok,F=p.detail===null?m?.detail??"control plane not yet probed":`${m?.detail??"control plane not yet probed"}; ${p.detail}`;mo(A,P?200:503,{ok:P,control_plane:F});return}let v=R.pathname==="/v1"||R.pathname.startsWith("/v1/"),O=R.pathname.startsWith("/partners/");if(!v&&!O){Aa(A,404,`no route for ${h.method} ${R.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz and /readyz`,"invalid_request_error");return}_(h,A)})().catch(v=>{if(!A.headersSent){Aa(A,500,String(v instanceof Error?v.message:v),"proxy_error");return}A.end()})}),y=t.conversations??new tr({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),b=[Ir(w,{authenticate:async h=>{let A=await e.resolve(h),R=y.connectionFor(A);return{clients:R.clients,scope:uo(A.apiKey),onBindResumeHandle:R.bindResumeHandle,clientsForResume:R.clientsForResume,release:R.release}}}),Ur(w,{clients:async h=>n.clientsFor(await d(h)),statusOf:c}).close,Tn(w,{resolver:{resolve:async(h,A)=>{let R=await e.resolve(Zt(h.headers.authorization)),v=y.connectionFor(R),O;try{O=await la(v.clients,aa(h),A,ua(h))}catch(j){throw v.release().catch(()=>{}),j}return{...O,release:v.release}}}})];w.on("upgrade",(h,A)=>{let R=new URL(h.url??"/","http://localhost");R.pathname===bn||R.pathname===$r||R.pathname===Wt||A.destroyed||(A.write(`HTTP/1.1 404 Not Found\r
68
68
  Connection: close\r
69
69
  \r
70
- no WS route for ${R.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),A.destroy())});let k=async()=>{for(let h of v)await h();await y.detachAll()};return{server:w,metricsServer:Ri(l),metrics:l,edgeIdentityServer:Oi(),registry:n,closeAll:()=>n.closeAll(),closeWebSockets:k}}async function Pa(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await ui()||li(),await e()}function Gc(){let t=null;return t=Zo({streams:Me.default,note:e=>{t?.isDead("stderr")!==!0&&Ne(Me.default.stderr,e)}}),t}async function Vc(){Gc();let t=Ai(Me.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:i}=Ta(t);await new Promise((a,u)=>{e.once("error",u),e.listen(t.port,tt,a)}),await new Promise((a,u)=>{n.once("error",u),n.listen(br,tt,a)}),await new Promise((a,u)=>{r.once("error",u),r.listen(kr,tt,a)}),Me.default.stdout.write(`inference-proxy listening on http://${tt}:${t.port}/v1 (metrics http://${tt}:${br}${fn}, edge identity http://${tt}:${kr}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
70
+ no WS route for ${R.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),A.destroy())});let k=async()=>{for(let h of b)await h();await y.detachAll()};return{server:w,metricsServer:Ri(l),metrics:l,edgeIdentityServer:Oi(),registry:n,closeAll:()=>n.closeAll(),closeWebSockets:k}}async function Pa(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await ui()||li(),await e()}function Gc(){let t=null;return t=Zo({streams:Me.default,note:e=>{t?.isDead("stderr")!==!0&&Ne(Me.default.stderr,e)}}),t}async function Vc(){Gc();let t=Ai(Me.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:i}=Ta(t);await new Promise((a,u)=>{e.once("error",u),e.listen(t.port,tt,a)}),await new Promise((a,u)=>{n.once("error",u),n.listen(br,tt,a)}),await new Promise((a,u)=>{r.once("error",u),r.listen(kr,tt,a)}),Me.default.stdout.write(`inference-proxy listening on http://${tt}:${t.port}/v1 (metrics http://${tt}:${br}${fn}, edge identity http://${tt}:${kr}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
71
71
  `);let s=async a=>{Me.default.stdout.write(`inference-proxy: ${a} \u2014 draining
72
72
  `),await Pa(e,o,i),await new Promise(u=>n.close(()=>u())),await new Promise(u=>r.close(()=>u()))};await new Promise(a=>{Me.default.once("SIGINT",()=>{s("SIGINT").finally(a)}),Me.default.once("SIGTERM",()=>{s("SIGTERM").finally(a)})})}Vc().then(()=>Me.default.exit(0),t=>{Me.default.stderr.write(`inference-proxy: ${String(t instanceof Error?t.stack??t.message:t)}
73
73
  `),Me.default.exit(1)});