@urun-sh/openai 0.6.36 → 0.6.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,37 +1,37 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Gl=Object.create;var Ds=Object.defineProperty;var Wl=Object.getOwnPropertyDescriptor;var Jl=Object.getOwnPropertyNames;var Vl=Object.getPrototypeOf,Kl=Object.prototype.hasOwnProperty;var zl=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Yl=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Xl=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Jl(e))!Kl.call(t,o)&&o!==n&&Ds(t,o,{get:()=>e[o],enumerable:!(r=Wl(e,o))||r.enumerable});return t};var Re=(t,e,n)=>(n=t!=null?Gl(Vl(t)):{},Xl(e||!t||!t.__esModule?Ds(n,"default",{value:t,enumerable:!0}):n,t));var E=zl(()=>{"use strict"});var Hs=Yl(()=>{"use strict";E();var Fs;(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 ao(Object.create(null))}:u?function(){return ao({__proto__:null})}:function(){return ao({})},has:l?function(v,k){return r.call(v,k)}:function(v,k){return k in v},get:l?function(v,k){return r.call(v,k)?v[k]:void 0}:function(v,k){return v[k]}},c=Object.getPrototypeOf(Function),p=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Fl(),m=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Hl(),h=typeof WeakMap=="function"?WeakMap:jl(),_=o?Symbol.for("@reflect-metadata:registry"):void 0,x=Nl(),w=Ul(x);function f(v,k,T,L){if(M(T)){if(!un(v))throw new TypeError;if(!Ps(k))throw new TypeError;return I(v,k)}else{if(!un(v))throw new TypeError;if(!se(k))throw new TypeError;if(!se(L)&&!M(L)&&!re(L))throw new TypeError;return re(L)&&(L=void 0),T=Le(T),U(v,k,T,L)}}e("decorate",f);function g(v,k){function T(L,G){if(!se(L))throw new TypeError;if(!M(G)&&!Ml(G))throw new TypeError;$e(v,k,L,G)}return T}e("metadata",g);function y(v,k,T,L){if(!se(T))throw new TypeError;return M(L)||(L=Le(L)),$e(v,k,T,L)}e("defineMetadata",y);function b(v,k,T){if(!se(k))throw new TypeError;return M(T)||(T=Le(T)),W(v,k,T)}e("hasMetadata",b);function C(v,k,T){if(!se(k))throw new TypeError;return M(T)||(T=Le(T)),K(v,k,T)}e("hasOwnMetadata",C);function P(v,k,T){if(!se(k))throw new TypeError;return M(T)||(T=Le(T)),te(v,k,T)}e("getMetadata",P);function S(v,k,T){if(!se(k))throw new TypeError;return M(T)||(T=Le(T)),ne(v,k,T)}e("getOwnMetadata",S);function A(v,k){if(!se(v))throw new TypeError;return M(k)||(k=Le(k)),oe(v,k)}e("getMetadataKeys",A);function R(v,k){if(!se(v))throw new TypeError;return M(k)||(k=Le(k)),ke(v,k)}e("getOwnMetadataKeys",R);function O(v,k,T){if(!se(k))throw new TypeError;if(M(T)||(T=Le(T)),!se(k))throw new TypeError;M(T)||(T=Le(T));var L=ln(k,T,!1);return M(L)?!1:L.OrdinaryDeleteMetadata(v,k,T)}e("deleteMetadata",O);function I(v,k){for(var T=v.length-1;T>=0;--T){var L=v[T],G=L(k);if(!M(G)&&!re(G)){if(!Ps(G))throw new TypeError;k=G}}return k}function U(v,k,T,L){for(var G=v.length-1;G>=0;--G){var ye=v[G],be=ye(k,T,L);if(!M(be)&&!re(be)){if(!se(be))throw new TypeError;L=be}}return L}function W(v,k,T){var L=K(v,k,T);if(L)return!0;var G=io(k);return re(G)?!1:W(v,G,T)}function K(v,k,T){var L=ln(k,T,!1);return M(L)?!1:Ce(L.OrdinaryHasOwnMetadata(v,k,T))}function te(v,k,T){var L=K(v,k,T);if(L)return ne(v,k,T);var G=io(k);if(!re(G))return te(v,G,T)}function ne(v,k,T){var L=ln(k,T,!1);if(!M(L))return L.OrdinaryGetOwnMetadata(v,k,T)}function $e(v,k,T,L){var G=ln(T,L,!0);G.OrdinaryDefineOwnMetadata(v,k,T,L)}function oe(v,k){var T=ke(v,k),L=io(v);if(L===null)return T;var G=oe(L,k);if(G.length<=0)return T;if(T.length<=0)return G;for(var ye=new m,be=[],Y=0,N=T;Y<N.length;Y++){var D=N[Y],H=ye.has(D);H||(ye.add(D),be.push(D))}for(var B=0,X=G;B<X.length;B++){var D=X[B],H=ye.has(D);H||(ye.add(D),be.push(D))}return be}function ke(v,k){var T=ln(v,k,!1);return T?T.OrdinaryOwnMetadataKeys(v,k):[]}function J(v){if(v===null)return 1;switch(typeof v){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return v===null?1:6;default:return 6}}function M(v){return v===void 0}function re(v){return v===null}function rt(v){return typeof v=="symbol"}function se(v){return typeof v=="object"?v!==null:typeof v=="function"}function ie(v,k){switch(J(v)){case 0:return v;case 1:return v;case 2:return v;case 3:return v;case 4:return v;case 5:return v}var T=k===3?"string":k===5?"number":"default",L=Cs(v,s);if(L!==void 0){var G=L.call(v,T);if(se(G))throw new TypeError;return G}return de(v,T==="default"?"number":T)}function de(v,k){if(k==="string"){var T=v.toString;if(st(T)){var L=T.call(v);if(!se(L))return L}var G=v.valueOf;if(st(G)){var L=G.call(v);if(!se(L))return L}}else{var G=v.valueOf;if(st(G)){var L=G.call(v);if(!se(L))return L}var ye=v.toString;if(st(ye)){var L=ye.call(v);if(!se(L))return L}}throw new TypeError}function Ce(v){return!!v}function ot(v){return""+v}function Le(v){var k=ie(v,3);return rt(k)?k:ot(k)}function un(v){return Array.isArray?Array.isArray(v):v instanceof Object?v instanceof Array:Object.prototype.toString.call(v)==="[object Array]"}function st(v){return typeof v=="function"}function Ps(v){return typeof v=="function"}function Ml(v){switch(J(v)){case 3:return!0;case 4:return!0;default:return!1}}function so(v,k){return v===k||v!==v&&k!==k}function Cs(v,k){var T=v[k];if(T!=null){if(!st(T))throw new TypeError;return T}}function Ls(v){var k=Cs(v,i);if(!st(k))throw new TypeError;var T=k.call(v);if(!se(T))throw new TypeError;return T}function Ms(v){return v.value}function $s(v){var k=v.next();return k.done?!1:k}function Ns(v){var k=v.return;k&&k.call(v)}function io(v){var k=Object.getPrototypeOf(v);if(typeof v!="function"||v===c||k!==c)return k;var T=v.prototype,L=T&&Object.getPrototypeOf(T);if(L==null||L===Object.prototype)return k;var G=L.constructor;return typeof G!="function"||G===v?k:G}function $l(){var v;!M(_)&&typeof n.Reflect<"u"&&!(_ in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(v=Dl(n.Reflect));var k,T,L,G=new h,ye={registerProvider:be,getProvider:N,setProvider:H};return ye;function be(B){if(!Object.isExtensible(ye))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case v===B:break;case M(k):k=B;break;case k===B:break;case M(T):T=B;break;case T===B:break;default:L===void 0&&(L=new m),L.add(B);break}}function Y(B,X){if(!M(k)){if(k.isProviderFor(B,X))return k;if(!M(T)){if(T.isProviderFor(B,X))return k;if(!M(L))for(var ue=Ls(L);;){var we=$s(ue);if(!we)return;var Ge=Ms(we);if(Ge.isProviderFor(B,X))return Ns(ue),Ge}}}if(!M(v)&&v.isProviderFor(B,X))return v}function N(B,X){var ue=G.get(B),we;return M(ue)||(we=ue.get(X)),M(we)&&(we=Y(B,X),M(we)||(M(ue)&&(ue=new p,G.set(B,ue)),ue.set(X,we))),we}function D(B){if(M(B))throw new TypeError;return k===B||T===B||!M(L)&&L.has(B)}function H(B,X,ue){if(!D(ue))throw new Error("Metadata provider not registered.");var we=N(B,X);if(we!==ue){if(!M(we))return!1;var Ge=G.get(B);M(Ge)&&(Ge=new p,G.set(B,Ge)),Ge.set(X,ue)}return!0}}function Nl(){var v;return!M(_)&&se(n.Reflect)&&Object.isExtensible(n.Reflect)&&(v=n.Reflect[_]),M(v)&&(v=$l()),!M(_)&&se(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,_,{enumerable:!1,configurable:!1,writable:!1,value:v}),v}function Ul(v){var k=new h,T={isProviderFor:function(D,H){var B=k.get(D);return M(B)?!1:B.has(H)},OrdinaryDefineOwnMetadata:be,OrdinaryHasOwnMetadata:G,OrdinaryGetOwnMetadata:ye,OrdinaryOwnMetadataKeys:Y,OrdinaryDeleteMetadata:N};return x.registerProvider(T),T;function L(D,H,B){var X=k.get(D),ue=!1;if(M(X)){if(!B)return;X=new p,k.set(D,X),ue=!0}var we=X.get(H);if(M(we)){if(!B)return;if(we=new p,X.set(H,we),!v.setProvider(D,H,T))throw X.delete(H),ue&&k.delete(D),new Error("Wrong provider for target.")}return we}function G(D,H,B){var X=L(H,B,!1);return M(X)?!1:Ce(X.has(D))}function ye(D,H,B){var X=L(H,B,!1);if(!M(X))return X.get(D)}function be(D,H,B,X){var ue=L(B,X,!0);ue.set(D,H)}function Y(D,H){var B=[],X=L(D,H,!1);if(M(X))return B;for(var ue=X.keys(),we=Ls(ue),Ge=0;;){var Us=$s(we);if(!Us)return B.length=Ge,B;var Bl=Ms(Us);try{B[Ge]=Bl}catch(ql){try{Ns(we)}finally{throw ql}}Ge++}}function N(D,H,B){var X=L(H,B,!1);if(M(X)||!X.delete(D))return!1;if(X.size===0){var ue=k.get(H);M(ue)||(ue.delete(B),ue.size===0&&k.delete(ue))}return!0}}function Dl(v){var k=v.defineMetadata,T=v.hasOwnMetadata,L=v.getOwnMetadata,G=v.getOwnMetadataKeys,ye=v.deleteMetadata,be=new h,Y={isProviderFor:function(N,D){var H=be.get(N);return!M(H)&&H.has(D)?!0:G(N,D).length?(M(H)&&(H=new m,be.set(N,H)),H.add(D),!0):!1},OrdinaryDefineOwnMetadata:k,OrdinaryHasOwnMetadata:T,OrdinaryGetOwnMetadata:L,OrdinaryOwnMetadataKeys:G,OrdinaryDeleteMetadata:ye};return Y}function ln(v,k,T){var L=x.getProvider(v,k);if(!M(L))return L;if(T){if(x.setProvider(v,k,w))return w;throw new Error("Illegal state.")}}function Fl(){var v={},k=[],T=(function(){function Y(N,D,H){this._index=0,this._keys=N,this._values=D,this._selector=H}return Y.prototype["@@iterator"]=function(){return this},Y.prototype[i]=function(){return this},Y.prototype.next=function(){var N=this._index;if(N>=0&&N<this._keys.length){var D=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:D,done:!1}}return{value:void 0,done:!0}},Y.prototype.throw=function(N){throw this._index>=0&&(this._index=-1,this._keys=k,this._values=k),N},Y.prototype.return=function(N){return this._index>=0&&(this._index=-1,this._keys=k,this._values=k),{value:N,done:!0}},Y})(),L=(function(){function Y(){this._keys=[],this._values=[],this._cacheKey=v,this._cacheIndex=-2}return Object.defineProperty(Y.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Y.prototype.has=function(N){return this._find(N,!1)>=0},Y.prototype.get=function(N){var D=this._find(N,!1);return D>=0?this._values[D]:void 0},Y.prototype.set=function(N,D){var H=this._find(N,!0);return this._values[H]=D,this},Y.prototype.delete=function(N){var D=this._find(N,!1);if(D>=0){for(var H=this._keys.length,B=D+1;B<H;B++)this._keys[B-1]=this._keys[B],this._values[B-1]=this._values[B];return this._keys.length--,this._values.length--,so(N,this._cacheKey)&&(this._cacheKey=v,this._cacheIndex=-2),!0}return!1},Y.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=v,this._cacheIndex=-2},Y.prototype.keys=function(){return new T(this._keys,this._values,G)},Y.prototype.values=function(){return new T(this._keys,this._values,ye)},Y.prototype.entries=function(){return new T(this._keys,this._values,be)},Y.prototype["@@iterator"]=function(){return this.entries()},Y.prototype[i]=function(){return this.entries()},Y.prototype._find=function(N,D){if(!so(this._cacheKey,N)){this._cacheIndex=-1;for(var H=0;H<this._keys.length;H++)if(so(this._keys[H],N)){this._cacheIndex=H;break}}return this._cacheIndex<0&&D&&(this._cacheIndex=this._keys.length,this._keys.push(N),this._values.push(void 0)),this._cacheIndex},Y})();return L;function G(Y,N){return Y}function ye(Y,N){return N}function be(Y,N){return[Y,N]}}function Hl(){var v=(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(T){return this._map.has(T)},k.prototype.add=function(T){return this._map.set(T,T),this},k.prototype.delete=function(T){return this._map.delete(T)},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 v}function jl(){var v=16,k=d.create(),T=L();return(function(){function N(){this._key=L()}return N.prototype.has=function(D){var H=G(D,!1);return H!==void 0?d.has(H,this._key):!1},N.prototype.get=function(D){var H=G(D,!1);return H!==void 0?d.get(H,this._key):void 0},N.prototype.set=function(D,H){var B=G(D,!0);return B[this._key]=H,this},N.prototype.delete=function(D){var H=G(D,!1);return H!==void 0?delete H[this._key]:!1},N.prototype.clear=function(){this._key=L()},N})();function L(){var N;do N="@@WeakMap@@"+Y();while(d.has(k,N));return k[N]=!0,N}function G(N,D){if(!r.call(N,T)){if(!D)return;Object.defineProperty(N,T,{value:d.create()})}return N[T]}function ye(N,D){for(var H=0;H<D;++H)N[H]=Math.random()*255|0;return N}function be(N){if(typeof Uint8Array=="function"){var D=new Uint8Array(N);return typeof crypto<"u"?crypto.getRandomValues(D):typeof msCrypto<"u"?msCrypto.getRandomValues(D):ye(D,N),D}return ye(new Array(N),N)}function Y(){var N=be(v);N[6]=N[6]&79|64,N[8]=N[8]&191|128;for(var D="",H=0;H<v;++H){var B=N[H];(H===4||H===6||H===8)&&(D+="-"),B<16&&(D+="0"),D+=B.toString(16).toLowerCase()}return D}}function ao(v){return v.__=void 0,delete v.__,v}})})(Fs||(Fs={}))});E();var Av=Re(Hs(),1),Qe=Re(require("process"),1);E();var Ed=Re(require("os"),1),xd=Re(require("path"),1),Ad=require("url"),Od=require("util");E();E();var ce=class extends Error{},Ql=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Zl(t){if(typeof t!="string")return!1;let e=Ql.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 ed(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",Zl(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 Nt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function js(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 ce(`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 uo(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 Bs(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 ed(await r.json())}E();function Ne(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}E();var De=class extends Error{name="ModelPriceError"},lo="per_million_input_tokens",co="per_million_output_tokens",Gs="model_id,variant,unit,price_usd,effective_at,expires_at",qs={per_request:!0,per_minute:!0,per_output_unit:!0},td=5e3;function nd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new De(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Ws(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new De(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function rd(t,e,n){return t===null?null:Ws(t,e,n)}function od(t,e){if(t===lo)return"input";if(t===co)return"output";if(typeof t=="string"&&Object.hasOwn(qs,t))return null;throw new De(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${lo} | ${co}) nor a known GPU-time unit (${Object.keys(qs).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 sd(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 po(t,e){return`${t}\0${e}`}function id(t){if(!Array.isArray(t))throw new De(`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 De(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of Gs.split(","))if(!Object.hasOwn(s,l))throw new De(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=od(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new De(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new De(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:nd(s.price_usd,o),effective_at:Ws(s.effective_at,o,"effective_at"),expires_at:rd(s.expires_at,o,"expires_at")})}return e}function Js(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,m,h)=>{let _=p&&p.length>0?p:d?.[m];if(!_||_.length===0)return null;let x=sd(_,m);return"reason"in x?x:x.rate.usd===0?m==="output"&&h!==null&&n?.has(po(u,h))?x.rate:{reason:`the ${m} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:x.rate};for(let[p,m]of o.get(u)){let h=l.get(p),_=c(h?.input,"input",m),x=c(h?.output,"output",m);if(_!==null&&"reason"in _){i.push({model_id:u,variant:m,reason:_.reason});continue}if(x!==null&&"reason"in x){i.push({model_id:u,variant:m,reason:x.reason});continue}_===null||x===null||s.push({model_id:u,variant:m,pricing:{input:_.usd,output:x.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 dn(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 cn={prices:[],refusals:[]};async function Vs(t){let e=t.fetchImpl??fetch,n=`${lo},${co}`,r=await e(`${t.catalogUrl}/model_prices?select=${Gs}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(td)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return id(await r.json())}E();var vt="/partners/openrouter/models",ad={chat:!0,code:!0,agent:!0,vl:!0},Ks={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function ud(t){let e=t.toLowerCase();return Object.hasOwn(Ks,e)?Ks[e]:null}var zs={"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 ld(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(zs,o)?zs[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 Ys={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Xs={2:"Llama2",3:"Llama3"};function dd(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(Ys,s))return Ys[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Xs,i))return Xs[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var cd=["context_length","max_model_len"];function pd(t){let e=cd.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 Fn(t){let e=t.map(pd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function fd(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function fo(t){if(t.length===0)return null;let e=t.map(fd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function mo(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 md(t,e){let n=e.filter(s=>Ne(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return pn(n);let r=e.filter(s=>Ne(s.model_id)===t);if(r.length>0)return pn(r);let o=mo(t,e);return o.length>0?pn(o):null}function pn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:gd(t),matches:t}:null}function gd(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 ct=class extends Error{name="ModelCreatedError"};function Ut(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 ct(`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 ct(`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 ct(`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 ct(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return u/1e3}function _t(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 Hn(t,e,n){let r=md(t,e);if(!r)return _t({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Fn(s),a=Ut(s),u=dn(o.model_id,o.variant,n),l=ei(o,s),d=fo(s);return _t({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 hd=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function ei(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:[...hd],defect:o}:{published:[],defect:o}}function go(t){let e=t.length>0?pn(t):null;return e===null?{published:[],defect:null}:ei(e.row,e.matches)}function Qs(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 Zs(t){return{input:[{type:"prompt",unit:"token",cost_usd:Qs(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Qs(t.output)}]}}function yd(t,e,n,r){if(e.length===0)return null;let o=pn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||ad[s.task]!==!0)return null;let a=Fn(i),u=dn(s.model_id,s.variant,n),l=dd(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:Ut(i),quantization:ud(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:Zs(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...u?{pricing:Zs(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function ti(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?Nt(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:ld(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=yd(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&a.push(c)}return{data:a}}E();var ni={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},Dt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function ri(t){let e=t.t;if(typeof e!="string"||!(e in ni))throw new Dt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(ni).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 wd(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Dt(`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 Dt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return ri(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Dt(`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 ri(t)}function oi(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function _d(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 si(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 oi(e);let s=o.next();if(e!==void 0&&await _d(s,e)==="aborted")throw s.catch(()=>{}),oi(e);let i=await s;if(i.done)return;yield wd(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var ee=class extends Error{},Q=class extends Error{},yo="urs1.";function Bn(t,e){return yo+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Wn(t){if(!t.startsWith(yo))return null;try{let e=JSON.parse(Buffer.from(t.slice(yo.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 ui(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 ii(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Sd(t);return e===null?[]:[e]}function vd(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 Gl=Object.create;var Ds=Object.defineProperty;var Wl=Object.getOwnPropertyDescriptor;var Jl=Object.getOwnPropertyNames;var Vl=Object.getPrototypeOf,Kl=Object.prototype.hasOwnProperty;var zl=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Yl=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Xl=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Jl(e))!Kl.call(t,o)&&o!==n&&Ds(t,o,{get:()=>e[o],enumerable:!(r=Wl(e,o))||r.enumerable});return t};var Re=(t,e,n)=>(n=t!=null?Gl(Vl(t)):{},Xl(e||!t||!t.__esModule?Ds(n,"default",{value:t,enumerable:!0}):n,t));var x=zl(()=>{"use strict"});var Hs=Yl(()=>{"use strict";x();var Fs;(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 ao(Object.create(null))}:u?function(){return ao({__proto__:null})}:function(){return ao({})},has:l?function(b,R){return r.call(b,R)}:function(b,R){return R in b},get:l?function(b,R){return r.call(b,R)?b[R]:void 0}:function(b,R){return b[R]}},c=Object.getPrototypeOf(Function),p=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Fl(),m=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Hl(),h=typeof WeakMap=="function"?WeakMap:jl(),_=o?Symbol.for("@reflect-metadata:registry"):void 0,S=Nl(),w=Ul(S);function f(b,R,T,L){if(M(T)){if(!un(b))throw new TypeError;if(!Ps(R))throw new TypeError;return I(b,R)}else{if(!un(b))throw new TypeError;if(!se(R))throw new TypeError;if(!se(L)&&!M(L)&&!re(L))throw new TypeError;return re(L)&&(L=void 0),T=Le(T),U(b,R,T,L)}}e("decorate",f);function g(b,R){function T(L,G){if(!se(L))throw new TypeError;if(!M(G)&&!Ml(G))throw new TypeError;$e(b,R,L,G)}return T}e("metadata",g);function y(b,R,T,L){if(!se(T))throw new TypeError;return M(L)||(L=Le(L)),$e(b,R,T,L)}e("defineMetadata",y);function v(b,R,T){if(!se(R))throw new TypeError;return M(T)||(T=Le(T)),W(b,R,T)}e("hasMetadata",v);function C(b,R,T){if(!se(R))throw new TypeError;return M(T)||(T=Le(T)),K(b,R,T)}e("hasOwnMetadata",C);function P(b,R,T){if(!se(R))throw new TypeError;return M(T)||(T=Le(T)),te(b,R,T)}e("getMetadata",P);function k(b,R,T){if(!se(R))throw new TypeError;return M(T)||(T=Le(T)),ne(b,R,T)}e("getOwnMetadata",k);function A(b,R){if(!se(b))throw new TypeError;return M(R)||(R=Le(R)),oe(b,R)}e("getMetadataKeys",A);function E(b,R){if(!se(b))throw new TypeError;return M(R)||(R=Le(R)),ke(b,R)}e("getOwnMetadataKeys",E);function O(b,R,T){if(!se(R))throw new TypeError;if(M(T)||(T=Le(T)),!se(R))throw new TypeError;M(T)||(T=Le(T));var L=ln(R,T,!1);return M(L)?!1:L.OrdinaryDeleteMetadata(b,R,T)}e("deleteMetadata",O);function I(b,R){for(var T=b.length-1;T>=0;--T){var L=b[T],G=L(R);if(!M(G)&&!re(G)){if(!Ps(G))throw new TypeError;R=G}}return R}function U(b,R,T,L){for(var G=b.length-1;G>=0;--G){var ye=b[G],be=ye(R,T,L);if(!M(be)&&!re(be)){if(!se(be))throw new TypeError;L=be}}return L}function W(b,R,T){var L=K(b,R,T);if(L)return!0;var G=io(R);return re(G)?!1:W(b,G,T)}function K(b,R,T){var L=ln(R,T,!1);return M(L)?!1:Ce(L.OrdinaryHasOwnMetadata(b,R,T))}function te(b,R,T){var L=K(b,R,T);if(L)return ne(b,R,T);var G=io(R);if(!re(G))return te(b,G,T)}function ne(b,R,T){var L=ln(R,T,!1);if(!M(L))return L.OrdinaryGetOwnMetadata(b,R,T)}function $e(b,R,T,L){var G=ln(T,L,!0);G.OrdinaryDefineOwnMetadata(b,R,T,L)}function oe(b,R){var T=ke(b,R),L=io(b);if(L===null)return T;var G=oe(L,R);if(G.length<=0)return T;if(T.length<=0)return G;for(var ye=new m,be=[],Y=0,N=T;Y<N.length;Y++){var D=N[Y],H=ye.has(D);H||(ye.add(D),be.push(D))}for(var B=0,X=G;B<X.length;B++){var D=X[B],H=ye.has(D);H||(ye.add(D),be.push(D))}return be}function ke(b,R){var T=ln(b,R,!1);return T?T.OrdinaryOwnMetadataKeys(b,R):[]}function J(b){if(b===null)return 1;switch(typeof b){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return b===null?1:6;default:return 6}}function M(b){return b===void 0}function re(b){return b===null}function rt(b){return typeof b=="symbol"}function se(b){return typeof b=="object"?b!==null:typeof b=="function"}function ie(b,R){switch(J(b)){case 0:return b;case 1:return b;case 2:return b;case 3:return b;case 4:return b;case 5:return b}var T=R===3?"string":R===5?"number":"default",L=Cs(b,s);if(L!==void 0){var G=L.call(b,T);if(se(G))throw new TypeError;return G}return de(b,T==="default"?"number":T)}function de(b,R){if(R==="string"){var T=b.toString;if(st(T)){var L=T.call(b);if(!se(L))return L}var G=b.valueOf;if(st(G)){var L=G.call(b);if(!se(L))return L}}else{var G=b.valueOf;if(st(G)){var L=G.call(b);if(!se(L))return L}var ye=b.toString;if(st(ye)){var L=ye.call(b);if(!se(L))return L}}throw new TypeError}function Ce(b){return!!b}function ot(b){return""+b}function Le(b){var R=ie(b,3);return rt(R)?R:ot(R)}function un(b){return Array.isArray?Array.isArray(b):b instanceof Object?b instanceof Array:Object.prototype.toString.call(b)==="[object Array]"}function st(b){return typeof b=="function"}function Ps(b){return typeof b=="function"}function Ml(b){switch(J(b)){case 3:return!0;case 4:return!0;default:return!1}}function so(b,R){return b===R||b!==b&&R!==R}function Cs(b,R){var T=b[R];if(T!=null){if(!st(T))throw new TypeError;return T}}function Ls(b){var R=Cs(b,i);if(!st(R))throw new TypeError;var T=R.call(b);if(!se(T))throw new TypeError;return T}function Ms(b){return b.value}function $s(b){var R=b.next();return R.done?!1:R}function Ns(b){var R=b.return;R&&R.call(b)}function io(b){var R=Object.getPrototypeOf(b);if(typeof b!="function"||b===c||R!==c)return R;var T=b.prototype,L=T&&Object.getPrototypeOf(T);if(L==null||L===Object.prototype)return R;var G=L.constructor;return typeof G!="function"||G===b?R:G}function $l(){var b;!M(_)&&typeof n.Reflect<"u"&&!(_ in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(b=Dl(n.Reflect));var R,T,L,G=new h,ye={registerProvider:be,getProvider:N,setProvider:H};return ye;function be(B){if(!Object.isExtensible(ye))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case b===B:break;case M(R):R=B;break;case R===B:break;case M(T):T=B;break;case T===B:break;default:L===void 0&&(L=new m),L.add(B);break}}function Y(B,X){if(!M(R)){if(R.isProviderFor(B,X))return R;if(!M(T)){if(T.isProviderFor(B,X))return R;if(!M(L))for(var ue=Ls(L);;){var we=$s(ue);if(!we)return;var Ge=Ms(we);if(Ge.isProviderFor(B,X))return Ns(ue),Ge}}}if(!M(b)&&b.isProviderFor(B,X))return b}function N(B,X){var ue=G.get(B),we;return M(ue)||(we=ue.get(X)),M(we)&&(we=Y(B,X),M(we)||(M(ue)&&(ue=new p,G.set(B,ue)),ue.set(X,we))),we}function D(B){if(M(B))throw new TypeError;return R===B||T===B||!M(L)&&L.has(B)}function H(B,X,ue){if(!D(ue))throw new Error("Metadata provider not registered.");var we=N(B,X);if(we!==ue){if(!M(we))return!1;var Ge=G.get(B);M(Ge)&&(Ge=new p,G.set(B,Ge)),Ge.set(X,ue)}return!0}}function Nl(){var b;return!M(_)&&se(n.Reflect)&&Object.isExtensible(n.Reflect)&&(b=n.Reflect[_]),M(b)&&(b=$l()),!M(_)&&se(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,_,{enumerable:!1,configurable:!1,writable:!1,value:b}),b}function Ul(b){var R=new h,T={isProviderFor:function(D,H){var B=R.get(D);return M(B)?!1:B.has(H)},OrdinaryDefineOwnMetadata:be,OrdinaryHasOwnMetadata:G,OrdinaryGetOwnMetadata:ye,OrdinaryOwnMetadataKeys:Y,OrdinaryDeleteMetadata:N};return S.registerProvider(T),T;function L(D,H,B){var X=R.get(D),ue=!1;if(M(X)){if(!B)return;X=new p,R.set(D,X),ue=!0}var we=X.get(H);if(M(we)){if(!B)return;if(we=new p,X.set(H,we),!b.setProvider(D,H,T))throw X.delete(H),ue&&R.delete(D),new Error("Wrong provider for target.")}return we}function G(D,H,B){var X=L(H,B,!1);return M(X)?!1:Ce(X.has(D))}function ye(D,H,B){var X=L(H,B,!1);if(!M(X))return X.get(D)}function be(D,H,B,X){var ue=L(B,X,!0);ue.set(D,H)}function Y(D,H){var B=[],X=L(D,H,!1);if(M(X))return B;for(var ue=X.keys(),we=Ls(ue),Ge=0;;){var Us=$s(we);if(!Us)return B.length=Ge,B;var Bl=Ms(Us);try{B[Ge]=Bl}catch(ql){try{Ns(we)}finally{throw ql}}Ge++}}function N(D,H,B){var X=L(H,B,!1);if(M(X)||!X.delete(D))return!1;if(X.size===0){var ue=R.get(H);M(ue)||(ue.delete(B),ue.size===0&&R.delete(ue))}return!0}}function Dl(b){var R=b.defineMetadata,T=b.hasOwnMetadata,L=b.getOwnMetadata,G=b.getOwnMetadataKeys,ye=b.deleteMetadata,be=new h,Y={isProviderFor:function(N,D){var H=be.get(N);return!M(H)&&H.has(D)?!0:G(N,D).length?(M(H)&&(H=new m,be.set(N,H)),H.add(D),!0):!1},OrdinaryDefineOwnMetadata:R,OrdinaryHasOwnMetadata:T,OrdinaryGetOwnMetadata:L,OrdinaryOwnMetadataKeys:G,OrdinaryDeleteMetadata:ye};return Y}function ln(b,R,T){var L=S.getProvider(b,R);if(!M(L))return L;if(T){if(S.setProvider(b,R,w))return w;throw new Error("Illegal state.")}}function Fl(){var b={},R=[],T=(function(){function Y(N,D,H){this._index=0,this._keys=N,this._values=D,this._selector=H}return Y.prototype["@@iterator"]=function(){return this},Y.prototype[i]=function(){return this},Y.prototype.next=function(){var N=this._index;if(N>=0&&N<this._keys.length){var D=this._selector(this._keys[N],this._values[N]);return N+1>=this._keys.length?(this._index=-1,this._keys=R,this._values=R):this._index++,{value:D,done:!1}}return{value:void 0,done:!0}},Y.prototype.throw=function(N){throw this._index>=0&&(this._index=-1,this._keys=R,this._values=R),N},Y.prototype.return=function(N){return this._index>=0&&(this._index=-1,this._keys=R,this._values=R),{value:N,done:!0}},Y})(),L=(function(){function Y(){this._keys=[],this._values=[],this._cacheKey=b,this._cacheIndex=-2}return Object.defineProperty(Y.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Y.prototype.has=function(N){return this._find(N,!1)>=0},Y.prototype.get=function(N){var D=this._find(N,!1);return D>=0?this._values[D]:void 0},Y.prototype.set=function(N,D){var H=this._find(N,!0);return this._values[H]=D,this},Y.prototype.delete=function(N){var D=this._find(N,!1);if(D>=0){for(var H=this._keys.length,B=D+1;B<H;B++)this._keys[B-1]=this._keys[B],this._values[B-1]=this._values[B];return this._keys.length--,this._values.length--,so(N,this._cacheKey)&&(this._cacheKey=b,this._cacheIndex=-2),!0}return!1},Y.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=b,this._cacheIndex=-2},Y.prototype.keys=function(){return new T(this._keys,this._values,G)},Y.prototype.values=function(){return new T(this._keys,this._values,ye)},Y.prototype.entries=function(){return new T(this._keys,this._values,be)},Y.prototype["@@iterator"]=function(){return this.entries()},Y.prototype[i]=function(){return this.entries()},Y.prototype._find=function(N,D){if(!so(this._cacheKey,N)){this._cacheIndex=-1;for(var H=0;H<this._keys.length;H++)if(so(this._keys[H],N)){this._cacheIndex=H;break}}return this._cacheIndex<0&&D&&(this._cacheIndex=this._keys.length,this._keys.push(N),this._values.push(void 0)),this._cacheIndex},Y})();return L;function G(Y,N){return Y}function ye(Y,N){return N}function be(Y,N){return[Y,N]}}function Hl(){var b=(function(){function R(){this._map=new p}return Object.defineProperty(R.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),R.prototype.has=function(T){return this._map.has(T)},R.prototype.add=function(T){return this._map.set(T,T),this},R.prototype.delete=function(T){return this._map.delete(T)},R.prototype.clear=function(){this._map.clear()},R.prototype.keys=function(){return this._map.keys()},R.prototype.values=function(){return this._map.keys()},R.prototype.entries=function(){return this._map.entries()},R.prototype["@@iterator"]=function(){return this.keys()},R.prototype[i]=function(){return this.keys()},R})();return b}function jl(){var b=16,R=d.create(),T=L();return(function(){function N(){this._key=L()}return N.prototype.has=function(D){var H=G(D,!1);return H!==void 0?d.has(H,this._key):!1},N.prototype.get=function(D){var H=G(D,!1);return H!==void 0?d.get(H,this._key):void 0},N.prototype.set=function(D,H){var B=G(D,!0);return B[this._key]=H,this},N.prototype.delete=function(D){var H=G(D,!1);return H!==void 0?delete H[this._key]:!1},N.prototype.clear=function(){this._key=L()},N})();function L(){var N;do N="@@WeakMap@@"+Y();while(d.has(R,N));return R[N]=!0,N}function G(N,D){if(!r.call(N,T)){if(!D)return;Object.defineProperty(N,T,{value:d.create()})}return N[T]}function ye(N,D){for(var H=0;H<D;++H)N[H]=Math.random()*255|0;return N}function be(N){if(typeof Uint8Array=="function"){var D=new Uint8Array(N);return typeof crypto<"u"?crypto.getRandomValues(D):typeof msCrypto<"u"?msCrypto.getRandomValues(D):ye(D,N),D}return ye(new Array(N),N)}function Y(){var N=be(b);N[6]=N[6]&79|64,N[8]=N[8]&191|128;for(var D="",H=0;H<b;++H){var B=N[H];(H===4||H===6||H===8)&&(D+="-"),B<16&&(D+="0"),D+=B.toString(16).toLowerCase()}return D}}function ao(b){return b.__=void 0,delete b.__,b}})})(Fs||(Fs={}))});x();var Av=Re(Hs(),1),Qe=Re(require("process"),1);x();var Ed=Re(require("os"),1),xd=Re(require("path"),1),Ad=require("url"),Od=require("util");x();x();var ce=class extends Error{},Ql=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Zl(t){if(typeof t!="string")return!1;let e=Ql.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 ed(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",Zl(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 Nt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function js(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 ce(`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 uo(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 Bs(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 ed(await r.json())}x();function Ne(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}x();var De=class extends Error{name="ModelPriceError"},lo="per_million_input_tokens",co="per_million_output_tokens",Gs="model_id,variant,unit,price_usd,effective_at,expires_at",qs={per_request:!0,per_minute:!0,per_output_unit:!0},td=5e3;function nd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new De(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Ws(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new De(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function rd(t,e,n){return t===null?null:Ws(t,e,n)}function od(t,e){if(t===lo)return"input";if(t===co)return"output";if(typeof t=="string"&&Object.hasOwn(qs,t))return null;throw new De(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${lo} | ${co}) nor a known GPU-time unit (${Object.keys(qs).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 sd(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 po(t,e){return`${t}\0${e}`}function id(t){if(!Array.isArray(t))throw new De(`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 De(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of Gs.split(","))if(!Object.hasOwn(s,l))throw new De(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=od(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new De(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new De(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:nd(s.price_usd,o),effective_at:Ws(s.effective_at,o,"effective_at"),expires_at:rd(s.expires_at,o,"expires_at")})}return e}function Js(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,m,h)=>{let _=p&&p.length>0?p:d?.[m];if(!_||_.length===0)return null;let S=sd(_,m);return"reason"in S?S:S.rate.usd===0?m==="output"&&h!==null&&n?.has(po(u,h))?S.rate:{reason:`the ${m} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:S.rate};for(let[p,m]of o.get(u)){let h=l.get(p),_=c(h?.input,"input",m),S=c(h?.output,"output",m);if(_!==null&&"reason"in _){i.push({model_id:u,variant:m,reason:_.reason});continue}if(S!==null&&"reason"in S){i.push({model_id:u,variant:m,reason:S.reason});continue}_===null||S===null||s.push({model_id:u,variant:m,pricing:{input:_.usd,output:S.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 dn(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 cn={prices:[],refusals:[]};async function Vs(t){let e=t.fetchImpl??fetch,n=`${lo},${co}`,r=await e(`${t.catalogUrl}/model_prices?select=${Gs}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(td)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return id(await r.json())}x();var vt="/partners/openrouter/models",ad={chat:!0,code:!0,agent:!0,vl:!0},Ks={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function ud(t){let e=t.toLowerCase();return Object.hasOwn(Ks,e)?Ks[e]:null}var zs={"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 ld(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(zs,o)?zs[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 Ys={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Xs={2:"Llama2",3:"Llama3"};function dd(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(Ys,s))return Ys[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Xs,i))return Xs[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var cd=["context_length","max_model_len"];function pd(t){let e=cd.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 Fn(t){let e=t.map(pd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function fd(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function fo(t){if(t.length===0)return null;let e=t.map(fd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function mo(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 md(t,e){let n=e.filter(s=>Ne(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return pn(n);let r=e.filter(s=>Ne(s.model_id)===t);if(r.length>0)return pn(r);let o=mo(t,e);return o.length>0?pn(o):null}function pn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:gd(t),matches:t}:null}function gd(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 ct=class extends Error{name="ModelCreatedError"};function Ut(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 ct(`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 ct(`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 ct(`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 ct(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return u/1e3}function _t(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 Hn(t,e,n){let r=md(t,e);if(!r)return _t({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Fn(s),a=Ut(s),u=dn(o.model_id,o.variant,n),l=ei(o,s),d=fo(s);return _t({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 hd=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function ei(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:[...hd],defect:o}:{published:[],defect:o}}function go(t){let e=t.length>0?pn(t):null;return e===null?{published:[],defect:null}:ei(e.row,e.matches)}function Qs(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 Zs(t){return{input:[{type:"prompt",unit:"token",cost_usd:Qs(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Qs(t.output)}]}}function yd(t,e,n,r){if(e.length===0)return null;let o=pn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||ad[s.task]!==!0)return null;let a=Fn(i),u=dn(s.model_id,s.variant,n),l=dd(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:Ut(i),quantization:ud(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:Zs(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...u?{pricing:Zs(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function ti(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?Nt(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:ld(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=yd(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 ni={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},Dt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function ri(t){let e=t.t;if(typeof e!="string"||!(e in ni))throw new Dt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(ni).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 wd(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Dt(`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 Dt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return ri(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Dt(`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 ri(t)}function oi(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function _d(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 si(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 oi(e);let s=o.next();if(e!==void 0&&await _d(s,e)==="aborted")throw s.catch(()=>{}),oi(e);let i=await s;if(i.done)return;yield wd(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var ee=class extends Error{},Q=class extends Error{},yo="urs1.";function Bn(t,e){return yo+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Wn(t){if(!t.startsWith(yo))return null;try{let e=JSON.parse(Buffer.from(t.slice(yo.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 ui(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 ii(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Sd(t);return e===null?[]:[e]}function vd(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
4
  `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function _o(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||Ne(`${r.model_id}-${r.variant}`)===e.appSlug||Ne(r.model_id)===e.appSlug)),n?vd(n.engine_args?.pool):null}function ho(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 ai(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 li="shared:",mn="speech:";function ft(t){return t.sharedApp?li+t.appSlug:t.appSlug}function qn(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 wo(t,e){let n=e.filter(s=>Ne(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>Ne(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function bd(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Sd(t){let e=t.map(bd),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var kd={stt:"stt",tts:"tts"};function pt(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:kd[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function di(t,e){let n=wo(t,e);return n.length>0?n:mo(t,e)}function fn(t,e){return di(t.appSlug,e)}function Rd(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 jn=6e4,Gn=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??jn):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??jn):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??jn):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??jn;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 De)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
5
  `),cn}let r=Js(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
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(po(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(li)||o.startsWith(mn)||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 ee(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=uo(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=Ne(s),u=n.endpoints.filter(c=>Ne(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:uo(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=Ne(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 ee(`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 ee(`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===Ne(u.model_id)||o===Ne(`${u.model_id}-${u.variant}`));if(a)throw new ee(`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=qn(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return _o(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return ft(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,ft(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,mn+ft(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:qn(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:Bn(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Bn(n,this.keyOf(r))}}async sessionForHandle(e){let n=Wn(e);if(!n)throw new Q(`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 Q(`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 Q(`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:cn;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
7
  `);let u=(n?Nt(n):[]).map(l=>{let d=s.filter(w=>w.model_id===l.model_id&&w.variant===l.variant),c=Fn(d),p=Ut(d),m=fo(d),h=dn(l.model_id,l.variant,i),_=go(d);return _t({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...h!==null?{pricing:h}:{},..._.published.length>0?{voices:[..._.published]}:{},...m!==null?{capabilities:{reasoning:m}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(l=>Hn(l,s,i)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return ti(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=ho(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return ai(`${r.modelId}:${r.variant}`,s).includes(n)}return ii(wo(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?pt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:pt(fn(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?pt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":pt(fn(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?pt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":pt(fn(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):fn(n,r);return Rd(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):fn(n,r);return go(o)}async imageModelList(){let e=await this.catalogRows(),n=cn,r=[];for(let s of await this.availableIds()){let i=ii(wo(s,e));i.length!==0&&r.push(_t({...Hn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of Nt(o)){let i=ho(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=ai(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let u=_t({id:`${s.model_id}:${s.variant}`,object:"model",created:Ut(i),owned_by:"urun",image_modes:a});r.push(u)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=cn,r=[];for(let s of await this.availableIds())pt(di(s,e))==="stt"&&r.push(Hn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of Nt(o)){let i=ho(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(pt(i)!=="stt")continue;let a=_t({id:`${s.model_id}:${s.variant}`,object:"model",created:Ut(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 ci(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 Jn(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 Id=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function pi(t){let e=t?.code;return typeof e=="string"&&Id.has(e)}function Ze(t,e){try{return t.write(e),!0}catch(n){if(pi(n))return!1;throw n}}function fi(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{pi(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)}}}E();var ge=require("@prometheus-io/client"),Ui=require("http");E();var Td={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Pd(t){return Td[t]??null}var hi=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Cd(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Ld(t){return t==="surface"}function Md(t){let e=t?.ledgerFailureReason;return hi.includes(e)?e:"unknown"}var $d=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],mi=["priced","unpriced"],Nd={written:mi,already_written:mi,skipped:$d,failed:hi},yi=Object.entries(Nd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Ud(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Dd(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 Fd=256,gi=4096,gn=12e4,Hd=250,jd=8e3,it=[],vo=new Set,hn=0,Ft=!1;function wi(){return it.length}function _i(t=Date.now()){let e=it[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var Vn=new Set;function vi(){return hn===0&&it.length===0}function bi(){if(vi()){Ft=!1;for(let t of[...Vn])t()}}async function Si(t=Ri){return vi()?!0:await new Promise(e=>{let n=null,r=()=>{Vn.delete(r),n&&clearTimeout(n),e(!0)};Vn.add(r),n=setTimeout(()=>{Vn.delete(r),e(!1)},t),n.unref?.()})}function ki(){Ft=!0;let t=[...it.splice(0,it.length),...vo];for(let e of t)e.settled||St(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 ${Ri}ms drain \u2014 the request was served and answered, and its billing row was never written`});return bi(),t.length}var Ri=5e3;function Ei(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
9
- `}function Bd(t){Ze(process.stdout,t)}function xi(t,e){try{t(e)}catch{}}function Ai(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Bd,o=Pd(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),xi(r,Ei("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:Dd(e),completed_at:e.ts,billable_outcome:Ud(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(it.length>=gi){i("queue_full",`${it.length} ledger writes are already waiting (capacity ${gi}, ${hn} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}it.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),hn<Fd&&(hn+=1,qd())}async function qd(){try{for(;;){let t=Gd();if(t===void 0)return;vo.add(t);try{await Wd(t)}finally{vo.delete(t)}}}finally{hn-=1,bi()}}function Gd(){let t=Date.now();for(;;){let e=it.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<gn)return e;St(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${gn}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);St(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=Cd(o);if(s!==null){St(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=Md(o),a=Date.now()-t.queuedAt;if(Ft){St(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Ld(i)&&a<gn){if(await Vd(Jd(t.attempts)),Ft||Date.now()-t.queuedAt>=gn){let u=Date.now()-t.queuedAt;St(t,{outcome:"failed",reason:Ft?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Ft?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${gn}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}St(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Jd(t){return Math.min(jd,Hd*2**Math.max(0,t-1))}function Vd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function St(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;xi(t.report,Ei(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}E();E();var zn="/v1/usage/requests",Oi=1e4,Kd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,mt=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},me=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Kn=class extends me{constructor(e){super(e),this.name="UsageWithholdingError"}},Ci=1024*1024;function ko(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new mt(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new mt(`"${e}" must be an array of uuid strings`);if(n.length>Oi)throw new mt(`"${e}" carries ${n.length} ids; at most ${Oi} 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"||!Kd.test(s))throw new mt(`"${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 Li(t){return ko(t,"inference_ids")}var zd=["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 Ht(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new me(`${n}: ${e} is not a non-empty string (got ${Bt(r)})`);return r}function bo(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new me(`${n}: ${e} is neither null nor a non-empty string (got ${Bt(r)})`);return r}function jt(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 me(`${n}: ${e} is not a number (got ${Bt(o)})`);if(r&&!Number.isSafeInteger(s))throw new me(`${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 me(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Yd=40,Ii=64,Ti=600;function Mi(t){let e=Object.keys(t).sort(),r=e.slice(0,Yd).map(o=>o.length>Ii?`${o.slice(0,Ii)}\u2026`:o).join(", ");return r.length>Ti&&(r=`${r.slice(0,Ti)}\u2026`),`${e.length} keys present: [${r}]`}function Bt(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})}
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 ge=require("@prometheus-io/client"),Ui=require("http");x();var Td={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Pd(t){return Td[t]??null}var hi=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Cd(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Ld(t){return t==="surface"}function Md(t){let e=t?.ledgerFailureReason;return hi.includes(e)?e:"unknown"}var $d=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],mi=["priced","unpriced"],Nd={written:mi,already_written:mi,skipped:$d,failed:hi},yi=Object.entries(Nd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Ud(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Dd(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 Fd=256,gi=4096,gn=12e4,Hd=250,jd=8e3,it=[],vo=new Set,hn=0,Ft=!1;function wi(){return it.length}function _i(t=Date.now()){let e=it[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var Vn=new Set;function vi(){return hn===0&&it.length===0}function bi(){if(vi()){Ft=!1;for(let t of[...Vn])t()}}async function Si(t=Ri){return vi()?!0:await new Promise(e=>{let n=null,r=()=>{Vn.delete(r),n&&clearTimeout(n),e(!0)};Vn.add(r),n=setTimeout(()=>{Vn.delete(r),e(!1)},t),n.unref?.()})}function ki(){Ft=!0;let t=[...it.splice(0,it.length),...vo];for(let e of t)e.settled||St(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 ${Ri}ms drain \u2014 the request was served and answered, and its billing row was never written`});return bi(),t.length}var Ri=5e3;function Ei(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
9
+ `}function Bd(t){Ze(process.stdout,t)}function xi(t,e){try{t(e)}catch{}}function Ai(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Bd,o=Pd(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),xi(r,Ei("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:Dd(e),completed_at:e.ts,billable_outcome:Ud(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(it.length>=gi){i("queue_full",`${it.length} ledger writes are already waiting (capacity ${gi}, ${hn} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}it.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),hn<Fd&&(hn+=1,qd())}async function qd(){try{for(;;){let t=Gd();if(t===void 0)return;vo.add(t);try{await Wd(t)}finally{vo.delete(t)}}}finally{hn-=1,bi()}}function Gd(){let t=Date.now();for(;;){let e=it.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<gn)return e;St(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${gn}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);St(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=Cd(o);if(s!==null){St(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=Md(o),a=Date.now()-t.queuedAt;if(Ft){St(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Ld(i)&&a<gn){if(await Vd(Jd(t.attempts)),Ft||Date.now()-t.queuedAt>=gn){let u=Date.now()-t.queuedAt;St(t,{outcome:"failed",reason:Ft?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Ft?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${gn}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}St(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Jd(t){return Math.min(jd,Hd*2**Math.max(0,t-1))}function Vd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function St(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;xi(t.report,Ei(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}x();x();var zn="/v1/usage/requests",Oi=1e4,Kd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,mt=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},me=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Kn=class extends me{constructor(e){super(e),this.name="UsageWithholdingError"}},Ci=1024*1024;function ko(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new mt(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new mt(`"${e}" must be an array of uuid strings`);if(n.length>Oi)throw new mt(`"${e}" carries ${n.length} ids; at most ${Oi} 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"||!Kd.test(s))throw new mt(`"${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 Li(t){return ko(t,"inference_ids")}var zd=["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 Ht(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new me(`${n}: ${e} is not a non-empty string (got ${Bt(r)})`);return r}function bo(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new me(`${n}: ${e} is neither null nor a non-empty string (got ${Bt(r)})`);return r}function jt(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 me(`${n}: ${e} is not a number (got ${Bt(o)})`);if(r&&!Number.isSafeInteger(s))throw new me(`${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 me(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Yd=40,Ii=64,Ti=600;function Mi(t){let e=Object.keys(t).sort(),r=e.slice(0,Yd).map(o=>o.length>Ii?`${o.slice(0,Ii)}\u2026`:o).join(", ");return r.length>Ti&&(r=`${r.slice(0,Ti)}\u2026`),`${e.length} keys present: [${r}]`}function Bt(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
10
  `)}function Xd(t,e){let n;try{n=t(e)}catch{Pi(t,e);return}Qd(n)&&Promise.resolve(n).catch(()=>{Pi(t,e)})}function Qd(t){return typeof t?.then=="function"}function Pi(t,e){if(t!==So)try{So(e)}catch{}}function $i(t,e=So){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?Mi(t):Bt(t);throw new me(`the usage surface answered without a "requests" array: got ${Bt(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Zd(n[o],s))}catch(i){if(i instanceof Kn||!(i instanceof me))throw i;Xd(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new me(`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 Zd(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new me(`${e} is not an object: got ${Bt(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new Kn(`${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 zd)if(!Object.hasOwn(n,o))throw new me(`${e} has no "${o}" column (${Mi(n)})`);let r=jt(n,"http_status",e,!0);if(r===null)throw new me(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Ht(n,"inference_id",e),model_id:Ht(n,"model_id",e),identity_kind:Ht(n,"identity_kind",e),variant:bo(n,"variant",e),task:Ht(n,"task",e),http_status:r,started_at:Ht(n,"started_at",e),completed_at:Ht(n,"completed_at",e),prompt_tokens:jt(n,"prompt_tokens",e,!0),completion_tokens:jt(n,"completion_tokens",e,!0),output_units:jt(n,"output_units",e,!1),output_minutes:jt(n,"output_minutes",e,!1),cost_nano_usd:jt(n,"cost_nano_usd",e,!0),price_version:bo(n,"price_version",e),priced_at:bo(n,"priced_at",e)}}function Yn(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 me(`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 me(`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 yn="/partners/huggingface/v1/billing/requests";function ec(t){return ko(t,"requestIds")}function tc(t){return t>=200&&t<=399}function nc(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&tc(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Ni(t,e){let n=ec(t),r=await e(n);return Yn(r,n),nc(r)}var Ro=9464,Xn="/metrics",Qn="(other)",rc="(none)",oc=64,sc=128,ic=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/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",zn,yn,vt],ac=new Set(ic);function uc(t){return ac.has(t)?t:Qn}function lc(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var Zn=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?rc:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,Qn):(this.admitted.add(e),e):Qn}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},er=class{registry=new ge.Registry;modelLabel=new Zn(oc);orgLabel=new Zn(sc);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new ge.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 ge.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 ge.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 ge.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 ge.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 ge.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 ge.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 yi)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ge.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"},wi()),this.ledgerQueue.set({measure:"oldest_age_seconds"},_i()/1e3)}}),this.labelCardinality=new ge.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 ge.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 ge.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 ge.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 ge.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 ge.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 ge.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,ge.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=uc(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===""?Qn:e.method,status_class:lc(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 Di(t){return(0,Ui.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Xn){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Xn}
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()})})}E();var Eo=require("crypto"),Hi=require("http"),xo=9465,dc="x-urun-key-id",cc="x-urun-key-fingerprint",pc="urun-ratelimit-bucket:",fc="urun-ratelimit-tier:",Fi="anonymous",mc=/^urun_sk_[A-Za-z0-9_-]{43}$/;function gc(t){return(0,Eo.createHash)("sha256").update(`${pc}${t}`).digest("hex")}function hc(t){return(0,Eo.createHash)("sha256").update(`${fc}${t}`).digest("hex")}function yc(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return mc.test(n)?n:null}function ji(){return(0,Hi.createServer)((t,e)=>{let n=yc(t.headers.authorization);e.setHeader(dc,n===null?Fi:gc(n)),e.setHeader(cc,n===null?Fi:hc(n)),e.writeHead(200),e.end()})}E();var wc=8080,Ao="serve",kt="0.0.0.0";function _c(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Bi(t=process.env){let e=(t.PORT??"").trim(),n=e===""?wc: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=ci(Jn(_c(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?Jn(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:Jn(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()},m=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],h=m.filter((R,O)=>Object.values(p)[O]==="");if(h.length!==0&&h.length!==m.length)throw new Error(`${m.join(", ")} must be set together (or all left unset) \u2014 missing: ${h.join(", ")}, which would half-configure the lane plane`);let _=h.length===0?p:void 0,x={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},w=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],f=w.filter((R,O)=>Object.values(x)[O]==="");if(f.length!==0&&f.length!==w.length)throw new Error(`${w.join(", ")} must be set together (or all left unset) \u2014 missing: ${f.join(", ")}, which would half-configure the pooler cutover`);let g=f.length===0?x: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()},b=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],C=b.filter((R,O)=>Object.values(y)[O]==="");if(C.length!==0&&C.length!==b.length)throw new Error(`${b.join(", ")} must be set together (or all left unset) \u2014 missing: ${C.join(", ")}, which would half-configure the machine-identity rung`);let P=y.issuers.split(",").map(R=>R.trim()).filter(R=>R!=="");if(P.length===0&&C.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 S=Number(y.tokenTtlS);if(C.length===0&&(!Number.isFinite(S)||S<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(y.tokenTtlS)}`);let A=C.length===0?{jwksBaseUrl:y.jwksBaseUrl,issuers:P,tokenTtlS:S}:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:u,ledgerSigning:c,lane:_,pooler:g,machine:A}}E();var Il=require("http");E();E();var Wi="audio",Oo=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 Ji(t,e,n=1e4){let r=new Oo(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Wi).attach(o);let s=await vc(t,n);return await r.startInbound(s),r}function vc(t,e){let n=t.stream(Wi);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 qi="rt-video-in",Gi=256e3;function Vi(t){let e=t.stream(qi),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${qi}') 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>Gi)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Gi}-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 bc=24e3,wn=480,Sc=111;async function kc(){let t=await import("opusscript"),e=t.default??t;return new e(bc,1,2048)}async function Ki(){let t=await import("werift"),e=await kc();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>=wn;){let d=u.subarray(l,l+wn);l+=wn;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,wn);o=o+1&65535,s=s+wn>>>0;let m=new t.RtpHeader({version:2,payloadType:Sc,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),h=new t.RtpPacket(m,p);n.writeRtp(h)}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}}}E();var tr=require("@urun-sh/core"),Io="rt-video-out";var Rc="h264";function Ec(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 xc(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;Ec(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 zi="urun.videoOut.v2-ws";function Yi(t){let e=t.stream(Io);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Io}') 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: "${Io}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=xc(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:Rc,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 sr="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Ac=1007,Qi=1008,at=1011,ir=1008,$=class extends Error{constructor(n,r=Ac){super(n);this.closeCode=r}closeCode},_e=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,nr=["setup","clientContent","realtimeInput","toolResponse"];function Zi(t){let e;try{e=JSON.parse(t)}catch{throw new $("client message is not valid JSON")}let n=_e(e);if(!n)throw new $("client message must be a JSON object");let r=nr.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!nr.includes(a));if(o.length>0)throw new $(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${nr.join(", ")}`);if(r.length!==1)throw new $(`client message must contain exactly one of ${nr.join(", ")} (got ${r.length})`);let s=r[0],i=_e(n[s]);if(!i)throw new $(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function ea(t,e){if(typeof t=="string")return t;let n=_e(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=_e(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 Oc={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Rt="urun.videoOut";function ta(t){return{framing:zi,codec:t}}function na(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Rt]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Ic={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Tc=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Rt],Xi=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Pc(t){let e=_e(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=_e(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(!Xi.includes(e.activityHandling))throw new $(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Xi.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Cc=["temperature","maxOutputTokens","responseModalities"];function ra(t){for(let[c,p]of Object.entries(Ic))if(t[c]!==void 0)throw new $(p);for(let c of Object.keys(t))if(!Tc.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=_e(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(!Cc.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 m=String(p).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="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:ea(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=_e(c);if(!p)throw new $("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new $(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new $("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let h=_e(m);if(!h||typeof h.name!="string")throw new $("functionDeclarations entries require a string name");a.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=_e(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?Oc:Pc(t.realtimeInputConfig),d=!1;if(t[Rt]!==void 0){if(!_e(t[Rt]))throw new $(`setup["${Rt}"] 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 oa(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function sa(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function ia(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=_e(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:ea(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var rr=16e3,aa=24e3,Lc=`audio/pcm;rate=${aa}`,ua=Buffer.alloc(960).toString("base64");function Mc(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 $c(t){let e=_e(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=_e(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])!==rr)throw new $(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${rr} Hz (audio/pcm;rate=${rr})`);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=Mc(o,rr,aa);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function la(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=_e(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:$c(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 da(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=_e(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 ca(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function pa(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Lc,data:t}}]}}}}function fa(t){let e=_e(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=_e(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=_e(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=_e(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)}`,at);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}`,at)}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=_e(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}}E();var ma=require("crypto"),ga=require("ws");var Uc=256,To=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Uc;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Dc="local",_n=t=>t.slice(0,120),Po=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 ee){this.ws.close(Qi,_n(e.message));return}if(e instanceof Q){this.ws.close(ir,_n(e.message));return}if(e instanceof $){this.ws.close(e.closeCode,_n(e.message));return}this.ws.close(at,_n(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Zi(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}=ia(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=la(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:ua);return}this.transcript.push(...da(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=ra(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",ir);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`,ir);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(na(l))),u=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[Rt]=ta(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)",at);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(pa(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)",at);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,ma.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(oa(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(sa(e.timeLeftMs)),this.ws.close(at,_n(`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)}`,at);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=ca(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new $("upstream produced no response.completed event",at);let{messages:i,assistantItems:a}=fa(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Et=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Fc(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 Et(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 Et(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 Et(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Co(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 ga.WebSocketServer({noServer:!0}),o=new To;t.on("upgrade",(i,a,u)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===sr&&(a.on("error",()=>{}),(async()=>{let d=Fc(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Et(401,"invalid local proxy api key");c={clients:e.clients,scope:Dc}}r.handleUpgrade(i,a,u,p=>{new Po(p,c,o)})})().catch(d=>{let c=502;(d instanceof Et||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
12
+ `);return}n.end()})})}x();var Eo=require("crypto"),Hi=require("http"),xo=9465,dc="x-urun-key-id",cc="x-urun-key-fingerprint",pc="urun-ratelimit-bucket:",fc="urun-ratelimit-tier:",Fi="anonymous",mc=/^urun_sk_[A-Za-z0-9_-]{43}$/;function gc(t){return(0,Eo.createHash)("sha256").update(`${pc}${t}`).digest("hex")}function hc(t){return(0,Eo.createHash)("sha256").update(`${fc}${t}`).digest("hex")}function yc(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return mc.test(n)?n:null}function ji(){return(0,Hi.createServer)((t,e)=>{let n=yc(t.headers.authorization);e.setHeader(dc,n===null?Fi:gc(n)),e.setHeader(cc,n===null?Fi:hc(n)),e.writeHead(200),e.end()})}x();var wc=8080,Ao="serve",kt="0.0.0.0";function _c(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Bi(t=process.env){let e=(t.PORT??"").trim(),n=e===""?wc: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=ci(Jn(_c(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?Jn(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:Jn(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()},m=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],h=m.filter((E,O)=>Object.values(p)[O]==="");if(h.length!==0&&h.length!==m.length)throw new Error(`${m.join(", ")} must be set together (or all left unset) \u2014 missing: ${h.join(", ")}, which would half-configure the lane plane`);let _=h.length===0?p:void 0,S={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},w=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],f=w.filter((E,O)=>Object.values(S)[O]==="");if(f.length!==0&&f.length!==w.length)throw new Error(`${w.join(", ")} must be set together (or all left unset) \u2014 missing: ${f.join(", ")}, which would half-configure the pooler cutover`);let g=f.length===0?S: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()},v=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],C=v.filter((E,O)=>Object.values(y)[O]==="");if(C.length!==0&&C.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${C.join(", ")}, which would half-configure the machine-identity rung`);let P=y.issuers.split(",").map(E=>E.trim()).filter(E=>E!=="");if(P.length===0&&C.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 k=Number(y.tokenTtlS);if(C.length===0&&(!Number.isFinite(k)||k<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(y.tokenTtlS)}`);let A=C.length===0?{jwksBaseUrl:y.jwksBaseUrl,issuers:P,tokenTtlS:k}:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:u,ledgerSigning:c,lane:_,pooler:g,machine:A}}x();var Il=require("http");x();x();var Wi="audio",Oo=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 Ji(t,e,n=1e4){let r=new Oo(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Wi).attach(o);let s=await vc(t,n);return await r.startInbound(s),r}function vc(t,e){let n=t.stream(Wi);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 qi="rt-video-in",Gi=256e3;function Vi(t){let e=t.stream(qi),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${qi}') 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>Gi)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Gi}-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 bc=24e3,wn=480,Sc=111;async function kc(){let t=await import("opusscript"),e=t.default??t;return new e(bc,1,2048)}async function Ki(){let t=await import("werift"),e=await kc();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>=wn;){let d=u.subarray(l,l+wn);l+=wn;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,wn);o=o+1&65535,s=s+wn>>>0;let m=new t.RtpHeader({version:2,payloadType:Sc,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),h=new t.RtpPacket(m,p);n.writeRtp(h)}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 tr=require("@urun-sh/core"),Io="rt-video-out";var Rc="h264";function Ec(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 xc(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;Ec(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 zi="urun.videoOut.v2-ws";function Yi(t){let e=t.stream(Io);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Io}') 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: "${Io}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=xc(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:Rc,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 sr="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Ac=1007,Qi=1008,at=1011,ir=1008,$=class extends Error{constructor(n,r=Ac){super(n);this.closeCode=r}closeCode},_e=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,nr=["setup","clientContent","realtimeInput","toolResponse"];function Zi(t){let e;try{e=JSON.parse(t)}catch{throw new $("client message is not valid JSON")}let n=_e(e);if(!n)throw new $("client message must be a JSON object");let r=nr.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!nr.includes(a));if(o.length>0)throw new $(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${nr.join(", ")}`);if(r.length!==1)throw new $(`client message must contain exactly one of ${nr.join(", ")} (got ${r.length})`);let s=r[0],i=_e(n[s]);if(!i)throw new $(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function ea(t,e){if(typeof t=="string")return t;let n=_e(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=_e(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 Oc={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Rt="urun.videoOut";function ta(t){return{framing:zi,codec:t}}function na(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Rt]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Ic={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Tc=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Rt],Xi=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Pc(t){let e=_e(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=_e(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(!Xi.includes(e.activityHandling))throw new $(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Xi.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Cc=["temperature","maxOutputTokens","responseModalities"];function ra(t){for(let[c,p]of Object.entries(Ic))if(t[c]!==void 0)throw new $(p);for(let c of Object.keys(t))if(!Tc.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=_e(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(!Cc.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 m=String(p).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="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:ea(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=_e(c);if(!p)throw new $("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new $(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new $("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let h=_e(m);if(!h||typeof h.name!="string")throw new $("functionDeclarations entries require a string name");a.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=_e(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?Oc:Pc(t.realtimeInputConfig),d=!1;if(t[Rt]!==void 0){if(!_e(t[Rt]))throw new $(`setup["${Rt}"] 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 oa(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function sa(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function ia(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=_e(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:ea(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var rr=16e3,aa=24e3,Lc=`audio/pcm;rate=${aa}`,ua=Buffer.alloc(960).toString("base64");function Mc(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 $c(t){let e=_e(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=_e(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])!==rr)throw new $(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${rr} Hz (audio/pcm;rate=${rr})`);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=Mc(o,rr,aa);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function la(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=_e(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:$c(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 da(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=_e(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 ca(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function pa(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Lc,data:t}}]}}}}function fa(t){let e=_e(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=_e(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=_e(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=_e(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)}`,at);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}`,at)}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=_e(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 ma=require("crypto"),ga=require("ws");var Uc=256,To=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Uc;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Dc="local",_n=t=>t.slice(0,120),Po=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 ee){this.ws.close(Qi,_n(e.message));return}if(e instanceof Q){this.ws.close(ir,_n(e.message));return}if(e instanceof $){this.ws.close(e.closeCode,_n(e.message));return}this.ws.close(at,_n(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Zi(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}=ia(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=la(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:ua);return}this.transcript.push(...da(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=ra(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",ir);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`,ir);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(na(l))),u=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},o[Rt]=ta(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)",at);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(pa(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)",at);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,ma.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(oa(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(sa(e.timeLeftMs)),this.ws.close(at,_n(`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)}`,at);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=ca(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new $("upstream produced no response.completed event",at);let{messages:i,assistantItems:a}=fa(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Et=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Fc(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 Et(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 Et(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 Et(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Co(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 ga.WebSocketServer({noServer:!0}),o=new To;t.on("upgrade",(i,a,u)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===sr&&(a.on("error",()=>{}),(async()=>{let d=Fc(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Et(401,"invalid local proxy api key");c={clients:e.clients,scope:Dc}}r.handleUpgrade(i,a,u,p=>{new Po(p,c,o)})})().catch(d=>{let c=502;(d instanceof Et||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
14
14
  Connection: close\r
15
15
  \r
16
16
  ${m}\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)}E();var yt=require("ws");E();E();var ha=require("crypto"),ya="Inference-Id";function vn(){return(0,ha.randomUUID)()}function Lo(t){return t==="/v1"||t.startsWith("/v1/")}function wa(t,e){if(!Lo(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 bn(t){return`resp_${t}`}function _a(t){return`chatcmpl-${t}`}function va(t){return`msg_${t}`}function Fe(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function ba(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 Sa(t){return`${JSON.stringify(t)}
18
- `}var Hc=256,jc=128;function Te(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,jc)}var xt=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>=Hc?"(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}}}},Bc=256;function qc(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 At=class extends Error{},qt=class{conversations=new Map;thread(e,n){let r=qc(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new At(`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<=Bc)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},ka=new WeakMap;function Sn(t){let e=ka.get(t);return e||(e=new qt,ka.set(t,e)),e}function Gt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function et(t){return t.find(e=>e.type==="response.completed")?.response??null}function Wt(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 gt=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}))}},Gc=["<tool_call>","<function="];function Wc(t){return Gc.find(e=>t.includes(e))}function Ot(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 It(t,e,n){if(!(!t||e>0))return Wc(n)}function Jt(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 ut(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Jc(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 Mo(t,e){let n=Jc(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var He=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Vt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof At?new He(n.message,"previous_response_not_found",400,"previous_response_id"):new He(String(n instanceof Error?n.message:n),"invalid_input")}}function Ra(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 He("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}:{},...Ra(e)!==void 0?{response_format:Ra(e)}:{}},o)}async function kn(t){let{body:e,clients:n,store:r,stats:o}=t,s=Vt(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=Te(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?Fe(c):void 0);return{responseId:i,events:Yc({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?zc(o[i++],u):u),...Kc(r,n)]}function Kc(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 zc(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*Yc(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:l}=t,d=[],c=J=>J.response&&typeof J.response=="object"?{...J,response:{...J.response,id:r}}:J,p=`item_${r.slice(5)}`,m=!1,h=!1,_=0;function*x(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let w=[],f=(J,M)=>{w.push({output_index:J,item:M})},g=!1,y=0,b="",C=0,P="";function*S(){if(!g)return;g=!1,yield{type:"response.reasoning_text.done",item_id:b,output_index:y,content_index:0,text:P};let J={id:b,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:P}],status:"completed"};yield{type:"response.output_item.done",output_index:y,item:J},f(y,J),P=""}let A=!1,R=0,O="",I=0,U="",W="";function*K(J){if(!A)return;A=!1,yield{type:"response.output_text.done",item_id:O,output_index:R,content_index:0,text:U},yield{type:"response.content_part.done",item_id:O,output_index:R,content_index:0,part:{type:"output_text",text:U}};let M={id:O,type:"message",role:"assistant",status:J,content:[{type:"output_text",text:U}]};yield{type:"response.output_item.done",output_index:R,item:M},f(R,M),U=""}let te=new gt,ne=null,$e=-1;function*oe(J){if(!ne)return;let M=ne;ne=null,yield{type:"response.function_call_arguments.done",item_id:M.fcId,output_index:M.outputIndex,arguments:M.args};let re={id:M.fcId,type:"function_call",call_id:M.callId??M.fcId,name:M.name??"",arguments:M.args,status:J};yield{type:"response.output_item.done",output_index:M.outputIndex,item:re},f(M.outputIndex,re)}let ke=!1;for await(let J of l.track(e,o,t.turn)){d.push(J);let M=String(J.type??"");if(M==="response.created"||M==="response.in_progress"){m=!0,yield c(J);continue}if(M==="response.output_item.added"){h=!0,yield c(J);continue}if(M==="response.reasoning_text.delta"&&!h){yield*x(),g||(g=!0,y=_++,C+=1,b=C===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${C}`,yield{type:"response.output_item.added",output_index:y,item:{id:b,type:"reasoning",summary:[],content:[],status:"in_progress"}}),P+=String(J.delta??""),yield{type:"response.reasoning_text.delta",item_id:b,output_index:y,content_index:0,delta:J.delta};continue}if(M==="response.output_text.delta"&&!h){yield*x(),yield*S(),A||(A=!0,R=_++,I+=1,O=I===1?p:`${p}_${I}`,yield{type:"response.output_item.added",output_index:R,item:{id:O,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:O,output_index:R,content_index:0,part:{type:"output_text",text:""}}),U+=String(J.delta??""),W+=String(J.delta??""),yield{type:M,item_id:O,output_index:R,content_index:0,delta:J.delta};continue}let re=h?null:Wt(J);if(re){if(yield*x(),yield*S(),yield*K("completed"),te.add(re),re.tool_index!==$e){yield*oe("completed"),$e=re.tool_index;let rt=_++;ne={fcId:`fc_${r.slice(5)}_${re.tool_index}`,outputIndex:rt,callId:re.call_id,name:re.name,args:""},yield{type:"response.output_item.added",output_index:rt,item:{id:ne.fcId,type:"function_call",call_id:ne.callId??ne.fcId,name:ne.name??"",arguments:"",status:"in_progress"}}}ne&&(re.call_id&&(ne.callId=re.call_id),re.name&&(ne.name=re.name),ne.args+=re.delta,yield{type:"response.function_call_arguments.delta",item_id:ne.fcId,output_index:ne.outputIndex,delta:re.delta});continue}if(M==="response.completed"&&!h){let rt=Gt(J.response),se=It(s,te.size+rt.length,W);if(se){ke=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Ot(o,se)}};break}if(yield*S(),yield*K("completed"),yield*oe("completed"),te.size===0)for(let de of rt){let Ce=_++,ot=de.id??de.call_id??`fc_${Ce}`,Le=de.arguments??"",un={id:ot,type:"function_call",call_id:de.call_id??ot,name:de.name??""};yield{type:"response.output_item.added",output_index:Ce,item:{...un,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:ot,output_index:Ce,delta:Le},yield{type:"response.function_call_arguments.done",item_id:ot,output_index:Ce,arguments:Le};let st={...un,arguments:Le,status:"completed"};yield{type:"response.output_item.done",output_index:Ce,item:st},f(Ce,st)}let ie=Vc(w,J.response);yield ie.length>0?c({...J,response:{...J.response,output:ie}}):c(J);continue}yield c(J)}if(yield*S(),yield*K("incomplete"),yield*oe("incomplete"),i&&!ke){let J=et(d);u.remember(r,n,Mo(J,Jt(d,J)),a)}}E();E();var je=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}};E();var ht=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)}},Rn=class extends ht{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},No=class extends ht{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")}},We=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},ar=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 Rn;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 Rn;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 No(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 Rn}}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)`)}};E();var Uo=require("@urun-sh/core"),Je=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)}},Do=33e4;function Ea(t,e=Do){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new ur),e),a;try{a=await Promise.race([r.next(),s])}catch(l){throw l instanceof Q||l instanceof Uo.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof ur?(await r.return?.(void 0),new Je("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 Je("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 Je("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var ur=class extends Error{constructor(){super("stream idle timeout")}};function xa(t){return t instanceof Je?!1:t instanceof Q?!0:t instanceof Uo.SessionFailedError?t.kind==="transport-failed":!1}var Xc=[/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 Ke(t){return!Xc.some(e=>e.test(t))}function ze(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function Ue(t,e){if(t instanceof Q)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=Aa(t);return n||{message:ze(e?.inferenceId??null),redacted:!0}}function Aa(t){return t instanceof ct?{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 ee?{message:t.message,redacted:!1}:t instanceof je?{message:t.message,redacted:!1}:t instanceof ht?{message:t.message,redacted:!1}:t instanceof Je?Ke(t.message)?{message:t.message,redacted:!1}:null:t instanceof We?{message:t.message,redacted:!1}:t instanceof Se?{message:t.message,redacted:!1}:null}function Kt(t,e,n){let r=n??(i=>console.error(i)),o=Aa(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ve(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Ke(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ve(e)}`),`the ${t} upstream failed while serving this request`)}function tt(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Ke(e)?e:null}function Ve(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var jo="/v1/responses",Qc=64*1024*1024,Zc=8*1024*1024,ep=16,Oa=32,Ia=3600*1e3,tp=/^[A-Za-z0-9._-]{1,256}$/;function Pe(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var np=Pe(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 Bo(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function rp(t){for(;t.bufferedAmount>Zc&&t.readyState===yt.WebSocket.OPEN;){let{promise:e,resolve:n}=Bo();setTimeout(n,5),await e}}var Fo=class extends qt{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 At))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)}},Ho=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 Fo(Sn(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(Pe(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Ia/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Ia).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(Pe(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(Pe(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(Pe(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(Pe(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(Pe(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(Pe(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"||!tp.test(o.stream_id)){this.sendFrame(np);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Oa){this.sendFrame(Pe(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Oa}). 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=vn();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await kn({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:bn(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!==yt.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await rp(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=vn(),o=bn(r);try{let s=Vt(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:Ve(e);if(e instanceof He)return Pe(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof ee)return Pe(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof Q){let a=Ue(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),Pe(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}`),Pe(s.status,{type:s.openaiType,message:o},n);let i=Ue(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),Pe(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=tt(o),a=i??ze(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)}`),Pe(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=ep;){let{promise:e,resolve:n}=Bo();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!==yt.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!==yt.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function lr(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 yt=require("ws");x();x();var ha=require("crypto"),ya="Inference-Id";function vn(){return(0,ha.randomUUID)()}function Lo(t){return t==="/v1"||t.startsWith("/v1/")}function wa(t,e){if(!Lo(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 bn(t){return`resp_${t}`}function _a(t){return`chatcmpl-${t}`}function va(t){return`msg_${t}`}function Fe(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function ba(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 Sa(t){return`${JSON.stringify(t)}
18
+ `}var Hc=256,jc=128;function Te(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,jc)}var xt=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>=Hc?"(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}}}},Bc=256;function qc(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 At=class extends Error{},qt=class{conversations=new Map;thread(e,n){let r=qc(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new At(`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<=Bc)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},ka=new WeakMap;function Sn(t){let e=ka.get(t);return e||(e=new qt,ka.set(t,e)),e}function Gt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function et(t){return t.find(e=>e.type==="response.completed")?.response??null}function Wt(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 gt=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}))}},Gc=["<tool_call>","<function="];function Wc(t){return Gc.find(e=>t.includes(e))}function Ot(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 It(t,e,n){if(!(!t||e>0))return Wc(n)}function Jt(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 ut(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Jc(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 Mo(t,e){let n=Jc(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var He=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Vt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof At?new He(n.message,"previous_response_not_found",400,"previous_response_id"):new He(String(n instanceof Error?n.message:n),"invalid_input")}}function Ra(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 He("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}:{},...Ra(e)!==void 0?{response_format:Ra(e)}:{}},o)}async function kn(t){let{body:e,clients:n,store:r,stats:o}=t,s=Vt(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=Te(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?Fe(c):void 0);return{responseId:i,events:Yc({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?zc(o[i++],u):u),...Kc(r,n)]}function Kc(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 zc(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*Yc(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:l}=t,d=[],c=J=>J.response&&typeof J.response=="object"?{...J,response:{...J.response,id:r}}:J,p=`item_${r.slice(5)}`,m=!1,h=!1,_=0;function*S(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let w=[],f=(J,M)=>{w.push({output_index:J,item:M})},g=!1,y=0,v="",C=0,P="";function*k(){if(!g)return;g=!1,yield{type:"response.reasoning_text.done",item_id:v,output_index:y,content_index:0,text:P};let J={id:v,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:P}],status:"completed"};yield{type:"response.output_item.done",output_index:y,item:J},f(y,J),P=""}let A=!1,E=0,O="",I=0,U="",W="";function*K(J){if(!A)return;A=!1,yield{type:"response.output_text.done",item_id:O,output_index:E,content_index:0,text:U},yield{type:"response.content_part.done",item_id:O,output_index:E,content_index:0,part:{type:"output_text",text:U}};let M={id:O,type:"message",role:"assistant",status:J,content:[{type:"output_text",text:U}]};yield{type:"response.output_item.done",output_index:E,item:M},f(E,M),U=""}let te=new gt,ne=null,$e=-1;function*oe(J){if(!ne)return;let M=ne;ne=null,yield{type:"response.function_call_arguments.done",item_id:M.fcId,output_index:M.outputIndex,arguments:M.args};let re={id:M.fcId,type:"function_call",call_id:M.callId??M.fcId,name:M.name??"",arguments:M.args,status:J};yield{type:"response.output_item.done",output_index:M.outputIndex,item:re},f(M.outputIndex,re)}let ke=!1;for await(let J of l.track(e,o,t.turn)){d.push(J);let M=String(J.type??"");if(M==="response.created"||M==="response.in_progress"){m=!0,yield c(J);continue}if(M==="response.output_item.added"){h=!0,yield c(J);continue}if(M==="response.reasoning_text.delta"&&!h){yield*S(),g||(g=!0,y=_++,C+=1,v=C===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${C}`,yield{type:"response.output_item.added",output_index:y,item:{id:v,type:"reasoning",summary:[],content:[],status:"in_progress"}}),P+=String(J.delta??""),yield{type:"response.reasoning_text.delta",item_id:v,output_index:y,content_index:0,delta:J.delta};continue}if(M==="response.output_text.delta"&&!h){yield*S(),yield*k(),A||(A=!0,E=_++,I+=1,O=I===1?p:`${p}_${I}`,yield{type:"response.output_item.added",output_index:E,item:{id:O,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:O,output_index:E,content_index:0,part:{type:"output_text",text:""}}),U+=String(J.delta??""),W+=String(J.delta??""),yield{type:M,item_id:O,output_index:E,content_index:0,delta:J.delta};continue}let re=h?null:Wt(J);if(re){if(yield*S(),yield*k(),yield*K("completed"),te.add(re),re.tool_index!==$e){yield*oe("completed"),$e=re.tool_index;let rt=_++;ne={fcId:`fc_${r.slice(5)}_${re.tool_index}`,outputIndex:rt,callId:re.call_id,name:re.name,args:""},yield{type:"response.output_item.added",output_index:rt,item:{id:ne.fcId,type:"function_call",call_id:ne.callId??ne.fcId,name:ne.name??"",arguments:"",status:"in_progress"}}}ne&&(re.call_id&&(ne.callId=re.call_id),re.name&&(ne.name=re.name),ne.args+=re.delta,yield{type:"response.function_call_arguments.delta",item_id:ne.fcId,output_index:ne.outputIndex,delta:re.delta});continue}if(M==="response.completed"&&!h){let rt=Gt(J.response),se=It(s,te.size+rt.length,W);if(se){ke=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Ot(o,se)}};break}if(yield*k(),yield*K("completed"),yield*oe("completed"),te.size===0)for(let de of rt){let Ce=_++,ot=de.id??de.call_id??`fc_${Ce}`,Le=de.arguments??"",un={id:ot,type:"function_call",call_id:de.call_id??ot,name:de.name??""};yield{type:"response.output_item.added",output_index:Ce,item:{...un,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:ot,output_index:Ce,delta:Le},yield{type:"response.function_call_arguments.done",item_id:ot,output_index:Ce,arguments:Le};let st={...un,arguments:Le,status:"completed"};yield{type:"response.output_item.done",output_index:Ce,item:st},f(Ce,st)}let ie=Vc(w,J.response);yield ie.length>0?c({...J,response:{...J.response,output:ie}}):c(J);continue}yield c(J)}if(yield*k(),yield*K("incomplete"),yield*oe("incomplete"),i&&!ke){let J=et(d);u.remember(r,n,Mo(J,Jt(d,J)),a)}}x();x();var je=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 ht=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)}},Rn=class extends ht{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},No=class extends ht{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")}},We=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},ar=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 Rn;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 Rn;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 No(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 Rn}}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 Uo=require("@urun-sh/core"),Je=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)}},Do=33e4;function Ea(t,e=Do){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new ur),e),a;try{a=await Promise.race([r.next(),s])}catch(l){throw l instanceof Q||l instanceof Uo.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof ur?(await r.return?.(void 0),new Je("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 Je("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 Je("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var ur=class extends Error{constructor(){super("stream idle timeout")}};function xa(t){return t instanceof Je?!1:t instanceof Q?!0:t instanceof Uo.SessionFailedError?t.kind==="transport-failed":!1}var Xc=[/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 Ke(t){return!Xc.some(e=>e.test(t))}function ze(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function Ue(t,e){if(t instanceof Q)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=Aa(t);return n||{message:ze(e?.inferenceId??null),redacted:!0}}function Aa(t){return t instanceof ct?{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 ee?{message:t.message,redacted:!1}:t instanceof je?{message:t.message,redacted:!1}:t instanceof ht?{message:t.message,redacted:!1}:t instanceof Je?Ke(t.message)?{message:t.message,redacted:!1}:null:t instanceof We?{message:t.message,redacted:!1}:t instanceof Se?{message:t.message,redacted:!1}:null}function Kt(t,e,n){let r=n??(i=>console.error(i)),o=Aa(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ve(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Ke(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ve(e)}`),`the ${t} upstream failed while serving this request`)}function tt(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Ke(e)?e:null}function Ve(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var jo="/v1/responses",Qc=64*1024*1024,Zc=8*1024*1024,ep=16,Oa=32,Ia=3600*1e3,tp=/^[A-Za-z0-9._-]{1,256}$/;function Pe(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var np=Pe(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 Bo(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function rp(t){for(;t.bufferedAmount>Zc&&t.readyState===yt.WebSocket.OPEN;){let{promise:e,resolve:n}=Bo();setTimeout(n,5),await e}}var Fo=class extends qt{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 At))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)}},Ho=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 Fo(Sn(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(Pe(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Ia/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Ia).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(Pe(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(Pe(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(Pe(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(Pe(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(Pe(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(Pe(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"||!tp.test(o.stream_id)){this.sendFrame(np);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Oa){this.sendFrame(Pe(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Oa}). 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=vn();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await kn({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:bn(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!==yt.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await rp(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=vn(),o=bn(r);try{let s=Vt(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:Ve(e);if(e instanceof He)return Pe(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof ee)return Pe(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof Q){let a=Ue(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),Pe(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}`),Pe(s.status,{type:s.openaiType,message:o},n);let i=Ue(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),Pe(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=tt(o),a=i??ze(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)}`),Pe(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=ep;){let{promise:e,resolve:n}=Bo();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!==yt.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!==yt.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function lr(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 qo(t,e){let n=new yt.WebSocketServer({noServer:!0,maxPayload:Qc}),r=new xt,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{lr(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==jo){i.add(c);return}s.add(c);let h=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){lr(c,401,"invalid local proxy api key");return}let _;try{_=await a(d)}catch(x){let w=e.statusOf?.(x)??null;lr(c,w?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(h=!0,n.handleUpgrade(d,c,p,x=>{s.delete(c),o.add(x),x.on("close",()=>o.delete(x));try{new Ho(x,_,r,e.statusOf,e.operatorLog??(w=>console.error(w)))}catch{o.delete(x),x.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!h&&!c.destroyed&&lr(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Bo();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let m of s)m.destroy();s.clear();for(let m of i)m.destroy();i.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==yt.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}E();E();var Yo=require("@urun-sh/core");E();var Ta=require("@urun-sh/core"),op={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},sp={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 En(t,e){let n=sp[t.code];return e?`${n} (${e})`:n}function dr(t){if(t==null)return null;let e=op[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 cr(t){if(t.kind==="create-failed")return dr(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Ta.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return dr(e?"cold_start_exceeded":"queue_timeout")}var Na=require("ws");E();var $a=require("@urun-sh/core");E();var Ca=require("crypto");function j(t){return`${t}_${(0,Ca.randomUUID)().replace(/-/g,"").slice(0,24)}`}var pr=4*1024*1024,Go=8*1024*1024,fr=512,mr=20*1024*1024;function ve(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Yt(t,e){return{type:"server_error",code:t,message:e}}function le(t){return{type:"error",event_id:j("event"),error:t}}function Wo(){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},ip={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},ap={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},up={format:!0,voice:!0,speed:!0};function lp(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function zt(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 Pa(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 dp=10;function Jo(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:dp})}function xn(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 ip));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=zt(o.modalities,"modalities"),u=zt(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=zt(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(!lp(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=Jo(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,m]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(m!=null&&m!==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(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new 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 ap))throw new q(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Pa(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=xn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=xn({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 up))throw new q(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Pa(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 gr(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 Vo(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:j("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:j("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 hr(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 cp=1001,pp=1011,La=t=>t.slice(0,120),fp=/^[A-Za-z0-9+/=]*$/,mp=2;function gp(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>mp)return!1;return!0}var An=class{id=j("conn");ws;binding;onClosed;operatorLog;config=Wo();sessionId=j("sess");conversationId=j("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:j("event"),session:gr(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:j("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 Q&&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(le(Yt("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:j("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:j("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:j("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:j("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:j("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:j("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:j("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:j("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=j("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:j("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:j("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:j("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(ve("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>pr){this.fail(ve("frame_too_large",`frame exceeds the ${pr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ve("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ve("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(le({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Yt(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=xn(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(le(ve("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:j("event"),session:gr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Vo(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:j("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(le(ve("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:j("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(le(ve("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:j("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(le(ve("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:j("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(le(ve("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!fp.test(e.audio)){this.send(le(ve("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>mr){this.send(le(ve("buffer_full",`uncommitted input audio exceeds the ${mr}-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:j("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(le(ve("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=j("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:j("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:j("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:j("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:j("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(le(ve("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(le(ve("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(le(ve("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(ve("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(le({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(le(ve("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?zt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?zt(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(le(ve("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=j("req"),a=`resp_${i}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:hr(this.items),c=Jo(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,m=n.max_output_tokens??this.config.maxOutputTokens,h=m==="inf"||m===void 0?void 0:m,_=n.tools!==void 0?n.tools:this.config.tools,x=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,w={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...h!==void 0?{max_output_tokens:h}:{},..._!==void 0?{tools:_}:{},...x!==void 0?{tool_choice:x}:{}};if(!(u&&!this.ensureVoice())){for(let f of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(f);this.inFlight=(async()=>{let f=[],g=P=>{this.responseFlushed?this.send(P):f.push(P)},y=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:j("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(a,"in_progress")});for(let P of f)this.send(P);f.length=0,this.responseFlushed=!0}},b={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},C=null;try{if(u){if(this.pendingTranscriptItemId!==null&&(await new Promise(O=>{this.pendingTranscriptSettled=O}),this.cancelled||this.closed))return;l=this.items.length,d=hr(this.items)}let{input:P,sawAudioOnlyItem:S}=d??{input:[],sawAudioOnlyItem:!1},A={...w,input:P,...u?this.compositeTurnAsk(n):{}};S&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let R;try{R=await this.upstreamStream(A,i)}catch(O){this.upstreamTurnFault(O,a);return}try{for await(let O of R){if(this.cancelled)break;let I=O;if(I.type==="error"){let U=this.upstreamErrorBody(I);this.responseFlushed?this.send(le(U)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(a,U)});return}if(I.type==="response.output_text.delta"&&typeof I.delta=="string"){y(),b.messageOpen||(this.beginMessageItem(a,b.nextOutputIndex++),b.messageOpen=!0),this.config.outputModalities.includes("text")&&g({type:"response.output_text.delta",event_id:j("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:I.delta}),this.turnOutputIsAudio()&&(b.transcriptDelta=!0,g({type:"response.output_audio_transcript.delta",event_id:j("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:I.delta})),b.messageText+=I.delta;continue}if(I.type==="response.function_call_arguments.delta"){y();let U=typeof I.delta=="string"?I.delta:"",W=typeof I.call_id=="string"&&I.call_id.length>0?I.call_id:`${a}_fc_${b.nextOutputIndex}`,K=b.tools.get(W);if(!K){let te=typeof I.name=="string"&&I.name.length>0?I.name:void 0;K={outputIndex:b.nextOutputIndex++,name:te,args:""},b.tools.set(W,K);let ne={id:W,object:"realtime.item",type:"function_call",call_id:W,name:te??"",arguments:"",status:"in_progress"};g({type:"response.output_item.added",event_id:j("event"),response_id:a,output_index:K.outputIndex,item:ne}),this.emitAssistantItemAdded(ne)}typeof I.name=="string"&&I.name.length>0&&(K.name=I.name),K.args+=U,g({type:"response.function_call_arguments.delta",event_id:j("event"),item_id:W,response_id:a,output_index:K.outputIndex,call_id:W,name:K.name??"",delta:U});continue}if(I.type==="response.completed"){C=I.response??null;continue}}}catch(O){this.upstreamTurnFault(O,a);return}if(this.cancelled)return;this.closeOpenItems(a,b,l),y(),this.send({type:"response.done",event_id:j("event"),response:this.doneResponse(a,l,C)})}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(gp(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(le({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:j("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:j("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:j("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:j("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:j("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:j("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:j("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:j("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:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:j("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:j("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:j("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:j("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:j("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:j("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:j("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=tt(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??ze(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&Ke(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: ${Ve(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(Yt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof Q){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=Yt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(le(r)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(ve("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:j("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>fr&&(this.items.shift(),this.send(le({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${fr} 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>Go){this.ws.close(cp,La("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=Ue(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ve(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(pp,La(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=>Ma(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Ma(this.id,e)}},Ko=[];function Ma(t,e){Ko.push({id:t,reason:e}),Ko.length>256&&Ko.shift()}var On="/v1/realtime",hp=t=>t.slice(0,120);function yp(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 qo(t,e){let n=new yt.WebSocketServer({noServer:!0,maxPayload:Qc}),r=new xt,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{lr(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==jo){i.add(c);return}s.add(c);let h=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){lr(c,401,"invalid local proxy api key");return}let _;try{_=await a(d)}catch(S){let w=e.statusOf?.(S)??null;lr(c,w?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(h=!0,n.handleUpgrade(d,c,p,S=>{s.delete(c),o.add(S),S.on("close",()=>o.delete(S));try{new Ho(S,_,r,e.statusOf,e.operatorLog??(w=>console.error(w)))}catch{o.delete(S),S.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!h&&!c.destroyed&&lr(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Bo();if(u)return c(),d;u=!0,t.off("upgrade",l);for(let m of s)m.destroy();s.clear();for(let m of i)m.destroy();i.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==yt.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}x();x();var Yo=require("@urun-sh/core");x();var Ta=require("@urun-sh/core"),op={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},sp={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 En(t,e){let n=sp[t.code];return e?`${n} (${e})`:n}function dr(t){if(t==null)return null;let e=op[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 cr(t){if(t.kind==="create-failed")return dr(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Ta.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return dr(e?"cold_start_exceeded":"queue_timeout")}var Na=require("ws");x();var $a=require("@urun-sh/core");x();var Ca=require("crypto");function j(t){return`${t}_${(0,Ca.randomUUID)().replace(/-/g,"").slice(0,24)}`}var pr=4*1024*1024,Go=8*1024*1024,fr=512,mr=20*1024*1024;function ve(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Yt(t,e){return{type:"server_error",code:t,message:e}}function le(t){return{type:"error",event_id:j("event"),error:t}}function Wo(){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},ip={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},ap={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},up={format:!0,voice:!0,speed:!0};function lp(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function zt(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 Pa(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 dp=10;function Jo(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:dp})}function xn(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 ip));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=zt(o.modalities,"modalities"),u=zt(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=zt(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(!lp(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=Jo(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,m]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(m!=null&&m!==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(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new 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 ap))throw new q(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Pa(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=xn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=xn({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 up))throw new q(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Pa(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 gr(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 Vo(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:j("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:j("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 hr(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 cp=1001,pp=1011,La=t=>t.slice(0,120),fp=/^[A-Za-z0-9+/=]*$/,mp=2;function gp(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>mp)return!1;return!0}var An=class{id=j("conn");ws;binding;onClosed;operatorLog;config=Wo();sessionId=j("sess");conversationId=j("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:j("event"),session:gr(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:j("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 Q&&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(le(Yt("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:j("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:j("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:j("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:j("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:j("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:j("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:j("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:j("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=j("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:j("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:j("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:j("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(ve("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>pr){this.fail(ve("frame_too_large",`frame exceeds the ${pr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ve("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ve("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(le({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Yt(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=xn(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(le(ve("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:j("event"),session:gr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Vo(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:j("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(le(ve("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:j("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(le(ve("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:j("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(le(ve("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:j("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(le(ve("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!fp.test(e.audio)){this.send(le(ve("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>mr){this.send(le(ve("buffer_full",`uncommitted input audio exceeds the ${mr}-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:j("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(le(ve("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=j("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:j("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:j("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:j("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:j("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(le(ve("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(le(ve("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(le(ve("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(ve("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(le({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(le(ve("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?zt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?zt(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(le(ve("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=j("req"),a=`resp_${i}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:hr(this.items),c=Jo(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,m=n.max_output_tokens??this.config.maxOutputTokens,h=m==="inf"||m===void 0?void 0:m,_=n.tools!==void 0?n.tools:this.config.tools,S=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,w={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...h!==void 0?{max_output_tokens:h}:{},..._!==void 0?{tools:_}:{},...S!==void 0?{tool_choice:S}:{}};if(!(u&&!this.ensureVoice())){for(let f of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(f);this.inFlight=(async()=>{let f=[],g=P=>{this.responseFlushed?this.send(P):f.push(P)},y=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:j("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(a,"in_progress")});for(let P of f)this.send(P);f.length=0,this.responseFlushed=!0}},v={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},C=null;try{if(u){if(this.pendingTranscriptItemId!==null&&(await new Promise(O=>{this.pendingTranscriptSettled=O}),this.cancelled||this.closed))return;l=this.items.length,d=hr(this.items)}let{input:P,sawAudioOnlyItem:k}=d??{input:[],sawAudioOnlyItem:!1},A={...w,input:P,...u?this.compositeTurnAsk(n):{}};k&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let E;try{E=await this.upstreamStream(A,i)}catch(O){this.upstreamTurnFault(O,a);return}try{for await(let O of E){if(this.cancelled)break;let I=O;if(I.type==="error"){let U=this.upstreamErrorBody(I);this.responseFlushed?this.send(le(U)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(a,U)});return}if(I.type==="response.output_text.delta"&&typeof I.delta=="string"){y(),v.messageOpen||(this.beginMessageItem(a,v.nextOutputIndex++),v.messageOpen=!0),this.config.outputModalities.includes("text")&&g({type:"response.output_text.delta",event_id:j("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:I.delta}),this.turnOutputIsAudio()&&(v.transcriptDelta=!0,g({type:"response.output_audio_transcript.delta",event_id:j("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:I.delta})),v.messageText+=I.delta;continue}if(I.type==="response.function_call_arguments.delta"){y();let U=typeof I.delta=="string"?I.delta:"",W=typeof I.call_id=="string"&&I.call_id.length>0?I.call_id:`${a}_fc_${v.nextOutputIndex}`,K=v.tools.get(W);if(!K){let te=typeof I.name=="string"&&I.name.length>0?I.name:void 0;K={outputIndex:v.nextOutputIndex++,name:te,args:""},v.tools.set(W,K);let ne={id:W,object:"realtime.item",type:"function_call",call_id:W,name:te??"",arguments:"",status:"in_progress"};g({type:"response.output_item.added",event_id:j("event"),response_id:a,output_index:K.outputIndex,item:ne}),this.emitAssistantItemAdded(ne)}typeof I.name=="string"&&I.name.length>0&&(K.name=I.name),K.args+=U,g({type:"response.function_call_arguments.delta",event_id:j("event"),item_id:W,response_id:a,output_index:K.outputIndex,call_id:W,name:K.name??"",delta:U});continue}if(I.type==="response.completed"){C=I.response??null;continue}}}catch(O){this.upstreamTurnFault(O,a);return}if(this.cancelled)return;this.closeOpenItems(a,v,l),y(),this.send({type:"response.done",event_id:j("event"),response:this.doneResponse(a,l,C)})}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(gp(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(le({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:j("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:j("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:j("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:j("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:j("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:j("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:j("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:j("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:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:j("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:j("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:j("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:j("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:j("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:j("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:j("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=tt(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??ze(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&Ke(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: ${Ve(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(Yt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof Q){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=Yt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(le(r)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(ve("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:j("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>fr&&(this.items.shift(),this.send(le({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${fr} 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>Go){this.ws.close(cp,La("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=Ue(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ve(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(pp,La(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=>Ma(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Ma(this.id,e)}},Ko=[];function Ma(t,e){Ko.push({id:t,reason:e}),Ko.length>256&&Ko.shift()}var On="/v1/realtime",hp=t=>t.slice(0,120);function yp(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
28
  ${hp(n)}\r
29
29
  `),t.destroy()}function wp(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
30
- `}function _p(t){Ze(process.stdout,t)}function vp(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function zo(t){return t.audioSession?.audio.sessionId??void 0}function yr(t,e){let n=new Na.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==On)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=j("rtup"),l=vp(o),d=b=>{(e.log??_p)(wp(b))};d({stage:"accept",conn:u,model:l}),s.resume();let c=new AbortController,p=null,m=b=>{p??=b,c.abort(new Error(p))},h=()=>m("client socket closed"),_=()=>m("client socket closed (half-close)"),x=b=>m(`client socket error: ${b.message}`);s.once("close",h),s.once("end",_),s.once("error",x);let w=()=>{s.removeListener("close",h),s.removeListener("end",_),s.removeListener("error",x)},f=b=>{d({stage:"close",conn:u,model:l,...b})},g=b=>{let C=b,P=C.session!=null&&typeof C.session.sendResponseCreate=="function",S=C.clients!=null&&typeof C.clients.createResponse=="function";if(!P&&!S)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((A,R)=>{n.handleUpgrade(o,s,i,O=>{try{new An({ws:O,binding:b,operatorLog:e.operatorLog,onClosed:(I,U)=>{f({while:"live",reason:U.reason})}}),d({stage:"admit",conn:u,model:l,...zo(b)===void 0?{}:{session:zo(b)}}),A()}catch(I){R(I)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async b=>{if(c.signal.aborted){w();let C=zo(b);try{await b.release?.()}catch(P){f({while:"queued",...C===void 0?{}:{session:C},reason:p??"client socket closed",release_failed:P instanceof Error?P.message:String(P)});return}f({while:"queued",...C===void 0?{}:{session:C},reason:p??"client socket closed",released:!0}),s.destroy();return}w(),await g(b)}).catch(b=>{let C=b instanceof Yo.SessionFailedError?cr(b):null,P=null;if(b!==null&&typeof b=="object"&&"status"in b){let O=b.status;typeof O=="number"&&(P=O)}let S=P??C?.status??502,A=b instanceof Error?b.message:String(b),R=P!==null?A:C!==null?En(C,b instanceof Yo.SessionFailedError&&b.status.sessionId?`session ${b.status.sessionId}`:void 0):Ue(b).message;f({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:A,status:S}}),s.destroyed||yp(s,S,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()))}}E();var Au=require("crypto");E();var Qp=require("http");E();var V=class extends Error{},Be=class extends Error{};function Ee(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function _r(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function Xt(t,e){if(t!=null)throw new V(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function wr(t){let e=_r(t);return e!==null&&e<=1?e:null}function Ua(t,e){if(!Ee(t))throw new V("decisions requires a JSON object body");Xt(t.prompt_cache_key,"prompt_cache_key"),Xt(t.prompt_cache_options,"prompt_cache_options"),Xt(t.safety_identifier,"safety_identifier");let n=[],r=bp(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new V("decisions requires a questions array of 1 to 400 questions");let s={},i=[],a=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=Ep(o[l],l,o.length,n);if(a.has(c.key))throw new V(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),s[c.key]=d,i.push(c)}let u={model:e,state:r,questions:s};return n.length>0&&(u.media=n),{systemone:u,specs:i}}function bp(t,e){if(typeof t=="string")return t;if(!Ee(t)&&!Array.isArray(t))throw new V("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)kp(o,r,e);return Sp(r)}function Sp(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
30
+ `}function _p(t){Ze(process.stdout,t)}function vp(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function zo(t){return t.audioSession?.audio.sessionId??void 0}function yr(t,e){let n=new Na.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==On)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=j("rtup"),l=vp(o),d=v=>{(e.log??_p)(wp(v))};d({stage:"accept",conn:u,model:l}),s.resume();let c=new AbortController,p=null,m=v=>{p??=v,c.abort(new Error(p))},h=()=>m("client socket closed"),_=()=>m("client socket closed (half-close)"),S=v=>m(`client socket error: ${v.message}`);s.once("close",h),s.once("end",_),s.once("error",S);let w=()=>{s.removeListener("close",h),s.removeListener("end",_),s.removeListener("error",S)},f=v=>{d({stage:"close",conn:u,model:l,...v})},g=v=>{let C=v,P=C.session!=null&&typeof C.session.sendResponseCreate=="function",k=C.clients!=null&&typeof C.clients.createResponse=="function";if(!P&&!k)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((A,E)=>{n.handleUpgrade(o,s,i,O=>{try{new An({ws:O,binding:v,operatorLog:e.operatorLog,onClosed:(I,U)=>{f({while:"live",reason:U.reason})}}),d({stage:"admit",conn:u,model:l,...zo(v)===void 0?{}:{session:zo(v)}}),A()}catch(I){E(I)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async v=>{if(c.signal.aborted){w();let C=zo(v);try{await v.release?.()}catch(P){f({while:"queued",...C===void 0?{}:{session:C},reason:p??"client socket closed",release_failed:P instanceof Error?P.message:String(P)});return}f({while:"queued",...C===void 0?{}:{session:C},reason:p??"client socket closed",released:!0}),s.destroy();return}w(),await g(v)}).catch(v=>{let C=v instanceof Yo.SessionFailedError?cr(v):null,P=null;if(v!==null&&typeof v=="object"&&"status"in v){let O=v.status;typeof O=="number"&&(P=O)}let k=P??C?.status??502,A=v instanceof Error?v.message:String(v),E=P!==null?A:C!==null?En(C,v instanceof Yo.SessionFailedError&&v.status.sessionId?`session ${v.status.sessionId}`:void 0):Ue(v).message;f({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:A,status:k}}),s.destroyed||yp(s,k,E)}).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 Au=require("crypto");x();var Qp=require("http");x();var V=class extends Error{},Be=class extends Error{};function Ee(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function _r(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function Xt(t,e){if(t!=null)throw new V(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function wr(t){let e=_r(t);return e!==null&&e<=1?e:null}function Ua(t,e){if(!Ee(t))throw new V("decisions requires a JSON object body");Xt(t.prompt_cache_key,"prompt_cache_key"),Xt(t.prompt_cache_options,"prompt_cache_options"),Xt(t.safety_identifier,"safety_identifier");let n=[],r=bp(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new V("decisions requires a questions array of 1 to 400 questions");let s={},i=[],a=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=Ep(o[l],l,o.length,n);if(a.has(c.key))throw new V(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),s[c.key]=d,i.push(c)}let u={model:e,state:r,questions:s};return n.length>0&&(u.media=n),{systemone:u,specs:i}}function bp(t,e){if(typeof t=="string")return t;if(!Ee(t)&&!Array.isArray(t))throw new V("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)kp(o,r,e);return Sp(r)}function Sp(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
31
31
 
32
- `)}function kp(t,e,n){if(!Ee(t))throw new V("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){Rp(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let s=t.output;if(typeof s=="string"){e.push({text:s});return}if(Array.isArray(s)){Da(s,e,n,void 0,!1);return}throw new V(`${o} output must be a string or an array of parts`)}default:throw new V(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function Rp(t,e,n,r){e==="assistant"&&Xt(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new V(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!Ee(s))throw new V("decisions assistant message parts must be JSON objects");if(s.type==="output_text"&&typeof s.text=="string")n.push({role:e,text:s.text});else if(s.type==="refusal"&&typeof s.refusal=="string")n.push({role:e,text:`[refusal] ${s.refusal}`});else throw new V(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}Da(o,n,r,e)}function Da(t,e,n,r,o=!0){for(let s of t){if(!Ee(s))throw new V("decisions content parts must be JSON objects");switch(Xt(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new V("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new V("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let i=s.data;if(!Ee(i)&&!(Array.isArray(i)&&i.every(Ee)))throw new V("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(Fa(s));break}default:throw new V(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function Fa(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new V("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new V("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new V("input_image data URL carries no image data");let s=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(s?o.length%4!==0:o.length%4===1))throw new V("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=t.detail;if(i!=null&&i!=="low"&&i!=="high"&&i!=="auto"&&i!=="original")throw new V("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(a.detail=i),a}function Ep(t,e,n,r){if(!Ee(t))throw new V(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new V(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let s=t.name;if(s!==void 0&&typeof s!="string")throw new V(`questions[${e}] name must be a string`);let i=s??null,a=i??`q${e}`,u=xp(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:u,options:[["no","the condition is not true"],["yes","the condition is true"]]},spec:{type:o,key:a,name:i}};case"choice":{let l=t.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new V(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let _ of l){if(!Ee(_))throw new V(`questions[${e}] choices must be JSON objects`);let x=_.value;if(typeof x!="string"&&typeof x!="boolean")throw new V(`questions[${e}] choice value must be a string or boolean`);let w=String(x);if(c.has(w))throw new V(`questions[${e}] has duplicate choice value ${JSON.stringify(w)} (choices must be unique)`);c.add(w);let f=_.description;if(f!==void 0&&typeof f!="string")throw new V(`questions[${e}] choice description must be a string`);d.push(x),p.push(f)}let m=l.map((_,x)=>({name:String(d[x]),description:p[x]??String(d[x])}));return{entry:{kind:"choice",prompt:u,options:m},spec:{type:o,key:a,name:i,choiceValues:d}}}case"score":{let l=t.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new V(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let m of l){if(!Ee(m)||typeof m.label!="string")throw new V(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new V(`questions[${e}] has duplicate level label ${JSON.stringify(m.label)}`);d.push(m.label);let h=m.description;if(h!==void 0&&typeof h!="string")throw new V(`questions[${e}] score level description must be a string`);let _=h!==void 0?`${m.label}: ${h}`:m.label;if(c.includes(_))throw new V(`questions[${e}] has duplicate score criterion ${JSON.stringify(_)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(_)}return{entry:{kind:"score",prompt:u,criteria:c},spec:{type:o,key:a,name:i,levelLabels:d,scoreCriteria:c}}}}}function xp(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new V(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!Ee(s))throw new V(`questions[${e}] instruction parts must be JSON objects`);switch(Xt(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new V(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new V(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(Fa(s));break}case"input_json":{let i=s.data;if(!Ee(i)&&!(Array.isArray(i)&&i.every(Ee)))throw new V(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new V(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
32
+ `)}function kp(t,e,n){if(!Ee(t))throw new V("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){Rp(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let s=t.output;if(typeof s=="string"){e.push({text:s});return}if(Array.isArray(s)){Da(s,e,n,void 0,!1);return}throw new V(`${o} output must be a string or an array of parts`)}default:throw new V(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function Rp(t,e,n,r){e==="assistant"&&Xt(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new V(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!Ee(s))throw new V("decisions assistant message parts must be JSON objects");if(s.type==="output_text"&&typeof s.text=="string")n.push({role:e,text:s.text});else if(s.type==="refusal"&&typeof s.refusal=="string")n.push({role:e,text:`[refusal] ${s.refusal}`});else throw new V(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}Da(o,n,r,e)}function Da(t,e,n,r,o=!0){for(let s of t){if(!Ee(s))throw new V("decisions content parts must be JSON objects");switch(Xt(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new V("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new V("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let i=s.data;if(!Ee(i)&&!(Array.isArray(i)&&i.every(Ee)))throw new V("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(Fa(s));break}default:throw new V(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function Fa(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new V("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new V("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new V("input_image data URL carries no image data");let s=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(s?o.length%4!==0:o.length%4===1))throw new V("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=t.detail;if(i!=null&&i!=="low"&&i!=="high"&&i!=="auto"&&i!=="original")throw new V("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(a.detail=i),a}function Ep(t,e,n,r){if(!Ee(t))throw new V(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new V(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let s=t.name;if(s!==void 0&&typeof s!="string")throw new V(`questions[${e}] name must be a string`);let i=s??null,a=i??`q${e}`,u=xp(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:u,options:[["no","the condition is not true"],["yes","the condition is true"]]},spec:{type:o,key:a,name:i}};case"choice":{let l=t.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new V(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let _ of l){if(!Ee(_))throw new V(`questions[${e}] choices must be JSON objects`);let S=_.value;if(typeof S!="string"&&typeof S!="boolean")throw new V(`questions[${e}] choice value must be a string or boolean`);let w=String(S);if(c.has(w))throw new V(`questions[${e}] has duplicate choice value ${JSON.stringify(w)} (choices must be unique)`);c.add(w);let f=_.description;if(f!==void 0&&typeof f!="string")throw new V(`questions[${e}] choice description must be a string`);d.push(S),p.push(f)}let m=l.map((_,S)=>({name:String(d[S]),description:p[S]??String(d[S])}));return{entry:{kind:"choice",prompt:u,options:m},spec:{type:o,key:a,name:i,choiceValues:d}}}case"score":{let l=t.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new V(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let m of l){if(!Ee(m)||typeof m.label!="string")throw new V(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new V(`questions[${e}] has duplicate level label ${JSON.stringify(m.label)}`);d.push(m.label);let h=m.description;if(h!==void 0&&typeof h!="string")throw new V(`questions[${e}] score level description must be a string`);let _=h!==void 0?`${m.label}: ${h}`:m.label;if(c.includes(_))throw new V(`questions[${e}] has duplicate score criterion ${JSON.stringify(_)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(_)}return{entry:{kind:"score",prompt:u,criteria:c},spec:{type:o,key:a,name:i,levelLabels:d,scoreCriteria:c}}}}}function xp(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new V(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!Ee(s))throw new V(`questions[${e}] instruction parts must be JSON objects`);switch(Xt(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new V(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new V(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(Fa(s));break}case"input_json":{let i=s.data;if(!Ee(i)&&!(Array.isArray(i)&&i.every(Ee)))throw new V(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new V(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
33
33
 
34
- `)}function Ha(t,e){if(!Ee(e))throw new Be("decision answer was not a JSON object");let n=e.choices;if(!Ee(n))throw new Be("decision answer carried no choices object");let r=[];for(let o of t){let s=n[o.key];if(!Ee(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=Ee(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let a=wr(i.yes),u=wr(i.no),l=a??(u!==null?1-u:null);if(l===null)throw new Be(`the predicate answer for "${o.key}" carries neither a yes nor a no probability to translate`);r.push({type:"predicate",name:o.name,probability:l});continue}case"choice":{let a=o.choiceValues??[],u=s.choice;if(typeof u!="string")throw new Be(`the choice answer for "${o.key}" carries no string choice`);let l=a.findIndex(p=>String(p)===u);if(l===-1)throw new Be(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(u)})`);let d=_r(s.confidence);if(d===null)throw new Be(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let m=wr(i[String(p)]);m!==null&&c.push({value:p,probability:m})}r.push({type:"choice",name:o.name,choice:a[l],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],u=o.scoreCriteria??[],l=_r(s.score);if(l===null)throw new Be(`the score answer for "${o.key}" carries no numeric score to translate`);let d=_r(s.confidence);if(d===null)throw new Be(`the score answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p=0;p<a.length;p++){let m=wr(i[u[p]]);m!==null&&c.push({value:p,label:a[p],probability:m})}r.push({type:"score",name:o.name,score:l,confidence:d,probabilities:c});continue}}}return r}E();E();var xe=class extends Error{};async function vr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new xe(`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 xe(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function br(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 xe(`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 xe?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var ja="/v1/images/generations",Sr="/v1/images/edits";function Ba(t){return t===ja||t===Sr}var qa="/v1/images/models";async function Ga(t,e,n){if(t){if(t.model=Te({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 Z=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Ap=16*1024*1024,Wa=64*1024*1024;function Ja(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 In(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 Va(t,e,n,r,o,s){let i=s??(h=>console.error(h)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),u=null;for await(let h of a){if(h.type==="error"){let _=h.error??{},x=typeof _.message=="string"&&_.message.length>0&&Ke(_.message)?_.message:null;throw x===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(h)}`),new Z(502,"the image upstream failed while serving this request")):new Z(502,`image upstream error: ${x}`)}if(h.type==="response.completed"){u=h.response??null;break}}if(u===null)throw new Z(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=ut(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new Z(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(Ja(p)===null)throw new Z(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 Ka(t,e){if(t instanceof Z)return t;if(t instanceof je)throw t;return t instanceof ee?new Z(404,t.message):new Z(502,Kt("image",t,e))}async function za(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 In(r,new Z(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 Ya(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 Op={model:!0,prompt:!0,response_format:!0,n:!0};async function Qa(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Wa;try{if(t.method!=="POST")throw new Z(405,`${String(t.method)} is not supported on ${ja}`);let s;try{s=JSON.parse((await vr(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof xe?new Z(413,p.message):new Z(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new Z(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!Op[p])throw new Z(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 Z(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 Z(400,"model must be a string","model");await Ga(n.turn,n.clients,u);let l=i.n??1;if(l!==1)throw new Z(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 Z(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 za(n.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Va(n.clients,u,c,n.turn?Fe(n.turn):void 0,n.turn,r);Ya(n.turn,p),Xa(e,p)}catch(p){throw Ka(p,r)}}catch(s){if(s instanceof xe){In(e,new Z(413,s.message));return}if(s instanceof Z){In(e,s);return}throw s}}var Ip={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Za(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Wa,s=n.maxImagePartBytes??Ap;try{if(t.method!=="POST")throw new Z(405,`${String(t.method)} is not supported on ${Sr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new Z(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await br(t,o)}catch(h){throw h instanceof xe?new Z(413,h.message):new Z(400,String(h instanceof Error?h.message:h))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new Z(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 Z(400,"model must be a string field","model");let d=l===null?void 0:l;await Ga(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new Z(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 h of a.keys())if(!Ip[h])throw new Z(400,`form field "${h}" 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[]).`,h);let p=[];for(let h of["image","image[]"])for(let _ of a.getAll(h)){if(!(_ instanceof File))throw new Z(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",h);if(_.size>s)throw new Z(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,h);let x=new Uint8Array(await _.arrayBuffer()),w=Ja(x);if(w===null)throw new Z(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",h);p.push({bytes:x,mime:w})}if(p.length===0)throw new Z(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await za(n.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:u}];for(let{bytes:h,mime:_}of p)m.push({type:"input_image",image_url:`data:${_};base64,${Buffer.from(h).toString("base64")}`});try{let h=await Va(n.clients,d,m,n.turn?Fe(n.turn):void 0,n.turn,r);Ya(n.turn,h),Xa(e,h)}catch(h){throw Ka(h,r)}}catch(i){if(i instanceof xe){In(e,new Z(413,i.message));return}if(i instanceof Z){In(e,i);return}throw i}}E();var Tn="/v1/audio/speech";function uu(t){return t===Tn}var eu=4096,tu=18e4,nu=5e3,Tp=64*1024*1024,ru=8,ou=5,su=1024*1024,Qt="voice_applied",Rr="X-Urun-Voice-Applied",z=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Xo(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 Er=class extends z{constructor(e){super(502,e)}};function lu(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 du(t){return new z(502,`the runtime's ${Qt} receipt ${JSON.stringify(t)} cannot be relayed as the ${Rr} 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 Pp(t,e,n){if(t){if(t.model=Te({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 cu(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Cp=2;function Lp(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Cp)return!1;return!0}function Mp(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 iu=new WeakMap,kr=new WeakMap;function $p(t,e){let n=kr.get(t)??0;if(n>=ru)throw new z(503,`this model's speech queue is full \u2014 ${ru} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${ou}s`,void 0,ou);kr.set(t,n+1);let r=iu.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return iu.set(t,s),(async()=>{await r;try{return await e()}finally{kr.set(t,(kr.get(t)??1)-1),o()}})()}async function Np(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new z(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 Q))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 Tt(t,e){if(t instanceof z)return t;if(t instanceof je)throw t;return t instanceof ee?new z(404,t.message):new z(502,Kt("speech",t,e))}async function au(t,e,n,r,o,s,i,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return $p(e,async()=>{if(i?.()===!0)return null;let p=!1,m=!1,h=!1,_,x=new Promise(S=>{_=S}),w=[],f=()=>{m&&!h&&w.length>=o.quietRunFrames&&(h=!0,_())},g=e.onOutputAudio(S=>{let A=Buffer.from(S,"base64");if(A.byteLength===0)return;let R=Lp(A);if(!p){if(R)return;p=!0}if(R){w.push(A),f();return}for(let O of w)c(O);w.length=0,c(A),f()}),y=null,b,C,P;try{P=(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 A=new Promise(I=>{C=setTimeout(I,s.capMs)}),R=!1;for(;;){let I=P.next(),U=await Promise.race([I,A]);if(U===void 0){R=!0,I.catch(()=>{});break}if(U.done)break;let W=U.value;if(W.type==="error"){let K=W.error??{};await P.return?.();let te=typeof K.message=="string"&&K.message.length>0&&Ke(K.message)?K.message:null;throw te===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(W)}`),new z(502,"the speech upstream failed while serving this request")):new z(502,`speech upstream error: ${te}`)}if(W.type==="response.completed"){y=W.response??null,m=!0,u?.(y),f(),await P.return?.();break}}if(clearTimeout(C),R)throw new z(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 z(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let O=!1;if(await Promise.race([x,new Promise(I=>{b=setTimeout(()=>{O=!0,I()},o.capMs)})]),b!==void 0&&clearTimeout(b),r.voice!==void 0){let I=y[Qt];if(typeof I!="string"||I!==r.voice){let U=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof I=="string"?`${Qt} ${JSON.stringify(I)}`:`no ${Qt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw h?new Er(U):new z(502,U)}}if(!p)throw new z(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(O&&!h&&w.length<1)throw new z(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(S){throw S instanceof Er||await Np(t,n,P,s.returnBoundMs),S}finally{b!==void 0&&clearTimeout(b),C!==void 0&&clearTimeout(C),g()}})}function Up(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",Rr)),t.write(a,u=>{u||(s+=a.byteLength,cu(e,s))}),t.writableLength>su&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${su} 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[Qt];if(typeof u=="string"){if(!lu(u))throw du(u);t.addTrailers({[Rr]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:i}}async function Dp(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Tt(s,r)}return o?!0:(Xo(n,new z(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 Fp={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Hp="wav, pcm";async function pu(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??Tp,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new z(405,`${String(t.method)} is not supported on ${Tn}`);let a;try{a=JSON.parse((await vr(t,o)).toString("utf8")||"{}")}catch(y){throw y instanceof xe?new z(413,y.message):new z(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new z(400,"request body must be a JSON object");let u=a;for(let y of Object.keys(u))if(!Fp[y])throw new z(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 z(400,"input is required and must be a non-empty string","input");if(l.length>eu)throw new z(400,`input is ${l.length} chars \u2014 over the ${eu}-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 z(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new z(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new z(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 ${Tn} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(y){throw Tt(y,r)}if(p.defect!==null)throw new z(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof c=="string"?c:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new z(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let h=u.response_format??"wav";if(h!=="wav"&&h!=="pcm")throw new z(400,`response_format ${JSON.stringify(h)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Hp} \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 z(400,"stream_format, when present, must be a string","stream_format");let _=u.speed;if(_!==void 0){if(typeof _!="number"||!Number.isFinite(_))throw new z(400,"speed, when present, must be a number","speed");if(_!==1)throw new z(400,`speed=${JSON.stringify(_)} 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 x=u.instructions;if(x!==void 0){if(typeof x!="string")throw new z(400,"instructions, when present, must be a string","instructions");if(x.trim().length>0)throw new z(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 Pp(n.turn,n.clients,d);let w=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",w,w),!await Dp(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new z(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 z(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 z(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 Tt(y,r)}let g;try{g=await n.clients.openAudioOn(f)}catch(y){throw Tt(y,r)}n.turn&&(n.turn.sessionId=g.sessionId);try{if(h==="wav"){let y=[],b=await au(n.clients,g,f,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??tu,returnBoundMs:n.turnReturnBoundMs??nu},i,P=>y.push(P),P=>{n.turn&&(n.turn.outputSeconds=ut(P))},r);if(b===null||i())return;let C=Buffer.concat(y);if(m===void 0){let P=b[Qt];if(typeof P=="string"){if(!lu(P))throw du(P);e.setHeader(Rr,P)}}cu(n.turn,C.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Mp(C.byteLength),C]))}else{let y=Up(e,n.turn,i,m===void 0),b;try{b=await au(n.clients,g,f,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??tu,returnBoundMs:n.turnReturnBoundMs??nu},i,y.sink,C=>{n.turn&&(n.turn.outputSeconds=ut(C))},r)}catch(C){let P=Tt(C,r);if(!y.started())throw P;n.turn&&(n.turn.streamError=!0),y.fail(P);return}if(b===null)return;try{await y.finish(b)}catch(C){let P=Tt(C,r);n.turn&&(n.turn.streamError=!0),y.fail(P);return}}}catch(y){throw Tt(y,r)}}catch(a){if(a instanceof xe){Xo(e,new z(413,a.message));return}if(a instanceof z){Xo(e,a);return}throw a}}E();var xr="/v1/audio/transcriptions";function fu(t){return t===xr}var mu="/v1/audio/models",jp=16*1024*1024,Bp=64*1024*1024,pe=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Qo(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 gu(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 qp(t){if(!gu(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 Gp(t,e,n){if(t){if(t.model=Te({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 Wp(t,e){t&&(t.outputUnits=e.seconds)}async function Jp(t,e,n,r,o,s,i){let a=i??(c=>console.error(c)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of u){if(l.push(c),c.type==="error"){let p=c.error??{},m=typeof p.type=="string"?p.type:"upstream_error",h=typeof p.message=="string"&&p.message.length>0&&Ke(p.message)?p.message:null;throw h===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new pe(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new pe(m==="invalid_request_error"?400:502,`transcription upstream error: ${h}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new pe(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=ut(d)),Jt(l,d)}function hu(t,e){if(t instanceof pe)return t;if(t instanceof je)throw t;return t instanceof ee?new pe(404,t.message):new pe(502,Kt("transcription",t,e))}async function Vp(t,e,n,r){let o;try{o=await t(e)}catch(s){throw hu(s,r)}return o?!0:(Qo(n,new pe(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 Kp=new Set(["file","model","language","response_format"]);async function yu(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Bp,s=n.maxAudioPartBytes??jp;try{if(t.method!=="POST")throw new pe(405,`${String(t.method)} is not supported on ${xr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new pe(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await br(t,o)}catch(f){throw f instanceof xe?new pe(413,f.message):new pe(400,String(f instanceof Error?f.message:f))}let u=new Map;for(let f of a.keys()){if(!Kp.has(f))throw new pe(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,g]of u)if(g>1)throw new pe(400,`form field "${f}" appears ${g} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,f);let l=a.get("model");if(l!==null&&typeof l!="string")throw new pe(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 pe(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,m=a.get("response_format")??"json";if(m!=="json")throw new pe(400,`response_format ${JSON.stringify(m)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let h=a.get("file");if(!(h instanceof File))throw new pe(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(h.size>s)throw new pe(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let _=new Uint8Array(await h.arrayBuffer());if(!gu(_))throw new pe(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 x=qp(_);if(x===null)throw new pe(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 Gp(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",_.length,_.length),!await Vp(n.transcriptionModels,d,e,r))return;let w=[{type:"input_audio",input_audio:{data:Buffer.from(_).toString("base64"),format:"wav"}}];try{let f=await Jp(n.clients,d,w,p,n.turn?Fe(n.turn):void 0,n.turn,r);Wp(n.turn,x),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:f}))}catch(f){throw hu(f,r)}}catch(i){if(i instanceof xe){Qo(e,new pe(413,i.message));return}if(i instanceof pe){Qo(e,i);return}throw i}}var Tr=require("@urun-sh/core");E();var es="x-urun-profile",Pn="voice";var Me=class extends Error{status=400},zp=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Yp=/\s/;function Xp(t){return zp.test(t)}function Zo(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Me(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function wu(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 Me(`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 Me(`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 Me(`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 _u(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 Me(`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 Me(`the ${es} header is empty \u2014 the only profile this lane accepts is "${Pn}" (omit the header for the ordinary lane)`);if(l!==Pn)throw new Me(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Pn}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Pn)throw new Me(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Pn}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new Me("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 Me("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:wu(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:wu(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Zo(u,"sentence_flush",!0),includeReasoning:Zo(u,"include_reasoning",!1),metadata:Zo(u,"metadata",!1)}}var Zt=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&&Xp(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 rs(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Zp(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 Ae(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function ae(t,e,n,r="invalid_request_error",o){Ae(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function os(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=tt(r),a=i??ze(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"),Ae(t,l,{error:{message:a,type:o,code:u}})}function Ye(t,e,n,r){Ae(t,e,{type:"error",error:{type:n,message:r}})}function en(t,e,n){if(e==="anthropic"){Ae(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}Ae(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var ef=64*1024*1024,Cn=class extends Error{};async function vu(t,e=ef){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Cn(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Pt(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 Su(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 Ar(t){let e=Su(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function bu(t){let e=Ar(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:tf(t)},completion_tokens_details:{reasoning_tokens:0}}}function tf(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function nf(t,e){let n=Su(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function rf(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 of(t,e){let n=rf(e);n&&(t.timing=n),t.outputSeconds=ut(e)}function Ct(t,e){nf(t,e),of(t,e)}async function Pr(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 ku(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 sf(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 Or=class extends Error{};function af(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 Or(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function uf(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:af(n.role,n.content)})}return e}function ts(t){return Gt(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 lf(t,e,n,r,o,s,i){let a=bn(s.id),u=t.stream===!0;if(s.model=Te(t),s.stream=u,await Pr(s,e,typeof t.model=="string"?t.model:void 0),u){let f;try{f=await kn({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(g){if(g instanceof ee){en(r,"openai",g);return}if(g instanceof He){ae(r,g.status,g.message);return}if(g instanceof We||g instanceof Se){r.setHeader("retry-after","2"),ae(r,503,g.message,"capacity_error");return}throw g}rs(r);for await(let g of f.events){if(g.type==="error"){s.streamError=!0;let y=g.error,b=tt(y),C=b??ze(s.id);b===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(g)}`),r.write(`event: error
34
+ `)}function Ha(t,e){if(!Ee(e))throw new Be("decision answer was not a JSON object");let n=e.choices;if(!Ee(n))throw new Be("decision answer carried no choices object");let r=[];for(let o of t){let s=n[o.key];if(!Ee(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=Ee(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let a=wr(i.yes),u=wr(i.no),l=a??(u!==null?1-u:null);if(l===null)throw new Be(`the predicate answer for "${o.key}" carries neither a yes nor a no probability to translate`);r.push({type:"predicate",name:o.name,probability:l});continue}case"choice":{let a=o.choiceValues??[],u=s.choice;if(typeof u!="string")throw new Be(`the choice answer for "${o.key}" carries no string choice`);let l=a.findIndex(p=>String(p)===u);if(l===-1)throw new Be(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(u)})`);let d=_r(s.confidence);if(d===null)throw new Be(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let m=wr(i[String(p)]);m!==null&&c.push({value:p,probability:m})}r.push({type:"choice",name:o.name,choice:a[l],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],u=o.scoreCriteria??[],l=_r(s.score);if(l===null)throw new Be(`the score answer for "${o.key}" carries no numeric score to translate`);let d=_r(s.confidence);if(d===null)throw new Be(`the score answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p=0;p<a.length;p++){let m=wr(i[u[p]]);m!==null&&c.push({value:p,label:a[p],probability:m})}r.push({type:"score",name:o.name,score:l,confidence:d,probabilities:c});continue}}}return r}x();x();var xe=class extends Error{};async function vr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new xe(`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 xe(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function br(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 xe(`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 xe?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var ja="/v1/images/generations",Sr="/v1/images/edits";function Ba(t){return t===ja||t===Sr}var qa="/v1/images/models";async function Ga(t,e,n){if(t){if(t.model=Te({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 Z=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Ap=16*1024*1024,Wa=64*1024*1024;function Ja(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 In(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 Va(t,e,n,r,o,s){let i=s??(h=>console.error(h)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),u=null;for await(let h of a){if(h.type==="error"){let _=h.error??{},S=typeof _.message=="string"&&_.message.length>0&&Ke(_.message)?_.message:null;throw S===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(h)}`),new Z(502,"the image upstream failed while serving this request")):new Z(502,`image upstream error: ${S}`)}if(h.type==="response.completed"){u=h.response??null;break}}if(u===null)throw new Z(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=ut(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new Z(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(Ja(p)===null)throw new Z(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 Ka(t,e){if(t instanceof Z)return t;if(t instanceof je)throw t;return t instanceof ee?new Z(404,t.message):new Z(502,Kt("image",t,e))}async function za(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 In(r,new Z(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 Ya(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 Op={model:!0,prompt:!0,response_format:!0,n:!0};async function Qa(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Wa;try{if(t.method!=="POST")throw new Z(405,`${String(t.method)} is not supported on ${ja}`);let s;try{s=JSON.parse((await vr(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof xe?new Z(413,p.message):new Z(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new Z(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!Op[p])throw new Z(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 Z(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 Z(400,"model must be a string","model");await Ga(n.turn,n.clients,u);let l=i.n??1;if(l!==1)throw new Z(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 Z(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 za(n.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Va(n.clients,u,c,n.turn?Fe(n.turn):void 0,n.turn,r);Ya(n.turn,p),Xa(e,p)}catch(p){throw Ka(p,r)}}catch(s){if(s instanceof xe){In(e,new Z(413,s.message));return}if(s instanceof Z){In(e,s);return}throw s}}var Ip={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Za(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Wa,s=n.maxImagePartBytes??Ap;try{if(t.method!=="POST")throw new Z(405,`${String(t.method)} is not supported on ${Sr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new Z(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await br(t,o)}catch(h){throw h instanceof xe?new Z(413,h.message):new Z(400,String(h instanceof Error?h.message:h))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new Z(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 Z(400,"model must be a string field","model");let d=l===null?void 0:l;await Ga(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new Z(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 h of a.keys())if(!Ip[h])throw new Z(400,`form field "${h}" 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[]).`,h);let p=[];for(let h of["image","image[]"])for(let _ of a.getAll(h)){if(!(_ instanceof File))throw new Z(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",h);if(_.size>s)throw new Z(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,h);let S=new Uint8Array(await _.arrayBuffer()),w=Ja(S);if(w===null)throw new Z(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",h);p.push({bytes:S,mime:w})}if(p.length===0)throw new Z(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await za(n.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:u}];for(let{bytes:h,mime:_}of p)m.push({type:"input_image",image_url:`data:${_};base64,${Buffer.from(h).toString("base64")}`});try{let h=await Va(n.clients,d,m,n.turn?Fe(n.turn):void 0,n.turn,r);Ya(n.turn,h),Xa(e,h)}catch(h){throw Ka(h,r)}}catch(i){if(i instanceof xe){In(e,new Z(413,i.message));return}if(i instanceof Z){In(e,i);return}throw i}}x();var Tn="/v1/audio/speech";function uu(t){return t===Tn}var eu=4096,tu=18e4,nu=5e3,Tp=64*1024*1024,ru=8,ou=5,su=1024*1024,Qt="voice_applied",Rr="X-Urun-Voice-Applied",z=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Xo(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 Er=class extends z{constructor(e){super(502,e)}};function lu(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 du(t){return new z(502,`the runtime's ${Qt} receipt ${JSON.stringify(t)} cannot be relayed as the ${Rr} 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 Pp(t,e,n){if(t){if(t.model=Te({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 cu(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Cp=2;function Lp(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Cp)return!1;return!0}function Mp(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 iu=new WeakMap,kr=new WeakMap;function $p(t,e){let n=kr.get(t)??0;if(n>=ru)throw new z(503,`this model's speech queue is full \u2014 ${ru} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${ou}s`,void 0,ou);kr.set(t,n+1);let r=iu.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return iu.set(t,s),(async()=>{await r;try{return await e()}finally{kr.set(t,(kr.get(t)??1)-1),o()}})()}async function Np(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new z(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 Q))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 Tt(t,e){if(t instanceof z)return t;if(t instanceof je)throw t;return t instanceof ee?new z(404,t.message):new z(502,Kt("speech",t,e))}async function au(t,e,n,r,o,s,i,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return $p(e,async()=>{if(i?.()===!0)return null;let p=!1,m=!1,h=!1,_,S=new Promise(k=>{_=k}),w=[],f=()=>{m&&!h&&w.length>=o.quietRunFrames&&(h=!0,_())},g=e.onOutputAudio(k=>{let A=Buffer.from(k,"base64");if(A.byteLength===0)return;let E=Lp(A);if(!p){if(E)return;p=!0}if(E){w.push(A),f();return}for(let O of w)c(O);w.length=0,c(A),f()}),y=null,v,C,P;try{P=(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 A=new Promise(I=>{C=setTimeout(I,s.capMs)}),E=!1;for(;;){let I=P.next(),U=await Promise.race([I,A]);if(U===void 0){E=!0,I.catch(()=>{});break}if(U.done)break;let W=U.value;if(W.type==="error"){let K=W.error??{};await P.return?.();let te=typeof K.message=="string"&&K.message.length>0&&Ke(K.message)?K.message:null;throw te===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(W)}`),new z(502,"the speech upstream failed while serving this request")):new z(502,`speech upstream error: ${te}`)}if(W.type==="response.completed"){y=W.response??null,m=!0,u?.(y),f(),await P.return?.();break}}if(clearTimeout(C),E)throw new z(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 z(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let O=!1;if(await Promise.race([S,new Promise(I=>{v=setTimeout(()=>{O=!0,I()},o.capMs)})]),v!==void 0&&clearTimeout(v),r.voice!==void 0){let I=y[Qt];if(typeof I!="string"||I!==r.voice){let U=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof I=="string"?`${Qt} ${JSON.stringify(I)}`:`no ${Qt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw h?new Er(U):new z(502,U)}}if(!p)throw new z(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(O&&!h&&w.length<1)throw new z(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(k){throw k instanceof Er||await Np(t,n,P,s.returnBoundMs),k}finally{v!==void 0&&clearTimeout(v),C!==void 0&&clearTimeout(C),g()}})}function Up(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",Rr)),t.write(a,u=>{u||(s+=a.byteLength,cu(e,s))}),t.writableLength>su&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${su} 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[Qt];if(typeof u=="string"){if(!lu(u))throw du(u);t.addTrailers({[Rr]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:i}}async function Dp(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Tt(s,r)}return o?!0:(Xo(n,new z(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 Fp={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Hp="wav, pcm";async function pu(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??Tp,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new z(405,`${String(t.method)} is not supported on ${Tn}`);let a;try{a=JSON.parse((await vr(t,o)).toString("utf8")||"{}")}catch(y){throw y instanceof xe?new z(413,y.message):new z(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new z(400,"request body must be a JSON object");let u=a;for(let y of Object.keys(u))if(!Fp[y])throw new z(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 z(400,"input is required and must be a non-empty string","input");if(l.length>eu)throw new z(400,`input is ${l.length} chars \u2014 over the ${eu}-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 z(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new z(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new z(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 ${Tn} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(y){throw Tt(y,r)}if(p.defect!==null)throw new z(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof c=="string"?c:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new z(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let h=u.response_format??"wav";if(h!=="wav"&&h!=="pcm")throw new z(400,`response_format ${JSON.stringify(h)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Hp} \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 z(400,"stream_format, when present, must be a string","stream_format");let _=u.speed;if(_!==void 0){if(typeof _!="number"||!Number.isFinite(_))throw new z(400,"speed, when present, must be a number","speed");if(_!==1)throw new z(400,`speed=${JSON.stringify(_)} 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 S=u.instructions;if(S!==void 0){if(typeof S!="string")throw new z(400,"instructions, when present, must be a string","instructions");if(S.trim().length>0)throw new z(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 Pp(n.turn,n.clients,d);let w=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",w,w),!await Dp(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new z(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 z(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 z(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 Tt(y,r)}let g;try{g=await n.clients.openAudioOn(f)}catch(y){throw Tt(y,r)}n.turn&&(n.turn.sessionId=g.sessionId);try{if(h==="wav"){let y=[],v=await au(n.clients,g,f,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??tu,returnBoundMs:n.turnReturnBoundMs??nu},i,P=>y.push(P),P=>{n.turn&&(n.turn.outputSeconds=ut(P))},r);if(v===null||i())return;let C=Buffer.concat(y);if(m===void 0){let P=v[Qt];if(typeof P=="string"){if(!lu(P))throw du(P);e.setHeader(Rr,P)}}cu(n.turn,C.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Mp(C.byteLength),C]))}else{let y=Up(e,n.turn,i,m===void 0),v;try{v=await au(n.clients,g,f,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??tu,returnBoundMs:n.turnReturnBoundMs??nu},i,y.sink,C=>{n.turn&&(n.turn.outputSeconds=ut(C))},r)}catch(C){let P=Tt(C,r);if(!y.started())throw P;n.turn&&(n.turn.streamError=!0),y.fail(P);return}if(v===null)return;try{await y.finish(v)}catch(C){let P=Tt(C,r);n.turn&&(n.turn.streamError=!0),y.fail(P);return}}}catch(y){throw Tt(y,r)}}catch(a){if(a instanceof xe){Xo(e,new z(413,a.message));return}if(a instanceof z){Xo(e,a);return}throw a}}x();var xr="/v1/audio/transcriptions";function fu(t){return t===xr}var mu="/v1/audio/models",jp=16*1024*1024,Bp=64*1024*1024,pe=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Qo(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 gu(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 qp(t){if(!gu(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 Gp(t,e,n){if(t){if(t.model=Te({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 Wp(t,e){t&&(t.outputUnits=e.seconds)}async function Jp(t,e,n,r,o,s,i){let a=i??(c=>console.error(c)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of u){if(l.push(c),c.type==="error"){let p=c.error??{},m=typeof p.type=="string"?p.type:"upstream_error",h=typeof p.message=="string"&&p.message.length>0&&Ke(p.message)?p.message:null;throw h===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new pe(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new pe(m==="invalid_request_error"?400:502,`transcription upstream error: ${h}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new pe(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=ut(d)),Jt(l,d)}function hu(t,e){if(t instanceof pe)return t;if(t instanceof je)throw t;return t instanceof ee?new pe(404,t.message):new pe(502,Kt("transcription",t,e))}async function Vp(t,e,n,r){let o;try{o=await t(e)}catch(s){throw hu(s,r)}return o?!0:(Qo(n,new pe(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 Kp=new Set(["file","model","language","response_format"]);async function yu(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Bp,s=n.maxAudioPartBytes??jp;try{if(t.method!=="POST")throw new pe(405,`${String(t.method)} is not supported on ${xr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new pe(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await br(t,o)}catch(f){throw f instanceof xe?new pe(413,f.message):new pe(400,String(f instanceof Error?f.message:f))}let u=new Map;for(let f of a.keys()){if(!Kp.has(f))throw new pe(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,g]of u)if(g>1)throw new pe(400,`form field "${f}" appears ${g} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,f);let l=a.get("model");if(l!==null&&typeof l!="string")throw new pe(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 pe(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,m=a.get("response_format")??"json";if(m!=="json")throw new pe(400,`response_format ${JSON.stringify(m)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let h=a.get("file");if(!(h instanceof File))throw new pe(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(h.size>s)throw new pe(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let _=new Uint8Array(await h.arrayBuffer());if(!gu(_))throw new pe(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 S=qp(_);if(S===null)throw new pe(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 Gp(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",_.length,_.length),!await Vp(n.transcriptionModels,d,e,r))return;let w=[{type:"input_audio",input_audio:{data:Buffer.from(_).toString("base64"),format:"wav"}}];try{let f=await Jp(n.clients,d,w,p,n.turn?Fe(n.turn):void 0,n.turn,r);Wp(n.turn,S),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:f}))}catch(f){throw hu(f,r)}}catch(i){if(i instanceof xe){Qo(e,new pe(413,i.message));return}if(i instanceof pe){Qo(e,i);return}throw i}}var Tr=require("@urun-sh/core");x();var es="x-urun-profile",Pn="voice";var Me=class extends Error{status=400},zp=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Yp=/\s/;function Xp(t){return zp.test(t)}function Zo(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Me(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function wu(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 Me(`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 Me(`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 Me(`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 _u(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 Me(`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 Me(`the ${es} header is empty \u2014 the only profile this lane accepts is "${Pn}" (omit the header for the ordinary lane)`);if(l!==Pn)throw new Me(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Pn}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Pn)throw new Me(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Pn}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new Me("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 Me("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:wu(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:wu(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Zo(u,"sentence_flush",!0),includeReasoning:Zo(u,"include_reasoning",!1),metadata:Zo(u,"metadata",!1)}}var Zt=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&&Xp(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 rs(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Zp(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 Ae(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function ae(t,e,n,r="invalid_request_error",o){Ae(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function os(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=tt(r),a=i??ze(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"),Ae(t,l,{error:{message:a,type:o,code:u}})}function Ye(t,e,n,r){Ae(t,e,{type:"error",error:{type:n,message:r}})}function en(t,e,n){if(e==="anthropic"){Ae(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}Ae(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var ef=64*1024*1024,Cn=class extends Error{};async function vu(t,e=ef){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Cn(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Pt(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 Su(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 Ar(t){let e=Su(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function bu(t){let e=Ar(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:tf(t)},completion_tokens_details:{reasoning_tokens:0}}}function tf(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function nf(t,e){let n=Su(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function rf(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 of(t,e){let n=rf(e);n&&(t.timing=n),t.outputSeconds=ut(e)}function Ct(t,e){nf(t,e),of(t,e)}async function Pr(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 ku(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 sf(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 Or=class extends Error{};function af(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 Or(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function uf(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:af(n.role,n.content)})}return e}function ts(t){return Gt(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 lf(t,e,n,r,o,s,i){let a=bn(s.id),u=t.stream===!0;if(s.model=Te(t),s.stream=u,await Pr(s,e,typeof t.model=="string"?t.model:void 0),u){let f;try{f=await kn({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(g){if(g instanceof ee){en(r,"openai",g);return}if(g instanceof He){ae(r,g.status,g.message);return}if(g instanceof We||g instanceof Se){r.setHeader("retry-after","2"),ae(r,503,g.message,"capacity_error");return}throw g}rs(r);for await(let g of f.events){if(g.type==="error"){s.streamError=!0;let y=g.error,v=tt(y),C=v??ze(s.id);v===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(g)}`),r.write(`event: error
35
35
  data: ${JSON.stringify({error:{message:C,type:y?.type??"upstream_error",code:y?.code??null}})}
36
36
 
37
37
  `),r.end();return}g.type==="response.completed"&&Ct(s,g.response),r.write(`event: ${String(g.type??"message")}
@@ -39,13 +39,13 @@ data: ${JSON.stringify(g)}
39
39
 
40
40
  `)}r.write(`data: [DONE]
41
41
 
42
- `),r.end();return}let l;try{l=Vt(n,t)}catch(f){if(f instanceof He){ae(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=Te(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await $o(e,t,l,!1,Fe(s))}catch(f){if(f instanceof ee){en(r,"openai",f);return}if(f instanceof He){ae(r,f.status,f.message);return}if(f instanceof We||f instanceof Se){r.setHeader("retry-after","2"),ae(r,503,f.message,"capacity_error");return}throw f}let h=[],_=null;for await(let f of o.track(m,c,s)){if(h.push(f),f.type==="error"){os(r,f,{inferenceId:s.id,operatorError:i});return}f.type==="response.completed"&&(_=f.response)}if(_==null){ae(r,502,"upstream produced no response.completed event","upstream_error");return}Ct(s,_);let x=Jt(h,_),w=It(p,Gt(_).length,x);if(w){ae(r,502,Ot(c,w),"upstream_error");return}d&&n.remember(a,l,Mo(_,x),d),Ae(r,200,{..._,id:a})}async function df(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){ae(n,400,"chat/completions requires a messages array");return}let u;try{u=_u(s,t)}catch(R){if(R instanceof Me){ae(n,R.status,R.message);return}throw R}let l=String(t.model??"urun"),d=_a(o.id),c;try{c=uf(a)}catch(R){if(R instanceof Or){ae(n,400,R.message);return}throw R}let p=Te(t);r.model(p),o.model=p,o.stream=t.stream===!0,await Pr(o,e,typeof t.model=="string"?t.model:void 0);let m=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:c,stream:!0,tools:sf(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}:{}},Fe(o))}catch(R){if(R instanceof ee){en(n,"openai",R);return}if(R instanceof We||R instanceof Se){n.setHeader("retry-after","2"),ae(n,503,R.message,"capacity_error");return}throw R}if(t.stream===!0){u?Zp(n):rs(n);let R=[],O=new gt,I="",U=u?new Zt(u,K=>{n.write(`data: ${JSON.stringify(Pt(d,l,{content:K},null))}
42
+ `),r.end();return}let l;try{l=Vt(n,t)}catch(f){if(f instanceof He){ae(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=Te(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await $o(e,t,l,!1,Fe(s))}catch(f){if(f instanceof ee){en(r,"openai",f);return}if(f instanceof He){ae(r,f.status,f.message);return}if(f instanceof We||f instanceof Se){r.setHeader("retry-after","2"),ae(r,503,f.message,"capacity_error");return}throw f}let h=[],_=null;for await(let f of o.track(m,c,s)){if(h.push(f),f.type==="error"){os(r,f,{inferenceId:s.id,operatorError:i});return}f.type==="response.completed"&&(_=f.response)}if(_==null){ae(r,502,"upstream produced no response.completed event","upstream_error");return}Ct(s,_);let S=Jt(h,_),w=It(p,Gt(_).length,S);if(w){ae(r,502,Ot(c,w),"upstream_error");return}d&&n.remember(a,l,Mo(_,S),d),Ae(r,200,{..._,id:a})}async function df(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){ae(n,400,"chat/completions requires a messages array");return}let u;try{u=_u(s,t)}catch(E){if(E instanceof Me){ae(n,E.status,E.message);return}throw E}let l=String(t.model??"urun"),d=_a(o.id),c;try{c=uf(a)}catch(E){if(E instanceof Or){ae(n,400,E.message);return}throw E}let p=Te(t);r.model(p),o.model=p,o.stream=t.stream===!0,await Pr(o,e,typeof t.model=="string"?t.model:void 0);let m=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:c,stream:!0,tools:sf(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}:{}},Fe(o))}catch(E){if(E instanceof ee){en(n,"openai",E);return}if(E instanceof We||E instanceof Se){n.setHeader("retry-after","2"),ae(n,503,E.message,"capacity_error");return}throw E}if(t.stream===!0){u?Zp(n):rs(n);let E=[],O=new gt,I="",U=u?new Zt(u,K=>{n.write(`data: ${JSON.stringify(Pt(d,l,{content:K},null))}
43
43
 
44
44
  `)}):null,W=K=>{U?.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}})}
45
45
 
46
46
  `),n.write(`data: ${JSON.stringify(Pt(d,l,{role:"assistant"},null))}
47
47
 
48
- `);for await(let oe of r.track(h,p,o)){R.push(oe);let ke=Wt(oe);if(oe.type==="response.output_text.delta"&&typeof oe.delta=="string")I+=oe.delta,U?U.push(oe.delta):n.write(`data: ${JSON.stringify(Pt(d,l,{content:oe.delta},null))}
48
+ `);for await(let oe of r.track(h,p,o)){E.push(oe);let ke=Wt(oe);if(oe.type==="response.output_text.delta"&&typeof oe.delta=="string")I+=oe.delta,U?U.push(oe.delta):n.write(`data: ${JSON.stringify(Pt(d,l,{content:oe.delta},null))}
49
49
 
50
50
  `);else if(oe.type==="response.reasoning_text.delta"&&typeof oe.delta=="string")(!u||u.includeReasoning)&&n.write(`data: ${JSON.stringify(Pt(d,l,{reasoning_content:oe.delta},null))}
51
51
 
@@ -53,46 +53,46 @@ data: ${JSON.stringify(g)}
53
53
 
54
54
  `)}else if(oe.type==="error"){o.streamError=!0;let J=oe.error??{},M=tt(J),re=M??ze(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(oe)}`),W(`data: ${JSON.stringify({error:{message:re,type:J.type??"upstream_error",code:J.code??null}})}
55
55
 
56
- `);return}}let K=ts(et(R)),te=It(m,O.size+K.length,I);if(te){o.streamError=!0,W(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Ot(p,te)}})}
56
+ `);return}}let K=ts(et(E)),te=It(m,O.size+K.length,I);if(te){o.streamError=!0,W(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Ot(p,te)}})}
57
57
 
58
58
  `);return}U?.flush(),O.size===0&&K.length>0&&n.write(`data: ${JSON.stringify(Pt(d,l,{tool_calls:K},null))}
59
59
 
60
60
  `);let ne=O.size>0||K.length>0;n.write(`data: ${JSON.stringify(Pt(d,l,{},ne?"tool_calls":"stop"))}
61
61
 
62
- `);let $e=Ar(et(R));Ct(o,et(R)),$e&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:bu(et(R))})}
62
+ `);let $e=Ar(et(E));Ct(o,et(E)),$e&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:bu(et(E))})}
63
63
 
64
64
  `),n.write(`data: [DONE]
65
65
 
66
- `),n.end();return}finally{U?.flush(),U?.dispose()}}let _="",x="",w=[],f=new gt;for await(let R of r.track(h,p,o)){w.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(_+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(x+=R.delta);let O=Wt(R);if(O&&f.add(O),R.type==="error"){os(n,R,{inferenceId:o.id,operatorError:i});return}}let g=et(w);Ct(o,g);let y=ts(g),b=y.length>0?y:ts({output:f.items()}),C=It(m,b.length,_);if(C){ae(n,502,Ot(p,C),"upstream_error");return}let P=b.map(({index:R,...O})=>O),S={role:"assistant",content:_||null},A=x||ku(g);A&&(S.reasoning_content=A),P.length>0&&(S.tool_calls=P),Ae(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:S,finish_reason:P.length>0?"tool_calls":"stop"}],usage:bu(g)})}var Cr="sense-latest";async function cf(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){ae(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:Cr,a=Te({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){ae(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){ae(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){ae(n,400,"systemone media, when present, must be an array");return}let l=await Ru(t,i,a,e,n,r,o,s);l!==null&&Ae(n,200,l.answer)}async function Ru(t,e,n,r,o,s,i,a){let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=u;let l=performance.now();s.model(n),await Pr(i,r,e),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},Fe(i))}catch(w){if(w instanceof ee)return en(o,"openai",w),null;if(w instanceof We||w instanceof Se)return o.setHeader("retry-after","2"),ae(o,503,w.message,"capacity_error"),null;throw w}u.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let w of s.track(d,n,i))if(m===null&&(m=performance.now(),u.first_event_ms=Math.round(m-c)),p.push(w),w.type==="error")return os(o,w,{inferenceId:i.id,operatorError:a}),null}catch(w){if(w instanceof ee)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),en(o,"openai",w),null;if(w instanceof We||w instanceof Se)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),o.setHeader("retry-after","2"),ae(o,503,w.message,"capacity_error"),null;throw m!==null&&(u.stream_ms=Math.round(performance.now()-m)),w}m!==null&&(u.stream_ms=Math.round(performance.now()-m));let h=et(p);if(h==null)return ae(o,502,"upstream produced no response.completed event","upstream_error"),null;Ct(i,h);let _=Jt(p,h),x;try{x=JSON.parse(_)}catch{return ae(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(x===null||typeof x!="object"||Array.isArray(x))return ae(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof x=="object"&&x!==null&&!Array.isArray(x)&&"timing"in x){let w=x.timing;if(typeof w=="object"&&w!==null&&!Array.isArray(w)&&"question_fwd_ms"in w&&"head_ms"in w){let f=g=>typeof g=="number"&&Number.isFinite(g)&&g>=0?Math.round(g):null;u.question_fwd_ms=f(w.question_fwd_ms),u.head_ms=f(w.head_ms)}}return{answer:x,completed:h}}async function pf(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){ae(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:Cr,a=Te({model:i});o.model=a,o.stream=!1;let u;try{u=Ua(t,i)}catch(p){if(p instanceof V){ae(n,400,p.message);return}throw p}let l=await Ru(u.systemone,i,a,e,n,r,o,s);if(l===null)return;let d;try{d=Ha(u.specs,l.answer)}catch(p){if(p instanceof Be){ae(n,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;Ae(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function ff(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Ln=class extends Error{};function Ir(t){return new Ln(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function mf(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 gf(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 Ln(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function hf(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Ir(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Ir(`tool_result > ${r}`);e+=String(n.text??"")}return e}function yf(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 Ir(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:hf(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Ir(a)}}return s(),r}function ns(t){return Gt(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 wf(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Ye(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){Ye(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Ye(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(S=>typeof S!="string"))){Ye(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),u=va(o.id),l=[],d;try{t.system&&l.push({role:"system",content:ff(t.system)});for(let S of i)l.push(...yf(S));d=gf(t.tool_choice)}catch(S){if(S instanceof Ln){Ye(n,400,"invalid_request_error",S.message);return}throw S}let c=Te(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Pr(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:l,stream:!0,tools:mf(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},Fe(o))}catch(S){if(S instanceof ee){en(n,"anthropic",S);return}if(S instanceof We||S instanceof Se){n.setHeader("retry-after","2"),Ye(n,503,"capacity_error",S.message);return}throw S}let h=(S,A)=>{n.destroyed||n.write(`event: ${S}
67
- data: ${JSON.stringify({type:S,...A})}
66
+ `),n.end();return}finally{U?.flush(),U?.dispose()}}let _="",S="",w=[],f=new gt;for await(let E of r.track(h,p,o)){w.push(E),E.type==="response.output_text.delta"&&typeof E.delta=="string"&&(_+=E.delta),E.type==="response.reasoning_text.delta"&&typeof E.delta=="string"&&(S+=E.delta);let O=Wt(E);if(O&&f.add(O),E.type==="error"){os(n,E,{inferenceId:o.id,operatorError:i});return}}let g=et(w);Ct(o,g);let y=ts(g),v=y.length>0?y:ts({output:f.items()}),C=It(m,v.length,_);if(C){ae(n,502,Ot(p,C),"upstream_error");return}let P=v.map(({index:E,...O})=>O),k={role:"assistant",content:_||null},A=S||ku(g);A&&(k.reasoning_content=A),P.length>0&&(k.tool_calls=P),Ae(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:k,finish_reason:P.length>0?"tool_calls":"stop"}],usage:bu(g)})}var Cr="sense-latest";async function cf(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){ae(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:Cr,a=Te({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){ae(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){ae(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){ae(n,400,"systemone media, when present, must be an array");return}let l=await Ru(t,i,a,e,n,r,o,s);l!==null&&Ae(n,200,l.answer)}async function Ru(t,e,n,r,o,s,i,a){let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=u;let l=performance.now();s.model(n),await Pr(i,r,e),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},Fe(i))}catch(w){if(w instanceof ee)return en(o,"openai",w),null;if(w instanceof We||w instanceof Se)return o.setHeader("retry-after","2"),ae(o,503,w.message,"capacity_error"),null;throw w}u.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let w of s.track(d,n,i))if(m===null&&(m=performance.now(),u.first_event_ms=Math.round(m-c)),p.push(w),w.type==="error")return os(o,w,{inferenceId:i.id,operatorError:a}),null}catch(w){if(w instanceof ee)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),en(o,"openai",w),null;if(w instanceof We||w instanceof Se)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),o.setHeader("retry-after","2"),ae(o,503,w.message,"capacity_error"),null;throw m!==null&&(u.stream_ms=Math.round(performance.now()-m)),w}m!==null&&(u.stream_ms=Math.round(performance.now()-m));let h=et(p);if(h==null)return ae(o,502,"upstream produced no response.completed event","upstream_error"),null;Ct(i,h);let _=Jt(p,h),S;try{S=JSON.parse(_)}catch{return ae(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(S===null||typeof S!="object"||Array.isArray(S))return ae(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof S=="object"&&S!==null&&!Array.isArray(S)&&"timing"in S){let w=S.timing;if(typeof w=="object"&&w!==null&&!Array.isArray(w)&&"question_fwd_ms"in w&&"head_ms"in w){let f=g=>typeof g=="number"&&Number.isFinite(g)&&g>=0?Math.round(g):null;u.question_fwd_ms=f(w.question_fwd_ms),u.head_ms=f(w.head_ms)}}return{answer:S,completed:h}}async function pf(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){ae(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:Cr,a=Te({model:i});o.model=a,o.stream=!1;let u;try{u=Ua(t,i)}catch(p){if(p instanceof V){ae(n,400,p.message);return}throw p}let l=await Ru(u.systemone,i,a,e,n,r,o,s);if(l===null)return;let d;try{d=Ha(u.specs,l.answer)}catch(p){if(p instanceof Be){ae(n,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;Ae(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function ff(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Ln=class extends Error{};function Ir(t){return new Ln(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function mf(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 gf(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 Ln(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function hf(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Ir(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Ir(`tool_result > ${r}`);e+=String(n.text??"")}return e}function yf(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 Ir(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:hf(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Ir(a)}}return s(),r}function ns(t){return Gt(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 wf(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Ye(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){Ye(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Ye(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(k=>typeof k!="string"))){Ye(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),u=va(o.id),l=[],d;try{t.system&&l.push({role:"system",content:ff(t.system)});for(let k of i)l.push(...yf(k));d=gf(t.tool_choice)}catch(k){if(k instanceof Ln){Ye(n,400,"invalid_request_error",k.message);return}throw k}let c=Te(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Pr(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:l,stream:!0,tools:mf(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},Fe(o))}catch(k){if(k instanceof ee){en(n,"anthropic",k);return}if(k instanceof We||k instanceof Se){n.setHeader("retry-after","2"),Ye(n,503,"capacity_error",k.message);return}throw k}let h=(k,A)=>{n.destroyed||n.write(`event: ${k}
67
+ data: ${JSON.stringify({type:k,...A})}
68
68
 
69
- `)};if(t.stream===!0){let S=r.track(m,c,o);rs(n),h("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let A=0,R="",O=0,I="none",U=()=>I,W=-1,K=-1,te=new gt,ne=[],$e=()=>{I!=="none"&&(I="none",h("content_block_stop",{index:W}))},oe=(ie,de)=>{$e(),I=ie,W=O++,h("content_block_start",{index:W,content_block:de})};for await(let ie of S){if(n.destroyed)break;ne.push(ie);let de=Wt(ie);if(ie.type==="response.reasoning_text.delta"&&typeof ie.delta=="string")U()!=="thinking"&&oe("thinking",{type:"thinking",thinking:""}),h("content_block_delta",{index:W,delta:{type:"thinking_delta",thinking:ie.delta}});else if(ie.type==="response.output_text.delta"&&typeof ie.delta=="string")U()!=="text"&&oe("text",{type:"text",text:""}),A+=1,R+=ie.delta,h("content_block_delta",{index:W,delta:{type:"text_delta",text:ie.delta}});else if(de){let{call:Ce}=te.add(de);(U()!=="tool"||de.tool_index!==K)&&(K=de.tool_index,oe("tool",{type:"tool_use",id:Ce.id??`call_${de.tool_index}`,name:Ce.name??"",input:{}})),de.delta&&h("content_block_delta",{index:W,delta:{type:"input_json_delta",partial_json:de.delta}})}else if(ie.type==="error"){o.streamError=!0;let Ce=ie.error,ot=tt(Ce);ot===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(ie)}`),h("error",{error:{type:"api_error",message:ot??ze(o.id)}}),n.end();return}}if(n.destroyed)return;let ke=et(ne),J=Gt(ke),M=It(p,te.size+J.length,R);if(M){o.streamError=!0,h("error",{error:{type:"api_error",message:Ot(c,M)}}),n.end();return}$e();let re=[];if(te.size===0)try{re=ns(ke)}catch(ie){o.streamError=!0;let de=Ue(ie,{inferenceId:o.id});de.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(ie instanceof Error?ie.message:ie)}`),h("error",{error:{type:"api_error",message:de.message}}),n.end();return}O===0&&re.length===0&&(oe("text",{type:"text",text:""}),$e()),re.forEach(ie=>{let de=O++;h("content_block_start",{index:de,content_block:{...ie,input:{}}}),h("content_block_delta",{index:de,delta:{type:"input_json_delta",partial_json:JSON.stringify(ie.input??{})}}),h("content_block_stop",{index:de})});let rt=te.size>0||re.length>0,se=Ar(ke);Ct(o,ke),h("message_delta",{delta:{stop_reason:rt?"tool_use":"end_turn"},usage:se?{input_tokens:se.input_tokens,output_tokens:se.output_tokens}:{output_tokens:A}}),h("message_stop",{}),n.end();return}let _="",x="",w=[],f=new gt;for await(let S of r.track(m,c,o)){w.push(S),S.type==="response.output_text.delta"&&typeof S.delta=="string"&&(_+=S.delta),S.type==="response.reasoning_text.delta"&&typeof S.delta=="string"&&(x+=S.delta);let A=Wt(S);if(A&&f.add(A),S.type==="error"){let R=S.error,O=R?.type==="invalid_request_error",I=tt(R);I===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(S)}`),Ye(n,O?400:502,O?"invalid_request_error":"api_error",I??ze(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let g=et(w);Ct(o,g);let y;try{y=ns(g),y.length===0&&f.size>0&&(y=ns({output:f.items()}))}catch(S){let A=Ue(S,{inferenceId:o.id});A.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(S instanceof Error?S.message:S)}`),Ye(n,502,"api_error",A.message);return}let b=It(p,y.length,_);if(b){Ye(n,502,"api_error",Ot(c,b));return}let C=[],P=x||ku(g);P&&C.push({type:"thinking",thinking:P}),(_||y.length===0)&&C.push({type:"text",text:_}),C.push(...y),Ae(n,200,{id:u,type:"message",role:"assistant",content:C,model:a,stop_reason:y.length>0?"tool_use":"end_turn",usage:Ar(g)??{input_tokens:0,output_tokens:0}})}function _f(t){Ze(process.stdout,t)}function Eu(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??_f,a=t.operatorLog??(d=>console.error(d)),u=t.observe,l=new xt;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),h=(g,y,b,C,P)=>m?Ye(c,g,C,y):ae(c,g,y,b,P),_=Lo(p.pathname),x=p.pathname.startsWith("/partners/"),w=_||x?{id:vn(),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;w&&(c.setHeader(ya,w.id),c.once("close",()=>{let g=ba({turn:w,method:d.method??"",path:p.pathname,res:c});i(Sa(g)),u?.(g),Ai({record:g,ledger:t.ledger??null,req:d})}));let f=()=>wa(p.pathname,w);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){Ae(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){Ae(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){h(401,"invalid local proxy api key","authentication_error","authentication_error");return}let g=p.pathname===zn?"canonical":p.pathname===yn?"huggingface":null;if(g){if(d.method!=="POST"){h(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let P=t.usage;if(!P){h(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 S=P.authorize(d),A;try{A=await vu(d,Ci)}catch(I){if(I instanceof Cn){h(413,I.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let R=I=>P.lookup(S,I),O;try{if(g==="canonical"){let I=Li(A),U=await R(I);Yn(U,I),O={requests:U}}else O=await Ni(A,R)}catch(I){if(I instanceof mt){h(I.status,I.message,"invalid_request_error","invalid_request_error");return}throw I}Ae(c,200,O);return}if(d.method==="GET"&&p.pathname===vt){let P=await s(d);if(w&&(w.org=P.tenant??null),!P.openRouterModels){h(501,`GET ${vt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}Ae(c,200,await P.openRouterModels());return}if(p.pathname.startsWith("/partners/")){h(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${yn} and GET ${vt}`,"invalid_request_error","not_found_error");return}let y=await s(d);if(w&&(w.org=y.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:vt}),c.end();return}Ae(c,200,await y.listModels());return}if(d.method==="GET"&&p.pathname===qa){if(!y.listImageModels){h(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}Ae(c,200,await y.listImageModels());return}if(Ba(p.pathname)){if(!y.supportsImages){h(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let P={clients:y,imageModels:y.supportsImages,stats:l,turn:f(),operatorLog:a};p.pathname===Sr?await Za(d,c,P):await Qa(d,c,P);return}if(d.method==="GET"&&p.pathname===mu){if(!y.listSpeechToTextModels){h(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}Ae(c,200,await y.listSpeechToTextModels());return}if(fu(p.pathname)){if(!y.supportsTranscription){h(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${xr}`,"not_implemented","not_implemented_error");return}let P={clients:y,transcriptionModels:y.supportsTranscription,stats:l,turn:f(),operatorLog:a};await yu(d,c,P);return}if(uu(p.pathname)){if(!y.supportsSpeech){h(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Tn}`,"not_implemented","not_implemented_error");return}let P={clients:y,speechModels:y.supportsSpeech,stats:l,turn:f(),operatorLog:a};await pu(d,c,P);return}if(d.method!=="POST"){h(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let b;try{b=await vu(d)}catch(P){if(P instanceof Cn){h(413,P.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let C=Buffer.byteLength(JSON.stringify(b));if(p.pathname==="/v1/responses"){l.request("responses",C,C),await lf(b,y,Sn(y),c,l,f(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",C,C),await df(b,y,c,l,f(),d.headers[es],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",C,C),await cf(b,y,c,l,f(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",C,C),await pf(b,y,c,l,f(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",C,C),await wf(b,y,c,l,f(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",C,C),Ye(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}h(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(g=>{let y=String(g instanceof Error?g.message:g);if(!c.headersSent){let P=o?.(g)??null;if(P){P.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${P.operatorDetail}`),h(P.status,y,P.openaiType,P.anthropicType,P.code);return}if(g instanceof Tr.SessionAllocationError){let A=dr(g.code);if(A){let R=g.retryAfterSeconds??(A.status===429?30:void 0);R!==void 0&&c.setHeader("Retry-After",String(R)),h(A.status,En(A,g.code??void 0),A.openaiType,A.anthropicType,A.code);return}}if(g instanceof Tr.SessionFailedError){let A=cr(g);if(A){let R=A.status===429?30:void 0;R!==void 0&&c.setHeader("Retry-After",String(R)),h(A.status,En(A,g.status.sessionId?`session ${g.status.sessionId}`:void 0),A.openaiType,A.anthropicType,A.code);return}}if(g instanceof me){h(502,y,"upstream_error","api_error");return}if(g instanceof Je){g.retryable&&c.setHeader("Retry-After","1");let A=Ue(g,{inferenceId:w?.id??null});A.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:Ve(g)}`),h(502,A.message,"upstream_error","api_error",g.code);return}if(g instanceof ht){c.setHeader("Retry-After",String(g.retryAfterSeconds)),h(g.status,y,g.status===429?"capacity_error":"upstream_error",g.status===429?"rate_limit_error":"overloaded_error",g.code);return}let S=Ue(g,{inferenceId:w?.id??null});S.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:Ve(g)}`),h(500,S.message,"proxy_error","api_error","proxy_error");return}w&&(w.streamError=!0);let b=g instanceof Je?g.code:null,C=Ue(g,{inferenceId:w?.id??null});C.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:Ve(g)}`),c.destroyed||(m?c.write(`event: error
69
+ `)};if(t.stream===!0){let k=r.track(m,c,o);rs(n),h("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let A=0,E="",O=0,I="none",U=()=>I,W=-1,K=-1,te=new gt,ne=[],$e=()=>{I!=="none"&&(I="none",h("content_block_stop",{index:W}))},oe=(ie,de)=>{$e(),I=ie,W=O++,h("content_block_start",{index:W,content_block:de})};for await(let ie of k){if(n.destroyed)break;ne.push(ie);let de=Wt(ie);if(ie.type==="response.reasoning_text.delta"&&typeof ie.delta=="string")U()!=="thinking"&&oe("thinking",{type:"thinking",thinking:""}),h("content_block_delta",{index:W,delta:{type:"thinking_delta",thinking:ie.delta}});else if(ie.type==="response.output_text.delta"&&typeof ie.delta=="string")U()!=="text"&&oe("text",{type:"text",text:""}),A+=1,E+=ie.delta,h("content_block_delta",{index:W,delta:{type:"text_delta",text:ie.delta}});else if(de){let{call:Ce}=te.add(de);(U()!=="tool"||de.tool_index!==K)&&(K=de.tool_index,oe("tool",{type:"tool_use",id:Ce.id??`call_${de.tool_index}`,name:Ce.name??"",input:{}})),de.delta&&h("content_block_delta",{index:W,delta:{type:"input_json_delta",partial_json:de.delta}})}else if(ie.type==="error"){o.streamError=!0;let Ce=ie.error,ot=tt(Ce);ot===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(ie)}`),h("error",{error:{type:"api_error",message:ot??ze(o.id)}}),n.end();return}}if(n.destroyed)return;let ke=et(ne),J=Gt(ke),M=It(p,te.size+J.length,E);if(M){o.streamError=!0,h("error",{error:{type:"api_error",message:Ot(c,M)}}),n.end();return}$e();let re=[];if(te.size===0)try{re=ns(ke)}catch(ie){o.streamError=!0;let de=Ue(ie,{inferenceId:o.id});de.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(ie instanceof Error?ie.message:ie)}`),h("error",{error:{type:"api_error",message:de.message}}),n.end();return}O===0&&re.length===0&&(oe("text",{type:"text",text:""}),$e()),re.forEach(ie=>{let de=O++;h("content_block_start",{index:de,content_block:{...ie,input:{}}}),h("content_block_delta",{index:de,delta:{type:"input_json_delta",partial_json:JSON.stringify(ie.input??{})}}),h("content_block_stop",{index:de})});let rt=te.size>0||re.length>0,se=Ar(ke);Ct(o,ke),h("message_delta",{delta:{stop_reason:rt?"tool_use":"end_turn"},usage:se?{input_tokens:se.input_tokens,output_tokens:se.output_tokens}:{output_tokens:A}}),h("message_stop",{}),n.end();return}let _="",S="",w=[],f=new gt;for await(let k of r.track(m,c,o)){w.push(k),k.type==="response.output_text.delta"&&typeof k.delta=="string"&&(_+=k.delta),k.type==="response.reasoning_text.delta"&&typeof k.delta=="string"&&(S+=k.delta);let A=Wt(k);if(A&&f.add(A),k.type==="error"){let E=k.error,O=E?.type==="invalid_request_error",I=tt(E);I===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(k)}`),Ye(n,O?400:502,O?"invalid_request_error":"api_error",I??ze(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let g=et(w);Ct(o,g);let y;try{y=ns(g),y.length===0&&f.size>0&&(y=ns({output:f.items()}))}catch(k){let A=Ue(k,{inferenceId:o.id});A.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(k instanceof Error?k.message:k)}`),Ye(n,502,"api_error",A.message);return}let v=It(p,y.length,_);if(v){Ye(n,502,"api_error",Ot(c,v));return}let C=[],P=S||ku(g);P&&C.push({type:"thinking",thinking:P}),(_||y.length===0)&&C.push({type:"text",text:_}),C.push(...y),Ae(n,200,{id:u,type:"message",role:"assistant",content:C,model:a,stop_reason:y.length>0?"tool_use":"end_turn",usage:Ar(g)??{input_tokens:0,output_tokens:0}})}function _f(t){Ze(process.stdout,t)}function Eu(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??_f,a=t.operatorLog??(d=>console.error(d)),u=t.observe,l=new xt;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),h=(g,y,v,C,P)=>m?Ye(c,g,C,y):ae(c,g,y,v,P),_=Lo(p.pathname),S=p.pathname.startsWith("/partners/"),w=_||S?{id:vn(),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;w&&(c.setHeader(ya,w.id),c.once("close",()=>{let g=ba({turn:w,method:d.method??"",path:p.pathname,res:c});i(Sa(g)),u?.(g),Ai({record:g,ledger:t.ledger??null,req:d})}));let f=()=>wa(p.pathname,w);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){Ae(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){Ae(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){h(401,"invalid local proxy api key","authentication_error","authentication_error");return}let g=p.pathname===zn?"canonical":p.pathname===yn?"huggingface":null;if(g){if(d.method!=="POST"){h(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let P=t.usage;if(!P){h(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 k=P.authorize(d),A;try{A=await vu(d,Ci)}catch(I){if(I instanceof Cn){h(413,I.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let E=I=>P.lookup(k,I),O;try{if(g==="canonical"){let I=Li(A),U=await E(I);Yn(U,I),O={requests:U}}else O=await Ni(A,E)}catch(I){if(I instanceof mt){h(I.status,I.message,"invalid_request_error","invalid_request_error");return}throw I}Ae(c,200,O);return}if(d.method==="GET"&&p.pathname===vt){let P=await s(d);if(w&&(w.org=P.tenant??null),!P.openRouterModels){h(501,`GET ${vt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}Ae(c,200,await P.openRouterModels());return}if(p.pathname.startsWith("/partners/")){h(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${yn} and GET ${vt}`,"invalid_request_error","not_found_error");return}let y=await s(d);if(w&&(w.org=y.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:vt}),c.end();return}Ae(c,200,await y.listModels());return}if(d.method==="GET"&&p.pathname===qa){if(!y.listImageModels){h(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}Ae(c,200,await y.listImageModels());return}if(Ba(p.pathname)){if(!y.supportsImages){h(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let P={clients:y,imageModels:y.supportsImages,stats:l,turn:f(),operatorLog:a};p.pathname===Sr?await Za(d,c,P):await Qa(d,c,P);return}if(d.method==="GET"&&p.pathname===mu){if(!y.listSpeechToTextModels){h(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}Ae(c,200,await y.listSpeechToTextModels());return}if(fu(p.pathname)){if(!y.supportsTranscription){h(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${xr}`,"not_implemented","not_implemented_error");return}let P={clients:y,transcriptionModels:y.supportsTranscription,stats:l,turn:f(),operatorLog:a};await yu(d,c,P);return}if(uu(p.pathname)){if(!y.supportsSpeech){h(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Tn}`,"not_implemented","not_implemented_error");return}let P={clients:y,speechModels:y.supportsSpeech,stats:l,turn:f(),operatorLog:a};await pu(d,c,P);return}if(d.method!=="POST"){h(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let v;try{v=await vu(d)}catch(P){if(P instanceof Cn){h(413,P.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let C=Buffer.byteLength(JSON.stringify(v));if(p.pathname==="/v1/responses"){l.request("responses",C,C),await lf(v,y,Sn(y),c,l,f(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",C,C),await df(v,y,c,l,f(),d.headers[es],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",C,C),await cf(v,y,c,l,f(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",C,C),await pf(v,y,c,l,f(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",C,C),await wf(v,y,c,l,f(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",C,C),Ye(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}h(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(g=>{let y=String(g instanceof Error?g.message:g);if(!c.headersSent){let P=o?.(g)??null;if(P){P.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${P.operatorDetail}`),h(P.status,y,P.openaiType,P.anthropicType,P.code);return}if(g instanceof Tr.SessionAllocationError){let A=dr(g.code);if(A){let E=g.retryAfterSeconds??(A.status===429?30:void 0);E!==void 0&&c.setHeader("Retry-After",String(E)),h(A.status,En(A,g.code??void 0),A.openaiType,A.anthropicType,A.code);return}}if(g instanceof Tr.SessionFailedError){let A=cr(g);if(A){let E=A.status===429?30:void 0;E!==void 0&&c.setHeader("Retry-After",String(E)),h(A.status,En(A,g.status.sessionId?`session ${g.status.sessionId}`:void 0),A.openaiType,A.anthropicType,A.code);return}}if(g instanceof me){h(502,y,"upstream_error","api_error");return}if(g instanceof Je){g.retryable&&c.setHeader("Retry-After","1");let A=Ue(g,{inferenceId:w?.id??null});A.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:Ve(g)}`),h(502,A.message,"upstream_error","api_error",g.code);return}if(g instanceof ht){c.setHeader("Retry-After",String(g.retryAfterSeconds)),h(g.status,y,g.status===429?"capacity_error":"upstream_error",g.status===429?"rate_limit_error":"overloaded_error",g.code);return}let k=Ue(g,{inferenceId:w?.id??null});k.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:Ve(g)}`),h(500,k.message,"proxy_error","api_error","proxy_error");return}w&&(w.streamError=!0);let v=g instanceof Je?g.code:null,C=Ue(g,{inferenceId:w?.id??null});C.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${g instanceof Error?`${g.name}: ${g.message}`:Ve(g)}`),c.destroyed||(m?c.write(`event: error
70
70
  data: ${JSON.stringify({type:"error",error:{type:"api_error",message:C.message}})}
71
71
 
72
- `):c.write(`data: ${JSON.stringify({error:{message:C.message,type:"upstream_error",code:b}})}
72
+ `):c.write(`data: ${JSON.stringify({error:{message:C.message,type:"upstream_error",code:v}})}
73
73
 
74
- `)),c.end()})}}E();var lt=(t,e)=>Object.assign(new Error(e),{status:t}),Sf='"transcription" (a transcription session), or no intent at all (the realtime voice session)',is=(t,e,n)=>new Q(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),ss=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof ee?lt(404,n.message):n}};async function xu(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw lt(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Sf}`);if(o==="transcription")throw lt(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 lt(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 lt(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(m){throw m instanceof ee?lt(404,m.message):m}if(!p)throw lt(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(m){throw m instanceof ee?lt(404,m.message):m}if(p!=="stt")throw lt(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 ss(t,n.stt),i=await ss(t,e),a=await ss(t,n.tts),u=await t.openAudioOn(s,r),l=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,kf({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(m){throw m instanceof Q?is("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function as(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Lr=class extends Error{};async function*kf(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:u}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,h=null,_=null,x=[],w=null,f=new Promise((O,I)=>{n&&n.addEventListener("abort",()=>I(new Lr),{once:!0})}),g=()=>m||n?.aborted===!0,y=async O=>{if(g())return;let I;try{I=await o.createResponseOn(i,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:O}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(W){throw W instanceof Q?is("tts",u.tts,W):W}let U=I[Symbol.asyncIterator]();_=U;try{for(;;){let W=U.next(),K;try{K=await Promise.race([W,f])}catch(ne){if(W.catch(()=>{}),ne instanceof Lr)return;throw ne}if(K.done)return;let te=K.value;if(te.type==="error"){let ne=te.error&&typeof te.error.message=="string"?te.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${ne}`)}if(te.type==="response.completed")return}}finally{_===U&&(_=null)}},b=async()=>{for(;x.length>0&&!g();){let O=x.shift();await y(O)}},C=O=>{if(O===""||g()||(x.push(O),w!==null))return;let I=b();w=I,I.then(()=>{w===I&&(w=null)},U=>{w===I&&(w=null),h??=U})},P=()=>{m=!0,x.length=0;let O=_;if(_=null,O){let I=O.return?.();I&&I.catch(()=>{})}},S=async()=>{for(;x.length>0||w!==null;){let O=w;if(O===null){await y(x.shift());continue}await O}},A=p?new Zt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},O=>C(O)):null,R=null;try{let O;try{O=await o.createResponseOn(s,d)}catch(I){throw I instanceof Q?is("chat",a,I):I}for await(let I of O){if(g())return;let U=I;if(U.type==="error"){yield I;return}if(U.type==="response.output_text.delta"&&typeof U.delta=="string"){yield I,A?.push(U.delta);continue}if(U.type==="response.function_call_arguments.delta"){A?.flush(),yield I;continue}if(U.type==="response.completed"){R=I.response;continue}}A?.flush(),A?.dispose(),p&&await S(),R!==null&&(yield{type:"response.completed",response:R})}finally{A?.dispose(),P();try{if(h instanceof Q)throw h}finally{r?.()}}}var qe=(t,e)=>Object.assign(new Error(e),{status:t});function Ou(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Iu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Rf='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Tu(t,e,n,r){if(!t.supportsAudio)throw qe(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 ee?qe(404,d.message):d}if(!o){let d=null;if(t.realtimeCompanionsFor)try{d=await t.realtimeCompanionsFor(e)}catch(c){throw c instanceof ee?qe(404,c.message):c}if(d!==null)return await xu(t,e,d,n,r);throw qe(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 qe(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 ee?qe(404,d.message):d}if(s&&!t.openTurnsOn)throw qe(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 ee?qe(404,c.message):c}if(d!=="stt")throw qe(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 qe(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Rf}`);if(r==="transcription"&&!s)throw qe(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?qe(503,d.message):d}let a=`conn_${(0,Au.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}E();var Wu=require("@urun-sh/core/internal"),Ju=Re(require("ws"),1);E();E();E();async function Pu(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)})}E();E();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 Mr(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}E();E();function Lu(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 Ef="llm-resp";async function*Nr(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 Lu(s);return}}}async function*us(t,e){let n=`${Ef}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Nr(e,t.stream(n).messages())}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var Ur=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(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=Mr(e,n,this.consumerId);return this.write(r),us(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=Cu(e,n,r,this.consumerId);return this.write(o),us(this.session,r)})}async writeGated(e,n){try{await Pu(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 Mu=0;function Af(){return Mu+=1,`req_${Date.now().toString(36)}_${Mu.toString(36)}`}var Lt=class{transport;constructor(e,n){this.transport=new Ur(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Af(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};E();var tn=Re(require("yjs"),1),$u=require("@urun-sh/core/internal"),Of=3e4;function If(t){return(e,n,r)=>{let o=t(e);tn.applyUpdate(n,tn.encodeStateAsUpdate(o));let s=a=>tn.applyUpdate(o,a),i=a=>tn.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)}}}}function ls(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?If(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=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=r.get(d);return c||(c=new $u.SessionDocumentImpl(d,e,n),r.set(d,c)),c},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=i.get(d);if(!c){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);c=t.streamEndpoint(d),i.set(d,c)}return c},u=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);async function*p(){let m=a(d);try{yield*m.messages()}finally{i.delete(d),await m.close()}}return{messages:()=>p(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:u,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let p=d?.timeout??t.whenLiveTimeoutMs??Of;await new Promise((m,h)=>{let _=setTimeout(()=>{x(),h(new Error(`lane ${e} llm doc never synced within ${p}ms`))},p),x=c.onSynced(()=>{clearTimeout(_),d?.signal?.removeEventListener("abort",w),m()}),w=()=>{clearTimeout(_),x(),h(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",w,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,c]of i)i.delete(d),c.close()}}}E();var Mt=Re(require("ws"),1),$t=require("@urun-sh/core"),Nu="/stream/";function Uu(t){if(!t.startsWith(Nu))return null;let e=t.slice(Nu.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function Hr(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Dr(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>$t.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Fr=class{reassembler=new $t.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===$t.STREAM_END&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},cs=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;(a.list.length>=Du||a.bytes+o.byteLength>Fu)&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Du} frames / ${Fu} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,u)=>a+u.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},Du=256,Fu=8*1024*1024,nt=new cs;function Hu(t,e){let n=new Fr,r={send(o){nt.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Dr(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),nt.detach(t,e,r)}};return nt.attach(t,e,r),r}function Tf(t){return{deliver(e){try{t.send(e,{binary:!0})}catch(n){console.warn(`[lane-stream] socket send failed: ${String(n)}`)}},close(e,n){try{t.close(e,n)}catch{}}}}function ju(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new Mt.default(r,Hr(e)),s=new Fr;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Dr(a)}catch(u){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(u)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Dr(i),o.readyState!==Mt.default.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function ds(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
74
+ `)),c.end()})}}x();var lt=(t,e)=>Object.assign(new Error(e),{status:t}),Sf='"transcription" (a transcription session), or no intent at all (the realtime voice session)',is=(t,e,n)=>new Q(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),ss=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof ee?lt(404,n.message):n}};async function xu(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw lt(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Sf}`);if(o==="transcription")throw lt(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 lt(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 lt(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(m){throw m instanceof ee?lt(404,m.message):m}if(!p)throw lt(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(m){throw m instanceof ee?lt(404,m.message):m}if(p!=="stt")throw lt(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 ss(t,n.stt),i=await ss(t,e),a=await ss(t,n.tts),u=await t.openAudioOn(s,r),l=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,kf({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(m){throw m instanceof Q?is("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function as(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Lr=class extends Error{};async function*kf(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:u}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,h=null,_=null,S=[],w=null,f=new Promise((O,I)=>{n&&n.addEventListener("abort",()=>I(new Lr),{once:!0})}),g=()=>m||n?.aborted===!0,y=async O=>{if(g())return;let I;try{I=await o.createResponseOn(i,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:O}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(W){throw W instanceof Q?is("tts",u.tts,W):W}let U=I[Symbol.asyncIterator]();_=U;try{for(;;){let W=U.next(),K;try{K=await Promise.race([W,f])}catch(ne){if(W.catch(()=>{}),ne instanceof Lr)return;throw ne}if(K.done)return;let te=K.value;if(te.type==="error"){let ne=te.error&&typeof te.error.message=="string"?te.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${ne}`)}if(te.type==="response.completed")return}}finally{_===U&&(_=null)}},v=async()=>{for(;S.length>0&&!g();){let O=S.shift();await y(O)}},C=O=>{if(O===""||g()||(S.push(O),w!==null))return;let I=v();w=I,I.then(()=>{w===I&&(w=null)},U=>{w===I&&(w=null),h??=U})},P=()=>{m=!0,S.length=0;let O=_;if(_=null,O){let I=O.return?.();I&&I.catch(()=>{})}},k=async()=>{for(;S.length>0||w!==null;){let O=w;if(O===null){await y(S.shift());continue}await O}},A=p?new Zt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},O=>C(O)):null,E=null;try{let O;try{O=await o.createResponseOn(s,d)}catch(I){throw I instanceof Q?is("chat",a,I):I}for await(let I of O){if(g())return;let U=I;if(U.type==="error"){yield I;return}if(U.type==="response.output_text.delta"&&typeof U.delta=="string"){yield I,A?.push(U.delta);continue}if(U.type==="response.function_call_arguments.delta"){A?.flush(),yield I;continue}if(U.type==="response.completed"){E=I.response;continue}}A?.flush(),A?.dispose(),p&&await k(),E!==null&&(yield{type:"response.completed",response:E})}finally{A?.dispose(),P();try{if(h instanceof Q)throw h}finally{r?.()}}}var qe=(t,e)=>Object.assign(new Error(e),{status:t});function Ou(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Iu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Rf='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Tu(t,e,n,r){if(!t.supportsAudio)throw qe(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 ee?qe(404,d.message):d}if(!o){let d=null;if(t.realtimeCompanionsFor)try{d=await t.realtimeCompanionsFor(e)}catch(c){throw c instanceof ee?qe(404,c.message):c}if(d!==null)return await xu(t,e,d,n,r);throw qe(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 qe(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 ee?qe(404,d.message):d}if(s&&!t.openTurnsOn)throw qe(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 ee?qe(404,c.message):c}if(d!=="stt")throw qe(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 qe(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Rf}`);if(r==="transcription"&&!s)throw qe(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?qe(503,d.message):d}let a=`conn_${(0,Au.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 Wu=require("@urun-sh/core/internal"),Ju=Re(require("ws"),1);x();x();x();async function Pu(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 Mr(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 Lu(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 Ef="llm-resp";async function*Nr(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 Lu(s);return}}}async function*us(t,e){let n=`${Ef}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Nr(e,t.stream(n).messages())}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var Ur=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(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=Mr(e,n,this.consumerId);return this.write(r),us(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=Cu(e,n,r,this.consumerId);return this.write(o),us(this.session,r)})}async writeGated(e,n){try{await Pu(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 Mu=0;function Af(){return Mu+=1,`req_${Date.now().toString(36)}_${Mu.toString(36)}`}var Lt=class{transport;constructor(e,n){this.transport=new Ur(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Af(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};x();var tn=Re(require("yjs"),1),$u=require("@urun-sh/core/internal"),Of=3e4;function If(t){return(e,n,r)=>{let o=t(e);tn.applyUpdate(n,tn.encodeStateAsUpdate(o));let s=a=>tn.applyUpdate(o,a),i=a=>tn.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)}}}}function ls(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?If(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=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=r.get(d);return c||(c=new $u.SessionDocumentImpl(d,e,n),r.set(d,c)),c},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=i.get(d);if(!c){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);c=t.streamEndpoint(d),i.set(d,c)}return c},u=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);async function*p(){let m=a(d);try{yield*m.messages()}finally{i.delete(d),await m.close()}}return{messages:()=>p(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:u,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let p=d?.timeout??t.whenLiveTimeoutMs??Of;await new Promise((m,h)=>{let _=setTimeout(()=>{S(),h(new Error(`lane ${e} llm doc never synced within ${p}ms`))},p),S=c.onSynced(()=>{clearTimeout(_),d?.signal?.removeEventListener("abort",w),m()}),w=()=>{clearTimeout(_),S(),h(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",w,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,c]of i)i.delete(d),c.close()}}}x();var Mt=Re(require("ws"),1),$t=require("@urun-sh/core"),Nu="/stream/";function Uu(t){if(!t.startsWith(Nu))return null;let e=t.slice(Nu.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function Hr(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Dr(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>$t.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Fr=class{reassembler=new $t.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===$t.STREAM_END&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},cs=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;(a.list.length>=Du||a.bytes+o.byteLength>Fu)&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Du} frames / ${Fu} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,u)=>a+u.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},Du=256,Fu=8*1024*1024,nt=new cs;function Hu(t,e){let n=new Fr,r={send(o){nt.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Dr(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),nt.detach(t,e,r)}};return nt.attach(t,e,r),r}function Tf(t){return{deliver(e){try{t.send(e,{binary:!0})}catch(n){console.warn(`[lane-stream] socket send failed: ${String(n)}`)}},close(e,n){try{t.close(e,n)}catch{}}}}function ju(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new Mt.default(r,Hr(e)),s=new Fr;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Dr(a)}catch(u){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(u)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Dr(i),o.readyState!==Mt.default.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function ds(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
75
75
  `;t.end(`HTTP/1.1 ${e} ${r}\r
76
76
  Connection: close\r
77
77
  Content-Type: text/plain; charset=utf-8\r
78
78
  Content-Length: ${Buffer.byteLength(o)}\r
79
79
  \r
80
- ${o}`)}function Bu(t,e){let n=new Mt.WebSocketServer({noServer:!0,handleProtocols:(u,l)=>{let d=Uu(new URL(l.url??"/","http://localhost").pathname);if(!d)return!1;let c=Hr(d.name);return u.has(c)?c:!1}}),r=new Map,o=new Set,s=!1,i=(u,l,d,c)=>{let p={client:d,upstream:c,laneId:u,name:l};o.add(p);let m=h=>{if(o.delete(p)){console.warn(`[lane-stream] ${u}/${l}: host-affinity pump torn down (${h})`);for(let _ of[d,c])try{(_.readyState===Mt.default.OPEN||_.readyState===Mt.default.CONNECTING)&&_.close(1001,"lane stream pump closed")}catch{}}};d.on("message",h=>{try{c.send(h,{binary:!0})}catch(_){m(`upstream send failed: ${String(_)}`)}}),c.on("message",h=>{try{d.send(h,{binary:!0})}catch(_){m(`client send failed: ${String(_)}`)}}),d.on("close",()=>m("client socket closed")),d.on("error",()=>m("client socket error")),c.on("close",()=>m("host socket closed")),c.on("error",()=>m("host socket error"))},a=(u,l,d)=>{let c;try{c=new URL(u.url??"/","http://localhost")}catch{ds(l,400,"malformed upgrade URL");return}l.on("error",()=>l.destroy());let p=Uu(c.pathname);p&&(s||l.destroyed||(async()=>{let m=c.searchParams.get("token")??"",h=null;try{h=m===""?null:await e.verifyToken(m,p.laneId,p.name)}catch{h=null}if(h===null){ds(l,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let _=await e.hostOf(p.laneId).catch(()=>null);if(_&&_!==e.selfAddress)try{let x=await e.podToPodDial(p.laneId,p.name,_);n.handleUpgrade(u,l,d,w=>{i(p.laneId,p.name,w,x)});return}catch(x){console.warn(`[lane-stream] ${p.laneId}/${p.name}: host dial to ${_} failed (${String(x)}) \u2014 falling back to the local relay`)}}n.handleUpgrade(u,l,d,_=>{let x=Tf(_);r.set(_,x),nt.attach(p.laneId,p.name,x),_.on("message",f=>{let g=new Uint8Array(f);try{Dr(g)}catch(y){console.warn(`[lane-stream] ${p.laneId}/${p.name}: dropped malformed envelope: ${String(y)}`);return}nt.deliver(p.laneId,p.name,x,g),g[1]===$t.ENVELOPE_KIND.END&&nt.detach(p.laneId,p.name,x)});let w=()=>{r.delete(_),nt.detach(p.laneId,p.name,x)};_.on("close",w),_.on("error",w)})})().catch(()=>{l.destroyed||ds(l,500,"lane stream upgrade failed")}))};return t.on("upgrade",a),{async close(){s=!0,t.off("upgrade",a),nt.clear();for(let u of r.values())u.close(1001,"lane stream host shutting down");r.clear();for(let u of o)for(let l of[u.client,u.upstream])try{l.close(1001,"lane stream host shutting down")}catch{}o.clear()}}}E();var wt=require("crypto"),Pf=["sfu","urun-doc"],Gu="runtime:lease",Cf="lane:join",Lf="urun-runtime-key-v1";function ps(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,wt.createHmac)("sha256",t).update(`${Lf}|${e}`).digest("base64url")}var Mf=120,Bw=1440*60;function qu(t){return Buffer.from(t).toString("base64url")}function $f(t,e,n){let r=qu(JSON.stringify(t)),o=qu(JSON.stringify(e)),s=(0,wt.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function Mn(t,e,n=Mf,r=Cf,o){let s=o?ps(e,o):e;return Nf(t,s,n,r,o)}function Nf(t,e,n,r,o){let s=Math.floor(Date.now()/1e3);return $f({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,wt.randomUUID)()},e)}function fs(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,m=[];if(p!==void 0?(m.push(ps(n,p)),o&&m.push(ps(o,p))):(m.push(n),o&&m.push(o)),!m.some(f=>{let g=(0,wt.createHmac)("sha256",f).update(`${i}.${a}`).digest();return c.length===g.length&&(0,wt.timingSafeEqual)(c,g)}))return null;let h=d.exp;if(typeof h!="number"||h<=r)return null;let _=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(_!==void 0&&Pf.some(f=>f===_||Array.isArray(_)&&_.includes(f))))return null;let w=d.session_id??d.sub;return typeof w!="string"||w!==e?null:{sessionId:w,aud:_,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:h}}E();var Uf=3,Df="llm",Ff=new Set(["paused","error"]);function jr(t,e,n){let r=t.doc(Df),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<Uf||d(new Q(`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&&Ff.has(c.name)&&d(new Q(`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*ms(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 Hf(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new je(`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 Vu(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=(p,m,h,_,x)=>{let w=h?b=>Hu(p,b):b=>ju(p,b,{hostUrl:`ws://${_}/stream/${p}`,token:()=>Mn(p,t.tokenSecret,void 0,void 0,x)}),f=h?ls({laneId:p,roomDoc:b=>t.roomDoc(p,b),streamEndpoint:w}):ls({laneId:p,streamEndpoint:w,connector:(0,Wu.createWebsocketDocConnector)({serverUrl:`ws://${_}/doc`,sessionId:p,token:()=>Mn(p,t.tokenSecret,void 0,void 0,x),WebSocketPolyfill:Ju.default})}),g=h?a(p):jr(f,`lane:${p}`,{armOnFirstSync:!0}),y={session:f,responses:new Lt(f,{sessionTag:null}),gone:g,goneWatch:g,laneId:p,pool:m,inFlight:0,laneSession:f,self:h,host:_??""};return n.set(p,y),g.onGone(()=>u(y)),y},a=p=>{let m=null,h=!1,_=new Set,x=f=>{if(!m){m=f;for(let g of[..._])g(f);_.clear()}},w=t.hostedSignal?.(p,f=>{if(f){h=!0;return}h&&x(new Q(`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:()=>m,onGone(f){return m?(f(m),()=>{}):(_.add(f),()=>_.delete(f))},dispose(){w?.(),_.clear()}}},u=p=>{l(p)&&(n.delete(p.laneId),r.delete(p.laneId),p.goneWatch?.dispose(),nt.forgetLane(p.laneId))},l=p=>{let m=p.laneId;return typeof m=="string"&&n.get(m)===p},d=(p,m)=>{throw t.metrics?.observeLane503Fast(m??""),s.set(p,e()),new Se(p)},c=async(p,m)=>{let h=Hf(m);o.add(h);let _=e();try{let x=await t.laneWarmWaitMsFor?.(p,m)??t.laneColdWakeDefaultMs??0,w=await t.plane.pick({pool:h,model:p,holdMs:x});t.metrics?.observeLaneReady(p??"",w.length);let g=w.map(b=>({laneId:b.laneId,self:b.host===t.selfAddress,host:b.host})).sort((b,C)=>b.self!==C.self?b.self?-1:1:(r.get(b.laneId)??0)-(r.get(C.laneId)??0))[0];g||d(h,p);let y=n.get(g.laneId);return y?.goneWatch?.gone()&&(u(y),y=void 0),y&&(y.pool!==h||y.self!==g.self||y.host!==g.host)&&(u(y),y=void 0),y||(y=i(g.laneId,h,g.self,g.host,m.sharedOrgId??void 0)),y.inFlight+=1,r.set(g.laneId,(r.get(g.laneId)??0)+1),{app:h,entry:y,identity:{kind:"catalog",model_id:m.modelId??p??"",variant:m.variant??""}}}finally{t.metrics?.observeLanePick(p??"",e()-_)}};return{sessionFor(p,m){return c(p,m)},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(_=>_.pool)])].sort(),m=await t.plane.status().catch(()=>[]),h=new Map(jf(m));return Promise.all(p.map(async _=>{let x=h.get(_)??{pool:_,lanes:[],lastDemandAt:null};return{pool:_,lanes:x.lanes,lastDemandAt:x.lastDemandAt,local:[...n.values()].filter(w=>w.pool===_).map(w=>({laneId:w.laneId,inFlight:w.inFlight,self:w.self,host:w.host})),lastRefusalAt:s.get(_)??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 jf(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}E();var Yu=require("http");var Bf="/pooler/v1/lanes/pick",qf="/pooler/v1/lanes/status",Gf=1e4;function Ku(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"),m=null;try{m=p===""?null:JSON.parse(p)}catch{m=null}s({status:d.statusCode??0,json:m})}),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 zu(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 Ku(t,"POST",Bf,{pool:e,model:n,hold_ms:r},r+Gf);if(o.status!==200)throw zu(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 Ku(t,"GET",qf,void 0,5e3);if(e.status!==200)throw zu(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}E();var ol=require("ws");E();var Zu=Re(require("yjs"),1),on=Re(require("y-protocols/sync"),1),dt=Re(require("y-protocols/awareness"),1),fe=Re(require("lib0/encoding"),1),sn=Re(require("lib0/decoding"),1),el=Re(require("lib0/map"),1),tl=Re(require("lodash.debounce"),1);E();var Qu=()=>{};var Jf=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,Vf=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,Kf=0,zf=1;var Yf=process.env.GC!=="false"&&process.env.GC!=="0",Xf=process.env.YPERSISTENCE,Br=null;if(typeof Xf=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var rn=new Map,qr=0,hs=1,Qf=(t,e,n)=>{let r=fe.createEncoder();fe.writeVarUint(r,qr),on.writeUpdate(r,t);let o=fe.toUint8Array(r);n.conns.forEach((s,i)=>$n(n,i,o))},gs=class extends Zu.Doc{constructor(e){super({gc:Yf}),this.name=e,this.conns=new Map,this.awareness=new dt.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=fe.createEncoder();fe.writeVarUint(u,hs),fe.writeVarUint8Array(u,dt.encodeAwarenessUpdate(this.awareness,a));let l=fe.toUint8Array(u);this.conns.forEach((d,c)=>{$n(this,c,l)})};this.awareness.on("update",n),this.on("update",Qf),!1}},ys=(t,e=!0)=>el.setIfUndefined(rn,t,()=>{let n=new gs(t);return n.gc=e,Br!==null&&Br.bindState(t,n),rn.set(t,n),n}),Zf=(t,e,n)=>{try{let r=fe.createEncoder(),o=sn.createDecoder(n);switch(sn.readVarUint(o)){case qr:fe.writeVarUint(r,qr),on.readSyncMessage(o,r,e,t),fe.length(r)>1&&$n(e,t,fe.toUint8Array(r));break;case hs:{dt.applyAwarenessUpdate(e.awareness,sn.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},nn=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),dt.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Br!==null&&(Br.writeState(t.name,t).then(()=>{t.destroy()}),rn.delete(t.name))}e.close()},$n=(t,e,n)=>{e.readyState!==Kf&&e.readyState!==zf&&nn(t,e);try{e.send(n,r=>{r!=null&&nn(t,e)})}catch{nn(t,e)}},em=3e4,nl=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=ys(n,r);o.conns.set(t,new Set),t.on("message",a=>Zf(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&nn(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{nn(o,t),clearInterval(i)}}},em);t.on("close",()=>{nn(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=fe.createEncoder();fe.writeVarUint(a,qr),on.writeSyncStep1(a,o),$n(o,t,fe.toUint8Array(a));let u=o.awareness.getStates();if(u.size>0){let l=fe.createEncoder();fe.writeVarUint(l,hs),fe.writeVarUint8Array(l,dt.encodeAwarenessUpdate(o.awareness,Array.from(u.keys()))),$n(o,t,fe.toUint8Array(l))}}};var ws="/doc/",sl=30,tm=1e4,rl="llm";function nm(t){if(!t.startsWith(ws))return null;let e=t.slice(ws.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 Nn(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
80
+ ${o}`)}function Bu(t,e){let n=e.heartbeatMs??3e4,r=new Mt.WebSocketServer({noServer:!0,handleProtocols:(l,d)=>{let c=Uu(new URL(d.url??"/","http://localhost").pathname);if(!c)return!1;let p=Hr(c.name);return l.has(p)?p:!1}}),o=new Map,s=new Set,i=!1,a=(l,d,c,p)=>{let m={client:c,upstream:p,laneId:l,name:d};s.add(m);let h=_=>{if(s.delete(m)){console.warn(`[lane-stream] ${l}/${d}: host-affinity pump torn down (${_})`);for(let S of[c,p])try{(S.readyState===Mt.default.OPEN||S.readyState===Mt.default.CONNECTING)&&S.close(1001,"lane stream pump closed")}catch{}}};if(n>0){let _=(S,w)=>{let f=!0;S.on("pong",()=>{f=!0});let g=setInterval(()=>{if(!f){console.warn(`[lane-stream] ${l}/${d}: pong timeout on ${w} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${w} dial never sends a close)`),clearInterval(g);try{S.terminate()}catch{}h(`${w} pong timeout`);return}f=!1;try{S.ping()}catch{}},n);g.unref?.();let y=()=>clearInterval(g);S.once("close",y),S.once("error",y)};_(c,"client"),_(p,"host")}c.on("message",_=>{try{p.send(_,{binary:!0})}catch(S){h(`upstream send failed: ${String(S)}`)}}),p.on("message",_=>{try{c.send(_,{binary:!0})}catch(S){h(`client send failed: ${String(S)}`)}}),c.on("close",()=>h("client socket closed")),c.on("error",()=>h("client socket error")),p.on("close",()=>h("host socket closed")),p.on("error",()=>h("host socket error"))},u=(l,d,c)=>{let p;try{p=new URL(l.url??"/","http://localhost")}catch{ds(d,400,"malformed upgrade URL");return}d.on("error",()=>d.destroy());let m=Uu(p.pathname);m&&(i||d.destroyed||(async()=>{let h=p.searchParams.get("token")??"",_=null;try{_=h===""?null:await e.verifyToken(h,m.laneId,m.name)}catch{_=null}if(_===null){ds(d,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let S=await e.hostOf(m.laneId).catch(()=>null);if(S&&S!==e.selfAddress)try{let w=await e.podToPodDial(m.laneId,m.name,S);r.handleUpgrade(l,d,c,f=>{a(m.laneId,m.name,f,w)});return}catch(w){console.warn(`[lane-stream] ${m.laneId}/${m.name}: host dial to ${S} failed (${String(w)}) \u2014 falling back to the local relay`)}}r.handleUpgrade(l,d,c,S=>{let w=Tf(S);if(o.set(S,w),nt.attach(m.laneId,m.name,w),n>0){let g=!0;S.on("pong",()=>{g=!0});let y=setInterval(()=>{if(!g){console.warn(`[lane-stream] ${m.laneId}/${m.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(y),S.terminate();return}g=!1;try{S.ping()}catch{}},n);y.unref?.();let v=()=>clearInterval(y);S.once("close",v),S.once("error",v)}S.on("message",g=>{let y=new Uint8Array(g);try{Dr(y)}catch(v){console.warn(`[lane-stream] ${m.laneId}/${m.name}: dropped malformed envelope: ${String(v)}`);return}nt.deliver(m.laneId,m.name,w,y),y[1]===$t.ENVELOPE_KIND.END&&nt.detach(m.laneId,m.name,w)});let f=()=>{o.delete(S),nt.detach(m.laneId,m.name,w)};S.on("close",f),S.on("error",f)})})().catch(()=>{d.destroyed||ds(d,500,"lane stream upgrade failed")}))};return t.on("upgrade",u),{async close(){i=!0,t.off("upgrade",u),nt.clear();for(let l of o.values())l.close(1001,"lane stream host shutting down");o.clear();for(let l of s)for(let d of[l.client,l.upstream])try{d.close(1001,"lane stream host shutting down")}catch{}s.clear()}}}x();var wt=require("crypto"),Pf=["sfu","urun-doc"],Gu="runtime:lease",Cf="lane:join",Lf="urun-runtime-key-v1";function ps(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,wt.createHmac)("sha256",t).update(`${Lf}|${e}`).digest("base64url")}var Mf=120,Bw=1440*60;function qu(t){return Buffer.from(t).toString("base64url")}function $f(t,e,n){let r=qu(JSON.stringify(t)),o=qu(JSON.stringify(e)),s=(0,wt.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function Mn(t,e,n=Mf,r=Cf,o){let s=o?ps(e,o):e;return Nf(t,s,n,r,o)}function Nf(t,e,n,r,o){let s=Math.floor(Date.now()/1e3);return $f({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,wt.randomUUID)()},e)}function fs(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,m=[];if(p!==void 0?(m.push(ps(n,p)),o&&m.push(ps(o,p))):(m.push(n),o&&m.push(o)),!m.some(f=>{let g=(0,wt.createHmac)("sha256",f).update(`${i}.${a}`).digest();return c.length===g.length&&(0,wt.timingSafeEqual)(c,g)}))return null;let h=d.exp;if(typeof h!="number"||h<=r)return null;let _=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(_!==void 0&&Pf.some(f=>f===_||Array.isArray(_)&&_.includes(f))))return null;let w=d.session_id??d.sub;return typeof w!="string"||w!==e?null:{sessionId:w,aud:_,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:h}}x();var Uf=3,Df="llm",Ff=new Set(["paused","error"]);function jr(t,e,n){let r=t.doc(Df),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<Uf||d(new Q(`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&&Ff.has(c.name)&&d(new Q(`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*ms(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 Hf(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new je(`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 Vu(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=(p,m,h,_,S)=>{let w=h?v=>Hu(p,v):v=>ju(p,v,{hostUrl:`ws://${_}/stream/${p}`,token:()=>Mn(p,t.tokenSecret,void 0,void 0,S)}),f=h?ls({laneId:p,roomDoc:v=>t.roomDoc(p,v),streamEndpoint:w}):ls({laneId:p,streamEndpoint:w,connector:(0,Wu.createWebsocketDocConnector)({serverUrl:`ws://${_}/doc`,sessionId:p,token:()=>Mn(p,t.tokenSecret,void 0,void 0,S),WebSocketPolyfill:Ju.default})}),g=h?a(p):jr(f,`lane:${p}`,{armOnFirstSync:!0}),y={session:f,responses:new Lt(f,{sessionTag:null}),gone:g,goneWatch:g,laneId:p,pool:m,inFlight:0,laneSession:f,self:h,host:_??""};return n.set(p,y),g.onGone(()=>u(y)),y},a=p=>{let m=null,h=!1,_=new Set,S=f=>{if(!m){m=f;for(let g of[..._])g(f);_.clear()}},w=t.hostedSignal?.(p,f=>{if(f){h=!0;return}h&&S(new Q(`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:()=>m,onGone(f){return m?(f(m),()=>{}):(_.add(f),()=>_.delete(f))},dispose(){w?.(),_.clear()}}},u=p=>{l(p)&&(n.delete(p.laneId),r.delete(p.laneId),p.goneWatch?.dispose(),nt.forgetLane(p.laneId))},l=p=>{let m=p.laneId;return typeof m=="string"&&n.get(m)===p},d=(p,m)=>{throw t.metrics?.observeLane503Fast(m??""),s.set(p,e()),new Se(p)},c=async(p,m)=>{let h=Hf(m);o.add(h);let _=e();try{let S=await t.laneWarmWaitMsFor?.(p,m)??t.laneColdWakeDefaultMs??0,w=await t.plane.pick({pool:h,model:p,holdMs:S});t.metrics?.observeLaneReady(p??"",w.length);let g=w.map(v=>({laneId:v.laneId,self:v.host===t.selfAddress,host:v.host})).sort((v,C)=>v.self!==C.self?v.self?-1:1:(r.get(v.laneId)??0)-(r.get(C.laneId)??0))[0];g||d(h,p);let y=n.get(g.laneId);return y?.goneWatch?.gone()&&(u(y),y=void 0),y&&(y.pool!==h||y.self!==g.self||y.host!==g.host)&&(u(y),y=void 0),y||(y=i(g.laneId,h,g.self,g.host,m.sharedOrgId??void 0)),y.inFlight+=1,r.set(g.laneId,(r.get(g.laneId)??0)+1),{app:h,entry:y,identity:{kind:"catalog",model_id:m.modelId??p??"",variant:m.variant??""}}}finally{t.metrics?.observeLanePick(p??"",e()-_)}};return{sessionFor(p,m){return c(p,m)},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(_=>_.pool)])].sort(),m=await t.plane.status().catch(()=>[]),h=new Map(jf(m));return Promise.all(p.map(async _=>{let S=h.get(_)??{pool:_,lanes:[],lastDemandAt:null};return{pool:_,lanes:S.lanes,lastDemandAt:S.lastDemandAt,local:[...n.values()].filter(w=>w.pool===_).map(w=>({laneId:w.laneId,inFlight:w.inFlight,self:w.self,host:w.host})),lastRefusalAt:s.get(_)??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 jf(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}x();var Yu=require("http");var Bf="/pooler/v1/lanes/pick",qf="/pooler/v1/lanes/status",Gf=1e4;function Ku(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"),m=null;try{m=p===""?null:JSON.parse(p)}catch{m=null}s({status:d.statusCode??0,json:m})}),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 zu(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 Ku(t,"POST",Bf,{pool:e,model:n,hold_ms:r},r+Gf);if(o.status!==200)throw zu(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 Ku(t,"GET",qf,void 0,5e3);if(e.status!==200)throw zu(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}x();var ol=require("ws");x();var Zu=Re(require("yjs"),1),on=Re(require("y-protocols/sync"),1),dt=Re(require("y-protocols/awareness"),1),fe=Re(require("lib0/encoding"),1),sn=Re(require("lib0/decoding"),1),el=Re(require("lib0/map"),1),tl=Re(require("lodash.debounce"),1);x();var Qu=()=>{};var Jf=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,Vf=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,Kf=0,zf=1;var Yf=process.env.GC!=="false"&&process.env.GC!=="0",Xf=process.env.YPERSISTENCE,Br=null;if(typeof Xf=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var rn=new Map,qr=0,hs=1,Qf=(t,e,n)=>{let r=fe.createEncoder();fe.writeVarUint(r,qr),on.writeUpdate(r,t);let o=fe.toUint8Array(r);n.conns.forEach((s,i)=>$n(n,i,o))},gs=class extends Zu.Doc{constructor(e){super({gc:Yf}),this.name=e,this.conns=new Map,this.awareness=new dt.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=fe.createEncoder();fe.writeVarUint(u,hs),fe.writeVarUint8Array(u,dt.encodeAwarenessUpdate(this.awareness,a));let l=fe.toUint8Array(u);this.conns.forEach((d,c)=>{$n(this,c,l)})};this.awareness.on("update",n),this.on("update",Qf),!1}},ys=(t,e=!0)=>el.setIfUndefined(rn,t,()=>{let n=new gs(t);return n.gc=e,Br!==null&&Br.bindState(t,n),rn.set(t,n),n}),Zf=(t,e,n)=>{try{let r=fe.createEncoder(),o=sn.createDecoder(n);switch(sn.readVarUint(o)){case qr:fe.writeVarUint(r,qr),on.readSyncMessage(o,r,e,t),fe.length(r)>1&&$n(e,t,fe.toUint8Array(r));break;case hs:{dt.applyAwarenessUpdate(e.awareness,sn.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},nn=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),dt.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Br!==null&&(Br.writeState(t.name,t).then(()=>{t.destroy()}),rn.delete(t.name))}e.close()},$n=(t,e,n)=>{e.readyState!==Kf&&e.readyState!==zf&&nn(t,e);try{e.send(n,r=>{r!=null&&nn(t,e)})}catch{nn(t,e)}},em=3e4,nl=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=ys(n,r);o.conns.set(t,new Set),t.on("message",a=>Zf(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&nn(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{nn(o,t),clearInterval(i)}}},em);t.on("close",()=>{nn(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=fe.createEncoder();fe.writeVarUint(a,qr),on.writeSyncStep1(a,o),$n(o,t,fe.toUint8Array(a));let u=o.awareness.getStates();if(u.size>0){let l=fe.createEncoder();fe.writeVarUint(l,hs),fe.writeVarUint8Array(l,dt.encodeAwarenessUpdate(o.awareness,Array.from(u.keys()))),$n(o,t,fe.toUint8Array(l))}}};var ws="/doc/",sl=30,tm=1e4,rl="llm";function nm(t){if(!t.startsWith(ws))return null;let e=t.slice(ws.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 Nn(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
81
81
  `;t.end(`HTTP/1.1 ${e} ${r}\r
82
82
  Connection: close\r
83
83
  Content-Type: text/plain; charset=utf-8\r
84
84
  Content-Length: ${Buffer.byteLength(o)}\r
85
85
  \r
86
- ${o}`)}function il(t,e){let n=new ol.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=w=>o.get(`${w}/${rl}`)??0,a=w=>s.get(w)??0,u=new Map,l=new Map,d=new Set,c=new Set,p=!1,m=(w,f,g)=>{let y=i(w)>0,b=a(w),C=b>0,P=`${w}/${f}`,S=o.get(P)??0;g>0?o.set(P,g):o.delete(P);let A=b+g-S;A>0?s.set(w,A):s.delete(w);let R=i(w)>0,O=A>0;if(y!==R){R?h(w):_(w);for(let I of u.get(w)??[])I(R)}C&&!O&&queueMicrotask(()=>{let I=`${w}/`;for(let[U,W]of[...rn.entries()])!U.startsWith(I)||W.conns.size>0||(rn.delete(U),W.destroy())})},h=w=>{if(!e.hostRegistry||l.has(w))return;let f=()=>{e.hostRegistry?.setHost(w,e.selfAddress).catch(()=>{})};f();let g=setInterval(f,tm);g.unref?.(),l.set(w,g)},_=w=>{let f=l.get(w);f&&(clearInterval(f),l.delete(w)),e.hostRegistry&&e.hostRegistry.delHost(w,e.selfAddress).catch(()=>{})},x=(w,f,g)=>{let y;try{y=new URL(w.url??"/","http://localhost")}catch{Nn(f,400,"malformed upgrade URL");return}f.on("error",()=>f.destroy()),f.on("close",()=>c.delete(f));let b=nm(y.pathname);if(!b){if(y.pathname.startsWith(ws)){Nn(f,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(f);return}d.add(f);let C=!1;(async()=>{let P=y.searchParams.get("token")??"",S=null;try{S=P===""?null:await e.verifyToken(P,b.laneId,b.docName)}catch{S=null}if(S===null){Nn(f,401,"invalid or missing lane doc token");return}let A=S;if(A.tenant!==void 0&&e.laneTenantOf){let R=null;try{R=await e.laneTenantOf(b.laneId)}catch{R=null}if(R==null||R==="")e.onLaneTenantMissing?.();else if(A.tenant!==R){Nn(f,403,"lane doc token org does not match the lane record");return}}p||f.destroyed||(C=!0,n.handleUpgrade(w,f,g,R=>{d.delete(f),r.add(R),R.on("close",()=>r.delete(R));let O=A.scope===Gu||A.scope===void 0&&typeof A.app=="string"&&typeof A.fn=="string"&&A.aud==="sfu";if(O){let U=`${b.laneId}/${b.docName}`,W=(o.get(U)??0)+1;m(b.laneId,b.docName,W),W>1&&b.docName===rl&&e.hostRegistry?.setHost(b.laneId,e.selfAddress).catch(()=>{})}R.on("close",()=>{if(!O)return;let U=`${b.laneId}/${b.docName}`;m(b.laneId,b.docName,Math.max(0,(o.get(U)??1)-1))}),nl(R,w,{docName:`${b.laneId}/${b.docName}`,gc:!0})}))})().catch(()=>{!C&&!f.destroyed&&Nn(f,500,"lane doc upgrade failed")}).finally(()=>d.delete(f))};return t.on("upgrade",x),{async close(){p=!0,t.off("upgrade",x);for(let f of[...l.keys()])_(f);await new Promise(f=>{if(r.size===0&&d.size===0){f();return}let g=r.size+d.size,y=()=>{g-=1,g<=0&&f()};for(let b of r)b.once("close",y);for(let b of d)b.once("close",y);for(let b of r)b.close(1001,"lane doc host shutting down");for(let b of d)b.destroy()}),o.clear(),s.clear(),u.clear()},roomDoc(w,f){return ys(`${w}/${f}`,!0)},isHosted(w){return i(w)>0},onHostedChange(w,f){let g=u.get(w);return g||(g=new Set,u.set(w,g)),g.add(f),f(i(w)>0),()=>{g.delete(f)}}}}var Tl=Re(require("ws"),1);E();var rm="urun:catalog:v1";function al(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(rm),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)
87
- `)}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 Pl=Re(require("ioredis"),1);E();var Jr=require("@urun-sh/core"),Vr=require("crypto"),ul="urun-session-gateway",om="machine",sm=3e5;function im(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var he=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Un=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}},Xe=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function Kr(t){let e=(t??"").trim();if(e==="")throw new he("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 he("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var am=60,um=6e4,lm=4096;function dm(t){return t===401||t===403}var Gr=class{constructor(e){this.opts=e;this.mint=e.mint??Jr.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new he("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<um)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:am});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 Jr.ClientTokenError&&dm(s.status)?(this.cache.delete(e),new he("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Xe("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 Xe("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>=lm){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 ll(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var Wr=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<sm)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 Xe("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 Xe("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 Xe("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 Xe?i:new Xe("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 he("malformed machine token");let s,i;try{s=ll(n),i=ll(r)}catch{throw new he("malformed machine token")}if(s.alg!=="RS256")throw new he(`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 he(`machine token issuer is not one this endpoint accepts (${JSON.stringify(u)})`);if(i.aud!==ul)throw new he(`machine token audience must be ${ul} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==om)throw new he(`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 he("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 he("machine token is expired \u2014 re-mint and retry");let c=w=>w.kty==="RSA"&&w.n!==void 0&&w.e!==void 0,p=await this.jwksKeys(!1),m=a===""?void 0:p.find(w=>w.kid===a&&c(w));if(m===void 0&&(p=await this.jwksKeys(!0),m=a===""?void 0:p.find(w=>w.kid===a&&c(w))),m===void 0)throw new he(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let h=Buffer.from(`${n}.${r}`,"ascii"),_=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),x=!1;try{let w=(0,Vr.createPublicKey)({key:m,format:"jwk"});x=(0,Vr.verify)("RSA-SHA256",h,w,_)}catch{x=!1}if(!x)throw new he("machine token signature failed verification");return{apiKey:e,orgId:l,credential:"machine"}}};function _s(t,e,n){return n!==null&&im(t)?n.verify(t):e.resolve(t)}E();var Dn=require("crypto");E();var Ie=require("@urun-sh/core");E();async function dl(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()}E();var cl=require("@urun-sh/core"),vs=2;function cm(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function pm(t){let e=t?.type;return e==="response.completed"||e==="error"}function pl(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=vs;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 m of p){if(pm(m)&&(d=!0),cm(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof cl.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,u,p)}catch{}throw p}if(i<vs&&!c){await t.evict(a,u);continue}throw p}if(d)return;if(i<vs&&!c){await t.evict(a,u);continue}return}})()}}var Ss=require("crypto");E();var fl=require("@urun-sh/core"),fm="audio";function ml(t){let e=t.streamEndpoint(fm);return{sessionId:t.id,appendInputAudio(n){let r=Buffer.from(n,"base64");r.byteLength!==0&&e.send((0,fl.encodeStreamEnvelope)(new Uint8Array(r)))},onOutputAudio(){return()=>{}}}}var gm=0,hm=4,ym=4;function hl(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):gm;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,hm));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",ym),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function bs(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 yl(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=_=>({session:_,responses:new Lt(_),gone:jr(_,n)});if(i.lane==="jwt"){let _=(0,Ie.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(bs(_,e.appSlug,a,l))}if(i.lane==="machine"){let{machineToken:_,gatewayUrl:x}=i,w=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ss.randomUUID)(),f=(0,Ie.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,Ie.createClientToken)(_,{baseUrl:x,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:w,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(bs(f,e.appSlug,a,l))}let{apiKey:c,gatewayUrl:p}=i,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ss.randomUUID)(),h=(0,Ie.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,Ie.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(bs(h,e.appSlug,a,l))}function wm(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 wl(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 _m=new Set(["error","paused"]);function ks(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=yl(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 Gn({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"?()=>ui({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>dl(n):null),listPrices:n?()=>Vs(n):null,shared:e.lane==="api-key"?()=>Bs({apiUrl:t.apiUrl,apiKey:e.apiKey}):e.lane==="machine"&&t.catalogRows?async()=>{let i=await t.catalogRows();return js(i)}:null,sessionKey:wm});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},ft({appSlug:t.defaultApp}))),s}function _l(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}
88
- `)},u=(d,c)=>{let p=o.get(c);if(p)return p;let m=new ar({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async h=>{let _=yl(t,d,c,{concurrencyKey:h.concurrencyKey});return _.gone.onGone(()=>m.markSessionDead(_)),await Yr(_.session),a(`slot attached pool=${c} slot=${h.concurrencyKey} session=${_.session.id??"(no id)"}`),_},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,_)=>a(`slot detached pool=${c} slot=${h.concurrencyKey} reason=${_}`),terminalOpenFailure:h=>h instanceof Ie.SessionFailedError&&wl(h)});return s.set(c,{target:d,env:n}),o.set(c,m),m},l=async(d,c)=>{let p=s.get(c);if(p)try{let m=await e.poolTuningFor(d);u(d,c).retune({min:m?.min??p.env.min,max:m?.max??p.env.max,inFlightCap:m?.in_flight_cap??p.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){a(`pool tuning refresh failed pool=${c} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await u(d,ft(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=ft(c),m=u(c,p);await l(c,p);let h=await m.acquire({timeoutMs:m.requestWaitMs}),_=i.get(h.entry)??[];return _.push(h),i.set(h.entry,_),{app:p,entry:h.entry,identity:qn(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await u(c,ft(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 vm(t){return(0,Ie.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?Ie.DEFAULT_WHEN_LIVE_TIMEOUT_MS:Ie.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:Ie.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Yr(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:vm(t.phase),signal:e})}async function gl(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 zr(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Rs(t,e=Ki,n,r,o=Do,s){let i=new WeakMap,a=new WeakMap,u=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let g=f.session.id;return typeof g=="string"&&g.length>0?g:null},p="lane",m=f=>{let g=Wn(f);if(!s||!g||g.app!==p)return null;let y=s.entryFor(g.key);if(!y)throw new Q(`the lane behind this handle (${g.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:g.key,entry:y}},h=async f=>m(f)?.entry??(await t.sessionForHandle(f)).entry,_=f=>{let g=i.get(f);if(!g){let y={waiting:0,gone:new AbortController};d.set(f,y),g=(async()=>{if(await Yr(f.session,y.gone.signal),y.gone.signal.aborted)throw zr(y.gone.signal);d.get(f)===y&&d.delete(f);let b=await Ji(f.session,await e());return Object.assign(b,{sessionId:f.session.id})})(),i.set(f,g),g.catch(()=>{i.get(f)===g&&i.delete(f)}),g.then(()=>{d.get(f)===y&&d.delete(f)},()=>{d.get(f)===y&&d.delete(f)})}return g},x=f=>{let g=l.get(f);return g||(g=(async()=>{let y=await _(f);return{appendInputAudio:b=>y.appendInputAudio(b),onOutputAudio:b=>y.onOutputAudio(b),sessionId:c(f)}})(),l.set(f,g),g.catch(()=>{l.get(f)===g&&l.delete(f)})),g},w=async(f,g,y)=>{if(y?.aborted){let P=d.get(f);throw(i.get(f)===void 0||P!==void 0&&P.waiting===0)&&await gl(f.session),zr(y)}let b=g(f),C=d.get(f);return C!==void 0&&C.waiting++,y===void 0?b:new Promise((P,S)=>{let A=()=>{C!==void 0&&--C.waiting===0&&d.get(f)===C&&(C.gone.abort(),d.delete(f),i.delete(f),l.delete(f),gl(f.session).catch(()=>{})),S(zr(y))};y.addEventListener("abort",A,{once:!0});let R=()=>y.removeEventListener("abort",A);b.then(O=>{R(),P(O)},O=>{R(),S(O)})})};return{createResponse:pl({sessionFor:s?async f=>{let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g);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,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(f,g)},onAdmissionVerdict:(f,g,y)=>{wl(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(f,g),n?.(f,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,g)=>{try{await Yr(f.session);let y=Ea(ms(await f.responses.responses.create(g),f.gone),o);if(!r&&!s)return y;let b=f;return(async function*(){try{yield*y}catch(P){throw xa(P)&&(s&&s.owns(b)?s.evict(b):r&&(P instanceof Q?r.markSessionDead(b):r.evict(b))),P}finally{s&&s.owns(b)?s.release(b):r?.end(b)}})()}catch(y){throw s&&s.owns(f)?s.release(f):r&&r.end(f),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,g)=>t.supportsImages(f,g),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,g)=>{let{entry:y}=await t.sessionFor(f);return await w(y,_,g)},openAudioOn:async(f,g,y)=>{let b=m(f);if(b){let P=b.entry.session;return ml(P)}let{entry:C}=await t.sessionForHandle(f);return await w(C,x,g)},openTurnsOn:async function*(f,g){if(g?.aborted)throw zr(g);let y=await h(f);yield*si(y.session,g)},openVideo:async f=>{let{entry:g}=await t.sessionFor(f),y=a.get(g);return y||(y=Vi(g.session),a.set(g,y)),y},openVideoOut:async f=>{let{entry:g}=await t.sessionFor(f),y=u.get(g);return y||(y=Yi(g.session),u.set(g,y)),y},sessionHandle:async f=>{if(s){let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g),b=c(y.entry);if(b===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Bn(p,b)}}return(await t.handleFor(f)).handle},releaseSessionHandle:f=>{let g=Wn(f);if(!s||g?.app!==p)return;let y=s.entryFor(g.key);y&&s.release(y)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:g,entry:y}=await t.sessionForHandle(f);await t.evict(g,y)},createResponseOn:async(f,g,y)=>{let b=await h(f);await Yr(b.session);let C=y!==void 0&&m(f)?new Lt({...b.session,consumerId:y},{sessionTag:y}):b.responses;return ms(await C.responses.create(g),b.gone)},onSessionEnd:async(f,g)=>{let y=m(f);if(y)return y.entry.gone.onGone(S=>g({timeLeftMs:null,reason:S.message}));let{entry:b}=await t.sessionForHandle(f),C=b.session;if(typeof C.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let P=!1;return C.onPhase(S=>{if(P||!_m.has(S.name))return;P=!0;let A=C.endsAt??null;g({timeLeftMs:A?Math.max(0,A.getTime()-Date.now()):null,reason:S.reason??`session ${S.name}`})})}}}E();var bl=require("http");var bm="/pooler/v1/inference",an=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},Sm=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)},km=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)}},Sl=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)}),Rm=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await Sl(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 an(t.status,e,n,t.retryAfterSeconds)};async function Em(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${bm}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Sm(e),firstMessage:km(e)}});return new Promise((a,u)=>{let l=(0,bl.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 an(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),l.end(i)})}var vl=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*xm(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
86
+ ${o}`)}function il(t,e){let n=new ol.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=w=>o.get(`${w}/${rl}`)??0,a=w=>s.get(w)??0,u=new Map,l=new Map,d=new Set,c=new Set,p=!1,m=(w,f,g)=>{let y=i(w)>0,v=a(w),C=v>0,P=`${w}/${f}`,k=o.get(P)??0;g>0?o.set(P,g):o.delete(P);let A=v+g-k;A>0?s.set(w,A):s.delete(w);let E=i(w)>0,O=A>0;if(y!==E){E?h(w):_(w);for(let I of u.get(w)??[])I(E)}C&&!O&&queueMicrotask(()=>{let I=`${w}/`;for(let[U,W]of[...rn.entries()])!U.startsWith(I)||W.conns.size>0||(rn.delete(U),W.destroy())})},h=w=>{if(!e.hostRegistry||l.has(w))return;let f=()=>{e.hostRegistry?.setHost(w,e.selfAddress).catch(()=>{})};f();let g=setInterval(f,tm);g.unref?.(),l.set(w,g)},_=w=>{let f=l.get(w);f&&(clearInterval(f),l.delete(w)),e.hostRegistry&&e.hostRegistry.delHost(w,e.selfAddress).catch(()=>{})},S=(w,f,g)=>{let y;try{y=new URL(w.url??"/","http://localhost")}catch{Nn(f,400,"malformed upgrade URL");return}f.on("error",()=>f.destroy()),f.on("close",()=>c.delete(f));let v=nm(y.pathname);if(!v){if(y.pathname.startsWith(ws)){Nn(f,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(f);return}d.add(f);let C=!1;(async()=>{let P=y.searchParams.get("token")??"",k=null;try{k=P===""?null:await e.verifyToken(P,v.laneId,v.docName)}catch{k=null}if(k===null){Nn(f,401,"invalid or missing lane doc token");return}let A=k;if(A.tenant!==void 0&&e.laneTenantOf){let E=null;try{E=await e.laneTenantOf(v.laneId)}catch{E=null}if(E==null||E==="")e.onLaneTenantMissing?.();else if(A.tenant!==E){Nn(f,403,"lane doc token org does not match the lane record");return}}p||f.destroyed||(C=!0,n.handleUpgrade(w,f,g,E=>{d.delete(f),r.add(E),E.on("close",()=>r.delete(E));let O=A.scope===Gu||A.scope===void 0&&typeof A.app=="string"&&typeof A.fn=="string"&&A.aud==="sfu";if(O){let U=`${v.laneId}/${v.docName}`,W=(o.get(U)??0)+1;m(v.laneId,v.docName,W),W>1&&v.docName===rl&&e.hostRegistry?.setHost(v.laneId,e.selfAddress).catch(()=>{})}E.on("close",()=>{if(!O)return;let U=`${v.laneId}/${v.docName}`;m(v.laneId,v.docName,Math.max(0,(o.get(U)??1)-1))}),nl(E,w,{docName:`${v.laneId}/${v.docName}`,gc:!0})}))})().catch(()=>{!C&&!f.destroyed&&Nn(f,500,"lane doc upgrade failed")}).finally(()=>d.delete(f))};return t.on("upgrade",S),{async close(){p=!0,t.off("upgrade",S);for(let f of[...l.keys()])_(f);await new Promise(f=>{if(r.size===0&&d.size===0){f();return}let g=r.size+d.size,y=()=>{g-=1,g<=0&&f()};for(let v of r)v.once("close",y);for(let v of d)v.once("close",y);for(let v of r)v.close(1001,"lane doc host shutting down");for(let v of d)v.destroy()}),o.clear(),s.clear(),u.clear()},roomDoc(w,f){return ys(`${w}/${f}`,!0)},isHosted(w){return i(w)>0},onHostedChange(w,f){let g=u.get(w);return g||(g=new Set,u.set(w,g)),g.add(f),f(i(w)>0),()=>{g.delete(f)}}}}var Tl=Re(require("ws"),1);x();var rm="urun:catalog:v1";function al(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(rm),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)
87
+ `)}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 Pl=Re(require("ioredis"),1);x();var Jr=require("@urun-sh/core"),Vr=require("crypto"),ul="urun-session-gateway",om="machine",sm=3e5;function im(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var he=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Un=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}},Xe=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function Kr(t){let e=(t??"").trim();if(e==="")throw new he("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 he("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var am=60,um=6e4,lm=4096;function dm(t){return t===401||t===403}var Gr=class{constructor(e){this.opts=e;this.mint=e.mint??Jr.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new he("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<um)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:am});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 Jr.ClientTokenError&&dm(s.status)?(this.cache.delete(e),new he("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Xe("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 Xe("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>=lm){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 ll(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var Wr=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<sm)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 Xe("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 Xe("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 Xe("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 Xe?i:new Xe("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 he("malformed machine token");let s,i;try{s=ll(n),i=ll(r)}catch{throw new he("malformed machine token")}if(s.alg!=="RS256")throw new he(`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 he(`machine token issuer is not one this endpoint accepts (${JSON.stringify(u)})`);if(i.aud!==ul)throw new he(`machine token audience must be ${ul} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==om)throw new he(`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 he("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 he("machine token is expired \u2014 re-mint and retry");let c=w=>w.kty==="RSA"&&w.n!==void 0&&w.e!==void 0,p=await this.jwksKeys(!1),m=a===""?void 0:p.find(w=>w.kid===a&&c(w));if(m===void 0&&(p=await this.jwksKeys(!0),m=a===""?void 0:p.find(w=>w.kid===a&&c(w))),m===void 0)throw new he(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let h=Buffer.from(`${n}.${r}`,"ascii"),_=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),S=!1;try{let w=(0,Vr.createPublicKey)({key:m,format:"jwk"});S=(0,Vr.verify)("RSA-SHA256",h,w,_)}catch{S=!1}if(!S)throw new he("machine token signature failed verification");return{apiKey:e,orgId:l,credential:"machine"}}};function _s(t,e,n){return n!==null&&im(t)?n.verify(t):e.resolve(t)}x();var Dn=require("crypto");x();var Ie=require("@urun-sh/core");x();async function dl(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 cl=require("@urun-sh/core"),vs=2;function cm(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function pm(t){let e=t?.type;return e==="response.completed"||e==="error"}function pl(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=vs;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 m of p){if(pm(m)&&(d=!0),cm(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof cl.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,u,p)}catch{}throw p}if(i<vs&&!c){await t.evict(a,u);continue}throw p}if(d)return;if(i<vs&&!c){await t.evict(a,u);continue}return}})()}}var Ss=require("crypto");x();var fl=require("@urun-sh/core"),fm="audio";function ml(t){let e=t.streamEndpoint(fm);return{sessionId:t.id,appendInputAudio(n){let r=Buffer.from(n,"base64");r.byteLength!==0&&e.send((0,fl.encodeStreamEnvelope)(new Uint8Array(r)))},onOutputAudio(){return()=>{}}}}var gm=0,hm=4,ym=4;function hl(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):gm;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,hm));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",ym),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function bs(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 yl(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=_=>({session:_,responses:new Lt(_),gone:jr(_,n)});if(i.lane==="jwt"){let _=(0,Ie.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(bs(_,e.appSlug,a,l))}if(i.lane==="machine"){let{machineToken:_,gatewayUrl:S}=i,w=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ss.randomUUID)(),f=(0,Ie.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,Ie.createClientToken)(_,{baseUrl:S,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:w,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(bs(f,e.appSlug,a,l))}let{apiKey:c,gatewayUrl:p}=i,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ss.randomUUID)(),h=(0,Ie.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,Ie.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(bs(h,e.appSlug,a,l))}function wm(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 wl(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 _m=new Set(["error","paused"]);function ks(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=yl(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 Gn({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"?()=>ui({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>dl(n):null),listPrices:n?()=>Vs(n):null,shared:e.lane==="api-key"?()=>Bs({apiUrl:t.apiUrl,apiKey:e.apiKey}):e.lane==="machine"&&t.catalogRows?async()=>{let i=await t.catalogRows();return js(i)}:null,sessionKey:wm});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},ft({appSlug:t.defaultApp}))),s}function _l(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}
88
+ `)},u=(d,c)=>{let p=o.get(c);if(p)return p;let m=new ar({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async h=>{let _=yl(t,d,c,{concurrencyKey:h.concurrencyKey});return _.gone.onGone(()=>m.markSessionDead(_)),await Yr(_.session),a(`slot attached pool=${c} slot=${h.concurrencyKey} session=${_.session.id??"(no id)"}`),_},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,_)=>a(`slot detached pool=${c} slot=${h.concurrencyKey} reason=${_}`),terminalOpenFailure:h=>h instanceof Ie.SessionFailedError&&wl(h)});return s.set(c,{target:d,env:n}),o.set(c,m),m},l=async(d,c)=>{let p=s.get(c);if(p)try{let m=await e.poolTuningFor(d);u(d,c).retune({min:m?.min??p.env.min,max:m?.max??p.env.max,inFlightCap:m?.in_flight_cap??p.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){a(`pool tuning refresh failed pool=${c} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await u(d,ft(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=ft(c),m=u(c,p);await l(c,p);let h=await m.acquire({timeoutMs:m.requestWaitMs}),_=i.get(h.entry)??[];return _.push(h),i.set(h.entry,_),{app:p,entry:h.entry,identity:qn(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await u(c,ft(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 vm(t){return(0,Ie.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?Ie.DEFAULT_WHEN_LIVE_TIMEOUT_MS:Ie.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:Ie.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Yr(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:vm(t.phase),signal:e})}async function gl(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 zr(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Rs(t,e=Ki,n,r,o=Do,s){let i=new WeakMap,a=new WeakMap,u=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let g=f.session.id;return typeof g=="string"&&g.length>0?g:null},p="lane",m=f=>{let g=Wn(f);if(!s||!g||g.app!==p)return null;let y=s.entryFor(g.key);if(!y)throw new Q(`the lane behind this handle (${g.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:g.key,entry:y}},h=async f=>m(f)?.entry??(await t.sessionForHandle(f)).entry,_=f=>{let g=i.get(f);if(!g){let y={waiting:0,gone:new AbortController};d.set(f,y),g=(async()=>{if(await Yr(f.session,y.gone.signal),y.gone.signal.aborted)throw zr(y.gone.signal);d.get(f)===y&&d.delete(f);let v=await Ji(f.session,await e());return Object.assign(v,{sessionId:f.session.id})})(),i.set(f,g),g.catch(()=>{i.get(f)===g&&i.delete(f)}),g.then(()=>{d.get(f)===y&&d.delete(f)},()=>{d.get(f)===y&&d.delete(f)})}return g},S=f=>{let g=l.get(f);return g||(g=(async()=>{let y=await _(f);return{appendInputAudio:v=>y.appendInputAudio(v),onOutputAudio:v=>y.onOutputAudio(v),sessionId:c(f)}})(),l.set(f,g),g.catch(()=>{l.get(f)===g&&l.delete(f)})),g},w=async(f,g,y)=>{if(y?.aborted){let P=d.get(f);throw(i.get(f)===void 0||P!==void 0&&P.waiting===0)&&await gl(f.session),zr(y)}let v=g(f),C=d.get(f);return C!==void 0&&C.waiting++,y===void 0?v:new Promise((P,k)=>{let A=()=>{C!==void 0&&--C.waiting===0&&d.get(f)===C&&(C.gone.abort(),d.delete(f),i.delete(f),l.delete(f),gl(f.session).catch(()=>{})),k(zr(y))};y.addEventListener("abort",A,{once:!0});let E=()=>y.removeEventListener("abort",A);v.then(O=>{E(),P(O)},O=>{E(),k(O)})})};return{createResponse:pl({sessionFor:s?async f=>{let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g);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,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(f,g)},onAdmissionVerdict:(f,g,y)=>{wl(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(f,g),n?.(f,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,g)=>{try{await Yr(f.session);let y=Ea(ms(await f.responses.responses.create(g),f.gone),o);if(!r&&!s)return y;let v=f;return(async function*(){try{yield*y}catch(P){throw xa(P)&&(s&&s.owns(v)?s.evict(v):r&&(P instanceof Q?r.markSessionDead(v):r.evict(v))),P}finally{s&&s.owns(v)?s.release(v):r?.end(v)}})()}catch(y){throw s&&s.owns(f)?s.release(f):r&&r.end(f),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,g)=>t.supportsImages(f,g),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,g)=>{let{entry:y}=await t.sessionFor(f);return await w(y,_,g)},openAudioOn:async(f,g,y)=>{let v=m(f);if(v){let P=v.entry.session;return ml(P)}let{entry:C}=await t.sessionForHandle(f);return await w(C,S,g)},openTurnsOn:async function*(f,g){if(g?.aborted)throw zr(g);let y=await h(f);yield*si(y.session,g)},openVideo:async f=>{let{entry:g}=await t.sessionFor(f),y=a.get(g);return y||(y=Vi(g.session),a.set(g,y)),y},openVideoOut:async f=>{let{entry:g}=await t.sessionFor(f),y=u.get(g);return y||(y=Yi(g.session),u.set(g,y)),y},sessionHandle:async f=>{if(s){let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g),v=c(y.entry);if(v===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Bn(p,v)}}return(await t.handleFor(f)).handle},releaseSessionHandle:f=>{let g=Wn(f);if(!s||g?.app!==p)return;let y=s.entryFor(g.key);y&&s.release(y)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:g,entry:y}=await t.sessionForHandle(f);await t.evict(g,y)},createResponseOn:async(f,g,y)=>{let v=await h(f);await Yr(v.session);let C=y!==void 0&&m(f)?new Lt({...v.session,consumerId:y},{sessionTag:y}):v.responses;return ms(await C.responses.create(g),v.gone)},onSessionEnd:async(f,g)=>{let y=m(f);if(y)return y.entry.gone.onGone(k=>g({timeLeftMs:null,reason:k.message}));let{entry:v}=await t.sessionForHandle(f),C=v.session;if(typeof C.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let P=!1;return C.onPhase(k=>{if(P||!_m.has(k.name))return;P=!0;let A=C.endsAt??null;g({timeLeftMs:A?Math.max(0,A.getTime()-Date.now()):null,reason:k.reason??`session ${k.name}`})})}}}x();var bl=require("http");var bm="/pooler/v1/inference",an=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},Sm=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)},km=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)}},Sl=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)}),Rm=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await Sl(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 an(t.status,e,n,t.retryAfterSeconds)};async function Em(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${bm}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Sm(e),firstMessage:km(e)}});return new Promise((a,u)=>{let l=(0,bl.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 an(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),l.end(i)})}var vl=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*xm(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
89
89
 
90
- `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=vl(s);i!==null&&(yield i)}let n=vl(e);n!==null&&(yield n)}async function kl(t,e,n,r){let o=Mr(e,n,r),s=o.model??"";if(s==="")throw new an(400,"missing_model","the pooler submit requires a model");let i=await Em(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Rm(i);let a=e.stream===!0?Nr(n,xm(i)):await Am(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Am(t,e){let n=await Sl(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 an(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Nr(e,(async function*(){yield o})())}var Om=512;function Es(t){return`urun-inference-proxy-${(0,Dn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Xr=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),s=this.opts.pooler;if(s===void 0)return o;let i=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,u)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)try{return await o.createResponse(a,u)}catch(c){if(!(c instanceof Se))throw c}let l=`px_${(0,Dn.randomUUID)()}`;return kl(s,a,l,l)}})}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,s.router),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ao,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:hl(process.env,process.env.HOSTNAME)??void 0},r=ks(n),o=n.decisionPool?_l(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,r),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>=Om;){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("; ")}`)}},Rl=512,Im=1024,Qr=class extends Error{constructor(){super(`conversation capacity reached (${Rl} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Tm(t){return{sessionStartOptions:e=>{if(e.startsWith(mn))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(mn)||t.set(e,n)}}}function Pm(t,e,n,r){let o=ks({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ao,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",...Tm(r)});return{clients:Rs(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var Zr=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${Es(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):Pm(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>=Rl;){let e=this.byCaller.keys().next();if(e.done)throw new Qr;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 Qr;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,Dn.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>=Im;){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 Q("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("; ")}`)}};E();var eo="/inference-usage",El=25e3;var Cm=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function xl(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Cm.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 to=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${eo}`,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(El)})}catch(i){throw new me(`the uRun usage surface (POST ${eo}) could not be reached within ${El}ms: ${xl(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new he("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 me(`the uRun usage surface (POST ${eo}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new me(`the uRun usage surface (POST ${eo}) answered HTTP ${o.status} with a body that is not JSON: ${xl(i)}`)}return $i(s,this.opts.onRejectedRow)}};E();var Lm="/inference-ledger",Mm=1e4,no=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Os=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},Oe=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Is=class extends he{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Ts=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},$m=[["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",xs],["output_minutes",xs],["cost_nano_usd",xs],["price_version",t=>t===null||typeof t=="string"]];function Nm(t){for(let[e,n]of $m){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Um(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"}:Nm(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function xs(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function As(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Dm(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Al(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 Fm(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&&Al(t.started_at,n.started_at)&&Al(t.completed_at,n.completed_at)&&As(t.prompt_tokens,n.prompt_tokens)&&As(t.completion_tokens,n.completion_tokens)&&As(t.output_units,n.output_units)&&Dm(t.output_minutes,n.output_minutes)}function Hm(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(`
91
- `)}async function jm(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(Hm(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Bm(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Oe(`${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 Oe(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new Oe(`${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 Oe(`${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 Oe(`${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 Oe(`${e} answered a non-string ${l}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new Oe(`${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 Oe(`${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 Oe(`${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 ro=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Lm}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await jm(n,this.opts.signing)}):JSON.stringify(n)}catch(l){throw new Oe(`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(Mm)})}catch(l){throw new Oe(`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=Um(l);throw d.status==="found"&&Fm(n,d.row)?new Os(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 no(`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 no(`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 Is("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 Ts(`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 Oe(`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 Oe(`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 Oe(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let u=Bm(a,`the uRun ledger surface at ${r}`);if(u.inference_id!==n.inference_id)throw new Oe(`the uRun ledger surface at ${r} answered for inference_id ${u.inference_id} when asked about ${n.inference_id}`);return u}};var qm=5e3,Gm=1e3,Wm=1500,Jm=3e3,Vm="/api/client-tokens";function oo(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Ol(t,e,n,r){oo(t,e,{error:{message:n,type:r}})}async function Km(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Vm}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Jm)});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 Cl(t){let e=t.resolver??new Gr({gatewayUrl:t.baseUrl}),n=t.machine?new Wr({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=new er(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,s=null,i=(()=>{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 S=new Pl.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),A=al({redis:S});return{registry:Vu({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:Xu({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(O,I)=>o?.onHostedChange(O,I)??(()=>()=>{}),roomDoc:(O,I)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(O,I)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(O,I)=>A.rows().then(U=>{let W=_o(U,I);return W?.warm_wait_s!==void 0?W.warm_wait_s*1e3:void 0})}),catalog:A,redis:S}})(),a=t.registry??new Xr({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry,pooler:t.pooler}),u=t.probeControlPlane??(()=>Km(t.baseUrl)),l=async()=>{let S=null;for(let O of a.decisionPools()){S=O;break}if(!S)return null;let A=S.stats();if(A.some(O=>O.draining))return{ok:!1,detail:"decision pool draining"};if(A.every(O=>O.attached===0&&O.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let R=await S.pingReady(Wm);return{ok:R,detail:R?"a decision slot answered its session ping":"no decision slot answered its session ping"}},d=t.usageClient??new to({apiUrl:t.apiUrl}),c=t.ledgerClient??new ro({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),p=process.env.URUN_SHARED_ORG_ID?.trim(),m=process.env.URUN_SHARED_ORG_API_KEY?.trim();p&&m&&(async()=>{try{await a.decisionWarmerFor({orgId:p,apiKey:m})?.warmFor(Cr)}catch(S){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(S instanceof Error?S.message:S)}
92
- `)}})();let h=async S=>_s(Kr(S.headers.authorization),e,n),_=async S=>{let A=await h(S);if(A.billingAudience==="platform"&&A.creditsAdmissionOk===!1){let R=A.creditsRefusalReason;throw new Un(R==="spend_cap_reached"||R==="insufficient_credits"?R:void 0)}return A},x=S=>S instanceof he?{status:S.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:S instanceof Un?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...S.code!==void 0?{code:S.code}:{}}:S instanceof Xe?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:S.detail}:null,w=Eu({clients:async S=>a.clientsFor(await _(S)),usage:{authorize:S=>Kr(S.headers.authorization),lookup:(S,A)=>d.lookup(S,A)},statusOf:x,...t.requestLog?{requestLog:t.requestLog}:{},observe:S=>r.observe(S),ledger:{write:(S,A)=>c.write(Kr(S.headers.authorization),A),observe:S=>r.observeLedger(S),...t.ledgerLog?{report:t.ledgerLog}:{}}}),f=null,g=null,y=(0,Il.createServer)((S,A)=>{let R=new URL(S.url??"/","http://localhost");(async()=>{if(S.method==="GET"&&R.pathname==="/healthz"){oo(A,200,{ok:!0});return}if(S.method==="GET"&&R.pathname==="/readyz"){let U=Date.now();if((!f||U-f.at>=qm)&&(f={at:U,...await u()}),!g||U-g.at>=Gm){let te=await l();g=te===null?{at:U,ok:!0,detail:null}:{at:U,ok:te.ok,detail:te.detail}}let W=(f?.ready??!1)&&g.ok,K=g.detail===null?f?.detail??"control plane not yet probed":`${f?.detail??"control plane not yet probed"}; ${g.detail}`;oo(A,W?200:503,{ok:W,control_plane:K});return}if(S.method==="GET"&&R.pathname==="/lanez"){oo(A,200,{pools:i?await i.registry.status():null});return}let O=R.pathname==="/v1"||R.pathname.startsWith("/v1/"),I=R.pathname.startsWith("/partners/");if(!O&&!I){Ol(A,404,`no route for ${S.method} ${R.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz, /readyz and /lanez`,"invalid_request_error");return}w(S,A)})().catch(O=>{if(!A.headersSent){Ol(A,500,String(O instanceof Error?O.message:O),"proxy_error");return}A.end()})}),b=t.conversations??new Zr({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry}),C=[Co(y,{authenticate:async S=>{let A=await _s(S,e,n),R=b.connectionFor(A);return{clients:R.clients,scope:Es(A.apiKey),onBindResumeHandle:R.bindResumeHandle,clientsForResume:R.clientsForResume,release:R.release}}}),qo(y,{clients:async S=>a.clientsFor(await _(S)),statusOf:x}).close,yr(y,{resolver:{resolve:async(S,A)=>{let R=await _(S),O=b.connectionFor(R),I;try{I=await Tu(as(O.clients,t.realtimeCompanions),Ou(S),A,Iu(S))}catch(W){throw O.release().catch(()=>{}),W}let U=I.release;return{...I,release:async()=>{await U?.(),await O.release()}}}}})];if(t.lane&&i){let S=t.lane,A=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=il(y,{verifyToken:(O,I)=>fs(O,I,S.tokenSecret,void 0,A),selfAddress:S.selfAddress,laneTenantOf:O=>i.redis.get(`lane_tenant:${O}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:A,hostRegistry:{setHost:(O,I)=>i.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(sl)),delHost:O=>i.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}`,S.selfAddress)}}),s=Bu(y,{verifyToken:(O,I)=>fs(O,I,S.tokenSecret,void 0,A),selfAddress:S.selfAddress,hostOf:async O=>{let I=await i.redis.get(`lane_hosts:${O}`);return I&&I.trim()!==""?I.trim():null},podToPodDial:(O,I,U)=>new Promise((W,K)=>{(async()=>{let te=await i.redis.get(`lane_tenant:${O}`),ne=Mn(O,S.tokenSecret,void 0,void 0,te||void 0),$e=`ws://${U}/stream/${encodeURIComponent(O)}/${encodeURIComponent(I)}?token=${encodeURIComponent(ne)}`,oe=new Tl.default($e,Hr(I));oe.once("open",()=>W(oe)),oe.once("error",K)})().catch(K)})});let R=i;C.push(async()=>{await o.close(),await s.close(),await R.registry.close(),R.redis.quit().catch(()=>{})})}y.on("upgrade",(S,A)=>{let R=new URL(S.url??"/","http://localhost");R.pathname===sr||R.pathname===jo||R.pathname===On||o!==null&&R.pathname.startsWith("/doc/")||s!==null&&R.pathname.startsWith("/stream/")||A.destroyed||(A.write(`HTTP/1.1 404 Not Found\r
90
+ `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=vl(s);i!==null&&(yield i)}let n=vl(e);n!==null&&(yield n)}async function kl(t,e,n,r){let o=Mr(e,n,r),s=o.model??"";if(s==="")throw new an(400,"missing_model","the pooler submit requires a model");let i=await Em(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Rm(i);let a=e.stream===!0?Nr(n,xm(i)):await Am(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Am(t,e){let n=await Sl(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 an(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Nr(e,(async function*(){yield o})())}var Om=512;function Es(t){return`urun-inference-proxy-${(0,Dn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Xr=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),s=this.opts.pooler;if(s===void 0)return o;let i=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,u)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)try{return await o.createResponse(a,u)}catch(c){if(!(c instanceof Se))throw c}let l=`px_${(0,Dn.randomUUID)()}`;return kl(s,a,l,l)}})}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,s.router),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ao,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:hl(process.env,process.env.HOSTNAME)??void 0},r=ks(n),o=n.decisionPool?_l(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,r),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>=Om;){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("; ")}`)}},Rl=512,Im=1024,Qr=class extends Error{constructor(){super(`conversation capacity reached (${Rl} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Tm(t){return{sessionStartOptions:e=>{if(e.startsWith(mn))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(mn)||t.set(e,n)}}}function Pm(t,e,n,r){let o=ks({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ao,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",...Tm(r)});return{clients:Rs(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var Zr=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${Es(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):Pm(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>=Rl;){let e=this.byCaller.keys().next();if(e.done)throw new Qr;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 Qr;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,Dn.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>=Im;){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 Q("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 eo="/inference-usage",El=25e3;var Cm=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function xl(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Cm.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 to=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${eo}`,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(El)})}catch(i){throw new me(`the uRun usage surface (POST ${eo}) could not be reached within ${El}ms: ${xl(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new he("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 me(`the uRun usage surface (POST ${eo}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new me(`the uRun usage surface (POST ${eo}) answered HTTP ${o.status} with a body that is not JSON: ${xl(i)}`)}return $i(s,this.opts.onRejectedRow)}};x();var Lm="/inference-ledger",Mm=1e4,no=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Os=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},Oe=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Is=class extends he{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Ts=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},$m=[["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",xs],["output_minutes",xs],["cost_nano_usd",xs],["price_version",t=>t===null||typeof t=="string"]];function Nm(t){for(let[e,n]of $m){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Um(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"}:Nm(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function xs(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function As(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Dm(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Al(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 Fm(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&&Al(t.started_at,n.started_at)&&Al(t.completed_at,n.completed_at)&&As(t.prompt_tokens,n.prompt_tokens)&&As(t.completion_tokens,n.completion_tokens)&&As(t.output_units,n.output_units)&&Dm(t.output_minutes,n.output_minutes)}function Hm(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(`
91
+ `)}async function jm(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(Hm(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Bm(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Oe(`${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 Oe(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new Oe(`${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 Oe(`${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 Oe(`${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 Oe(`${e} answered a non-string ${l}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new Oe(`${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 Oe(`${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 Oe(`${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 ro=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Lm}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await jm(n,this.opts.signing)}):JSON.stringify(n)}catch(l){throw new Oe(`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(Mm)})}catch(l){throw new Oe(`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=Um(l);throw d.status==="found"&&Fm(n,d.row)?new Os(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 no(`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 no(`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 Is("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 Ts(`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 Oe(`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 Oe(`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 Oe(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let u=Bm(a,`the uRun ledger surface at ${r}`);if(u.inference_id!==n.inference_id)throw new Oe(`the uRun ledger surface at ${r} answered for inference_id ${u.inference_id} when asked about ${n.inference_id}`);return u}};var qm=5e3,Gm=1e3,Wm=1500,Jm=3e3,Vm="/api/client-tokens";function oo(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Ol(t,e,n,r){oo(t,e,{error:{message:n,type:r}})}async function Km(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Vm}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Jm)});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 Cl(t){let e=t.resolver??new Gr({gatewayUrl:t.baseUrl}),n=t.machine?new Wr({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=new er(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,s=null,i=(()=>{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 k=new Pl.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),A=al({redis:k});return{registry:Vu({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:Xu({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(O,I)=>o?.onHostedChange(O,I)??(()=>()=>{}),roomDoc:(O,I)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(O,I)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(O,I)=>A.rows().then(U=>{let W=_o(U,I);return W?.warm_wait_s!==void 0?W.warm_wait_s*1e3:void 0})}),catalog:A,redis:k}})(),a=t.registry??new Xr({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry,pooler:t.pooler}),u=t.probeControlPlane??(()=>Km(t.baseUrl)),l=async()=>{let k=null;for(let O of a.decisionPools()){k=O;break}if(!k)return null;let A=k.stats();if(A.some(O=>O.draining))return{ok:!1,detail:"decision pool draining"};if(A.every(O=>O.attached===0&&O.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let E=await k.pingReady(Wm);return{ok:E,detail:E?"a decision slot answered its session ping":"no decision slot answered its session ping"}},d=t.usageClient??new to({apiUrl:t.apiUrl}),c=t.ledgerClient??new ro({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),p=process.env.URUN_SHARED_ORG_ID?.trim(),m=process.env.URUN_SHARED_ORG_API_KEY?.trim();p&&m&&(async()=>{try{await a.decisionWarmerFor({orgId:p,apiKey:m})?.warmFor(Cr)}catch(k){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(k instanceof Error?k.message:k)}
92
+ `)}})();let h=async k=>_s(Kr(k.headers.authorization),e,n),_=async k=>{let A=await h(k);if(A.billingAudience==="platform"&&A.creditsAdmissionOk===!1){let E=A.creditsRefusalReason;throw new Un(E==="spend_cap_reached"||E==="insufficient_credits"?E:void 0)}return A},S=k=>k instanceof he?{status:k.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:k instanceof Un?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...k.code!==void 0?{code:k.code}:{}}:k instanceof Xe?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:k.detail}:null,w=Eu({clients:async k=>a.clientsFor(await _(k)),usage:{authorize:k=>Kr(k.headers.authorization),lookup:(k,A)=>d.lookup(k,A)},statusOf:S,...t.requestLog?{requestLog:t.requestLog}:{},observe:k=>r.observe(k),ledger:{write:(k,A)=>c.write(Kr(k.headers.authorization),A),observe:k=>r.observeLedger(k),...t.ledgerLog?{report:t.ledgerLog}:{}}}),f=null,g=null,y=(0,Il.createServer)((k,A)=>{let E=new URL(k.url??"/","http://localhost");(async()=>{if(k.method==="GET"&&E.pathname==="/healthz"){oo(A,200,{ok:!0});return}if(k.method==="GET"&&E.pathname==="/readyz"){let U=Date.now();if((!f||U-f.at>=qm)&&(f={at:U,...await u()}),!g||U-g.at>=Gm){let te=await l();g=te===null?{at:U,ok:!0,detail:null}:{at:U,ok:te.ok,detail:te.detail}}let W=(f?.ready??!1)&&g.ok,K=g.detail===null?f?.detail??"control plane not yet probed":`${f?.detail??"control plane not yet probed"}; ${g.detail}`;oo(A,W?200:503,{ok:W,control_plane:K});return}if(k.method==="GET"&&E.pathname==="/lanez"){oo(A,200,{pools:i?await i.registry.status():null});return}let O=E.pathname==="/v1"||E.pathname.startsWith("/v1/"),I=E.pathname.startsWith("/partners/");if(!O&&!I){Ol(A,404,`no route for ${k.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}w(k,A)})().catch(O=>{if(!A.headersSent){Ol(A,500,String(O instanceof Error?O.message:O),"proxy_error");return}A.end()})}),v=t.conversations??new Zr({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry}),C=[Co(y,{authenticate:async k=>{let A=await _s(k,e,n),E=v.connectionFor(A);return{clients:E.clients,scope:Es(A.apiKey),onBindResumeHandle:E.bindResumeHandle,clientsForResume:E.clientsForResume,release:E.release}}}),qo(y,{clients:async k=>a.clientsFor(await _(k)),statusOf:S}).close,yr(y,{resolver:{resolve:async(k,A)=>{let E=await _(k),O=v.connectionFor(E),I;try{I=await Tu(as(O.clients,t.realtimeCompanions),Ou(k),A,Iu(k))}catch(W){throw O.release().catch(()=>{}),W}let U=I.release;return{...I,release:async()=>{await U?.(),await O.release()}}}}})];if(t.lane&&i){let k=t.lane,A=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=il(y,{verifyToken:(O,I)=>fs(O,I,k.tokenSecret,void 0,A),selfAddress:k.selfAddress,laneTenantOf:O=>i.redis.get(`lane_tenant:${O}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:A,hostRegistry:{setHost:(O,I)=>i.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(sl)),delHost:O=>i.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}`,k.selfAddress)}}),s=Bu(y,{verifyToken:(O,I)=>fs(O,I,k.tokenSecret,void 0,A),selfAddress:k.selfAddress,hostOf:async O=>{let I=await i.redis.get(`lane_hosts:${O}`);return I&&I.trim()!==""?I.trim():null},podToPodDial:(O,I,U)=>new Promise((W,K)=>{(async()=>{let te=await i.redis.get(`lane_tenant:${O}`),ne=Mn(O,k.tokenSecret,void 0,void 0,te||void 0),$e=`ws://${U}/stream/${encodeURIComponent(O)}/${encodeURIComponent(I)}?token=${encodeURIComponent(ne)}`,oe=new Tl.default($e,Hr(I));oe.once("open",()=>W(oe)),oe.once("error",K)})().catch(K)})});let E=i;C.push(async()=>{await o.close(),await s.close(),await E.registry.close(),E.redis.quit().catch(()=>{})})}y.on("upgrade",(k,A)=>{let E=new URL(k.url??"/","http://localhost");E.pathname===sr||E.pathname===jo||E.pathname===On||o!==null&&E.pathname.startsWith("/doc/")||s!==null&&E.pathname.startsWith("/stream/")||A.destroyed||(A.write(`HTTP/1.1 404 Not Found\r
93
93
  Connection: close\r
94
94
  \r
95
- no WS route for ${R.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),A.destroy())});let P=async()=>{for(let S of C)await S();await b.detachAll()};return{server:y,metricsServer:Di(r),metrics:r,edgeIdentityServer:ji(),registry:a,closeAll:()=>a.closeAll(),closeWebSockets:P}}async function Ll(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await Si()||ki(),await e()}function zm(){let t=null;return t=fi({streams:Qe.default,note:e=>{t?.isDead("stderr")!==!0&&Ze(Qe.default.stderr,e)}}),t}async function Ym(){zm();let t=Bi(Qe.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:s}=Cl(t);await new Promise((a,u)=>{e.once("error",u),e.listen(t.port,kt,a)}),await new Promise((a,u)=>{n.once("error",u),n.listen(Ro,kt,a)}),await new Promise((a,u)=>{r.once("error",u),r.listen(xo,kt,a)}),Qe.default.stdout.write(`inference-proxy listening on http://${kt}:${t.port}/v1 (metrics http://${kt}:${Ro}${Xn}, edge identity http://${kt}:${xo}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
95
+ no WS route for ${E.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),A.destroy())});let P=async()=>{for(let k of C)await k();await v.detachAll()};return{server:y,metricsServer:Di(r),metrics:r,edgeIdentityServer:ji(),registry:a,closeAll:()=>a.closeAll(),closeWebSockets:P}}async function Ll(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await Si()||ki(),await e()}function zm(){let t=null;return t=fi({streams:Qe.default,note:e=>{t?.isDead("stderr")!==!0&&Ze(Qe.default.stderr,e)}}),t}async function Ym(){zm();let t=Bi(Qe.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:s}=Cl(t);await new Promise((a,u)=>{e.once("error",u),e.listen(t.port,kt,a)}),await new Promise((a,u)=>{n.once("error",u),n.listen(Ro,kt,a)}),await new Promise((a,u)=>{r.once("error",u),r.listen(xo,kt,a)}),Qe.default.stdout.write(`inference-proxy listening on http://${kt}:${t.port}/v1 (metrics http://${kt}:${Ro}${Xn}, edge identity http://${kt}:${xo}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
96
96
  `);let i=async a=>{Qe.default.stdout.write(`inference-proxy: ${a} \u2014 draining
97
97
  `),await Ll(e,o,s),await new Promise(u=>n.close(()=>u())),await new Promise(u=>r.close(()=>u()))};await new Promise(a=>{Qe.default.once("SIGINT",()=>{i("SIGINT").finally(a)}),Qe.default.once("SIGTERM",()=>{i("SIGTERM").finally(a)})})}Ym().then(()=>Qe.default.exit(0),t=>{Qe.default.stderr.write(`inference-proxy: ${String(t instanceof Error?t.stack??t.message:t)}
98
98
  `),Qe.default.exit(1)});