@urun-sh/openai 0.6.33 → 0.6.34

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.
Files changed (39) hide show
  1. package/dist/chunk-2L7UL6BM.js +17 -0
  2. package/dist/chunk-6K7NOPD5.js +6 -0
  3. package/dist/chunk-7KRHHEKZ.js +1 -0
  4. package/dist/{chunk-GR3UAW6P.js → chunk-AVMTHHBR.js} +1 -1
  5. package/dist/{chunk-NL3UBLXV.js → chunk-CY4RJOTS.js} +2 -2
  6. package/dist/chunk-ETX6IX25.js +1 -0
  7. package/dist/{chunk-GL7EWL3V.js → chunk-EV4DZCHN.js} +1 -1
  8. package/dist/{chunk-L6HTHDVV.js → chunk-GQTWIDJ6.js} +1 -1
  9. package/dist/chunk-LDBKLCCU.js +2 -0
  10. package/dist/{composite-CwfOOT0b.d.cts → composite-DGytPb8F.d.cts} +10 -8
  11. package/dist/gemini-live.cjs +2 -2
  12. package/dist/gemini-live.d.cts +0 -26
  13. package/dist/gemini-live.d.ts +0 -5
  14. package/dist/gemini-live.js +1 -1
  15. package/dist/hosted/bin.cjs +44 -44
  16. package/dist/hosted/bin.js +1 -1
  17. package/dist/hosted/index.cjs +38 -38
  18. package/dist/hosted/index.d.cts +44 -1
  19. package/dist/hosted/index.d.ts +9 -1
  20. package/dist/hosted/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/pi-extension/index.cjs +7 -7
  24. package/dist/pi-extension/index.js +1 -1
  25. package/dist/pi-extension/standalone.cjs +40 -40
  26. package/dist/pooler/bin.cjs +24 -24
  27. package/dist/pooler/bin.js +23 -23
  28. package/dist/proxy/cli.cjs +37 -37
  29. package/dist/proxy/cli.js +1 -1
  30. package/dist/proxy/index.cjs +13 -13
  31. package/dist/proxy/index.d.cts +2 -2
  32. package/dist/proxy/index.d.ts +2 -2
  33. package/dist/proxy/index.js +1 -1
  34. package/package.json +2 -2
  35. package/dist/chunk-7D2HMQFC.js +0 -2
  36. package/dist/chunk-NN6TQQUG.js +0 -1
  37. package/dist/chunk-OOCRI7ZM.js +0 -6
  38. package/dist/chunk-PBKCUSTI.js +0 -17
  39. /package/dist/{composite-D9VDruCV.d.ts → composite-D4oZXeX4.d.ts} +0 -0
@@ -1,91 +1,91 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var dl=Object.create;var ys=Object.defineProperty;var cl=Object.getOwnPropertyDescriptor;var pl=Object.getOwnPropertyNames;var fl=Object.getPrototypeOf,ml=Object.prototype.hasOwnProperty;var gl=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var hl=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var yl=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pl(e))!ml.call(t,o)&&o!==n&&ys(t,o,{get:()=>e[o],enumerable:!(r=cl(e,o))||r.enumerable});return t};var Re=(t,e,n)=>(n=t!=null?dl(fl(t)):{},yl(e||!t||!t.__esModule?ys(n,"default",{value:t,enumerable:!0}):n,t));var x=gl(()=>{"use strict"});var _s=hl(()=>{"use strict";x();var ws;(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 s(){try{return Function("return this;")()}catch{}}function i(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return s()||i()}})(function(e,n){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",s=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",i=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 Vr(Object.create(null))}:u?function(){return Vr({__proto__:null})}:function(){return Vr({})},has:l?function(w,S){return r.call(w,S)}:function(w,S){return S in w},get:l?function(w,S){return r.call(w,S)?w[S]:void 0}:function(w,S){return w[S]}},c=Object.getPrototypeOf(Function),p=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:sl(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:il(),g=typeof WeakMap=="function"?WeakMap:al(),k=o?Symbol.for("@reflect-metadata:registry"):void 0,P=nl(),b=rl(P);function f(w,S,A,L){if(M(A)){if(!en(w))throw new TypeError;if(!ds(S))throw new TypeError;return T(w,S)}else{if(!en(w))throw new TypeError;if(!ne(S))throw new TypeError;if(!ne(L)&&!M(L)&&!ee(L))throw new TypeError;return ee(L)&&(L=void 0),A=Oe(A),j(w,S,A,L)}}e("decorate",f);function m(w,S){function A(L,G){if(!ne(L))throw new TypeError;if(!M(G)&&!el(G))throw new TypeError;Be(w,S,L,G)}return A}e("metadata",m);function y(w,S,A,L){if(!ne(A))throw new TypeError;return M(L)||(L=Oe(L)),Be(w,S,A,L)}e("defineMetadata",y);function _(w,S,A){if(!ne(S))throw new TypeError;return M(A)||(A=Oe(A)),W(w,S,A)}e("hasMetadata",_);function v(w,S,A){if(!ne(S))throw new TypeError;return M(A)||(A=Oe(A)),K(w,S,A)}e("hasOwnMetadata",v);function R(w,S,A){if(!ne(S))throw new TypeError;return M(A)||(A=Oe(A)),oe(w,S,A)}e("getMetadata",R);function E(w,S,A){if(!ne(S))throw new TypeError;return M(A)||(A=Oe(A)),te(w,S,A)}e("getOwnMetadata",E);function O(w,S){if(!ne(w))throw new TypeError;return M(S)||(S=Oe(S)),se(w,S)}e("getMetadataKeys",O);function I(w,S){if(!ne(w))throw new TypeError;return M(S)||(S=Oe(S)),ve(w,S)}e("getOwnMetadataKeys",I);function C(w,S,A){if(!ne(S))throw new TypeError;if(M(A)||(A=Oe(A)),!ne(S))throw new TypeError;M(A)||(A=Oe(A));var L=tn(S,A,!1);return M(L)?!1:L.OrdinaryDeleteMetadata(w,S,A)}e("deleteMetadata",C);function T(w,S){for(var A=w.length-1;A>=0;--A){var L=w[A],G=L(S);if(!M(G)&&!ee(G)){if(!ds(G))throw new TypeError;S=G}}return S}function j(w,S,A,L){for(var G=w.length-1;G>=0;--G){var ge=w[G],_e=ge(S,A,L);if(!M(_e)&&!ee(_e)){if(!ne(_e))throw new TypeError;L=_e}}return L}function W(w,S,A){var L=K(w,S,A);if(L)return!0;var G=Gr(S);return ee(G)?!1:W(w,G,A)}function K(w,S,A){var L=tn(S,A,!1);return M(L)?!1:Ae(L.OrdinaryHasOwnMetadata(w,S,A))}function oe(w,S,A){var L=K(w,S,A);if(L)return te(w,S,A);var G=Gr(S);if(!ee(G))return oe(w,G,A)}function te(w,S,A){var L=tn(S,A,!1);if(!M(L))return L.OrdinaryGetOwnMetadata(w,S,A)}function Be(w,S,A,L){var G=tn(A,L,!0);G.OrdinaryDefineOwnMetadata(w,S,A,L)}function se(w,S){var A=ve(w,S),L=Gr(w);if(L===null)return A;var G=se(L,S);if(G.length<=0)return A;if(A.length<=0)return G;for(var ge=new h,_e=[],z=0,N=A;z<N.length;z++){var U=N[z],D=ge.has(U);D||(ge.add(U),_e.push(U))}for(var H=0,Y=G;H<Y.length;H++){var U=Y[H],D=ge.has(U);D||(ge.add(U),_e.push(U))}return _e}function ve(w,S){var A=tn(w,S,!1);return A?A.OrdinaryOwnMetadataKeys(w,S):[]}function V(w){if(w===null)return 1;switch(typeof w){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return w===null?1:6;default:return 6}}function M(w){return w===void 0}function ee(w){return w===null}function Qe(w){return typeof w=="symbol"}function ne(w){return typeof w=="object"?w!==null:typeof w=="function"}function re(w,S){switch(V(w)){case 0:return w;case 1:return w;case 2:return w;case 3:return w;case 4:return w;case 5:return w}var A=S===3?"string":S===5?"number":"default",L=cs(w,s);if(L!==void 0){var G=L.call(w,A);if(ne(G))throw new TypeError;return G}return ue(w,A==="default"?"number":A)}function ue(w,S){if(S==="string"){var A=w.toString;if(et(A)){var L=A.call(w);if(!ne(L))return L}var G=w.valueOf;if(et(G)){var L=G.call(w);if(!ne(L))return L}}else{var G=w.valueOf;if(et(G)){var L=G.call(w);if(!ne(L))return L}var ge=w.toString;if(et(ge)){var L=ge.call(w);if(!ne(L))return L}}throw new TypeError}function Ae(w){return!!w}function Ze(w){return""+w}function Oe(w){var S=re(w,3);return Qe(S)?S:Ze(S)}function en(w){return Array.isArray?Array.isArray(w):w instanceof Object?w instanceof Array:Object.prototype.toString.call(w)==="[object Array]"}function et(w){return typeof w=="function"}function ds(w){return typeof w=="function"}function el(w){switch(V(w)){case 3:return!0;case 4:return!0;default:return!1}}function qr(w,S){return w===S||w!==w&&S!==S}function cs(w,S){var A=w[S];if(A!=null){if(!et(A))throw new TypeError;return A}}function ps(w){var S=cs(w,i);if(!et(S))throw new TypeError;var A=S.call(w);if(!ne(A))throw new TypeError;return A}function fs(w){return w.value}function ms(w){var S=w.next();return S.done?!1:S}function gs(w){var S=w.return;S&&S.call(w)}function Gr(w){var S=Object.getPrototypeOf(w);if(typeof w!="function"||w===c||S!==c)return S;var A=w.prototype,L=A&&Object.getPrototypeOf(A);if(L==null||L===Object.prototype)return S;var G=L.constructor;return typeof G!="function"||G===w?S:G}function tl(){var w;!M(k)&&typeof n.Reflect<"u"&&!(k in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(w=ol(n.Reflect));var S,A,L,G=new g,ge={registerProvider:_e,getProvider:N,setProvider:D};return ge;function _e(H){if(!Object.isExtensible(ge))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case w===H:break;case M(S):S=H;break;case S===H:break;case M(A):A=H;break;case A===H:break;default:L===void 0&&(L=new h),L.add(H);break}}function z(H,Y){if(!M(S)){if(S.isProviderFor(H,Y))return S;if(!M(A)){if(A.isProviderFor(H,Y))return S;if(!M(L))for(var ie=ps(L);;){var he=ms(ie);if(!he)return;var He=fs(he);if(He.isProviderFor(H,Y))return gs(ie),He}}}if(!M(w)&&w.isProviderFor(H,Y))return w}function N(H,Y){var ie=G.get(H),he;return M(ie)||(he=ie.get(Y)),M(he)&&(he=z(H,Y),M(he)||(M(ie)&&(ie=new p,G.set(H,ie)),ie.set(Y,he))),he}function U(H){if(M(H))throw new TypeError;return S===H||A===H||!M(L)&&L.has(H)}function D(H,Y,ie){if(!U(ie))throw new Error("Metadata provider not registered.");var he=N(H,Y);if(he!==ie){if(!M(he))return!1;var He=G.get(H);M(He)&&(He=new p,G.set(H,He)),He.set(Y,ie)}return!0}}function nl(){var w;return!M(k)&&ne(n.Reflect)&&Object.isExtensible(n.Reflect)&&(w=n.Reflect[k]),M(w)&&(w=tl()),!M(k)&&ne(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,k,{enumerable:!1,configurable:!1,writable:!1,value:w}),w}function rl(w){var S=new g,A={isProviderFor:function(U,D){var H=S.get(U);return M(H)?!1:H.has(D)},OrdinaryDefineOwnMetadata:_e,OrdinaryHasOwnMetadata:G,OrdinaryGetOwnMetadata:ge,OrdinaryOwnMetadataKeys:z,OrdinaryDeleteMetadata:N};return P.registerProvider(A),A;function L(U,D,H){var Y=S.get(U),ie=!1;if(M(Y)){if(!H)return;Y=new p,S.set(U,Y),ie=!0}var he=Y.get(D);if(M(he)){if(!H)return;if(he=new p,Y.set(D,he),!w.setProvider(U,D,A))throw Y.delete(D),ie&&S.delete(U),new Error("Wrong provider for target.")}return he}function G(U,D,H){var Y=L(D,H,!1);return M(Y)?!1:Ae(Y.has(U))}function ge(U,D,H){var Y=L(D,H,!1);if(!M(Y))return Y.get(U)}function _e(U,D,H,Y){var ie=L(H,Y,!0);ie.set(U,D)}function z(U,D){var H=[],Y=L(U,D,!1);if(M(Y))return H;for(var ie=Y.keys(),he=ps(ie),He=0;;){var hs=ms(he);if(!hs)return H.length=He,H;var ul=fs(hs);try{H[He]=ul}catch(ll){try{gs(he)}finally{throw ll}}He++}}function N(U,D,H){var Y=L(D,H,!1);if(M(Y)||!Y.delete(U))return!1;if(Y.size===0){var ie=S.get(D);M(ie)||(ie.delete(H),ie.size===0&&S.delete(ie))}return!0}}function ol(w){var S=w.defineMetadata,A=w.hasOwnMetadata,L=w.getOwnMetadata,G=w.getOwnMetadataKeys,ge=w.deleteMetadata,_e=new g,z={isProviderFor:function(N,U){var D=_e.get(N);return!M(D)&&D.has(U)?!0:G(N,U).length?(M(D)&&(D=new h,_e.set(N,D)),D.add(U),!0):!1},OrdinaryDefineOwnMetadata:S,OrdinaryHasOwnMetadata:A,OrdinaryGetOwnMetadata:L,OrdinaryOwnMetadataKeys:G,OrdinaryDeleteMetadata:ge};return z}function tn(w,S,A){var L=P.getProvider(w,S);if(!M(L))return L;if(A){if(P.setProvider(w,S,b))return b;throw new Error("Illegal state.")}}function sl(){var w={},S=[],A=(function(){function z(N,U,D){this._index=0,this._keys=N,this._values=U,this._selector=D}return z.prototype["@@iterator"]=function(){return this},z.prototype[i]=function(){return this},z.prototype.next=function(){var N=this._index;if(N>=0&&N<this._keys.length){var U=this._selector(this._keys[N],this._values[N]);return N+1>=this._keys.length?(this._index=-1,this._keys=S,this._values=S):this._index++,{value:U,done:!1}}return{value:void 0,done:!0}},z.prototype.throw=function(N){throw this._index>=0&&(this._index=-1,this._keys=S,this._values=S),N},z.prototype.return=function(N){return this._index>=0&&(this._index=-1,this._keys=S,this._values=S),{value:N,done:!0}},z})(),L=(function(){function z(){this._keys=[],this._values=[],this._cacheKey=w,this._cacheIndex=-2}return Object.defineProperty(z.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),z.prototype.has=function(N){return this._find(N,!1)>=0},z.prototype.get=function(N){var U=this._find(N,!1);return U>=0?this._values[U]:void 0},z.prototype.set=function(N,U){var D=this._find(N,!0);return this._values[D]=U,this},z.prototype.delete=function(N){var U=this._find(N,!1);if(U>=0){for(var D=this._keys.length,H=U+1;H<D;H++)this._keys[H-1]=this._keys[H],this._values[H-1]=this._values[H];return this._keys.length--,this._values.length--,qr(N,this._cacheKey)&&(this._cacheKey=w,this._cacheIndex=-2),!0}return!1},z.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=w,this._cacheIndex=-2},z.prototype.keys=function(){return new A(this._keys,this._values,G)},z.prototype.values=function(){return new A(this._keys,this._values,ge)},z.prototype.entries=function(){return new A(this._keys,this._values,_e)},z.prototype["@@iterator"]=function(){return this.entries()},z.prototype[i]=function(){return this.entries()},z.prototype._find=function(N,U){if(!qr(this._cacheKey,N)){this._cacheIndex=-1;for(var D=0;D<this._keys.length;D++)if(qr(this._keys[D],N)){this._cacheIndex=D;break}}return this._cacheIndex<0&&U&&(this._cacheIndex=this._keys.length,this._keys.push(N),this._values.push(void 0)),this._cacheIndex},z})();return L;function G(z,N){return z}function ge(z,N){return N}function _e(z,N){return[z,N]}}function il(){var w=(function(){function S(){this._map=new p}return Object.defineProperty(S.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),S.prototype.has=function(A){return this._map.has(A)},S.prototype.add=function(A){return this._map.set(A,A),this},S.prototype.delete=function(A){return this._map.delete(A)},S.prototype.clear=function(){this._map.clear()},S.prototype.keys=function(){return this._map.keys()},S.prototype.values=function(){return this._map.keys()},S.prototype.entries=function(){return this._map.entries()},S.prototype["@@iterator"]=function(){return this.keys()},S.prototype[i]=function(){return this.keys()},S})();return w}function al(){var w=16,S=d.create(),A=L();return(function(){function N(){this._key=L()}return N.prototype.has=function(U){var D=G(U,!1);return D!==void 0?d.has(D,this._key):!1},N.prototype.get=function(U){var D=G(U,!1);return D!==void 0?d.get(D,this._key):void 0},N.prototype.set=function(U,D){var H=G(U,!0);return H[this._key]=D,this},N.prototype.delete=function(U){var D=G(U,!1);return D!==void 0?delete D[this._key]:!1},N.prototype.clear=function(){this._key=L()},N})();function L(){var N;do N="@@WeakMap@@"+z();while(d.has(S,N));return S[N]=!0,N}function G(N,U){if(!r.call(N,A)){if(!U)return;Object.defineProperty(N,A,{value:d.create()})}return N[A]}function ge(N,U){for(var D=0;D<U;++D)N[D]=Math.random()*255|0;return N}function _e(N){if(typeof Uint8Array=="function"){var U=new Uint8Array(N);return typeof crypto<"u"?crypto.getRandomValues(U):typeof msCrypto<"u"?msCrypto.getRandomValues(U):ge(U,N),U}return ge(new Array(N),N)}function z(){var N=_e(w);N[6]=N[6]&79|64,N[8]=N[8]&191|128;for(var U="",D=0;D<w;++D){var H=N[D];(D===4||D===6||D===8)&&(U+="-"),H<16&&(U+="0"),U+=H.toString(16).toLowerCase()}return U}}function Vr(w){return w.__=void 0,delete w.__,w}})})(ws||(ws={}))});x();var S_=Re(_s(),1),Ke=Re(require("process"),1);x();var Vl=Re(require("os"),1),Wl=Re(require("path"),1),Jl=require("url"),Kl=require("util");x();x();var ce=class extends Error{},wl=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function _l(t){if(typeof t!="string")return!1;let e=wl.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let u=new Date(Date.UTC(n,r-1,o,s,i,a));return u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===o&&u.getUTCHours()===s&&u.getUTCMinutes()===i&&u.getUTCSeconds()===a}function vl(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new ce(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new ce(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new ce(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,u)=>{if(a===null||typeof a!="object")throw new ce(`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 ce(`catalog shared endpoints[${u}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new ce(`catalog shared endpoints[${u}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let d=(c,p)=>{if(l[c]!==void 0&&l[c]!==null&&!p)throw new ce(`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",_l(l.ready_since));for(let c of["model_id","variant"]){let p=l[c];if(p.includes(":"))throw new ce(`catalog shared endpoints[${u}] has "${c}" containing ":" (${JSON.stringify(p)}) \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 ce(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new ce(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let u of Object.keys(a))if(u!=="zdr"&&u!=="hipaa")throw new ce(`catalog "shared" block compliance carries "${u}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function It(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Wr(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(l=>l.model_id===o);if(a.length===0)return null;if(s!==void 0){let l=a.find(d=>d.variant===s);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 ce(`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 vs(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 ce(`catalog read failed: GET ${n} \u2192 ${r.status}`);return vl(await r.json())}x();function Ce(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}x();var Me=class extends Error{name="ModelPriceError"},Jr="per_million_input_tokens",Kr="per_million_output_tokens",Ss="model_id,variant,unit,price_usd,effective_at,expires_at",bs={per_request:!0,per_minute:!0,per_output_unit:!0},bl=5e3;function Sl(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new Me(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function ks(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new Me(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function kl(t,e,n){return t===null?null:ks(t,e,n)}function Rl(t,e){if(t===Jr)return"input";if(t===Kr)return"output";if(typeof t=="string"&&Object.hasOwn(bs,t))return null;throw new Me(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Jr} | ${Kr}) nor a known GPU-time unit (${Object.keys(bs).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 xl(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s: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 zr(t,e){return`${t}\0${e}`}function El(t){if(!Array.isArray(t))throw new Me(`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 Me(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of Ss.split(","))if(!Object.hasOwn(s,l))throw new Me(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=Rl(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new Me(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new Me(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:Sl(s.price_usd,o),effective_at:ks(s.effective_at,o,"effective_at"),expires_at:kl(s.expires_at,o,"expires_at")})}return e}function Rs(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 s=[],i=[];for(let[u,l]of r){let d=l.get(""),c=(p,h,g)=>{let k=p&&p.length>0?p:d?.[h];if(!k||k.length===0)return null;let P=xl(k,h);return"reason"in P?P:P.rate.usd===0?h==="output"&&g!==null&&n?.has(zr(u,g))?P.rate:{reason:`the ${h} 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`}:P.rate};for(let[p,h]of o.get(u)){let g=l.get(p),k=c(g?.input,"input",h),P=c(g?.output,"output",h);if(k!==null&&"reason"in k){i.push({model_id:u,variant:h,reason:k.reason});continue}if(P!==null&&"reason"in P){i.push({model_id:u,variant:h,reason:P.reason});continue}k===null||P===null||s.push({model_id:u,variant:h,pricing:{input:k.usd,output:P.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:s.sort(a),refusals:i.sort(a)}}function nn(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var rn={prices:[],refusals:[]};async function xs(t){let e=t.fetchImpl??fetch,n=`${Jr},${Kr}`,r=await e(`${t.catalogUrl}/model_prices?select=${Ss}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(bl)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return El(await r.json())}x();var gt="/partners/openrouter/models",Al={chat:!0,code:!0,agent:!0,vl:!0},Es={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Ol(t){let e=t.toLowerCase();return Object.hasOwn(Es,e)?Es[e]:null}var As={"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 Il(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(As,o)?As[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,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 Os={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Is={2:"Llama2",3:"Llama3"};function Tl(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 s=r[o];if(Object.hasOwn(Os,s))return Os[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Is,i))return Is[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Pl=["context_length","max_model_len"];function Cl(t){let e=Pl.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 Pn(t){let e=t.map(Cl),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Ll(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function Yr(t){if(t.length===0)return null;let e=t.map(Ll),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Xr(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function Ml(t,e){let n=e.filter(s=>Ce(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return on(n);let r=e.filter(s=>Ce(s.model_id)===t);if(r.length>0)return on(r);let o=Xr(t,e);return o.length>0?on(o):null}function on(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:$l(t),matches:t}:null}function $l(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")}}var it=class extends Error{name="ModelCreatedError"};function Tt(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new it(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new it(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new it(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),u=Date.UTC(s,i-1,a),l=new Date(u);if(l.getUTCFullYear()!==s||l.getUTCMonth()!==i-1||l.getUTCDate()!==a)throw new it(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return u/1e3}function mt(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 Cn(t,e,n){let r=Ml(t,e);if(!r)return mt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Pn(s),a=Tt(s),u=nn(o.model_id,o.variant,n),l=Cs(o,s),d=Yr(s);return mt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...u!==null?{pricing:u}:{},...l.published.length>0?{voices:[...l.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var Nl=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Cs(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=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:[...Nl],defect:o}:{published:[],defect:o}}function Qr(t){let e=t.length>0?on(t):null;return e===null?{published:[],defect:null}:Cs(e.row,e.matches)}function Ts(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,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Ps(t){return{input:[{type:"prompt",unit:"token",cost_usd:Ts(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Ts(t.output)}]}}function Ul(t,e,n,r){if(e.length===0)return null;let o=on(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Al[s.task]!==!0)return null;let a=Pn(i),u=nn(s.model_id,s.variant,n),l=Tl(s.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:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Tt(i),quantization:Ol(s.variant),...l!==null?{tokenizer:l}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.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:Ps(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...u?{pricing:Ps(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Ls(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?It(t):[];if(s.length>0){let l=s.filter(d=>d.ready===void 0);if(l.length===s.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 i={datacenters:Il(t?.regions,o),compliance:t?.compliance??null},a=[],u=new Set;for(let l of s){let d=`${l.model_id}:${l.variant}`;if(u.has(d))continue;u.add(d);let c=Ul(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&a.push(c)}return{data:a}}x();var Ms={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},Pt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function $s(t){let e=t.t;if(typeof e!="string"||!(e in Ms))throw new Pt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Ms).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 Dl(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Pt(`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 Pt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return $s(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Pt(`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 $s(t)}function Ns(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Fl(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function Us(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 Ns(e);let s=o.next();if(e!==void 0&&await Fl(s,e)==="aborted")throw s.catch(()=>{}),Ns(e);let i=await s;if(i.done)return;yield Dl(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var Z=class extends Error{},X=class extends Error{},eo="urs1.";function Mn(t,e){return eo+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Un(t){if(!t.startsWith(eo))return null;try{let e=JSON.parse(Buffer.from(t.slice(eo.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 Bs(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 Ds(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=jl(t);return e===null?[]:[e]}function Bl(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
2
+ "use strict";var yl=Object.create;var Ss=Object.defineProperty;var wl=Object.getOwnPropertyDescriptor;var _l=Object.getOwnPropertyNames;var vl=Object.getPrototypeOf,bl=Object.prototype.hasOwnProperty;var Sl=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var kl=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Rl=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _l(e))!bl.call(t,o)&&o!==n&&Ss(t,o,{get:()=>e[o],enumerable:!(r=wl(e,o))||r.enumerable});return t};var xe=(t,e,n)=>(n=t!=null?yl(vl(t)):{},Rl(e||!t||!t.__esModule?Ss(n,"default",{value:t,enumerable:!0}):n,t));var x=Sl(()=>{"use strict"});var Rs=kl(()=>{"use strict";x();var ks;(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 s(){try{return Function("return this;")()}catch{}}function i(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return s()||i()}})(function(e,n){var r=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",s=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",i=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 Jr(Object.create(null))}:u?function(){return Jr({__proto__:null})}:function(){return Jr({})},has:l?function(w,k){return r.call(w,k)}:function(w,k){return k in w},get:l?function(w,k){return r.call(w,k)?w[k]:void 0}:function(w,k){return w[k]}},c=Object.getPrototypeOf(Function),p=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:pl(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:fl(),g=typeof WeakMap=="function"?WeakMap:ml(),v=o?Symbol.for("@reflect-metadata:registry"):void 0,I=ll(),b=dl(I);function f(w,k,A,L){if(M(A)){if(!en(w))throw new TypeError;if(!gs(k))throw new TypeError;return T(w,k)}else{if(!en(w))throw new TypeError;if(!ne(k))throw new TypeError;if(!ne(L)&&!M(L)&&!ee(L))throw new TypeError;return ee(L)&&(L=void 0),A=Te(A),D(w,k,A,L)}}e("decorate",f);function m(w,k){function A(L,G){if(!ne(L))throw new TypeError;if(!M(G)&&!al(G))throw new TypeError;Be(w,k,L,G)}return A}e("metadata",m);function y(w,k,A,L){if(!ne(A))throw new TypeError;return M(L)||(L=Te(L)),Be(w,k,A,L)}e("defineMetadata",y);function S(w,k,A){if(!ne(k))throw new TypeError;return M(A)||(A=Te(A)),V(w,k,A)}e("hasMetadata",S);function P(w,k,A){if(!ne(k))throw new TypeError;return M(A)||(A=Te(A)),J(w,k,A)}e("hasOwnMetadata",P);function _(w,k,A){if(!ne(k))throw new TypeError;return M(A)||(A=Te(A)),oe(w,k,A)}e("getMetadata",_);function E(w,k,A){if(!ne(k))throw new TypeError;return M(A)||(A=Te(A)),te(w,k,A)}e("getOwnMetadata",E);function O(w,k){if(!ne(w))throw new TypeError;return M(k)||(k=Te(k)),se(w,k)}e("getMetadataKeys",O);function R(w,k){if(!ne(w))throw new TypeError;return M(k)||(k=Te(k)),be(w,k)}e("getOwnMetadataKeys",R);function C(w,k,A){if(!ne(k))throw new TypeError;if(M(A)||(A=Te(A)),!ne(k))throw new TypeError;M(A)||(A=Te(A));var L=tn(k,A,!1);return M(L)?!1:L.OrdinaryDeleteMetadata(w,k,A)}e("deleteMetadata",C);function T(w,k){for(var A=w.length-1;A>=0;--A){var L=w[A],G=L(k);if(!M(G)&&!ee(G)){if(!gs(G))throw new TypeError;k=G}}return k}function D(w,k,A,L){for(var G=w.length-1;G>=0;--G){var he=w[G],ve=he(k,A,L);if(!M(ve)&&!ee(ve)){if(!ne(ve))throw new TypeError;L=ve}}return L}function V(w,k,A){var L=J(w,k,A);if(L)return!0;var G=Vr(k);return ee(G)?!1:V(w,G,A)}function J(w,k,A){var L=tn(k,A,!1);return M(L)?!1:Ie(L.OrdinaryHasOwnMetadata(w,k,A))}function oe(w,k,A){var L=J(w,k,A);if(L)return te(w,k,A);var G=Vr(k);if(!ee(G))return oe(w,G,A)}function te(w,k,A){var L=tn(k,A,!1);if(!M(L))return L.OrdinaryGetOwnMetadata(w,k,A)}function Be(w,k,A,L){var G=tn(A,L,!0);G.OrdinaryDefineOwnMetadata(w,k,A,L)}function se(w,k){var A=be(w,k),L=Vr(w);if(L===null)return A;var G=se(L,k);if(G.length<=0)return A;if(A.length<=0)return G;for(var he=new h,ve=[],z=0,N=A;z<N.length;z++){var U=N[z],B=he.has(U);B||(he.add(U),ve.push(U))}for(var j=0,Y=G;j<Y.length;j++){var U=Y[j],B=he.has(U);B||(he.add(U),ve.push(U))}return ve}function be(w,k){var A=tn(w,k,!1);return A?A.OrdinaryOwnMetadataKeys(w,k):[]}function W(w){if(w===null)return 1;switch(typeof w){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return w===null?1:6;default:return 6}}function M(w){return w===void 0}function ee(w){return w===null}function Ze(w){return typeof w=="symbol"}function ne(w){return typeof w=="object"?w!==null:typeof w=="function"}function re(w,k){switch(W(w)){case 0:return w;case 1:return w;case 2:return w;case 3:return w;case 4:return w;case 5:return w}var A=k===3?"string":k===5?"number":"default",L=hs(w,s);if(L!==void 0){var G=L.call(w,A);if(ne(G))throw new TypeError;return G}return ue(w,A==="default"?"number":A)}function ue(w,k){if(k==="string"){var A=w.toString;if(tt(A)){var L=A.call(w);if(!ne(L))return L}var G=w.valueOf;if(tt(G)){var L=G.call(w);if(!ne(L))return L}}else{var G=w.valueOf;if(tt(G)){var L=G.call(w);if(!ne(L))return L}var he=w.toString;if(tt(he)){var L=he.call(w);if(!ne(L))return L}}throw new TypeError}function Ie(w){return!!w}function et(w){return""+w}function Te(w){var k=re(w,3);return Ze(k)?k:et(k)}function en(w){return Array.isArray?Array.isArray(w):w instanceof Object?w instanceof Array:Object.prototype.toString.call(w)==="[object Array]"}function tt(w){return typeof w=="function"}function gs(w){return typeof w=="function"}function al(w){switch(W(w)){case 3:return!0;case 4:return!0;default:return!1}}function Wr(w,k){return w===k||w!==w&&k!==k}function hs(w,k){var A=w[k];if(A!=null){if(!tt(A))throw new TypeError;return A}}function ys(w){var k=hs(w,i);if(!tt(k))throw new TypeError;var A=k.call(w);if(!ne(A))throw new TypeError;return A}function ws(w){return w.value}function _s(w){var k=w.next();return k.done?!1:k}function vs(w){var k=w.return;k&&k.call(w)}function Vr(w){var k=Object.getPrototypeOf(w);if(typeof w!="function"||w===c||k!==c)return k;var A=w.prototype,L=A&&Object.getPrototypeOf(A);if(L==null||L===Object.prototype)return k;var G=L.constructor;return typeof G!="function"||G===w?k:G}function ul(){var w;!M(v)&&typeof n.Reflect<"u"&&!(v in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(w=cl(n.Reflect));var k,A,L,G=new g,he={registerProvider:ve,getProvider:N,setProvider:B};return he;function ve(j){if(!Object.isExtensible(he))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case w===j:break;case M(k):k=j;break;case k===j:break;case M(A):A=j;break;case A===j:break;default:L===void 0&&(L=new h),L.add(j);break}}function z(j,Y){if(!M(k)){if(k.isProviderFor(j,Y))return k;if(!M(A)){if(A.isProviderFor(j,Y))return k;if(!M(L))for(var ie=ys(L);;){var ye=_s(ie);if(!ye)return;var He=ws(ye);if(He.isProviderFor(j,Y))return vs(ie),He}}}if(!M(w)&&w.isProviderFor(j,Y))return w}function N(j,Y){var ie=G.get(j),ye;return M(ie)||(ye=ie.get(Y)),M(ye)&&(ye=z(j,Y),M(ye)||(M(ie)&&(ie=new p,G.set(j,ie)),ie.set(Y,ye))),ye}function U(j){if(M(j))throw new TypeError;return k===j||A===j||!M(L)&&L.has(j)}function B(j,Y,ie){if(!U(ie))throw new Error("Metadata provider not registered.");var ye=N(j,Y);if(ye!==ie){if(!M(ye))return!1;var He=G.get(j);M(He)&&(He=new p,G.set(j,He)),He.set(Y,ie)}return!0}}function ll(){var w;return!M(v)&&ne(n.Reflect)&&Object.isExtensible(n.Reflect)&&(w=n.Reflect[v]),M(w)&&(w=ul()),!M(v)&&ne(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,v,{enumerable:!1,configurable:!1,writable:!1,value:w}),w}function dl(w){var k=new g,A={isProviderFor:function(U,B){var j=k.get(U);return M(j)?!1:j.has(B)},OrdinaryDefineOwnMetadata:ve,OrdinaryHasOwnMetadata:G,OrdinaryGetOwnMetadata:he,OrdinaryOwnMetadataKeys:z,OrdinaryDeleteMetadata:N};return I.registerProvider(A),A;function L(U,B,j){var Y=k.get(U),ie=!1;if(M(Y)){if(!j)return;Y=new p,k.set(U,Y),ie=!0}var ye=Y.get(B);if(M(ye)){if(!j)return;if(ye=new p,Y.set(B,ye),!w.setProvider(U,B,A))throw Y.delete(B),ie&&k.delete(U),new Error("Wrong provider for target.")}return ye}function G(U,B,j){var Y=L(B,j,!1);return M(Y)?!1:Ie(Y.has(U))}function he(U,B,j){var Y=L(B,j,!1);if(!M(Y))return Y.get(U)}function ve(U,B,j,Y){var ie=L(j,Y,!0);ie.set(U,B)}function z(U,B){var j=[],Y=L(U,B,!1);if(M(Y))return j;for(var ie=Y.keys(),ye=ys(ie),He=0;;){var bs=_s(ye);if(!bs)return j.length=He,j;var gl=ws(bs);try{j[He]=gl}catch(hl){try{vs(ye)}finally{throw hl}}He++}}function N(U,B,j){var Y=L(B,j,!1);if(M(Y)||!Y.delete(U))return!1;if(Y.size===0){var ie=k.get(B);M(ie)||(ie.delete(j),ie.size===0&&k.delete(ie))}return!0}}function cl(w){var k=w.defineMetadata,A=w.hasOwnMetadata,L=w.getOwnMetadata,G=w.getOwnMetadataKeys,he=w.deleteMetadata,ve=new g,z={isProviderFor:function(N,U){var B=ve.get(N);return!M(B)&&B.has(U)?!0:G(N,U).length?(M(B)&&(B=new h,ve.set(N,B)),B.add(U),!0):!1},OrdinaryDefineOwnMetadata:k,OrdinaryHasOwnMetadata:A,OrdinaryGetOwnMetadata:L,OrdinaryOwnMetadataKeys:G,OrdinaryDeleteMetadata:he};return z}function tn(w,k,A){var L=I.getProvider(w,k);if(!M(L))return L;if(A){if(I.setProvider(w,k,b))return b;throw new Error("Illegal state.")}}function pl(){var w={},k=[],A=(function(){function z(N,U,B){this._index=0,this._keys=N,this._values=U,this._selector=B}return z.prototype["@@iterator"]=function(){return this},z.prototype[i]=function(){return this},z.prototype.next=function(){var N=this._index;if(N>=0&&N<this._keys.length){var U=this._selector(this._keys[N],this._values[N]);return N+1>=this._keys.length?(this._index=-1,this._keys=k,this._values=k):this._index++,{value:U,done:!1}}return{value:void 0,done:!0}},z.prototype.throw=function(N){throw this._index>=0&&(this._index=-1,this._keys=k,this._values=k),N},z.prototype.return=function(N){return this._index>=0&&(this._index=-1,this._keys=k,this._values=k),{value:N,done:!0}},z})(),L=(function(){function z(){this._keys=[],this._values=[],this._cacheKey=w,this._cacheIndex=-2}return Object.defineProperty(z.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),z.prototype.has=function(N){return this._find(N,!1)>=0},z.prototype.get=function(N){var U=this._find(N,!1);return U>=0?this._values[U]:void 0},z.prototype.set=function(N,U){var B=this._find(N,!0);return this._values[B]=U,this},z.prototype.delete=function(N){var U=this._find(N,!1);if(U>=0){for(var B=this._keys.length,j=U+1;j<B;j++)this._keys[j-1]=this._keys[j],this._values[j-1]=this._values[j];return this._keys.length--,this._values.length--,Wr(N,this._cacheKey)&&(this._cacheKey=w,this._cacheIndex=-2),!0}return!1},z.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=w,this._cacheIndex=-2},z.prototype.keys=function(){return new A(this._keys,this._values,G)},z.prototype.values=function(){return new A(this._keys,this._values,he)},z.prototype.entries=function(){return new A(this._keys,this._values,ve)},z.prototype["@@iterator"]=function(){return this.entries()},z.prototype[i]=function(){return this.entries()},z.prototype._find=function(N,U){if(!Wr(this._cacheKey,N)){this._cacheIndex=-1;for(var B=0;B<this._keys.length;B++)if(Wr(this._keys[B],N)){this._cacheIndex=B;break}}return this._cacheIndex<0&&U&&(this._cacheIndex=this._keys.length,this._keys.push(N),this._values.push(void 0)),this._cacheIndex},z})();return L;function G(z,N){return z}function he(z,N){return N}function ve(z,N){return[z,N]}}function fl(){var w=(function(){function k(){this._map=new p}return Object.defineProperty(k.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),k.prototype.has=function(A){return this._map.has(A)},k.prototype.add=function(A){return this._map.set(A,A),this},k.prototype.delete=function(A){return this._map.delete(A)},k.prototype.clear=function(){this._map.clear()},k.prototype.keys=function(){return this._map.keys()},k.prototype.values=function(){return this._map.keys()},k.prototype.entries=function(){return this._map.entries()},k.prototype["@@iterator"]=function(){return this.keys()},k.prototype[i]=function(){return this.keys()},k})();return w}function ml(){var w=16,k=d.create(),A=L();return(function(){function N(){this._key=L()}return N.prototype.has=function(U){var B=G(U,!1);return B!==void 0?d.has(B,this._key):!1},N.prototype.get=function(U){var B=G(U,!1);return B!==void 0?d.get(B,this._key):void 0},N.prototype.set=function(U,B){var j=G(U,!0);return j[this._key]=B,this},N.prototype.delete=function(U){var B=G(U,!1);return B!==void 0?delete B[this._key]:!1},N.prototype.clear=function(){this._key=L()},N})();function L(){var N;do N="@@WeakMap@@"+z();while(d.has(k,N));return k[N]=!0,N}function G(N,U){if(!r.call(N,A)){if(!U)return;Object.defineProperty(N,A,{value:d.create()})}return N[A]}function he(N,U){for(var B=0;B<U;++B)N[B]=Math.random()*255|0;return N}function ve(N){if(typeof Uint8Array=="function"){var U=new Uint8Array(N);return typeof crypto<"u"?crypto.getRandomValues(U):typeof msCrypto<"u"?msCrypto.getRandomValues(U):he(U,N),U}return he(new Array(N),N)}function z(){var N=ve(w);N[6]=N[6]&79|64,N[8]=N[8]&191|128;for(var U="",B=0;B<w;++B){var j=N[B];(B===4||B===6||B===8)&&(U+="-"),j<16&&(U+="0"),U+=j.toString(16).toLowerCase()}return U}}function Jr(w){return w.__=void 0,delete w.__,w}})})(ks||(ks={}))});x();var N_=xe(Rs(),1),ze=xe(require("process"),1);x();var Ql=xe(require("os"),1),Zl=xe(require("path"),1),ed=require("url"),td=require("util");x();x();var le=class extends Error{},xl=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function El(t){if(typeof t!="string")return!1;let e=xl.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let u=new Date(Date.UTC(n,r-1,o,s,i,a));return u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===o&&u.getUTCHours()===s&&u.getUTCMinutes()===i&&u.getUTCSeconds()===a}function Al(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new le(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new le(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new le(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,u)=>{if(a===null||typeof a!="object")throw new le(`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 le(`catalog shared endpoints[${u}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new le(`catalog shared endpoints[${u}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let d=(c,p)=>{if(l[c]!==void 0&&l[c]!==null&&!p)throw new le(`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",El(l.ready_since));for(let c of["model_id","variant"]){let p=l[c];if(p.includes(":"))throw new le(`catalog shared endpoints[${u}] has "${c}" containing ":" (${JSON.stringify(p)}) \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 le(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new le(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let u of Object.keys(a))if(u!=="zdr"&&u!=="hipaa")throw new le(`catalog "shared" block compliance carries "${u}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function Tt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function xs(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=a=>new le(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let u=o[a];if(typeof u!="string"||u===""||u.includes(":"))throw i(`"${a}" ${JSON.stringify(u)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function Kr(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(l=>l.model_id===o);if(a.length===0)return null;if(s!==void 0){let l=a.find(d=>d.variant===s);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 le(`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 Es(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 le(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Al(await r.json())}x();function Le(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}x();var $e=class extends Error{name="ModelPriceError"},zr="per_million_input_tokens",Yr="per_million_output_tokens",Os="model_id,variant,unit,price_usd,effective_at,expires_at",As={per_request:!0,per_minute:!0,per_output_unit:!0},Ol=5e3;function Il(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new $e(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Is(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new $e(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Tl(t,e,n){return t===null?null:Is(t,e,n)}function Pl(t,e){if(t===zr)return"input";if(t===Yr)return"output";if(typeof t=="string"&&Object.hasOwn(As,t))return null;throw new $e(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${zr} | ${Yr}) nor a known GPU-time unit (${Object.keys(As).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 Cl(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s: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 Xr(t,e){return`${t}\0${e}`}function Ll(t){if(!Array.isArray(t))throw new $e(`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 $e(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of Os.split(","))if(!Object.hasOwn(s,l))throw new $e(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=Pl(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new $e(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new $e(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:Il(s.price_usd,o),effective_at:Is(s.effective_at,o,"effective_at"),expires_at:Tl(s.expires_at,o,"expires_at")})}return e}function Ts(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 s=[],i=[];for(let[u,l]of r){let d=l.get(""),c=(p,h,g)=>{let v=p&&p.length>0?p:d?.[h];if(!v||v.length===0)return null;let I=Cl(v,h);return"reason"in I?I:I.rate.usd===0?h==="output"&&g!==null&&n?.has(Xr(u,g))?I.rate:{reason:`the ${h} 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`}:I.rate};for(let[p,h]of o.get(u)){let g=l.get(p),v=c(g?.input,"input",h),I=c(g?.output,"output",h);if(v!==null&&"reason"in v){i.push({model_id:u,variant:h,reason:v.reason});continue}if(I!==null&&"reason"in I){i.push({model_id:u,variant:h,reason:I.reason});continue}v===null||I===null||s.push({model_id:u,variant:h,pricing:{input:v.usd,output:I.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:s.sort(a),refusals:i.sort(a)}}function nn(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var rn={prices:[],refusals:[]};async function Ps(t){let e=t.fetchImpl??fetch,n=`${zr},${Yr}`,r=await e(`${t.catalogUrl}/model_prices?select=${Os}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Ol)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Ll(await r.json())}x();var ht="/partners/openrouter/models",Ml={chat:!0,code:!0,agent:!0,vl:!0},Cs={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function $l(t){let e=t.toLowerCase();return Object.hasOwn(Cs,e)?Cs[e]:null}var Ls={"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 Nl(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Ls,o)?Ls[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,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 Ms={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},$s={2:"Llama2",3:"Llama3"};function Ul(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 s=r[o];if(Object.hasOwn(Ms,s))return Ms[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn($s,i))return $s[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Dl=["context_length","max_model_len"];function Fl(t){let e=Dl.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 Pn(t){let e=t.map(Fl),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Bl(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function Qr(t){if(t.length===0)return null;let e=t.map(Bl),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Zr(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function Hl(t,e){let n=e.filter(s=>Le(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return on(n);let r=e.filter(s=>Le(s.model_id)===t);if(r.length>0)return on(r);let o=Zr(t,e);return o.length>0?on(o):null}function on(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:jl(t),matches:t}:null}function jl(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")}}var at=class extends Error{name="ModelCreatedError"};function Pt(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new at(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new at(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new at(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),a=Number(o[3]),u=Date.UTC(s,i-1,a),l=new Date(u);if(l.getUTCFullYear()!==s||l.getUTCMonth()!==i-1||l.getUTCDate()!==a)throw new at(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return u/1e3}function gt(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 Cn(t,e,n){let r=Hl(t,e);if(!r)return gt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Pn(s),a=Pt(s),u=nn(o.model_id,o.variant,n),l=Ds(o,s),d=Qr(s);return gt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...u!==null?{pricing:u}:{},...l.published.length>0?{voices:[...l.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var ql=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Ds(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=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:[...ql],defect:o}:{published:[],defect:o}}function eo(t){let e=t.length>0?on(t):null;return e===null?{published:[],defect:null}:Ds(e.row,e.matches)}function Ns(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,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Us(t){return{input:[{type:"prompt",unit:"token",cost_usd:Ns(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Ns(t.output)}]}}function Gl(t,e,n,r){if(e.length===0)return null;let o=on(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Ml[s.task]!==!0)return null;let a=Pn(i),u=nn(s.model_id,s.variant,n),l=Ul(s.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:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Pt(i),quantization:$l(s.variant),...l!==null?{tokenizer:l}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.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:Us(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...u?{pricing:Us(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Fs(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?Tt(t):[];if(s.length>0){let l=s.filter(d=>d.ready===void 0);if(l.length===s.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 i={datacenters:Nl(t?.regions,o),compliance:t?.compliance??null},a=[],u=new Set;for(let l of s){let d=`${l.model_id}:${l.variant}`;if(u.has(d))continue;u.add(d);let c=Gl(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&a.push(c)}return{data:a}}x();var Bs={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},Ct=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Hs(t){let e=t.t;if(typeof e!="string"||!(e in Bs))throw new Ct(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Bs).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 Wl(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Ct(`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 Ct(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Hs(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Ct(`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 Hs(t)}function js(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Vl(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function qs(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 js(e);let s=o.next();if(e!==void 0&&await Vl(s,e)==="aborted")throw s.catch(()=>{}),js(e);let i=await s;if(i.done)return;yield Wl(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var Z=class extends Error{},X=class extends Error{},no="urs1.";function Mn(t,e){return no+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Un(t){if(!t.startsWith(no))return null;try{let e=JSON.parse(Buffer.from(t.slice(no.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 Vs(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 Gs(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=zl(t);return e===null?[]:[e]}function Jl(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
3
3
  `),null;let e={},n=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],r=!1;for(let[o,s]of n){let i=t[o];if(i==null)continue;let a=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(a)||a<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
4
- `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function no(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||Ce(`${r.model_id}-${r.variant}`)===e.appSlug||Ce(r.model_id)===e.appSlug)),n?Bl(n.engine_args?.pool):null}function Zr(t,e,n,r,o){if(!o)throw new ce(`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 ce(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new ce(`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 s}function Fs(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 ce(`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 Hs="shared:",an="speech:";function ut(t){return t.sharedApp?Hs+t.appSlug:t.appSlug}function $n(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 to(t,e){let n=e.filter(s=>Ce(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>Ce(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function Hl(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function jl(t){let e=t.map(Hl),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var ql={stt:"stt",tts:"tts"};function at(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:ql[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function js(t,e){let n=to(t,e);return n.length>0?n:Xr(t,e)}function sn(t,e){return js(t.appSlug,e)}function Gl(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 ce(`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 Ln=6e4,Nn=class{constructor(e){this.opts=e}opts;pool=new Map;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??Ln):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??Ln):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??Ln):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Ln;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 Me)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
5
- `),rn}let r=Rs(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}
6
- `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(zr(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(Hs)||o.startsWith(an)||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 sharedLane(e){if(!this.opts.shared)return null;let n=await this.sharedBlock();if(!n)return null;let r=Wr(n,e);if(r)return r;let o=e.lastIndexOf(":"),s=o>0?e.slice(0,o):e,i=o>0?e.slice(o+1):void 0,a=Ce(s),u=n.endpoints.filter(c=>Ce(c.model_id)===a&&(i===void 0||c.variant===i)),l=new Set(u.map(c=>c.model_id)),d=[...l][0];return d===void 0||l.size!==1?null:Wr(n,d,i)}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=Ce(n);if(o===r)return{appSlug:r};let s=await this.sharedLane(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:s.shared_org_id,gpuSpec:s.endpoint.gpu_spec??void 0,appId:s.endpoint.app_id??void 0};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let i=await this.deployedApps(),a=this.servable(i);if(a.includes(o))return{appSlug:o};let u=a.filter(d=>d.startsWith(`${o}-`));if(u.length===1)return{appSlug:u[0]};if(u.length>1)throw new Z(`model "${n}" is ambiguous across deployed apps ${u.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(l)throw new Z(`model "${n}" maps to app "${l.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.listCatalog){let a=(await this.opts.listCatalog()).find(u=>n===u.model_id||n===`${u.model_id}:${u.variant}`||o===Ce(u.model_id)||o===Ce(`${u.model_id}-${u.variant}`));if(a)throw new Z(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${a.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=$n(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return no(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return ut(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,ut(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,an+ut(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:$n(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:Mn(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Mn(n,this.keyOf(r))}}async sessionForHandle(e){let n=Un(e);if(!n)throw new X(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,s=this.pool.get(r),i=s?await s.then(a=>a,()=>null):null;if(i===null)throw new X(`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(i)!==o)throw new X(`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:i}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(s=>s,()=>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))]),s=r.rows,i=r.ok?o:rn;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)
7
- `);let u=(n?It(n):[]).map(l=>{let d=s.filter(b=>b.model_id===l.model_id&&b.variant===l.variant),c=Pn(d),p=Tt(d),h=Yr(d),g=nn(l.model_id,l.variant,i),k=Qr(d);return mt({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...g!==null?{pricing:g}:{},...k.published.length>0?{voices:[...k.published]}:{},...h!==null?{capabilities:{reasoning:h}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(l=>Cn(l,s,i)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Ls(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 s=Zr(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Fs(`${r.modelId}:${r.variant}`,s).includes(n)}return Ds(to(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?at(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:at(sn(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?at(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":at(sn(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?at(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":at(sn(n,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):sn(n,r);return Gl(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):sn(n,r);return Qr(o)}async imageModelList(){let e=await this.catalogRows(),n=rn,r=[];for(let s of await this.availableIds()){let i=Ds(to(s,e));i.length!==0&&r.push(mt({...Cn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of It(o)){let i=Zr(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Fs(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let u=mt({id:`${s.model_id}:${s.variant}`,object:"model",created:Tt(i),owned_by:"urun",image_modes:a});r.push(u)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=rn,r=[];for(let s of await this.availableIds())at(js(s,e))==="stt"&&r.push(Cn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of It(o)){let i=Zr(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(at(i)!=="stt")continue;let a=mt({id:`${s.model_id}:${s.variant}`,object:"model",created:Tt(i),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 qs(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 Dn(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 zl=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Gs(t){let e=t?.code;return typeof e=="string"&&zl.has(e)}function ze(t,e){try{return t.write(e),!0}catch(n){if(Gs(n))return!1;throw n}}function Vs(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Gs(i)&&(e[r]=!0);let a=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
8
- `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}x();var me=require("@prometheus-io/client"),gi=require("http");x();var Yl={"/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 Xl(t){return Yl[t]??null}var Ks=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Ql(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Zl(t){return t==="surface"}function ed(t){let e=t?.ledgerFailureReason;return Ks.includes(e)?e:"unknown"}var td=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Ws=["priced","unpriced"],nd={written:Ws,already_written:Ws,skipped:td,failed:Ks},zs=Object.entries(nd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function rd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function od(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 sd=256,Js=4096,un=12e4,id=250,ad=8e3,tt=[],ro=new Set,ln=0,Ct=!1;function Ys(){return tt.length}function Xs(t=Date.now()){let e=tt[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var Fn=new Set;function Qs(){return ln===0&&tt.length===0}function Zs(){if(Qs()){Ct=!1;for(let t of[...Fn])t()}}async function ei(t=ni){return Qs()?!0:await new Promise(e=>{let n=null,r=()=>{Fn.delete(r),n&&clearTimeout(n),e(!0)};Fn.add(r),n=setTimeout(()=>{Fn.delete(r),e(!1)},t),n.unref?.()})}function ti(){Ct=!0;let t=[...tt.splice(0,tt.length),...ro];for(let e of t)e.settled||yt(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 ${ni}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Zs(),t.length}var ni=5e3;function ri(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
9
- `}function ud(t){ze(process.stdout,t)}function oi(t,e){try{t(e)}catch{}}function si(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??ud,o=Xl(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),oi(r,ri("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:od(e),completed_at:e.ts,billable_outcome:rd(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(tt.length>=Js){i("queue_full",`${tt.length} ledger writes are already waiting (capacity ${Js}, ${ln} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}tt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),ln<sd&&(ln+=1,ld())}async function ld(){try{for(;;){let t=dd();if(t===void 0)return;ro.add(t);try{await cd(t)}finally{ro.delete(t)}}}finally{ln-=1,Zs()}}function dd(){let t=Date.now();for(;;){let e=tt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<un)return e;yt(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 ${un}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 cd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);yt(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=Ql(o);if(s!==null){yt(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=ed(o),a=Date.now()-t.queuedAt;if(Ct){yt(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(Zl(i)&&a<un){if(await fd(pd(t.attempts)),Ct||Date.now()-t.queuedAt>=un){let u=Date.now()-t.queuedAt;yt(t,{outcome:"failed",reason:Ct?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Ct?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${un}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}yt(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function pd(t){return Math.min(ad,id*2**Math.max(0,t-1))}function fd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function yt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;oi(t.report,ri(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}x();x();var Hn="/v1/usage/requests",ii=1e4,md=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,lt=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},fe=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Bn=class extends fe{constructor(e){super(e),this.name="UsageWithholdingError"}},di=1024*1024;function io(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new lt(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new lt(`"${e}" must be an array of uuid strings`);if(n.length>ii)throw new lt(`"${e}" carries ${n.length} ids; at most ${ii} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!md.test(s))throw new lt(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function ci(t){return io(t,"inference_ids")}var gd=["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 Lt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new fe(`${n}: ${e} is not a non-empty string (got ${$t(r)})`);return r}function oo(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new fe(`${n}: ${e} is neither null nor a non-empty string (got ${$t(r)})`);return r}function Mt(t,e,n,r){let o=t[e];if(o===null)return null;let s=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(s))throw new fe(`${n}: ${e} is not a number (got ${$t(o)})`);if(r&&!Number.isSafeInteger(s))throw new fe(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(s<0)throw new fe(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var hd=40,ai=64,ui=600;function pi(t){let e=Object.keys(t).sort(),r=e.slice(0,hd).map(o=>o.length>ai?`${o.slice(0,ai)}\u2026`:o).join(", ");return r.length>ui&&(r=`${r.slice(0,ui)}\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 so(t){ze(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
10
- `)}function yd(t,e){let n;try{n=t(e)}catch{li(t,e);return}wd(n)&&Promise.resolve(n).catch(()=>{li(t,e)})}function wd(t){return typeof t?.then=="function"}function li(t,e){if(t!==so)try{so(e)}catch{}}function fi(t,e=so){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?pi(t):$t(t);throw new fe(`the usage surface answered without a "requests" array: got ${$t(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(_d(n[o],s))}catch(i){if(i instanceof Bn||!(i instanceof fe))throw i;yd(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new fe(`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 _d(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new fe(`${e} is not an object: got ${$t(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new Bn(`${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 gd)if(!Object.hasOwn(n,o))throw new fe(`${e} has no "${o}" column (${pi(n)})`);let r=Mt(n,"http_status",e,!0);if(r===null)throw new fe(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Lt(n,"inference_id",e),model_id:Lt(n,"model_id",e),identity_kind:Lt(n,"identity_kind",e),variant:oo(n,"variant",e),task:Lt(n,"task",e),http_status:r,started_at:Lt(n,"started_at",e),completed_at:Lt(n,"completed_at",e),prompt_tokens:Mt(n,"prompt_tokens",e,!0),completion_tokens:Mt(n,"completion_tokens",e,!0),output_units:Mt(n,"output_units",e,!1),output_minutes:Mt(n,"output_minutes",e,!1),cost_nano_usd:Mt(n,"cost_nano_usd",e,!0),price_version:oo(n,"price_version",e),priced_at:oo(n,"priced_at",e)}}function jn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new fe(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(s.inference_id))throw new fe(`the usage surface returned ${s.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(s.inference_id)}}var dn="/partners/huggingface/v1/billing/requests";function vd(t){return io(t,"requestIds")}function bd(t){return t>=200&&t<=399}function Sd(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&bd(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function mi(t,e){let n=vd(t),r=await e(n);return jn(r,n),Sd(r)}var ao=9464,qn="/metrics",Gn="(other)",kd="(none)",Rd=64,xd=128,Ed=["/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",Hn,dn,gt],Ad=new Set(Ed);function Od(t){return Ad.has(t)?t:Gn}function Id(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var Vn=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?kd:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,Gn):(this.admitted.add(e),e):Gn}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},Wn=class{registry=new me.Registry;modelLabel=new Vn(Rd);orgLabel=new Vn(xd);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new me.Gauge({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new me.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 me.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 me.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 me.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 me.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 me.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 zs)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new me.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"},Ys()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Xs()/1e3)}}),this.labelCardinality=new me.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 me.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]}),this.lanesReady=new me.Gauge({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new me.Histogram({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new me.Histogram({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new me.Counter({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new me.Counter({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&(0,me.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=Od(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(e.model,r),i=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===""?Gn:e.method,status_class:Id(e.status),stream:u,model:s,org:i}),this.duration.observe({lane:n,stream:u,model:s,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:s}),e.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function hi(t){return(0,gi.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==qn){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${qn}
4
+ `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function oo(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||Le(`${r.model_id}-${r.variant}`)===e.appSlug||Le(r.model_id)===e.appSlug)),n?Jl(n.engine_args?.pool):null}function to(t,e,n,r,o){if(!o)throw new le(`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 le(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new le(`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 s}function Ws(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 le(`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 Js="shared:",an="speech:";function lt(t){return t.sharedApp?Js+t.appSlug:t.appSlug}function $n(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 ro(t,e){let n=e.filter(s=>Le(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>Le(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function Kl(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function zl(t){let e=t.map(Kl),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Yl={stt:"stt",tts:"tts"};function ut(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:Yl[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Ks(t,e){let n=ro(t,e);return n.length>0?n:Zr(t,e)}function sn(t,e){return Ks(t.appSlug,e)}function Xl(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 le(`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 Ln=6e4,Nn=class{constructor(e){this.opts=e}opts;pool=new Map;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??Ln):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??Ln):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??Ln):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Ln;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 $e)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
5
+ `),rn}let r=Ts(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}
6
+ `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(Xr(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(Js)||o.startsWith(an)||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 sharedLane(e){if(!this.opts.shared)return null;let n=await this.sharedBlock();if(!n)return null;let r=Kr(n,e);if(r)return r;let o=e.lastIndexOf(":"),s=o>0?e.slice(0,o):e,i=o>0?e.slice(o+1):void 0,a=Le(s),u=n.endpoints.filter(c=>Le(c.model_id)===a&&(i===void 0||c.variant===i)),l=new Set(u.map(c=>c.model_id)),d=[...l][0];return d===void 0||l.size!==1?null:Kr(n,d,i)}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=Le(n);if(o===r)return{appSlug:r};let s=await this.sharedLane(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:s.shared_org_id,gpuSpec:s.endpoint.gpu_spec??void 0,appId:s.endpoint.app_id??void 0};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let i=await this.deployedApps(),a=this.servable(i);if(a.includes(o))return{appSlug:o};let u=a.filter(d=>d.startsWith(`${o}-`));if(u.length===1)return{appSlug:u[0]};if(u.length>1)throw new Z(`model "${n}" is ambiguous across deployed apps ${u.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(l)throw new Z(`model "${n}" maps to app "${l.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.listCatalog){let a=(await this.opts.listCatalog()).find(u=>n===u.model_id||n===`${u.model_id}:${u.variant}`||o===Le(u.model_id)||o===Le(`${u.model_id}-${u.variant}`));if(a)throw new Z(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${a.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=$n(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return oo(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return lt(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,lt(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,an+lt(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:$n(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:Mn(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Mn(n,this.keyOf(r))}}async sessionForHandle(e){let n=Un(e);if(!n)throw new X(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,s=this.pool.get(r),i=s?await s.then(a=>a,()=>null):null;if(i===null)throw new X(`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(i)!==o)throw new X(`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:i}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(s=>s,()=>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))]),s=r.rows,i=r.ok?o:rn;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)
7
+ `);let u=(n?Tt(n):[]).map(l=>{let d=s.filter(b=>b.model_id===l.model_id&&b.variant===l.variant),c=Pn(d),p=Pt(d),h=Qr(d),g=nn(l.model_id,l.variant,i),v=eo(d);return gt({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...g!==null?{pricing:g}:{},...v.published.length>0?{voices:[...v.published]}:{},...h!==null?{capabilities:{reasoning:h}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(l=>Cn(l,s,i)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Fs(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 s=to(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Ws(`${r.modelId}:${r.variant}`,s).includes(n)}return Gs(ro(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ut(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:ut(sn(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ut(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":ut(sn(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ut(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":ut(sn(n,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):sn(n,r);return Xl(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):sn(n,r);return eo(o)}async imageModelList(){let e=await this.catalogRows(),n=rn,r=[];for(let s of await this.availableIds()){let i=Gs(ro(s,e));i.length!==0&&r.push(gt({...Cn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of Tt(o)){let i=to(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Ws(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let u=gt({id:`${s.model_id}:${s.variant}`,object:"model",created:Pt(i),owned_by:"urun",image_modes:a});r.push(u)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=rn,r=[];for(let s of await this.availableIds())ut(Ks(s,e))==="stt"&&r.push(Cn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of Tt(o)){let i=to(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(ut(i)!=="stt")continue;let a=gt({id:`${s.model_id}:${s.variant}`,object:"model",created:Pt(i),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 zs(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 Dn(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 nd=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Ys(t){let e=t?.code;return typeof e=="string"&&nd.has(e)}function Ye(t,e){try{return t.write(e),!0}catch(n){if(Ys(n))return!1;throw n}}function Xs(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Ys(i)&&(e[r]=!0);let a=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
8
+ `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}x();var me=require("@prometheus-io/client"),bi=require("http");x();var rd={"/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 od(t){return rd[t]??null}var ei=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function sd(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function id(t){return t==="surface"}function ad(t){let e=t?.ledgerFailureReason;return ei.includes(e)?e:"unknown"}var ud=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Qs=["priced","unpriced"],ld={written:Qs,already_written:Qs,skipped:ud,failed:ei},ti=Object.entries(ld).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function dd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function cd(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 pd=256,Zs=4096,un=12e4,fd=250,md=8e3,nt=[],so=new Set,ln=0,Lt=!1;function ni(){return nt.length}function ri(t=Date.now()){let e=nt[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var Fn=new Set;function oi(){return ln===0&&nt.length===0}function si(){if(oi()){Lt=!1;for(let t of[...Fn])t()}}async function ii(t=ui){return oi()?!0:await new Promise(e=>{let n=null,r=()=>{Fn.delete(r),n&&clearTimeout(n),e(!0)};Fn.add(r),n=setTimeout(()=>{Fn.delete(r),e(!1)},t),n.unref?.()})}function ai(){Lt=!0;let t=[...nt.splice(0,nt.length),...so];for(let e of t)e.settled||wt(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 ${ui}ms drain \u2014 the request was served and answered, and its billing row was never written`});return si(),t.length}var ui=5e3;function li(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
9
+ `}function gd(t){Ye(process.stdout,t)}function di(t,e){try{t(e)}catch{}}function ci(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??gd,o=od(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),di(r,li("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:cd(e),completed_at:e.ts,billable_outcome:dd(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(nt.length>=Zs){i("queue_full",`${nt.length} ledger writes are already waiting (capacity ${Zs}, ${ln} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}nt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),ln<pd&&(ln+=1,hd())}async function hd(){try{for(;;){let t=yd();if(t===void 0)return;so.add(t);try{await wd(t)}finally{so.delete(t)}}}finally{ln-=1,si()}}function yd(){let t=Date.now();for(;;){let e=nt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<un)return e;wt(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 ${un}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 wd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);wt(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=sd(o);if(s!==null){wt(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=ad(o),a=Date.now()-t.queuedAt;if(Lt){wt(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(id(i)&&a<un){if(await vd(_d(t.attempts)),Lt||Date.now()-t.queuedAt>=un){let u=Date.now()-t.queuedAt;wt(t,{outcome:"failed",reason:Lt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Lt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${un}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}wt(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function _d(t){return Math.min(md,fd*2**Math.max(0,t-1))}function vd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function wt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;di(t.report,li(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}x();x();var Hn="/v1/usage/requests",pi=1e4,bd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,dt=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},fe=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Bn=class extends fe{constructor(e){super(e),this.name="UsageWithholdingError"}},hi=1024*1024;function uo(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new dt(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new dt(`"${e}" must be an array of uuid strings`);if(n.length>pi)throw new dt(`"${e}" carries ${n.length} ids; at most ${pi} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!bd.test(s))throw new dt(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function yi(t){return uo(t,"inference_ids")}var Sd=["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 Mt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new fe(`${n}: ${e} is not a non-empty string (got ${Nt(r)})`);return r}function io(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new fe(`${n}: ${e} is neither null nor a non-empty string (got ${Nt(r)})`);return r}function $t(t,e,n,r){let o=t[e];if(o===null)return null;let s=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(s))throw new fe(`${n}: ${e} is not a number (got ${Nt(o)})`);if(r&&!Number.isSafeInteger(s))throw new fe(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(s<0)throw new fe(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var kd=40,fi=64,mi=600;function wi(t){let e=Object.keys(t).sort(),r=e.slice(0,kd).map(o=>o.length>fi?`${o.slice(0,fi)}\u2026`:o).join(", ");return r.length>mi&&(r=`${r.slice(0,mi)}\u2026`),`${e.length} keys present: [${r}]`}function Nt(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function ao(t){Ye(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
10
+ `)}function Rd(t,e){let n;try{n=t(e)}catch{gi(t,e);return}xd(n)&&Promise.resolve(n).catch(()=>{gi(t,e)})}function xd(t){return typeof t?.then=="function"}function gi(t,e){if(t!==ao)try{ao(e)}catch{}}function _i(t,e=ao){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?wi(t):Nt(t);throw new fe(`the usage surface answered without a "requests" array: got ${Nt(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Ed(n[o],s))}catch(i){if(i instanceof Bn||!(i instanceof fe))throw i;Rd(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new fe(`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 Ed(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new fe(`${e} is not an object: got ${Nt(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new Bn(`${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 Sd)if(!Object.hasOwn(n,o))throw new fe(`${e} has no "${o}" column (${wi(n)})`);let r=$t(n,"http_status",e,!0);if(r===null)throw new fe(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Mt(n,"inference_id",e),model_id:Mt(n,"model_id",e),identity_kind:Mt(n,"identity_kind",e),variant:io(n,"variant",e),task:Mt(n,"task",e),http_status:r,started_at:Mt(n,"started_at",e),completed_at:Mt(n,"completed_at",e),prompt_tokens:$t(n,"prompt_tokens",e,!0),completion_tokens:$t(n,"completion_tokens",e,!0),output_units:$t(n,"output_units",e,!1),output_minutes:$t(n,"output_minutes",e,!1),cost_nano_usd:$t(n,"cost_nano_usd",e,!0),price_version:io(n,"price_version",e),priced_at:io(n,"priced_at",e)}}function jn(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new fe(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(s.inference_id))throw new fe(`the usage surface returned ${s.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(s.inference_id)}}var dn="/partners/huggingface/v1/billing/requests";function Ad(t){return uo(t,"requestIds")}function Od(t){return t>=200&&t<=399}function Id(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Od(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function vi(t,e){let n=Ad(t),r=await e(n);return jn(r,n),Id(r)}var lo=9464,qn="/metrics",Gn="(other)",Td="(none)",Pd=64,Cd=128,Ld=["/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",Hn,dn,ht],Md=new Set(Ld);function $d(t){return Md.has(t)?t:Gn}function Nd(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var Wn=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?Td:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,Gn):(this.admitted.add(e),e):Gn}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},Vn=class{registry=new me.Registry;modelLabel=new Wn(Pd);orgLabel=new Wn(Cd);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new me.Gauge({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new me.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 me.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 me.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 me.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 me.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 me.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 ti)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new me.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"},ni()),this.ledgerQueue.set({measure:"oldest_age_seconds"},ri()/1e3)}}),this.labelCardinality=new me.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 me.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]}),this.lanesReady=new me.Gauge({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new me.Histogram({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new me.Histogram({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new me.Counter({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new me.Counter({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&(0,me.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=$d(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(e.model,r),i=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===""?Gn:e.method,status_class:Nd(e.status),stream:u,model:s,org:i}),this.duration.observe({lane:n,stream:u,model:s,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:s}),e.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Si(t){return(0,bi.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==qn){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${qn}
11
11
  `);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)}
12
- `);return}n.end()})})}x();var uo=require("crypto"),wi=require("http"),lo=9465,Td="x-urun-key-id",Pd="x-urun-key-fingerprint",Cd="urun-ratelimit-bucket:",Ld="urun-ratelimit-tier:",yi="anonymous",Md=/^urun_sk_[A-Za-z0-9_-]{43}$/;function $d(t){return(0,uo.createHash)("sha256").update(`${Cd}${t}`).digest("hex")}function Nd(t){return(0,uo.createHash)("sha256").update(`${Ld}${t}`).digest("hex")}function Ud(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Md.test(n)?n:null}function _i(){return(0,wi.createServer)((t,e)=>{let n=Ud(t.headers.authorization);e.setHeader(Td,n===null?yi:$d(n)),e.setHeader(Pd,n===null?yi:Nd(n)),e.writeHead(200),e.end()})}x();var Dd=8080,co="serve",wt="0.0.0.0";function Fd(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function vi(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Dd: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=qs(Dn(Fd(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(),s=o?Dn(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!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=i?{catalogUrl:Dn(i,"URUN_CATALOG_URL"),anonKey:a}:null,l=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!l!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let c=l?{keyId:d,key:l}:void 0,p={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},h=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],g=h.filter((y,_)=>Object.values(p)[_]==="");if(g.length!==0&&g.length!==h.length)throw new Error(`${h.join(", ")} must be set together (or all left unset) \u2014 missing: ${g.join(", ")}, which would half-configure the lane plane`);let k=g.length===0?p:void 0,P={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},b=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],f=b.filter((y,_)=>Object.values(P)[_]==="");if(f.length!==0&&f.length!==b.length)throw new Error(`${b.join(", ")} must be set together (or all left unset) \u2014 missing: ${f.join(", ")}, which would half-configure the pooler cutover`);let m=f.length===0?P:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:u,ledgerSigning:c,lane:k,pooler:m}}x();var Yu=require("http");x();x();var ki="audio",po=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 s=0;s<r;s++)o[s]=n.readInt16LE(s*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 Ri(t,e,n=1e4){let r=new po(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(ki).attach(o);let s=await Bd(t,n);return await r.startInbound(s),r}function Bd(t,e){let n=t.stream(ki);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),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(i),s?.(),r(u))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var bi="rt-video-in",Si=256e3;function xi(t){let e=t.stream(bi),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${bi}') 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>Si)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Si}-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 Hd=24e3,cn=480,jd=111;async function qd(){let t=await import("opusscript"),e=t.default??t;return new e(Hd,1,2048)}async function Ei(){let t=await import("werift"),e=await qd();return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let u=new Int16Array(i.length+a.length);u.set(i,0),u.set(a,i.length);let l=0;for(;u.length-l>=cn;){let d=u.subarray(l,l+cn);l+=cn;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,cn);o=o+1&65535,s=s+cn>>>0;let h=new t.RtpHeader({version:2,payloadType:jd,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),g=new t.RtpPacket(h,p);n.writeRtp(g)}i=u.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let u=0;u<a.length;u++)a[u]=i.readInt16LE(u*2);r.onframe?.({samples:a})}),r}}}x();var Jn=require("@urun-sh/core"),fo="rt-video-out";var Gd="h264";function Vd(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 Wd(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(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}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;Vd(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var Ai="urun.videoOut.v2-ws";function Oi(t){let e=t.stream(fo);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${fo}') 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,s=u=>{for(let l of r)l(u)},i=!1,a=async()=>{for await(let u of e.messages()){if(!(u instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${fo}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=Wd(u)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(l)}for(let u of o)u()};return{codec:Gd,onOutputFrame:u=>(n.add(u),i||(i=!0,a().catch(l=>s(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 Xn="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Jd=1007,Ti=1008,nt=1011,Qn=1008,$=class extends Error{constructor(n,r=Jd){super(n);this.closeCode=r}closeCode},ye=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Kn=["setup","clientContent","realtimeInput","toolResponse"];function Pi(t){let e;try{e=JSON.parse(t)}catch{throw new $("client message is not valid JSON")}let n=ye(e);if(!n)throw new $("client message must be a JSON object");let r=Kn.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Kn.includes(a));if(o.length>0)throw new $(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Kn.join(", ")}`);if(r.length!==1)throw new $(`client message must contain exactly one of ${Kn.join(", ")} (got ${r.length})`);let s=r[0],i=ye(n[s]);if(!i)throw new $(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Ci(t,e){if(typeof t=="string")return t;let n=ye(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new $(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=ye(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new $(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new $(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new $(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
13
- `)}var Kd={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},_t="urun.videoOut";function Li(t){return{framing:Ai,codec:t}}function Mi(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[_t]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var zd={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Yd=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",_t],Ii=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Xd(t){let e=ye(t);if(!e)throw new $("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new $(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ye(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new $("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new $(`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 $("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(!Ii.includes(e.activityHandling))throw new $(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Ii.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Qd=["temperature","maxOutputTokens","responseModalities"];function $i(t){for(let[c,p]of Object.entries(zd))if(t[c]!==void 0)throw new $(p);for(let c of Object.keys(t))if(!Yd.includes(c))throw new $(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new $('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=ye(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new $("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Qd.includes(c))throw new $(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new $("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new $("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of c){let h=String(p).toUpperCase();if(h==="AUDIO"){o=!0;continue}if(h!=="TEXT")throw new $(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:Ci(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new $("setup.tools must be an array");a=[];for(let c of t.tools){let p=ye(c);if(!p)throw new $("setup.tools entries must be objects");for(let h of Object.keys(p))if(h!=="functionDeclarations")throw new $(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new $("tool.functionDeclarations must be an array");for(let h of p.functionDeclarations){let g=ye(h);if(!g||typeof g.name!="string")throw new $("functionDeclarations entries require a string name");a.push({type:"function",name:g.name,description:g.description,parameters:g.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ye(t.sessionResumption);if(!c)throw new $("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new $(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new $("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?Kd:Xd(t.realtimeInputConfig),d=!1;if(t[_t]!==void 0){if(!ye(t[_t]))throw new $(`setup["${_t}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:u,videoOut:d}}function Ni(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Ui(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Di(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new $(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new $("clientContent.turns must be an array");let n=[];for(let r of e){let o=ye(r);if(!o)throw new $("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new $(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Ci(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var zn=16e3,Fi=24e3,Zd=`audio/pcm;rate=${Fi}`,Bi=Buffer.alloc(960).toString("base64");function ec(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let u=a*s,l=Math.floor(u);if(l>=i){o[a]=t[i];continue}let d=u-l;o[a]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function tc(t){let e=ye(t);if(!e)throw new $("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new $(`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 $("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 $("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function nc(t){let e=ye(t);if(!e)throw new $("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new $(`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])!==zn)throw new $(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${zn} Hz (audio/pcm;rate=${zn})`);if(typeof e.data!="string"||e.data.length===0)throw new $("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 $(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=ec(o,zn,Fi);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Hi(t){if(t.mediaChunks!==void 0)throw new $('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 $("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=ye(t[o]);if(!s||Object.keys(s).length!==0)throw new $(`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 $(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new $(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:nc(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:tc(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new $("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new $("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function ji(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new $(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new $("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ye(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new $("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 qi(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Gi(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Zd,data:t}}]}}}}function Vi(t){let e=ye(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let l of n){let d=ye(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=ye(c);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let l of n){let d=ye(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new $(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,nt);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new $(`upstream function_call arguments are not valid JSON: ${c}`,nt)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=ye(e.usage),u={serverContent:{turnComplete:!0}};if(a){let l={};typeof a.input_tokens=="number"&&(l.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(l.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(l.totalTokenCount=a.total_tokens),Object.keys(l).length>0&&(u.usageMetadata=l)}return i.push(u),{messages:i,assistantItems:o}}x();var Wi=require("crypto"),Ji=require("ws");var rc=256,mo=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>rc;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},oc="local",pn=t=>t.slice(0,120),go=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(Ti,pn(e.message));return}if(e instanceof X){this.ws.close(Qn,pn(e.message));return}if(e instanceof $){this.ws.close(e.closeCode,pn(e.message));return}this.ws.close(nt,pn(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Pi(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 $(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=Di(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Hi(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:Bi);return}this.transcript.push(...ji(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new $("setup may only be sent once, as the first client message");let n=$i(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new $("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",Qn);if(s.model!==n.model)throw new $(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new $("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new $(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Qn);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(l=>this.send(Mi(l))),u=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[_t]=Li(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new $("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new $("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",nt);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Gi(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 $("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new $("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",nt);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 $(`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 $("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 $("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,Wi.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Ni(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(Ui(e.timeLeftMs)),this.ws.close(nt,pn(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let u of r){if(n.interrupted)break;let l=u;if(l.type==="error")throw new $(`upstream error: ${JSON.stringify(l)}`,nt);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=qi(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new $("upstream produced no response.completed event",nt);let{messages:i,assistantItems:a}=Vi(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},vt=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function sc(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new vt(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new vt(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 vt(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ho(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 Ji.WebSocketServer({noServer:!0}),o=new mo;t.on("upgrade",(i,a,u)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===Xn&&(a.on("error",()=>{}),(async()=>{let d=sc(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new vt(401,"invalid local proxy api key");c={clients:e.clients,scope:oc}}r.handleUpgrade(i,a,u,p=>{new go(p,c,o)})})().catch(d=>{let c=502;(d instanceof vt||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",h=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
12
+ `);return}n.end()})})}x();var co=require("crypto"),Ri=require("http"),po=9465,Ud="x-urun-key-id",Dd="x-urun-key-fingerprint",Fd="urun-ratelimit-bucket:",Bd="urun-ratelimit-tier:",ki="anonymous",Hd=/^urun_sk_[A-Za-z0-9_-]{43}$/;function jd(t){return(0,co.createHash)("sha256").update(`${Fd}${t}`).digest("hex")}function qd(t){return(0,co.createHash)("sha256").update(`${Bd}${t}`).digest("hex")}function Gd(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Hd.test(n)?n:null}function xi(){return(0,Ri.createServer)((t,e)=>{let n=Gd(t.headers.authorization);e.setHeader(Ud,n===null?ki:jd(n)),e.setHeader(Dd,n===null?ki:qd(n)),e.writeHead(200),e.end()})}x();var Wd=8080,fo="serve",_t="0.0.0.0";function Vd(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Ei(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Wd: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=zs(Dn(Vd(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(),s=o?Dn(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!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=i?{catalogUrl:Dn(i,"URUN_CATALOG_URL"),anonKey:a}:null,l=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!l!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let c=l?{keyId:d,key:l}:void 0,p={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},h=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],g=h.filter((R,C)=>Object.values(p)[C]==="");if(g.length!==0&&g.length!==h.length)throw new Error(`${h.join(", ")} must be set together (or all left unset) \u2014 missing: ${g.join(", ")}, which would half-configure the lane plane`);let v=g.length===0?p:void 0,I={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},b=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],f=b.filter((R,C)=>Object.values(I)[C]==="");if(f.length!==0&&f.length!==b.length)throw new Error(`${b.join(", ")} must be set together (or all left unset) \u2014 missing: ${f.join(", ")}, which would half-configure the pooler cutover`);let m=f.length===0?I:void 0,y={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},S=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],P=S.filter((R,C)=>Object.values(y)[C]==="");if(P.length!==0&&P.length!==S.length)throw new Error(`${S.join(", ")} must be set together (or all left unset) \u2014 missing: ${P.join(", ")}, which would half-configure the machine-identity rung`);let _=y.issuers.split(",").map(R=>R.trim()).filter(R=>R!=="");if(_.length===0&&P.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let E=Number(y.tokenTtlS);if(P.length===0&&(!Number.isFinite(E)||E<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(y.tokenTtlS)}`);let O=P.length===0?{jwksBaseUrl:y.jwksBaseUrl,issuers:_,tokenTtlS:E}:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:u,ledgerSigning:c,lane:v,pooler:m,machine:O}}x();var rl=require("http");x();x();var Ii="audio",mo=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 s=0;s<r;s++)o[s]=n.readInt16LE(s*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 Ti(t,e,n=1e4){let r=new mo(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Ii).attach(o);let s=await Jd(t,n);return await r.startInbound(s),r}function Jd(t,e){let n=t.stream(Ii);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),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(i),s?.(),r(u))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var Ai="rt-video-in",Oi=256e3;function Pi(t){let e=t.stream(Ai),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${Ai}') 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>Oi)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Oi}-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 Kd=24e3,cn=480,zd=111;async function Yd(){let t=await import("opusscript"),e=t.default??t;return new e(Kd,1,2048)}async function Ci(){let t=await import("werift"),e=await Yd();return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let u=new Int16Array(i.length+a.length);u.set(i,0),u.set(a,i.length);let l=0;for(;u.length-l>=cn;){let d=u.subarray(l,l+cn);l+=cn;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,cn);o=o+1&65535,s=s+cn>>>0;let h=new t.RtpHeader({version:2,payloadType:zd,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),g=new t.RtpPacket(h,p);n.writeRtp(g)}i=u.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let u=0;u<a.length;u++)a[u]=i.readInt16LE(u*2);r.onframe?.({samples:a})}),r}}}x();var Jn=require("@urun-sh/core"),go="rt-video-out";var Xd="h264";function Qd(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 Zd(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(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}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;Qd(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var Li="urun.videoOut.v2-ws";function Mi(t){let e=t.stream(go);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${go}') 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,s=u=>{for(let l of r)l(u)},i=!1,a=async()=>{for await(let u of e.messages()){if(!(u instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${go}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=Zd(u)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(l)}for(let u of o)u()};return{codec:Xd,onOutputFrame:u=>(n.add(u),i||(i=!0,a().catch(l=>s(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 Xn="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",ec=1007,Ni=1008,rt=1011,Qn=1008,$=class extends Error{constructor(n,r=ec){super(n);this.closeCode=r}closeCode},we=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Kn=["setup","clientContent","realtimeInput","toolResponse"];function Ui(t){let e;try{e=JSON.parse(t)}catch{throw new $("client message is not valid JSON")}let n=we(e);if(!n)throw new $("client message must be a JSON object");let r=Kn.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Kn.includes(a));if(o.length>0)throw new $(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Kn.join(", ")}`);if(r.length!==1)throw new $(`client message must contain exactly one of ${Kn.join(", ")} (got ${r.length})`);let s=r[0],i=we(n[s]);if(!i)throw new $(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Di(t,e){if(typeof t=="string")return t;let n=we(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new $(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=we(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new $(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new $(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new $(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
13
+ `)}var tc={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},vt="urun.videoOut";function Fi(t){return{framing:Li,codec:t}}function Bi(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[vt]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var nc={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},rc=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",vt],$i=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function oc(t){let e=we(t);if(!e)throw new $("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new $(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=we(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new $("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new $(`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 $("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(!$i.includes(e.activityHandling))throw new $(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${$i.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var sc=["temperature","maxOutputTokens","responseModalities"];function Hi(t){for(let[c,p]of Object.entries(nc))if(t[c]!==void 0)throw new $(p);for(let c of Object.keys(t))if(!rc.includes(c))throw new $(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new $('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=we(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new $("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!sc.includes(c))throw new $(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new $("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new $("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of c){let h=String(p).toUpperCase();if(h==="AUDIO"){o=!0;continue}if(h!=="TEXT")throw new $(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:Di(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new $("setup.tools must be an array");a=[];for(let c of t.tools){let p=we(c);if(!p)throw new $("setup.tools entries must be objects");for(let h of Object.keys(p))if(h!=="functionDeclarations")throw new $(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new $("tool.functionDeclarations must be an array");for(let h of p.functionDeclarations){let g=we(h);if(!g||typeof g.name!="string")throw new $("functionDeclarations entries require a string name");a.push({type:"function",name:g.name,description:g.description,parameters:g.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=we(t.sessionResumption);if(!c)throw new $("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new $(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new $("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?tc:oc(t.realtimeInputConfig),d=!1;if(t[vt]!==void 0){if(!we(t[vt]))throw new $(`setup["${vt}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:u,videoOut:d}}function ji(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function qi(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Gi(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new $(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new $("clientContent.turns must be an array");let n=[];for(let r of e){let o=we(r);if(!o)throw new $("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new $(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Di(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var zn=16e3,Wi=24e3,ic=`audio/pcm;rate=${Wi}`,Vi=Buffer.alloc(960).toString("base64");function ac(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let u=a*s,l=Math.floor(u);if(l>=i){o[a]=t[i];continue}let d=u-l;o[a]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function uc(t){let e=we(t);if(!e)throw new $("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new $(`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 $("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 $("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function lc(t){let e=we(t);if(!e)throw new $("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new $(`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])!==zn)throw new $(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${zn} Hz (audio/pcm;rate=${zn})`);if(typeof e.data!="string"||e.data.length===0)throw new $("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 $(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=ac(o,zn,Wi);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Ji(t){if(t.mediaChunks!==void 0)throw new $('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 $("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=we(t[o]);if(!s||Object.keys(s).length!==0)throw new $(`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 $(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new $(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:lc(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:uc(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new $("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new $("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Ki(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new $(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new $("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=we(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new $("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 zi(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Yi(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:ic,data:t}}]}}}}function Xi(t){let e=we(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let l of n){let d=we(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=we(c);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let l of n){let d=we(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new $(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,rt);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new $(`upstream function_call arguments are not valid JSON: ${c}`,rt)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=we(e.usage),u={serverContent:{turnComplete:!0}};if(a){let l={};typeof a.input_tokens=="number"&&(l.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(l.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(l.totalTokenCount=a.total_tokens),Object.keys(l).length>0&&(u.usageMetadata=l)}return i.push(u),{messages:i,assistantItems:o}}x();var Qi=require("crypto"),Zi=require("ws");var dc=256,ho=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>dc;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},cc="local",pn=t=>t.slice(0,120),yo=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(Ni,pn(e.message));return}if(e instanceof X){this.ws.close(Qn,pn(e.message));return}if(e instanceof $){this.ws.close(e.closeCode,pn(e.message));return}this.ws.close(rt,pn(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Ui(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 $(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=Gi(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Ji(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:Vi);return}this.transcript.push(...Ki(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new $("setup may only be sent once, as the first client message");let n=Hi(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new $("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",Qn);if(s.model!==n.model)throw new $(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new $("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new $(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Qn);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(l=>this.send(Bi(l))),u=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[vt]=Fi(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new $("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new $("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",rt);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Yi(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 $("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new $("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",rt);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 $(`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 $("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 $("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,Qi.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(ji(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(qi(e.timeLeftMs)),this.ws.close(rt,pn(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let u of r){if(n.interrupted)break;let l=u;if(l.type==="error")throw new $(`upstream error: ${JSON.stringify(l)}`,rt);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=zi(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new $("upstream produced no response.completed event",rt);let{messages:i,assistantItems:a}=Xi(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},bt=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function pc(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new bt(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new bt(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 bt(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function wo(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 Zi.WebSocketServer({noServer:!0}),o=new ho;t.on("upgrade",(i,a,u)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===Xn&&(a.on("error",()=>{}),(async()=>{let d=pc(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new bt(401,"invalid local proxy api key");c={clients:e.clients,scope:cc}}r.handleUpgrade(i,a,u,p=>{new yo(p,c,o)})})().catch(d=>{let c=502;(d instanceof bt||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",h=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
14
14
  Connection: close\r
15
15
  \r
16
16
  ${h}\r
17
- `),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}x();var pt=require("ws");x();x();var Ki=require("crypto"),zi="Inference-Id";function fn(){return(0,Ki.randomUUID)()}function yo(t){return t==="/v1"||t.startsWith("/v1/")}function Yi(t,e){if(!yo(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 mn(t){return`resp_${t}`}function Xi(t){return`chatcmpl-${t}`}function Qi(t){return`msg_${t}`}function $e(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Zi(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function ea(t){return`${JSON.stringify(t)}
18
- `}var ic=256,ac=128;function Ie(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,ac)}var bt=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>=ic?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},uc=256;function lc(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 St=class extends Error{},Nt=class{conversations=new Map;thread(e,n){let r=lc(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new St(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=uc)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},ta=new WeakMap;function gn(t){let e=ta.get(t);return e||(e=new Nt,ta.set(t,e)),e}function Ut(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Ye(t){return t.find(e=>e.type==="response.completed")?.response??null}function Dt(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 dt=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}))}},dc=["<tool_call>","<function="];function cc(t){return dc.find(e=>t.includes(e))}function kt(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 Rt(t,e,n){if(!(!t||e>0))return cc(n)}function Ft(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 rt(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function pc(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 wo(t,e){let n=pc(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var Ne=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Bt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof St?new Ne(n.message,"previous_response_not_found",400,"previous_response_id"):new Ne(String(n instanceof Error?n.message:n),"invalid_input")}}function na(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function _o(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new Ne("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...na(e)!==void 0?{response_format:na(e)}:{}},o)}async function hn(t){let{body:e,clients:n,store:r,stats:o}=t,s=Bt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,l=Ie(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await _o(n,e,s,!0,c?$e(c):void 0);return{responseId:i,events:hc({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function fc(t,e){let n=[...t].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),s=n.filter(u=>u.type==="message").length===o.length,i=0;return[...n.map(u=>u.type==="message"&&s?gc(o[i++],u):u),...mc(r,n)]}function mc(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),s=e.filter(l=>l.type==="function_call"),i=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=s.length===i,u=new Set(s.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!u.has(o(d)):!0})}function gc(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*hc(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:l}=t,d=[],c=V=>V.response&&typeof V.response=="object"?{...V,response:{...V.response,id:r}}:V,p=`item_${r.slice(5)}`,h=!1,g=!1,k=0;function*P(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let b=[],f=(V,M)=>{b.push({output_index:V,item:M})},m=!1,y=0,_="",v=0,R="";function*E(){if(!m)return;m=!1,yield{type:"response.reasoning_text.done",item_id:_,output_index:y,content_index:0,text:R};let V={id:_,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:R}],status:"completed"};yield{type:"response.output_item.done",output_index:y,item:V},f(y,V),R=""}let O=!1,I=0,C="",T=0,j="",W="";function*K(V){if(!O)return;O=!1,yield{type:"response.output_text.done",item_id:C,output_index:I,content_index:0,text:j},yield{type:"response.content_part.done",item_id:C,output_index:I,content_index:0,part:{type:"output_text",text:j}};let M={id:C,type:"message",role:"assistant",status:V,content:[{type:"output_text",text:j}]};yield{type:"response.output_item.done",output_index:I,item:M},f(I,M),j=""}let oe=new dt,te=null,Be=-1;function*se(V){if(!te)return;let M=te;te=null,yield{type:"response.function_call_arguments.done",item_id:M.fcId,output_index:M.outputIndex,arguments:M.args};let ee={id:M.fcId,type:"function_call",call_id:M.callId??M.fcId,name:M.name??"",arguments:M.args,status:V};yield{type:"response.output_item.done",output_index:M.outputIndex,item:ee},f(M.outputIndex,ee)}let ve=!1;for await(let V of l.track(e,o,t.turn)){d.push(V);let M=String(V.type??"");if(M==="response.created"||M==="response.in_progress"){h=!0,yield c(V);continue}if(M==="response.output_item.added"){g=!0,yield c(V);continue}if(M==="response.reasoning_text.delta"&&!g){yield*P(),m||(m=!0,y=k++,v+=1,_=v===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${v}`,yield{type:"response.output_item.added",output_index:y,item:{id:_,type:"reasoning",summary:[],content:[],status:"in_progress"}}),R+=String(V.delta??""),yield{type:"response.reasoning_text.delta",item_id:_,output_index:y,content_index:0,delta:V.delta};continue}if(M==="response.output_text.delta"&&!g){yield*P(),yield*E(),O||(O=!0,I=k++,T+=1,C=T===1?p:`${p}_${T}`,yield{type:"response.output_item.added",output_index:I,item:{id:C,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:C,output_index:I,content_index:0,part:{type:"output_text",text:""}}),j+=String(V.delta??""),W+=String(V.delta??""),yield{type:M,item_id:C,output_index:I,content_index:0,delta:V.delta};continue}let ee=g?null:Dt(V);if(ee){if(yield*P(),yield*E(),yield*K("completed"),oe.add(ee),ee.tool_index!==Be){yield*se("completed"),Be=ee.tool_index;let Qe=k++;te={fcId:`fc_${r.slice(5)}_${ee.tool_index}`,outputIndex:Qe,callId:ee.call_id,name:ee.name,args:""},yield{type:"response.output_item.added",output_index:Qe,item:{id:te.fcId,type:"function_call",call_id:te.callId??te.fcId,name:te.name??"",arguments:"",status:"in_progress"}}}te&&(ee.call_id&&(te.callId=ee.call_id),ee.name&&(te.name=ee.name),te.args+=ee.delta,yield{type:"response.function_call_arguments.delta",item_id:te.fcId,output_index:te.outputIndex,delta:ee.delta});continue}if(M==="response.completed"&&!g){let Qe=Ut(V.response),ne=Rt(s,oe.size+Qe.length,W);if(ne){ve=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:kt(o,ne)}};break}if(yield*E(),yield*K("completed"),yield*se("completed"),oe.size===0)for(let ue of Qe){let Ae=k++,Ze=ue.id??ue.call_id??`fc_${Ae}`,Oe=ue.arguments??"",en={id:Ze,type:"function_call",call_id:ue.call_id??Ze,name:ue.name??""};yield{type:"response.output_item.added",output_index:Ae,item:{...en,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Ze,output_index:Ae,delta:Oe},yield{type:"response.function_call_arguments.done",item_id:Ze,output_index:Ae,arguments:Oe};let et={...en,arguments:Oe,status:"completed"};yield{type:"response.output_item.done",output_index:Ae,item:et},f(Ae,et)}let re=fc(b,V.response);yield re.length>0?c({...V,response:{...V.response,output:re}}):c(V);continue}yield c(V)}if(yield*E(),yield*K("incomplete"),yield*se("incomplete"),i&&!ve){let V=Ye(d);u.remember(r,n,wo(V,Ft(d,V)),a)}}x();x();var Ue=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},be=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};x();var ct=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)}},yn=class extends ct{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},vo=class extends ct{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},je=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Zn=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(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.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}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,generation:0,dead:!1};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.dead=!1,e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new yn;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new yn;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening);if(!s&&(i||a)&&this.slots.length<this.opts.max){this.openForDemand();continue}let u=r+n-Date.now();if(u<=0)throw new vo(n,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,u)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new yn}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening);(r||o)&&this.openForDemand()}return 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 s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let a=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);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())}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(),e+=1}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,s)=>o+s.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(s=>{r=s});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();var bo=require("@urun-sh/core"),qe=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)}},So=33e4;function ra(t,e=So){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new er),e),a;try{a=await Promise.race([r.next(),s])}catch(l){throw l instanceof X||l instanceof bo.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof er?(await r.return?.(void 0),new qe("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 qe("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new qe("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var er=class extends Error{constructor(){super("stream idle timeout")}};function oa(t){return t instanceof qe?!1:t instanceof X?!0:t instanceof bo.SessionFailedError?t.kind==="transport-failed":!1}var yc=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function Ve(t){return!yc.some(e=>e.test(t))}function We(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function Le(t,e){if(t instanceof X)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=sa(t);return n||{message:We(e?.inferenceId??null),redacted:!0}}function sa(t){return t instanceof it?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof ce?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof Z?{message:t.message,redacted:!1}:t instanceof Ue?{message:t.message,redacted:!1}:t instanceof ct?{message:t.message,redacted:!1}:t instanceof qe?Ve(t.message)?{message:t.message,redacted:!1}:null:t instanceof je?{message:t.message,redacted:!1}:t instanceof be?{message:t.message,redacted:!1}:null}function Ht(t,e,n){let r=n??(i=>console.error(i)),o=sa(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ge(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Ve(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ge(e)}`),`the ${t} upstream failed while serving this request`)}function Xe(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Ve(e)?e:null}function Ge(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var xo="/v1/responses",wc=64*1024*1024,_c=8*1024*1024,vc=16,ia=32,aa=3600*1e3,bc=/^[A-Za-z0-9._-]{1,256}$/;function Ee(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Sc=Ee(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function Eo(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function kc(t){for(;t.bufferedAmount>_c&&t.readyState===pt.WebSocket.OPEN;){let{promise:e,resolve:n}=Eo();setTimeout(n,5),await e}}var ko=class extends Nt{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 St))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},Ro=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new ko(gn(n)),e.on("message",(a,u)=>this.onMessage(a,u)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(Ee(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${aa/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},aa).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(Ee(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(Ee(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(Ee(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(Ee(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(Ee(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(Ee(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!bc.test(o.stream_id)){this.sendFrame(Sc);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=ia){this.sendFrame(Ee(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${ia}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=fn();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await hn({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:mn(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let a of i){if(this.closed||this.ws.readyState!==pt.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await kc(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=fn(),o=mn(r);try{let s=Bt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:Ge(e);if(e instanceof Ne)return Ee(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof Z)return Ee(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof X){let a=Le(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),Ee(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),Ee(s.status,{type:s.openaiType,message:o},n);let i=Le(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),Ee(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Xe(o),a=i??We(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),Ee(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=vc;){let{promise:e,resolve:n}=Eo();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!==pt.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!==pt.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function tr(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
17
+ `),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}x();var ft=require("ws");x();x();var ea=require("crypto"),ta="Inference-Id";function fn(){return(0,ea.randomUUID)()}function _o(t){return t==="/v1"||t.startsWith("/v1/")}function na(t,e){if(!_o(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 mn(t){return`resp_${t}`}function ra(t){return`chatcmpl-${t}`}function oa(t){return`msg_${t}`}function Ne(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function sa(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function ia(t){return`${JSON.stringify(t)}
18
+ `}var fc=256,mc=128;function Pe(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,mc)}var St=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>=fc?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},gc=256;function hc(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 kt=class extends Error{},Ut=class{conversations=new Map;thread(e,n){let r=hc(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new kt(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=gc)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},aa=new WeakMap;function gn(t){let e=aa.get(t);return e||(e=new Ut,aa.set(t,e)),e}function Dt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Xe(t){return t.find(e=>e.type==="response.completed")?.response??null}function Ft(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 ct=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}))}},yc=["<tool_call>","<function="];function wc(t){return yc.find(e=>t.includes(e))}function Rt(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 xt(t,e,n){if(!(!t||e>0))return wc(n)}function Bt(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 ot(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function _c(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 vo(t,e){let n=_c(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var Ue=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Ht(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof kt?new Ue(n.message,"previous_response_not_found",400,"previous_response_id"):new Ue(String(n instanceof Error?n.message:n),"invalid_input")}}function ua(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function bo(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new Ue("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...ua(e)!==void 0?{response_format:ua(e)}:{}},o)}async function hn(t){let{body:e,clients:n,store:r,stats:o}=t,s=Ht(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,l=Pe(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await bo(n,e,s,!0,c?Ne(c):void 0);return{responseId:i,events:kc({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function vc(t,e){let n=[...t].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),s=n.filter(u=>u.type==="message").length===o.length,i=0;return[...n.map(u=>u.type==="message"&&s?Sc(o[i++],u):u),...bc(r,n)]}function bc(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),s=e.filter(l=>l.type==="function_call"),i=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=s.length===i,u=new Set(s.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!u.has(o(d)):!0})}function Sc(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*kc(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:l}=t,d=[],c=W=>W.response&&typeof W.response=="object"?{...W,response:{...W.response,id:r}}:W,p=`item_${r.slice(5)}`,h=!1,g=!1,v=0;function*I(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let b=[],f=(W,M)=>{b.push({output_index:W,item:M})},m=!1,y=0,S="",P=0,_="";function*E(){if(!m)return;m=!1,yield{type:"response.reasoning_text.done",item_id:S,output_index:y,content_index:0,text:_};let W={id:S,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:_}],status:"completed"};yield{type:"response.output_item.done",output_index:y,item:W},f(y,W),_=""}let O=!1,R=0,C="",T=0,D="",V="";function*J(W){if(!O)return;O=!1,yield{type:"response.output_text.done",item_id:C,output_index:R,content_index:0,text:D},yield{type:"response.content_part.done",item_id:C,output_index:R,content_index:0,part:{type:"output_text",text:D}};let M={id:C,type:"message",role:"assistant",status:W,content:[{type:"output_text",text:D}]};yield{type:"response.output_item.done",output_index:R,item:M},f(R,M),D=""}let oe=new ct,te=null,Be=-1;function*se(W){if(!te)return;let M=te;te=null,yield{type:"response.function_call_arguments.done",item_id:M.fcId,output_index:M.outputIndex,arguments:M.args};let ee={id:M.fcId,type:"function_call",call_id:M.callId??M.fcId,name:M.name??"",arguments:M.args,status:W};yield{type:"response.output_item.done",output_index:M.outputIndex,item:ee},f(M.outputIndex,ee)}let be=!1;for await(let W of l.track(e,o,t.turn)){d.push(W);let M=String(W.type??"");if(M==="response.created"||M==="response.in_progress"){h=!0,yield c(W);continue}if(M==="response.output_item.added"){g=!0,yield c(W);continue}if(M==="response.reasoning_text.delta"&&!g){yield*I(),m||(m=!0,y=v++,P+=1,S=P===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${P}`,yield{type:"response.output_item.added",output_index:y,item:{id:S,type:"reasoning",summary:[],content:[],status:"in_progress"}}),_+=String(W.delta??""),yield{type:"response.reasoning_text.delta",item_id:S,output_index:y,content_index:0,delta:W.delta};continue}if(M==="response.output_text.delta"&&!g){yield*I(),yield*E(),O||(O=!0,R=v++,T+=1,C=T===1?p:`${p}_${T}`,yield{type:"response.output_item.added",output_index:R,item:{id:C,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:C,output_index:R,content_index:0,part:{type:"output_text",text:""}}),D+=String(W.delta??""),V+=String(W.delta??""),yield{type:M,item_id:C,output_index:R,content_index:0,delta:W.delta};continue}let ee=g?null:Ft(W);if(ee){if(yield*I(),yield*E(),yield*J("completed"),oe.add(ee),ee.tool_index!==Be){yield*se("completed"),Be=ee.tool_index;let Ze=v++;te={fcId:`fc_${r.slice(5)}_${ee.tool_index}`,outputIndex:Ze,callId:ee.call_id,name:ee.name,args:""},yield{type:"response.output_item.added",output_index:Ze,item:{id:te.fcId,type:"function_call",call_id:te.callId??te.fcId,name:te.name??"",arguments:"",status:"in_progress"}}}te&&(ee.call_id&&(te.callId=ee.call_id),ee.name&&(te.name=ee.name),te.args+=ee.delta,yield{type:"response.function_call_arguments.delta",item_id:te.fcId,output_index:te.outputIndex,delta:ee.delta});continue}if(M==="response.completed"&&!g){let Ze=Dt(W.response),ne=xt(s,oe.size+Ze.length,V);if(ne){be=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Rt(o,ne)}};break}if(yield*E(),yield*J("completed"),yield*se("completed"),oe.size===0)for(let ue of Ze){let Ie=v++,et=ue.id??ue.call_id??`fc_${Ie}`,Te=ue.arguments??"",en={id:et,type:"function_call",call_id:ue.call_id??et,name:ue.name??""};yield{type:"response.output_item.added",output_index:Ie,item:{...en,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:et,output_index:Ie,delta:Te},yield{type:"response.function_call_arguments.done",item_id:et,output_index:Ie,arguments:Te};let tt={...en,arguments:Te,status:"completed"};yield{type:"response.output_item.done",output_index:Ie,item:tt},f(Ie,tt)}let re=vc(b,W.response);yield re.length>0?c({...W,response:{...W.response,output:re}}):c(W);continue}yield c(W)}if(yield*E(),yield*J("incomplete"),yield*se("incomplete"),i&&!be){let W=Xe(d);u.remember(r,n,vo(W,Bt(d,W)),a)}}x();x();var De=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},Se=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};x();var pt=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)}},yn=class extends pt{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},So=class extends pt{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},je=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Zn=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(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.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}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,generation:0,dead:!1};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.dead=!1,e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new yn;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new yn;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening);if(!s&&(i||a)&&this.slots.length<this.opts.max){this.openForDemand();continue}let u=r+n-Date.now();if(u<=0)throw new So(n,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,u)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new yn}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening);(r||o)&&this.openForDemand()}return 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 s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let a=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);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())}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(),e+=1}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,s)=>o+s.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(s=>{r=s});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();var ko=require("@urun-sh/core"),qe=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)}},Ro=33e4;function la(t,e=Ro){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new er),e),a;try{a=await Promise.race([r.next(),s])}catch(l){throw l instanceof X||l instanceof ko.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof er?(await r.return?.(void 0),new qe("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 qe("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new qe("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var er=class extends Error{constructor(){super("stream idle timeout")}};function da(t){return t instanceof qe?!1:t instanceof X?!0:t instanceof ko.SessionFailedError?t.kind==="transport-failed":!1}var Rc=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function We(t){return!Rc.some(e=>e.test(t))}function Ve(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function Me(t,e){if(t instanceof X)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=ca(t);return n||{message:Ve(e?.inferenceId??null),redacted:!0}}function ca(t){return t instanceof at?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof le?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof Z?{message:t.message,redacted:!1}:t instanceof De?{message:t.message,redacted:!1}:t instanceof pt?{message:t.message,redacted:!1}:t instanceof qe?We(t.message)?{message:t.message,redacted:!1}:null:t instanceof je?{message:t.message,redacted:!1}:t instanceof Se?{message:t.message,redacted:!1}:null}function jt(t,e,n){let r=n??(i=>console.error(i)),o=ca(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ge(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&We(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ge(e)}`),`the ${t} upstream failed while serving this request`)}function Qe(t){let e=t?.message;return typeof e=="string"&&e.length>0&&We(e)?e:null}function Ge(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Ao="/v1/responses",xc=64*1024*1024,Ec=8*1024*1024,Ac=16,pa=32,fa=3600*1e3,Oc=/^[A-Za-z0-9._-]{1,256}$/;function Oe(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Ic=Oe(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 Oo(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Tc(t){for(;t.bufferedAmount>Ec&&t.readyState===ft.WebSocket.OPEN;){let{promise:e,resolve:n}=Oo();setTimeout(n,5),await e}}var xo=class extends Ut{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 kt))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},Eo=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new xo(gn(n)),e.on("message",(a,u)=>this.onMessage(a,u)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(Oe(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${fa/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},fa).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(Oe(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(Oe(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(Oe(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(Oe(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(Oe(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(Oe(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Oc.test(o.stream_id)){this.sendFrame(Ic);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=pa){this.sendFrame(Oe(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${pa}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=fn();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await hn({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:mn(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let a of i){if(this.closed||this.ws.readyState!==ft.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Tc(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=fn(),o=mn(r);try{let s=Ht(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:Ge(e);if(e instanceof Ue)return Oe(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 Oe(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof X){let a=Me(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),Oe(503,{type:"upstream_error",code:"session_gone",message:a.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),Oe(s.status,{type:s.openaiType,message:o},n);let i=Me(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),Oe(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Qe(o),a=i??Ve(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),Oe(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=Ac;){let{promise:e,resolve:n}=Oo();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!==ft.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!==ft.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function tr(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
19
19
  `;t.end(`HTTP/1.1 ${e} ${r}\r
20
20
  Connection: close\r
21
21
  Content-Type: text/plain; charset=utf-8\r
22
22
  Content-Length: ${Buffer.byteLength(o)}\r
23
23
  \r
24
- ${o}`)}function Ao(t,e){let n=new pt.WebSocketServer({noServer:!0,maxPayload:wc}),r=new bt,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,p)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{tr(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==xo){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){tr(c,401,"invalid local proxy api key");return}let k;try{k=await a(d)}catch(P){let b=e.statusOf?.(P)??null;tr(c,b?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(g=!0,n.handleUpgrade(d,c,p,P=>{s.delete(c),o.add(P),P.on("close",()=>o.delete(P));try{new Ro(P,k,r,e.statusOf,e.operatorLog??(b=>console.error(b)))}catch{o.delete(P),P.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&tr(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Eo();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let p=setTimeout(()=>{for(let h of o)h.readyState!==pt.WebSocket.CLOSED&&h.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}x();x();var Mo=require("@urun-sh/core");x();var ua=require("@urun-sh/core"),Rc={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},xc={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function wn(t,e){let n=xc[t.code];return e?`${n} (${e})`:n}function nr(t){if(t==null)return null;let e=Rc[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 rr(t){if(t.kind==="create-failed")return nr(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ua.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return nr(e?"cold_start_exceeded":"queue_timeout")}var ma=require("ws");x();var fa=require("@urun-sh/core");x();var da=require("crypto");function B(t){return`${t}_${(0,da.randomUUID)().replace(/-/g,"").slice(0,24)}`}var or=4*1024*1024,Oo=8*1024*1024,sr=512,ir=20*1024*1024;function we(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function qt(t,e){return{type:"server_error",code:t,message:e}}function ae(t){return{type:"error",event_id:B("event"),error:t}}function Io(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var q=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Ec={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Ac={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Oc={format:!0,voice:!0,speed:!0};function Ic(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function jt(t,e){if(!Array.isArray(t)||t.length===0)throw new q(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new q(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function la(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new q(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Tc=10;function To(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Tc})}function _n(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new q("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Ec));if(s.length>0)throw new q(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=jt(o.modalities,"modalities"),u=jt(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new q("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(o))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new q(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new q(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!n.turns)throw new q('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new q(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=jt(u,a);for(let d of l)if(d==="audio"&&!n.voice)throw new q('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");i.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Ic(u))throw new q(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new q("model must be a string or null","model");i.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new q("instructions must be a string or null","instructions");i.instructions=To(u??void 0)??void 0;break;case"voice":if(u===null){delete i.voice;break}if(typeof u!="string")throw new q("voice must be a string or null","voice");if(!n.voice)throw new q("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new q(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new q("temperature must be a finite number or null","temperature");i.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new q(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new q("tools must be an array","tools");i.tools=u;break;case"tool_choice":i.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new q("metadata must be an object or null","metadata");i.metadata=u??null;break;case"turn_detection":{if(u===null){i.turnDetection=null;break}if(!n.turns)throw new q("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new q("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new q(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,h]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new q(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(h!=null&&h!==c[p])throw new q(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new q("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new q("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new q(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new q(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new q("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new q("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new q("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Ac))throw new q(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&la(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=_n({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=_n({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new q("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new q("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Oc))throw new q(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&la(d.format,"audio.output.format"),d.speed!==void 0)throw new q("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete i.voice;else{if(typeof d.voice!="string")throw new q("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new q("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function ar(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 Po(t,e){let n=t;if(!n||typeof n!="object")throw new q("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 q("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:B("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 q('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new q("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new q("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new q(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new q("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new q("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new q(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:B("item"),type:"message",role:r,content:o}}throw new q(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function ur(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Pc=1001,Cc=1011,ca=t=>t.slice(0,120),Lc=/^[A-Za-z0-9+/=]*$/,Mc=2;function $c(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Mc)return!1;return!0}var vn=class{id=B("conn");ws;binding;onClosed;operatorLog;config=Io();sessionId=B("sess");conversationId=B("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:B("event"),session:ar(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:B("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof X&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(ae(qt("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:B("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:B("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:B("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:B("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:B("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:B("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:B("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:B("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=B("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:B("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:B("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:B("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:B("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(we("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>or){this.fail(we("frame_too_large",`frame exceeds the ${or}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(we("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(we("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(ae({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(qt(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=_n(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(ae(we("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:B("event"),session:ar(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Po(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.added",event_id:B("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(ae(we("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:B("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(ae(we("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:B("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(ae(we("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:B("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(ae(we("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Lc.test(e.audio)){this.send(ae(we("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>ir){this.send(ae(we("buffer_full",`uncommitted input audio exceeds the ${ir}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:B("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(ae(we("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=B("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:B("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:B("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:B("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:B("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(ae(we("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(ae(we("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(ae(we("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(ae(we("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(ae({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(ae(we("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?jt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?jt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new q("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(ae(we("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=B("req"),a=`resp_${i}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:ur(this.items),c=To(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,h=n.max_output_tokens??this.config.maxOutputTokens,g=h==="inf"||h===void 0?void 0:h,k=n.tools!==void 0?n.tools:this.config.tools,P=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,b={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...g!==void 0?{max_output_tokens:g}:{},...k!==void 0?{tools:k}:{},...P!==void 0?{tool_choice:P}:{}};if(!(u&&!this.ensureVoice())){for(let f of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(f);this.inFlight=(async()=>{let f=[],m=R=>{this.responseFlushed?this.send(R):f.push(R)},y=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:B("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:B("event"),response:this.responseObject(a,"in_progress")});for(let R of f)this.send(R);f.length=0,this.responseFlushed=!0}},_={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},v=null;try{if(u){if(this.pendingTranscriptItemId!==null&&(await new Promise(C=>{this.pendingTranscriptSettled=C}),this.cancelled||this.closed))return;l=this.items.length,d=ur(this.items)}let{input:R,sawAudioOnlyItem:E}=d??{input:[],sawAudioOnlyItem:!1},O={...b,input:R,...u?this.compositeTurnAsk(n):{}};E&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let I;try{I=await this.upstreamStream(O,i)}catch(C){this.upstreamTurnFault(C,a);return}try{for await(let C of I){if(this.cancelled)break;let T=C;if(T.type==="error"){let j=this.upstreamErrorBody(T);this.responseFlushed?this.send(ae(j)):this.send({type:"response.failed",event_id:B("event"),response:this.failedResponse(a,j)});return}if(T.type==="response.output_text.delta"&&typeof T.delta=="string"){y(),_.messageOpen||(this.beginMessageItem(a,_.nextOutputIndex++),_.messageOpen=!0),this.config.outputModalities.includes("text")&&m({type:"response.output_text.delta",event_id:B("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:T.delta}),this.turnOutputIsAudio()&&(_.transcriptDelta=!0,m({type:"response.output_audio_transcript.delta",event_id:B("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:T.delta})),_.messageText+=T.delta;continue}if(T.type==="response.function_call_arguments.delta"){y();let j=typeof T.delta=="string"?T.delta:"",W=typeof T.call_id=="string"&&T.call_id.length>0?T.call_id:`${a}_fc_${_.nextOutputIndex}`,K=_.tools.get(W);if(!K){let oe=typeof T.name=="string"&&T.name.length>0?T.name:void 0;K={outputIndex:_.nextOutputIndex++,name:oe,args:""},_.tools.set(W,K);let te={id:W,object:"realtime.item",type:"function_call",call_id:W,name:oe??"",arguments:"",status:"in_progress"};m({type:"response.output_item.added",event_id:B("event"),response_id:a,output_index:K.outputIndex,item:te}),this.emitAssistantItemAdded(te)}typeof T.name=="string"&&T.name.length>0&&(K.name=T.name),K.args+=j,m({type:"response.function_call_arguments.delta",event_id:B("event"),item_id:W,response_id:a,output_index:K.outputIndex,call_id:W,name:K.name??"",delta:j});continue}if(T.type==="response.completed"){v=T.response??null;continue}}}catch(C){this.upstreamTurnFault(C,a);return}if(this.cancelled)return;this.closeOpenItems(a,_,l),y(),this.send({type:"response.done",event_id:B("event"),response:this.doneResponse(a,l,v)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if($c(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(ae({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:B("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:B("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:B("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:B("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:B("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:B("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:B("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:B("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:B("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:B("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:B("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:B("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:B("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let u=[];s&&u.push({type:"output_audio",transcript:a}),n.messageText.length>0&&u.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:B("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:B("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:B("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=Xe(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??We(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&Ve(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Ge(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(qt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof X){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof fa.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=qt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(ae(r)):this.send({type:"response.failed",event_id:B("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(ae(we("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:B("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>sr&&(this.items.shift(),this.send(ae({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${sr} 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>Oo){this.ws.close(Pc,ca("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=Le(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ge(e)}`),r.message}fail(e,n){this.send(ae(e)),this.ws.close(Cc,ca(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>pa(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),pa(this.id,e)}},Co=[];function pa(t,e){Co.push({id:t,reason:e}),Co.length>256&&Co.shift()}var bn="/v1/realtime",Nc=t=>t.slice(0,120);function Uc(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
24
+ ${o}`)}function Io(t,e){let n=new ft.WebSocketServer({noServer:!0,maxPayload:xc}),r=new St,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,p)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{tr(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==Ao){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){tr(c,401,"invalid local proxy api key");return}let v;try{v=await a(d)}catch(I){let b=e.statusOf?.(I)??null;tr(c,b?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(g=!0,n.handleUpgrade(d,c,p,I=>{s.delete(c),o.add(I),I.on("close",()=>o.delete(I));try{new Eo(I,v,r,e.statusOf,e.operatorLog??(b=>console.error(b)))}catch{o.delete(I),I.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&tr(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Oo();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let p=setTimeout(()=>{for(let h of o)h.readyState!==ft.WebSocket.CLOSED&&h.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}x();x();var No=require("@urun-sh/core");x();var ma=require("@urun-sh/core"),Pc={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},Cc={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function wn(t,e){let n=Cc[t.code];return e?`${n} (${e})`:n}function nr(t){if(t==null)return null;let e=Pc[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 rr(t){if(t.kind==="create-failed")return nr(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ma.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return nr(e?"cold_start_exceeded":"queue_timeout")}var va=require("ws");x();var _a=require("@urun-sh/core");x();var ha=require("crypto");function H(t){return`${t}_${(0,ha.randomUUID)().replace(/-/g,"").slice(0,24)}`}var or=4*1024*1024,To=8*1024*1024,sr=512,ir=20*1024*1024;function _e(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Gt(t,e){return{type:"server_error",code:t,message:e}}function ae(t){return{type:"error",event_id:H("event"),error:t}}function Po(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var q=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Lc={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Mc={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},$c={format:!0,voice:!0,speed:!0};function Nc(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function qt(t,e){if(!Array.isArray(t)||t.length===0)throw new q(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new q(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function ga(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new q(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Uc=10;function Co(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Uc})}function _n(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new q("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Lc));if(s.length>0)throw new q(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=qt(o.modalities,"modalities"),u=qt(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new q("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(o))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new q(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new q(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!n.turns)throw new q('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new q(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=qt(u,a);for(let d of l)if(d==="audio"&&!n.voice)throw new q('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");i.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Nc(u))throw new q(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new q("model must be a string or null","model");i.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new q("instructions must be a string or null","instructions");i.instructions=Co(u??void 0)??void 0;break;case"voice":if(u===null){delete i.voice;break}if(typeof u!="string")throw new q("voice must be a string or null","voice");if(!n.voice)throw new q("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new q(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new q("temperature must be a finite number or null","temperature");i.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new q(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new q("tools must be an array","tools");i.tools=u;break;case"tool_choice":i.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new q("metadata must be an object or null","metadata");i.metadata=u??null;break;case"turn_detection":{if(u===null){i.turnDetection=null;break}if(!n.turns)throw new q("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new q("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new q(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,h]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new q(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(h!=null&&h!==c[p])throw new q(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new q("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new q("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new q(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new q(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new q("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new q("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new q("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Mc))throw new q(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&ga(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=_n({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=_n({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new q("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new q("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in $c))throw new q(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&ga(d.format,"audio.output.format"),d.speed!==void 0)throw new q("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete i.voice;else{if(typeof d.voice!="string")throw new q("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new q("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function ar(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 Lo(t,e){let n=t;if(!n||typeof n!="object")throw new q("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 q("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:H("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 q('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new q("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new q("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new q(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new q("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new q("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new q(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:H("item"),type:"message",role:r,content:o}}throw new q(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function ur(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var Dc=1001,Fc=1011,ya=t=>t.slice(0,120),Bc=/^[A-Za-z0-9+/=]*$/,Hc=2;function jc(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Hc)return!1;return!0}var vn=class{id=H("conn");ws;binding;onClosed;operatorLog;config=Po();sessionId=H("sess");conversationId=H("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:H("event"),session:ar(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:H("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof X&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(ae(Gt("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:H("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:H("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:H("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:H("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:H("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:H("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:H("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:H("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=H("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:H("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:H("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:H("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:H("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(_e("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>or){this.fail(_e("frame_too_large",`frame exceeds the ${or}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(_e("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(_e("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(ae({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Gt(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=_n(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(ae(_e("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:H("event"),session:ar(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Lo(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.added",event_id:H("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(ae(_e("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:H("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(ae(_e("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:H("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(ae(_e("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:H("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(ae(_e("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Bc.test(e.audio)){this.send(ae(_e("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>ir){this.send(ae(_e("buffer_full",`uncommitted input audio exceeds the ${ir}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:H("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(ae(_e("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=H("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:H("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:H("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:H("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:H("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(ae(_e("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(ae(_e("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(ae(_e("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(ae(_e("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(ae({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(ae(_e("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?qt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?qt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new q("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(ae(_e("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=H("req"),a=`resp_${i}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:ur(this.items),c=Co(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,h=n.max_output_tokens??this.config.maxOutputTokens,g=h==="inf"||h===void 0?void 0:h,v=n.tools!==void 0?n.tools:this.config.tools,I=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,b={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...g!==void 0?{max_output_tokens:g}:{},...v!==void 0?{tools:v}:{},...I!==void 0?{tool_choice:I}:{}};if(!(u&&!this.ensureVoice())){for(let f of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(f);this.inFlight=(async()=>{let f=[],m=_=>{this.responseFlushed?this.send(_):f.push(_)},y=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:H("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:H("event"),response:this.responseObject(a,"in_progress")});for(let _ of f)this.send(_);f.length=0,this.responseFlushed=!0}},S={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},P=null;try{if(u){if(this.pendingTranscriptItemId!==null&&(await new Promise(C=>{this.pendingTranscriptSettled=C}),this.cancelled||this.closed))return;l=this.items.length,d=ur(this.items)}let{input:_,sawAudioOnlyItem:E}=d??{input:[],sawAudioOnlyItem:!1},O={...b,input:_,...u?this.compositeTurnAsk(n):{}};E&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let R;try{R=await this.upstreamStream(O,i)}catch(C){this.upstreamTurnFault(C,a);return}try{for await(let C of R){if(this.cancelled)break;let T=C;if(T.type==="error"){let D=this.upstreamErrorBody(T);this.responseFlushed?this.send(ae(D)):this.send({type:"response.failed",event_id:H("event"),response:this.failedResponse(a,D)});return}if(T.type==="response.output_text.delta"&&typeof T.delta=="string"){y(),S.messageOpen||(this.beginMessageItem(a,S.nextOutputIndex++),S.messageOpen=!0),this.config.outputModalities.includes("text")&&m({type:"response.output_text.delta",event_id:H("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:T.delta}),this.turnOutputIsAudio()&&(S.transcriptDelta=!0,m({type:"response.output_audio_transcript.delta",event_id:H("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:T.delta})),S.messageText+=T.delta;continue}if(T.type==="response.function_call_arguments.delta"){y();let D=typeof T.delta=="string"?T.delta:"",V=typeof T.call_id=="string"&&T.call_id.length>0?T.call_id:`${a}_fc_${S.nextOutputIndex}`,J=S.tools.get(V);if(!J){let oe=typeof T.name=="string"&&T.name.length>0?T.name:void 0;J={outputIndex:S.nextOutputIndex++,name:oe,args:""},S.tools.set(V,J);let te={id:V,object:"realtime.item",type:"function_call",call_id:V,name:oe??"",arguments:"",status:"in_progress"};m({type:"response.output_item.added",event_id:H("event"),response_id:a,output_index:J.outputIndex,item:te}),this.emitAssistantItemAdded(te)}typeof T.name=="string"&&T.name.length>0&&(J.name=T.name),J.args+=D,m({type:"response.function_call_arguments.delta",event_id:H("event"),item_id:V,response_id:a,output_index:J.outputIndex,call_id:V,name:J.name??"",delta:D});continue}if(T.type==="response.completed"){P=T.response??null;continue}}}catch(C){this.upstreamTurnFault(C,a);return}if(this.cancelled)return;this.closeOpenItems(a,S,l),y(),this.send({type:"response.done",event_id:H("event"),response:this.doneResponse(a,l,P)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(jc(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(ae({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:H("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:H("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:H("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:H("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:H("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:H("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:H("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:H("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:H("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:H("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:H("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:H("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:H("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let u=[];s&&u.push({type:"output_audio",transcript:a}),n.messageText.length>0&&u.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:H("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:H("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:H("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=Qe(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??Ve(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&We(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Ge(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Gt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof X){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof _a.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Gt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(ae(r)):this.send({type:"response.failed",event_id:H("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(ae(_e("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:H("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>sr&&(this.items.shift(),this.send(ae({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${sr} 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>To){this.ws.close(Dc,ya("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=Me(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ge(e)}`),r.message}fail(e,n){this.send(ae(e)),this.ws.close(Fc,ya(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>wa(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),wa(this.id,e)}},Mo=[];function wa(t,e){Mo.push({id:t,reason:e}),Mo.length>256&&Mo.shift()}var bn="/v1/realtime",qc=t=>t.slice(0,120);function Gc(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
25
25
  Connection: close\r
26
26
  Content-Type: text/plain\r
27
27
  \r
28
- ${Nc(n)}\r
29
- `),t.destroy()}function Dc(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
30
- `}function Fc(t){ze(process.stdout,t)}function Bc(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Lo(t){return t.audioSession?.audio.sessionId??void 0}function lr(t,e){let n=new ma.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==bn)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=B("rtup"),l=Bc(o),d=_=>{(e.log??Fc)(Dc(_))};d({stage:"accept",conn:u,model:l}),s.resume();let c=new AbortController,p=null,h=_=>{p??=_,c.abort(new Error(p))},g=()=>h("client socket closed"),k=()=>h("client socket closed (half-close)"),P=_=>h(`client socket error: ${_.message}`);s.once("close",g),s.once("end",k),s.once("error",P);let b=()=>{s.removeListener("close",g),s.removeListener("end",k),s.removeListener("error",P)},f=_=>{d({stage:"close",conn:u,model:l,..._})},m=_=>{let v=_,R=v.session!=null&&typeof v.session.sendResponseCreate=="function",E=v.clients!=null&&typeof v.clients.createResponse=="function";if(!R&&!E)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((O,I)=>{n.handleUpgrade(o,s,i,C=>{try{new vn({ws:C,binding:_,operatorLog:e.operatorLog,onClosed:(T,j)=>{f({while:"live",reason:j.reason})}}),d({stage:"admit",conn:u,model:l,...Lo(_)===void 0?{}:{session:Lo(_)}}),O()}catch(T){I(T)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async _=>{if(c.signal.aborted){b();let v=Lo(_);try{await _.release?.()}catch(R){f({while:"queued",...v===void 0?{}:{session:v},reason:p??"client socket closed",release_failed:R instanceof Error?R.message:String(R)});return}f({while:"queued",...v===void 0?{}:{session:v},reason:p??"client socket closed",released:!0}),s.destroy();return}b(),await m(_)}).catch(_=>{let v=_ instanceof Mo.SessionFailedError?rr(_):null,R=null;if(_!==null&&typeof _=="object"&&"status"in _){let C=_.status;typeof C=="number"&&(R=C)}let E=R??v?.status??502,O=_ instanceof Error?_.message:String(_),I=R!==null?O:v!==null?wn(v,_ instanceof Mo.SessionFailedError&&_.status.sessionId?`session ${_.status.sessionId}`:void 0):Le(_).message;f({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:O,status:E}}),s.destroyed||Uc(s,E,I)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}x();var eu=require("crypto");x();var pp=require("http");x();x();var Se=class extends Error{};async function dr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Se(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new Se(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function cr(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new Se(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")i.set(l,d);else if(Array.isArray(d))for(let c of d)i.append(l,c);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof Se?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var ga="/v1/images/generations",pr="/v1/images/edits";function ha(t){return t===ga||t===pr}var ya="/v1/images/models";async function wa(t,e,n){if(t){if(t.model=Ie({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 Q=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Hc=16*1024*1024,_a=64*1024*1024;function va(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 Sn(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 ba(t,e,n,r,o,s){let i=s??(g=>console.error(g)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),u=null;for await(let g of a){if(g.type==="error"){let k=g.error??{},P=typeof k.message=="string"&&k.message.length>0&&Ve(k.message)?k.message:null;throw P===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(g)}`),new Q(502,"the image upstream failed while serving this request")):new Q(502,`image upstream error: ${P}`)}if(g.type==="response.completed"){u=g.response??null;break}}if(u===null)throw new Q(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=rt(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new Q(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(va(p)===null)throw new Q(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function Sa(t,e){if(t instanceof Q)return t;if(t instanceof Ue)throw t;return t instanceof Z?new Q(404,t.message):new Q(502,Ht("image",t,e))}async function ka(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 Sn(r,new Q(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 Ra(t,e){t&&(t.outputUnits=e.images.length)}function xa(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 jc={model:!0,prompt:!0,response_format:!0,n:!0};async function Ea(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??_a;try{if(t.method!=="POST")throw new Q(405,`${String(t.method)} is not supported on ${ga}`);let s;try{s=JSON.parse((await dr(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof Se?new Q(413,p.message):new Q(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new Q(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!jc[p])throw new Q(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let a=i.prompt;if(typeof a!="string"||a.trim().length===0)throw new Q(400,"prompt is required and must be a non-empty string","prompt");let u=i.model===void 0?void 0:i.model;if(u!==void 0&&typeof u!="string")throw new Q(400,"model must be a string","model");await wa(n.turn,n.clients,u);let l=i.n??1;if(l!==1)throw new Q(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new Q(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",a.length,a.length),!await ka(n.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await ba(n.clients,u,c,n.turn?$e(n.turn):void 0,n.turn,r);Ra(n.turn,p),xa(e,p)}catch(p){throw Sa(p,r)}}catch(s){if(s instanceof Se){Sn(e,new Q(413,s.message));return}if(s instanceof Q){Sn(e,s);return}throw s}}var qc={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Aa(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??_a,s=n.maxImagePartBytes??Hc;try{if(t.method!=="POST")throw new Q(405,`${String(t.method)} is not supported on ${pr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new Q(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await cr(t,o)}catch(g){throw g instanceof Se?new Q(413,g.message):new Q(400,String(g instanceof Error?g.message:g))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new Q(400,"prompt is required and must be a non-empty string field","prompt");let l=a.get("model");if(l!==null&&typeof l!="string")throw new Q(400,"model must be a string field","model");let d=l===null?void 0:l;await wa(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new Q(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let g of a.keys())if(!qc[g])throw new Q(400,`form field "${g}" 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[]).`,g);let p=[];for(let g of["image","image[]"])for(let k of a.getAll(g)){if(!(k instanceof File))throw new Q(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",g);if(k.size>s)throw new Q(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,g);let P=new Uint8Array(await k.arrayBuffer()),b=va(P);if(b===null)throw new Q(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",g);p.push({bytes:P,mime:b})}if(p.length===0)throw new Q(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await ka(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:u}];for(let{bytes:g,mime:k}of p)h.push({type:"input_image",image_url:`data:${k};base64,${Buffer.from(g).toString("base64")}`});try{let g=await ba(n.clients,d,h,n.turn?$e(n.turn):void 0,n.turn,r);Ra(n.turn,g),xa(e,g)}catch(g){throw Sa(g,r)}}catch(i){if(i instanceof Se){Sn(e,new Q(413,i.message));return}if(i instanceof Q){Sn(e,i);return}throw i}}x();var kn="/v1/audio/speech";function Na(t){return t===kn}var Oa=4096,Ia=18e4,Ta=5e3,Gc=64*1024*1024,Pa=8,Ca=5,La=1024*1024,Gt="voice_applied",mr="X-Urun-Voice-Applied",J=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function $o(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 gr=class extends J{constructor(e){super(502,e)}};function Ua(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 Da(t){return new J(502,`the runtime's ${Gt} receipt ${JSON.stringify(t)} cannot be relayed as the ${mr} 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 Vc(t,e,n){if(t){if(t.model=Ie({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 Fa(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Wc=2;function Jc(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Wc)return!1;return!0}function Kc(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 Ma=new WeakMap,fr=new WeakMap;function zc(t,e){let n=fr.get(t)??0;if(n>=Pa)throw new J(503,`this model's speech queue is full \u2014 ${Pa} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Ca}s`,void 0,Ca);fr.set(t,n+1);let r=Ma.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Ma.set(t,s),(async()=>{await r;try{return await e()}finally{fr.set(t,(fr.get(t)??1)-1),o()}})()}async function Yc(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new J(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof X))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function xt(t,e){if(t instanceof J)return t;if(t instanceof Ue)throw t;return t instanceof Z?new J(404,t.message):new J(502,Ht("speech",t,e))}async function $a(t,e,n,r,o,s,i,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return zc(e,async()=>{if(i?.()===!0)return null;let p=!1,h=!1,g=!1,k,P=new Promise(E=>{k=E}),b=[],f=()=>{h&&!g&&b.length>=o.quietRunFrames&&(g=!0,k())},m=e.onOutputAudio(E=>{let O=Buffer.from(E,"base64");if(O.byteLength===0)return;let I=Jc(O);if(!p){if(I)return;p=!0}if(I){b.push(O),f();return}for(let C of b)c(C);b.length=0,c(O),f()}),y=null,_,v,R;try{R=(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 O=new Promise(T=>{v=setTimeout(T,s.capMs)}),I=!1;for(;;){let T=R.next(),j=await Promise.race([T,O]);if(j===void 0){I=!0,T.catch(()=>{});break}if(j.done)break;let W=j.value;if(W.type==="error"){let K=W.error??{};await R.return?.();let oe=typeof K.message=="string"&&K.message.length>0&&Ve(K.message)?K.message:null;throw oe===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(W)}`),new J(502,"the speech upstream failed while serving this request")):new J(502,`speech upstream error: ${oe}`)}if(W.type==="response.completed"){y=W.response??null,h=!0,u?.(y),f(),await R.return?.();break}}if(clearTimeout(v),I)throw new J(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(y===null)throw new J(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let C=!1;if(await Promise.race([P,new Promise(T=>{_=setTimeout(()=>{C=!0,T()},o.capMs)})]),_!==void 0&&clearTimeout(_),r.voice!==void 0){let T=y[Gt];if(typeof T!="string"||T!==r.voice){let j=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof T=="string"?`${Gt} ${JSON.stringify(T)}`:`no ${Gt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw g?new gr(j):new J(502,j)}}if(!p)throw new J(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(C&&!g&&b.length<1)throw new J(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return y}catch(E){throw E instanceof gr||await Yc(t,n,R,s.returnBoundMs),E}finally{_!==void 0&&clearTimeout(_),v!==void 0&&clearTimeout(v),m()}})}function Xc(t,e,n,r){let o=!1,s=0,i=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",mr)),t.write(a,u=>{u||(s+=a.byteLength,Fa(e,s))}),t.writableLength>La&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${La} 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[Gt];if(typeof u=="string"){if(!Ua(u))throw Da(u);t.addTrailers({[mr]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:i}}async function Qc(t,e,n,r){let o;try{o=await t(e)}catch(s){throw xt(s,r)}return o?!0:($o(n,new J(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 Zc={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},ep="wav, pcm";async function Ba(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??Gc,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new J(405,`${String(t.method)} is not supported on ${kn}`);let a;try{a=JSON.parse((await dr(t,o)).toString("utf8")||"{}")}catch(y){throw y instanceof Se?new J(413,y.message):new J(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new J(400,"request body must be a JSON object");let u=a;for(let y of Object.keys(u))if(!Zc[y])throw new J(400,`request field "${y}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,y);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new J(400,"input is required and must be a non-empty string","input");if(l.length>Oa)throw new J(400,`input is ${l.length} chars \u2014 over the ${Oa}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=u.model===void 0?void 0:u.model;if(d!==void 0&&typeof d!="string")throw new J(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new J(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new J(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 ${kn} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(y){throw xt(y,r)}if(p.defect!==null)throw new J(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let h=typeof c=="string"?c:void 0;if(h!==void 0&&p.published.length>0&&!p.published.includes(h))throw new J(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let g=u.response_format??"wav";if(g!=="wav"&&g!=="pcm")throw new J(400,`response_format ${JSON.stringify(g)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${ep} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new J(400,"stream_format, when present, must be a string","stream_format");let k=u.speed;if(k!==void 0){if(typeof k!="number"||!Number.isFinite(k))throw new J(400,"speed, when present, must be a number","speed");if(k!==1)throw new J(400,`speed=${JSON.stringify(k)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let P=u.instructions;if(P!==void 0){if(typeof P!="string")throw new J(400,"instructions, when present, must be a string","instructions");if(P.trim().length>0)throw new J(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 Vc(n.turn,n.clients,d);let b=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",b,b),!await Qc(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new J(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 J(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 J(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 f;try{f=await n.clients.speechSessionHandle(d)}catch(y){throw xt(y,r)}let m;try{m=await n.clients.openAudioOn(f)}catch(y){throw xt(y,r)}n.turn&&(n.turn.sessionId=m.sessionId);try{if(g==="wav"){let y=[],_=await $a(n.clients,m,f,{model:d,text:l,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ia,returnBoundMs:n.turnReturnBoundMs??Ta},i,R=>y.push(R),R=>{n.turn&&(n.turn.outputSeconds=rt(R))},r);if(_===null||i())return;let v=Buffer.concat(y);if(h===void 0){let R=_[Gt];if(typeof R=="string"){if(!Ua(R))throw Da(R);e.setHeader(mr,R)}}Fa(n.turn,v.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Kc(v.byteLength),v]))}else{let y=Xc(e,n.turn,i,h===void 0),_;try{_=await $a(n.clients,m,f,{model:d,text:l,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ia,returnBoundMs:n.turnReturnBoundMs??Ta},i,y.sink,v=>{n.turn&&(n.turn.outputSeconds=rt(v))},r)}catch(v){let R=xt(v,r);if(!y.started())throw R;n.turn&&(n.turn.streamError=!0),y.fail(R);return}if(_===null)return;try{await y.finish(_)}catch(v){let R=xt(v,r);n.turn&&(n.turn.streamError=!0),y.fail(R);return}}}catch(y){throw xt(y,r)}}catch(a){if(a instanceof Se){$o(e,new J(413,a.message));return}if(a instanceof J){$o(e,a);return}throw a}}x();var hr="/v1/audio/transcriptions";function Ha(t){return t===hr}var ja="/v1/audio/models",tp=16*1024*1024,np=64*1024*1024,le=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function No(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 qa(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 rp(t){if(!qa(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(s==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,l=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:l,channels:u,bitsPerSample:d}}else if(s==="data"){let u=t.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function op(t,e,n){if(t){if(t.model=Ie({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 sp(t,e){t&&(t.outputUnits=e.seconds)}async function ip(t,e,n,r,o,s,i){let a=i??(c=>console.error(c)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of u){if(l.push(c),c.type==="error"){let p=c.error??{},h=typeof p.type=="string"?p.type:"upstream_error",g=typeof p.message=="string"&&p.message.length>0&&Ve(p.message)?p.message:null;throw g===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new le(h==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new le(h==="invalid_request_error"?400:502,`transcription upstream error: ${g}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new le(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=rt(d)),Ft(l,d)}function Ga(t,e){if(t instanceof le)return t;if(t instanceof Ue)throw t;return t instanceof Z?new le(404,t.message):new le(502,Ht("transcription",t,e))}async function ap(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Ga(s,r)}return o?!0:(No(n,new le(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 up=new Set(["file","model","language","response_format"]);async function Va(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??np,s=n.maxAudioPartBytes??tp;try{if(t.method!=="POST")throw new le(405,`${String(t.method)} is not supported on ${hr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new le(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await cr(t,o)}catch(f){throw f instanceof Se?new le(413,f.message):new le(400,String(f instanceof Error?f.message:f))}let u=new Map;for(let f of a.keys()){if(!up.has(f))throw new le(400,`form field "${f}" 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.`,f);u.set(f,(u.get(f)??0)+1)}for(let[f,m]of u)if(m>1)throw new le(400,`form field "${f}" appears ${m} 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`,f);let l=a.get("model");if(l!==null&&typeof l!="string")throw new le(400,"model must be a string field","model");let d=l===null?void 0:l,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new le(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,h=a.get("response_format")??"json";if(h!=="json")throw new le(400,`response_format ${JSON.stringify(h)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let g=a.get("file");if(!(g instanceof File))throw new le(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(g.size>s)throw new le(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let k=new Uint8Array(await g.arrayBuffer());if(!qa(k))throw new le(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let P=rp(k);if(P===null)throw new le(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 op(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",k.length,k.length),!await ap(n.transcriptionModels,d,e,r))return;let b=[{type:"input_audio",input_audio:{data:Buffer.from(k).toString("base64"),format:"wav"}}];try{let f=await ip(n.clients,d,b,p,n.turn?$e(n.turn):void 0,n.turn,r);sp(n.turn,P),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:f}))}catch(f){throw Ga(f,r)}}catch(i){if(i instanceof Se){No(e,new le(413,i.message));return}if(i instanceof le){No(e,i);return}throw i}}var vr=require("@urun-sh/core");x();var Do="x-urun-profile",Rn="voice";var Te=class extends Error{status=400},lp=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,dp=/\s/;function cp(t){return lp.test(t)}function Uo(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Te(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Wa(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new Te(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new Te(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new Te(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function Ja(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new Te(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let l=n.trim();if(l==="")throw new Te(`the ${Do} header is empty \u2014 the only profile this lane accepts is "${Rn}" (omit the header for the ordinary lane)`);if(l!==Rn)throw new Te(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Rn}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Rn)throw new Te(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Rn}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new Te("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new Te("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Wa(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:Wa(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Uo(u,"sentence_flush",!0),includeReasoning:Uo(u,"include_reasoning",!1),metadata:Uo(u,"metadata",!1)}}var Vt=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&&cp(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(dp.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 Ho(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function fp(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 xe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function de(t,e,n,r="invalid_request_error",o){xe(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function jo(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Xe(r),a=i??We(n?.inferenceId??null);i===null&&s(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let u=r?.code??null,l=o==="invalid_request_error"?400:u==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),xe(t,l,{error:{message:a,type:o,code:u}})}function Je(t,e,n,r){xe(t,e,{type:"error",error:{type:n,message:r}})}function Wt(t,e,n){if(e==="anthropic"){xe(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}xe(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var mp=64*1024*1024,xn=class extends Error{};async function Ka(t,e=mp){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new xn(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Et(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 Ya(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function yr(t){let e=Ya(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function za(t){let e=yr(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 gp(t,e){let n=Ya(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function hp(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let l=n[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function yp(t,e){let n=hp(e);n&&(t.timing=n),t.outputSeconds=rt(e)}function At(t,e){gp(t,e),yp(t,e)}async function br(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 Xa(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 wp(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 wr=class extends Error{};function _p(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 wr(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function vp(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:_p(n.role,n.content)})}return e}function Fo(t){return Ut(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 bp(t,e,n,r,o,s,i){let a=mn(s.id),u=t.stream===!0;if(s.model=Ie(t),s.stream=u,await br(s,e,typeof t.model=="string"?t.model:void 0),u){let f;try{f=await hn({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(m){if(m instanceof Z){Wt(r,"openai",m);return}if(m instanceof Ne){de(r,m.status,m.message);return}if(m instanceof je||m instanceof be){r.setHeader("retry-after","2"),de(r,503,m.message,"capacity_error");return}throw m}Ho(r);for await(let m of f.events){if(m.type==="error"){s.streamError=!0;let y=m.error,_=Xe(y),v=_??We(s.id);_===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(m)}`),r.write(`event: error
31
- data: ${JSON.stringify({error:{message:v,type:y?.type??"upstream_error",code:y?.code??null}})}
28
+ ${qc(n)}\r
29
+ `),t.destroy()}function Wc(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
30
+ `}function Vc(t){Ye(process.stdout,t)}function Jc(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function $o(t){return t.audioSession?.audio.sessionId??void 0}function lr(t,e){let n=new va.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==bn)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=H("rtup"),l=Jc(o),d=S=>{(e.log??Vc)(Wc(S))};d({stage:"accept",conn:u,model:l}),s.resume();let c=new AbortController,p=null,h=S=>{p??=S,c.abort(new Error(p))},g=()=>h("client socket closed"),v=()=>h("client socket closed (half-close)"),I=S=>h(`client socket error: ${S.message}`);s.once("close",g),s.once("end",v),s.once("error",I);let b=()=>{s.removeListener("close",g),s.removeListener("end",v),s.removeListener("error",I)},f=S=>{d({stage:"close",conn:u,model:l,...S})},m=S=>{let P=S,_=P.session!=null&&typeof P.session.sendResponseCreate=="function",E=P.clients!=null&&typeof P.clients.createResponse=="function";if(!_&&!E)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((O,R)=>{n.handleUpgrade(o,s,i,C=>{try{new vn({ws:C,binding:S,operatorLog:e.operatorLog,onClosed:(T,D)=>{f({while:"live",reason:D.reason})}}),d({stage:"admit",conn:u,model:l,...$o(S)===void 0?{}:{session:$o(S)}}),O()}catch(T){R(T)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async S=>{if(c.signal.aborted){b();let P=$o(S);try{await S.release?.()}catch(_){f({while:"queued",...P===void 0?{}:{session:P},reason:p??"client socket closed",release_failed:_ instanceof Error?_.message:String(_)});return}f({while:"queued",...P===void 0?{}:{session:P},reason:p??"client socket closed",released:!0}),s.destroy();return}b(),await m(S)}).catch(S=>{let P=S instanceof No.SessionFailedError?rr(S):null,_=null;if(S!==null&&typeof S=="object"&&"status"in S){let C=S.status;typeof C=="number"&&(_=C)}let E=_??P?.status??502,O=S instanceof Error?S.message:String(S),R=_!==null?O:P!==null?wn(P,S instanceof No.SessionFailedError&&S.status.sessionId?`session ${S.status.sessionId}`:void 0):Me(S).message;f({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:O,status:E}}),s.destroyed||Gc(s,E,R)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}x();var iu=require("crypto");x();var _p=require("http");x();x();var ke=class extends Error{};async function dr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ke(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new ke(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function cr(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new ke(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")i.set(l,d);else if(Array.isArray(d))for(let c of d)i.append(l,c);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof ke?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var ba="/v1/images/generations",pr="/v1/images/edits";function Sa(t){return t===ba||t===pr}var ka="/v1/images/models";async function Ra(t,e,n){if(t){if(t.model=Pe({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 Q=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Kc=16*1024*1024,xa=64*1024*1024;function Ea(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 Sn(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 Aa(t,e,n,r,o,s){let i=s??(g=>console.error(g)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),u=null;for await(let g of a){if(g.type==="error"){let v=g.error??{},I=typeof v.message=="string"&&v.message.length>0&&We(v.message)?v.message:null;throw I===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(g)}`),new Q(502,"the image upstream failed while serving this request")):new Q(502,`image upstream error: ${I}`)}if(g.type==="response.completed"){u=g.response??null;break}}if(u===null)throw new Q(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=ot(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new Q(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(Ea(p)===null)throw new Q(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function Oa(t,e){if(t instanceof Q)return t;if(t instanceof De)throw t;return t instanceof Z?new Q(404,t.message):new Q(502,jt("image",t,e))}async function Ia(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 Sn(r,new Q(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 Ta(t,e){t&&(t.outputUnits=e.images.length)}function Pa(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 zc={model:!0,prompt:!0,response_format:!0,n:!0};async function Ca(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??xa;try{if(t.method!=="POST")throw new Q(405,`${String(t.method)} is not supported on ${ba}`);let s;try{s=JSON.parse((await dr(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof ke?new Q(413,p.message):new Q(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new Q(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!zc[p])throw new Q(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let a=i.prompt;if(typeof a!="string"||a.trim().length===0)throw new Q(400,"prompt is required and must be a non-empty string","prompt");let u=i.model===void 0?void 0:i.model;if(u!==void 0&&typeof u!="string")throw new Q(400,"model must be a string","model");await Ra(n.turn,n.clients,u);let l=i.n??1;if(l!==1)throw new Q(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new Q(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",a.length,a.length),!await Ia(n.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Aa(n.clients,u,c,n.turn?Ne(n.turn):void 0,n.turn,r);Ta(n.turn,p),Pa(e,p)}catch(p){throw Oa(p,r)}}catch(s){if(s instanceof ke){Sn(e,new Q(413,s.message));return}if(s instanceof Q){Sn(e,s);return}throw s}}var Yc={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function La(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??xa,s=n.maxImagePartBytes??Kc;try{if(t.method!=="POST")throw new Q(405,`${String(t.method)} is not supported on ${pr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new Q(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await cr(t,o)}catch(g){throw g instanceof ke?new Q(413,g.message):new Q(400,String(g instanceof Error?g.message:g))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new Q(400,"prompt is required and must be a non-empty string field","prompt");let l=a.get("model");if(l!==null&&typeof l!="string")throw new Q(400,"model must be a string field","model");let d=l===null?void 0:l;await Ra(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new Q(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let g of a.keys())if(!Yc[g])throw new Q(400,`form field "${g}" 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[]).`,g);let p=[];for(let g of["image","image[]"])for(let v of a.getAll(g)){if(!(v instanceof File))throw new Q(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",g);if(v.size>s)throw new Q(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,g);let I=new Uint8Array(await v.arrayBuffer()),b=Ea(I);if(b===null)throw new Q(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",g);p.push({bytes:I,mime:b})}if(p.length===0)throw new Q(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await Ia(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:u}];for(let{bytes:g,mime:v}of p)h.push({type:"input_image",image_url:`data:${v};base64,${Buffer.from(g).toString("base64")}`});try{let g=await Aa(n.clients,d,h,n.turn?Ne(n.turn):void 0,n.turn,r);Ta(n.turn,g),Pa(e,g)}catch(g){throw Oa(g,r)}}catch(i){if(i instanceof ke){Sn(e,new Q(413,i.message));return}if(i instanceof Q){Sn(e,i);return}throw i}}x();var kn="/v1/audio/speech";function ja(t){return t===kn}var Ma=4096,$a=18e4,Na=5e3,Xc=64*1024*1024,Ua=8,Da=5,Fa=1024*1024,Wt="voice_applied",mr="X-Urun-Voice-Applied",K=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Uo(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 gr=class extends K{constructor(e){super(502,e)}};function qa(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 Ga(t){return new K(502,`the runtime's ${Wt} receipt ${JSON.stringify(t)} cannot be relayed as the ${mr} 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 Qc(t,e,n){if(t){if(t.model=Pe({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 Wa(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Zc=2;function ep(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Zc)return!1;return!0}function tp(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 Ba=new WeakMap,fr=new WeakMap;function np(t,e){let n=fr.get(t)??0;if(n>=Ua)throw new K(503,`this model's speech queue is full \u2014 ${Ua} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Da}s`,void 0,Da);fr.set(t,n+1);let r=Ba.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Ba.set(t,s),(async()=>{await r;try{return await e()}finally{fr.set(t,(fr.get(t)??1)-1),o()}})()}async function rp(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new K(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof X))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function Et(t,e){if(t instanceof K)return t;if(t instanceof De)throw t;return t instanceof Z?new K(404,t.message):new K(502,jt("speech",t,e))}async function Ha(t,e,n,r,o,s,i,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return np(e,async()=>{if(i?.()===!0)return null;let p=!1,h=!1,g=!1,v,I=new Promise(E=>{v=E}),b=[],f=()=>{h&&!g&&b.length>=o.quietRunFrames&&(g=!0,v())},m=e.onOutputAudio(E=>{let O=Buffer.from(E,"base64");if(O.byteLength===0)return;let R=ep(O);if(!p){if(R)return;p=!0}if(R){b.push(O),f();return}for(let C of b)c(C);b.length=0,c(O),f()}),y=null,S,P,_;try{_=(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 O=new Promise(T=>{P=setTimeout(T,s.capMs)}),R=!1;for(;;){let T=_.next(),D=await Promise.race([T,O]);if(D===void 0){R=!0,T.catch(()=>{});break}if(D.done)break;let V=D.value;if(V.type==="error"){let J=V.error??{};await _.return?.();let oe=typeof J.message=="string"&&J.message.length>0&&We(J.message)?J.message:null;throw oe===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(V)}`),new K(502,"the speech upstream failed while serving this request")):new K(502,`speech upstream error: ${oe}`)}if(V.type==="response.completed"){y=V.response??null,h=!0,u?.(y),f(),await _.return?.();break}}if(clearTimeout(P),R)throw new K(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(y===null)throw new K(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let C=!1;if(await Promise.race([I,new Promise(T=>{S=setTimeout(()=>{C=!0,T()},o.capMs)})]),S!==void 0&&clearTimeout(S),r.voice!==void 0){let T=y[Wt];if(typeof T!="string"||T!==r.voice){let D=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof T=="string"?`${Wt} ${JSON.stringify(T)}`:`no ${Wt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw g?new gr(D):new K(502,D)}}if(!p)throw new K(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(C&&!g&&b.length<1)throw new K(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return y}catch(E){throw E instanceof gr||await rp(t,n,_,s.returnBoundMs),E}finally{S!==void 0&&clearTimeout(S),P!==void 0&&clearTimeout(P),m()}})}function op(t,e,n,r){let o=!1,s=0,i=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",mr)),t.write(a,u=>{u||(s+=a.byteLength,Wa(e,s))}),t.writableLength>Fa&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Fa} 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[Wt];if(typeof u=="string"){if(!qa(u))throw Ga(u);t.addTrailers({[mr]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:i}}async function sp(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Et(s,r)}return o?!0:(Uo(n,new K(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 ip={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},ap="wav, pcm";async function Va(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??Xc,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${kn}`);let a;try{a=JSON.parse((await dr(t,o)).toString("utf8")||"{}")}catch(y){throw y instanceof ke?new K(413,y.message):new K(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new K(400,"request body must be a JSON object");let u=a;for(let y of Object.keys(u))if(!ip[y])throw new K(400,`request field "${y}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,y);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new K(400,"input is required and must be a non-empty string","input");if(l.length>Ma)throw new K(400,`input is ${l.length} chars \u2014 over the ${Ma}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=u.model===void 0?void 0:u.model;if(d!==void 0&&typeof d!="string")throw new K(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new K(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new K(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 ${kn} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(y){throw Et(y,r)}if(p.defect!==null)throw new K(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let h=typeof c=="string"?c:void 0;if(h!==void 0&&p.published.length>0&&!p.published.includes(h))throw new K(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let g=u.response_format??"wav";if(g!=="wav"&&g!=="pcm")throw new K(400,`response_format ${JSON.stringify(g)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${ap} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new K(400,"stream_format, when present, must be a string","stream_format");let v=u.speed;if(v!==void 0){if(typeof v!="number"||!Number.isFinite(v))throw new K(400,"speed, when present, must be a number","speed");if(v!==1)throw new K(400,`speed=${JSON.stringify(v)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let I=u.instructions;if(I!==void 0){if(typeof I!="string")throw new K(400,"instructions, when present, must be a string","instructions");if(I.trim().length>0)throw new K(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 Qc(n.turn,n.clients,d);let b=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",b,b),!await sp(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new K(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 K(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 K(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 f;try{f=await n.clients.speechSessionHandle(d)}catch(y){throw Et(y,r)}let m;try{m=await n.clients.openAudioOn(f)}catch(y){throw Et(y,r)}n.turn&&(n.turn.sessionId=m.sessionId);try{if(g==="wav"){let y=[],S=await Ha(n.clients,m,f,{model:d,text:l,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??$a,returnBoundMs:n.turnReturnBoundMs??Na},i,_=>y.push(_),_=>{n.turn&&(n.turn.outputSeconds=ot(_))},r);if(S===null||i())return;let P=Buffer.concat(y);if(h===void 0){let _=S[Wt];if(typeof _=="string"){if(!qa(_))throw Ga(_);e.setHeader(mr,_)}}Wa(n.turn,P.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([tp(P.byteLength),P]))}else{let y=op(e,n.turn,i,h===void 0),S;try{S=await Ha(n.clients,m,f,{model:d,text:l,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??$a,returnBoundMs:n.turnReturnBoundMs??Na},i,y.sink,P=>{n.turn&&(n.turn.outputSeconds=ot(P))},r)}catch(P){let _=Et(P,r);if(!y.started())throw _;n.turn&&(n.turn.streamError=!0),y.fail(_);return}if(S===null)return;try{await y.finish(S)}catch(P){let _=Et(P,r);n.turn&&(n.turn.streamError=!0),y.fail(_);return}}}catch(y){throw Et(y,r)}}catch(a){if(a instanceof ke){Uo(e,new K(413,a.message));return}if(a instanceof K){Uo(e,a);return}throw a}}x();var hr="/v1/audio/transcriptions";function Ja(t){return t===hr}var Ka="/v1/audio/models",up=16*1024*1024,lp=64*1024*1024,de=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Do(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 za(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 dp(t){if(!za(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(s==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,l=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:l,channels:u,bitsPerSample:d}}else if(s==="data"){let u=t.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function cp(t,e,n){if(t){if(t.model=Pe({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 pp(t,e){t&&(t.outputUnits=e.seconds)}async function fp(t,e,n,r,o,s,i){let a=i??(c=>console.error(c)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of u){if(l.push(c),c.type==="error"){let p=c.error??{},h=typeof p.type=="string"?p.type:"upstream_error",g=typeof p.message=="string"&&p.message.length>0&&We(p.message)?p.message:null;throw g===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new de(h==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new de(h==="invalid_request_error"?400:502,`transcription upstream error: ${g}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new de(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=ot(d)),Bt(l,d)}function Ya(t,e){if(t instanceof de)return t;if(t instanceof De)throw t;return t instanceof Z?new de(404,t.message):new de(502,jt("transcription",t,e))}async function mp(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Ya(s,r)}return o?!0:(Do(n,new de(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 gp=new Set(["file","model","language","response_format"]);async function Xa(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??lp,s=n.maxAudioPartBytes??up;try{if(t.method!=="POST")throw new de(405,`${String(t.method)} is not supported on ${hr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new de(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await cr(t,o)}catch(f){throw f instanceof ke?new de(413,f.message):new de(400,String(f instanceof Error?f.message:f))}let u=new Map;for(let f of a.keys()){if(!gp.has(f))throw new de(400,`form field "${f}" 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.`,f);u.set(f,(u.get(f)??0)+1)}for(let[f,m]of u)if(m>1)throw new de(400,`form field "${f}" appears ${m} 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`,f);let l=a.get("model");if(l!==null&&typeof l!="string")throw new de(400,"model must be a string field","model");let d=l===null?void 0:l,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new de(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,h=a.get("response_format")??"json";if(h!=="json")throw new de(400,`response_format ${JSON.stringify(h)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let g=a.get("file");if(!(g instanceof File))throw new de(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(g.size>s)throw new de(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let v=new Uint8Array(await g.arrayBuffer());if(!za(v))throw new de(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let I=dp(v);if(I===null)throw new de(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 cp(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",v.length,v.length),!await mp(n.transcriptionModels,d,e,r))return;let b=[{type:"input_audio",input_audio:{data:Buffer.from(v).toString("base64"),format:"wav"}}];try{let f=await fp(n.clients,d,b,p,n.turn?Ne(n.turn):void 0,n.turn,r);pp(n.turn,I),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:f}))}catch(f){throw Ya(f,r)}}catch(i){if(i instanceof ke){Do(e,new de(413,i.message));return}if(i instanceof de){Do(e,i);return}throw i}}var vr=require("@urun-sh/core");x();var Bo="x-urun-profile",Rn="voice";var Ce=class extends Error{status=400},hp=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,yp=/\s/;function wp(t){return hp.test(t)}function Fo(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Ce(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Qa(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 Ce(`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 Ce(`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 Ce(`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 Za(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 Ce(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let l=n.trim();if(l==="")throw new Ce(`the ${Bo} header is empty \u2014 the only profile this lane accepts is "${Rn}" (omit the header for the ordinary lane)`);if(l!==Rn)throw new Ce(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Rn}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Rn)throw new Ce(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Rn}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new Ce("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 Ce("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:Qa(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:Qa(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Fo(u,"sentence_flush",!0),includeReasoning:Fo(u,"include_reasoning",!1),metadata:Fo(u,"metadata",!1)}}var Vt=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&&wp(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(yp.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 qo(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function vp(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function Ee(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function ce(t,e,n,r="invalid_request_error",o){Ee(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Go(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Qe(r),a=i??Ve(n?.inferenceId??null);i===null&&s(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let u=r?.code??null,l=o==="invalid_request_error"?400:u==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),Ee(t,l,{error:{message:a,type:o,code:u}})}function Je(t,e,n,r){Ee(t,e,{type:"error",error:{type:n,message:r}})}function Jt(t,e,n){if(e==="anthropic"){Ee(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}Ee(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var bp=64*1024*1024,xn=class extends Error{};async function eu(t,e=bp){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new xn(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function At(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 nu(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function yr(t){let e=nu(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function tu(t){let e=yr(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 Sp(t,e){let n=nu(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function kp(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let l=n[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function Rp(t,e){let n=kp(e);n&&(t.timing=n),t.outputSeconds=ot(e)}function Ot(t,e){Sp(t,e),Rp(t,e)}async function br(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 ru(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 xp(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 wr=class extends Error{};function Ep(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 wr(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Ap(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:Ep(n.role,n.content)})}return e}function Ho(t){return Dt(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 Op(t,e,n,r,o,s,i){let a=mn(s.id),u=t.stream===!0;if(s.model=Pe(t),s.stream=u,await br(s,e,typeof t.model=="string"?t.model:void 0),u){let f;try{f=await hn({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(m){if(m instanceof Z){Jt(r,"openai",m);return}if(m instanceof Ue){ce(r,m.status,m.message);return}if(m instanceof je||m instanceof Se){r.setHeader("retry-after","2"),ce(r,503,m.message,"capacity_error");return}throw m}qo(r);for await(let m of f.events){if(m.type==="error"){s.streamError=!0;let y=m.error,S=Qe(y),P=S??Ve(s.id);S===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(m)}`),r.write(`event: error
31
+ data: ${JSON.stringify({error:{message:P,type:y?.type??"upstream_error",code:y?.code??null}})}
32
32
 
33
- `),r.end();return}m.type==="response.completed"&&At(s,m.response),r.write(`event: ${String(m.type??"message")}
33
+ `),r.end();return}m.type==="response.completed"&&Ot(s,m.response),r.write(`event: ${String(m.type??"message")}
34
34
  data: ${JSON.stringify(m)}
35
35
 
36
36
  `)}r.write(`data: [DONE]
37
37
 
38
- `),r.end();return}let l;try{l=Bt(n,t)}catch(f){if(f instanceof Ne){de(r,f.status,f.message);return}throw f}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=Ie(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await _o(e,t,l,!1,$e(s))}catch(f){if(f instanceof Z){Wt(r,"openai",f);return}if(f instanceof Ne){de(r,f.status,f.message);return}if(f instanceof je||f instanceof be){r.setHeader("retry-after","2"),de(r,503,f.message,"capacity_error");return}throw f}let g=[],k=null;for await(let f of o.track(h,c,s)){if(g.push(f),f.type==="error"){jo(r,f,{inferenceId:s.id,operatorError:i});return}f.type==="response.completed"&&(k=f.response)}if(k==null){de(r,502,"upstream produced no response.completed event","upstream_error");return}At(s,k);let P=Ft(g,k),b=Rt(p,Ut(k).length,P);if(b){de(r,502,kt(c,b),"upstream_error");return}d&&n.remember(a,l,wo(k,P),d),xe(r,200,{...k,id:a})}async function Sp(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){de(n,400,"chat/completions requires a messages array");return}let u;try{u=Ja(s,t)}catch(I){if(I instanceof Te){de(n,I.status,I.message);return}throw I}let l=String(t.model??"urun"),d=Xi(o.id),c;try{c=vp(a)}catch(I){if(I instanceof wr){de(n,400,I.message);return}throw I}let p=Ie(t);r.model(p),o.model=p,o.stream=t.stream===!0,await br(o,e,typeof t.model=="string"?t.model:void 0);let h=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await e.createResponse({model:t.model,input:c,stream:!0,tools:wp(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}:{}},$e(o))}catch(I){if(I instanceof Z){Wt(n,"openai",I);return}if(I instanceof je||I instanceof be){n.setHeader("retry-after","2"),de(n,503,I.message,"capacity_error");return}throw I}if(t.stream===!0){u?fp(n):Ho(n);let I=[],C=new dt,T="",j=u?new Vt(u,K=>{n.write(`data: ${JSON.stringify(Et(d,l,{content:K},null))}
38
+ `),r.end();return}let l;try{l=Ht(n,t)}catch(f){if(f instanceof Ue){ce(r,f.status,f.message);return}throw f}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=Pe(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await bo(e,t,l,!1,Ne(s))}catch(f){if(f instanceof Z){Jt(r,"openai",f);return}if(f instanceof Ue){ce(r,f.status,f.message);return}if(f instanceof je||f instanceof Se){r.setHeader("retry-after","2"),ce(r,503,f.message,"capacity_error");return}throw f}let g=[],v=null;for await(let f of o.track(h,c,s)){if(g.push(f),f.type==="error"){Go(r,f,{inferenceId:s.id,operatorError:i});return}f.type==="response.completed"&&(v=f.response)}if(v==null){ce(r,502,"upstream produced no response.completed event","upstream_error");return}Ot(s,v);let I=Bt(g,v),b=xt(p,Dt(v).length,I);if(b){ce(r,502,Rt(c,b),"upstream_error");return}d&&n.remember(a,l,vo(v,I),d),Ee(r,200,{...v,id:a})}async function Ip(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){ce(n,400,"chat/completions requires a messages array");return}let u;try{u=Za(s,t)}catch(R){if(R instanceof Ce){ce(n,R.status,R.message);return}throw R}let l=String(t.model??"urun"),d=ra(o.id),c;try{c=Ap(a)}catch(R){if(R instanceof wr){ce(n,400,R.message);return}throw R}let p=Pe(t);r.model(p),o.model=p,o.stream=t.stream===!0,await br(o,e,typeof t.model=="string"?t.model:void 0);let h=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await e.createResponse({model:t.model,input:c,stream:!0,tools:xp(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}:{}},Ne(o))}catch(R){if(R instanceof Z){Jt(n,"openai",R);return}if(R instanceof je||R instanceof Se){n.setHeader("retry-after","2"),ce(n,503,R.message,"capacity_error");return}throw R}if(t.stream===!0){u?vp(n):qo(n);let R=[],C=new ct,T="",D=u?new Vt(u,J=>{n.write(`data: ${JSON.stringify(At(d,l,{content:J},null))}
39
39
 
40
- `)}):null,W=K=>{j?.flush(),n.write(K),n.end()};try{u?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
40
+ `)}):null,V=J=>{D?.flush(),n.write(J),n.end()};try{u?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
41
41
 
42
- `),n.write(`data: ${JSON.stringify(Et(d,l,{role:"assistant"},null))}
42
+ `),n.write(`data: ${JSON.stringify(At(d,l,{role:"assistant"},null))}
43
43
 
44
- `);for await(let se of r.track(g,p,o)){I.push(se);let ve=Dt(se);if(se.type==="response.output_text.delta"&&typeof se.delta=="string")T+=se.delta,j?j.push(se.delta):n.write(`data: ${JSON.stringify(Et(d,l,{content:se.delta},null))}
44
+ `);for await(let se of r.track(g,p,o)){R.push(se);let be=Ft(se);if(se.type==="response.output_text.delta"&&typeof se.delta=="string")T+=se.delta,D?D.push(se.delta):n.write(`data: ${JSON.stringify(At(d,l,{content:se.delta},null))}
45
45
 
46
- `);else if(se.type==="response.reasoning_text.delta"&&typeof se.delta=="string")(!u||u.includeReasoning)&&n.write(`data: ${JSON.stringify(Et(d,l,{reasoning_content:se.delta},null))}
46
+ `);else if(se.type==="response.reasoning_text.delta"&&typeof se.delta=="string")(!u||u.includeReasoning)&&n.write(`data: ${JSON.stringify(At(d,l,{reasoning_content:se.delta},null))}
47
47
 
48
- `);else if(ve){j?.flush();let{call:V,isNew:M}=C.add(ve),ee=M?{index:ve.tool_index,id:V.id??`call_${ve.tool_index}`,type:"function",function:{name:V.name??"",arguments:ve.delta}}:{index:ve.tool_index,function:{arguments:ve.delta}};n.write(`data: ${JSON.stringify(Et(d,l,{tool_calls:[ee]},null))}
48
+ `);else if(be){D?.flush();let{call:W,isNew:M}=C.add(be),ee=M?{index:be.tool_index,id:W.id??`call_${be.tool_index}`,type:"function",function:{name:W.name??"",arguments:be.delta}}:{index:be.tool_index,function:{arguments:be.delta}};n.write(`data: ${JSON.stringify(At(d,l,{tool_calls:[ee]},null))}
49
49
 
50
- `)}else if(se.type==="error"){o.streamError=!0;let V=se.error??{},M=Xe(V),ee=M??We(o.id);M===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(se)}`),W(`data: ${JSON.stringify({error:{message:ee,type:V.type??"upstream_error",code:V.code??null}})}
50
+ `)}else if(se.type==="error"){o.streamError=!0;let W=se.error??{},M=Qe(W),ee=M??Ve(o.id);M===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(se)}`),V(`data: ${JSON.stringify({error:{message:ee,type:W.type??"upstream_error",code:W.code??null}})}
51
51
 
52
- `);return}}let K=Fo(Ye(I)),oe=Rt(h,C.size+K.length,T);if(oe){o.streamError=!0,W(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:kt(p,oe)}})}
52
+ `);return}}let J=Ho(Xe(R)),oe=xt(h,C.size+J.length,T);if(oe){o.streamError=!0,V(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Rt(p,oe)}})}
53
53
 
54
- `);return}j?.flush(),C.size===0&&K.length>0&&n.write(`data: ${JSON.stringify(Et(d,l,{tool_calls:K},null))}
54
+ `);return}D?.flush(),C.size===0&&J.length>0&&n.write(`data: ${JSON.stringify(At(d,l,{tool_calls:J},null))}
55
55
 
56
- `);let te=C.size>0||K.length>0;n.write(`data: ${JSON.stringify(Et(d,l,{},te?"tool_calls":"stop"))}
56
+ `);let te=C.size>0||J.length>0;n.write(`data: ${JSON.stringify(At(d,l,{},te?"tool_calls":"stop"))}
57
57
 
58
- `);let Be=yr(Ye(I));At(o,Ye(I)),Be&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:za(Ye(I))})}
58
+ `);let Be=yr(Xe(R));Ot(o,Xe(R)),Be&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:tu(Xe(R))})}
59
59
 
60
60
  `),n.write(`data: [DONE]
61
61
 
62
- `),n.end();return}finally{j?.flush(),j?.dispose()}}let k="",P="",b=[],f=new dt;for await(let I of r.track(g,p,o)){b.push(I),I.type==="response.output_text.delta"&&typeof I.delta=="string"&&(k+=I.delta),I.type==="response.reasoning_text.delta"&&typeof I.delta=="string"&&(P+=I.delta);let C=Dt(I);if(C&&f.add(C),I.type==="error"){jo(n,I,{inferenceId:o.id,operatorError:i});return}}let m=Ye(b);At(o,m);let y=Fo(m),_=y.length>0?y:Fo({output:f.items()}),v=Rt(h,_.length,k);if(v){de(n,502,kt(p,v),"upstream_error");return}let R=_.map(({index:I,...C})=>C),E={role:"assistant",content:k||null},O=P||Xa(m);O&&(E.reasoning_content=O),R.length>0&&(E.tool_calls=R),xe(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:E,finish_reason:R.length>0?"tool_calls":"stop"}],usage:za(m)})}var qo="sense-latest";async function kp(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){de(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:qo,a=Ie({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){de(n,400,"systemone requires a state (string or JSON structure)");return}let u=t.questions;if(u===null||typeof u!="object"||Array.isArray(u)||Object.keys(u).length===0){de(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){de(n,400,"systemone media, when present, must be an array");return}let l={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=l;let d=performance.now();r.model(a),await br(o,e,i),l.resolve_ms=Math.round(performance.now()-d);let c,p=performance.now();try{c=await e.createResponse({model:i,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},$e(o))}catch(f){if(f instanceof Z){Wt(n,"openai",f);return}if(f instanceof je){n.setHeader("retry-after","2"),de(n,503,f.message,"capacity_error");return}if(f instanceof be){n.setHeader("retry-after","2"),de(n,503,f.message,"capacity_error");return}throw f}l.dial_ms=Math.round(performance.now()-p);let h=[],g=null;try{for await(let f of r.track(c,a,o))if(g===null&&(g=performance.now(),l.first_event_ms=Math.round(g-p)),h.push(f),f.type==="error"){jo(n,f,{inferenceId:o.id,operatorError:s});return}}catch(f){if(f instanceof Z){g!==null&&(l.stream_ms=Math.round(performance.now()-g)),Wt(n,"openai",f);return}if(f instanceof je){g!==null&&(l.stream_ms=Math.round(performance.now()-g)),n.setHeader("retry-after","2"),de(n,503,f.message,"capacity_error");return}if(f instanceof be){g!==null&&(l.stream_ms=Math.round(performance.now()-g)),n.setHeader("retry-after","2"),de(n,503,f.message,"capacity_error");return}throw g!==null&&(l.stream_ms=Math.round(performance.now()-g)),f}g!==null&&(l.stream_ms=Math.round(performance.now()-g));let k=Ye(h);if(k==null){de(n,502,"upstream produced no response.completed event","upstream_error");return}At(o,k);let P=Ft(h,k),b;try{b=JSON.parse(P)}catch{de(n,502,"systemone answer was not valid JSON","upstream_error");return}if(b===null||typeof b!="object"||Array.isArray(b)){de(n,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof b=="object"&&b!==null&&!Array.isArray(b)&&"timing"in b){let f=b.timing;if(typeof f=="object"&&f!==null&&!Array.isArray(f)&&"question_fwd_ms"in f&&"head_ms"in f){let m=y=>typeof y=="number"&&Number.isFinite(y)&&y>=0?Math.round(y):null;l.question_fwd_ms=m(f.question_fwd_ms),l.head_ms=m(f.head_ms)}}xe(n,200,b)}function Rp(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var En=class extends Error{};function _r(t){return new En(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function xp(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 Ep(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 En(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Ap(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw _r(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw _r(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Op(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 _r(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:Ap(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw _r(a)}}return s(),r}function Bo(t){return Ut(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 Ip(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Je(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){Je(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Je(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(E=>typeof E!="string"))){Je(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),u=Qi(o.id),l=[],d;try{t.system&&l.push({role:"system",content:Rp(t.system)});for(let E of i)l.push(...Op(E));d=Ep(t.tool_choice)}catch(E){if(E instanceof En){Je(n,400,"invalid_request_error",E.message);return}throw E}let c=Ie(t);r.model(c),o.model=c,o.stream=t.stream===!0,await br(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:l,stream:!0,tools:xp(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},$e(o))}catch(E){if(E instanceof Z){Wt(n,"anthropic",E);return}if(E instanceof je||E instanceof be){n.setHeader("retry-after","2"),Je(n,503,"capacity_error",E.message);return}throw E}let g=(E,O)=>{n.destroyed||n.write(`event: ${E}
62
+ `),n.end();return}finally{D?.flush(),D?.dispose()}}let v="",I="",b=[],f=new ct;for await(let R of r.track(g,p,o)){b.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(v+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(I+=R.delta);let C=Ft(R);if(C&&f.add(C),R.type==="error"){Go(n,R,{inferenceId:o.id,operatorError:i});return}}let m=Xe(b);Ot(o,m);let y=Ho(m),S=y.length>0?y:Ho({output:f.items()}),P=xt(h,S.length,v);if(P){ce(n,502,Rt(p,P),"upstream_error");return}let _=S.map(({index:R,...C})=>C),E={role:"assistant",content:v||null},O=I||ru(m);O&&(E.reasoning_content=O),_.length>0&&(E.tool_calls=_),Ee(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:E,finish_reason:_.length>0?"tool_calls":"stop"}],usage:tu(m)})}var Wo="sense-latest";async function Tp(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){ce(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:Wo,a=Pe({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){ce(n,400,"systemone requires a state (string or JSON structure)");return}let u=t.questions;if(u===null||typeof u!="object"||Array.isArray(u)||Object.keys(u).length===0){ce(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){ce(n,400,"systemone media, when present, must be an array");return}let l={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=l;let d=performance.now();r.model(a),await br(o,e,i),l.resolve_ms=Math.round(performance.now()-d);let c,p=performance.now();try{c=await e.createResponse({model:i,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},Ne(o))}catch(f){if(f instanceof Z){Jt(n,"openai",f);return}if(f instanceof je){n.setHeader("retry-after","2"),ce(n,503,f.message,"capacity_error");return}if(f instanceof Se){n.setHeader("retry-after","2"),ce(n,503,f.message,"capacity_error");return}throw f}l.dial_ms=Math.round(performance.now()-p);let h=[],g=null;try{for await(let f of r.track(c,a,o))if(g===null&&(g=performance.now(),l.first_event_ms=Math.round(g-p)),h.push(f),f.type==="error"){Go(n,f,{inferenceId:o.id,operatorError:s});return}}catch(f){if(f instanceof Z){g!==null&&(l.stream_ms=Math.round(performance.now()-g)),Jt(n,"openai",f);return}if(f instanceof je){g!==null&&(l.stream_ms=Math.round(performance.now()-g)),n.setHeader("retry-after","2"),ce(n,503,f.message,"capacity_error");return}if(f instanceof Se){g!==null&&(l.stream_ms=Math.round(performance.now()-g)),n.setHeader("retry-after","2"),ce(n,503,f.message,"capacity_error");return}throw g!==null&&(l.stream_ms=Math.round(performance.now()-g)),f}g!==null&&(l.stream_ms=Math.round(performance.now()-g));let v=Xe(h);if(v==null){ce(n,502,"upstream produced no response.completed event","upstream_error");return}Ot(o,v);let I=Bt(h,v),b;try{b=JSON.parse(I)}catch{ce(n,502,"systemone answer was not valid JSON","upstream_error");return}if(b===null||typeof b!="object"||Array.isArray(b)){ce(n,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof b=="object"&&b!==null&&!Array.isArray(b)&&"timing"in b){let f=b.timing;if(typeof f=="object"&&f!==null&&!Array.isArray(f)&&"question_fwd_ms"in f&&"head_ms"in f){let m=y=>typeof y=="number"&&Number.isFinite(y)&&y>=0?Math.round(y):null;l.question_fwd_ms=m(f.question_fwd_ms),l.head_ms=m(f.head_ms)}}Ee(n,200,b)}function Pp(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var En=class extends Error{};function _r(t){return new En(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Cp(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 Lp(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 En(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Mp(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw _r(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw _r(`tool_result > ${r}`);e+=String(n.text??"")}return e}function $p(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 _r(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:Mp(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw _r(a)}}return s(),r}function jo(t){return Dt(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 Np(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Je(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){Je(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Je(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(E=>typeof E!="string"))){Je(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),u=oa(o.id),l=[],d;try{t.system&&l.push({role:"system",content:Pp(t.system)});for(let E of i)l.push(...$p(E));d=Lp(t.tool_choice)}catch(E){if(E instanceof En){Je(n,400,"invalid_request_error",E.message);return}throw E}let c=Pe(t);r.model(c),o.model=c,o.stream=t.stream===!0,await br(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:l,stream:!0,tools:Cp(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},Ne(o))}catch(E){if(E instanceof Z){Jt(n,"anthropic",E);return}if(E instanceof je||E instanceof Se){n.setHeader("retry-after","2"),Je(n,503,"capacity_error",E.message);return}throw E}let g=(E,O)=>{n.destroyed||n.write(`event: ${E}
63
63
  data: ${JSON.stringify({type:E,...O})}
64
64
 
65
- `)};if(t.stream===!0){let E=r.track(h,c,o);Ho(n),g("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let O=0,I="",C=0,T="none",j=()=>T,W=-1,K=-1,oe=new dt,te=[],Be=()=>{T!=="none"&&(T="none",g("content_block_stop",{index:W}))},se=(re,ue)=>{Be(),T=re,W=C++,g("content_block_start",{index:W,content_block:ue})};for await(let re of E){if(n.destroyed)break;te.push(re);let ue=Dt(re);if(re.type==="response.reasoning_text.delta"&&typeof re.delta=="string")j()!=="thinking"&&se("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:W,delta:{type:"thinking_delta",thinking:re.delta}});else if(re.type==="response.output_text.delta"&&typeof re.delta=="string")j()!=="text"&&se("text",{type:"text",text:""}),O+=1,I+=re.delta,g("content_block_delta",{index:W,delta:{type:"text_delta",text:re.delta}});else if(ue){let{call:Ae}=oe.add(ue);(j()!=="tool"||ue.tool_index!==K)&&(K=ue.tool_index,se("tool",{type:"tool_use",id:Ae.id??`call_${ue.tool_index}`,name:Ae.name??"",input:{}})),ue.delta&&g("content_block_delta",{index:W,delta:{type:"input_json_delta",partial_json:ue.delta}})}else if(re.type==="error"){o.streamError=!0;let Ae=re.error,Ze=Xe(Ae);Ze===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(re)}`),g("error",{error:{type:"api_error",message:Ze??We(o.id)}}),n.end();return}}if(n.destroyed)return;let ve=Ye(te),V=Ut(ve),M=Rt(p,oe.size+V.length,I);if(M){o.streamError=!0,g("error",{error:{type:"api_error",message:kt(c,M)}}),n.end();return}Be();let ee=[];if(oe.size===0)try{ee=Bo(ve)}catch(re){o.streamError=!0;let ue=Le(re,{inferenceId:o.id});ue.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(re instanceof Error?re.message:re)}`),g("error",{error:{type:"api_error",message:ue.message}}),n.end();return}C===0&&ee.length===0&&(se("text",{type:"text",text:""}),Be()),ee.forEach(re=>{let ue=C++;g("content_block_start",{index:ue,content_block:{...re,input:{}}}),g("content_block_delta",{index:ue,delta:{type:"input_json_delta",partial_json:JSON.stringify(re.input??{})}}),g("content_block_stop",{index:ue})});let Qe=oe.size>0||ee.length>0,ne=yr(ve);At(o,ve),g("message_delta",{delta:{stop_reason:Qe?"tool_use":"end_turn"},usage:ne?{input_tokens:ne.input_tokens,output_tokens:ne.output_tokens}:{output_tokens:O}}),g("message_stop",{}),n.end();return}let k="",P="",b=[],f=new dt;for await(let E of r.track(h,c,o)){b.push(E),E.type==="response.output_text.delta"&&typeof E.delta=="string"&&(k+=E.delta),E.type==="response.reasoning_text.delta"&&typeof E.delta=="string"&&(P+=E.delta);let O=Dt(E);if(O&&f.add(O),E.type==="error"){let I=E.error,C=I?.type==="invalid_request_error",T=Xe(I);T===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(E)}`),Je(n,C?400:502,C?"invalid_request_error":"api_error",T??We(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let m=Ye(b);At(o,m);let y;try{y=Bo(m),y.length===0&&f.size>0&&(y=Bo({output:f.items()}))}catch(E){let O=Le(E,{inferenceId:o.id});O.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(E instanceof Error?E.message:E)}`),Je(n,502,"api_error",O.message);return}let _=Rt(p,y.length,k);if(_){Je(n,502,"api_error",kt(c,_));return}let v=[],R=P||Xa(m);R&&v.push({type:"thinking",thinking:R}),(k||y.length===0)&&v.push({type:"text",text:k}),v.push(...y),xe(n,200,{id:u,type:"message",role:"assistant",content:v,model:a,stop_reason:y.length>0?"tool_use":"end_turn",usage:yr(m)??{input_tokens:0,output_tokens:0}})}function Tp(t){ze(process.stdout,t)}function Qa(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Tp,a=t.operatorLog??(d=>console.error(d)),u=t.observe,l=new bt;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),h=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),g=(m,y,_,v,R)=>h?Je(c,m,v,y):de(c,m,y,_,R),k=yo(p.pathname),P=p.pathname.startsWith("/partners/"),b=k||P?{id:fn(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;b&&(c.setHeader(zi,b.id),c.once("close",()=>{let m=Zi({turn:b,method:d.method??"",path:p.pathname,res:c});i(ea(m)),u?.(m),si({record:m,ledger:t.ledger??null,req:d})}));let f=()=>Yi(p.pathname,b);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){xe(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){xe(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){g(401,"invalid local proxy api key","authentication_error","authentication_error");return}let m=p.pathname===Hn?"canonical":p.pathname===dn?"huggingface":null;if(m){if(d.method!=="POST"){g(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let R=t.usage;if(!R){g(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let E=R.authorize(d),O;try{O=await Ka(d,di)}catch(T){if(T instanceof xn){g(413,T.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let I=T=>R.lookup(E,T),C;try{if(m==="canonical"){let T=ci(O),j=await I(T);jn(j,T),C={requests:j}}else C=await mi(O,I)}catch(T){if(T instanceof lt){g(T.status,T.message,"invalid_request_error","invalid_request_error");return}throw T}xe(c,200,C);return}if(d.method==="GET"&&p.pathname===gt){let R=await s(d);if(b&&(b.org=R.tenant??null),!R.openRouterModels){g(501,`GET ${gt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}xe(c,200,await R.openRouterModels());return}if(p.pathname.startsWith("/partners/")){g(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${dn} and GET ${gt}`,"invalid_request_error","not_found_error");return}let y=await s(d);if(b&&(b.org=y.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:gt}),c.end();return}xe(c,200,await y.listModels());return}if(d.method==="GET"&&p.pathname===ya){if(!y.listImageModels){g(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}xe(c,200,await y.listImageModels());return}if(ha(p.pathname)){if(!y.supportsImages){g(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let R={clients:y,imageModels:y.supportsImages,stats:l,turn:f(),operatorLog:a};p.pathname===pr?await Aa(d,c,R):await Ea(d,c,R);return}if(d.method==="GET"&&p.pathname===ja){if(!y.listSpeechToTextModels){g(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}xe(c,200,await y.listSpeechToTextModels());return}if(Ha(p.pathname)){if(!y.supportsTranscription){g(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${hr}`,"not_implemented","not_implemented_error");return}let R={clients:y,transcriptionModels:y.supportsTranscription,stats:l,turn:f(),operatorLog:a};await Va(d,c,R);return}if(Na(p.pathname)){if(!y.supportsSpeech){g(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${kn}`,"not_implemented","not_implemented_error");return}let R={clients:y,speechModels:y.supportsSpeech,stats:l,turn:f(),operatorLog:a};await Ba(d,c,R);return}if(d.method!=="POST"){g(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let _;try{_=await Ka(d)}catch(R){if(R instanceof xn){g(413,R.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let v=Buffer.byteLength(JSON.stringify(_));if(p.pathname==="/v1/responses"){l.request("responses",v,v),await bp(_,y,gn(y),c,l,f(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",v,v),await Sp(_,y,c,l,f(),d.headers[Do],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",v,v),await kp(_,y,c,l,f(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",v,v),await Ip(_,y,c,l,f(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",v,v),Je(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}g(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(m=>{let y=String(m instanceof Error?m.message:m);if(!c.headersSent){let R=o?.(m)??null;if(R){R.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${R.operatorDetail}`),g(R.status,y,R.openaiType,R.anthropicType,R.code);return}if(m instanceof vr.SessionAllocationError){let O=nr(m.code);if(O){let I=m.retryAfterSeconds??(O.status===429?30:void 0);I!==void 0&&c.setHeader("Retry-After",String(I)),g(O.status,wn(O,m.code??void 0),O.openaiType,O.anthropicType,O.code);return}}if(m instanceof vr.SessionFailedError){let O=rr(m);if(O){let I=O.status===429?30:void 0;I!==void 0&&c.setHeader("Retry-After",String(I)),g(O.status,wn(O,m.status.sessionId?`session ${m.status.sessionId}`:void 0),O.openaiType,O.anthropicType,O.code);return}}if(m instanceof fe){g(502,y,"upstream_error","api_error");return}if(m instanceof qe){m.retryable&&c.setHeader("Retry-After","1");let O=Le(m,{inferenceId:b?.id??null});O.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:Ge(m)}`),g(502,O.message,"upstream_error","api_error",m.code);return}if(m instanceof ct){c.setHeader("Retry-After",String(m.retryAfterSeconds)),g(m.status,y,m.status===429?"capacity_error":"upstream_error",m.status===429?"rate_limit_error":"overloaded_error",m.code);return}let E=Le(m,{inferenceId:b?.id??null});E.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:Ge(m)}`),g(500,E.message,"proxy_error","api_error","proxy_error");return}b&&(b.streamError=!0);let _=m instanceof qe?m.code:null,v=Le(m,{inferenceId:b?.id??null});v.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:Ge(m)}`),c.destroyed||(h?c.write(`event: error
66
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:v.message}})}
65
+ `)};if(t.stream===!0){let E=r.track(h,c,o);qo(n),g("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let O=0,R="",C=0,T="none",D=()=>T,V=-1,J=-1,oe=new ct,te=[],Be=()=>{T!=="none"&&(T="none",g("content_block_stop",{index:V}))},se=(re,ue)=>{Be(),T=re,V=C++,g("content_block_start",{index:V,content_block:ue})};for await(let re of E){if(n.destroyed)break;te.push(re);let ue=Ft(re);if(re.type==="response.reasoning_text.delta"&&typeof re.delta=="string")D()!=="thinking"&&se("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:V,delta:{type:"thinking_delta",thinking:re.delta}});else if(re.type==="response.output_text.delta"&&typeof re.delta=="string")D()!=="text"&&se("text",{type:"text",text:""}),O+=1,R+=re.delta,g("content_block_delta",{index:V,delta:{type:"text_delta",text:re.delta}});else if(ue){let{call:Ie}=oe.add(ue);(D()!=="tool"||ue.tool_index!==J)&&(J=ue.tool_index,se("tool",{type:"tool_use",id:Ie.id??`call_${ue.tool_index}`,name:Ie.name??"",input:{}})),ue.delta&&g("content_block_delta",{index:V,delta:{type:"input_json_delta",partial_json:ue.delta}})}else if(re.type==="error"){o.streamError=!0;let Ie=re.error,et=Qe(Ie);et===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(re)}`),g("error",{error:{type:"api_error",message:et??Ve(o.id)}}),n.end();return}}if(n.destroyed)return;let be=Xe(te),W=Dt(be),M=xt(p,oe.size+W.length,R);if(M){o.streamError=!0,g("error",{error:{type:"api_error",message:Rt(c,M)}}),n.end();return}Be();let ee=[];if(oe.size===0)try{ee=jo(be)}catch(re){o.streamError=!0;let ue=Me(re,{inferenceId:o.id});ue.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(re instanceof Error?re.message:re)}`),g("error",{error:{type:"api_error",message:ue.message}}),n.end();return}C===0&&ee.length===0&&(se("text",{type:"text",text:""}),Be()),ee.forEach(re=>{let ue=C++;g("content_block_start",{index:ue,content_block:{...re,input:{}}}),g("content_block_delta",{index:ue,delta:{type:"input_json_delta",partial_json:JSON.stringify(re.input??{})}}),g("content_block_stop",{index:ue})});let Ze=oe.size>0||ee.length>0,ne=yr(be);Ot(o,be),g("message_delta",{delta:{stop_reason:Ze?"tool_use":"end_turn"},usage:ne?{input_tokens:ne.input_tokens,output_tokens:ne.output_tokens}:{output_tokens:O}}),g("message_stop",{}),n.end();return}let v="",I="",b=[],f=new ct;for await(let E of r.track(h,c,o)){b.push(E),E.type==="response.output_text.delta"&&typeof E.delta=="string"&&(v+=E.delta),E.type==="response.reasoning_text.delta"&&typeof E.delta=="string"&&(I+=E.delta);let O=Ft(E);if(O&&f.add(O),E.type==="error"){let R=E.error,C=R?.type==="invalid_request_error",T=Qe(R);T===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(E)}`),Je(n,C?400:502,C?"invalid_request_error":"api_error",T??Ve(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let m=Xe(b);Ot(o,m);let y;try{y=jo(m),y.length===0&&f.size>0&&(y=jo({output:f.items()}))}catch(E){let O=Me(E,{inferenceId:o.id});O.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(E instanceof Error?E.message:E)}`),Je(n,502,"api_error",O.message);return}let S=xt(p,y.length,v);if(S){Je(n,502,"api_error",Rt(c,S));return}let P=[],_=I||ru(m);_&&P.push({type:"thinking",thinking:_}),(v||y.length===0)&&P.push({type:"text",text:v}),P.push(...y),Ee(n,200,{id:u,type:"message",role:"assistant",content:P,model:a,stop_reason:y.length>0?"tool_use":"end_turn",usage:yr(m)??{input_tokens:0,output_tokens:0}})}function Up(t){Ye(process.stdout,t)}function ou(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Up,a=t.operatorLog??(d=>console.error(d)),u=t.observe,l=new St;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),h=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),g=(m,y,S,P,_)=>h?Je(c,m,P,y):ce(c,m,y,S,_),v=_o(p.pathname),I=p.pathname.startsWith("/partners/"),b=v||I?{id:fn(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;b&&(c.setHeader(ta,b.id),c.once("close",()=>{let m=sa({turn:b,method:d.method??"",path:p.pathname,res:c});i(ia(m)),u?.(m),ci({record:m,ledger:t.ledger??null,req:d})}));let f=()=>na(p.pathname,b);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){Ee(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){Ee(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){g(401,"invalid local proxy api key","authentication_error","authentication_error");return}let m=p.pathname===Hn?"canonical":p.pathname===dn?"huggingface":null;if(m){if(d.method!=="POST"){g(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let _=t.usage;if(!_){g(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let E=_.authorize(d),O;try{O=await eu(d,hi)}catch(T){if(T instanceof xn){g(413,T.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let R=T=>_.lookup(E,T),C;try{if(m==="canonical"){let T=yi(O),D=await R(T);jn(D,T),C={requests:D}}else C=await vi(O,R)}catch(T){if(T instanceof dt){g(T.status,T.message,"invalid_request_error","invalid_request_error");return}throw T}Ee(c,200,C);return}if(d.method==="GET"&&p.pathname===ht){let _=await s(d);if(b&&(b.org=_.tenant??null),!_.openRouterModels){g(501,`GET ${ht} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}Ee(c,200,await _.openRouterModels());return}if(p.pathname.startsWith("/partners/")){g(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${dn} and GET ${ht}`,"invalid_request_error","not_found_error");return}let y=await s(d);if(b&&(b.org=y.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:ht}),c.end();return}Ee(c,200,await y.listModels());return}if(d.method==="GET"&&p.pathname===ka){if(!y.listImageModels){g(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}Ee(c,200,await y.listImageModels());return}if(Sa(p.pathname)){if(!y.supportsImages){g(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let _={clients:y,imageModels:y.supportsImages,stats:l,turn:f(),operatorLog:a};p.pathname===pr?await La(d,c,_):await Ca(d,c,_);return}if(d.method==="GET"&&p.pathname===Ka){if(!y.listSpeechToTextModels){g(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}Ee(c,200,await y.listSpeechToTextModels());return}if(Ja(p.pathname)){if(!y.supportsTranscription){g(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${hr}`,"not_implemented","not_implemented_error");return}let _={clients:y,transcriptionModels:y.supportsTranscription,stats:l,turn:f(),operatorLog:a};await Xa(d,c,_);return}if(ja(p.pathname)){if(!y.supportsSpeech){g(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${kn}`,"not_implemented","not_implemented_error");return}let _={clients:y,speechModels:y.supportsSpeech,stats:l,turn:f(),operatorLog:a};await Va(d,c,_);return}if(d.method!=="POST"){g(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let S;try{S=await eu(d)}catch(_){if(_ instanceof xn){g(413,_.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let P=Buffer.byteLength(JSON.stringify(S));if(p.pathname==="/v1/responses"){l.request("responses",P,P),await Op(S,y,gn(y),c,l,f(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",P,P),await Ip(S,y,c,l,f(),d.headers[Bo],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",P,P),await Tp(S,y,c,l,f(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",P,P),await Np(S,y,c,l,f(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",P,P),Je(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}g(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(m=>{let y=String(m instanceof Error?m.message:m);if(!c.headersSent){let _=o?.(m)??null;if(_){_.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${_.operatorDetail}`),g(_.status,y,_.openaiType,_.anthropicType,_.code);return}if(m instanceof vr.SessionAllocationError){let O=nr(m.code);if(O){let R=m.retryAfterSeconds??(O.status===429?30:void 0);R!==void 0&&c.setHeader("Retry-After",String(R)),g(O.status,wn(O,m.code??void 0),O.openaiType,O.anthropicType,O.code);return}}if(m instanceof vr.SessionFailedError){let O=rr(m);if(O){let R=O.status===429?30:void 0;R!==void 0&&c.setHeader("Retry-After",String(R)),g(O.status,wn(O,m.status.sessionId?`session ${m.status.sessionId}`:void 0),O.openaiType,O.anthropicType,O.code);return}}if(m instanceof fe){g(502,y,"upstream_error","api_error");return}if(m instanceof qe){m.retryable&&c.setHeader("Retry-After","1");let O=Me(m,{inferenceId:b?.id??null});O.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:Ge(m)}`),g(502,O.message,"upstream_error","api_error",m.code);return}if(m instanceof pt){c.setHeader("Retry-After",String(m.retryAfterSeconds)),g(m.status,y,m.status===429?"capacity_error":"upstream_error",m.status===429?"rate_limit_error":"overloaded_error",m.code);return}let E=Me(m,{inferenceId:b?.id??null});E.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:Ge(m)}`),g(500,E.message,"proxy_error","api_error","proxy_error");return}b&&(b.streamError=!0);let S=m instanceof qe?m.code:null,P=Me(m,{inferenceId:b?.id??null});P.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:Ge(m)}`),c.destroyed||(h?c.write(`event: error
66
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:P.message}})}
67
67
 
68
- `):c.write(`data: ${JSON.stringify({error:{message:v.message,type:"upstream_error",code:_}})}
68
+ `):c.write(`data: ${JSON.stringify({error:{message:P.message,type:"upstream_error",code:S}})}
69
69
 
70
- `)),c.end()})}}x();var ot=(t,e)=>Object.assign(new Error(e),{status:t}),Lp='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Vo=(t,e,n)=>new X(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Go=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof Z?ot(404,n.message):n}};async function Za(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw ot(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Lp}`);if(o==="transcription")throw ot(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw ot(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw ot(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(h){throw h instanceof Z?ot(404,h.message):h}if(!p)throw ot(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(h){throw h instanceof Z?ot(404,h.message):h}if(p!=="stt")throw ot(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await Go(t,n.stt),i=await Go(t,e),a=await Go(t,n.tts),u=await t.openAudioOn(s,r),l=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let h=new AbortController;return d=h,Mp({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},p,h.signal,()=>{d===h&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(h){throw h instanceof X?Vo("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function Wo(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Sr=class extends Error{};async function*Mp(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:u}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),h=!1,g=null,k=null,P=[],b=null,f=new Promise((C,T)=>{n&&n.addEventListener("abort",()=>T(new Sr),{once:!0})}),m=()=>h||n?.aborted===!0,y=async C=>{if(m())return;let T;try{T=await o.createResponseOn(i,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:C}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(W){throw W instanceof X?Vo("tts",u.tts,W):W}let j=T[Symbol.asyncIterator]();k=j;try{for(;;){let W=j.next(),K;try{K=await Promise.race([W,f])}catch(te){if(W.catch(()=>{}),te instanceof Sr)return;throw te}if(K.done)return;let oe=K.value;if(oe.type==="error"){let te=oe.error&&typeof oe.error.message=="string"?oe.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${te}`)}if(oe.type==="response.completed")return}}finally{k===j&&(k=null)}},_=async()=>{for(;P.length>0&&!m();){let C=P.shift();await y(C)}},v=C=>{if(C===""||m()||(P.push(C),b!==null))return;let T=_();b=T,T.then(()=>{b===T&&(b=null)},j=>{b===T&&(b=null),g??=j})},R=()=>{h=!0,P.length=0;let C=k;if(k=null,C){let T=C.return?.();T&&T.catch(()=>{})}},E=async()=>{for(;P.length>0||b!==null;){let C=b;if(C===null){await y(P.shift());continue}await C}},O=p?new Vt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},C=>v(C)):null,I=null;try{let C;try{C=await o.createResponseOn(s,d)}catch(T){throw T instanceof X?Vo("chat",a,T):T}for await(let T of C){if(m())return;let j=T;if(j.type==="error"){yield T;return}if(j.type==="response.output_text.delta"&&typeof j.delta=="string"){yield T,O?.push(j.delta);continue}if(j.type==="response.function_call_arguments.delta"){O?.flush(),yield T;continue}if(j.type==="response.completed"){I=T.response;continue}}O?.flush(),O?.dispose(),p&&await E(),I!==null&&(yield{type:"response.completed",response:I})}finally{O?.dispose(),R();try{if(g instanceof X)throw g}finally{r?.()}}}var De=(t,e)=>Object.assign(new Error(e),{status:t});function tu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function nu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var $p='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function ru(t,e,n,r){if(!t.supportsAudio)throw De(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let o;try{o=await t.supportsAudio(e)}catch(d){throw d instanceof Z?De(404,d.message):d}if(!o){let d=null;if(t.realtimeCompanionsFor)try{d=await t.realtimeCompanionsFor(e)}catch(c){throw c instanceof Z?De(404,c.message):c}if(d!==null)return await Za(t,e,d,n,r);throw De(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw De(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(d){throw d instanceof Z?De(404,d.message):d}if(s&&!t.openTurnsOn)throw De(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(s&&t.transcriptStreamFor){let d;try{d=await t.transcriptStreamFor(e)}catch(c){throw c instanceof Z?De(404,c.message):c}if(d!=="stt")throw De(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw De(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${$p}`);if(r==="transcription"&&!s)throw De(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i;try{i=await t.sessionHandle(e)}catch(d){throw d instanceof be?De(503,d.message):d}let a=`conn_${(0,eu.randomUUID)()}`,u={audio:await t.openAudioOn(i,n,a)},l={clients:{createResponse:async d=>await t.createResponseOn(i,d,a)},voice:o,audioSession:u};return s&&(l.turns=d=>t.openTurnsOn(i,d)),r==="transcription"&&(l.intent="transcription"),t.releaseSessionHandle&&(l.release=()=>t.releaseSessionHandle(i)),e!==void 0&&(l.model=e),l}x();var pu=require("@urun-sh/core/internal"),fu=Re(require("ws"),1);x();x();x();x();function ou(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function kr(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 su(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 Np="llm-resp";async function*xr(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let a=typeof i.index=="number"?i.index:0,u=r.get(a)??{};i.id&&(u.id=i.id),i.function?.name&&(u.name=i.function.name),r.set(a,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:u.id,name:u.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield su(s);return}}}async function*Jo(t,e){let n=`${Np}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*xr(e,t.stream(n).messages())}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var Er=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,s)=>{let i=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{i(),s(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=kr(e,n,this.consumerId);return this.write(r),Jo(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=ou(e,n,r,this.consumerId);return this.write(o),Jo(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 iu=0;function Up(){return iu+=1,`req_${Date.now().toString(36)}_${iu.toString(36)}`}var Ot=class{transport;constructor(e){this.transport=new Er(e)}responses={create:async e=>{let n=Up(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};x();var Jt=Re(require("yjs"),1),au=require("@urun-sh/core/internal"),Dp=3e4;function Fp(t){return(e,n,r)=>{let o=t(e);Jt.applyUpdate(n,Jt.encodeStateAsUpdate(o));let s=a=>Jt.applyUpdate(o,a),i=a=>Jt.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}async function*Bp(t,e){let n=[],r=!1,o=null,s="",i=u=>{if(!("responses"in u)||typeof u.responses!="object"||u.responses===null)return null;let l=u.responses;if(!(e in l))return null;let d=l[e];if(d===null||typeof d!="object"||!("error"in d))return{body:d,error:null};let c=d.error;return c===null?{body:d,error:null}:{body:d,error:c}},a=u=>{let l={};for(let[c,p]of Object.entries(u)){let h=p;l[c]=typeof h?.toJSON=="function"?h.toJSON():p}if("tokens"in l&&typeof l.tokens=="object"&&l.tokens!==null){let c=l.tokens[e];typeof c=="string"&&c.length>s.length&&(n.push({t:"delta",delta:c.slice(s.length)}),s=c)}let d=i(l);if(d!==null){d.error!==null?n.push({t:"error",body:d.error}):n.push({t:"response",body:d.body}),r=!0,o?.(),o=null;return}if("progress"in l&&typeof l.progress=="object"&&l.progress!==null){let c=l.progress[e];if(typeof c=="object"&&c!==null&&"state"in c&&c.state==="error"){let h="error"in c&&typeof c.error=="string"?c.error:"lane request failed";n.push({t:"error",body:{message:h}}),r=!0,o?.(),o=null;return}}o?.(),o=null};if(a(t.get()??{}),!r){let u=t.on("change",a);try{for(;!r;){if(n.length>0){yield n.shift();continue}await new Promise(l=>{o=l})}}finally{u()}}for(;n.length>0;)yield n.shift()}function Ko(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Fp(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=u=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let l=r.get(u);return l||(l=new au.SessionDocumentImpl(u,e,n),r.set(u,l)),l},i=u=>{let l="llm-resp:";if(!u.startsWith(l))throw new Error(`lane session exposes no stream "${u}" \u2014 only the llm reply lanes (${l}<rid>)`);let d=u.slice(l.length);return{messages:()=>Bp(s("llm"),d),attach:async()=>{throw new Error("lane session carries no media track \u2014 the doc mirror IS the reply lane")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(u){return s(u)},stream:i,async end(){},async whenLive(u){let l=s("llm");if(l.synced===!0)return;let d=u?.timeout??t.whenLiveTimeoutMs??Dp;await new Promise((c,p)=>{let h=setTimeout(()=>{g(),p(new Error(`lane ${e} llm doc never synced within ${d}ms`))},d),g=l.onSynced(()=>{clearTimeout(h),u?.signal?.removeEventListener("abort",k),c()}),k=()=>{clearTimeout(h),g(),p(u?.signal?.reason instanceof Error?u.signal.reason:new Error("aborted"))};u?.signal?.addEventListener("abort",k,{once:!0})})},destroy(){o=!0;for(let u of r.values())u.dispose();r.clear()}}}x();var ft=require("crypto"),Hp=["sfu","urun-doc"],lu="runtime:lease",jp="lane:join",qp="urun-runtime-key-v1";function zo(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,ft.createHmac)("sha256",t).update(`${qp}|${e}`).digest("base64url")}var Gp=120;function uu(t){return Buffer.from(t).toString("base64url")}function Vp(t,e,n){let r=uu(JSON.stringify(t)),o=uu(JSON.stringify(e)),s=(0,ft.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function du(t,e,n=Gp,r=jp,o){let s=Math.floor(Date.now()/1e3),i=o?zo(e,o):e;return Vp({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,ft.randomUUID)()},i)}function cu(t,e,n,r=Math.floor(Date.now()/1e3),o){let s=t.split(".");if(s.length!==3)return null;let[i,a,u]=s,l,d;try{l=JSON.parse(Buffer.from(i,"base64url").toString()),d=JSON.parse(Buffer.from(a,"base64url").toString())}catch{return null}if(l.alg!=="HS256")return null;let c;try{c=Buffer.from(u,"base64url")}catch{return null}let p=typeof d.tenant=="string"&&d.tenant!==""?d.tenant:void 0,h=[];if(p!==void 0?(h.push(zo(n,p)),o&&h.push(zo(o,p))):(h.push(n),o&&h.push(o)),!h.some(f=>{let m=(0,ft.createHmac)("sha256",f).update(`${i}.${a}`).digest();return c.length===m.length&&(0,ft.timingSafeEqual)(c,m)}))return null;let g=d.exp;if(typeof g!="number"||g<=r)return null;let k=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(k!==void 0&&Hp.some(f=>f===k||Array.isArray(k)&&k.includes(f))))return null;let b=d.session_id??d.sub;return typeof b!="string"||b!==e?null:{sessionId:b,aud:k,scope:typeof d.scope=="string"?d.scope:void 0,tenant:p,app:typeof d.app=="string"?d.app:void 0,fn:typeof d.fn=="string"?d.fn:void 0,exp:g}}x();var Wp=3,Jp="llm",Kp=new Set(["paused","error"]);function Ar(t,e,n){let r=t.doc(Jp),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)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,a=!1,u=new Set,l=[],d=c=>{if(!i){i=c;for(let p of[...u])p(c);u.clear()}};return o&&l.push(r.onConnectionState(c=>{a&&(c.consecutiveFailures<Wp||d(new X(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?l.push(r.onSynced(()=>{a=!0})):s&&l.push(t.onPhase(c=>{if(c.name==="live"){a=!0;return}a&&Kp.has(c.name)&&d(new X(`the pooled session for app "${e}" lost its compute binding (phase "${c.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(c){return i?(c(i),()=>{}):(u.add(c),()=>u.delete(c))},dispose(){u.clear();for(let c of l.splice(0))c()}}}async function*Yo(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(u=>a(u))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}function zp(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new Ue(`the shared lane target (app slug "${t.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${e}.${t.appId}.${t.fnName??""}`}function mu(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=(p,h,g,k,P)=>{let b=g?Ko({laneId:p,roomDoc:y=>t.roomDoc(p,y)}):Ko({laneId:p,connector:(0,pu.createWebsocketDocConnector)({serverUrl:`ws://${k}/doc`,sessionId:p,token:()=>du(p,t.tokenSecret,void 0,void 0,P),WebSocketPolyfill:fu.default})}),f=g?a(p):Ar(b,`lane:${p}`,{armOnFirstSync:!0}),m={session:b,responses:new Ot(b),gone:f,goneWatch:f,laneId:p,pool:h,inFlight:0,laneSession:b,self:g,host:k??""};return n.set(p,m),f.onGone(()=>u(m)),m},a=p=>{let h=null,g=!1,k=new Set,P=f=>{if(!h){h=f;for(let m of[...k])m(f);k.clear()}},b=t.hostedSignal?.(p,f=>{if(f){g=!0;return}g&&P(new X(`the lane ${p} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>h,onGone(f){return h?(f(h),()=>{}):(k.add(f),()=>k.delete(f))},dispose(){b?.(),k.clear()}}},u=p=>{l(p)&&(n.delete(p.laneId),r.delete(p.laneId),p.goneWatch?.dispose())},l=p=>{let h=p.laneId;return typeof h=="string"&&n.get(h)===p},d=(p,h)=>{throw t.metrics?.observeLane503Fast(h??""),s.set(p,e()),new be(p)},c=async(p,h)=>{let g=zp(h);o.add(g);let k=e();try{let P=await t.laneWarmWaitMsFor?.(p,h)??t.laneColdWakeDefaultMs??0,b=await t.plane.pick({pool:g,model:p,holdMs:P});t.metrics?.observeLaneReady(p??"",b.length);let m=b.map(_=>({laneId:_.laneId,self:_.host===t.selfAddress,host:_.host})).sort((_,v)=>_.self!==v.self?_.self?-1:1:(r.get(_.laneId)??0)-(r.get(v.laneId)??0))[0];m||d(g,p);let y=n.get(m.laneId);return y?.goneWatch?.gone()&&(u(y),y=void 0),y&&(y.pool!==g||y.self!==m.self||y.host!==m.host)&&(u(y),y=void 0),y||(y=i(m.laneId,g,m.self,m.host,h.sharedOrgId??void 0)),y.inFlight+=1,r.set(m.laneId,(r.get(m.laneId)??0)+1),{app:g,entry:y,identity:{kind:"catalog",model_id:h.modelId??p??"",variant:h.variant??""}}}finally{t.metrics?.observeLanePick(p??"",e()-k)}};return{sessionFor(p,h){return c(p,h)},release(p){l(p)&&(p.inFlight=Math.max(0,p.inFlight-1),r.set(p.laneId,p.inFlight))},owns(p){return l(p)},entryFor(p){return n.get(p)??null},evict(p){l(p)&&(p.gone.dispose(),n.delete(p.laneId),r.set(p.laneId,0),p.laneSession.destroy())},async status(){let p=[...new Set([...o,...[...n.values()].map(k=>k.pool)])].sort(),h=await t.plane.status().catch(()=>[]),g=new Map(Yp(h));return Promise.all(p.map(async k=>{let P=g.get(k)??{pool:k,lanes:[],lastDemandAt:null};return{pool:k,lanes:P.lanes,lastDemandAt:P.lastDemandAt,local:[...n.values()].filter(b=>b.pool===k).map(b=>({laneId:b.laneId,inFlight:b.inFlight,self:b.self,host:b.host})),lastRefusalAt:s.get(k)??null}}))},async close(){for(let p of n.values())p.gone.dispose(),p.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(p=>({pool:p.pool,laneId:p.laneId,inFlight:p.inFlight}))}}}function Yp(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}x();var yu=require("http");var Xp="/pooler/v1/lanes/pick",Qp="/pooler/v1/lanes/status",Zp=1e4;function gu(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),u=r===void 0?void 0:Buffer.from(JSON.stringify(r)),l=(0,yu.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...u===void 0?{}:{"content-type":"application/json","content-length":String(u.byteLength)}},timeout:o},d=>{let c=[];d.on("data",p=>c.push(p)),d.on("end",()=>{let p=Buffer.concat(c).toString("utf8"),h=null;try{h=p===""?null:JSON.parse(p)}catch{h=null}s({status:d.statusCode??0,json:h})}),d.on("error",i)});l.on("timeout",()=>{l.destroy(new Error(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),l.on("error",i),l.end(u)})}function hu(t,e,n){if(t===503)return new be(n);let r=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${r}`)}function wu(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=await gu(t,"POST",Xp,{pool:e,model:n,hold_ms:r},r+Zp);if(o.status!==200)throw hu(o.status,o.json,e);return(o.json?.lanes??[]).filter(i=>typeof i.lane_id=="string"&&i.lane_id!==""&&typeof i.host=="string"&&i.host!=="").map(i=>({laneId:i.lane_id,host:i.host}))},async status(){let e=await gu(t,"GET",Qp,void 0,5e3);if(e.status!==200)throw hu(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}x();var xu=require("ws");x();var vu=Re(require("yjs"),1),Yt=Re(require("y-protocols/sync"),1),st=Re(require("y-protocols/awareness"),1),pe=Re(require("lib0/encoding"),1),Xt=Re(require("lib0/decoding"),1),bu=Re(require("lib0/map"),1),Su=Re(require("lodash.debounce"),1);x();var _u=()=>{};var tf=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,nf=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,rf=0,of=1;var sf=process.env.GC!=="false"&&process.env.GC!=="0",af=process.env.YPERSISTENCE,Or=null;if(typeof af=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var zt=new Map,Ir=0,Qo=1,uf=(t,e,n)=>{let r=pe.createEncoder();pe.writeVarUint(r,Ir),Yt.writeUpdate(r,t);let o=pe.toUint8Array(r);n.conns.forEach((s,i)=>An(n,i,o))},Xo=class extends vu.Doc{constructor(e){super({gc:sf}),this.name=e,this.conns=new Map,this.awareness=new st.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let d=this.conns.get(i);d!==void 0&&(r.forEach(c=>{d.add(c)}),s.forEach(c=>{d.delete(c)}))}let u=pe.createEncoder();pe.writeVarUint(u,Qo),pe.writeVarUint8Array(u,st.encodeAwarenessUpdate(this.awareness,a));let l=pe.toUint8Array(u);this.conns.forEach((d,c)=>{An(this,c,l)})};this.awareness.on("update",n),this.on("update",uf),!1}},Zo=(t,e=!0)=>bu.setIfUndefined(zt,t,()=>{let n=new Xo(t);return n.gc=e,Or!==null&&Or.bindState(t,n),zt.set(t,n),n}),lf=(t,e,n)=>{try{let r=pe.createEncoder(),o=Xt.createDecoder(n);switch(Xt.readVarUint(o)){case Ir:pe.writeVarUint(r,Ir),Yt.readSyncMessage(o,r,e,t),pe.length(r)>1&&An(e,t,pe.toUint8Array(r));break;case Qo:{st.applyAwarenessUpdate(e.awareness,Xt.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},Kt=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),st.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Or!==null&&(Or.writeState(t.name,t).then(()=>{t.destroy()}),zt.delete(t.name))}e.close()},An=(t,e,n)=>{e.readyState!==rf&&e.readyState!==of&&Kt(t,e);try{e.send(n,r=>{r!=null&&Kt(t,e)})}catch{Kt(t,e)}},df=3e4,ku=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=Zo(n,r);o.conns.set(t,new Set),t.on("message",a=>lf(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&Kt(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{Kt(o,t),clearInterval(i)}}},df);t.on("close",()=>{Kt(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=pe.createEncoder();pe.writeVarUint(a,Ir),Yt.writeSyncStep1(a,o),An(o,t,pe.toUint8Array(a));let u=o.awareness.getStates();if(u.size>0){let l=pe.createEncoder();pe.writeVarUint(l,Qo),pe.writeVarUint8Array(l,st.encodeAwarenessUpdate(o.awareness,Array.from(u.keys()))),An(o,t,pe.toUint8Array(l))}}};var es="/doc/",Eu=30,cf=1e4,Ru="llm";function pf(t){if(!t.startsWith(es))return null;let e=t.slice(es.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function On(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
70
+ `)),c.end()})}}x();var st=(t,e)=>Object.assign(new Error(e),{status:t}),Bp='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Jo=(t,e,n)=>new X(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Vo=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof Z?st(404,n.message):n}};async function su(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw st(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Bp}`);if(o==="transcription")throw st(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw st(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw st(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(h){throw h instanceof Z?st(404,h.message):h}if(!p)throw st(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(h){throw h instanceof Z?st(404,h.message):h}if(p!=="stt")throw st(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await Vo(t,n.stt),i=await Vo(t,e),a=await Vo(t,n.tts),u=await t.openAudioOn(s,r),l=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let h=new AbortController;return d=h,Hp({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},p,h.signal,()=>{d===h&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(h){throw h instanceof X?Jo("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function Ko(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Sr=class extends Error{};async function*Hp(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:u}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),h=!1,g=null,v=null,I=[],b=null,f=new Promise((C,T)=>{n&&n.addEventListener("abort",()=>T(new Sr),{once:!0})}),m=()=>h||n?.aborted===!0,y=async C=>{if(m())return;let T;try{T=await o.createResponseOn(i,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:C}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(V){throw V instanceof X?Jo("tts",u.tts,V):V}let D=T[Symbol.asyncIterator]();v=D;try{for(;;){let V=D.next(),J;try{J=await Promise.race([V,f])}catch(te){if(V.catch(()=>{}),te instanceof Sr)return;throw te}if(J.done)return;let oe=J.value;if(oe.type==="error"){let te=oe.error&&typeof oe.error.message=="string"?oe.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${te}`)}if(oe.type==="response.completed")return}}finally{v===D&&(v=null)}},S=async()=>{for(;I.length>0&&!m();){let C=I.shift();await y(C)}},P=C=>{if(C===""||m()||(I.push(C),b!==null))return;let T=S();b=T,T.then(()=>{b===T&&(b=null)},D=>{b===T&&(b=null),g??=D})},_=()=>{h=!0,I.length=0;let C=v;if(v=null,C){let T=C.return?.();T&&T.catch(()=>{})}},E=async()=>{for(;I.length>0||b!==null;){let C=b;if(C===null){await y(I.shift());continue}await C}},O=p?new Vt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},C=>P(C)):null,R=null;try{let C;try{C=await o.createResponseOn(s,d)}catch(T){throw T instanceof X?Jo("chat",a,T):T}for await(let T of C){if(m())return;let D=T;if(D.type==="error"){yield T;return}if(D.type==="response.output_text.delta"&&typeof D.delta=="string"){yield T,O?.push(D.delta);continue}if(D.type==="response.function_call_arguments.delta"){O?.flush(),yield T;continue}if(D.type==="response.completed"){R=T.response;continue}}O?.flush(),O?.dispose(),p&&await E(),R!==null&&(yield{type:"response.completed",response:R})}finally{O?.dispose(),_();try{if(g instanceof X)throw g}finally{r?.()}}}var Fe=(t,e)=>Object.assign(new Error(e),{status:t});function au(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function uu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var jp='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function lu(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(d){throw d instanceof Z?Fe(404,d.message):d}if(!o){let d=null;if(t.realtimeCompanionsFor)try{d=await t.realtimeCompanionsFor(e)}catch(c){throw c instanceof Z?Fe(404,c.message):c}if(d!==null)return await su(t,e,d,n,r);throw Fe(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw 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 s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(d){throw d instanceof Z?Fe(404,d.message):d}if(s&&!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(s&&t.transcriptStreamFor){let d;try{d=await t.transcriptStreamFor(e)}catch(c){throw c instanceof Z?Fe(404,c.message):c}if(d!=="stt")throw Fe(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw Fe(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${jp}`);if(r==="transcription"&&!s)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 i;try{i=await t.sessionHandle(e)}catch(d){throw d instanceof Se?Fe(503,d.message):d}let a=`conn_${(0,iu.randomUUID)()}`,u={audio:await t.openAudioOn(i,n,a)},l={clients:{createResponse:async d=>await t.createResponseOn(i,d,a)},voice:o,audioSession:u};return s&&(l.turns=d=>t.openTurnsOn(i,d)),r==="transcription"&&(l.intent="transcription"),t.releaseSessionHandle&&(l.release=()=>t.releaseSessionHandle(i)),e!==void 0&&(l.model=e),l}x();var _u=require("@urun-sh/core/internal"),vu=xe(require("ws"),1);x();x();x();async function du(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}x();x();function cu(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function kr(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 pu(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 qp="llm-resp";async function*xr(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let a=typeof i.index=="number"?i.index:0,u=r.get(a)??{};i.id&&(u.id=i.id),i.function?.name&&(u.name=i.function.name),r.set(a,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:u.id,name:u.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield pu(s);return}}}async function*zo(t,e){let n=`${qp}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*xr(e,t.stream(n).messages())}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var Er=class{constructor(e,n=15e3){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}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=kr(e,n,this.consumerId);return this.write(r),zo(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=cu(e,n,r,this.consumerId);return this.write(o),zo(this.session,r)})}async writeGated(e,n){try{await du(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var fu=0;function Wp(){return fu+=1,`req_${Date.now().toString(36)}_${fu.toString(36)}`}var It=class{transport;constructor(e){this.transport=new Er(e)}responses={create:async e=>{let n=Wp(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};x();var Kt=xe(require("yjs"),1),mu=require("@urun-sh/core/internal"),Vp=3e4;function Jp(t){return(e,n,r)=>{let o=t(e);Kt.applyUpdate(n,Kt.encodeStateAsUpdate(o));let s=a=>Kt.applyUpdate(o,a),i=a=>Kt.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}async function*Kp(t,e){let n=[],r=!1,o=null,s="",i=0,a=l=>{if(!("responses"in l)||typeof l.responses!="object"||l.responses===null)return null;let d=l.responses;if(!(e in d))return null;let c=d[e];if(c===null||typeof c!="object"||!("error"in c))return{body:c,error:null};let p=c.error;return p===null?{body:c,error:null}:{body:c,error:p}},u=l=>{let d={};for(let[p,h]of Object.entries(l)){let g=h;d[p]=typeof g?.toJSON=="function"?g.toJSON():h}if("tokens"in d&&typeof d.tokens=="object"&&d.tokens!==null){let p=d.tokens[e];if(typeof p=="string"&&p.length>s.length)n.push({t:"delta",delta:p.slice(s.length)}),s=p;else if(p!==null&&typeof p=="object"){let h=p,g=Object.keys(h).map(v=>Number(v)).filter(v=>Number.isFinite(v)&&v>i).sort((v,I)=>v-I);for(let v of g){let I=h[String(v)];typeof I=="string"&&I.length>0&&(n.push({t:"delta",delta:I}),i=v)}}}let c=a(d);if(c!==null){c.error!==null?n.push({t:"error",body:c.error}):n.push({t:"response",body:c.body}),r=!0,o?.(),o=null;return}if("progress"in d&&typeof d.progress=="object"&&d.progress!==null){let p=d.progress[e];if(typeof p=="object"&&p!==null&&"state"in p&&p.state==="error"){let g="error"in p&&typeof p.error=="string"?p.error:"lane request failed";n.push({t:"error",body:{message:g}}),r=!0,o?.(),o=null;return}}o?.(),o=null};if(u(t.get()??{}),!r){let l=t.on("change",u);try{for(;!r;){if(n.length>0){yield n.shift();continue}await new Promise(d=>{o=d})}}finally{l()}}for(;n.length>0;)yield n.shift()}function Yo(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Jp(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=u=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let l=r.get(u);return l||(l=new mu.SessionDocumentImpl(u,e,n),r.set(u,l)),l},i=u=>{let l="llm-resp:";if(!u.startsWith(l))throw new Error(`lane session exposes no stream "${u}" \u2014 only the llm reply lanes (${l}<rid>)`);let d=u.slice(l.length);return{messages:()=>Kp(s("llm"),d),attach:async()=>{throw new Error("lane session carries no media track \u2014 the doc mirror IS the reply lane")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(u){return s(u)},stream:i,async end(){},async whenLive(u){let l=s("llm");if(l.synced===!0)return;let d=u?.timeout??t.whenLiveTimeoutMs??Vp;await new Promise((c,p)=>{let h=setTimeout(()=>{g(),p(new Error(`lane ${e} llm doc never synced within ${d}ms`))},d),g=l.onSynced(()=>{clearTimeout(h),u?.signal?.removeEventListener("abort",v),c()}),v=()=>{clearTimeout(h),g(),p(u?.signal?.reason instanceof Error?u.signal.reason:new Error("aborted"))};u?.signal?.addEventListener("abort",v,{once:!0})})},destroy(){o=!0;for(let u of r.values())u.dispose();r.clear()}}}x();var mt=require("crypto"),zp=["sfu","urun-doc"],hu="runtime:lease",Yp="lane:join",Xp="urun-runtime-key-v1";function Xo(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,mt.createHmac)("sha256",t).update(`${Xp}|${e}`).digest("base64url")}var Qp=120;function gu(t){return Buffer.from(t).toString("base64url")}function Zp(t,e,n){let r=gu(JSON.stringify(t)),o=gu(JSON.stringify(e)),s=(0,mt.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function yu(t,e,n=Qp,r=Yp,o){let s=Math.floor(Date.now()/1e3),i=o?Xo(e,o):e;return Zp({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,mt.randomUUID)()},i)}function wu(t,e,n,r=Math.floor(Date.now()/1e3),o){let s=t.split(".");if(s.length!==3)return null;let[i,a,u]=s,l,d;try{l=JSON.parse(Buffer.from(i,"base64url").toString()),d=JSON.parse(Buffer.from(a,"base64url").toString())}catch{return null}if(l.alg!=="HS256")return null;let c;try{c=Buffer.from(u,"base64url")}catch{return null}let p=typeof d.tenant=="string"&&d.tenant!==""?d.tenant:void 0,h=[];if(p!==void 0?(h.push(Xo(n,p)),o&&h.push(Xo(o,p))):(h.push(n),o&&h.push(o)),!h.some(f=>{let m=(0,mt.createHmac)("sha256",f).update(`${i}.${a}`).digest();return c.length===m.length&&(0,mt.timingSafeEqual)(c,m)}))return null;let g=d.exp;if(typeof g!="number"||g<=r)return null;let v=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(v!==void 0&&zp.some(f=>f===v||Array.isArray(v)&&v.includes(f))))return null;let b=d.session_id??d.sub;return typeof b!="string"||b!==e?null:{sessionId:b,aud:v,scope:typeof d.scope=="string"?d.scope:void 0,tenant:p,app:typeof d.app=="string"?d.app:void 0,fn:typeof d.fn=="string"?d.fn:void 0,exp:g}}x();var ef=3,tf="llm",nf=new Set(["paused","error"]);function Ar(t,e,n){let r=t.doc(tf),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)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,a=!1,u=new Set,l=[],d=c=>{if(!i){i=c;for(let p of[...u])p(c);u.clear()}};return o&&l.push(r.onConnectionState(c=>{a&&(c.consecutiveFailures<ef||d(new X(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?l.push(r.onSynced(()=>{a=!0})):s&&l.push(t.onPhase(c=>{if(c.name==="live"){a=!0;return}a&&nf.has(c.name)&&d(new X(`the pooled session for app "${e}" lost its compute binding (phase "${c.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(c){return i?(c(i),()=>{}):(u.add(c),()=>u.delete(c))},dispose(){u.clear();for(let c of l.splice(0))c()}}}async function*Qo(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(u=>a(u))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}function rf(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new De(`the shared lane target (app slug "${t.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${e}.${t.appId}.${t.fnName??""}`}function bu(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=(p,h,g,v,I)=>{let b=g?Yo({laneId:p,roomDoc:y=>t.roomDoc(p,y)}):Yo({laneId:p,connector:(0,_u.createWebsocketDocConnector)({serverUrl:`ws://${v}/doc`,sessionId:p,token:()=>yu(p,t.tokenSecret,void 0,void 0,I),WebSocketPolyfill:vu.default})}),f=g?a(p):Ar(b,`lane:${p}`,{armOnFirstSync:!0}),m={session:b,responses:new It(b),gone:f,goneWatch:f,laneId:p,pool:h,inFlight:0,laneSession:b,self:g,host:v??""};return n.set(p,m),f.onGone(()=>u(m)),m},a=p=>{let h=null,g=!1,v=new Set,I=f=>{if(!h){h=f;for(let m of[...v])m(f);v.clear()}},b=t.hostedSignal?.(p,f=>{if(f){g=!0;return}g&&I(new X(`the lane ${p} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>h,onGone(f){return h?(f(h),()=>{}):(v.add(f),()=>v.delete(f))},dispose(){b?.(),v.clear()}}},u=p=>{l(p)&&(n.delete(p.laneId),r.delete(p.laneId),p.goneWatch?.dispose())},l=p=>{let h=p.laneId;return typeof h=="string"&&n.get(h)===p},d=(p,h)=>{throw t.metrics?.observeLane503Fast(h??""),s.set(p,e()),new Se(p)},c=async(p,h)=>{let g=rf(h);o.add(g);let v=e();try{let I=await t.laneWarmWaitMsFor?.(p,h)??t.laneColdWakeDefaultMs??0,b=await t.plane.pick({pool:g,model:p,holdMs:I});t.metrics?.observeLaneReady(p??"",b.length);let m=b.map(S=>({laneId:S.laneId,self:S.host===t.selfAddress,host:S.host})).sort((S,P)=>S.self!==P.self?S.self?-1:1:(r.get(S.laneId)??0)-(r.get(P.laneId)??0))[0];m||d(g,p);let y=n.get(m.laneId);return y?.goneWatch?.gone()&&(u(y),y=void 0),y&&(y.pool!==g||y.self!==m.self||y.host!==m.host)&&(u(y),y=void 0),y||(y=i(m.laneId,g,m.self,m.host,h.sharedOrgId??void 0)),y.inFlight+=1,r.set(m.laneId,(r.get(m.laneId)??0)+1),{app:g,entry:y,identity:{kind:"catalog",model_id:h.modelId??p??"",variant:h.variant??""}}}finally{t.metrics?.observeLanePick(p??"",e()-v)}};return{sessionFor(p,h){return c(p,h)},release(p){l(p)&&(p.inFlight=Math.max(0,p.inFlight-1),r.set(p.laneId,p.inFlight))},owns(p){return l(p)},entryFor(p){return n.get(p)??null},evict(p){l(p)&&(p.gone.dispose(),n.delete(p.laneId),r.set(p.laneId,0),p.laneSession.destroy())},async status(){let p=[...new Set([...o,...[...n.values()].map(v=>v.pool)])].sort(),h=await t.plane.status().catch(()=>[]),g=new Map(of(h));return Promise.all(p.map(async v=>{let I=g.get(v)??{pool:v,lanes:[],lastDemandAt:null};return{pool:v,lanes:I.lanes,lastDemandAt:I.lastDemandAt,local:[...n.values()].filter(b=>b.pool===v).map(b=>({laneId:b.laneId,inFlight:b.inFlight,self:b.self,host:b.host})),lastRefusalAt:s.get(v)??null}}))},async close(){for(let p of n.values())p.gone.dispose(),p.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(p=>({pool:p.pool,laneId:p.laneId,inFlight:p.inFlight}))}}}function of(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}x();var Ru=require("http");var sf="/pooler/v1/lanes/pick",af="/pooler/v1/lanes/status",uf=1e4;function Su(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),u=r===void 0?void 0:Buffer.from(JSON.stringify(r)),l=(0,Ru.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...u===void 0?{}:{"content-type":"application/json","content-length":String(u.byteLength)}},timeout:o},d=>{let c=[];d.on("data",p=>c.push(p)),d.on("end",()=>{let p=Buffer.concat(c).toString("utf8"),h=null;try{h=p===""?null:JSON.parse(p)}catch{h=null}s({status:d.statusCode??0,json:h})}),d.on("error",i)});l.on("timeout",()=>{l.destroy(new Error(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),l.on("error",i),l.end(u)})}function ku(t,e,n){if(t===503)return new Se(n);let r=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${r}`)}function xu(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=await Su(t,"POST",sf,{pool:e,model:n,hold_ms:r},r+uf);if(o.status!==200)throw ku(o.status,o.json,e);return(o.json?.lanes??[]).filter(i=>typeof i.lane_id=="string"&&i.lane_id!==""&&typeof i.host=="string"&&i.host!=="").map(i=>({laneId:i.lane_id,host:i.host}))},async status(){let e=await Su(t,"GET",af,void 0,5e3);if(e.status!==200)throw ku(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}x();var Cu=require("ws");x();var Au=xe(require("yjs"),1),Xt=xe(require("y-protocols/sync"),1),it=xe(require("y-protocols/awareness"),1),pe=xe(require("lib0/encoding"),1),Qt=xe(require("lib0/decoding"),1),Ou=xe(require("lib0/map"),1),Iu=xe(require("lodash.debounce"),1);x();var Eu=()=>{};var df=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,cf=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,pf=0,ff=1;var mf=process.env.GC!=="false"&&process.env.GC!=="0",gf=process.env.YPERSISTENCE,Or=null;if(typeof gf=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var Yt=new Map,Ir=0,es=1,hf=(t,e,n)=>{let r=pe.createEncoder();pe.writeVarUint(r,Ir),Xt.writeUpdate(r,t);let o=pe.toUint8Array(r);n.conns.forEach((s,i)=>An(n,i,o))},Zo=class extends Au.Doc{constructor(e){super({gc:mf}),this.name=e,this.conns=new Map,this.awareness=new it.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let d=this.conns.get(i);d!==void 0&&(r.forEach(c=>{d.add(c)}),s.forEach(c=>{d.delete(c)}))}let u=pe.createEncoder();pe.writeVarUint(u,es),pe.writeVarUint8Array(u,it.encodeAwarenessUpdate(this.awareness,a));let l=pe.toUint8Array(u);this.conns.forEach((d,c)=>{An(this,c,l)})};this.awareness.on("update",n),this.on("update",hf),!1}},ts=(t,e=!0)=>Ou.setIfUndefined(Yt,t,()=>{let n=new Zo(t);return n.gc=e,Or!==null&&Or.bindState(t,n),Yt.set(t,n),n}),yf=(t,e,n)=>{try{let r=pe.createEncoder(),o=Qt.createDecoder(n);switch(Qt.readVarUint(o)){case Ir:pe.writeVarUint(r,Ir),Xt.readSyncMessage(o,r,e,t),pe.length(r)>1&&An(e,t,pe.toUint8Array(r));break;case es:{it.applyAwarenessUpdate(e.awareness,Qt.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},zt=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),it.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Or!==null&&(Or.writeState(t.name,t).then(()=>{t.destroy()}),Yt.delete(t.name))}e.close()},An=(t,e,n)=>{e.readyState!==pf&&e.readyState!==ff&&zt(t,e);try{e.send(n,r=>{r!=null&&zt(t,e)})}catch{zt(t,e)}},wf=3e4,Tu=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=ts(n,r);o.conns.set(t,new Set),t.on("message",a=>yf(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&zt(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{zt(o,t),clearInterval(i)}}},wf);t.on("close",()=>{zt(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=pe.createEncoder();pe.writeVarUint(a,Ir),Xt.writeSyncStep1(a,o),An(o,t,pe.toUint8Array(a));let u=o.awareness.getStates();if(u.size>0){let l=pe.createEncoder();pe.writeVarUint(l,es),pe.writeVarUint8Array(l,it.encodeAwarenessUpdate(o.awareness,Array.from(u.keys()))),An(o,t,pe.toUint8Array(l))}}};var ns="/doc/",Lu=30,_f=1e4,Pu="llm";function vf(t){if(!t.startsWith(ns))return null;let e=t.slice(ns.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function On(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
71
71
  `;t.end(`HTTP/1.1 ${e} ${r}\r
72
72
  Connection: close\r
73
73
  Content-Type: text/plain; charset=utf-8\r
74
74
  Content-Length: ${Buffer.byteLength(o)}\r
75
75
  \r
76
- ${o}`)}function Au(t,e){let n=new xu.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=b=>o.get(`${b}/${Ru}`)??0,a=b=>s.get(b)??0,u=new Map,l=new Map,d=new Set,c=new Set,p=!1,h=(b,f,m)=>{let y=i(b)>0,_=a(b),v=_>0,R=`${b}/${f}`,E=o.get(R)??0;m>0?o.set(R,m):o.delete(R);let O=_+m-E;O>0?s.set(b,O):s.delete(b);let I=i(b)>0,C=O>0;if(y!==I){I?g(b):k(b);for(let T of u.get(b)??[])T(I)}v&&!C&&queueMicrotask(()=>{let T=`${b}/`;for(let[j,W]of[...zt.entries()])!j.startsWith(T)||W.conns.size>0||(zt.delete(j),W.destroy())})},g=b=>{if(!e.hostRegistry||l.has(b))return;let f=()=>{e.hostRegistry?.setHost(b,e.selfAddress).catch(()=>{})};f();let m=setInterval(f,cf);m.unref?.(),l.set(b,m)},k=b=>{let f=l.get(b);f&&(clearInterval(f),l.delete(b)),e.hostRegistry&&e.hostRegistry.delHost(b,e.selfAddress).catch(()=>{})},P=(b,f,m)=>{let y;try{y=new URL(b.url??"/","http://localhost")}catch{On(f,400,"malformed upgrade URL");return}f.on("error",()=>f.destroy()),f.on("close",()=>c.delete(f));let _=pf(y.pathname);if(!_){if(y.pathname.startsWith(es)){On(f,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(f);return}d.add(f);let v=!1;(async()=>{let R=y.searchParams.get("token")??"",E=null;try{E=R===""?null:await e.verifyToken(R,_.laneId,_.docName)}catch{E=null}if(E===null){On(f,401,"invalid or missing lane doc token");return}let O=E;if(O.tenant!==void 0&&e.laneTenantOf){let I=null;try{I=await e.laneTenantOf(_.laneId)}catch{I=null}if(I==null||I==="")e.onLaneTenantMissing?.();else if(O.tenant!==I){On(f,403,"lane doc token org does not match the lane record");return}}p||f.destroyed||(v=!0,n.handleUpgrade(b,f,m,I=>{d.delete(f),r.add(I),I.on("close",()=>r.delete(I));let C=O.scope===lu||O.scope===void 0&&typeof O.app=="string"&&typeof O.fn=="string"&&O.aud==="sfu";if(C){let j=`${_.laneId}/${_.docName}`,W=(o.get(j)??0)+1;h(_.laneId,_.docName,W),W>1&&_.docName===Ru&&e.hostRegistry?.setHost(_.laneId,e.selfAddress).catch(()=>{})}I.on("close",()=>{if(!C)return;let j=`${_.laneId}/${_.docName}`;h(_.laneId,_.docName,Math.max(0,(o.get(j)??1)-1))}),ku(I,b,{docName:`${_.laneId}/${_.docName}`,gc:!0})}))})().catch(()=>{!v&&!f.destroyed&&On(f,500,"lane doc upgrade failed")}).finally(()=>d.delete(f))};return t.on("upgrade",P),{async close(){p=!0,t.off("upgrade",P);for(let f of[...l.keys()])k(f);await new Promise(f=>{if(r.size===0&&d.size===0){f();return}let m=r.size+d.size,y=()=>{m-=1,m<=0&&f()};for(let _ of r)_.once("close",y);for(let _ of d)_.once("close",y);for(let _ of r)_.close(1001,"lane doc host shutting down");for(let _ of d)_.destroy()}),o.clear(),s.clear(),u.clear()},roomDoc(b,f){return Zo(`${b}/${f}`,!0)},isHosted(b){return i(b)>0},onHostedChange(b,f){let m=u.get(b);return m||(m=new Set,u.set(b,m)),m.add(f),f(i(b)>0),()=>{m.delete(f)}}}}x();var ff="urun:catalog:v1";function Ou(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,s=null,i=async()=>{let u=await t.redis.hgetall(ff),l=[];for(let d of Object.values(u))try{l.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
77
- `)}return r=l,o=n(),l},a=()=>r===null||n()-o>=e;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}var Xu=Re(require("ioredis"),1);x();var Pr=require("@urun-sh/core"),Fe=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},In=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},Qt=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function Cr(t){let e=(t??"").trim();if(e==="")throw new Fe("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 Fe("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var mf=60,gf=6e4,hf=4096;function yf(t){return t===401||t===403}var Tr=class{constructor(e){this.opts=e;this.mint=e.mint??Pr.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new Fe("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<gf)return{apiKey:e,orgId:n.orgId,...n.billingAudience!==void 0?{billingAudience:n.billingAudience}:{},...n.creditsAdmissionOk!==void 0?{creditsAdmissionOk:n.creditsAdmissionOk}:{},...n.creditsRefusalReason!==void 0?{creditsRefusalReason:n.creditsRefusalReason}:{}};let r,o;try{let s=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:mf});r=s.orgId,o={...s.billingAudience!==void 0?{billingAudience:s.billingAudience}:{},...s.creditsAdmissionOk!==void 0?{creditsAdmissionOk:s.creditsAdmissionOk}:{},...s.creditsRefusalReason!==void 0?{creditsRefusalReason:s.creditsRefusalReason}:{}}}catch(s){throw s instanceof Pr.ClientTokenError&&yf(s.status)?(this.cache.delete(e),new Fe("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Qt("the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the API key against the control plane at ${this.opts.gatewayUrl}: ${s instanceof Error?s.message:String(s)}`)}if(!r)throw new Qt("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>=hf){let s=this.cache.keys().next();s.done||this.cache.delete(s.value)}return this.cache.set(e,{orgId:r,at:this.now(),...o}),{apiKey:e,orgId:r,...o}}clear(){this.cache.clear()}};x();var Tn=require("crypto");x();var Pe=require("@urun-sh/core");x();async function Iu(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,serve_app_slug,serve_function,created_at,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 Tu=require("@urun-sh/core"),ts=2;function wf(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function _f(t){let e=t?.type;return e==="response.completed"||e==="error"}function Pu(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=ts;i++){let{app:a,entry:u,identity:l}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(u)??null,identity:l});let d=!1,c=!1;try{let p=await t.createStream(u,n);for await(let h of p){if(_f(h)&&(d=!0),wf(h)){if(i>1)continue}else c=!0;yield h}}catch(p){if(p instanceof Tu.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,u,p)}catch{}throw p}if(i<ts&&!c){await t.evict(a,u);continue}throw p}if(d)return;if(i<ts&&!c){await t.evict(a,u);continue}return}})()}}var Nu=require("crypto");x();var vf="audio";var Cu=new WeakMap;function Lu(t,e,n){let r=t.doc(vf),o=[],s=0,i=0;return{sessionId:e,appendInputAudio(a){let u=Buffer.from(a,"base64");if(u.byteLength===0||(o.push(u),s+=u.byteLength,s<4800))return;let l=Buffer.concat(o,s).toString("base64");if(o=[],s=0,n===void 0){let d=(Cu.get(t)??0)+1;Cu.set(t,d),r.set({frames:{[String(d%32)]:{s:d,pcm16:l}}})}else{let d=++i;r.set({frames:{[`${n}:${d%32}`]:{s:d,pcm16:l,c:n}}})}},onOutputAudio(){return()=>{}}}}var Sf=0,kf=4,Rf=4;function Uu(t,e){let n=(i,a)=>{let u=(t[i]??"").trim();if(!u)return a;let l=Number.parseInt(u,10);if(!Number.isInteger(l)||l<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Sf;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 s=n("URUN_DECISION_POOL_MAX",Math.max(o,kf));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Rf),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function Mu(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 s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function Du(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,u=t.sessionStartOptions?.(n),l=r||u||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...u,...r}:void 0,d=k=>({session:k,responses:new Ot(k),gone:Ar(k,n)});if(i.lane==="jwt"){let k=(0,Pe.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(Mu(k,e.appSlug,a,l))}let{apiKey:c,gatewayUrl:p}=i,h=(typeof t.subject=="function"?t.subject():t.subject)??(0,Nu.randomUUID)(),g=(0,Pe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,Pe.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:h,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Mu(g,e.appSlug,a,l))}function xf(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 Fu(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 Ef=new Set(["error","paused"]);function ns(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=Du(t,i,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},s=new Nn({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>Bs({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>Iu(n):null),listPrices:n?()=>xs(n):null,shared:e.lane==="api-key"?()=>vs({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:xf});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},ut({appSlug:t.defaultApp}))),s}function Bu(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,a=d=>{process.stderr.write(`[decision-pool] ${d}
78
- `)},u=(d,c)=>{let p=o.get(c);if(p)return p;let h=new Zn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async g=>{let k=Du(t,d,c,{concurrencyKey:g.concurrencyKey});return k.gone.onGone(()=>h.markSessionDead(k)),await Mr(k.session),a(`slot attached pool=${c} slot=${g.concurrencyKey} session=${k.session.id??"(no id)"}`),k},closeSlot:async g=>{g.gone.dispose(),await g.session.end()},onDetach:(g,k)=>a(`slot detached pool=${c} slot=${g.concurrencyKey} reason=${k}`),terminalOpenFailure:g=>g instanceof Pe.SessionFailedError&&Fu(g)});return s.set(c,{target:d,env:n}),o.set(c,h),h},l=async(d,c)=>{let p=s.get(c);if(p)try{let h=await e.poolTuningFor(d);u(d,c).retune({min:h?.min??p.env.min,max:h?.max??p.env.max,inFlightCap:h?.in_flight_cap??p.env.inFlightCap,idleGraceMs:h?.idle_grace_s!==void 0?h.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:h?.warm_wait_s!==void 0?h.warm_wait_s*1e3:void 0})}catch(h){a(`pool tuning refresh failed pool=${c} reason=${h instanceof Error?h.message:String(h)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await u(d,ut(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=ut(c),h=u(c,p);await l(c,p);let g=await h.acquire({timeoutMs:h.requestWaitMs}),k=i.get(g.entry)??[];return k.push(g),i.set(g.entry,k),{app:p,entry:g.entry,identity:$n(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await u(c,ut(c)).boot()},end(d){let c=i.get(d)?.shift();c&&(i.get(d)?.length===0&&i.delete(d),c.release())},evict(d){for(let c of o.values())c.evict(d)},markSessionDead(d){for(let c of o.values())c.markSessionDead(d)},reap(){for(let[d,{target:c}]of s)l(c,d).then(()=>{let p=o.get(d);p&&p.reap()})},async pingReady(d){for(let c of o.values())if(await c.pingReady(d))return!0;return!1},stats(){return[...o.entries()].map(([d,c])=>({poolKey:d,...c.stats()}))},async drain(d){await Promise.all([...o.values()].map(c=>c.drain({timeoutMs:d})))},async close(){await Promise.all([...o.values()].map(d=>d.close()))}}}function Af(t){return(0,Pe.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?Pe.DEFAULT_WHEN_LIVE_TIMEOUT_MS:Pe.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:Pe.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Mr(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:Af(t.phase),signal:e})}async function $u(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 Lr(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function rs(t,e=Ei,n,r,o=So,s){let i=new WeakMap,a=new WeakMap,u=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let m=f.session.id;return typeof m=="string"&&m.length>0?m:null},p="lane",h=f=>{let m=Un(f);if(!s||!m||m.app!==p)return null;let y=s.entryFor(m.key);if(!y)throw new X(`the lane behind this handle (${m.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:m.key,entry:y}},g=async f=>h(f)?.entry??(await t.sessionForHandle(f)).entry,k=f=>{let m=i.get(f);if(!m){let y={waiting:0,gone:new AbortController};d.set(f,y),m=(async()=>{if(await Mr(f.session,y.gone.signal),y.gone.signal.aborted)throw Lr(y.gone.signal);d.get(f)===y&&d.delete(f);let _=await Ri(f.session,await e());return Object.assign(_,{sessionId:f.session.id})})(),i.set(f,m),m.catch(()=>{i.get(f)===m&&i.delete(f)}),m.then(()=>{d.get(f)===y&&d.delete(f)},()=>{d.get(f)===y&&d.delete(f)})}return m},P=f=>{let m=l.get(f);return m||(m=(async()=>{let y=await k(f);return{appendInputAudio:_=>y.appendInputAudio(_),onOutputAudio:_=>y.onOutputAudio(_),sessionId:c(f)}})(),l.set(f,m),m.catch(()=>{l.get(f)===m&&l.delete(f)})),m},b=async(f,m,y)=>{if(y?.aborted){let R=d.get(f);throw(i.get(f)===void 0||R!==void 0&&R.waiting===0)&&await $u(f.session),Lr(y)}let _=m(f),v=d.get(f);return v!==void 0&&v.waiting++,y===void 0?_:new Promise((R,E)=>{let O=()=>{v!==void 0&&--v.waiting===0&&d.get(f)===v&&(v.gone.abort(),d.delete(f),i.delete(f),l.delete(f),$u(f.session).catch(()=>{})),E(Lr(y))};y.addEventListener("abort",O,{once:!0});let I=()=>y.removeEventListener("abort",O);_.then(C=>{I(),R(C)},C=>{I(),E(C)})})};return{createResponse:Pu({sessionFor:s?async f=>{let m=await t.resolveTargetFor(f);if(m.sharedApp){let y=await s.sessionFor(f,m);return{app:y.app,entry:y.entry,identity:y.identity}}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,m)=>{s&&s.owns(m)?s.evict(m):r?r.evict(m):t.evict(f,m)},onAdmissionVerdict:(f,m,y)=>{Fu(y)&&(s&&s.owns(m)?s.evict(m):r?r.markSessionDead(m):t.evict(f,m),n?.(f,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,m)=>{try{await Mr(f.session);let y=ra(Yo(await f.responses.responses.create(m),f.gone),o);if(!r&&!s)return y;let _=f;return(async function*(){try{yield*y}catch(R){throw oa(R)&&(s&&s.owns(_)?s.evict(_):r&&(R instanceof X?r.markSessionDead(_):r.evict(_))),R}finally{s&&s.owns(_)?s.release(_):r?.end(_)}})()}catch(y){throw s&&s.owns(f)?s.release(f):r&&r.end(f),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,m)=>t.supportsImages(f,m),listImageModels:()=>t.imageModelList(),catalogIdentity:f=>t.catalogIdentityFor(f),servingAppSlug:async f=>await t.servingAppSlugFor(f),supportsAudio:f=>t.supportsAudio(f),supportsSpeech:f=>t.supportsSpeech(f),speechVoices:f=>t.speechVoices(f),supportsTranscription:f=>t.supportsTranscription(f),transcriptStreamFor:f=>t.transcriptStreamFor(f),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(f,m)=>{let{entry:y}=await t.sessionFor(f);return await b(y,k,m)},openAudioOn:async(f,m,y)=>{let _=h(f);if(_)return Lu(_.entry.session,_.laneId,y);let{entry:v}=await t.sessionForHandle(f);return await b(v,P,m)},openTurnsOn:async function*(f,m){if(m?.aborted)throw Lr(m);let y=await g(f);yield*Us(y.session,m)},openVideo:async f=>{let{entry:m}=await t.sessionFor(f),y=a.get(m);return y||(y=xi(m.session),a.set(m,y)),y},openVideoOut:async f=>{let{entry:m}=await t.sessionFor(f),y=u.get(m);return y||(y=Oi(m.session),u.set(m,y)),y},sessionHandle:async f=>{if(s){let m=await t.resolveTargetFor(f);if(m.sharedApp){let y=await s.sessionFor(f,m),_=c(y.entry);if(_===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Mn(p,_)}}return(await t.handleFor(f)).handle},releaseSessionHandle:f=>{let m=Un(f);if(!s||m?.app!==p)return;let y=s.entryFor(m.key);y&&s.release(y)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:m,entry:y}=await t.sessionForHandle(f);await t.evict(m,y)},createResponseOn:async(f,m,y)=>{let _=await g(f);await Mr(_.session);let v=y!==void 0&&h(f)?new Ot({..._.session,consumerId:y}):_.responses;return Yo(await v.responses.create(m),_.gone)},onSessionEnd:async(f,m)=>{let y=h(f);if(y)return y.entry.gone.onGone(E=>m({timeLeftMs:null,reason:E.message}));let{entry:_}=await t.sessionForHandle(f),v=_.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 R=!1;return v.onPhase(E=>{if(R||!Ef.has(E.name))return;R=!0;let O=v.endsAt??null;m({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:E.reason??`session ${E.name}`})})}}}x();var ju=require("http");var Of="/pooler/v1/inference",Zt=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds},If=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},Tf=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},qu=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),Pf=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await qu(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new Zt(t.status,e,n,t.retryAfterSeconds)};async function Cf(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${Of}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:If(e),firstMessage:Tf(e)}});return new Promise((a,u)=>{let l=(0,ju.request)({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let c=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(c)?c:void 0,body:d})});l.on("error",d=>u(new Zt(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),l.end(i)})}var Hu=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*Lf(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
76
+ ${o}`)}function Mu(t,e){let n=new Cu.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=b=>o.get(`${b}/${Pu}`)??0,a=b=>s.get(b)??0,u=new Map,l=new Map,d=new Set,c=new Set,p=!1,h=(b,f,m)=>{let y=i(b)>0,S=a(b),P=S>0,_=`${b}/${f}`,E=o.get(_)??0;m>0?o.set(_,m):o.delete(_);let O=S+m-E;O>0?s.set(b,O):s.delete(b);let R=i(b)>0,C=O>0;if(y!==R){R?g(b):v(b);for(let T of u.get(b)??[])T(R)}P&&!C&&queueMicrotask(()=>{let T=`${b}/`;for(let[D,V]of[...Yt.entries()])!D.startsWith(T)||V.conns.size>0||(Yt.delete(D),V.destroy())})},g=b=>{if(!e.hostRegistry||l.has(b))return;let f=()=>{e.hostRegistry?.setHost(b,e.selfAddress).catch(()=>{})};f();let m=setInterval(f,_f);m.unref?.(),l.set(b,m)},v=b=>{let f=l.get(b);f&&(clearInterval(f),l.delete(b)),e.hostRegistry&&e.hostRegistry.delHost(b,e.selfAddress).catch(()=>{})},I=(b,f,m)=>{let y;try{y=new URL(b.url??"/","http://localhost")}catch{On(f,400,"malformed upgrade URL");return}f.on("error",()=>f.destroy()),f.on("close",()=>c.delete(f));let S=vf(y.pathname);if(!S){if(y.pathname.startsWith(ns)){On(f,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(f);return}d.add(f);let P=!1;(async()=>{let _=y.searchParams.get("token")??"",E=null;try{E=_===""?null:await e.verifyToken(_,S.laneId,S.docName)}catch{E=null}if(E===null){On(f,401,"invalid or missing lane doc token");return}let O=E;if(O.tenant!==void 0&&e.laneTenantOf){let R=null;try{R=await e.laneTenantOf(S.laneId)}catch{R=null}if(R==null||R==="")e.onLaneTenantMissing?.();else if(O.tenant!==R){On(f,403,"lane doc token org does not match the lane record");return}}p||f.destroyed||(P=!0,n.handleUpgrade(b,f,m,R=>{d.delete(f),r.add(R),R.on("close",()=>r.delete(R));let C=O.scope===hu||O.scope===void 0&&typeof O.app=="string"&&typeof O.fn=="string"&&O.aud==="sfu";if(C){let D=`${S.laneId}/${S.docName}`,V=(o.get(D)??0)+1;h(S.laneId,S.docName,V),V>1&&S.docName===Pu&&e.hostRegistry?.setHost(S.laneId,e.selfAddress).catch(()=>{})}R.on("close",()=>{if(!C)return;let D=`${S.laneId}/${S.docName}`;h(S.laneId,S.docName,Math.max(0,(o.get(D)??1)-1))}),Tu(R,b,{docName:`${S.laneId}/${S.docName}`,gc:!0})}))})().catch(()=>{!P&&!f.destroyed&&On(f,500,"lane doc upgrade failed")}).finally(()=>d.delete(f))};return t.on("upgrade",I),{async close(){p=!0,t.off("upgrade",I);for(let f of[...l.keys()])v(f);await new Promise(f=>{if(r.size===0&&d.size===0){f();return}let m=r.size+d.size,y=()=>{m-=1,m<=0&&f()};for(let S of r)S.once("close",y);for(let S of d)S.once("close",y);for(let S of r)S.close(1001,"lane doc host shutting down");for(let S of d)S.destroy()}),o.clear(),s.clear(),u.clear()},roomDoc(b,f){return ts(`${b}/${f}`,!0)},isHosted(b){return i(b)>0},onHostedChange(b,f){let m=u.get(b);return m||(m=new Set,u.set(b,m)),m.add(f),f(i(b)>0),()=>{m.delete(f)}}}}x();var bf="urun:catalog:v1";function $u(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,s=null,i=async()=>{let u=await t.redis.hgetall(bf),l=[];for(let d of Object.values(u))try{l.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
77
+ `)}return r=l,o=n(),l},a=()=>r===null||n()-o>=e;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}var ol=xe(require("ioredis"),1);x();var Cr=require("@urun-sh/core"),Lr=require("crypto"),Nu="urun-session-gateway",Sf="machine",kf=3e5;function Rf(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var ge=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},In=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},Ke=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function Mr(t){let e=(t??"").trim();if(e==="")throw new ge("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 ge("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var xf=60,Ef=6e4,Af=4096;function Of(t){return t===401||t===403}var Tr=class{constructor(e){this.opts=e;this.mint=e.mint??Cr.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new ge("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<Ef)return{apiKey:e,orgId:n.orgId,credential:"api-key",...n.billingAudience!==void 0?{billingAudience:n.billingAudience}:{},...n.creditsAdmissionOk!==void 0?{creditsAdmissionOk:n.creditsAdmissionOk}:{},...n.creditsRefusalReason!==void 0?{creditsRefusalReason:n.creditsRefusalReason}:{}};let r,o;try{let s=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:xf});r=s.orgId,o={...s.billingAudience!==void 0?{billingAudience:s.billingAudience}:{},...s.creditsAdmissionOk!==void 0?{creditsAdmissionOk:s.creditsAdmissionOk}:{},...s.creditsRefusalReason!==void 0?{creditsRefusalReason:s.creditsRefusalReason}:{}}}catch(s){throw s instanceof Cr.ClientTokenError&&Of(s.status)?(this.cache.delete(e),new ge("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Ke("the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the API key against the control plane at ${this.opts.gatewayUrl}: ${s instanceof Error?s.message:String(s)}`)}if(!r)throw new Ke("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>=Af){let s=this.cache.keys().next();s.done||this.cache.delete(s.value)}return this.cache.set(e,{orgId:r,at:this.now(),...o}),{apiKey:e,orgId:r,credential:"api-key",...o}}clear(){this.cache.clear()}};function Uu(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var Pr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now}opts;fetchImpl;now;jwks=null;inFlight=null;async jwksKeys(e){if(!e&&this.jwks!==null&&this.now()-this.jwks.at<kf)return this.jwks.keys;if(this.inFlight!==null)return this.inFlight;this.inFlight=(async()=>{let r=`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,o;try{o=await this.fetchImpl(r,{signal:AbortSignal.timeout(3e3)})}catch(i){throw new Ke("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`could not fetch the machine issuer's JWKS at ${r}: ${i instanceof Error?i.message:String(i)}`)}if(!o.ok)throw new Ke("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered HTTP ${o.status}`);let s;try{let i=await o.json();if(!Array.isArray(i.keys))throw new Ke("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered no "keys" array`);s=i.keys}catch(i){throw i instanceof Ke?i:new Ke("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered a body that is not JSON`)}return s})().finally(()=>{this.inFlight=null});let n=await this.inFlight;return this.jwks={keys:n,at:this.now()},n}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new ge("malformed machine token");let s,i;try{s=Uu(n),i=Uu(r)}catch{throw new ge("malformed machine token")}if(s.alg!=="RS256")throw new ge(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",u=typeof i.iss=="string"?i.iss:"";if(u===""||!this.opts.issuers.includes(u))throw new ge(`machine token issuer is not one this endpoint accepts (${JSON.stringify(u)})`);if(i.aud!==Nu)throw new ge(`machine token audience must be ${Nu} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==Sf)throw new ge(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let l=typeof i.org_id=="string"?i.org_id:"";if(l==="")throw new ge("machine token carries no org_id \u2014 no tenancy to route by");if((typeof i.exp=="number"?i.exp:0)<=Math.floor(this.now()/1e3))throw new ge("machine token is expired \u2014 re-mint and retry");let c=b=>b.kty==="RSA"&&b.n!==void 0&&b.e!==void 0,p=await this.jwksKeys(!1),h=a===""?void 0:p.find(b=>b.kid===a&&c(b));if(h===void 0&&(p=await this.jwksKeys(!0),h=a===""?void 0:p.find(b=>b.kid===a&&c(b))),h===void 0)throw new ge(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let g=Buffer.from(`${n}.${r}`,"ascii"),v=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),I=!1;try{let b=(0,Lr.createPublicKey)({key:h,format:"jwk"});I=(0,Lr.verify)("RSA-SHA256",g,b,v)}catch{I=!1}if(!I)throw new ge("machine token signature failed verification");return{apiKey:e,orgId:l,credential:"machine"}}};function rs(t,e,n){return n!==null&&Rf(t)?n.verify(t):e.resolve(t)}x();var Tn=require("crypto");x();var Ae=require("@urun-sh/core");x();async function Du(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,serve_app_slug,serve_function,created_at,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 Fu=require("@urun-sh/core"),os=2;function If(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Tf(t){let e=t?.type;return e==="response.completed"||e==="error"}function Bu(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=os;i++){let{app:a,entry:u,identity:l}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(u)??null,identity:l});let d=!1,c=!1;try{let p=await t.createStream(u,n);for await(let h of p){if(Tf(h)&&(d=!0),If(h)){if(i>1)continue}else c=!0;yield h}}catch(p){if(p instanceof Fu.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,u,p)}catch{}throw p}if(i<os&&!c){await t.evict(a,u);continue}throw p}if(d)return;if(i<os&&!c){await t.evict(a,u);continue}return}})()}}var is=require("crypto");x();var Pf="audio";var Hu=new WeakMap;function ju(t,e,n){let r=t.doc(Pf),o=[],s=0,i=0;return{sessionId:e,appendInputAudio(a){let u=Buffer.from(a,"base64");if(u.byteLength===0||(o.push(u),s+=u.byteLength,s<4800))return;let l=Buffer.concat(o,s).toString("base64");if(o=[],s=0,n===void 0){let d=(Hu.get(t)??0)+1;Hu.set(t,d),r.set({frames:{[String(d%32)]:{s:d,pcm16:l}}})}else{let d=++i;r.set({frames:{[`${n}:${d%32}`]:{s:d,pcm16:l,c:n}}})}},onOutputAudio(){return()=>{}}}}var Lf=0,Mf=4,$f=4;function Gu(t,e){let n=(i,a)=>{let u=(t[i]??"").trim();if(!u)return a;let l=Number.parseInt(u,10);if(!Number.isInteger(l)||l<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Lf;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 s=n("URUN_DECISION_POOL_MAX",Math.max(o,Mf));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",$f),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function ss(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 s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function Wu(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,u=t.sessionStartOptions?.(n),l=r||u||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...u,...r}:void 0,d=v=>({session:v,responses:new It(v),gone:Ar(v,n)});if(i.lane==="jwt"){let v=(0,Ae.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(ss(v,e.appSlug,a,l))}if(i.lane==="machine"){let{machineToken:v,gatewayUrl:I}=i,b=(typeof t.subject=="function"?t.subject():t.subject)??(0,is.randomUUID)(),f=(0,Ae.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,Ae.createClientToken)(v,{baseUrl:I,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:b,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(ss(f,e.appSlug,a,l))}let{apiKey:c,gatewayUrl:p}=i,h=(typeof t.subject=="function"?t.subject():t.subject)??(0,is.randomUUID)(),g=(0,Ae.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,Ae.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:h,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(ss(g,e.appSlug,a,l))}function Nf(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 Vu(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 Uf=new Set(["error","paused"]);function as(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=Wu(t,i,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},s=new Nn({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>Vs({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>Du(n):null),listPrices:n?()=>Ps(n):null,shared:e.lane==="api-key"?()=>Es({apiUrl:t.apiUrl,apiKey:e.apiKey}):e.lane==="machine"&&t.catalogRows?async()=>{let i=await t.catalogRows();return xs(i)}:null,sessionKey:Nf});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},lt({appSlug:t.defaultApp}))),s}function Ju(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,a=d=>{process.stderr.write(`[decision-pool] ${d}
78
+ `)},u=(d,c)=>{let p=o.get(c);if(p)return p;let h=new Zn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async g=>{let v=Wu(t,d,c,{concurrencyKey:g.concurrencyKey});return v.gone.onGone(()=>h.markSessionDead(v)),await Nr(v.session),a(`slot attached pool=${c} slot=${g.concurrencyKey} session=${v.session.id??"(no id)"}`),v},closeSlot:async g=>{g.gone.dispose(),await g.session.end()},onDetach:(g,v)=>a(`slot detached pool=${c} slot=${g.concurrencyKey} reason=${v}`),terminalOpenFailure:g=>g instanceof Ae.SessionFailedError&&Vu(g)});return s.set(c,{target:d,env:n}),o.set(c,h),h},l=async(d,c)=>{let p=s.get(c);if(p)try{let h=await e.poolTuningFor(d);u(d,c).retune({min:h?.min??p.env.min,max:h?.max??p.env.max,inFlightCap:h?.in_flight_cap??p.env.inFlightCap,idleGraceMs:h?.idle_grace_s!==void 0?h.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:h?.warm_wait_s!==void 0?h.warm_wait_s*1e3:void 0})}catch(h){a(`pool tuning refresh failed pool=${c} reason=${h instanceof Error?h.message:String(h)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await u(d,lt(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=lt(c),h=u(c,p);await l(c,p);let g=await h.acquire({timeoutMs:h.requestWaitMs}),v=i.get(g.entry)??[];return v.push(g),i.set(g.entry,v),{app:p,entry:g.entry,identity:$n(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await u(c,lt(c)).boot()},end(d){let c=i.get(d)?.shift();c&&(i.get(d)?.length===0&&i.delete(d),c.release())},evict(d){for(let c of o.values())c.evict(d)},markSessionDead(d){for(let c of o.values())c.markSessionDead(d)},reap(){for(let[d,{target:c}]of s)l(c,d).then(()=>{let p=o.get(d);p&&p.reap()})},async pingReady(d){for(let c of o.values())if(await c.pingReady(d))return!0;return!1},stats(){return[...o.entries()].map(([d,c])=>({poolKey:d,...c.stats()}))},async drain(d){await Promise.all([...o.values()].map(c=>c.drain({timeoutMs:d})))},async close(){await Promise.all([...o.values()].map(d=>d.close()))}}}function Df(t){return(0,Ae.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?Ae.DEFAULT_WHEN_LIVE_TIMEOUT_MS:Ae.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:Ae.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Nr(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:Df(t.phase),signal:e})}async function qu(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 $r(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function us(t,e=Ci,n,r,o=Ro,s){let i=new WeakMap,a=new WeakMap,u=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let m=f.session.id;return typeof m=="string"&&m.length>0?m:null},p="lane",h=f=>{let m=Un(f);if(!s||!m||m.app!==p)return null;let y=s.entryFor(m.key);if(!y)throw new X(`the lane behind this handle (${m.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:m.key,entry:y}},g=async f=>h(f)?.entry??(await t.sessionForHandle(f)).entry,v=f=>{let m=i.get(f);if(!m){let y={waiting:0,gone:new AbortController};d.set(f,y),m=(async()=>{if(await Nr(f.session,y.gone.signal),y.gone.signal.aborted)throw $r(y.gone.signal);d.get(f)===y&&d.delete(f);let S=await Ti(f.session,await e());return Object.assign(S,{sessionId:f.session.id})})(),i.set(f,m),m.catch(()=>{i.get(f)===m&&i.delete(f)}),m.then(()=>{d.get(f)===y&&d.delete(f)},()=>{d.get(f)===y&&d.delete(f)})}return m},I=f=>{let m=l.get(f);return m||(m=(async()=>{let y=await v(f);return{appendInputAudio:S=>y.appendInputAudio(S),onOutputAudio:S=>y.onOutputAudio(S),sessionId:c(f)}})(),l.set(f,m),m.catch(()=>{l.get(f)===m&&l.delete(f)})),m},b=async(f,m,y)=>{if(y?.aborted){let _=d.get(f);throw(i.get(f)===void 0||_!==void 0&&_.waiting===0)&&await qu(f.session),$r(y)}let S=m(f),P=d.get(f);return P!==void 0&&P.waiting++,y===void 0?S:new Promise((_,E)=>{let O=()=>{P!==void 0&&--P.waiting===0&&d.get(f)===P&&(P.gone.abort(),d.delete(f),i.delete(f),l.delete(f),qu(f.session).catch(()=>{})),E($r(y))};y.addEventListener("abort",O,{once:!0});let R=()=>y.removeEventListener("abort",O);S.then(C=>{R(),_(C)},C=>{R(),E(C)})})};return{createResponse:Bu({sessionFor:s?async f=>{let m=await t.resolveTargetFor(f);if(m.sharedApp){let y=await s.sessionFor(f,m);return{app:y.app,entry:y.entry,identity:y.identity}}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,m)=>{s&&s.owns(m)?s.evict(m):r?r.evict(m):t.evict(f,m)},onAdmissionVerdict:(f,m,y)=>{Vu(y)&&(s&&s.owns(m)?s.evict(m):r?r.markSessionDead(m):t.evict(f,m),n?.(f,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,m)=>{try{await Nr(f.session);let y=la(Qo(await f.responses.responses.create(m),f.gone),o);if(!r&&!s)return y;let S=f;return(async function*(){try{yield*y}catch(_){throw da(_)&&(s&&s.owns(S)?s.evict(S):r&&(_ instanceof X?r.markSessionDead(S):r.evict(S))),_}finally{s&&s.owns(S)?s.release(S):r?.end(S)}})()}catch(y){throw s&&s.owns(f)?s.release(f):r&&r.end(f),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,m)=>t.supportsImages(f,m),listImageModels:()=>t.imageModelList(),catalogIdentity:f=>t.catalogIdentityFor(f),servingAppSlug:async f=>await t.servingAppSlugFor(f),supportsAudio:f=>t.supportsAudio(f),supportsSpeech:f=>t.supportsSpeech(f),speechVoices:f=>t.speechVoices(f),supportsTranscription:f=>t.supportsTranscription(f),transcriptStreamFor:f=>t.transcriptStreamFor(f),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(f,m)=>{let{entry:y}=await t.sessionFor(f);return await b(y,v,m)},openAudioOn:async(f,m,y)=>{let S=h(f);if(S)return ju(S.entry.session,S.laneId,y);let{entry:P}=await t.sessionForHandle(f);return await b(P,I,m)},openTurnsOn:async function*(f,m){if(m?.aborted)throw $r(m);let y=await g(f);yield*qs(y.session,m)},openVideo:async f=>{let{entry:m}=await t.sessionFor(f),y=a.get(m);return y||(y=Pi(m.session),a.set(m,y)),y},openVideoOut:async f=>{let{entry:m}=await t.sessionFor(f),y=u.get(m);return y||(y=Mi(m.session),u.set(m,y)),y},sessionHandle:async f=>{if(s){let m=await t.resolveTargetFor(f);if(m.sharedApp){let y=await s.sessionFor(f,m),S=c(y.entry);if(S===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Mn(p,S)}}return(await t.handleFor(f)).handle},releaseSessionHandle:f=>{let m=Un(f);if(!s||m?.app!==p)return;let y=s.entryFor(m.key);y&&s.release(y)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:m,entry:y}=await t.sessionForHandle(f);await t.evict(m,y)},createResponseOn:async(f,m,y)=>{let S=await g(f);await Nr(S.session);let P=y!==void 0&&h(f)?new It({...S.session,consumerId:y}):S.responses;return Qo(await P.responses.create(m),S.gone)},onSessionEnd:async(f,m)=>{let y=h(f);if(y)return y.entry.gone.onGone(E=>m({timeLeftMs:null,reason:E.message}));let{entry:S}=await t.sessionForHandle(f),P=S.session;if(typeof P.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let _=!1;return P.onPhase(E=>{if(_||!Uf.has(E.name))return;_=!0;let O=P.endsAt??null;m({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:E.reason??`session ${E.name}`})})}}}x();var zu=require("http");var Ff="/pooler/v1/inference",Zt=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Bf=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},Hf=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},Yu=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),jf=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await Yu(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new Zt(t.status,e,n,t.retryAfterSeconds)};async function qf(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${Ff}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Bf(e),firstMessage:Hf(e)}});return new Promise((a,u)=>{let l=(0,zu.request)({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let c=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(c)?c:void 0,body:d})});l.on("error",d=>u(new Zt(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),l.end(i)})}var Ku=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*Gf(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
79
79
 
80
- `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=Hu(s);i!==null&&(yield i)}let n=Hu(e);n!==null&&(yield n)}async function Gu(t,e,n,r){let o=kr(e,n,r),s=o.model??"";if(s==="")throw new Zt(400,"missing_model","the pooler submit requires a model");let i=await Cf(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Pf(i);let a=e.stream===!0?xr(n,Lf(i)):await Mf(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Mf(t,e){let n=await qu(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new Zt(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return xr(e,(async function*(){yield o})())}var $f=512;function os(t){return`urun-inference-proxy-${(0,Tn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var $r=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){let r=Object.assign(Object.create(e),{tenant:n.orgId}),o=this.opts.pooler;return o===void 0?r:Object.assign(Object.create(r),{createResponse:(s,i)=>{let a=`px_${(0,Tn.randomUUID)()}`;return Gu(o,s,a,a)}})}build(e){if(this.opts.build){let s=this.opts.build(e);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,e),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:co,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:Uu(process.env,process.env.HOSTNAME)??void 0},r=ns(n),o=n.decisionPool?Bu(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(rs(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),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>=$f;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.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(s=>{n.push(String(s instanceof Error?s.message:s))})];r.decision&&o.push(r.decision.close().catch(s=>{n.push(String(s instanceof Error?s.message:s))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Vu=512,Nf=1024,Nr=class extends Error{constructor(){super(`conversation capacity reached (${Vu} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Uf(t){return{sessionStartOptions:e=>{if(e.startsWith(an))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(an)||t.set(e,n)}}}function Df(t,e,n,r){let o=ns({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:co,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...Uf(r)});return{clients:rs(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var Ur=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${os(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):Df(this.opts,e,r,o);return{id:n,backhaul:s,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 s=this.build(e,n);return s.attachments=1,r.set(n,s),s}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Vu;){let e=this.byCaller.keys().next();if(e.done)throw new Nr;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[s,i]of r)if(!(i.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),i.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new Nr;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,Tn.randomUUID)())),n),s={createResponse:(i,a)=>o().backhaul.clients.createResponse(i,a),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{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(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),releaseSessionHandle:i=>o().backhaul.clients.releaseSessionHandle?.(i),createResponseOn:(i,a,u)=>o().backhaul.clients.createResponseOn(i,a,u),onSessionEnd:(i,a)=>o().backhaul.clients.onSessionEnd(i,a)};return s.openAudio=async(i,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(i,a)},s.openVideo=async i=>{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(i)},s.openVideoOut=async i=>{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(i)},s.supportsAudio=async i=>{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(i)},s.supportsSpeech=async i=>{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(i)},s.speechVoices=async i=>{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(i)},s.speechSessionHandle=async i=>{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(i)},s.openAudioOn=async(i,a,u)=>{let l=o().backhaul.clients.openAudioOn;if(l===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 l(i,a,u)},s.openTurnsOn=(i,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(i,a)},s.evictSpeechSession=async i=>{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(i)},s.supportsTranscription=async i=>{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(i)},s.transcriptStreamFor=async i=>{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(i)},s.listSpeechToTextModels=async()=>{let i=o().backhaul.clients.listSpeechToTextModels;if(i===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 i()},{clients:s,bindResumeHandle:i=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Nf;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async i=>{let a=this.byHandle.get(i),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 X("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 i=n;n=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.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 Dr="/inference-usage",Wu=25e3;var Ff=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Ju(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Ff.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 Fr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Dr}`,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(Wu)})}catch(i){throw new fe(`the uRun usage surface (POST ${Dr}) could not be reached within ${Wu}ms: ${Ju(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new Fe("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 i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new fe(`the uRun usage surface (POST ${Dr}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new fe(`the uRun usage surface (POST ${Dr}) answered HTTP ${o.status} with a body that is not JSON: ${Ju(i)}`)}return fi(s,this.opts.onRejectedRow)}};x();var Bf="/inference-ledger",Hf=1e4,Br=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},as=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},ke=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},us=class extends Fe{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ls=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},jf=[["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",ss],["output_minutes",ss],["cost_nano_usd",ss],["price_version",t=>t===null||typeof t=="string"]];function qf(t){for(let[e,n]of jf){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Gf(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"}:qf(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function ss(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function is(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Vf(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Ku(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 Wf(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&&Ku(t.started_at,n.started_at)&&Ku(t.completed_at,n.completed_at)&&is(t.prompt_tokens,n.prompt_tokens)&&is(t.completion_tokens,n.completion_tokens)&&is(t.output_units,n.output_units)&&Vf(t.output_minutes,n.output_minutes)}function Jf(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
81
- `)}async function Kf(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(Jf(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function zf(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ke(`${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 ke(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new ke(`${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 ke(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=l=>{if(!(l in n))throw new ke(`${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 ke(`${e} answered a non-string ${l}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new ke(`${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},i=s("price_version"),a=s("unpriced_reason"),u=o!=null;if(u&&(i===null||a!==null))throw new ke(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(i!==null||a===null))throw new ke(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, 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:i,unpriced_reason:a}}var Hr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Bf}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Kf(n,this.opts.signing)}):JSON.stringify(n)}catch(l){throw new ke(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${l instanceof Error?l.message:String(l)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(Hf)})}catch(l){throw new ke(`the uRun ledger surface at ${r} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(s.status===409){let l=await s.text().catch(()=>""),d=Gf(l);throw d.status==="found"&&Wf(n,d.row)?new as(d.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.`):d.status==="not_in_this_org"?new Br(`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 Br(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.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). ${l.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new us("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(!s.ok){let l=await s.text().catch(c=>`<body unreadable: ${c instanceof Error?c.message:String(c)}>`),d;try{let c=JSON.parse(l);if(c!==null&&typeof c=="object"&&"error"in c){let p=c.error;p!==null&&typeof p=="object"&&"code"in p&&(d=p.code)}}catch{}throw d==="ledger_signature_invalid"?new ls(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+l.slice(0,400)):new ke(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${l.slice(0,400)}`)}let i;try{i=await s.json()}catch(l){throw new ke(`the uRun ledger surface at ${r} answered a body that is not JSON: ${l instanceof Error?l.message:String(l)}`)}let a=i?.recorded;if(a===void 0)throw new ke(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let u=zf(a,`the uRun ledger surface at ${r}`);if(u.inference_id!==n.inference_id)throw new ke(`the uRun ledger surface at ${r} answered for inference_id ${u.inference_id} when asked about ${n.inference_id}`);return u}};var Yf=5e3,Xf=1e3,Qf=1500,Zf=3e3,em="/api/client-tokens";function jr(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function zu(t,e,n,r){jr(t,e,{error:{message:n,type:r}})}async function tm(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${em}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Zf)});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 Qu(t){let e=t.resolver??new Tr({gatewayUrl:t.baseUrl}),n=new Wn(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),r=null,o=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let v=new Xu.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),R=Ou({redis:v});return{registry:mu({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:wu({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(O,I)=>r?.onHostedChange(O,I)??(()=>()=>{}),roomDoc:(O,I)=>{if(!r)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return r.roomDoc(O,I)},metrics:n,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(O,I)=>R.rows().then(C=>{let T=no(C,I);return T?.warm_wait_s!==void 0?T.warm_wait_s*1e3:void 0})}),catalog:R,redis:v}})(),s=t.registry??new $r({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:o?null:t.catalog,catalogRows:o?()=>o.catalog.rows():void 0,lanes:o?.registry,pooler:t.pooler}),i=t.probeControlPlane??(()=>tm(t.baseUrl)),a=async()=>{let v=null;for(let O of s.decisionPools()){v=O;break}if(!v)return null;let R=v.stats();if(R.some(O=>O.draining))return{ok:!1,detail:"decision pool draining"};if(R.every(O=>O.attached===0&&O.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let E=await v.pingReady(Qf);return{ok:E,detail:E?"a decision slot answered its session ping":"no decision slot answered its session ping"}},u=t.usageClient??new Fr({apiUrl:t.apiUrl}),l=t.ledgerClient??new Hr({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),d=process.env.URUN_SHARED_ORG_ID?.trim(),c=process.env.URUN_SHARED_ORG_API_KEY?.trim();d&&c&&(async()=>{try{await s.decisionWarmerFor({orgId:d,apiKey:c})?.warmFor(qo)}catch(v){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(v instanceof Error?v.message:v)}
82
- `)}})();let p=async v=>e.resolve(Cr(v.headers.authorization)),h=async v=>{let R=await p(v);if(R.billingAudience==="platform"&&R.creditsAdmissionOk===!1){let E=R.creditsRefusalReason;throw new In(E==="spend_cap_reached"||E==="insufficient_credits"?E:void 0)}return R},g=v=>v instanceof Fe?{status:v.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:v instanceof In?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...v.code!==void 0?{code:v.code}:{}}:v instanceof Qt?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:v.detail}:null,k=Qa({clients:async v=>s.clientsFor(await h(v)),usage:{authorize:v=>Cr(v.headers.authorization),lookup:(v,R)=>u.lookup(v,R)},statusOf:g,...t.requestLog?{requestLog:t.requestLog}:{},observe:v=>n.observe(v),ledger:{write:(v,R)=>l.write(Cr(v.headers.authorization),R),observe:v=>n.observeLedger(v),...t.ledgerLog?{report:t.ledgerLog}:{}}}),P=null,b=null,f=(0,Yu.createServer)((v,R)=>{let E=new URL(v.url??"/","http://localhost");(async()=>{if(v.method==="GET"&&E.pathname==="/healthz"){jr(R,200,{ok:!0});return}if(v.method==="GET"&&E.pathname==="/readyz"){let C=Date.now();if((!P||C-P.at>=Yf)&&(P={at:C,...await i()}),!b||C-b.at>=Xf){let W=await a();b=W===null?{at:C,ok:!0,detail:null}:{at:C,ok:W.ok,detail:W.detail}}let T=(P?.ready??!1)&&b.ok,j=b.detail===null?P?.detail??"control plane not yet probed":`${P?.detail??"control plane not yet probed"}; ${b.detail}`;jr(R,T?200:503,{ok:T,control_plane:j});return}if(v.method==="GET"&&E.pathname==="/lanez"){jr(R,200,{pools:o?await o.registry.status():null});return}let O=E.pathname==="/v1"||E.pathname.startsWith("/v1/"),I=E.pathname.startsWith("/partners/");if(!O&&!I){zu(R,404,`no route for ${v.method} ${E.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, /readyz and /lanez`,"invalid_request_error");return}k(v,R)})().catch(O=>{if(!R.headersSent){zu(R,500,String(O instanceof Error?O.message:O),"proxy_error");return}R.end()})}),m=t.conversations??new Ur({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:o?null:t.catalog,catalogRows:o?()=>o.catalog.rows():void 0,lanes:o?.registry}),y=[ho(f,{authenticate:async v=>{let R=await e.resolve(v),E=m.connectionFor(R);return{clients:E.clients,scope:os(R.apiKey),onBindResumeHandle:E.bindResumeHandle,clientsForResume:E.clientsForResume,release:E.release}}}),Ao(f,{clients:async v=>s.clientsFor(await h(v)),statusOf:g}).close,lr(f,{resolver:{resolve:async(v,R)=>{let E=await h(v),O=m.connectionFor(E),I;try{I=await ru(Wo(O.clients,t.realtimeCompanions),tu(v),R,nu(v))}catch(T){throw O.release().catch(()=>{}),T}let C=I.release;return{...I,release:async()=>{await C?.(),await O.release()}}}}})];if(t.lane&&o){let v=t.lane,R=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;r=Au(f,{verifyToken:(O,I)=>cu(O,I,v.tokenSecret,void 0,R),selfAddress:v.selfAddress,laneTenantOf:O=>o.redis.get(`lane_tenant:${O}`),onLaneTenantMissing:()=>n.observeLaneDocTenantMissing(),previousTokenSecret:R,hostRegistry:{setHost:(O,I)=>o.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${O}`,I,String(Eu)),delHost:O=>o.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${O}`,v.selfAddress)}});let E=o;y.push(async()=>{await r.close(),await E.registry.close(),E.redis.quit().catch(()=>{})})}f.on("upgrade",(v,R)=>{let E=new URL(v.url??"/","http://localhost");E.pathname===Xn||E.pathname===xo||E.pathname===bn||r!==null&&E.pathname.startsWith("/doc/")||R.destroyed||(R.write(`HTTP/1.1 404 Not Found\r
80
+ `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=Ku(s);i!==null&&(yield i)}let n=Ku(e);n!==null&&(yield n)}async function Xu(t,e,n,r){let o=kr(e,n,r),s=o.model??"";if(s==="")throw new Zt(400,"missing_model","the pooler submit requires a model");let i=await qf(t,o,n,s,e.stream===!0);if(i.status>=400)throw await jf(i);let a=e.stream===!0?xr(n,Gf(i)):await Wf(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Wf(t,e){let n=await Yu(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new Zt(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return xr(e,(async function*(){yield o})())}var Vf=512;function ls(t){return`urun-inference-proxy-${(0,Tn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Ur=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){let r=Object.assign(Object.create(e),{tenant:n.orgId}),o=this.opts.pooler;return o===void 0?r:Object.assign(Object.create(r),{createResponse:(s,i)=>{let a=`px_${(0,Tn.randomUUID)()}`;return Xu(o,s,a,a)}})}build(e){if(this.opts.build){let s=this.opts.build(e);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,e),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:fo,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:Gu(process.env,process.env.HOSTNAME)??void 0},r=as(n),o=n.decisionPool?Ju(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(us(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),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>=Vf;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.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(s=>{n.push(String(s instanceof Error?s.message:s))})];r.decision&&o.push(r.decision.close().catch(s=>{n.push(String(s instanceof Error?s.message:s))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Qu=512,Jf=1024,Dr=class extends Error{constructor(){super(`conversation capacity reached (${Qu} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Kf(t){return{sessionStartOptions:e=>{if(e.startsWith(an))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(an)||t.set(e,n)}}}function zf(t,e,n,r){let o=as({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:fo,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...Kf(r)});return{clients:us(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var Fr=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${ls(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):zf(this.opts,e,r,o);return{id:n,backhaul:s,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 s=this.build(e,n);return s.attachments=1,r.set(n,s),s}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Qu;){let e=this.byCaller.keys().next();if(e.done)throw new Dr;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[s,i]of r)if(!(i.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),i.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new Dr;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,Tn.randomUUID)())),n),s={createResponse:(i,a)=>o().backhaul.clients.createResponse(i,a),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{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(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),releaseSessionHandle:i=>o().backhaul.clients.releaseSessionHandle?.(i),createResponseOn:(i,a,u)=>o().backhaul.clients.createResponseOn(i,a,u),onSessionEnd:(i,a)=>o().backhaul.clients.onSessionEnd(i,a)};return s.openAudio=async(i,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(i,a)},s.openVideo=async i=>{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(i)},s.openVideoOut=async i=>{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(i)},s.supportsAudio=async i=>{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(i)},s.supportsSpeech=async i=>{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(i)},s.speechVoices=async i=>{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(i)},s.speechSessionHandle=async i=>{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(i)},s.openAudioOn=async(i,a,u)=>{let l=o().backhaul.clients.openAudioOn;if(l===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 l(i,a,u)},s.openTurnsOn=(i,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(i,a)},s.evictSpeechSession=async i=>{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(i)},s.supportsTranscription=async i=>{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(i)},s.transcriptStreamFor=async i=>{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(i)},s.listSpeechToTextModels=async()=>{let i=o().backhaul.clients.listSpeechToTextModels;if(i===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 i()},{clients:s,bindResumeHandle:i=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Jf;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async i=>{let a=this.byHandle.get(i),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 X("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 i=n;n=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.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 Br="/inference-usage",Zu=25e3;var Yf=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function el(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Yf.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 Hr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Br}`,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(Zu)})}catch(i){throw new fe(`the uRun usage surface (POST ${Br}) could not be reached within ${Zu}ms: ${el(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new ge("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 i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new fe(`the uRun usage surface (POST ${Br}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new fe(`the uRun usage surface (POST ${Br}) answered HTTP ${o.status} with a body that is not JSON: ${el(i)}`)}return _i(s,this.opts.onRejectedRow)}};x();var Xf="/inference-ledger",Qf=1e4,jr=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},ps=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},Re=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},fs=class extends ge{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ms=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Zf=[["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",ds],["output_minutes",ds],["cost_nano_usd",ds],["price_version",t=>t===null||typeof t=="string"]];function em(t){for(let[e,n]of Zf){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function tm(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"}:em(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function ds(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function cs(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function nm(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function tl(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 rm(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&&tl(t.started_at,n.started_at)&&tl(t.completed_at,n.completed_at)&&cs(t.prompt_tokens,n.prompt_tokens)&&cs(t.completion_tokens,n.completion_tokens)&&cs(t.output_units,n.output_units)&&nm(t.output_minutes,n.output_minutes)}function om(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
81
+ `)}async function sm(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(om(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function im(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Re(`${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 Re(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new Re(`${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 Re(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=l=>{if(!(l in n))throw new Re(`${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 Re(`${e} answered a non-string ${l}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new Re(`${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},i=s("price_version"),a=s("unpriced_reason"),u=o!=null;if(u&&(i===null||a!==null))throw new Re(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(i!==null||a===null))throw new Re(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, 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:i,unpriced_reason:a}}var qr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Xf}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await sm(n,this.opts.signing)}):JSON.stringify(n)}catch(l){throw new Re(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${l instanceof Error?l.message:String(l)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(Qf)})}catch(l){throw new Re(`the uRun ledger surface at ${r} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(s.status===409){let l=await s.text().catch(()=>""),d=tm(l);throw d.status==="found"&&rm(n,d.row)?new ps(d.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.`):d.status==="not_in_this_org"?new jr(`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 jr(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.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). ${l.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new fs("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(!s.ok){let l=await s.text().catch(c=>`<body unreadable: ${c instanceof Error?c.message:String(c)}>`),d;try{let c=JSON.parse(l);if(c!==null&&typeof c=="object"&&"error"in c){let p=c.error;p!==null&&typeof p=="object"&&"code"in p&&(d=p.code)}}catch{}throw d==="ledger_signature_invalid"?new ms(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+l.slice(0,400)):new Re(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${l.slice(0,400)}`)}let i;try{i=await s.json()}catch(l){throw new Re(`the uRun ledger surface at ${r} answered a body that is not JSON: ${l instanceof Error?l.message:String(l)}`)}let a=i?.recorded;if(a===void 0)throw new Re(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let u=im(a,`the uRun ledger surface at ${r}`);if(u.inference_id!==n.inference_id)throw new Re(`the uRun ledger surface at ${r} answered for inference_id ${u.inference_id} when asked about ${n.inference_id}`);return u}};var am=5e3,um=1e3,lm=1500,dm=3e3,cm="/api/client-tokens";function Gr(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function nl(t,e,n,r){Gr(t,e,{error:{message:n,type:r}})}async function pm(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${cm}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(dm)});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 sl(t){let e=t.resolver??new Tr({gatewayUrl:t.baseUrl}),n=t.machine?new Pr({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=new Vn(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,s=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let _=new ol.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),E=$u({redis:_});return{registry:bu({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:xu({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(R,C)=>o?.onHostedChange(R,C)??(()=>()=>{}),roomDoc:(R,C)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(R,C)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(R,C)=>E.rows().then(T=>{let D=oo(T,C);return D?.warm_wait_s!==void 0?D.warm_wait_s*1e3:void 0})}),catalog:E,redis:_}})(),i=t.registry??new Ur({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:s?null:t.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry,pooler:t.pooler}),a=t.probeControlPlane??(()=>pm(t.baseUrl)),u=async()=>{let _=null;for(let R of i.decisionPools()){_=R;break}if(!_)return null;let E=_.stats();if(E.some(R=>R.draining))return{ok:!1,detail:"decision pool draining"};if(E.every(R=>R.attached===0&&R.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let O=await _.pingReady(lm);return{ok:O,detail:O?"a decision slot answered its session ping":"no decision slot answered its session ping"}},l=t.usageClient??new Hr({apiUrl:t.apiUrl}),d=t.ledgerClient??new qr({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),c=process.env.URUN_SHARED_ORG_ID?.trim(),p=process.env.URUN_SHARED_ORG_API_KEY?.trim();c&&p&&(async()=>{try{await i.decisionWarmerFor({orgId:c,apiKey:p})?.warmFor(Wo)}catch(_){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(_ instanceof Error?_.message:_)}
82
+ `)}})();let h=async _=>rs(Mr(_.headers.authorization),e,n),g=async _=>{let E=await h(_);if(E.billingAudience==="platform"&&E.creditsAdmissionOk===!1){let O=E.creditsRefusalReason;throw new In(O==="spend_cap_reached"||O==="insufficient_credits"?O:void 0)}return E},v=_=>_ instanceof ge?{status:_.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:_ instanceof In?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",..._.code!==void 0?{code:_.code}:{}}:_ instanceof Ke?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:_.detail}:null,I=ou({clients:async _=>i.clientsFor(await g(_)),usage:{authorize:_=>Mr(_.headers.authorization),lookup:(_,E)=>l.lookup(_,E)},statusOf:v,...t.requestLog?{requestLog:t.requestLog}:{},observe:_=>r.observe(_),ledger:{write:(_,E)=>d.write(Mr(_.headers.authorization),E),observe:_=>r.observeLedger(_),...t.ledgerLog?{report:t.ledgerLog}:{}}}),b=null,f=null,m=(0,rl.createServer)((_,E)=>{let O=new URL(_.url??"/","http://localhost");(async()=>{if(_.method==="GET"&&O.pathname==="/healthz"){Gr(E,200,{ok:!0});return}if(_.method==="GET"&&O.pathname==="/readyz"){let T=Date.now();if((!b||T-b.at>=am)&&(b={at:T,...await a()}),!f||T-f.at>=um){let J=await u();f=J===null?{at:T,ok:!0,detail:null}:{at:T,ok:J.ok,detail:J.detail}}let D=(b?.ready??!1)&&f.ok,V=f.detail===null?b?.detail??"control plane not yet probed":`${b?.detail??"control plane not yet probed"}; ${f.detail}`;Gr(E,D?200:503,{ok:D,control_plane:V});return}if(_.method==="GET"&&O.pathname==="/lanez"){Gr(E,200,{pools:s?await s.registry.status():null});return}let R=O.pathname==="/v1"||O.pathname.startsWith("/v1/"),C=O.pathname.startsWith("/partners/");if(!R&&!C){nl(E,404,`no route for ${_.method} ${O.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, /readyz and /lanez`,"invalid_request_error");return}I(_,E)})().catch(R=>{if(!E.headersSent){nl(E,500,String(R instanceof Error?R.message:R),"proxy_error");return}E.end()})}),y=t.conversations??new Fr({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:s?null:t.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry}),S=[wo(m,{authenticate:async _=>{let E=await rs(_,e,n),O=y.connectionFor(E);return{clients:O.clients,scope:ls(E.apiKey),onBindResumeHandle:O.bindResumeHandle,clientsForResume:O.clientsForResume,release:O.release}}}),Io(m,{clients:async _=>i.clientsFor(await g(_)),statusOf:v}).close,lr(m,{resolver:{resolve:async(_,E)=>{let O=await g(_),R=y.connectionFor(O),C;try{C=await lu(Ko(R.clients,t.realtimeCompanions),au(_),E,uu(_))}catch(D){throw R.release().catch(()=>{}),D}let T=C.release;return{...C,release:async()=>{await T?.(),await R.release()}}}}})];if(t.lane&&s){let _=t.lane,E=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=Mu(m,{verifyToken:(R,C)=>wu(R,C,_.tokenSecret,void 0,E),selfAddress:_.selfAddress,laneTenantOf:R=>s.redis.get(`lane_tenant:${R}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:E,hostRegistry:{setHost:(R,C)=>s.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${R}`,C,String(Lu)),delHost:R=>s.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${R}`,_.selfAddress)}});let O=s;S.push(async()=>{await o.close(),await O.registry.close(),O.redis.quit().catch(()=>{})})}m.on("upgrade",(_,E)=>{let O=new URL(_.url??"/","http://localhost");O.pathname===Xn||O.pathname===Ao||O.pathname===bn||o!==null&&O.pathname.startsWith("/doc/")||E.destroyed||(E.write(`HTTP/1.1 404 Not Found\r
83
83
  Connection: close\r
84
84
  \r
85
- no WS route for ${E.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),R.destroy())});let _=async()=>{for(let v of y)await v();await m.detachAll()};return{server:f,metricsServer:hi(n),metrics:n,edgeIdentityServer:_i(),registry:s,closeAll:()=>s.closeAll(),closeWebSockets:_}}async function Zu(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await ei()||ti(),await e()}function nm(){let t=null;return t=Vs({streams:Ke.default,note:e=>{t?.isDead("stderr")!==!0&&ze(Ke.default.stderr,e)}}),t}async function rm(){nm();let t=vi(Ke.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:s}=Qu(t);await new Promise((a,u)=>{e.once("error",u),e.listen(t.port,wt,a)}),await new Promise((a,u)=>{n.once("error",u),n.listen(ao,wt,a)}),await new Promise((a,u)=>{r.once("error",u),r.listen(lo,wt,a)}),Ke.default.stdout.write(`inference-proxy listening on http://${wt}:${t.port}/v1 (metrics http://${wt}:${ao}${qn}, edge identity http://${wt}:${lo}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
86
- `);let i=async a=>{Ke.default.stdout.write(`inference-proxy: ${a} \u2014 draining
87
- `),await Zu(e,o,s),await new Promise(u=>n.close(()=>u())),await new Promise(u=>r.close(()=>u()))};await new Promise(a=>{Ke.default.once("SIGINT",()=>{i("SIGINT").finally(a)}),Ke.default.once("SIGTERM",()=>{i("SIGTERM").finally(a)})})}rm().then(()=>Ke.default.exit(0),t=>{Ke.default.stderr.write(`inference-proxy: ${String(t instanceof Error?t.stack??t.message:t)}
88
- `),Ke.default.exit(1)});
85
+ no WS route for ${O.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),E.destroy())});let P=async()=>{for(let _ of S)await _();await y.detachAll()};return{server:m,metricsServer:Si(r),metrics:r,edgeIdentityServer:xi(),registry:i,closeAll:()=>i.closeAll(),closeWebSockets:P}}async function il(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await ii()||ai(),await e()}function fm(){let t=null;return t=Xs({streams:ze.default,note:e=>{t?.isDead("stderr")!==!0&&Ye(ze.default.stderr,e)}}),t}async function mm(){fm();let t=Ei(ze.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:s}=sl(t);await new Promise((a,u)=>{e.once("error",u),e.listen(t.port,_t,a)}),await new Promise((a,u)=>{n.once("error",u),n.listen(lo,_t,a)}),await new Promise((a,u)=>{r.once("error",u),r.listen(po,_t,a)}),ze.default.stdout.write(`inference-proxy listening on http://${_t}:${t.port}/v1 (metrics http://${_t}:${lo}${qn}, edge identity http://${_t}:${po}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
86
+ `);let i=async a=>{ze.default.stdout.write(`inference-proxy: ${a} \u2014 draining
87
+ `),await il(e,o,s),await new Promise(u=>n.close(()=>u())),await new Promise(u=>r.close(()=>u()))};await new Promise(a=>{ze.default.once("SIGINT",()=>{i("SIGINT").finally(a)}),ze.default.once("SIGTERM",()=>{i("SIGTERM").finally(a)})})}mm().then(()=>ze.default.exit(0),t=>{ze.default.stderr.write(`inference-proxy: ${String(t instanceof Error?t.stack??t.message:t)}
88
+ `),ze.default.exit(1)});
89
89
  /*! Bundled license information:
90
90
 
91
91
  reflect-metadata/Reflect.js: