@urun-sh/openai 0.6.54 → 0.6.56

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,102 +1,103 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Td=Object.create;var ci=Object.defineProperty;var Pd=Object.getOwnPropertyDescriptor;var Cd=Object.getOwnPropertyNames;var Ld=Object.getPrototypeOf,Md=Object.prototype.hasOwnProperty;var $d=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Nd=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Ud=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Cd(e))!Md.call(t,o)&&o!==n&&ci(t,o,{get:()=>e[o],enumerable:!(r=Pd(e,o))||r.enumerable});return t};var Ee=(t,e,n)=>(n=t!=null?Td(Ld(t)):{},Ud(e||!t||!t.__esModule?ci(n,"default",{value:t,enumerable:!0}):n,t));var O=$d(()=>{"use strict"});var fi=Nd(()=>{"use strict";O();var pi;(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(l,u){return function(d,c){Object.defineProperty(l,d,{configurable:!0,writable:!0,value:c}),u&&u(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",l={__proto__:[]}instanceof Array,u=!a&&!l,d={create:a?function(){return So(Object.create(null))}:l?function(){return So({__proto__:null})}:function(){return So({})},has:u?function(k,I){return r.call(k,I)}:function(k,I){return I in k},get:u?function(k,I){return r.call(k,I)?k[I]:void 0}:function(k,I){return k[I]}},c=Object.getPrototypeOf(Function),f=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Ed(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:xd(),m=typeof WeakMap=="function"?WeakMap:Ad(),w=o?Symbol.for("@reflect-metadata:registry"):void 0,E=Sd(),x=kd(E);function b(k,I,L,U){if(M(L)){if(!_n(k))throw new TypeError;if(!oi(I))throw new TypeError;return _(k,I)}else{if(!_n(k))throw new TypeError;if(!ue(I))throw new TypeError;if(!ue(U)&&!M(U)&&!ee(U))throw new TypeError;return ee(U)&&(U=void 0),L=$e(L),C(k,I,L,U)}}e("decorate",b);function v(k,I){function L(U,Y){if(!ue(U))throw new TypeError;if(!M(Y)&&!vd(Y))throw new TypeError;X(k,I,U,Y)}return L}e("metadata",v);function p(k,I,L,U){if(!ue(L))throw new TypeError;return M(U)||(U=$e(U)),X(k,I,L,U)}e("defineMetadata",p);function g(k,I,L){if(!ue(I))throw new TypeError;return M(L)||(L=$e(L)),$(k,I,L)}e("hasMetadata",g);function y(k,I,L){if(!ue(I))throw new TypeError;return M(L)||(L=$e(L)),N(k,I,L)}e("hasOwnMetadata",y);function S(k,I,L){if(!ue(I))throw new TypeError;return M(L)||(L=$e(L)),D(k,I,L)}e("getMetadata",S);function A(k,I,L){if(!ue(I))throw new TypeError;return M(L)||(L=$e(L)),q(k,I,L)}e("getOwnMetadata",A);function P(k,I){if(!ue(k))throw new TypeError;return M(I)||(I=$e(I)),G(k,I)}e("getMetadataKeys",P);function R(k,I){if(!ue(k))throw new TypeError;return M(I)||(I=$e(I)),re(k,I)}e("getOwnMetadataKeys",R);function T(k,I,L){if(!ue(I))throw new TypeError;if(M(L)||(L=$e(L)),!ue(I))throw new TypeError;M(L)||(L=$e(L));var U=vn(I,L,!1);return M(U)?!1:U.OrdinaryDeleteMetadata(k,I,L)}e("deleteMetadata",T);function _(k,I){for(var L=k.length-1;L>=0;--L){var U=k[L],Y=U(I);if(!M(Y)&&!ee(Y)){if(!oi(Y))throw new TypeError;I=Y}}return I}function C(k,I,L,U){for(var Y=k.length-1;Y>=0;--Y){var ve=k[Y],ke=ve(I,L,U);if(!M(ke)&&!ee(ke)){if(!ue(ke))throw new TypeError;U=ke}}return U}function $(k,I,L){var U=N(k,I,L);if(U)return!0;var Y=bo(I);return ee(Y)?!1:$(k,Y,L)}function N(k,I,L){var U=vn(I,L,!1);return M(U)?!1:Me(U.OrdinaryHasOwnMetadata(k,I,L))}function D(k,I,L){var U=N(k,I,L);if(U)return q(k,I,L);var Y=bo(I);if(!ee(Y))return D(k,Y,L)}function q(k,I,L){var U=vn(I,L,!1);if(!M(U))return U.OrdinaryGetOwnMetadata(k,I,L)}function X(k,I,L,U){var Y=vn(L,U,!0);Y.OrdinaryDefineOwnMetadata(k,I,L,U)}function G(k,I){var L=re(k,I),U=bo(k);if(U===null)return L;var Y=G(U,I);if(Y.length<=0)return L;if(L.length<=0)return Y;for(var ve=new h,ke=[],ne=0,B=L;ne<B.length;ne++){var W=B[ne],J=ve.has(W);J||(ve.add(W),ke.push(W))}for(var V=0,oe=Y;V<oe.length;V++){var W=oe[V],J=ve.has(W);J||(ve.add(W),ke.push(W))}return ke}function re(k,I){var L=vn(k,I,!1);return L?L.OrdinaryOwnMetadataKeys(k,I):[]}function K(k){if(k===null)return 1;switch(typeof k){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return k===null?1:6;default:return 6}}function M(k){return k===void 0}function ee(k){return k===null}function Fe(k){return typeof k=="symbol"}function ue(k){return typeof k=="object"?k!==null:typeof k=="function"}function ce(k,I){switch(K(k)){case 0:return k;case 1:return k;case 2:return k;case 3:return k;case 4:return k;case 5:return k}var L=I===3?"string":I===5?"number":"default",U=si(k,s);if(U!==void 0){var Y=U.call(k,L);if(ue(Y))throw new TypeError;return Y}return me(k,L==="default"?"number":L)}function me(k,I){if(I==="string"){var L=k.toString;if(at(L)){var U=L.call(k);if(!ue(U))return U}var Y=k.valueOf;if(at(Y)){var U=Y.call(k);if(!ue(U))return U}}else{var Y=k.valueOf;if(at(Y)){var U=Y.call(k);if(!ue(U))return U}var ve=k.toString;if(at(ve)){var U=ve.call(k);if(!ue(U))return U}}throw new TypeError}function Me(k){return!!k}function it(k){return""+k}function $e(k){var I=ce(k,3);return Fe(I)?I:it(I)}function _n(k){return Array.isArray?Array.isArray(k):k instanceof Object?k instanceof Array:Object.prototype.toString.call(k)==="[object Array]"}function at(k){return typeof k=="function"}function oi(k){return typeof k=="function"}function vd(k){switch(K(k)){case 3:return!0;case 4:return!0;default:return!1}}function vo(k,I){return k===I||k!==k&&I!==I}function si(k,I){var L=k[I];if(L!=null){if(!at(L))throw new TypeError;return L}}function ii(k){var I=si(k,i);if(!at(I))throw new TypeError;var L=I.call(k);if(!ue(L))throw new TypeError;return L}function ai(k){return k.value}function li(k){var I=k.next();return I.done?!1:I}function ui(k){var I=k.return;I&&I.call(k)}function bo(k){var I=Object.getPrototypeOf(k);if(typeof k!="function"||k===c||I!==c)return I;var L=k.prototype,U=L&&Object.getPrototypeOf(L);if(U==null||U===Object.prototype)return I;var Y=U.constructor;return typeof Y!="function"||Y===k?I:Y}function bd(){var k;!M(w)&&typeof n.Reflect<"u"&&!(w in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(k=Rd(n.Reflect));var I,L,U,Y=new m,ve={registerProvider:ke,getProvider:B,setProvider:J};return ve;function ke(V){if(!Object.isExtensible(ve))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case k===V:break;case M(I):I=V;break;case I===V:break;case M(L):L=V;break;case L===V:break;default:U===void 0&&(U=new h),U.add(V);break}}function ne(V,oe){if(!M(I)){if(I.isProviderFor(V,oe))return I;if(!M(L)){if(L.isProviderFor(V,oe))return I;if(!M(U))for(var pe=ii(U);;){var be=li(pe);if(!be)return;var Je=ai(be);if(Je.isProviderFor(V,oe))return ui(pe),Je}}}if(!M(k)&&k.isProviderFor(V,oe))return k}function B(V,oe){var pe=Y.get(V),be;return M(pe)||(be=pe.get(oe)),M(be)&&(be=ne(V,oe),M(be)||(M(pe)&&(pe=new f,Y.set(V,pe)),pe.set(oe,be))),be}function W(V){if(M(V))throw new TypeError;return I===V||L===V||!M(U)&&U.has(V)}function J(V,oe,pe){if(!W(pe))throw new Error("Metadata provider not registered.");var be=B(V,oe);if(be!==pe){if(!M(be))return!1;var Je=Y.get(V);M(Je)&&(Je=new f,Y.set(V,Je)),Je.set(oe,pe)}return!0}}function Sd(){var k;return!M(w)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&(k=n.Reflect[w]),M(k)&&(k=bd()),!M(w)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:k}),k}function kd(k){var I=new m,L={isProviderFor:function(W,J){var V=I.get(W);return M(V)?!1:V.has(J)},OrdinaryDefineOwnMetadata:ke,OrdinaryHasOwnMetadata:Y,OrdinaryGetOwnMetadata:ve,OrdinaryOwnMetadataKeys:ne,OrdinaryDeleteMetadata:B};return E.registerProvider(L),L;function U(W,J,V){var oe=I.get(W),pe=!1;if(M(oe)){if(!V)return;oe=new f,I.set(W,oe),pe=!0}var be=oe.get(J);if(M(be)){if(!V)return;if(be=new f,oe.set(J,be),!k.setProvider(W,J,L))throw oe.delete(J),pe&&I.delete(W),new Error("Wrong provider for target.")}return be}function Y(W,J,V){var oe=U(J,V,!1);return M(oe)?!1:Me(oe.has(W))}function ve(W,J,V){var oe=U(J,V,!1);if(!M(oe))return oe.get(W)}function ke(W,J,V,oe){var pe=U(V,oe,!0);pe.set(W,J)}function ne(W,J){var V=[],oe=U(W,J,!1);if(M(oe))return V;for(var pe=oe.keys(),be=ii(pe),Je=0;;){var di=li(be);if(!di)return V.length=Je,V;var Id=ai(di);try{V[Je]=Id}catch(Od){try{ui(be)}finally{throw Od}}Je++}}function B(W,J,V){var oe=U(J,V,!1);if(M(oe)||!oe.delete(W))return!1;if(oe.size===0){var pe=I.get(J);M(pe)||(pe.delete(V),pe.size===0&&I.delete(pe))}return!0}}function Rd(k){var I=k.defineMetadata,L=k.hasOwnMetadata,U=k.getOwnMetadata,Y=k.getOwnMetadataKeys,ve=k.deleteMetadata,ke=new m,ne={isProviderFor:function(B,W){var J=ke.get(B);return!M(J)&&J.has(W)?!0:Y(B,W).length?(M(J)&&(J=new h,ke.set(B,J)),J.add(W),!0):!1},OrdinaryDefineOwnMetadata:I,OrdinaryHasOwnMetadata:L,OrdinaryGetOwnMetadata:U,OrdinaryOwnMetadataKeys:Y,OrdinaryDeleteMetadata:ve};return ne}function vn(k,I,L){var U=E.getProvider(k,I);if(!M(U))return U;if(L){if(E.setProvider(k,I,x))return x;throw new Error("Illegal state.")}}function Ed(){var k={},I=[],L=(function(){function ne(B,W,J){this._index=0,this._keys=B,this._values=W,this._selector=J}return ne.prototype["@@iterator"]=function(){return this},ne.prototype[i]=function(){return this},ne.prototype.next=function(){var B=this._index;if(B>=0&&B<this._keys.length){var W=this._selector(this._keys[B],this._values[B]);return B+1>=this._keys.length?(this._index=-1,this._keys=I,this._values=I):this._index++,{value:W,done:!1}}return{value:void 0,done:!0}},ne.prototype.throw=function(B){throw this._index>=0&&(this._index=-1,this._keys=I,this._values=I),B},ne.prototype.return=function(B){return this._index>=0&&(this._index=-1,this._keys=I,this._values=I),{value:B,done:!0}},ne})(),U=(function(){function ne(){this._keys=[],this._values=[],this._cacheKey=k,this._cacheIndex=-2}return Object.defineProperty(ne.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ne.prototype.has=function(B){return this._find(B,!1)>=0},ne.prototype.get=function(B){var W=this._find(B,!1);return W>=0?this._values[W]:void 0},ne.prototype.set=function(B,W){var J=this._find(B,!0);return this._values[J]=W,this},ne.prototype.delete=function(B){var W=this._find(B,!1);if(W>=0){for(var J=this._keys.length,V=W+1;V<J;V++)this._keys[V-1]=this._keys[V],this._values[V-1]=this._values[V];return this._keys.length--,this._values.length--,vo(B,this._cacheKey)&&(this._cacheKey=k,this._cacheIndex=-2),!0}return!1},ne.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=k,this._cacheIndex=-2},ne.prototype.keys=function(){return new L(this._keys,this._values,Y)},ne.prototype.values=function(){return new L(this._keys,this._values,ve)},ne.prototype.entries=function(){return new L(this._keys,this._values,ke)},ne.prototype["@@iterator"]=function(){return this.entries()},ne.prototype[i]=function(){return this.entries()},ne.prototype._find=function(B,W){if(!vo(this._cacheKey,B)){this._cacheIndex=-1;for(var J=0;J<this._keys.length;J++)if(vo(this._keys[J],B)){this._cacheIndex=J;break}}return this._cacheIndex<0&&W&&(this._cacheIndex=this._keys.length,this._keys.push(B),this._values.push(void 0)),this._cacheIndex},ne})();return U;function Y(ne,B){return ne}function ve(ne,B){return B}function ke(ne,B){return[ne,B]}}function xd(){var k=(function(){function I(){this._map=new f}return Object.defineProperty(I.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),I.prototype.has=function(L){return this._map.has(L)},I.prototype.add=function(L){return this._map.set(L,L),this},I.prototype.delete=function(L){return this._map.delete(L)},I.prototype.clear=function(){this._map.clear()},I.prototype.keys=function(){return this._map.keys()},I.prototype.values=function(){return this._map.keys()},I.prototype.entries=function(){return this._map.entries()},I.prototype["@@iterator"]=function(){return this.keys()},I.prototype[i]=function(){return this.keys()},I})();return k}function Ad(){var k=16,I=d.create(),L=U();return(function(){function B(){this._key=U()}return B.prototype.has=function(W){var J=Y(W,!1);return J!==void 0?d.has(J,this._key):!1},B.prototype.get=function(W){var J=Y(W,!1);return J!==void 0?d.get(J,this._key):void 0},B.prototype.set=function(W,J){var V=Y(W,!0);return V[this._key]=J,this},B.prototype.delete=function(W){var J=Y(W,!1);return J!==void 0?delete J[this._key]:!1},B.prototype.clear=function(){this._key=U()},B})();function U(){var B;do B="@@WeakMap@@"+ne();while(d.has(I,B));return I[B]=!0,B}function Y(B,W){if(!r.call(B,L)){if(!W)return;Object.defineProperty(B,L,{value:d.create()})}return B[L]}function ve(B,W){for(var J=0;J<W;++J)B[J]=Math.random()*255|0;return B}function ke(B){if(typeof Uint8Array=="function"){var W=new Uint8Array(B);return typeof crypto<"u"?crypto.getRandomValues(W):typeof msCrypto<"u"?msCrypto.getRandomValues(W):ve(W,B),W}return ve(new Array(B),B)}function ne(){var B=ke(k);B[6]=B[6]&79|64,B[8]=B[8]&191|128;for(var W="",J=0;J<k;++J){var V=B[J];(J===4||J===6||J===8)&&(W+="-"),V<16&&(W+="0"),W+=V.toString(16).toLowerCase()}return W}}function So(k){return k.__=void 0,delete k.__,k}})})(pi||(pi={}))});O();var nS=Ee(fi(),1),et=Ee(require("process"),1);O();var cc=Ee(require("os"),1),pc=Ee(require("path"),1),fc=require("url"),mc=require("util");O();var $i=require("crypto");O();var he=class extends Error{},Dd=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Fd(t){if(typeof t!="string")return!1;let e=Dd.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 l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Bd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new he(`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 he(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new he(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new he(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new he(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new he(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new he(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",Fd(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new he(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new he(`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 he(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new he(`catalog "shared" block compliance carries "${l}" 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 Gt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function mi(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 he(`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 l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} 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 ko(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(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new he(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function hi(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 he(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Bd(await r.json())}O();function Ue(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}O();var Be=class extends Error{name="ModelPriceError"},Ro="per_million_input_tokens",Eo="per_million_output_tokens",yi="model_id,variant,unit,price_usd,effective_at,expires_at",gi={per_request:!0,per_minute:!0,per_output_unit:!0},Hd=5e3;function jd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new Be(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function wi(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new Be(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function qd(t,e,n){return t===null?null:wi(t,e,n)}function Gd(t,e){if(t===Ro)return"input";if(t===Eo)return"output";if(typeof t=="string"&&Object.hasOwn(gi,t))return null;throw new Be(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Ro} | ${Eo}) nor a known GPU-time unit (${Object.keys(gi).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 Wd(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 xo(t,e){return`${t}\0${e}`}function Jd(t){if(!Array.isArray(t))throw new Be(`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 Be(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of yi.split(","))if(!Object.hasOwn(s,u))throw new Be(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=Gd(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new Be(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new Be(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:jd(s.price_usd,o),effective_at:wi(s.effective_at,o,"effective_at"),expires_at:qd(s.expires_at,o,"expires_at")})}return e}function _i(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,h,m)=>{let w=f&&f.length>0?f:d?.[h];if(!w||w.length===0)return null;let E=Wd(w,h);return"reason"in E?E:E.rate.usd===0?h==="output"&&m!==null&&n?.has(xo(l,m))?E.rate:{reason:`the ${h} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:E.rate};for(let[f,h]of o.get(l)){let m=u.get(f),w=c(m?.input,"input",h),E=c(m?.output,"output",h);if(w!==null&&"reason"in w){i.push({model_id:l,variant:h,reason:w.reason});continue}if(E!==null&&"reason"in E){i.push({model_id:l,variant:h,reason:E.reason});continue}w===null||E===null||s.push({model_id:l,variant:h,pricing:{input:w.usd,output:E.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function bn(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 Sn={prices:[],refusals:[]};async function vi(t){let e=t.fetchImpl??fetch,n=`${Ro},${Eo}`,r=await e(`${t.catalogUrl}/model_prices?select=${yi}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Hd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Jd(await r.json())}O();var Rt="/partners/openrouter/models",Vd={chat:!0,code:!0,agent:!0,vl:!0},bi={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Kd(t){let e=t.toLowerCase();return Object.hasOwn(bi,e)?bi[e]:null}var Si={"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 zd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Si,o)?Si[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 ki={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Ri={2:"Llama2",3:"Llama3"};function Yd(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(ki,s))return ki[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Ri,i))return Ri[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Xd=["context_length","max_model_len"];function Qd(t){let e=Xd.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 rr(t){let e=t.map(Qd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Zd(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function Ao(t){if(t.length===0)return null;let e=t.map(Zd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Io(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 ec(t,e){let n=e.filter(s=>Ue(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return kn(n);let r=e.filter(s=>Ue(s.model_id)===t);if(r.length>0)return kn(r);let o=Io(t,e);return o.length>0?kn(o):null}function kn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:tc(t),matches:t}:null}function tc(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 mt=class extends Error{name="ModelCreatedError"};function Wt(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 mt(`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 mt(`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 mt(`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]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new mt(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function kt(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 or(t,e,n){let r=ec(t,e);if(!r)return kt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=rr(s),a=Wt(s),l=bn(o.model_id,o.variant,n),u=Ai(o,s),d=Ao(s);return kt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var nc=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Ai(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:[...nc],defect:o}:{published:[],defect:o}}function Oo(t){let e=t.length>0?kn(t):null;return e===null?{published:[],defect:null}:Ai(e.row,e.matches)}function Ei(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 xi(t){return{input:[{type:"prompt",unit:"token",cost_usd:Ei(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Ei(t.output)}]}}function rc(t,e,n,r){if(e.length===0)return null;let o=kn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Vd[s.task]!==!0)return null;let a=rr(i),l=bn(s.model_id,s.variant,n),u=Yd(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:Wt(i),quantization:Kd(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:xi(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:xi(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Ii(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?Gt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.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:zd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=rc(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}O();var Oi={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},Jt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Ti(t){let e=t.t;if(typeof e!="string"||!(e in Oi))throw new Jt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Oi).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 oc(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Jt(`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 Jt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Ti(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Jt(`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 Ti(t)}function Pi(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function sc(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 Ci(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 Pi(e);let s=o.next();if(e!==void 0&&await sc(s,e)==="aborted")throw s.catch(()=>{}),Pi(e);let i=await s;if(i.done)return;yield oc(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var ie=class extends Error{},te=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},Lo="credits_exhausted",Mo="insufficient_credits",Po="urs1.";function xn(t,e){return Po+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Et(t){if(!t.startsWith(Po))return null;try{let e=JSON.parse(Buffer.from(t.slice(Po.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 Ni(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 Li(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=lc(t);return e===null?[]:[e]}function ic(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 Md=Object.create;var mi=Object.defineProperty;var $d=Object.getOwnPropertyDescriptor;var Nd=Object.getOwnPropertyNames;var Ud=Object.getPrototypeOf,Dd=Object.prototype.hasOwnProperty;var Fd=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Bd=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Hd=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Nd(e))!Dd.call(t,o)&&o!==n&&mi(t,o,{get:()=>e[o],enumerable:!(r=$d(e,o))||r.enumerable});return t};var Ee=(t,e,n)=>(n=t!=null?Md(Ud(t)):{},Hd(e||!t||!t.__esModule?mi(n,"default",{value:t,enumerable:!0}):n,t));var T=Fd(()=>{"use strict"});var gi=Bd(()=>{"use strict";T();var hi;(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(l,u){return function(d,c){Object.defineProperty(l,d,{configurable:!0,writable:!0,value:c}),u&&u(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",l={__proto__:[]}instanceof Array,u=!a&&!l,d={create:a?function(){return Ro(Object.create(null))}:l?function(){return Ro({__proto__:null})}:function(){return Ro({})},has:u?function(k,I){return r.call(k,I)}:function(k,I){return I in k},get:u?function(k,I){return r.call(k,I)?k[I]:void 0}:function(k,I){return k[I]}},c=Object.getPrototypeOf(Function),f=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Td(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Od(),m=typeof WeakMap=="function"?WeakMap:Pd(),w=o?Symbol.for("@reflect-metadata:registry"):void 0,E=xd(),x=Ad(E);function v(k,I,L,D){if(N(L)){if(!vn(k))throw new TypeError;if(!ai(I))throw new TypeError;return b(k,I)}else{if(!vn(k))throw new TypeError;if(!ue(I))throw new TypeError;if(!ue(D)&&!N(D)&&!ee(D))throw new TypeError;return ee(D)&&(D=void 0),L=$e(L),C(k,I,L,D)}}e("decorate",v);function _(k,I){function L(D,Y){if(!ue(D))throw new TypeError;if(!N(Y)&&!Rd(Y))throw new TypeError;X(k,I,D,Y)}return L}e("metadata",_);function p(k,I,L,D){if(!ue(L))throw new TypeError;return N(D)||(D=$e(D)),X(k,I,L,D)}e("defineMetadata",p);function g(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),$(k,I,L)}e("hasMetadata",g);function y(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),M(k,I,L)}e("hasOwnMetadata",y);function S(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),U(k,I,L)}e("getMetadata",S);function A(k,I,L){if(!ue(I))throw new TypeError;return N(L)||(L=$e(L)),q(k,I,L)}e("getOwnMetadata",A);function P(k,I){if(!ue(k))throw new TypeError;return N(I)||(I=$e(I)),G(k,I)}e("getMetadataKeys",P);function R(k,I){if(!ue(k))throw new TypeError;return N(I)||(I=$e(I)),re(k,I)}e("getOwnMetadataKeys",R);function O(k,I,L){if(!ue(I))throw new TypeError;if(N(L)||(L=$e(L)),!ue(I))throw new TypeError;N(L)||(L=$e(L));var D=bn(I,L,!1);return N(D)?!1:D.OrdinaryDeleteMetadata(k,I,L)}e("deleteMetadata",O);function b(k,I){for(var L=k.length-1;L>=0;--L){var D=k[L],Y=D(I);if(!N(Y)&&!ee(Y)){if(!ai(Y))throw new TypeError;I=Y}}return I}function C(k,I,L,D){for(var Y=k.length-1;Y>=0;--Y){var ve=k[Y],ke=ve(I,L,D);if(!N(ke)&&!ee(ke)){if(!ue(ke))throw new TypeError;D=ke}}return D}function $(k,I,L){var D=M(k,I,L);if(D)return!0;var Y=ko(I);return ee(Y)?!1:$(k,Y,L)}function M(k,I,L){var D=bn(I,L,!1);return N(D)?!1:Me(D.OrdinaryHasOwnMetadata(k,I,L))}function U(k,I,L){var D=M(k,I,L);if(D)return q(k,I,L);var Y=ko(I);if(!ee(Y))return U(k,Y,L)}function q(k,I,L){var D=bn(I,L,!1);if(!N(D))return D.OrdinaryGetOwnMetadata(k,I,L)}function X(k,I,L,D){var Y=bn(L,D,!0);Y.OrdinaryDefineOwnMetadata(k,I,L,D)}function G(k,I){var L=re(k,I),D=ko(k);if(D===null)return L;var Y=G(D,I);if(Y.length<=0)return L;if(L.length<=0)return Y;for(var ve=new h,ke=[],ne=0,B=L;ne<B.length;ne++){var W=B[ne],J=ve.has(W);J||(ve.add(W),ke.push(W))}for(var V=0,oe=Y;V<oe.length;V++){var W=oe[V],J=ve.has(W);J||(ve.add(W),ke.push(W))}return ke}function re(k,I){var L=bn(k,I,!1);return L?L.OrdinaryOwnMetadataKeys(k,I):[]}function K(k){if(k===null)return 1;switch(typeof k){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return k===null?1:6;default:return 6}}function N(k){return k===void 0}function ee(k){return k===null}function Fe(k){return typeof k=="symbol"}function ue(k){return typeof k=="object"?k!==null:typeof k=="function"}function ce(k,I){switch(K(k)){case 0:return k;case 1:return k;case 2:return k;case 3:return k;case 4:return k;case 5:return k}var L=I===3?"string":I===5?"number":"default",D=li(k,s);if(D!==void 0){var Y=D.call(k,L);if(ue(Y))throw new TypeError;return Y}return me(k,L==="default"?"number":L)}function me(k,I){if(I==="string"){var L=k.toString;if(at(L)){var D=L.call(k);if(!ue(D))return D}var Y=k.valueOf;if(at(Y)){var D=Y.call(k);if(!ue(D))return D}}else{var Y=k.valueOf;if(at(Y)){var D=Y.call(k);if(!ue(D))return D}var ve=k.toString;if(at(ve)){var D=ve.call(k);if(!ue(D))return D}}throw new TypeError}function Me(k){return!!k}function it(k){return""+k}function $e(k){var I=ce(k,3);return Fe(I)?I:it(I)}function vn(k){return Array.isArray?Array.isArray(k):k instanceof Object?k instanceof Array:Object.prototype.toString.call(k)==="[object Array]"}function at(k){return typeof k=="function"}function ai(k){return typeof k=="function"}function Rd(k){switch(K(k)){case 3:return!0;case 4:return!0;default:return!1}}function So(k,I){return k===I||k!==k&&I!==I}function li(k,I){var L=k[I];if(L!=null){if(!at(L))throw new TypeError;return L}}function ui(k){var I=li(k,i);if(!at(I))throw new TypeError;var L=I.call(k);if(!ue(L))throw new TypeError;return L}function di(k){return k.value}function ci(k){var I=k.next();return I.done?!1:I}function pi(k){var I=k.return;I&&I.call(k)}function ko(k){var I=Object.getPrototypeOf(k);if(typeof k!="function"||k===c||I!==c)return I;var L=k.prototype,D=L&&Object.getPrototypeOf(L);if(D==null||D===Object.prototype)return I;var Y=D.constructor;return typeof Y!="function"||Y===k?I:Y}function Ed(){var k;!N(w)&&typeof n.Reflect<"u"&&!(w in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(k=Id(n.Reflect));var I,L,D,Y=new m,ve={registerProvider:ke,getProvider:B,setProvider:J};return ve;function ke(V){if(!Object.isExtensible(ve))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case k===V:break;case N(I):I=V;break;case I===V:break;case N(L):L=V;break;case L===V:break;default:D===void 0&&(D=new h),D.add(V);break}}function ne(V,oe){if(!N(I)){if(I.isProviderFor(V,oe))return I;if(!N(L)){if(L.isProviderFor(V,oe))return I;if(!N(D))for(var pe=ui(D);;){var be=ci(pe);if(!be)return;var Je=di(be);if(Je.isProviderFor(V,oe))return pi(pe),Je}}}if(!N(k)&&k.isProviderFor(V,oe))return k}function B(V,oe){var pe=Y.get(V),be;return N(pe)||(be=pe.get(oe)),N(be)&&(be=ne(V,oe),N(be)||(N(pe)&&(pe=new f,Y.set(V,pe)),pe.set(oe,be))),be}function W(V){if(N(V))throw new TypeError;return I===V||L===V||!N(D)&&D.has(V)}function J(V,oe,pe){if(!W(pe))throw new Error("Metadata provider not registered.");var be=B(V,oe);if(be!==pe){if(!N(be))return!1;var Je=Y.get(V);N(Je)&&(Je=new f,Y.set(V,Je)),Je.set(oe,pe)}return!0}}function xd(){var k;return!N(w)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&(k=n.Reflect[w]),N(k)&&(k=Ed()),!N(w)&&ue(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:k}),k}function Ad(k){var I=new m,L={isProviderFor:function(W,J){var V=I.get(W);return N(V)?!1:V.has(J)},OrdinaryDefineOwnMetadata:ke,OrdinaryHasOwnMetadata:Y,OrdinaryGetOwnMetadata:ve,OrdinaryOwnMetadataKeys:ne,OrdinaryDeleteMetadata:B};return E.registerProvider(L),L;function D(W,J,V){var oe=I.get(W),pe=!1;if(N(oe)){if(!V)return;oe=new f,I.set(W,oe),pe=!0}var be=oe.get(J);if(N(be)){if(!V)return;if(be=new f,oe.set(J,be),!k.setProvider(W,J,L))throw oe.delete(J),pe&&I.delete(W),new Error("Wrong provider for target.")}return be}function Y(W,J,V){var oe=D(J,V,!1);return N(oe)?!1:Me(oe.has(W))}function ve(W,J,V){var oe=D(J,V,!1);if(!N(oe))return oe.get(W)}function ke(W,J,V,oe){var pe=D(V,oe,!0);pe.set(W,J)}function ne(W,J){var V=[],oe=D(W,J,!1);if(N(oe))return V;for(var pe=oe.keys(),be=ui(pe),Je=0;;){var fi=ci(be);if(!fi)return V.length=Je,V;var Cd=di(fi);try{V[Je]=Cd}catch(Ld){try{pi(be)}finally{throw Ld}}Je++}}function B(W,J,V){var oe=D(J,V,!1);if(N(oe)||!oe.delete(W))return!1;if(oe.size===0){var pe=I.get(J);N(pe)||(pe.delete(V),pe.size===0&&I.delete(pe))}return!0}}function Id(k){var I=k.defineMetadata,L=k.hasOwnMetadata,D=k.getOwnMetadata,Y=k.getOwnMetadataKeys,ve=k.deleteMetadata,ke=new m,ne={isProviderFor:function(B,W){var J=ke.get(B);return!N(J)&&J.has(W)?!0:Y(B,W).length?(N(J)&&(J=new h,ke.set(B,J)),J.add(W),!0):!1},OrdinaryDefineOwnMetadata:I,OrdinaryHasOwnMetadata:L,OrdinaryGetOwnMetadata:D,OrdinaryOwnMetadataKeys:Y,OrdinaryDeleteMetadata:ve};return ne}function bn(k,I,L){var D=E.getProvider(k,I);if(!N(D))return D;if(L){if(E.setProvider(k,I,x))return x;throw new Error("Illegal state.")}}function Td(){var k={},I=[],L=(function(){function ne(B,W,J){this._index=0,this._keys=B,this._values=W,this._selector=J}return ne.prototype["@@iterator"]=function(){return this},ne.prototype[i]=function(){return this},ne.prototype.next=function(){var B=this._index;if(B>=0&&B<this._keys.length){var W=this._selector(this._keys[B],this._values[B]);return B+1>=this._keys.length?(this._index=-1,this._keys=I,this._values=I):this._index++,{value:W,done:!1}}return{value:void 0,done:!0}},ne.prototype.throw=function(B){throw this._index>=0&&(this._index=-1,this._keys=I,this._values=I),B},ne.prototype.return=function(B){return this._index>=0&&(this._index=-1,this._keys=I,this._values=I),{value:B,done:!0}},ne})(),D=(function(){function ne(){this._keys=[],this._values=[],this._cacheKey=k,this._cacheIndex=-2}return Object.defineProperty(ne.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ne.prototype.has=function(B){return this._find(B,!1)>=0},ne.prototype.get=function(B){var W=this._find(B,!1);return W>=0?this._values[W]:void 0},ne.prototype.set=function(B,W){var J=this._find(B,!0);return this._values[J]=W,this},ne.prototype.delete=function(B){var W=this._find(B,!1);if(W>=0){for(var J=this._keys.length,V=W+1;V<J;V++)this._keys[V-1]=this._keys[V],this._values[V-1]=this._values[V];return this._keys.length--,this._values.length--,So(B,this._cacheKey)&&(this._cacheKey=k,this._cacheIndex=-2),!0}return!1},ne.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=k,this._cacheIndex=-2},ne.prototype.keys=function(){return new L(this._keys,this._values,Y)},ne.prototype.values=function(){return new L(this._keys,this._values,ve)},ne.prototype.entries=function(){return new L(this._keys,this._values,ke)},ne.prototype["@@iterator"]=function(){return this.entries()},ne.prototype[i]=function(){return this.entries()},ne.prototype._find=function(B,W){if(!So(this._cacheKey,B)){this._cacheIndex=-1;for(var J=0;J<this._keys.length;J++)if(So(this._keys[J],B)){this._cacheIndex=J;break}}return this._cacheIndex<0&&W&&(this._cacheIndex=this._keys.length,this._keys.push(B),this._values.push(void 0)),this._cacheIndex},ne})();return D;function Y(ne,B){return ne}function ve(ne,B){return B}function ke(ne,B){return[ne,B]}}function Od(){var k=(function(){function I(){this._map=new f}return Object.defineProperty(I.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),I.prototype.has=function(L){return this._map.has(L)},I.prototype.add=function(L){return this._map.set(L,L),this},I.prototype.delete=function(L){return this._map.delete(L)},I.prototype.clear=function(){this._map.clear()},I.prototype.keys=function(){return this._map.keys()},I.prototype.values=function(){return this._map.keys()},I.prototype.entries=function(){return this._map.entries()},I.prototype["@@iterator"]=function(){return this.keys()},I.prototype[i]=function(){return this.keys()},I})();return k}function Pd(){var k=16,I=d.create(),L=D();return(function(){function B(){this._key=D()}return B.prototype.has=function(W){var J=Y(W,!1);return J!==void 0?d.has(J,this._key):!1},B.prototype.get=function(W){var J=Y(W,!1);return J!==void 0?d.get(J,this._key):void 0},B.prototype.set=function(W,J){var V=Y(W,!0);return V[this._key]=J,this},B.prototype.delete=function(W){var J=Y(W,!1);return J!==void 0?delete J[this._key]:!1},B.prototype.clear=function(){this._key=D()},B})();function D(){var B;do B="@@WeakMap@@"+ne();while(d.has(I,B));return I[B]=!0,B}function Y(B,W){if(!r.call(B,L)){if(!W)return;Object.defineProperty(B,L,{value:d.create()})}return B[L]}function ve(B,W){for(var J=0;J<W;++J)B[J]=Math.random()*255|0;return B}function ke(B){if(typeof Uint8Array=="function"){var W=new Uint8Array(B);return typeof crypto<"u"?crypto.getRandomValues(W):typeof msCrypto<"u"?msCrypto.getRandomValues(W):ve(W,B),W}return ve(new Array(B),B)}function ne(){var B=ke(k);B[6]=B[6]&79|64,B[8]=B[8]&191|128;for(var W="",J=0;J<k;++J){var V=B[J];(J===4||J===6||J===8)&&(W+="-"),V<16&&(W+="0"),W+=V.toString(16).toLowerCase()}return W}}function Ro(k){return k.__=void 0,delete k.__,k}})})(hi||(hi={}))});T();var iS=Ee(gi(),1),et=Ee(require("process"),1);T();var hc=Ee(require("os"),1),gc=Ee(require("path"),1),yc=require("url"),wc=require("util");T();var Di=require("crypto");T();var he=class extends Error{},jd=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function qd(t){if(typeof t!="string")return!1;let e=jd.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 l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Gd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new he(`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 he(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new he(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new he(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new he(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new he(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new he(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",qd(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new he(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new he(`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 he(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new he(`catalog "shared" block compliance carries "${l}" 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 Wt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function yi(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 he(`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 l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} 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 Eo(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(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new he(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function wi(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 he(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Gd(await r.json())}T();function Ue(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}T();var Be=class extends Error{name="ModelPriceError"},xo="per_million_input_tokens",Ao="per_million_output_tokens",vi="model_id,variant,unit,price_usd,effective_at,expires_at",_i={per_request:!0,per_minute:!0,per_output_unit:!0},Wd=5e3;function Jd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new Be(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function bi(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new Be(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Vd(t,e,n){return t===null?null:bi(t,e,n)}function Kd(t,e){if(t===xo)return"input";if(t===Ao)return"output";if(typeof t=="string"&&Object.hasOwn(_i,t))return null;throw new Be(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${xo} | ${Ao}) nor a known GPU-time unit (${Object.keys(_i).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 zd(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 Io(t,e){return`${t}\0${e}`}function Yd(t){if(!Array.isArray(t))throw new Be(`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 Be(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of vi.split(","))if(!Object.hasOwn(s,u))throw new Be(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=Kd(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new Be(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new Be(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Jd(s.price_usd,o),effective_at:bi(s.effective_at,o,"effective_at"),expires_at:Vd(s.expires_at,o,"expires_at")})}return e}function Si(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,h,m)=>{let w=f&&f.length>0?f:d?.[h];if(!w||w.length===0)return null;let E=zd(w,h);return"reason"in E?E:E.rate.usd===0?h==="output"&&m!==null&&n?.has(Io(l,m))?E.rate:{reason:`the ${h} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:E.rate};for(let[f,h]of o.get(l)){let m=u.get(f),w=c(m?.input,"input",h),E=c(m?.output,"output",h);if(w!==null&&"reason"in w){i.push({model_id:l,variant:h,reason:w.reason});continue}if(E!==null&&"reason"in E){i.push({model_id:l,variant:h,reason:E.reason});continue}w===null||E===null||s.push({model_id:l,variant:h,pricing:{input:w.usd,output:E.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function Sn(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 kn={prices:[],refusals:[]};async function ki(t){let e=t.fetchImpl??fetch,n=`${xo},${Ao}`,r=await e(`${t.catalogUrl}/model_prices?select=${vi}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Wd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Yd(await r.json())}T();var Rt="/partners/openrouter/models",Xd={chat:!0,code:!0,agent:!0,vl:!0},Ri={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Qd(t){let e=t.toLowerCase();return Object.hasOwn(Ri,e)?Ri[e]:null}var Ei={"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 Zd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Ei,o)?Ei[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 xi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Ai={2:"Llama2",3:"Llama3"};function ec(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(xi,s))return xi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Ai,i))return Ai[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var tc=["context_length","max_model_len"];function nc(t){let e=tc.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 or(t){let e=t.map(nc),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function rc(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function To(t){if(t.length===0)return null;let e=t.map(rc),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Oo(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 oc(t,e){let n=e.filter(s=>Ue(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Rn(n);let r=e.filter(s=>Ue(s.model_id)===t);if(r.length>0)return Rn(r);let o=Oo(t,e);return o.length>0?Rn(o):null}function Rn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:sc(t),matches:t}:null}function sc(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 mt=class extends Error{name="ModelCreatedError"};function Jt(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 mt(`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 mt(`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 mt(`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]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new mt(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function kt(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 sr(t,e,n){let r=oc(t,e);if(!r)return kt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=or(s),a=Jt(s),l=Sn(o.model_id,o.variant,n),u=Oi(o,s),d=To(s);return kt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var ic=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Oi(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:[...ic],defect:o}:{published:[],defect:o}}function Po(t){let e=t.length>0?Rn(t):null;return e===null?{published:[],defect:null}:Oi(e.row,e.matches)}function Ii(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 Ti(t){return{input:[{type:"prompt",unit:"token",cost_usd:Ii(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Ii(t.output)}]}}function ac(t,e,n,r){if(e.length===0)return null;let o=Rn(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Xd[s.task]!==!0)return null;let a=or(i),l=Sn(s.model_id,s.variant,n),u=ec(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:Jt(i),quantization:Qd(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:Ti(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:Ti(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Pi(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?Wt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.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:Zd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=ac(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}T();var Ci={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},Vt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Li(t){let e=t.t;if(typeof e!="string"||!(e in Ci))throw new Vt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Ci).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 lc(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Vt(`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 Vt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Li(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Vt(`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 Li(t)}function Mi(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function uc(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 $i(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 Mi(e);let s=o.next();if(e!==void 0&&await uc(s,e)==="aborted")throw s.catch(()=>{}),Mi(e);let i=await s;if(i.done)return;yield lc(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var ie=class extends Error{},te=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},$o="credits_exhausted",No="insufficient_credits",Lo="urs1.";function An(t,e){return Lo+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Et(t){if(!t.startsWith(Lo))return null;try{let e=JSON.parse(Buffer.from(t.slice(Lo.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 Fi(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 Ni(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=pc(t);return e===null?[]:[e]}function dc(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
3
3
  `),null;let e={},n=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],r=!1;for(let[o,s]of n){let i=t[o];if(i==null)continue;let a=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(a)||a<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
4
- `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function $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||Ue(`${r.model_id}-${r.variant}`)===e.appSlug||Ue(r.model_id)===e.appSlug)),n?ic(n.engine_args?.pool):null}function To(t,e,n,r,o){if(!o)throw new he(`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 he(`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 he(`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 Mi(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 he(`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 Ui="shared:",Vt="speech:",yt="realtime:";function gt(t){return t.sharedApp?Ui+t.appSlug:t.appSlug}function En(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 Co(t,e){let n=e.filter(s=>Ue(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>Ue(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function ac(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function lc(t){let e=t.map(ac),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var uc={stt:"stt",tts:"tts"};function ht(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:uc[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=Co(t,e);return n.length>0?n:Io(t,e)}function Rn(t,e){return Di(t.appSlug,e)}function dc(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 he(`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 sr=6e4,ir=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;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.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??sr):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??sr):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??sr):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??sr;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 Be)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
- `),Sn}let r=_i(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
6
- `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(xo(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(Ui)||o.startsWith(Vt)||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 ie(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=ko(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=Ue(s),l=n.endpoints.filter(c=>Ue(c.model_id)===a&&(i===void 0||c.variant===i)),u=new Set(l.map(c=>c.model_id)),d=[...u][0];return d===void 0||u.size!==1?null:ko(n,d,i)}async resolveTarget(e){let n=await this.dialTargetFor(e);return this.opts.callerOrgId&&(n.callerOrgId=this.opts.callerOrgId),n}async dialTargetFor(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};n=n.replace(/^urun\//i,"");let o=Ue(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 l=a.filter(d=>d.startsWith(`${o}-`));if(l.length===1)return{appSlug:l[0]};if(l.length>1)throw new ie(`model "${n}" is ambiguous across deployed apps ${l.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new ie(`model "${n}" maps to app "${u.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let a=(await this.opts.listCatalog()).find(l=>n===l.model_id||n===`${l.model_id}:${l.variant}`||o===Ue(l.model_id)||o===Ue(`${l.model_id}-${l.variant}`));if(a)throw new ie(`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=En(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 gt(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,gt(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return En(await this.resolveTarget(e))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Vt+gt(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,yt+(0,$i.randomUUID)())}async evictHandle(e){let n=Et(e);if(!n)return;let r=this.pool.get(n.app);if(!r)return;let o=await r.then(s=>s,()=>null);o!==null&&await this.evict(n.app,o)}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.then(o=>this.snapshotMintId(o),()=>{}),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:En(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:xn(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:xn(n,this.keyOf(r))}}async sessionForHandle(e){let n=Et(e);if(!n)throw new te(`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 te(`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&&this.mintedIds.get(i)!==o)throw new te(`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(u=>({ok:!0,rows:u}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:Sn;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
7
- `);let l=(n?Gt(n):[]).map(u=>{let d=s.filter(x=>x.model_id===u.model_id&&x.variant===u.variant),c=rr(d),f=Wt(d),h=Ao(d),m=bn(u.model_id,u.variant,i),w=Oo(d);return kt({id:`${u.model_id}:${u.variant}`,object:"model",created:f,owned_by:"urun",...c!==null?{context_length:c}:{},...m!==null?{pricing:m}:{},...w.published.length>0?{voices:[...w.published]}:{},...h!==null?{capabilities:{reasoning:h}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?l:[...e.map(u=>or(u,s,i)),...l]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Ii(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let s=To(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Mi(`${r.modelId}:${r.variant}`,s).includes(n)}return Li(Co(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ht(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:ht(Rn(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ht(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":ht(Rn(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ht(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":ht(Rn(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):Rn(n,r);return dc(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):Rn(n,r);return Oo(o)}async imageModelList(){let e=await this.catalogRows(),n=Sn,r=[];for(let s of await this.availableIds()){let i=Li(Co(s,e));i.length!==0&&r.push(kt({...or(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of Gt(o)){let i=To(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Mi(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let l=kt({id:`${s.model_id}:${s.variant}`,object:"model",created:Wt(i),owned_by:"urun",image_modes:a});r.push(l)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=Sn,r=[];for(let s of await this.availableIds())ht(Di(s,e))==="stt"&&r.push(or(s,e,n));let o=await this.sharedBlock();if(o)for(let s of Gt(o)){let i=To(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(ht(i)!=="stt")continue;let a=kt({id:`${s.model_id}:${s.variant}`,object:"model",created:Wt(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 Fi(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 ar(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 hc=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Bi(t){let e=t?.code;return typeof e=="string"&&hc.has(e)}function tt(t,e){try{return t.write(e),!0}catch(n){if(Bi(n))return!1;throw n}}function Hi(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Bi(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)}}}O();var _e=require("@prometheus-io/client"),da=require("http");O();var gc={"/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","/v1/realtime":"realtime"};function yc(t){return gc[t]??null}var Gi=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function wc(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function _c(t){return t==="surface"}function vc(t){let e=t?.ledgerFailureReason;return Gi.includes(e)?e:"unknown"}var bc=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ji=["priced","unpriced"],Sc={written:ji,already_written:ji,skipped:bc,failed:Gi},Wi=Object.entries(Sc).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function kc(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Rc(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 Ec=256,qi=4096,An=12e4,xc=250,Ac=8e3,lt=[],No=new Set,In=0,Kt=!1;function Ji(){return lt.length}function Vi(t=Date.now()){let e=lt[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var lr=new Set;function Ki(){return In===0&&lt.length===0}function zi(){if(Ki()){Kt=!1;for(let t of[...lr])t()}}async function Yi(t=Qi){return Ki()?!0:await new Promise(e=>{let n,r=()=>{lr.delete(r),clearTimeout(n),e(!0)};lr.add(r),n=setTimeout(()=>{lr.delete(r),e(!1)},t),n.unref?.()})}function Xi(){Kt=!0;let t=[...lt.splice(0,lt.length),...No];for(let e of t)e.settled||At(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 ${Qi}ms drain \u2014 the request was served and answered, and its billing row was never written`});return zi(),t.length}var Qi=5e3;function Zi(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
9
- `}function Ic(t){tt(process.stdout,t)}function ea(t,e){try{t(e)}catch{}}function ur(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Ic,o=yc(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),ea(r,Zi("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 l;if(a.kind==="catalog")l={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}l={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let u={inference_id:e.inference_id,...l,task:o,http_status:e.status,started_at:Rc(e),completed_at:e.ts,billable_outcome:kc(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,session_seconds:e.session_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(lt.length>=qi){i("queue_full",`${lt.length} ledger writes are already waiting (capacity ${qi}, ${In} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}lt.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),In<Ec&&(In+=1,Oc())}async function Oc(){try{for(;;){let t=Tc();if(t===void 0)return;No.add(t);try{await Pc(t)}finally{No.delete(t)}}}finally{In-=1,zi()}}function Tc(){let t=Date.now();for(;;){let e=lt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<An)return e;At(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 ${An}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 Pc(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);At(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=wc(o);if(s!==null){At(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=vc(o),a=Date.now()-t.queuedAt;if(Kt){At(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(_c(i)&&a<An){if(await Lc(Cc(t.attempts)),Kt||Date.now()-t.queuedAt>=An){let l=Date.now()-t.queuedAt;At(t,{outcome:"failed",reason:Kt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Kt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:l,error:`this row's backoff outlived the ${An}ms dwell bound (waited ${l}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}At(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 Cc(t){return Math.min(Ac,xc*2**Math.max(0,t-1))}function Lc(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function At(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;ea(t.report,Zi(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}O();O();var cr="/v1/usage/requests",ta=1e4,Mc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,wt=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},we=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},dr=class extends we{constructor(e){super(e),this.name="UsageWithholdingError"}},sa=1024*1024;function Fo(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new wt(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new wt(`"${e}" must be an array of uuid strings`);if(n.length>ta)throw new wt(`"${e}" carries ${n.length} ids; at most ${ta} 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"||!Mc.test(s))throw new wt(`"${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 ia(t){return Fo(t,"inference_ids")}var $c=["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 zt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new we(`${n}: ${e} is not a non-empty string (got ${Xt(r)})`);return r}function Uo(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new we(`${n}: ${e} is neither null nor a non-empty string (got ${Xt(r)})`);return r}function Yt(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 we(`${n}: ${e} is not a number (got ${Xt(o)})`);if(r&&!Number.isSafeInteger(s))throw new we(`${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 we(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Nc=40,na=64,ra=600;function aa(t){let e=Object.keys(t).sort(),r=e.slice(0,Nc).map(o=>o.length>na?`${o.slice(0,na)}\u2026`:o).join(", ");return r.length>ra&&(r=`${r.slice(0,ra)}\u2026`),`${e.length} keys present: [${r}]`}function Xt(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function Do(t){tt(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
10
- `)}function Uc(t,e){let n;try{n=t(e)}catch{oa(t,e);return}Dc(n)&&Promise.resolve(n).catch(()=>{oa(t,e)})}function Dc(t){return typeof t?.then=="function"}function oa(t,e){if(t!==Do)try{Do(e)}catch{}}function la(t,e=Do){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?aa(t):Xt(t);throw new we(`the usage surface answered without a "requests" array: got ${Xt(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Fc(n[o],s))}catch(i){if(i instanceof dr||!(i instanceof we))throw i;Uc(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new we(`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 Fc(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new we(`${e} is not an object: got ${Xt(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new dr(`${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 $c)if(!Object.hasOwn(n,o))throw new we(`${e} has no "${o}" column (${aa(n)})`);let r=Yt(n,"http_status",e,!0);if(r===null)throw new we(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:zt(n,"inference_id",e),model_id:zt(n,"model_id",e),identity_kind:zt(n,"identity_kind",e),variant:Uo(n,"variant",e),task:zt(n,"task",e),http_status:r,started_at:zt(n,"started_at",e),completed_at:zt(n,"completed_at",e),prompt_tokens:Yt(n,"prompt_tokens",e,!0),completion_tokens:Yt(n,"completion_tokens",e,!0),output_units:Yt(n,"output_units",e,!1),output_minutes:Yt(n,"output_minutes",e,!1),cost_nano_usd:Yt(n,"cost_nano_usd",e,!0),price_version:Uo(n,"price_version",e),priced_at:Uo(n,"priced_at",e)}}function pr(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 we(`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 we(`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 On="/partners/huggingface/v1/billing/requests";function Bc(t){return Fo(t,"requestIds")}function Hc(t){return t>=200&&t<=399}function jc(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Hc(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function ua(t,e){let n=Bc(t),r=await e(n);return pr(r,n),jc(r)}var Bo=9464,fr="/metrics",mr="(other)",qc="(none)",Gc=64,Wc=128,Jc=["/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",cr,On,Rt],Vc=new Set(Jc);function Kc(t){return Vc.has(t)?t:mr}function zc(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var hr=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?qc:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,mr):(this.admitted.add(e),e):mr}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},gr=class{registry=new _e.Registry;modelLabel=new hr(Gc);orgLabel=new hr(Wc);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new _e.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 _e.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 _e.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 _e.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 _e.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 _e.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 _e.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 Wi)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new _e.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"},Ji()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Vi()/1e3)}}),this.labelCardinality=new _e.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 _e.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 _e.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 _e.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 _e.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 _e.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 _e.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,_e.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=Kc(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 l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?mr:e.method,status_class:zc(e.status),stream:l,model:s,org:i}),this.duration.observe({lane:n,stream:l,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 ca(t){return(0,da.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==fr){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${fr}
4
+ `),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function Uo(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||Ue(`${r.model_id}-${r.variant}`)===e.appSlug||Ue(r.model_id)===e.appSlug)),n?dc(n.engine_args?.pool):null}function Co(t,e,n,r,o){if(!o)throw new he(`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 he(`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 he(`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 Ui(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 he(`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 Bi="shared:",Kt="speech:",yt="realtime:";function gt(t){return t.sharedApp?Bi+t.appSlug:t.appSlug}function xn(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 Mo(t,e){let n=e.filter(s=>Ue(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>Ue(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function cc(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function pc(t){let e=t.map(cc),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var fc={stt:"stt",tts:"tts"};function ht(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:fc[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Hi(t,e){let n=Mo(t,e);return n.length>0?n:Oo(t,e)}function En(t,e){return Hi(t.appSlug,e)}function mc(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 he(`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 ir=6e4,ar=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;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.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??ir):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??ir):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??ir):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??ir;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 Be)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
+ `),kn}let r=Si(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
6
+ `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(Io(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(Bi)||o.startsWith(Kt)||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 ie(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=Eo(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=Ue(s),l=n.endpoints.filter(c=>Ue(c.model_id)===a&&(i===void 0||c.variant===i)),u=new Set(l.map(c=>c.model_id)),d=[...u][0];return d===void 0||u.size!==1?null:Eo(n,d,i)}async resolveTarget(e){let n=await this.dialTargetFor(e);return this.opts.callerOrgId&&(n.callerOrgId=this.opts.callerOrgId),n}async dialTargetFor(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};n=n.replace(/^urun\//i,"");let o=Ue(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 l=a.filter(d=>d.startsWith(`${o}-`));if(l.length===1)return{appSlug:l[0]};if(l.length>1)throw new ie(`model "${n}" is ambiguous across deployed apps ${l.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new ie(`model "${n}" maps to app "${u.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let a=(await this.opts.listCatalog()).find(l=>n===l.model_id||n===`${l.model_id}:${l.variant}`||o===Ue(l.model_id)||o===Ue(`${l.model_id}-${l.variant}`));if(a)throw new ie(`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=xn(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return Uo(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return gt(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,gt(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return xn(await this.resolveTarget(e))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Kt+gt(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,yt+(0,Di.randomUUID)())}async evictHandle(e){let n=Et(e);if(!n)return;let r=this.pool.get(n.app);if(!r)return;let o=await r.then(s=>s,()=>null);o!==null&&await this.evict(n.app,o)}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.then(o=>this.snapshotMintId(o),()=>{}),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:xn(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:An(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:An(n,this.keyOf(r))}}async sessionForHandle(e){let n=Et(e);if(!n)throw new te(`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 te(`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&&this.mintedIds.get(i)!==o)throw new te(`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(u=>({ok:!0,rows:u}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:kn;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
7
+ `);let l=(n?Wt(n):[]).map(u=>{let d=s.filter(x=>x.model_id===u.model_id&&x.variant===u.variant),c=or(d),f=Jt(d),h=To(d),m=Sn(u.model_id,u.variant,i),w=Po(d);return kt({id:`${u.model_id}:${u.variant}`,object:"model",created:f,owned_by:"urun",...c!==null?{context_length:c}:{},...m!==null?{pricing:m}:{},...w.published.length>0?{voices:[...w.published]}:{},...h!==null?{capabilities:{reasoning:h}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?l:[...e.map(u=>sr(u,s,i)),...l]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Pi(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=Co(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Ui(`${r.modelId}:${r.variant}`,s).includes(n)}return Ni(Mo(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ht(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:ht(En(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ht(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":ht(En(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ht(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":ht(En(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):En(n,r);return mc(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):En(n,r);return Po(o)}async imageModelList(){let e=await this.catalogRows(),n=kn,r=[];for(let s of await this.availableIds()){let i=Ni(Mo(s,e));i.length!==0&&r.push(kt({...sr(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of Wt(o)){let i=Co(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Ui(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let l=kt({id:`${s.model_id}:${s.variant}`,object:"model",created:Jt(i),owned_by:"urun",image_modes:a});r.push(l)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=kn,r=[];for(let s of await this.availableIds())ht(Hi(s,e))==="stt"&&r.push(sr(s,e,n));let o=await this.sharedBlock();if(o)for(let s of Wt(o)){let i=Co(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(ht(i)!=="stt")continue;let a=kt({id:`${s.model_id}:${s.variant}`,object:"model",created:Jt(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 ji(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 lr(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 _c=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function qi(t){let e=t?.code;return typeof e=="string"&&_c.has(e)}function tt(t,e){try{return t.write(e),!0}catch(n){if(qi(n))return!1;throw n}}function Gi(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{qi(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)}}}T();var _e=require("@prometheus-io/client"),fa=require("http");T();var vc={"/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","/v1/realtime":"realtime"};function bc(t){return vc[t]??null}var Vi=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Sc(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function kc(t){return t==="surface"}function Rc(t){let e=t?.ledgerFailureReason;return Vi.includes(e)?e:"unknown"}var Ec=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Wi=["priced","unpriced"],xc={written:Wi,already_written:Wi,skipped:Ec,failed:Vi},Ki=Object.entries(xc).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Ac(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Ic(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 Tc=256,Ji=4096,In=12e4,Oc=250,Pc=8e3,lt=[],Do=new Set,Tn=0,zt=!1;function zi(){return lt.length}function Yi(t=Date.now()){let e=lt[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var ur=new Set;function Xi(){return Tn===0&&lt.length===0}function Qi(){if(Xi()){zt=!1;for(let t of[...ur])t()}}async function Zi(t=ta){return Xi()?!0:await new Promise(e=>{let n,r=()=>{ur.delete(r),clearTimeout(n),e(!0)};ur.add(r),n=setTimeout(()=>{ur.delete(r),e(!1)},t),n.unref?.()})}function ea(){zt=!0;let t=[...lt.splice(0,lt.length),...Do];for(let e of t)e.settled||At(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 ${ta}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Qi(),t.length}var ta=5e3;function na(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
9
+ `}function Cc(t){tt(process.stdout,t)}function ra(t,e){try{t(e)}catch{}}function dr(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Cc,o=bc(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),ra(r,na("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 l;if(a.kind==="catalog")l={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}l={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let u={inference_id:e.inference_id,...l,task:o,http_status:e.status,started_at:Ic(e),completed_at:e.ts,billable_outcome:Ac(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,session_seconds:e.session_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(lt.length>=Ji){i("queue_full",`${lt.length} ledger writes are already waiting (capacity ${Ji}, ${Tn} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}lt.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Tn<Tc&&(Tn+=1,Lc())}async function Lc(){try{for(;;){let t=Mc();if(t===void 0)return;Do.add(t);try{await $c(t)}finally{Do.delete(t)}}}finally{Tn-=1,Qi()}}function Mc(){let t=Date.now();for(;;){let e=lt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<In)return e;At(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 ${In}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 $c(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);At(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=Sc(o);if(s!==null){At(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=Rc(o),a=Date.now()-t.queuedAt;if(zt){At(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(kc(i)&&a<In){if(await Uc(Nc(t.attempts)),zt||Date.now()-t.queuedAt>=In){let l=Date.now()-t.queuedAt;At(t,{outcome:"failed",reason:zt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:zt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:l,error:`this row's backoff outlived the ${In}ms dwell bound (waited ${l}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}At(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 Nc(t){return Math.min(Pc,Oc*2**Math.max(0,t-1))}function Uc(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function At(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;ra(t.report,na(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}T();T();var pr="/v1/usage/requests",oa=1e4,Dc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,wt=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},we=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},cr=class extends we{constructor(e){super(e),this.name="UsageWithholdingError"}},la=1024*1024;function Ho(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new wt(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new wt(`"${e}" must be an array of uuid strings`);if(n.length>oa)throw new wt(`"${e}" carries ${n.length} ids; at most ${oa} 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"||!Dc.test(s))throw new wt(`"${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 ua(t){return Ho(t,"inference_ids")}var Fc=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function Yt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new we(`${n}: ${e} is not a non-empty string (got ${Qt(r)})`);return r}function Fo(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new we(`${n}: ${e} is neither null nor a non-empty string (got ${Qt(r)})`);return r}function Xt(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 we(`${n}: ${e} is not a number (got ${Qt(o)})`);if(r&&!Number.isSafeInteger(s))throw new we(`${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 we(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Bc=40,sa=64,ia=600;function da(t){let e=Object.keys(t).sort(),r=e.slice(0,Bc).map(o=>o.length>sa?`${o.slice(0,sa)}\u2026`:o).join(", ");return r.length>ia&&(r=`${r.slice(0,ia)}\u2026`),`${e.length} keys present: [${r}]`}function Qt(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function Bo(t){tt(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
10
+ `)}function Hc(t,e){let n;try{n=t(e)}catch{aa(t,e);return}jc(n)&&Promise.resolve(n).catch(()=>{aa(t,e)})}function jc(t){return typeof t?.then=="function"}function aa(t,e){if(t!==Bo)try{Bo(e)}catch{}}function ca(t,e=Bo){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?da(t):Qt(t);throw new we(`the usage surface answered without a "requests" array: got ${Qt(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(qc(n[o],s))}catch(i){if(i instanceof cr||!(i instanceof we))throw i;Hc(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new we(`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 qc(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new we(`${e} is not an object: got ${Qt(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new cr(`${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 Fc)if(!Object.hasOwn(n,o))throw new we(`${e} has no "${o}" column (${da(n)})`);let r=Xt(n,"http_status",e,!0);if(r===null)throw new we(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Yt(n,"inference_id",e),model_id:Yt(n,"model_id",e),identity_kind:Yt(n,"identity_kind",e),variant:Fo(n,"variant",e),task:Yt(n,"task",e),http_status:r,started_at:Yt(n,"started_at",e),completed_at:Yt(n,"completed_at",e),prompt_tokens:Xt(n,"prompt_tokens",e,!0),completion_tokens:Xt(n,"completion_tokens",e,!0),output_units:Xt(n,"output_units",e,!1),output_minutes:Xt(n,"output_minutes",e,!1),cost_nano_usd:Xt(n,"cost_nano_usd",e,!0),price_version:Fo(n,"price_version",e),priced_at:Fo(n,"priced_at",e)}}function fr(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 we(`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 we(`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 On="/partners/huggingface/v1/billing/requests";function Gc(t){return Ho(t,"requestIds")}function Wc(t){return t>=200&&t<=399}function Jc(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Wc(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function pa(t,e){let n=Gc(t),r=await e(n);return fr(r,n),Jc(r)}var jo=9464,mr="/metrics",hr="(other)",Vc="(none)",Kc=64,zc=128,Yc=["/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",pr,On,Rt],Xc=new Set(Yc);function Qc(t){return Xc.has(t)?t:hr}function Zc(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var gr=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?Vc:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,hr):(this.admitted.add(e),e):hr}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},yr=class{registry=new _e.Registry;modelLabel=new gr(Kc);orgLabel=new gr(zc);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new _e.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 _e.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 _e.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 _e.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 _e.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 _e.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 _e.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 Ki)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new _e.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"},zi()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Yi()/1e3)}}),this.labelCardinality=new _e.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 _e.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 _e.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 _e.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 _e.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 _e.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 _e.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,_e.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=Qc(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 l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?hr:e.method,status_class:Zc(e.status),stream:l,model:s,org:i}),this.duration.observe({lane:n,stream:l,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 ma(t){return(0,fa.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==mr){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${mr}
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()})})}O();var Ho=require("crypto"),fa=require("http"),jo=9465,Yc="x-urun-key-id",Xc="x-urun-key-fingerprint",Qc="urun-ratelimit-bucket:",Zc="urun-ratelimit-tier:",pa="anonymous",ep=/^urun_sk_[A-Za-z0-9_-]{43}$/;function tp(t){return(0,Ho.createHash)("sha256").update(`${Qc}${t}`).digest("hex")}function np(t){return(0,Ho.createHash)("sha256").update(`${Zc}${t}`).digest("hex")}function rp(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return ep.test(n)?n:null}function ma(){return(0,fa.createServer)((t,e)=>{let n=rp(t.headers.authorization);e.setHeader(Yc,n===null?pa:tp(n)),e.setHeader(Xc,n===null?pa:np(n)),e.writeHead(200),e.end()})}O();var op=8080,qo="serve",It="0.0.0.0";function sp(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function ha(t=process.env){let e=(t.PORT??"").trim(),n=e===""?op: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=Fi(ar(sp(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?ar(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 l=i?{catalogUrl:ar(i,"URUN_CATALOG_URL"),anonKey:a}:null,u=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!u!=!!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=u?{keyId:d,key:u}:void 0,f={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},h=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],m=h.filter((_,C)=>Object.values(f)[C]==="");if(m.length!==0&&m.length!==h.length)throw new Error(`${h.join(", ")} must be set together (or all left unset) \u2014 missing: ${m.join(", ")}, which would half-configure the lane plane`);let w=m.length===0?f:void 0,E={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},x=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],b=x.filter((_,C)=>Object.values(E)[C]==="");if(b.length!==0&&b.length!==x.length)throw new Error(`${x.join(", ")} must be set together (or all left unset) \u2014 missing: ${b.join(", ")}, which would half-configure the pooler cutover`);let v=b.length===0?E:void 0,p={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},g=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],y=g.filter((_,C)=>Object.values(p)[C]==="");if(y.length!==0&&y.length!==g.length)throw new Error(`${g.join(", ")} must be set together (or all left unset) \u2014 missing: ${y.join(", ")}, which would half-configure the machine-identity rung`);let S=p.issuers.split(",").map(_=>_.trim()).filter(_=>_!=="");if(S.length===0&&y.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 A=Number(p.tokenTtlS);if(y.length===0&&(!Number.isFinite(A)||A<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(p.tokenTtlS)}`);let P=y.length===0?{jwksBaseUrl:p.jwksBaseUrl,issuers:S,tokenTtlS:A}:void 0,R=(t.URUN_WORKOS_ISSUERS??"").trim(),T=R.split(",").map(_=>_.trim()).filter(_=>_!=="");if(R!==""&&T.length===0)throw new Error("URUN_WORKOS_ISSUERS resolved to no issuer URLs \u2014 set at least one (e.g. https://api.workos.com/user_management/client_01KNNB76YVGNH78X98A1X3S56C)");for(let _ of T){let C;try{C=new URL(_)}catch{throw new Error(`URUN_WORKOS_ISSUERS entry is not a URL: ${JSON.stringify(_)}`)}if(C.protocol!=="https:")throw new Error(`URUN_WORKOS_ISSUERS entry must be https (got ${_}) \u2014 the issuer is the user rung's trust root`)}return{port:n,baseUrl:r,apiUrl:s,catalog:l,ledgerSigning:c,lane:w,pooler:v,machine:P,...T.length>0?{userIssuers:T}:{}}}O();var hd=require("http");O();O();var ya="audio",Go=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(e,"base64"),o=Math.floor(r.byteLength/2),s=new Int16Array(o);for(let i=0;i<o;i++)s[i]=r.readInt16LE(i*2);this.source.onData(s),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(i=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(i instanceof Error?i.message:String(i)))}))}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)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function wa(t,e,n=1e4){try{return await ip(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function ip(t,e,n){let r=new Go(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(ya);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(a=>s.emit(a));let i=await ap(t,n);return await r.startInbound(i),r}function ap(t,e){let n=t.stream(ya);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=l=>{l!=null&&(clearTimeout(i),s?.(),r(l))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var ga="rt-video-in",Pn=256e3;function Jo(t){let e=t.stream(ga),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${ga}') 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>Pn)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Pn}-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 lp=24e3,Tn=480,up=111,dp=50,yr=null;async function cp(){if(yr)return;let t=await import("opusscript");yr=t.default??t}function pp(){if(!yr)throw new Error("[opus-guard] opusscript module not loaded");return new yr(lp,1,2048)}var Wo=class{constructor(e=pp){this.build=e;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let e=this.build();return this.inner=e,e}get wedged(){return this._wedged||this.consecutiveFailures>=dp}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let o=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,o}catch(o){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${o instanceof Error?o.message:String(o)}`);return null}}decode(e){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(e);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let e=this.inner;this.inner=null;try{e?.delete?.()}catch{}}};async function _a(){let t=await import("werift");await cp();let e=new Wo;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 l=new Int16Array(i.length+a.length);l.set(i,0),l.set(a,i.length);let u=0;for(;l.length-u>=Tn;){let d=l.subarray(u,u+Tn);u+=Tn;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),f=e.encode(c,Tn);if(f===null){i=l.slice(u);break}o=o+1&65535,s=s+Tn>>>0;let h=new t.RtpHeader({version:2,payloadType:up,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),m=new t.RtpPacket(h,f);n.writeRtp(m)}i=l.slice(u)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{if(s.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${s.payload.length} B > 3828 B max`);return}let i;try{i=e.decode(s.payload)}catch(l){if(e.wedged)throw l;return}let a=new Int16Array(i.length/2);for(let l=0;l<a.length;l++)a[l]=i.readInt16LE(l*2);r.onframe?.({samples:a})}),r},dispose:()=>e.dispose()}}O();var wr=require("@urun-sh/core"),Vo="rt-video-out";var fp="h264";function mp(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 hp(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;mp(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 va="urun.videoOut.v2-ws";function ba(t){let e=t.stream(Vo);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Vo}') 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=l=>{for(let u of r)u(l)},i=!1,a=async()=>{for await(let l of e.messages()){if(!(l instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${Vo}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=hp(l)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(u)}for(let l of o)l()};return{codec:fp,onOutputFrame:l=>(n.add(l),i||(i=!0,a().catch(u=>s(u instanceof Error?u:new Error(String(u))))),()=>n.delete(l)),onLaneError:l=>(r.add(l),()=>r.delete(l)),onEnd:l=>(o.add(l),()=>o.delete(l))}}var Sr="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",gp=1007,ka=1008,ut=1011,kr=1008,F=class extends Error{constructor(n,r=gp){super(n);this.closeCode=r}closeCode},Se=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,_r=["setup","clientContent","realtimeInput","toolResponse"];function Ra(t){let e;try{e=JSON.parse(t)}catch{throw new F("client message is not valid JSON")}let n=Se(e);if(!n)throw new F("client message must be a JSON object");let r=_r.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!_r.includes(a));if(o.length>0)throw new F(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${_r.join(", ")}`);if(r.length!==1)throw new F(`client message must contain exactly one of ${_r.join(", ")} (got ${r.length})`);let s=r[0],i=Se(n[s]);if(!i)throw new F(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Ea(t,e){if(typeof t=="string")return t;let n=Se(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new F(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=Se(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new F(`${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 F(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new F(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
13
- `)}var yp={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Ot="urun.videoOut";function xa(t){return{framing:va,codec:t}}function Aa(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Ot]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var wp={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},_p=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Ot],Sa=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function vp(t){let e=Se(t);if(!e)throw new F("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new F(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=Se(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new F("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new F(`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 F("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(!Sa.includes(e.activityHandling))throw new F(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Sa.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var bp=["temperature","maxOutputTokens","responseModalities"];function Ia(t){for(let[c,f]of Object.entries(wp))if(t[c]!==void 0)throw new F(f);for(let c of Object.keys(t))if(!_p.includes(c))throw new F(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new F('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=Se(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new F("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!bp.includes(c))throw new F(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new F("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new F("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 f of c){let h=String(f).toUpperCase();if(h==="AUDIO"){o=!0;continue}if(h!=="TEXT")throw new F(`responseModalities ${JSON.stringify(f)} 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 F("setup.tools must be an array");a=[];for(let c of t.tools){let f=Se(c);if(!f)throw new F("setup.tools entries must be objects");for(let h of Object.keys(f))if(h!=="functionDeclarations")throw new F(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new F("tool.functionDeclarations must be an array");for(let h of f.functionDeclarations){let m=Se(h);if(!m||typeof m.name!="string")throw new F("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=Se(t.sessionResumption);if(!c)throw new F("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(c))if(f!=="handle")throw new F(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new F("sessionResumption.handle must be a non-empty string when present");l={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?yp:vp(t.realtimeInputConfig),d=!1;if(t[Ot]!==void 0){if(!Se(t[Ot]))throw new F(`setup["${Ot}"] 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:u,sessionResumption:l,videoOut:d}}function Oa(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Ta(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Pa(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new F(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new F("clientContent.turns must be an array");let n=[];for(let r of e){let o=Se(r);if(!o)throw new F("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 F(`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 vr=16e3,Ca=24e3,Sp=`audio/pcm;rate=${Ca}`,La=Buffer.alloc(960).toString("base64");function kp(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 l=a*s,u=Math.floor(l);if(u>=i){o[a]=t[i];continue}let d=l-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*d)}return o}function Rp(t){let e=Se(t);if(!e)throw new F("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new F(`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 F("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 F("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Ep(t){let e=Se(t);if(!e)throw new F("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new F(`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])!==vr)throw new F(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${vr} Hz (audio/pcm;rate=${vr})`);if(typeof e.data!="string"||e.data.length===0)throw new F("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 F(`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=kp(o,vr,Ca);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Ma(t){if(t.mediaChunks!==void 0)throw new F('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 F("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=Se(t[o]);if(!s||Object.keys(s).length!==0)throw new F(`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 F(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new F(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Ep(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Rp(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new F("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new F("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function $a(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new F(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new F("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=Se(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new F("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 Na(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Ua(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Sp,data:t}}]}}}}function Da(t){let e=Se(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let u of n){let d=Se(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let f=Se(c);f?.type==="output_text"&&typeof f.text=="string"&&(s+=f.text)}}s&&o.push({role:"assistant",content:s});for(let u of n){let d=Se(u);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new F(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,ut);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",f;try{f=JSON.parse(c)}catch{throw new F(`upstream function_call arguments are not valid JSON: ${c}`,ut)}r.push({id:d.call_id,name:d.name,args:f}),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=Se(e.usage),l={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(l.usageMetadata=u)}return i.push(l),{messages:i,assistantItems:o}}O();var Fa=require("crypto"),Ba=require("ws");var xp=256,Ko=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>xp;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Ap="local",Cn=t=>t.slice(0,120),zo=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 ie){this.ws.close(ka,Cn(e.message));return}if(e instanceof te){this.ws.close(kr,Cn(e.message));return}if(e instanceof F){this.ws.close(e.closeCode,Cn(e.message));return}this.ws.close(ut,Cn(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Ra(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 F(`"${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}=Pa(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Ma(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:La);return}this.transcript.push(...$a(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new F("setup may only be sent once, as the first client message");let n=Ia(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new F("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",kr);if(s.model!==n.model)throw new F(`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 F("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 F(`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`,kr);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(u=>this.send(Aa(u))),l=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),l()},o[Ot]=xa(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 F("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new F("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",ut);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Ua(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 F("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new F("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",ut);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 F(`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 F("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 F("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,Fa.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(Ta(e.timeLeftMs)),this.ws.close(ut,Cn(`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 l of r){if(n.interrupted)break;let u=l;if(u.type==="error")throw new F(`upstream error: ${JSON.stringify(u)}`,ut);if(u.type==="response.completed"){o=u.response,s=!0;continue}let d=Na(u);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new F("upstream produced no response.completed event",ut);let{messages:i,assistantItems:a}=Da(o);this.transcript.push(...a);for(let l of i)this.send(l);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Tt=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Ip(t,e,n){let r=new Set;(l=>{if(typeof l=="string")l!==""&&r.add(l);else if(Array.isArray(l))for(let u of l)u!==""&&r.add(u)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Tt(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 Tt(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 l of r)a=l;if(a===void 0&&n)throw new Tt(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Yo(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 Ba.WebSocketServer({noServer:!0}),o=new Ko;t.on("upgrade",(i,a,l)=>{let u=new URL(i.url??"/","http://localhost");u.pathname===Sr&&(a.on("error",()=>{}),(async()=>{let d=Ip(i,u,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Tt(401,"invalid local proxy api key");c={clients:e.clients,scope:Ap}}r.handleUpgrade(i,a,l,f=>{new zo(f,c,o)})})().catch(d=>{let c=502;(d instanceof Tt||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let f=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",h=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${f}\r
12
+ `);return}n.end()})})}T();var qo=require("crypto"),ga=require("http"),Go=9465,ep="x-urun-key-id",tp="x-urun-key-fingerprint",np="urun-ratelimit-bucket:",rp="urun-ratelimit-tier:",ha="anonymous",op=/^urun_sk_[A-Za-z0-9_-]{43}$/;function sp(t){return(0,qo.createHash)("sha256").update(`${np}${t}`).digest("hex")}function ip(t){return(0,qo.createHash)("sha256").update(`${rp}${t}`).digest("hex")}function ap(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return op.test(n)?n:null}function ya(){return(0,ga.createServer)((t,e)=>{let n=ap(t.headers.authorization);e.setHeader(ep,n===null?ha:sp(n)),e.setHeader(tp,n===null?ha:ip(n)),e.writeHead(200),e.end()})}T();var lp=8080,Wo="serve",It="0.0.0.0";function up(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function wa(t=process.env){let e=(t.PORT??"").trim(),n=e===""?lp: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=ji(lr(up(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?lr(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 l=i?{catalogUrl:lr(i,"URUN_CATALOG_URL"),anonKey:a}:null,u=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!u!=!!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=u?{keyId:d,key:u}:void 0,f={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},h=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],m=h.filter((M,U)=>Object.values(f)[U]==="");if(m.length!==0&&m.length!==h.length)throw new Error(`${h.join(", ")} must be set together (or all left unset) \u2014 missing: ${m.join(", ")}, which would half-configure the lane plane`);let w=m.length===0?f:void 0,E={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},x=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],v=x.filter((M,U)=>Object.values(E)[U]==="");if(v.length!==0&&v.length!==x.length)throw new Error(`${x.join(", ")} must be set together (or all left unset) \u2014 missing: ${v.join(", ")}, which would half-configure the pooler cutover`);let _=v.length===0?E:void 0,p={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},g=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],y=g.filter((M,U)=>Object.values(p)[U]==="");if(y.length!==0&&y.length!==g.length)throw new Error(`${g.join(", ")} must be set together (or all left unset) \u2014 missing: ${y.join(", ")}, which would half-configure the machine-identity rung`);let S=p.issuers.split(",").map(M=>M.trim()).filter(M=>M!=="");if(S.length===0&&y.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 A=Number(p.tokenTtlS);if(y.length===0&&(!Number.isFinite(A)||A<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(p.tokenTtlS)}`);let P=y.length===0?{jwksBaseUrl:p.jwksBaseUrl,issuers:S,tokenTtlS:A}:void 0,R=(t.URUN_WORKOS_ISSUERS??"").trim(),O=R.split(",").map(M=>M.trim()).filter(M=>M!=="");if(R!==""&&O.length===0)throw new Error("URUN_WORKOS_ISSUERS resolved to no issuer URLs \u2014 set at least one (e.g. https://api.workos.com/user_management/client_01KNNB76YVGNH78X98A1X3S56C)");for(let M of O){let U;try{U=new URL(M)}catch{throw new Error(`URUN_WORKOS_ISSUERS entry is not a URL: ${JSON.stringify(M)}`)}if(U.protocol!=="https:")throw new Error(`URUN_WORKOS_ISSUERS entry must be https (got ${M}) \u2014 the issuer is the user rung's trust root`)}let b=(t.URUN_CONTROL_PLANE_URL??"").trim(),C=(t.URUN_CONTROL_PLANE_TOKEN??"").trim(),$=b!==""&&C!==""?{url:b.replace(/\/+$/,""),token:C}:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:l,ledgerSigning:c,lane:w,pooler:_,machine:P,memberGate:$,...O.length>0?{userIssuers:O}:{}}}T();var _d=require("http");T();T();function _r(t){let e=t.byteLength>>1,n=0;for(let r=0;r<e;r++){let o=t.readInt16LE(r*2);if(o>16||o<-16)return!1;n+=o*o}return n<=64*e}var va="audio",Jo=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(e,"base64"),o=Math.floor(r.byteLength/2),s=new Int16Array(o);for(let i=0;i<o;i++)s[i]=r.readInt16LE(i*2);this.source.onData(s),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(i=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(i instanceof Error?i.message:String(i)))}))}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)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function ba(t,e,n=1e4){try{return await dp(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function dp(t,e,n){let r=new Jo(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(va);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(a=>s.emit(a));let i=await cp(t,n);return await r.startInbound(i),r}function cp(t,e){let n=t.stream(va);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=l=>{l!=null&&(clearTimeout(i),s?.(),r(l))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var _a="rt-video-in",Cn=256e3;function Ko(t){let e=t.stream(_a),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${_a}') 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>Cn)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Cn}-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 pp=24e3,Pn=480,fp=111,mp=50,wr=null;async function hp(){if(wr)return;let t=await import("opusscript");wr=t.default??t}function gp(){if(!wr)throw new Error("[opus-guard] opusscript module not loaded");return new wr(pp,1,2048)}var Vo=class{constructor(e=gp){this.build=e;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let e=this.build();return this.inner=e,e}get wedged(){return this._wedged||this.consecutiveFailures>=mp}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let o=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,o}catch(o){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${o instanceof Error?o.message:String(o)}`);return null}}decode(e){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(e);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let e=this.inner;this.inner=null;try{e?.delete?.()}catch{}}};async function Sa(){let t=await import("werift");await hp();let e=new Vo;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 l=new Int16Array(i.length+a.length);l.set(i,0),l.set(a,i.length);let u=0;for(;l.length-u>=Pn;){let d=l.subarray(u,u+Pn);u+=Pn;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),f=e.encode(c,Pn);if(f===null){i=l.slice(u);break}o=o+1&65535,s=s+Pn>>>0;let h=new t.RtpHeader({version:2,payloadType:fp,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),m=new t.RtpPacket(h,f);n.writeRtp(m)}i=l.slice(u)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{if(s.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${s.payload.length} B > 3828 B max`);return}let i;try{i=e.decode(s.payload)}catch(l){if(e.wedged)throw l;return}let a=new Int16Array(i.length/2);for(let l=0;l<a.length;l++)a[l]=i.readInt16LE(l*2);r.onframe?.({samples:a})}),r},dispose:()=>e.dispose()}}T();var vr=require("@urun-sh/core"),zo="rt-video-out";var yp="h264";function wp(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 _p(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;wp(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 ka="urun.videoOut.v2-ws";function Ra(t){let e=t.stream(zo);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${zo}') 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=l=>{for(let u of r)u(l)},i=!1,a=async()=>{for await(let l of e.messages()){if(!(l instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${zo}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=_p(l)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(u)}for(let l of o)l()};return{codec:yp,onOutputFrame:l=>(n.add(l),i||(i=!0,a().catch(u=>s(u instanceof Error?u:new Error(String(u))))),()=>n.delete(l)),onLaneError:l=>(r.add(l),()=>r.delete(l)),onEnd:l=>(o.add(l),()=>o.delete(l))}}var Rr="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",vp=1007,xa=1008,ut=1011,Er=1008,F=class extends Error{constructor(n,r=vp){super(n);this.closeCode=r}closeCode},Se=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,br=["setup","clientContent","realtimeInput","toolResponse"];function Aa(t){let e;try{e=JSON.parse(t)}catch{throw new F("client message is not valid JSON")}let n=Se(e);if(!n)throw new F("client message must be a JSON object");let r=br.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!br.includes(a));if(o.length>0)throw new F(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${br.join(", ")}`);if(r.length!==1)throw new F(`client message must contain exactly one of ${br.join(", ")} (got ${r.length})`);let s=r[0],i=Se(n[s]);if(!i)throw new F(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Ia(t,e){if(typeof t=="string")return t;let n=Se(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new F(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=Se(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new F(`${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 F(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new F(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
13
+ `)}var bp={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Tt="urun.videoOut";function Ta(t){return{framing:ka,codec:t}}function Oa(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Tt]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Sp={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},kp=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Tt],Ea=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Rp(t){let e=Se(t);if(!e)throw new F("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new F(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=Se(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new F("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new F(`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 F("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(!Ea.includes(e.activityHandling))throw new F(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Ea.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Ep=["temperature","maxOutputTokens","responseModalities"];function Pa(t){for(let[c,f]of Object.entries(Sp))if(t[c]!==void 0)throw new F(f);for(let c of Object.keys(t))if(!kp.includes(c))throw new F(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new F('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=Se(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new F("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Ep.includes(c))throw new F(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new F("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new F("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 f of c){let h=String(f).toUpperCase();if(h==="AUDIO"){o=!0;continue}if(h!=="TEXT")throw new F(`responseModalities ${JSON.stringify(f)} 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:Ia(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new F("setup.tools must be an array");a=[];for(let c of t.tools){let f=Se(c);if(!f)throw new F("setup.tools entries must be objects");for(let h of Object.keys(f))if(h!=="functionDeclarations")throw new F(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new F("tool.functionDeclarations must be an array");for(let h of f.functionDeclarations){let m=Se(h);if(!m||typeof m.name!="string")throw new F("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=Se(t.sessionResumption);if(!c)throw new F("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(c))if(f!=="handle")throw new F(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new F("sessionResumption.handle must be a non-empty string when present");l={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?bp:Rp(t.realtimeInputConfig),d=!1;if(t[Tt]!==void 0){if(!Se(t[Tt]))throw new F(`setup["${Tt}"] 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:u,sessionResumption:l,videoOut:d}}function Ca(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function La(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Ma(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new F(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new F("clientContent.turns must be an array");let n=[];for(let r of e){let o=Se(r);if(!o)throw new F("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 F(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Ia(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Sr=16e3,$a=24e3,xp=`audio/pcm;rate=${$a}`,Na=Buffer.alloc(960).toString("base64");function Ap(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 l=a*s,u=Math.floor(l);if(u>=i){o[a]=t[i];continue}let d=l-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*d)}return o}function Ip(t){let e=Se(t);if(!e)throw new F("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new F(`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 F("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 F("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Tp(t){let e=Se(t);if(!e)throw new F("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new F(`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])!==Sr)throw new F(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Sr} Hz (audio/pcm;rate=${Sr})`);if(typeof e.data!="string"||e.data.length===0)throw new F("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 F(`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=Ap(o,Sr,$a);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Ua(t){if(t.mediaChunks!==void 0)throw new F('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 F("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=Se(t[o]);if(!s||Object.keys(s).length!==0)throw new F(`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 F(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new F(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Tp(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Ip(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new F("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new F("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 F(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new F("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=Se(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new F("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 Fa(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Ba(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:xp,data:t}}]}}}}function Ha(t){let e=Se(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let u of n){let d=Se(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let f=Se(c);f?.type==="output_text"&&typeof f.text=="string"&&(s+=f.text)}}s&&o.push({role:"assistant",content:s});for(let u of n){let d=Se(u);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new F(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,ut);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",f;try{f=JSON.parse(c)}catch{throw new F(`upstream function_call arguments are not valid JSON: ${c}`,ut)}r.push({id:d.call_id,name:d.name,args:f}),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=Se(e.usage),l={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(l.usageMetadata=u)}return i.push(l),{messages:i,assistantItems:o}}T();var ja=require("crypto"),qa=require("ws");var Op=256,Yo=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Op;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Pp="local",Ln=t=>t.slice(0,120),Xo=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 ie){this.ws.close(xa,Ln(e.message));return}if(e instanceof te){this.ws.close(Er,Ln(e.message));return}if(e instanceof F){this.ws.close(e.closeCode,Ln(e.message));return}this.ws.close(ut,Ln(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Aa(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 F(`"${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}=Ma(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Ua(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:Na);return}this.transcript.push(...Da(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new F("setup may only be sent once, as the first client message");let n=Pa(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new F("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",Er);if(s.model!==n.model)throw new F(`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 F("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 F(`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`,Er);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(u=>this.send(Oa(u))),l=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),l()},o[Tt]=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 F("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new F("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",ut);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Ba(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 F("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new F("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",ut);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 F(`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 F("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 F("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,ja.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Ca(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(La(e.timeLeftMs)),this.ws.close(ut,Ln(`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 l of r){if(n.interrupted)break;let u=l;if(u.type==="error")throw new F(`upstream error: ${JSON.stringify(u)}`,ut);if(u.type==="response.completed"){o=u.response,s=!0;continue}let d=Fa(u);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new F("upstream produced no response.completed event",ut);let{messages:i,assistantItems:a}=Ha(o);this.transcript.push(...a);for(let l of i)this.send(l);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ot=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Cp(t,e,n){let r=new Set;(l=>{if(typeof l=="string")l!==""&&r.add(l);else if(Array.isArray(l))for(let u of l)u!==""&&r.add(u)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Ot(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 Ot(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 l of r)a=l;if(a===void 0&&n)throw new Ot(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Qo(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 qa.WebSocketServer({noServer:!0}),o=new Yo;t.on("upgrade",(i,a,l)=>{let u=new URL(i.url??"/","http://localhost");u.pathname===Rr&&(a.on("error",()=>{}),(async()=>{let d=Cp(i,u,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Ot(401,"invalid local proxy api key");c={clients:e.clients,scope:Pp}}r.handleUpgrade(i,a,l,f=>{new Xo(f,c,o)})})().catch(d=>{let c=502;(d instanceof Ot||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let f=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",h=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${f}\r
14
14
  Connection: close\r
15
15
  \r
16
16
  ${h}\r
17
- `),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(l=>l===void 0?i():a(l)))})(),s)}O();var bt=require("ws");O();O();var Ha=require("crypto"),ja="Inference-Id";function Pt(){return(0,Ha.randomUUID)()}function Xo(t){return t==="/v1"||t.startsWith("/v1/")}function qa(t,e){if(!Xo(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 Ln(t){return`resp_${t}`}function Ga(t){return`chatcmpl-${t}`}function Wa(t){return`msg_${t}`}function He(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Ja(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_seconds: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 Va(t){return`${JSON.stringify(t)}
18
- `}var Op=256,Tp=128;function Ce(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Tp)}var Ct=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>=Op?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let u of e)u.type==="response.output_text.delta"&&typeof u.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=u.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield u;let l=(performance.now()-(i??s))/1e3;a>0&&l>0&&(o.tokRates.push(a/l),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}}}},Pp=256;function Cp(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 Lt=class extends Error{},Qt=class{conversations=new Map;thread(e,n){let r=Cp(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Lt(`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<=Pp)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Ka=new WeakMap;function Mn(t){let e=Ka.get(t);return e||(e=new Qt,Ka.set(t,e)),e}function Zt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function nt(t){return t.find(e=>e.type==="response.completed")?.response??null}function en(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 _t=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}))}},Lp=["<tool_call>","<function="];function Mp(t){return Lp.find(e=>t.includes(e))}function Mt(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 $t(t,e,n){if(!(!t||e>0))return Mp(n)}function tn(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 dt(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function $p(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 Qo(t,e){let n=$p(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var je=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function nn(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Lt?new je(n.message,"previous_response_not_found",400,"previous_response_id"):new je(String(n instanceof Error?n.message:n),"invalid_input")}}function za(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Zo(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new je("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}:{},...za(e)!==void 0?{response_format:za(e)}:{}},o)}async function $n(t){let{body:e,clients:n,store:r,stats:o}=t,s=nn(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,l=e.store!==!1,u=Ce(e);o.model(u);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,f=await Zo(n,e,s,!0,c?He(c):void 0);return{responseId:i,events:Fp({events:f,conversation:s,responseId:i,modelKey:u,requestHadTools:d,remember:a,persist:l,store:r,stats:o,turn:t.turn})}}function Np(t,e){let n=[...t].sort((l,u)=>l.output_index-u.output_index).map(({item:l})=>l),r=Array.isArray(e?.output)?e.output:[],o=r.filter(l=>l!==null&&typeof l=="object"&&l.type==="message"),s=n.filter(l=>l.type==="message").length===o.length,i=0;return[...n.map(l=>l.type==="message"&&s?Dp(o[i++],l):l),...Up(r,n)]}function Up(t,e){let n=e.some(u=>u.type==="message"),r=e.some(u=>u.type==="reasoning"),o=u=>String(u.call_id??u.id??""),s=e.filter(u=>u.type==="function_call"),i=t.filter(u=>u!==null&&typeof u=="object"&&u.type==="function_call").length,a=s.length===i,l=new Set(s.map(o));return t.filter(u=>{if(u===null||typeof u!="object")return!0;let d=u;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!l.has(o(d)):!0})}function Dp(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*Fp(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:l,stats:u}=t,d=[],c=K=>K.response&&typeof K.response=="object"?{...K,response:{...K.response,id:r}}:K,f=`item_${r.slice(5)}`,h=!1,m=!1,w=0;function*E(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let x=[],b=(K,M)=>{x.push({output_index:K,item:M})},v=!1,p=0,g="",y=0,S="";function*A(){if(!v)return;v=!1,yield{type:"response.reasoning_text.done",item_id:g,output_index:p,content_index:0,text:S};let K={id:g,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:S}],status:"completed"};yield{type:"response.output_item.done",output_index:p,item:K},b(p,K),S=""}let P=!1,R=0,T="",_=0,C="",$="";function*N(K){if(!P)return;P=!1,yield{type:"response.output_text.done",item_id:T,output_index:R,content_index:0,text:C},yield{type:"response.content_part.done",item_id:T,output_index:R,content_index:0,part:{type:"output_text",text:C}};let M={id:T,type:"message",role:"assistant",status:K,content:[{type:"output_text",text:C}]};yield{type:"response.output_item.done",output_index:R,item:M},b(R,M),C=""}let D=new _t,q=null,X=-1;function*G(K){if(!q)return;let M=q;q=null,yield{type:"response.function_call_arguments.done",item_id:M.fcId,output_index:M.outputIndex,arguments:M.args};let ee={id:M.fcId,type:"function_call",call_id:M.callId??M.fcId,name:M.name??"",arguments:M.args,status:K};yield{type:"response.output_item.done",output_index:M.outputIndex,item:ee},b(M.outputIndex,ee)}let re=!1;for await(let K of u.track(e,o,t.turn)){d.push(K);let M=String(K.type??"");if(M==="response.created"||M==="response.in_progress"){h=!0,yield c(K);continue}if(M==="response.output_item.added"){m=!0,yield c(K);continue}if(M==="response.reasoning_text.delta"&&!m){yield*E(),v||(v=!0,p=w++,y+=1,g=y===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${y}`,yield{type:"response.output_item.added",output_index:p,item:{id:g,type:"reasoning",summary:[],content:[],status:"in_progress"}}),S+=String(K.delta??""),yield{type:"response.reasoning_text.delta",item_id:g,output_index:p,content_index:0,delta:K.delta};continue}if(M==="response.output_text.delta"&&!m){yield*E(),yield*A(),P||(P=!0,R=w++,_+=1,T=_===1?f:`${f}_${_}`,yield{type:"response.output_item.added",output_index:R,item:{id:T,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:T,output_index:R,content_index:0,part:{type:"output_text",text:""}}),C+=String(K.delta??""),$+=String(K.delta??""),yield{type:M,item_id:T,output_index:R,content_index:0,delta:K.delta};continue}let ee=m?null:en(K);if(ee){if(yield*E(),yield*A(),yield*N("completed"),D.add(ee),ee.tool_index!==X){yield*G("completed"),X=ee.tool_index;let Fe=w++;q={fcId:`fc_${r.slice(5)}_${ee.tool_index}`,outputIndex:Fe,callId:ee.call_id,name:ee.name,args:""},yield{type:"response.output_item.added",output_index:Fe,item:{id:q.fcId,type:"function_call",call_id:q.callId??q.fcId,name:q.name??"",arguments:"",status:"in_progress"}}}q&&(ee.call_id&&(q.callId=ee.call_id),ee.name&&(q.name=ee.name),q.args+=ee.delta,yield{type:"response.function_call_arguments.delta",item_id:q.fcId,output_index:q.outputIndex,delta:ee.delta});continue}if(M==="response.completed"&&!m){let Fe=Zt(K.response),ue=$t(s,D.size+Fe.length,$);if(ue){re=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Mt(o,ue)}};break}if(yield*A(),yield*N("completed"),yield*G("completed"),D.size===0)for(let me of Fe){let Me=w++,it=me.id??me.call_id??`fc_${Me}`,$e=me.arguments??"",_n={id:it,type:"function_call",call_id:me.call_id??it,name:me.name??""};yield{type:"response.output_item.added",output_index:Me,item:{..._n,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:it,output_index:Me,delta:$e},yield{type:"response.function_call_arguments.done",item_id:it,output_index:Me,arguments:$e};let at={..._n,arguments:$e,status:"completed"};yield{type:"response.output_item.done",output_index:Me,item:at},b(Me,at)}let ce=Np(x,K.response);yield ce.length>0?c({...K,response:{...K.response,output:ce}}):c(K);continue}yield c(K)}if(yield*A(),yield*N("incomplete"),yield*G("incomplete"),i&&!re){let K=nt(d);l.remember(r,n,Qo(K,tn(d,K)),a)}}O();O();var qe=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},Ae=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Nt=class extends Error{pool;model;constructor(e,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=e,this.model=n}};O();var vt=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)}},Nn=class extends vt{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},es=class extends vt{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")}},Ve=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Rr=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(e){e||this.dropDeadSlots();let n=this.now(),r=this.slots.filter(o=>o.state==="paused"&&!o.opening&&(e||!o.dead)&&(!o.dead||n>=o.nextDialAt)).sort((o,s)=>o.slot.index-s.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let n=this.slots[e];n.dead&&!n.opening&&n.inFlight===0&&(n.backoffTimer&&(clearTimeout(n.backoffTimer),n.backoffTimer=void 0),this.slots.splice(e,1))}}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,rotations:0,nextDialAt:0,backoffTimer:void 0};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.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),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 Nn;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 Nn;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&&this.now()>=c.nextDialAt);if(!s&&(i||a)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let l=r+n-Date.now();if(l<=0)throw new es(n,this.slots.some(c=>c.state==="queued"));let u,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{u=setTimeout(c,l)})])}finally{clearTimeout(u);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 Nn}}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&&this.now()>=s.nextDialAt);(r||o)&&this.openForDemand(!1)}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,this.opts.onLease?.(n);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.disposeDropped(e),this.signalDrain())}disposeDropped(e){this.opts.closeSlot(e).catch(()=>{})}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)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),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(!0),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,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);for(let o of this.slots)clearTimeout(o.backoffTimer),o.backoffTimer=void 0;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)`)}};O();var ts=require("@urun-sh/core"),Ke=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)}},ns=33e4;function Ya(t,e=ns){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((u,d)=>{o=d}),i=setTimeout(()=>o(new Er),e),a;try{a=await Promise.race([r.next(),s])}catch(u){throw u instanceof te||u instanceof ts.SessionFailedError&&u.kind==="transport-failed"?u:u instanceof Er?(await r.return?.(void 0),new Ke("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 Ke("upstream_threw",`decision stream failed: ${String(u instanceof Error?u.message:u)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let l=a.value;if(typeof l=="object"&&l!==null&&"type"in l&&l.type==="error")throw new Ke("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield l}})()}var Er=class extends Error{constructor(){super("stream idle timeout")}};function Xa(t){return t instanceof Ke?!1:t instanceof te?!0:t instanceof ts.SessionFailedError?t.kind==="transport-failed":!1}var Bp=[/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 ze(t){return!Bp.some(e=>e.test(t))}function Ye(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 De(t,e){if(t instanceof te)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=Qa(t);return n||{message:Ye(e?.inferenceId??null),redacted:!0}}function Qa(t){return t instanceof mt?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof he?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof ie?{message:t.message,redacted:!1}:t instanceof qe?{message:t.message,redacted:!1}:t instanceof vt?{message:t.message,redacted:!1}:t instanceof Ke?ze(t.message)?{message:t.message,redacted:!1}:null:t instanceof Ve?{message:t.message,redacted:!1}:t instanceof Ae?{message:t.message,redacted:!1}:null}function rn(t,e,n){let r=n??(i=>console.error(i)),o=Qa(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ge(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&ze(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ge(e)}`),`the ${t} upstream failed while serving this request`)}function rt(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ze(e)?e:null}function Ge(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var ss="/v1/responses",Hp=64*1024*1024,jp=8*1024*1024,qp=16,Za=32,el=3600*1e3,Gp=/^[A-Za-z0-9._-]{1,256}$/;function Le(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Wp=Le(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 is(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Jp(t){for(;t.bufferedAmount>jp&&t.readyState===bt.WebSocket.OPEN;){let{promise:e,resolve:n}=is();setTimeout(n,5),await e}}var rs=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 Lt))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)}},os=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 rs(Mn(n)),e.on("message",(a,l)=>this.onMessage(a,l)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(Le(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${el/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},el).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(Le(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(Le(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(Le(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(Le(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(Le(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(Le(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"||!Gp.test(o.stream_id)){this.sendFrame(Wp);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Za){this.sendFrame(Le(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Za}). 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??"",l=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,l.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=Pt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await $n({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Ln(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!==bt.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Jp(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=Pt(),o=Ln(r);try{let s=nn(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:Ge(e);if(e instanceof je)return Le(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof ie)return Le(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof te){let a=De(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}`),Le(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}`),Le(s.status,{type:s.openaiType,message:o},n);let i=De(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}`),Le(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=rt(o),a=i??Ye(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)}`),Le(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=qp;){let{promise:e,resolve:n}=is();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!==bt.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!==bt.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function xr(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(l=>l===void 0?i():a(l)))})(),s)}T();var bt=require("ws");T();T();var Ga=require("crypto"),Wa="Inference-Id";function Pt(){return(0,Ga.randomUUID)()}function Zo(t){return t==="/v1"||t.startsWith("/v1/")}function Ja(t,e){if(!Zo(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function Mn(t){return`resp_${t}`}function Va(t){return`chatcmpl-${t}`}function Ka(t){return`msg_${t}`}function He(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function za(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_seconds: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 Ya(t){return`${JSON.stringify(t)}
18
+ `}var Lp=256,Mp=128;function Ce(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Mp)}var Ct=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>=Lp?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let u of e)u.type==="response.output_text.delta"&&typeof u.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=u.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield u;let l=(performance.now()-(i??s))/1e3;a>0&&l>0&&(o.tokRates.push(a/l),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}}}},$p=256;function Np(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 Lt=class extends Error{},Zt=class{conversations=new Map;thread(e,n){let r=Np(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Lt(`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<=$p)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Xa=new WeakMap;function $n(t){let e=Xa.get(t);return e||(e=new Zt,Xa.set(t,e)),e}function en(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function nt(t){return t.find(e=>e.type==="response.completed")?.response??null}function tn(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 _t=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}))}},Up=["<tool_call>","<function="];function Dp(t){return Up.find(e=>t.includes(e))}function Mt(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 $t(t,e,n){if(!(!t||e>0))return Dp(n)}function nn(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 dt(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Fp(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 es(t,e){let n=Fp(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var je=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function rn(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Lt?new je(n.message,"previous_response_not_found",400,"previous_response_id"):new je(String(n instanceof Error?n.message:n),"invalid_input")}}function Qa(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function ts(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new je("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}:{},...Qa(e)!==void 0?{response_format:Qa(e)}:{}},o)}async function Nn(t){let{body:e,clients:n,store:r,stats:o}=t,s=rn(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,l=e.store!==!1,u=Ce(e);o.model(u);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,f=await ts(n,e,s,!0,c?He(c):void 0);return{responseId:i,events:qp({events:f,conversation:s,responseId:i,modelKey:u,requestHadTools:d,remember:a,persist:l,store:r,stats:o,turn:t.turn})}}function Bp(t,e){let n=[...t].sort((l,u)=>l.output_index-u.output_index).map(({item:l})=>l),r=Array.isArray(e?.output)?e.output:[],o=r.filter(l=>l!==null&&typeof l=="object"&&l.type==="message"),s=n.filter(l=>l.type==="message").length===o.length,i=0;return[...n.map(l=>l.type==="message"&&s?jp(o[i++],l):l),...Hp(r,n)]}function Hp(t,e){let n=e.some(u=>u.type==="message"),r=e.some(u=>u.type==="reasoning"),o=u=>String(u.call_id??u.id??""),s=e.filter(u=>u.type==="function_call"),i=t.filter(u=>u!==null&&typeof u=="object"&&u.type==="function_call").length,a=s.length===i,l=new Set(s.map(o));return t.filter(u=>{if(u===null||typeof u!="object")return!0;let d=u;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!l.has(o(d)):!0})}function jp(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*qp(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:l,stats:u}=t,d=[],c=K=>K.response&&typeof K.response=="object"?{...K,response:{...K.response,id:r}}:K,f=`item_${r.slice(5)}`,h=!1,m=!1,w=0;function*E(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let x=[],v=(K,N)=>{x.push({output_index:K,item:N})},_=!1,p=0,g="",y=0,S="";function*A(){if(!_)return;_=!1,yield{type:"response.reasoning_text.done",item_id:g,output_index:p,content_index:0,text:S};let K={id:g,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:S}],status:"completed"};yield{type:"response.output_item.done",output_index:p,item:K},v(p,K),S=""}let P=!1,R=0,O="",b=0,C="",$="";function*M(K){if(!P)return;P=!1,yield{type:"response.output_text.done",item_id:O,output_index:R,content_index:0,text:C},yield{type:"response.content_part.done",item_id:O,output_index:R,content_index:0,part:{type:"output_text",text:C}};let N={id:O,type:"message",role:"assistant",status:K,content:[{type:"output_text",text:C}]};yield{type:"response.output_item.done",output_index:R,item:N},v(R,N),C=""}let U=new _t,q=null,X=-1;function*G(K){if(!q)return;let N=q;q=null,yield{type:"response.function_call_arguments.done",item_id:N.fcId,output_index:N.outputIndex,arguments:N.args};let ee={id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:N.args,status:K};yield{type:"response.output_item.done",output_index:N.outputIndex,item:ee},v(N.outputIndex,ee)}let re=!1;for await(let K of u.track(e,o,t.turn)){d.push(K);let N=String(K.type??"");if(N==="response.created"||N==="response.in_progress"){h=!0,yield c(K);continue}if(N==="response.output_item.added"){m=!0,yield c(K);continue}if(N==="response.reasoning_text.delta"&&!m){yield*E(),_||(_=!0,p=w++,y+=1,g=y===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${y}`,yield{type:"response.output_item.added",output_index:p,item:{id:g,type:"reasoning",summary:[],content:[],status:"in_progress"}}),S+=String(K.delta??""),yield{type:"response.reasoning_text.delta",item_id:g,output_index:p,content_index:0,delta:K.delta};continue}if(N==="response.output_text.delta"&&!m){yield*E(),yield*A(),P||(P=!0,R=w++,b+=1,O=b===1?f:`${f}_${b}`,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:""}}),C+=String(K.delta??""),$+=String(K.delta??""),yield{type:N,item_id:O,output_index:R,content_index:0,delta:K.delta};continue}let ee=m?null:tn(K);if(ee){if(yield*E(),yield*A(),yield*M("completed"),U.add(ee),ee.tool_index!==X){yield*G("completed"),X=ee.tool_index;let Fe=w++;q={fcId:`fc_${r.slice(5)}_${ee.tool_index}`,outputIndex:Fe,callId:ee.call_id,name:ee.name,args:""},yield{type:"response.output_item.added",output_index:Fe,item:{id:q.fcId,type:"function_call",call_id:q.callId??q.fcId,name:q.name??"",arguments:"",status:"in_progress"}}}q&&(ee.call_id&&(q.callId=ee.call_id),ee.name&&(q.name=ee.name),q.args+=ee.delta,yield{type:"response.function_call_arguments.delta",item_id:q.fcId,output_index:q.outputIndex,delta:ee.delta});continue}if(N==="response.completed"&&!m){let Fe=en(K.response),ue=$t(s,U.size+Fe.length,$);if(ue){re=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Mt(o,ue)}};break}if(yield*A(),yield*M("completed"),yield*G("completed"),U.size===0)for(let me of Fe){let Me=w++,it=me.id??me.call_id??`fc_${Me}`,$e=me.arguments??"",vn={id:it,type:"function_call",call_id:me.call_id??it,name:me.name??""};yield{type:"response.output_item.added",output_index:Me,item:{...vn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:it,output_index:Me,delta:$e},yield{type:"response.function_call_arguments.done",item_id:it,output_index:Me,arguments:$e};let at={...vn,arguments:$e,status:"completed"};yield{type:"response.output_item.done",output_index:Me,item:at},v(Me,at)}let ce=Bp(x,K.response);yield ce.length>0?c({...K,response:{...K.response,output:ce}}):c(K);continue}yield c(K)}if(yield*A(),yield*M("incomplete"),yield*G("incomplete"),i&&!re){let K=nt(d);l.remember(r,n,es(K,nn(d,K)),a)}}T();T();var qe=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},Ae=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Nt=class extends Error{pool;model;constructor(e,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=e,this.model=n}};T();var vt=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)}},Un=class extends vt{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},ns=class extends vt{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")}},Ve=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},xr=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(e){e||this.dropDeadSlots();let n=this.now(),r=this.slots.filter(o=>o.state==="paused"&&!o.opening&&(e||!o.dead)&&(!o.dead||n>=o.nextDialAt)).sort((o,s)=>o.slot.index-s.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let n=this.slots[e];n.dead&&!n.opening&&n.inFlight===0&&(n.backoffTimer&&(clearTimeout(n.backoffTimer),n.backoffTimer=void 0),this.slots.splice(e,1))}}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,rotations:0,nextDialAt:0,backoffTimer:void 0};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.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),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 Un;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 Un;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&&this.now()>=c.nextDialAt);if(!s&&(i||a)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let l=r+n-Date.now();if(l<=0)throw new ns(n,this.slots.some(c=>c.state==="queued"));let u,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{u=setTimeout(c,l)})])}finally{clearTimeout(u);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 Un}}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&&this.now()>=s.nextDialAt);(r||o)&&this.openForDemand(!1)}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,this.opts.onLease?.(n);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.disposeDropped(e),this.signalDrain())}disposeDropped(e){this.opts.closeSlot(e).catch(()=>{})}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)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),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(!0),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,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);for(let o of this.slots)clearTimeout(o.backoffTimer),o.backoffTimer=void 0;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)`)}};T();var rs=require("@urun-sh/core"),Ke=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)}},os=33e4;function Za(t,e=os){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((u,d)=>{o=d}),i=setTimeout(()=>o(new Ar),e),a;try{a=await Promise.race([r.next(),s])}catch(u){throw u instanceof te||u instanceof rs.SessionFailedError&&u.kind==="transport-failed"?u:u instanceof Ar?(await r.return?.(void 0),new Ke("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 Ke("upstream_threw",`decision stream failed: ${String(u instanceof Error?u.message:u)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let l=a.value;if(typeof l=="object"&&l!==null&&"type"in l&&l.type==="error")throw new Ke("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield l}})()}var Ar=class extends Error{constructor(){super("stream idle timeout")}};function el(t){return t instanceof Ke?!1:t instanceof te?!0:t instanceof rs.SessionFailedError?t.kind==="transport-failed":!1}var Gp=[/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 ze(t){return!Gp.some(e=>e.test(t))}function Ye(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 De(t,e){if(t instanceof te)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=tl(t);return n||{message:Ye(e?.inferenceId??null),redacted:!0}}function tl(t){return t instanceof mt?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof he?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof ie?{message:t.message,redacted:!1}:t instanceof qe?{message:t.message,redacted:!1}:t instanceof vt?{message:t.message,redacted:!1}:t instanceof Ke?ze(t.message)?{message:t.message,redacted:!1}:null:t instanceof Ve?{message:t.message,redacted:!1}:t instanceof Ae?{message:t.message,redacted:!1}:null}function on(t,e,n){let r=n??(i=>console.error(i)),o=tl(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ge(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&ze(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ge(e)}`),`the ${t} upstream failed while serving this request`)}function rt(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ze(e)?e:null}function Ge(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var as="/v1/responses",Wp=64*1024*1024,Jp=8*1024*1024,Vp=16,nl=32,rl=3600*1e3,Kp=/^[A-Za-z0-9._-]{1,256}$/;function Le(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var zp=Le(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 ls(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Yp(t){for(;t.bufferedAmount>Jp&&t.readyState===bt.WebSocket.OPEN;){let{promise:e,resolve:n}=ls();setTimeout(n,5),await e}}var ss=class extends Zt{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 Lt))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)}},is=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 ss($n(n)),e.on("message",(a,l)=>this.onMessage(a,l)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(Le(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${rl/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},rl).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(Le(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(Le(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(Le(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(Le(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(Le(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(Le(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"||!Kp.test(o.stream_id)){this.sendFrame(zp);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=nl){this.sendFrame(Le(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${nl}). 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??"",l=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,l.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=Pt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await Nn({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Mn(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let a of i){if(this.closed||this.ws.readyState!==bt.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await Yp(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=Pt(),o=Mn(r);try{let s=rn(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:Ge(e);if(e instanceof je)return Le(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof ie)return Le(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof te){let a=De(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}`),Le(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}`),Le(s.status,{type:s.openaiType,message:o},n);let i=De(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}`),Le(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=rt(o),a=i??Ye(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)}`),Le(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=Vp;){let{promise:e,resolve:n}=ls();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!==bt.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!==bt.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Ir(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 as(t,e){let n=new bt.WebSocketServer({noServer:!0,maxPayload:Hp}),r=new Ct,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,f)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{xr(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==ss){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){xr(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(E){let x=e.statusOf?.(E)??null;xr(c,x?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(m=!0,n.handleUpgrade(d,c,f,E=>{s.delete(c),o.add(E),E.on("close",()=>o.delete(E));try{new os(E,w,r,e.statusOf,e.operatorLog??(x=>console.error(x)))}catch{o.delete(E),E.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&xr(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=is();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of o)h.readyState!==bt.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}O();O();var ws=require("@urun-sh/core");O();var tl=require("@urun-sh/core"),Vp={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},Kp={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 Un(t,e){let n=Kp[t.code];return e?`${n} (${e})`:n}function Ar(t){if(t==null)return null;let e=Vp[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 Ir(t){if(t.kind==="create-failed")return Ar(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=tl.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Ar(e?"cold_start_exceeded":"queue_timeout")}var Bn=require("ws");O();var sl=require("@urun-sh/core");O();var rl=require("crypto");function j(t){return`${t}_${(0,rl.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Or=4*1024*1024,ls=8*1024*1024,us=512,sn=20*1024*1024;function fe(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function ot(t,e){return{type:"server_error",code:t,message:e}}function le(t){return{type:"error",event_id:j("event"),error:t}}function ds(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var z=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},zp={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},Yp={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Xp={format:!0,voice:!0,speed:!0};function Qp(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function on(t,e){if(!Array.isArray(t)||t.length===0)throw new z(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new z(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function nl(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new z(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Zp=10;function cs(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:Zp})}function Dn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new z("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in zp));if(s.length>0)throw new z(`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=on(o.modalities,"modalities"),l=on(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new z("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,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new z(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new z(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: 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(l==="transcription"&&!n.turns)throw new z('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=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new z(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=on(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new z('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=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Qp(l))throw new z(`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(l!==null&&typeof l!="string")throw new z("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new z("instructions must be a string or null","instructions");i.instructions=cs(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new z("voice must be a string or null","voice");if(!n.voice)throw new z("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new z(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new z("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new z(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new z("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new z("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new z("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new z(`turn_detection.type ${JSON.stringify(u.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[f,h]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new z(`turn_detection.${f} 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.${f}`,"unsupported_field");if(h!=null&&h!==c[f])throw new z(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new z("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(!l||typeof l!="object"||Array.isArray(l))throw new z("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new z(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new z(`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(l!==null)throw new z("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(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new z("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Yp))throw new z(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&nl(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Dn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Dn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new z("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new z("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Xp))throw new z(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&nl(d.format,"audio.output.format"),d.speed!==void 0)throw new z("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 z("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new z("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 Tr(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 ps(t,e){let n=t;if(!n||typeof n!="object")throw new z("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 z("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 z('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new z("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 z("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 z(`${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 z("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 z("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new z("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new z("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new z("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let l=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...l!==void 0?{detail:l}:{}});continue}throw new z(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:j("item"),type:"message",role:r,content:o}}throw new z(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Pr(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 ef=1001,tf=1011,nf=6e4,rf=3e5,fs=3;var Cr=class extends Error{},Lr=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ut=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},ms=t=>t.slice(0,120),of=/^[A-Za-z0-9+/=]*$/,sf=2,af=600;function hs(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>sf)return!1;return!0}var Fn=class{id=j("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=ds();sessionId=j("sess");conversationId=j("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;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.turnStallMs=e.turnStallMs??nf,this.responseDeadlineMs=e.responseDeadlineMs??rf,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.binding.onSessionEnd?.(n=>{n.reason===Lo&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:j("event"),session:Tr(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(),this.binding.duplex&&this.ensureVoice();for(let n of e.replayFrames??[])this.onMessage(n)}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 te&&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(ot("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.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),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.binding.duplex&&!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(fe("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Or){this.fail(fe("frame_too_large",`frame exceeds the ${Or}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(fe("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(fe("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);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}if(o instanceof Cr){this.fail(ot(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
25
- ${o?.stack??Ge(o)}`),this.send(le(ot(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Dn(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(fe("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:Tr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=ps(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(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(fe("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(fe("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(fe("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(fe("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!of.test(e.audio)){this.send(le(fe("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>sn&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${sn}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${sn} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>sn&&this.pendingAudioBytes.length>0;){let s=this.pendingAudioBytes.shift();o-=Buffer.byteLength(s.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;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.lastCommittedTranscript===null){this.send(le(fe("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(fe("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(fe("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}if(this.binding.duplex){this.send(le(fe("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,ms("session ended by client"))}catch{}});return}case"ping":return;default:this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(fe("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 Cr("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*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0){o=!1;let i=n.next();i.catch(()=>{}),s=r?await Promise.race([i,r]):await i}else{let i,a=new Promise((d,c)=>{i=setTimeout(()=>c(new Lr),this.turnStallMs)}),l=n.next();l.catch(()=>{}),s=await(r?Promise.race([l,a,r]):Promise.race([l,a])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return this.config.model&&s.model===void 0&&(s.model=this.config.model),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,n=!1){if(this.inFlight){this.send(le(fe("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?on(r.modalities,"response.modalities"):void 0,s=r.output_modalities!==void 0?on(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&s!==void 0&&o.slice().sort().join(",")!==s.slice().sort().join(","))throw new z("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((s??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(le(fe("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.deadlineFired=!1,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},l=new Promise((A,P)=>{a=()=>P(new Ut)});this.turnCancelled=l,this.wakeTurnCancelled=()=>a(),l.catch(()=>{});let u=()=>{},d=new Promise((A,P)=>{u=()=>P(new Ut)});this.turnDialGate=d,this.wakeTurnDialGate=()=>u(),d.catch(()=>{});let c=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let f=j("req"),h=`resp_${f}`;this.activeResponseId=h,this.activeRequestId=f;let m=this.binding.composite===!0,w=m?0:this.items.length,E=m?null:Pr(this.items),x=cs(typeof r.instructions=="string"?r.instructions:this.config.instructions),b=typeof r.temperature=="number"?r.temperature:this.config.temperature,v=r.max_output_tokens??this.config.maxOutputTokens,p=v==="inf"||v===void 0?void 0:v,g=r.tools!==void 0?r.tools:this.config.tools,y=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...x!==void 0?{instructions:x}:{},...b!==void 0?{temperature:b}:{},...p!==void 0?{max_output_tokens:p}:{},...g!==void 0?{tools:g}:{},...y!==void 0?{tool_choice:y}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:A,captureWallMs:P}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(A,P);this.inFlight=(async()=>{let A=[],P=$=>{this.responseFlushed?this.send($):A.push($)},R=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:j("event"),response:this.responseObject(h,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(h,"in_progress")});for(let $ of A)this.send($);A.length=0,this.responseFlushed=!0}},T={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},_=null,C=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(h,T,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.responseObject(h,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(X=>{this.pendingTranscriptSettled=X}),this.cancelled||this.closed))throw new Ut;w=this.items.length,E=Pr(this.items)}let{input:$,sawAudioOnlyItem:N}=E??{input:[],sawAudioOnlyItem:!1},D={...S,input:$,...m?this.compositeTurnAsk(r):{}};N&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let q;try{let X=this.upstreamStream(D,f);Promise.resolve(X).catch(G=>{G instanceof te&&this.failSessionGone(G)}),q=await Promise.race([X,d])}catch(X){if(X instanceof Ut){this.deadlineFired&&!this.closed&&C();return}this.upstreamTurnFault(X,h);return}R();try{for await(let X of this.stallBoundedTurn(q)){if(this.cancelled)break;let G=X;if(G.type==="error"){let re=this.upstreamErrorBody(G);T.contentFlowed?this.send(le(re)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(h,re)});return}if(G.type==="response.output_text.delta"&&typeof G.delta=="string"){R(),T.contentFlowed=!0,T.messageOpen||(this.beginMessageItem(h,T.nextOutputIndex++),T.messageOpen=!0),this.config.outputModalities.includes("text")&&P({type:"response.output_text.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta}),this.turnOutputIsAudio()&&(T.transcriptDelta=!0,P({type:"response.output_audio_transcript.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta})),T.messageText+=G.delta;continue}if(G.type==="response.function_call_arguments.delta"){R(),T.contentFlowed=!0;let re=typeof G.delta=="string"?G.delta:"",K=typeof G.call_id=="string"&&G.call_id.length>0?G.call_id:`${h}_fc_${T.nextOutputIndex}`,M=T.tools.get(K);if(!M){let ee=typeof G.name=="string"&&G.name.length>0?G.name:void 0;M={outputIndex:T.nextOutputIndex++,name:ee,args:""},T.tools.set(K,M);let Fe={id:K,object:"realtime.item",type:"function_call",call_id:K,name:ee??"",arguments:"",status:"in_progress"};P({type:"response.output_item.added",event_id:j("event"),response_id:h,output_index:M.outputIndex,item:Fe}),this.emitAssistantItemAdded(Fe)}typeof G.name=="string"&&G.name.length>0&&(M.name=G.name),M.args+=re,P({type:"response.function_call_arguments.delta",event_id:j("event"),item_id:K,response_id:h,output_index:M.outputIndex,call_id:K,name:M.name??"",delta:re});continue}if(G.type==="response.completed"){_=G.response??null;continue}}}catch(X){if(this.closed)return;if(X instanceof Ut){this.deadlineFired&&C();return}if(this.cancelled)return;if(X instanceof Lr)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${h} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(X,h);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&C();return}this.closeOpenItems(h,T,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.doneResponse(h,w,_)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(T.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=fs){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${fs} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(le(ot("member_unresponsive",`the member served no content for ${fs} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}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.binding.duplex){if(this.activeResponseId===null){if(hs(n))return;this.openDuplexResponse()}else if(hs(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=af){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(hs(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.turnOutputFlowed=!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})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${j("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:j("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}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 l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.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=rt(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??Ye(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(ot(Mo,"the organization is out of credits \u2014 top up to continue"),Mo))}failSessionGone(e){if(e instanceof te&&e.reason===Lo){this.failInsufficientCredits();return}let n=e instanceof Error&&ze(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Ge(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(ot("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof te){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof sl.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=ot(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)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(fe("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:j("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>us&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(le(fe("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>Pn){this.send(le(fe("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${Pn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(le(fe("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(le(ot(null,s instanceof Error?s.message:String(s)))))}}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}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{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>ls){this.ws.close(ef,ms("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=De(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ge(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(tf,ms(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.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>ol(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ol(this.id,e)}},gs=[];function ol(t,e){gs.push({id:t,reason:e}),gs.length>256&&gs.shift()}var Hn="/v1/realtime",il="urun.admission",al=t=>t.slice(0,120);function lf(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 us(t,e){let n=new bt.WebSocketServer({noServer:!0,maxPayload:Wp}),r=new Ct,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,f)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{Ir(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==as){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ir(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(E){let x=e.statusOf?.(E)??null;Ir(c,x?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(m=!0,n.handleUpgrade(d,c,f,E=>{s.delete(c),o.add(E),E.on("close",()=>o.delete(E));try{new is(E,w,r,e.statusOf,e.operatorLog??(x=>console.error(x)))}catch{o.delete(E),E.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&Ir(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=ls();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of o)h.readyState!==bt.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}T();T();var vs=require("@urun-sh/core");T();var ol=require("@urun-sh/core"),Xp={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},Qp={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 Dn(t,e){let n=Qp[t.code];return e?`${n} (${e})`:n}function Tr(t){if(t==null)return null;let e=Xp[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 Or(t){if(t.kind==="create-failed")return Tr(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ol.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Tr(e?"cold_start_exceeded":"queue_timeout")}var Hn=require("ws");T();var ll=require("@urun-sh/core");T();var il=require("crypto");function j(t){return`${t}_${(0,il.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Pr=4*1024*1024,ds=8*1024*1024,cs=512,an=20*1024*1024;function fe(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function ot(t,e){return{type:"server_error",code:t,message:e}}function le(t){return{type:"error",event_id:j("event"),error:t}}function ps(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var z=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Zp={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},ef={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},tf={format:!0,voice:!0,speed:!0};function nf(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function sn(t,e){if(!Array.isArray(t)||t.length===0)throw new z(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new z(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function sl(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new z(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var rf=10;function fs(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:rf})}function Fn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new z("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Zp));if(s.length>0)throw new z(`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=sn(o.modalities,"modalities"),l=sn(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new z("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,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new z(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new z(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: 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(l==="transcription"&&!n.turns)throw new z('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=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new z(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=sn(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new z('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=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!nf(l))throw new z(`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(l!==null&&typeof l!="string")throw new z("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new z("instructions must be a string or null","instructions");i.instructions=fs(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new z("voice must be a string or null","voice");if(!n.voice)throw new z("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new z(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new z("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new z(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new z("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new z("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new z("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new z(`turn_detection.type ${JSON.stringify(u.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[f,h]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new z(`turn_detection.${f} 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.${f}`,"unsupported_field");if(h!=null&&h!==c[f])throw new z(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new z("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(!l||typeof l!="object"||Array.isArray(l))throw new z("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new z(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new z(`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(l!==null)throw new z("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(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new z("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in ef))throw new z(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&sl(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Fn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Fn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new z("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new z("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in tf))throw new z(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&sl(d.format,"audio.output.format"),d.speed!==void 0)throw new z("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 z("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new z("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 Cr(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 ms(t,e){let n=t;if(!n||typeof n!="object")throw new z("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 z("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 z('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new z("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 z("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 z(`${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 z("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 z("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new z("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new z("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new z("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let l=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...l!==void 0?{detail:l}:{}});continue}throw new z(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:j("item"),type:"message",role:r,content:o}}throw new z(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Lr(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 of=1001,sf=1011,af=6e4,lf=3e5,hs=3;var Mr=class extends Error{},$r=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ut=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},gs=t=>t.slice(0,120),uf=/^[A-Za-z0-9+/=]*$/,df=600;function ys(t){return _r(Buffer.from(t,"base64"))}var Bn=class{id=j("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=ps();sessionId=j("sess");conversationId=j("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;userTurnOpen=!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.turnStallMs=e.turnStallMs??af,this.responseDeadlineMs=e.responseDeadlineMs??lf,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.binding.onSessionEnd?.(n=>{n.reason===$o&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:j("event"),session:Cr(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(),this.binding.duplex&&this.ensureVoice();for(let n of e.replayFrames??[])this.onMessage(n)}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 te&&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(ot("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.userTurnOpen=!0,this.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{this.userTurnOpen=!1;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.binding.duplex&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_dropped":{this.userTurnOpen=!1,this.turnTranscript={open:!1,text:"",final:!1},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}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(fe("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Pr){this.fail(fe("frame_too_large",`frame exceeds the ${Pr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(fe("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(fe("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);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}if(o instanceof Mr){this.fail(ot(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
25
+ ${o?.stack??Ge(o)}`),this.send(le(ot(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Fn(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(fe("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:Cr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=ms(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(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(fe("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(fe("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(fe("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(fe("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!uf.test(e.audio)){this.send(le(fe("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>an&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${an}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${an} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>an&&this.pendingAudioBytes.length>0;){let s=this.pendingAudioBytes.shift();o-=Buffer.byteLength(s.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;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.lastCommittedTranscript===null){this.send(le(fe("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(fe("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(fe("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}if(this.binding.duplex){this.send(le(fe("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,gs("session ended by client"))}catch{}});return}case"ping":return;default:this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(fe("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 Mr("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*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0){o=!1;let i=n.next();i.catch(()=>{}),s=r?await Promise.race([i,r]):await i}else{let i,a=new Promise((d,c)=>{i=setTimeout(()=>c(new $r),this.turnStallMs)}),l=n.next();l.catch(()=>{}),s=await(r?Promise.race([l,a,r]):Promise.race([l,a])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return this.config.model&&s.model===void 0&&(s.model=this.config.model),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,n=!1){if(this.inFlight){this.send(le(fe("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?sn(r.modalities,"response.modalities"):void 0,s=r.output_modalities!==void 0?sn(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&s!==void 0&&o.slice().sort().join(",")!==s.slice().sort().join(","))throw new z("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((s??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(le(fe("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.deadlineFired=!1,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},l=new Promise((A,P)=>{a=()=>P(new Ut)});this.turnCancelled=l,this.wakeTurnCancelled=()=>a(),l.catch(()=>{});let u=()=>{},d=new Promise((A,P)=>{u=()=>P(new Ut)});this.turnDialGate=d,this.wakeTurnDialGate=()=>u(),d.catch(()=>{});let c=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let f=j("req"),h=`resp_${f}`;this.activeResponseId=h,this.activeRequestId=f;let m=this.binding.composite===!0,w=m?0:this.items.length,E=m?null:Lr(this.items),x=fs(typeof r.instructions=="string"?r.instructions:this.config.instructions),v=typeof r.temperature=="number"?r.temperature:this.config.temperature,_=r.max_output_tokens??this.config.maxOutputTokens,p=_==="inf"||_===void 0?void 0:_,g=r.tools!==void 0?r.tools:this.config.tools,y=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...x!==void 0?{instructions:x}:{},...v!==void 0?{temperature:v}:{},...p!==void 0?{max_output_tokens:p}:{},...g!==void 0?{tools:g}:{},...y!==void 0?{tool_choice:y}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:A,captureWallMs:P}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(A,P);this.inFlight=(async()=>{let A=[],P=$=>{this.responseFlushed?this.send($):A.push($)},R=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:j("event"),response:this.responseObject(h,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(h,"in_progress")});for(let $ of A)this.send($);A.length=0,this.responseFlushed=!0}},O={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},b=null,C=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(h,O,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.responseObject(h,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(X=>{this.pendingTranscriptSettled=X}),this.cancelled||this.closed))throw new Ut;w=this.items.length,E=Lr(this.items)}let{input:$,sawAudioOnlyItem:M}=E??{input:[],sawAudioOnlyItem:!1},U={...S,input:$,...m?this.compositeTurnAsk(r):{}};M&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let q;try{let X=this.upstreamStream(U,f);Promise.resolve(X).catch(G=>{G instanceof te&&this.failSessionGone(G)}),q=await Promise.race([X,d])}catch(X){if(X instanceof Ut){this.deadlineFired&&!this.closed&&C();return}this.upstreamTurnFault(X,h);return}R();try{for await(let X of this.stallBoundedTurn(q)){if(this.cancelled)break;let G=X;if(G.type==="error"){let re=this.upstreamErrorBody(G);O.contentFlowed?this.send(le(re)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(h,re)});return}if(G.type==="response.output_text.delta"&&typeof G.delta=="string"){R(),O.contentFlowed=!0,O.messageOpen||(this.beginMessageItem(h,O.nextOutputIndex++),O.messageOpen=!0),this.config.outputModalities.includes("text")&&P({type:"response.output_text.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta}),this.turnOutputIsAudio()&&(O.transcriptDelta=!0,P({type:"response.output_audio_transcript.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta})),O.messageText+=G.delta;continue}if(G.type==="response.function_call_arguments.delta"){R(),O.contentFlowed=!0;let re=typeof G.delta=="string"?G.delta:"",K=typeof G.call_id=="string"&&G.call_id.length>0?G.call_id:`${h}_fc_${O.nextOutputIndex}`,N=O.tools.get(K);if(!N){let ee=typeof G.name=="string"&&G.name.length>0?G.name:void 0;N={outputIndex:O.nextOutputIndex++,name:ee,args:""},O.tools.set(K,N);let Fe={id:K,object:"realtime.item",type:"function_call",call_id:K,name:ee??"",arguments:"",status:"in_progress"};P({type:"response.output_item.added",event_id:j("event"),response_id:h,output_index:N.outputIndex,item:Fe}),this.emitAssistantItemAdded(Fe)}typeof G.name=="string"&&G.name.length>0&&(N.name=G.name),N.args+=re,P({type:"response.function_call_arguments.delta",event_id:j("event"),item_id:K,response_id:h,output_index:N.outputIndex,call_id:K,name:N.name??"",delta:re});continue}if(G.type==="response.completed"){b=G.response??null;continue}}}catch(X){if(this.closed)return;if(X instanceof Ut){this.deadlineFired&&C();return}if(this.cancelled)return;if(X instanceof $r)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${h} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(X,h);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&C();return}this.closeOpenItems(h,O,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.doneResponse(h,w,b)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(O.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=hs){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${hs} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(le(ot("member_unresponsive",`the member served no content for ${hs} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}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.binding.duplex){if(this.activeResponseId===null){if(ys(n)||this.userTurnOpen)return;this.openDuplexResponse()}else if(ys(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=df){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(ys(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.turnOutputFlowed=!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})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${j("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:j("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}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 l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.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=rt(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??Ye(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(ot(No,"the organization is out of credits \u2014 top up to continue"),No))}failSessionGone(e){if(e instanceof te&&e.reason===$o){this.failInsufficientCredits();return}let n=e instanceof Error&&ze(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Ge(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(ot("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof te){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof ll.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=ot(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)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(fe("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:j("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>cs&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(le(fe("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>Cn){this.send(le(fe("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${Cn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(le(fe("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(le(ot(null,s instanceof Error?s.message:String(s)))))}}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}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{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>ds){this.ws.close(of,gs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=De(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ge(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(sf,gs(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>al(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),al(this.id,e)}},ws=[];function al(t,e){ws.push({id:t,reason:e}),ws.length>256&&ws.shift()}var jn="/v1/realtime",ul="urun.admission",dl=t=>t.slice(0,120);function cf(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
26
26
  Connection: close\r
27
27
  Content-Type: text/plain\r
28
28
  \r
29
- ${al(n)}\r
30
- `),t.destroy()}function uf(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
31
- `}function df(t){tt(process.stdout,t)}function cf(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function ys(t){return t.audioSession?.audio.sessionId??void 0}function Mr(t,e){let n=new Bn.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Hn)return;r.add(s),s.on("close",()=>{r.delete(s)});let l=j("rtup"),u=cf(o),d=R=>{(e.log??df)(uf(R))};d({stage:"accept",conn:l,model:u}),s.resume();let c=new AbortController,f=null,h=R=>{f??=R,c.abort(new Error(f))},m=()=>h("client socket closed"),w=()=>h("client socket closed (half-close)"),E=R=>h(`client socket error: ${R.message}`);s.once("close",m),s.once("end",w),s.once("error",E);let x=()=>{s.removeListener("close",m),s.removeListener("end",w),s.removeListener("error",E)},b=R=>{d({stage:"close",conn:l,model:u,...R})},v=null,p=!1,g=null,y=R=>JSON.stringify({type:il,event_id:j("event"),...R}),S=R=>{if(v!==null){v.readyState===Bn.WebSocket.OPEN&&v.send(y(R));return}p||(p=!0,n.handleUpgrade(o,s,i,T=>{v=T,g=[],T.on("message",_=>{g?.push(String(_))}),d({stage:"waiting",conn:l,model:u,status:R.status}),T.send(y(R))}))},A=R=>{let T=R,_=T.session!=null&&typeof T.session.sendResponseCreate=="function",C=T.clients!=null&&typeof T.clients.createResponse=="function";if(!_&&!C)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(($,N)=>{let D=(q,X)=>{try{let G=Date.now();new Fn({ws:q,binding:R,operatorLog:e.operatorLog,...X.length>0?{replayFrames:X}:{},onClosed:(re,K)=>{b({while:"live",reason:K.reason});try{e.onSessionEnded?.({req:o,binding:R,connected_ms:Math.max(0,Date.now()-G),reason:K.reason})}catch(M){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${M instanceof Error?M.message:String(M)}
32
- `)}}}),d({stage:"admit",conn:l,model:u,...ys(R)===void 0?{}:{session:ys(R)}}),$()}catch(G){N(G)}};if(v!==null){let q=g??[];g=null,D(v,q);return}n.handleUpgrade(o,s,i,q=>D(q,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,S).then(async R=>{if(c.signal.aborted){x();let T=ys(R);try{await R.release?.()}catch(_){b({while:"queued",...T===void 0?{}:{session:T},reason:f??"client socket closed",release_failed:_ instanceof Error?_.message:String(_)});return}b({while:"queued",...T===void 0?{}:{session:T},reason:f??"client socket closed",released:!0}),s.destroy();return}x(),await A(R)}).catch(R=>{let T=R instanceof ws.SessionFailedError?Ir(R):null,_=null;if(R!==null&&typeof R=="object"&&"status"in R){let D=R.status;typeof D=="number"&&(_=D)}let C=_??T?.status??502,$=R instanceof Error?R.message:String(R),N=_!==null?$:T!==null?Un(T,R instanceof ws.SessionFailedError&&R.status.sessionId?`session ${R.status.sessionId}`:void 0):De(R).message;if(b({while:"queued",...c.signal.aborted?{reason:f??"client socket closed"}:{reason:$,status:C}}),v!==null&&!c.signal.aborted){let D=JSON.stringify({type:il,event_id:j("event"),status:C<500?"rejected":"failed",reason:N});v.readyState===Bn.WebSocket.OPEN&&v.send(D),v.close(1011,al(N));return}s.destroyed||lf(s,C,N)}).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()))}}O();var Xe=require("crypto"),pl=require("dns/promises");O();var ll="/realtime/openai.quic-relay";async function ul(t){let e=await fetch(`${t.sfuBase}${ll}${t.query}`,{method:"POST",headers:{"content-type":"application/json",authorization:t.upstreamHeaders.authorization??""},body:"{}"});if(e.status!==201){let s=await e.text().catch(()=>"");throw new Error(`quic relay ${t.sfuBase}${ll} -> ${e.status} ${s}`)}let n=await e.json(),r=new URL(t.sfuBase).host,o=n.url??`https://${r}:${n.wtPort??4443}/wt`;return{status:201,body:{callId:n.callId,url:o,token:n.token,certHashes:n.certHashes},location:`/v1/realtime/calls/${n.callId}`}}var _s="/v1/realtime/calls",dl="/v1/realtime/client_secrets",pf="session-server-ts-pods.urun.svc.cluster.local",cl=8081,ff="/realtime/openai.relay",mf=262144,hf=600,$r={"access-control-allow-origin":"*","access-control-allow-methods":"POST, OPTIONS","access-control-allow-headers":"authorization, content-type","access-control-max-age":"86400"};function fl(t){let e=t.secret===void 0?void 0:Buffer.from((0,Xe.hkdfSync)("sha256",t.secret,"","urun realtime client secret",32)),n=t.mediaEdges??(async()=>vf(await(0,pl.resolve4)(pf))),r=(o,s,i,a,l=!1)=>{o.writeHead(s,{"content-type":"application/json",...l?$r:{}}),o.end(JSON.stringify({error:{message:i,type:"invalid_request_error",...a?{code:a}:{}}}))};return async(o,s)=>{let i=new URL(o.url??"/","http://proxy"),a=i.pathname===_s;if(o.method==="OPTIONS"&&a)return s.writeHead(204,$r),s.end(),!0;if(o.method!=="POST"||!a&&i.pathname!==dl)return!1;let l=await yf(o);if(l===null)return r(s,413,"request body too large",void 0,a),!0;let u=(o.headers.authorization??"").replace(/^Bearer\s+/i,"");if(u.startsWith("ek_")){let b=e===void 0?null:_f(e,u.slice(3));if(b===null)return r(s,401,"invalid or expired client secret","invalid_api_key",a),!0;o.headers.authorization=`Bearer ${b}`}try{await t.authorize(o)}catch(b){let v=typeof b=="object"&&b!==null&&"status"in b&&typeof b.status=="number"?b.status:401;return r(s,v,b instanceof Error?b.message:String(b),void 0,a),!0}if(i.pathname===dl){if(e===void 0)return r(s,501,"client secrets are not configured on this proxy"),!0;let b=l.length===0?{}:JSON.parse(l.toString("utf8")),v=typeof b=="object"&&b!==null&&"session"in b?b.session:null,p=Math.floor(Date.now()/1e3)+hf,g=(o.headers.authorization??"").replace(/^Bearer\s+/i,"");return s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({value:`ek_${wf(e,g,p)}`,expires_at:p,session:v})),!0}if(i.searchParams.get("transport")==="quic"){let b=i.searchParams.get("model");if(b===null)return r(s,400,"model is required (?model=)",void 0,a),!0;let v=`quic_${(0,Xe.randomUUID)().replaceAll("-","")}`,p=new URLSearchParams(i.searchParams);p.set("model",b),p.set("call_id",v);let g="no media edge resolved";for(let y of await n())try{let S=await ul({sfuBase:`http://${y}:${cl}`,query:`?${p}`,upstreamHeaders:{authorization:o.headers.authorization??""}});return s.writeHead(201,{"content-type":"application/json",location:`${_s}/${S.body.callId}`,...a?$r:{}}),s.end(JSON.stringify(S.body)),!0}catch(S){g=`${y}: ${String(S)}`}return r(s,502,`no media edge accepted the quic call (${g})`,void 0,a),!0}let{sdp:d,session:c}=await gf(o.headers["content-type"]??"",l);if(d===void 0)return r(s,400,"the request carries no SDP offer (application/sdp body or multipart `sdp` field)",void 0,a),!0;let f=typeof c=="object"&&c!==null&&"model"in c&&typeof c.model=="string"?c.model:void 0,h=i.searchParams.get("model")??f;if(h===void 0)return r(s,400,"model is required (?model= or session.model)",void 0,a),!0;let m=`rtc_${(0,Xe.randomUUID)().replaceAll("-","")}`,w=new URLSearchParams(i.searchParams);w.set("model",h),w.set("call_id",m);let E=JSON.stringify({sdp:d,...c!==void 0?{session:c}:{}}),x="no media edge resolved";for(let b of await n()){let v;try{v=await fetch(`http://${b}:${cl}${ff}?${w}`,{method:"POST",headers:{"content-type":"application/json",authorization:o.headers.authorization??""},body:E,signal:AbortSignal.timeout(1e4)})}catch(g){x=`${b}: ${String(g)}`;continue}let p=await v.text();if(v.status===201)return s.writeHead(201,{"content-type":"application/sdp",location:`${_s}/${m}`,...a?$r:{}}),s.end(p),!0;if(v.status>=500||v.status===404||v.status===405||v.status===501){x=`${b}: ${v.status} ${p}`;continue}return r(s,v.status,p,void 0,a),!0}return r(s,503,`no media edge answered the offer (${x})`,"media_edge_unavailable",a),!0}}async function gf(t,e){if(t.startsWith("application/sdp"))return{sdp:e.toString("utf8")};if(!t.startsWith("multipart/form-data"))return{};let n=await new Response(new Uint8Array(e),{headers:{"content-type":t}}).formData(),r=n.get("sdp"),o=n.get("session");return{...typeof r=="string"?{sdp:r}:{},...typeof o=="string"?{session:JSON.parse(o)}:{}}}async function yf(t){let e=[],n=0;for await(let r of t){if(n+=r.length,n>mf)return null;e.push(r)}return Buffer.concat(e)}function wf(t,e,n){let r=(0,Xe.randomBytes)(12),o=(0,Xe.createCipheriv)("aes-256-gcm",t,r),s=Buffer.concat([o.update(JSON.stringify({b:e,e:n}),"utf8"),o.final()]);return Buffer.concat([r,o.getAuthTag(),s]).toString("base64url")}function _f(t,e){try{let n=Buffer.from(e,"base64url"),r=(0,Xe.createDecipheriv)("aes-256-gcm",t,n.subarray(0,12));r.setAuthTag(n.subarray(12,28));let o=JSON.parse(Buffer.concat([r.update(n.subarray(28)),r.final()]).toString("utf8"));if(typeof o!="object"||o===null||!("b"in o)||!("e"in o))return null;let{b:s,e:i}=o;return typeof s!="string"||typeof i!="number"?null:i>Date.now()/1e3?s:null}catch{return null}}function vf(t){for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}O();var su=require("crypto");O();var Zf=require("http");O();var Q=class extends Error{},Pe=class extends Error{};function Re(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function jn(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function ln(t,e){if(t!=null)throw new Q(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function vs(t){let e=jn(t);return e!==null&&e<=1?e:null}function ml(t,e){if(!Re(t))throw new Q("decisions requires a JSON object body");ln(t.prompt_cache_key,"prompt_cache_key"),ln(t.prompt_cache_options,"prompt_cache_options"),ln(t.safety_identifier,"safety_identifier");let n=[],r=bf(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new Q("decisions requires a questions array of 1 to 400 questions");let s={},i=[],a=new Set;for(let u=0;u<o.length;u++){let{entry:d,spec:c}=Ef(o[u],u,o.length,n);if(a.has(c.key))throw new Q(`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 l={model:e,state:r,questions:s};return n.length>0&&(l.media=n),{systemone:l,specs:i}}function bf(t,e){if(typeof t=="string")return t;if(!Re(t)&&!Array.isArray(t))throw new Q("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)kf(o,r,e);return Sf(r)}function Sf(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
29
+ ${dl(n)}\r
30
+ `),t.destroy()}function pf(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
31
+ `}function ff(t){tt(process.stdout,t)}function mf(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function _s(t){return t.audioSession?.audio.sessionId??void 0}function Nr(t,e){let n=new Hn.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==jn)return;r.add(s),s.on("close",()=>{r.delete(s)});let l=j("rtup"),u=mf(o),d=R=>{(e.log??ff)(pf(R))};d({stage:"accept",conn:l,model:u}),s.resume();let c=new AbortController,f=null,h=R=>{f??=R,c.abort(new Error(f))},m=()=>h("client socket closed"),w=()=>h("client socket closed (half-close)"),E=R=>h(`client socket error: ${R.message}`);s.once("close",m),s.once("end",w),s.once("error",E);let x=()=>{s.removeListener("close",m),s.removeListener("end",w),s.removeListener("error",E)},v=R=>{d({stage:"close",conn:l,model:u,...R})},_=null,p=!1,g=null,y=R=>JSON.stringify({type:ul,event_id:j("event"),...R}),S=R=>{if(_!==null){_.readyState===Hn.WebSocket.OPEN&&_.send(y(R));return}p||(p=!0,n.handleUpgrade(o,s,i,O=>{_=O,g=[],O.on("message",b=>{g?.push(String(b))}),d({stage:"waiting",conn:l,model:u,status:R.status}),O.send(y(R))}))},A=R=>{let O=R,b=O.session!=null&&typeof O.session.sendResponseCreate=="function",C=O.clients!=null&&typeof O.clients.createResponse=="function";if(!b&&!C)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(($,M)=>{let U=(q,X)=>{try{let G=Date.now();new Bn({ws:q,binding:R,operatorLog:e.operatorLog,...X.length>0?{replayFrames:X}:{},onClosed:(re,K)=>{v({while:"live",reason:K.reason});try{e.onSessionEnded?.({req:o,binding:R,connected_ms:Math.max(0,Date.now()-G),reason:K.reason})}catch(N){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${N instanceof Error?N.message:String(N)}
32
+ `)}}}),d({stage:"admit",conn:l,model:u,..._s(R)===void 0?{}:{session:_s(R)}}),$()}catch(G){M(G)}};if(_!==null){let q=g??[];g=null,U(_,q);return}n.handleUpgrade(o,s,i,q=>U(q,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,S).then(async R=>{if(c.signal.aborted){x();let O=_s(R);try{await R.release?.()}catch(b){v({while:"queued",...O===void 0?{}:{session:O},reason:f??"client socket closed",release_failed:b instanceof Error?b.message:String(b)});return}v({while:"queued",...O===void 0?{}:{session:O},reason:f??"client socket closed",released:!0}),s.destroy();return}x(),await A(R)}).catch(R=>{let O=R instanceof vs.SessionFailedError?Or(R):null,b=null;if(R!==null&&typeof R=="object"&&"status"in R){let U=R.status;typeof U=="number"&&(b=U)}let C=b??O?.status??502,$=R instanceof Error?R.message:String(R),M=b!==null?$:O!==null?Dn(O,R instanceof vs.SessionFailedError&&R.status.sessionId?`session ${R.status.sessionId}`:void 0):De(R).message;if(v({while:"queued",...c.signal.aborted?{reason:f??"client socket closed"}:{reason:$,status:C}}),_!==null&&!c.signal.aborted){let U=JSON.stringify({type:ul,event_id:j("event"),status:C<500?"rejected":"failed",reason:M});_.readyState===Hn.WebSocket.OPEN&&_.send(U),_.close(1011,dl(M));return}s.destroyed||cf(s,C,M)}).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()))}}T();var Xe=require("crypto"),hl=require("dns/promises");T();var cl="/realtime/openai.quic-relay";async function pl(t){let e=await fetch(`${t.sfuBase}${cl}${t.query}`,{method:"POST",headers:{"content-type":"application/json",authorization:t.upstreamHeaders.authorization??""},body:"{}"});if(e.status!==201){let s=await e.text().catch(()=>"");throw new Error(`quic relay ${t.sfuBase}${cl} -> ${e.status} ${s}`)}let n=await e.json(),r=new URL(t.sfuBase).host,o=n.url??`https://${r}:${n.wtPort??4443}/wt`;return{status:201,body:{callId:n.callId,url:o,token:n.token,certHashes:n.certHashes},location:`/v1/realtime/calls/${n.callId}`}}var bs="/v1/realtime/calls",fl="/v1/realtime/client_secrets",hf="session-server-ts-pods.urun.svc.cluster.local",ml=8081,gf="/realtime/openai.relay",yf=262144,wf=600,Ur={"access-control-allow-origin":"*","access-control-allow-methods":"POST, OPTIONS","access-control-allow-headers":"authorization, content-type","access-control-max-age":"86400"};function gl(t){let e=t.secret===void 0?void 0:Buffer.from((0,Xe.hkdfSync)("sha256",t.secret,"","urun realtime client secret",32)),n=t.mediaEdges??(async()=>kf(await(0,hl.resolve4)(hf))),r=(o,s,i,a,l=!1)=>{o.writeHead(s,{"content-type":"application/json",...l?Ur:{}}),o.end(JSON.stringify({error:{message:i,type:"invalid_request_error",...a?{code:a}:{}}}))};return async(o,s)=>{let i=new URL(o.url??"/","http://proxy"),a=i.pathname===bs;if(o.method==="OPTIONS"&&a)return s.writeHead(204,Ur),s.end(),!0;if(o.method!=="POST"||!a&&i.pathname!==fl)return!1;let l=await vf(o);if(l===null)return r(s,413,"request body too large",void 0,a),!0;let u=(o.headers.authorization??"").replace(/^Bearer\s+/i,"");if(u.startsWith("ek_")){let v=e===void 0?null:Sf(e,u.slice(3));if(v===null)return r(s,401,"invalid or expired client secret","invalid_api_key",a),!0;o.headers.authorization=`Bearer ${v}`}try{await t.authorize(o)}catch(v){let _=typeof v=="object"&&v!==null&&"status"in v&&typeof v.status=="number"?v.status:401;return r(s,_,v instanceof Error?v.message:String(v),void 0,a),!0}if(i.pathname===fl){if(e===void 0)return r(s,501,"client secrets are not configured on this proxy"),!0;let v=l.length===0?{}:JSON.parse(l.toString("utf8")),_=typeof v=="object"&&v!==null&&"session"in v?v.session:null,p=Math.floor(Date.now()/1e3)+wf,g=(o.headers.authorization??"").replace(/^Bearer\s+/i,"");return s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({value:`ek_${bf(e,g,p)}`,expires_at:p,session:_})),!0}if(i.searchParams.get("transport")==="quic"){let v=i.searchParams.get("model");if(v===null)return r(s,400,"model is required (?model=)",void 0,a),!0;let _=`quic_${(0,Xe.randomUUID)().replaceAll("-","")}`,p=new URLSearchParams(i.searchParams);p.set("model",v),p.set("call_id",_);let g="no media edge resolved";for(let y of await n())try{let S=await pl({sfuBase:`http://${y}:${ml}`,query:`?${p}`,upstreamHeaders:{authorization:o.headers.authorization??""}});return s.writeHead(201,{"content-type":"application/json",location:`${bs}/${S.body.callId}`,...a?Ur:{}}),s.end(JSON.stringify(S.body)),!0}catch(S){g=`${y}: ${String(S)}`}return r(s,502,`no media edge accepted the quic call (${g})`,void 0,a),!0}let{sdp:d,session:c}=await _f(o.headers["content-type"]??"",l);if(d===void 0)return r(s,400,"the request carries no SDP offer (application/sdp body or multipart `sdp` field)",void 0,a),!0;let f=typeof c=="object"&&c!==null&&"model"in c&&typeof c.model=="string"?c.model:void 0,h=i.searchParams.get("model")??f;if(h===void 0)return r(s,400,"model is required (?model= or session.model)",void 0,a),!0;let m=`rtc_${(0,Xe.randomUUID)().replaceAll("-","")}`,w=new URLSearchParams(i.searchParams);w.set("model",h),w.set("call_id",m);let E=JSON.stringify({sdp:d,...c!==void 0?{session:c}:{}}),x="no media edge resolved";for(let v of await n()){let _;try{_=await fetch(`http://${v}:${ml}${gf}?${w}`,{method:"POST",headers:{"content-type":"application/json",authorization:o.headers.authorization??""},body:E,signal:AbortSignal.timeout(1e4)})}catch(g){x=`${v}: ${String(g)}`;continue}let p=await _.text();if(_.status===201)return s.writeHead(201,{"content-type":"application/sdp",location:`${bs}/${m}`,...a?Ur:{}}),s.end(p),!0;if(_.status>=500||_.status===404||_.status===405||_.status===501){x=`${v}: ${_.status} ${p}`;continue}return r(s,_.status,p,void 0,a),!0}return r(s,503,`no media edge answered the offer (${x})`,"media_edge_unavailable",a),!0}}async function _f(t,e){if(t.startsWith("application/sdp"))return{sdp:e.toString("utf8")};if(!t.startsWith("multipart/form-data"))return{};let n=await new Response(new Uint8Array(e),{headers:{"content-type":t}}).formData(),r=n.get("sdp"),o=n.get("session");return{...typeof r=="string"?{sdp:r}:{},...typeof o=="string"?{session:JSON.parse(o)}:{}}}async function vf(t){let e=[],n=0;for await(let r of t){if(n+=r.length,n>yf)return null;e.push(r)}return Buffer.concat(e)}function bf(t,e,n){let r=(0,Xe.randomBytes)(12),o=(0,Xe.createCipheriv)("aes-256-gcm",t,r),s=Buffer.concat([o.update(JSON.stringify({b:e,e:n}),"utf8"),o.final()]);return Buffer.concat([r,o.getAuthTag(),s]).toString("base64url")}function Sf(t,e){try{let n=Buffer.from(e,"base64url"),r=(0,Xe.createDecipheriv)("aes-256-gcm",t,n.subarray(0,12));r.setAuthTag(n.subarray(12,28));let o=JSON.parse(Buffer.concat([r.update(n.subarray(28)),r.final()]).toString("utf8"));if(typeof o!="object"||o===null||!("b"in o)||!("e"in o))return null;let{b:s,e:i}=o;return typeof s!="string"||typeof i!="number"?null:i>Date.now()/1e3?s:null}catch{return null}}function kf(t){for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}T();var lu=require("crypto");T();var em=require("http");T();var Q=class extends Error{},Pe=class extends Error{};function Re(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qn(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function un(t,e){if(t!=null)throw new Q(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Ss(t){let e=qn(t);return e!==null&&e<=1?e:null}function yl(t,e){if(!Re(t))throw new Q("decisions requires a JSON object body");un(t.prompt_cache_key,"prompt_cache_key"),un(t.prompt_cache_options,"prompt_cache_options"),un(t.safety_identifier,"safety_identifier");let n=[],r=Rf(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new Q("decisions requires a questions array of 1 to 400 questions");let s={},i=[],a=new Set;for(let u=0;u<o.length;u++){let{entry:d,spec:c}=If(o[u],u,o.length,n);if(a.has(c.key))throw new Q(`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 l={model:e,state:r,questions:s};return n.length>0&&(l.media=n),{systemone:l,specs:i}}function Rf(t,e){if(typeof t=="string")return t;if(!Re(t)&&!Array.isArray(t))throw new Q("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)xf(o,r,e);return Ef(r)}function Ef(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
33
33
 
34
- `)}function kf(t,e,n){if(!Re(t))throw new Q("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){Rf(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)){hl(s,e,n,void 0,!1);return}throw new Q(`${o} output must be a string or an array of parts`)}default:throw new Q(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function Rf(t,e,n,r){e==="assistant"&&ln(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 Q(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!Re(s))throw new Q("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 Q(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}hl(o,n,r,e)}function hl(t,e,n,r,o=!0){for(let s of t){if(!Re(s))throw new Q("decisions content parts must be JSON objects");switch(ln(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new Q("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new Q("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(!Re(i)&&!(Array.isArray(i)&&i.every(Re)))throw new Q("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(gl(s));break}default:throw new Q(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function gl(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new Q("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new Q("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 Q("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 Q("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 Q("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 Ef(t,e,n,r){if(!Re(t))throw new Q(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new Q(`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 Q(`questions[${e}] name must be a string`);let i=s??null,a=i??`q${e}`,l=xf(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:l,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:a,name:i}};case"choice":{let u=t.choices;if(!Array.isArray(u)||u.length<2||u.length>255)throw new Q(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,f=[];for(let w of u){if(!Re(w))throw new Q(`questions[${e}] choices must be JSON objects`);let E=w.value;if(typeof E!="string"&&typeof E!="boolean")throw new Q(`questions[${e}] choice value must be a string or boolean`);let x=String(E);if(c.has(x))throw new Q(`questions[${e}] has duplicate choice value ${JSON.stringify(x)} (choices must be unique)`);c.add(x);let b=w.description;if(b!==void 0&&typeof b!="string")throw new Q(`questions[${e}] choice description must be a string`);d.push(E),f.push(b)}let h=u.map((w,E)=>({name:String(d[E]),description:f[E]??String(d[E])}));return{entry:{kind:"choice",prompt:l,options:h},spec:{type:o,key:a,name:i,choiceValues:d}}}case"score":{let u=t.levels;if(!Array.isArray(u)||u.length<2||u.length>10)throw new Q(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let h of u){if(!Re(h)||typeof h.label!="string")throw new Q(`questions[${e}] score levels must carry a string label`);if(d.includes(h.label))throw new Q(`questions[${e}] has duplicate level label ${JSON.stringify(h.label)}`);d.push(h.label);let m=h.description;if(m!==void 0&&typeof m!="string")throw new Q(`questions[${e}] score level description must be a string`);let w=m!==void 0?`${h.label}: ${m}`:h.label;if(c.includes(w))throw new Q(`questions[${e}] has duplicate score criterion ${JSON.stringify(w)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(w)}return{entry:{kind:"score",prompt:l,criteria:c},spec:{type:o,key:a,name:i,levelLabels:d}}}}}function xf(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new Q(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!Re(s))throw new Q(`questions[${e}] instruction parts must be JSON objects`);switch(ln(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new Q(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new Q(`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(gl(s));break}case"input_json":{let i=s.data;if(!Re(i)&&!(Array.isArray(i)&&i.every(Re)))throw new Q(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new Q(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
34
+ `)}function xf(t,e,n){if(!Re(t))throw new Q("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){Af(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)){wl(s,e,n,void 0,!1);return}throw new Q(`${o} output must be a string or an array of parts`)}default:throw new Q(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function Af(t,e,n,r){e==="assistant"&&un(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 Q(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!Re(s))throw new Q("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 Q(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}wl(o,n,r,e)}function wl(t,e,n,r,o=!0){for(let s of t){if(!Re(s))throw new Q("decisions content parts must be JSON objects");switch(un(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new Q("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new Q("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(!Re(i)&&!(Array.isArray(i)&&i.every(Re)))throw new Q("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(_l(s));break}default:throw new Q(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function _l(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new Q("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new Q("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 Q("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 Q("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 Q("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 If(t,e,n,r){if(!Re(t))throw new Q(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new Q(`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 Q(`questions[${e}] name must be a string`);let i=s??null,a=i??`q${e}`,l=Tf(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:l,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:a,name:i}};case"choice":{let u=t.choices;if(!Array.isArray(u)||u.length<2||u.length>255)throw new Q(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,f=[];for(let w of u){if(!Re(w))throw new Q(`questions[${e}] choices must be JSON objects`);let E=w.value;if(typeof E!="string"&&typeof E!="boolean")throw new Q(`questions[${e}] choice value must be a string or boolean`);let x=String(E);if(c.has(x))throw new Q(`questions[${e}] has duplicate choice value ${JSON.stringify(x)} (choices must be unique)`);c.add(x);let v=w.description;if(v!==void 0&&typeof v!="string")throw new Q(`questions[${e}] choice description must be a string`);d.push(E),f.push(v)}let h=u.map((w,E)=>({name:String(d[E]),description:f[E]??String(d[E])}));return{entry:{kind:"choice",prompt:l,options:h},spec:{type:o,key:a,name:i,choiceValues:d}}}case"score":{let u=t.levels;if(!Array.isArray(u)||u.length<2||u.length>10)throw new Q(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let h of u){if(!Re(h)||typeof h.label!="string")throw new Q(`questions[${e}] score levels must carry a string label`);if(d.includes(h.label))throw new Q(`questions[${e}] has duplicate level label ${JSON.stringify(h.label)}`);d.push(h.label);let m=h.description;if(m!==void 0&&typeof m!="string")throw new Q(`questions[${e}] score level description must be a string`);let w=m!==void 0?`${h.label}: ${m}`:h.label;if(c.includes(w))throw new Q(`questions[${e}] has duplicate score criterion ${JSON.stringify(w)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(w)}return{entry:{kind:"score",prompt:l,criteria:c},spec:{type:o,key:a,name:i,levelLabels:d}}}}}function Tf(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new Q(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!Re(s))throw new Q(`questions[${e}] instruction parts must be JSON objects`);switch(un(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new Q(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new Q(`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(_l(s));break}case"input_json":{let i=s.data;if(!Re(i)&&!(Array.isArray(i)&&i.every(Re)))throw new Q(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new Q(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
35
35
 
36
- `)}function yl(t,e){if(!Re(e))throw new Pe("decision answer was not a JSON object");let n=e.answers;if(!Re(n))throw new Pe("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!Re(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=Re(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let a=vs(s.noul);if(a===null)throw new Pe(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:a});continue}case"choice":{let a=o.choiceValues??[],l=s.choice;if(typeof l!="string")throw new Pe(`the choice answer for "${o.key}" carries no string choice`);let u=a.findIndex(f=>String(f)===l);if(u===-1)throw new Pe(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(l)})`);let d=jn(s.confidence);if(d===null)throw new Pe(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let f of a){let h=vs(i[String(f)]);h!==null&&c.push({value:f,probability:h})}r.push({type:"choice",name:o.name,choice:a[u],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],l=jn(s.score);if(l===null)throw new Pe(`the score answer for "${o.key}" carries no numeric score to translate`);let u=jn(s.confidence);if(u===null)throw new Pe(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<a.length;c++){let f=vs(i[String(c)]);f!==null&&d.push({value:c,label:a[c],probability:f})}r.push({type:"score",name:o.name,score:l,confidence:u,probabilities:d});continue}}}return r}function an(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function Af(t){let e=Re(t.input_tokens_details)?t.input_tokens_details.cached_tokens:void 0,n=e!==void 0?e:t.cached_tokens;return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?n:0}function wl(t){if(t==null)return null;if(!Re(t))throw new Pe("decision reply carried a usage receipt that is not a JSON object");let e=an(t.prompt_tokens)??an(t.input_tokens),n=an(t.completion_tokens)??an(t.output_tokens);if(e===null||n===null)throw new Pe("decision reply carried a usage receipt with no usable token counts");let r=jn(t.ttft_ms),o=an(t.total_tokens)??an(e+n);if(o===null)throw new Pe("decision reply carried a usage receipt with an unusable token total");return{input_tokens:e,input_tokens_details:{cache_write_tokens:0,cached_tokens:Af(t)},output_tokens:n,output_tokens_details:{reasoning_tokens:0},total_tokens:o,...r!==null?{ttft_ms:r}:{}}}O();O();var Ie=class extends Error{};async function Nr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Ie(`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 Ie(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function Ur(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 Ie(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[u,d]of Object.entries(t.headers))if(typeof d=="string")i.set(u,d);else if(Array.isArray(d))for(let c of d)i.append(u,c);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof Ie?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var _l="/v1/images/generations",Dr="/v1/images/edits";function vl(t){return t===_l||t===Dr}var bl="/v1/images/models";async function Sl(t,e,n){if(t){if(t.model=Ce({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 se=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},If=16*1024*1024,kl=64*1024*1024;function Rl(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 qn(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 El(t,e,n,r,o,s){let i=s??(m=>console.error(m)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),l=null;for await(let m of a){if(m.type==="error"){let w=m.error??{},E=typeof w.message=="string"&&w.message.length>0&&ze(w.message)?w.message:null;throw E===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(m)}`),new se(502,"the image upstream failed while serving this request")):new se(502,`image upstream error: ${E}`)}if(m.type==="response.completed"){l=m.response??null;break}}if(l===null)throw new se(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=dt(l));let u=l.images;if(!Array.isArray(u)||u.length!==1||typeof u[0]!="string"||u[0].length===0)throw new se(502,`image upstream returned ${Array.isArray(u)?u.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=u[0].startsWith("data:")?u[0].slice(u[0].indexOf(";base64,")+8):u[0],f=Buffer.from(c,"base64");if(Rl(f)===null)throw new se(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${f.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function xl(t,e){if(t instanceof se)return t;if(t instanceof qe)throw t;return t instanceof ie?new se(404,t.message):new se(502,rn("image",t,e))}async function Al(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 qn(r,new se(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 Il(t,e){t&&(t.outputUnits=e.images.length)}function Ol(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 Of={model:!0,prompt:!0,response_format:!0,n:!0};async function Tl(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??kl;try{if(t.method!=="POST")throw new se(405,`${String(t.method)} is not supported on ${_l}`);let s;try{s=JSON.parse((await Nr(t,o)).toString("utf8")||"{}")}catch(f){throw f instanceof Ie?new se(413,f.message):new se(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new se(400,"request body must be a JSON object");let i=s;for(let f of Object.keys(i))if(!Of[f])throw new se(400,`request field "${f}" 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.`,f);let a=i.prompt;if(typeof a!="string"||a.trim().length===0)throw new se(400,"prompt is required and must be a non-empty string","prompt");let l=i.model===void 0?void 0:i.model;if(l!==void 0&&typeof l!="string")throw new se(400,"model must be a string","model");await Sl(n.turn,n.clients,l);let u=i.n??1;if(u!==1)throw new se(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new se(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 Al(n.imageModels,l,"generation",e))return;let c=[{type:"input_text",text:a}];try{let f=await El(n.clients,l,c,n.turn?He(n.turn):void 0,n.turn,r);Il(n.turn,f),Ol(e,f)}catch(f){throw xl(f,r)}}catch(s){if(s instanceof Ie){qn(e,new se(413,s.message));return}if(s instanceof se){qn(e,s);return}throw s}}var Tf={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Pl(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??kl,s=n.maxImagePartBytes??If;try{if(t.method!=="POST")throw new se(405,`${String(t.method)} is not supported on ${Dr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new se(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await Ur(t,o)}catch(m){throw m instanceof Ie?new se(413,m.message):new se(400,String(m instanceof Error?m.message:m))}let l=a.get("prompt");if(typeof l!="string"||l.trim().length===0)throw new se(400,"prompt is required and must be a non-empty string field","prompt");let u=a.get("model");if(u!==null&&typeof u!="string")throw new se(400,"model must be a string field","model");let d=u===null?void 0:u;await Sl(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new se(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 m of a.keys())if(!Tf[m])throw new se(400,`form field "${m}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,m);let f=[];for(let m of["image","image[]"])for(let w of a.getAll(m)){if(!(w instanceof File))throw new se(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(w.size>s)throw new se(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let E=new Uint8Array(await w.arrayBuffer()),x=Rl(E);if(x===null)throw new se(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);f.push({bytes:E,mime:x})}if(f.length===0)throw new se(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",l.length,l.length),!await Al(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:l}];for(let{bytes:m,mime:w}of f)h.push({type:"input_image",image_url:`data:${w};base64,${Buffer.from(m).toString("base64")}`});try{let m=await El(n.clients,d,h,n.turn?He(n.turn):void 0,n.turn,r);Il(n.turn,m),Ol(e,m)}catch(m){throw xl(m,r)}}catch(i){if(i instanceof Ie){qn(e,new se(413,i.message));return}if(i instanceof se){qn(e,i);return}throw i}}O();var Gn="/v1/audio/speech";function Bl(t){return t===Gn}var Cl=4096,Ll=18e4,Ml=5e3,Pf=64*1024*1024,$l=8,Nl=5,Ul=1024*1024,un="voice_applied",Br="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 bs(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 Hr=class extends Z{constructor(e){super(502,e)}};function Hl(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 jl(t){return new Z(502,`the runtime's ${un} receipt ${JSON.stringify(t)} cannot be relayed as the ${Br} 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 Cf(t,e,n){if(t){if(t.model=Ce({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 ql(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Lf=2;function Mf(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Lf)return!1;return!0}function $f(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 Dl=new WeakMap,Fr=new WeakMap;function Nf(t,e){let n=Fr.get(t)??0;if(n>=$l)throw new Z(503,`this model's speech queue is full \u2014 ${$l} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Nl}s`,void 0,Nl);Fr.set(t,n+1);let r=Dl.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Dl.set(t,s),(async()=>{await r;try{return await e()}finally{Fr.set(t,(Fr.get(t)??1)-1),o()}})()}async function Uf(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 te))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(()=>{clearTimeout(s)})}function Dt(t,e){if(t instanceof Z)return t;if(t instanceof qe)throw t;return t instanceof ie?new Z(404,t.message):new Z(502,rn("speech",t,e))}async function Fl(t,e,n,r,o,s,i,a,l,u){let d=u??(f=>console.error(f)),c=a??(()=>{});return Nf(e,async()=>{if(i?.()===!0)return null;let f=!1,h=!1,m=!1,w,E=new Promise(T=>{w=T}),x=[],b,v=!1,p=null,g=()=>{p!==null&&(clearTimeout(b),b=setTimeout(()=>{v=!0,p?.()},o.capMs))},y=()=>{h&&!m&&x.length>=o.quietRunFrames&&(m=!0,w())},S=e.onOutputAudio(T=>{let _=Buffer.from(T,"base64");if(_.byteLength===0)return;g();let C=Mf(_);if(!f){if(C)return;f=!0}if(C){x.push(_),y();return}for(let $ of x)c($);x.length=0,c(_),y()}),A=null,P,R;try{R=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let _=()=>(clearTimeout(P),new Promise(D=>{P=setTimeout(D,s.capMs)})),C=_(),$=!1;for(;;){let D=R.next(),q=await Promise.race([D,C]);if(q===void 0){$=!0,D.catch(()=>{});break}if(q.done)break;let X=q.value;if(C=_(),X.type==="error"){let G=X.error??{};await R.return?.();let re=typeof G.message=="string"&&G.message.length>0&&ze(G.message)?G.message:null;throw re===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(X)}`),new Z(502,"the speech upstream failed while serving this request")):new Z(502,`speech upstream error: ${re}`)}if(X.type==="response.completed"){A=X.response??null,h=!0,l?.(A),y(),await R.return?.();break}}if(clearTimeout(P),$)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(A===null)throw new Z(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let N=new Promise(D=>{p=D});if(g(),await Promise.race([E,N]),clearTimeout(b),b=void 0,p=null,r.voice!==void 0){let D=A[un];if(typeof D!="string"||D!==r.voice){let q=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof D=="string"?`${un} ${JSON.stringify(D)}`:`no ${un} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw m?new Hr(q):new Z(502,q)}}if(!f)throw new Z(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(v&&!m&&x.length<1)throw new Z(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return A}catch(T){throw T instanceof Hr||await Uf(t,n,R,s.returnBoundMs),T}finally{clearTimeout(b),clearTimeout(P),S()}})}function Df(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",Br)),t.write(a,l=>{l||(s+=a.byteLength,ql(e,s))}),t.writableLength>Ul&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Ul} 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 l=a[un];if(typeof l=="string"){if(!Hl(l))throw jl(l);t.addTrailers({[Br]:l})}}await new Promise(l=>{t.end(()=>l())})}},fail:i}}async function Ff(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Dt(s,r)}return o?!0:(bs(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 Bf={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Hf="wav, pcm";async function Gl(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??Pf,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 ${Gn}`);let a;try{a=JSON.parse((await Nr(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof Ie?new Z(413,p.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 l=a;for(let p of Object.keys(l))if(!Bf[p])throw new Z(400,`request field "${p}" 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.`,p);let u=l.input;if(typeof u!="string"||u.trim().length===0)throw new Z(400,"input is required and must be a non-empty string","input");if(u.length>Cl)throw new Z(400,`input is ${u.length} chars \u2014 over the ${Cl}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=l.model===void 0?void 0:l.model;if(d!==void 0&&typeof d!="string")throw new Z(400,"model must be a string","model");let c=l.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 ${Gn} against a stale copy of the list`);let f;try{f=await n.clients.speechVoices(d)}catch(p){throw Dt(p,r)}if(f.defect!==null)throw new Z(500,`the voice set for this model cannot be resolved: ${f.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let h=typeof c=="string"?c:void 0;if(h!==void 0&&f.published.length>0&&!f.published.includes(h))throw new Z(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${f.published.join(", ")}`,"voice");let m=l.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new Z(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Hf} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(l.stream_format!==void 0&&typeof l.stream_format!="string")throw new Z(400,"stream_format, when present, must be a string","stream_format");let w=l.speed;if(w!==void 0){if(typeof w!="number"||!Number.isFinite(w))throw new Z(400,"speed, when present, must be a number","speed");if(w!==1)throw new Z(400,`speed=${JSON.stringify(w)} 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 E=l.instructions;if(E!==void 0){if(typeof E!="string")throw new Z(400,"instructions, when present, must be a string","instructions");if(E.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 Cf(n.turn,n.clients,d);let x=Buffer.byteLength(JSON.stringify(l));if(n.stats?.request("audio_speech",x,x),!await Ff(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 b;try{b=await n.clients.speechSessionHandle(d)}catch(p){throw Dt(p,r)}let v;try{v=await n.clients.openAudioOn(b)}catch(p){throw Dt(p,r)}n.turn&&(n.turn.sessionId=v.sessionId);try{if(m==="wav"){let p=[],g=await Fl(n.clients,v,b,{model:d,text:u,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ll,returnBoundMs:n.turnReturnBoundMs??Ml},i,S=>p.push(S),S=>{n.turn&&(n.turn.outputSeconds=dt(S))},r);if(g===null||i())return;let y=Buffer.concat(p);if(h===void 0){let S=g[un];if(typeof S=="string"){if(!Hl(S))throw jl(S);e.setHeader(Br,S)}}ql(n.turn,y.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([$f(y.byteLength),y]))}else{let p=Df(e,n.turn,i,h===void 0),g;try{g=await Fl(n.clients,v,b,{model:d,text:u,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ll,returnBoundMs:n.turnReturnBoundMs??Ml},i,p.sink,y=>{n.turn&&(n.turn.outputSeconds=dt(y))},r)}catch(y){let S=Dt(y,r);if(!p.started())throw S;n.turn&&(n.turn.streamError=!0),p.fail(S);return}if(g===null)return;try{await p.finish(g)}catch(y){let S=Dt(y,r);n.turn&&(n.turn.streamError=!0),p.fail(S);return}}}catch(p){throw Dt(p,r)}}catch(a){if(a instanceof Ie){bs(e,new Z(413,a.message));return}if(a instanceof Z){bs(e,a);return}throw a}}O();var jr="/v1/audio/transcriptions";function Wl(t){return t===jr}var Jl="/v1/audio/models",jf=16*1024*1024,qf=64*1024*1024,ge=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Ss(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 Vl(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 Gf(t){if(!Vl(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 l=t[a+2]|t[a+3]<<8,u=(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:u,channels:l,bitsPerSample:d}}else if(s==="data"){let l=t.length-a;r=Math.min(i===0||i===4294967295?l:i,l)}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 Wf(t,e,n){if(t){if(t.model=Ce({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 Jf(t,e){t&&(t.outputUnits=e.seconds)}async function Vf(t,e,n,r,o,s,i){let a=i??(c=>console.error(c)),l=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),u=[],d=null;for await(let c of l){if(u.push(c),c.type==="error"){let f=c.error??{},h=typeof f.type=="string"?f.type:"upstream_error",m=typeof f.message=="string"&&f.message.length>0&&ze(f.message)?f.message:null;throw m===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new ge(h==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new ge(h==="invalid_request_error"?400:502,`transcription upstream error: ${m}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new ge(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=dt(d)),tn(u,d)}function Kl(t,e){if(t instanceof ge)return t;if(t instanceof qe)throw t;return t instanceof ie?new ge(404,t.message):new ge(502,rn("transcription",t,e))}async function Kf(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Kl(s,r)}return o?!0:(Ss(n,new ge(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 zf=new Set(["file","model","language","response_format"]);async function zl(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??qf,s=n.maxAudioPartBytes??jf;try{if(t.method!=="POST")throw new ge(405,`${String(t.method)} is not supported on ${jr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new ge(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await Ur(t,o)}catch(b){throw b instanceof Ie?new ge(413,b.message):new ge(400,String(b instanceof Error?b.message:b))}let l=new Map;for(let b of a.keys()){if(!zf.has(b))throw new ge(400,`form field "${b}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,b);l.set(b,(l.get(b)??0)+1)}for(let[b,v]of l)if(v>1)throw new ge(400,`form field "${b}" appears ${v} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,b);let u=a.get("model");if(u!==null&&typeof u!="string")throw new ge(400,"model must be a string field","model");let d=u===null?void 0:u,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new ge(400,"language, when present, must be a non-empty string","language");let f=c===null?void 0:c,h=a.get("response_format")??"json";if(h!=="json")throw new ge(400,`response_format ${JSON.stringify(h)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let m=a.get("file");if(!(m instanceof File))throw new ge(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>s)throw new ge(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let w=new Uint8Array(await m.arrayBuffer());if(!Vl(w))throw new ge(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 E=Gf(w);if(E===null)throw new ge(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 Wf(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",w.length,w.length),!await Kf(n.transcriptionModels,d,e,r))return;let x=[{type:"input_audio",input_audio:{data:Buffer.from(w).toString("base64"),format:"wav"}}];try{let b=await Vf(n.clients,d,x,f,n.turn?He(n.turn):void 0,n.turn,r);Jf(n.turn,E),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:b}))}catch(b){throw Kl(b,r)}}catch(i){if(i instanceof Ie){Ss(e,new ge(413,i.message));return}if(i instanceof ge){Ss(e,i);return}throw i}}var Jr=require("@urun-sh/core");O();var Rs="x-urun-profile",Wn="voice";var Ne=class extends Error{status=400},Yf=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Xf=/\s/;function Qf(t){return Yf.test(t)}function ks(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Ne(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Yl(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 Ne(`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 Ne(`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 Ne(`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 Xl(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 Ne(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let u=n.trim();if(u==="")throw new Ne(`the ${Rs} header is empty \u2014 the only profile this lane accepts is "${Wn}" (omit the header for the ordinary lane)`);if(u!==Wn)throw new Ne(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${Wn}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Wn)throw new Ne(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Wn}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new Ne("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 Ne("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let l=a??{};return{flushMaxChars:Yl(l,"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:Yl(l,"flush_max_ms",250,{max:2147483647}),sentenceFlush:ks(l,"sentence_flush",!0),includeReasoning:ks(l,"include_reasoning",!1),metadata:ks(l,"metadata",!1)}}var dn=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&&Qf(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(Xf.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 As(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function em(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 Oe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function de(t,e,n,r="invalid_request_error",o){Oe(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Is(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=rt(r),a=i??Ye(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 l=r?.code??null,u=o==="invalid_request_error"?400:l==="queue_timeout"?429:502;u===429&&t.setHeader("retry-after","30"),Oe(t,u,{error:{message:a,type:o,code:l}})}function Qe(t,e,n,r){Oe(t,e,{type:"error",error:{type:n,message:r}})}function cn(t,e,n){if(e==="anthropic"){Oe(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}Oe(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var tm=64*1024*1024,Jn=class extends Error{};async function Ql(t,e=tm){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Jn(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ft(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 eu(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:null,o=r(n.input_tokens),s=r(n.output_tokens),i=l=>l??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let l={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:l}:{kind:"counts",usage:l}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function qr(t){let e=eu(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Zl(t){let e=qr(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:nm(t)},completion_tokens_details:{reasoning_tokens:0}}}function nm(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 rm(t,e){let n=eu(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function om(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=l=>{let u=n[l];return typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function sm(t,e){let n=om(e);n&&(t.timing=n),t.outputSeconds=dt(e)}function Bt(t,e){rm(t,e),sm(t,e)}async function Vr(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 tu(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 im(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 Gr=class extends Error{};function am(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 Gr(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function lm(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:am(n.role,n.content)})}return e}function Es(t){return Zt(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 um(t,e,n,r,o,s,i){let a=Ln(s.id),l=t.stream===!0;if(s.model=Ce(t),s.stream=l,await Vr(s,e,typeof t.model=="string"?t.model:void 0),l){let b;try{b=await $n({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(v){if(v instanceof ie){cn(r,"openai",v);return}if(v instanceof je){de(r,v.status,v.message);return}if(v instanceof Ve||v instanceof Ae){r.setHeader("retry-after","2"),de(r,503,v.message,"capacity_error");return}throw v}As(r);for await(let v of b.events){if(v.type==="error"){s.streamError=!0;let p=v.error,g=rt(p),y=g??Ye(s.id);g===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(v)}`),r.write(`event: error
36
+ `)}function vl(t,e){if(!Re(e))throw new Pe("decision answer was not a JSON object");let n=e.answers;if(!Re(n))throw new Pe("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!Re(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=Re(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let a=Ss(s.noul);if(a===null)throw new Pe(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:a});continue}case"choice":{let a=o.choiceValues??[],l=s.choice;if(typeof l!="string")throw new Pe(`the choice answer for "${o.key}" carries no string choice`);let u=a.findIndex(f=>String(f)===l);if(u===-1)throw new Pe(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(l)})`);let d=qn(s.confidence);if(d===null)throw new Pe(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let f of a){let h=Ss(i[String(f)]);h!==null&&c.push({value:f,probability:h})}r.push({type:"choice",name:o.name,choice:a[u],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],l=qn(s.score);if(l===null)throw new Pe(`the score answer for "${o.key}" carries no numeric score to translate`);let u=qn(s.confidence);if(u===null)throw new Pe(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<a.length;c++){let f=Ss(i[String(c)]);f!==null&&d.push({value:c,label:a[c],probability:f})}r.push({type:"score",name:o.name,score:l,confidence:u,probabilities:d});continue}}}return r}function ln(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function Of(t){let e=Re(t.input_tokens_details)?t.input_tokens_details.cached_tokens:void 0,n=e!==void 0?e:t.cached_tokens;return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?n:0}function bl(t){if(t==null)return null;if(!Re(t))throw new Pe("decision reply carried a usage receipt that is not a JSON object");let e=ln(t.prompt_tokens)??ln(t.input_tokens),n=ln(t.completion_tokens)??ln(t.output_tokens);if(e===null||n===null)throw new Pe("decision reply carried a usage receipt with no usable token counts");let r=qn(t.ttft_ms),o=ln(t.total_tokens)??ln(e+n);if(o===null)throw new Pe("decision reply carried a usage receipt with an unusable token total");return{input_tokens:e,input_tokens_details:{cache_write_tokens:0,cached_tokens:Of(t)},output_tokens:n,output_tokens_details:{reasoning_tokens:0},total_tokens:o,...r!==null?{ttft_ms:r}:{}}}T();T();var Ie=class extends Error{};async function Dr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Ie(`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 Ie(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function Fr(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 Ie(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[u,d]of Object.entries(t.headers))if(typeof d=="string")i.set(u,d);else if(Array.isArray(d))for(let c of d)i.append(u,c);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof Ie?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Sl="/v1/images/generations",Br="/v1/images/edits";function kl(t){return t===Sl||t===Br}var Rl="/v1/images/models";async function El(t,e,n){if(t){if(t.model=Ce({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 se=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Pf=16*1024*1024,xl=64*1024*1024;function Al(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 Gn(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 Il(t,e,n,r,o,s){let i=s??(m=>console.error(m)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),l=null;for await(let m of a){if(m.type==="error"){let w=m.error??{},E=typeof w.message=="string"&&w.message.length>0&&ze(w.message)?w.message:null;throw E===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(m)}`),new se(502,"the image upstream failed while serving this request")):new se(502,`image upstream error: ${E}`)}if(m.type==="response.completed"){l=m.response??null;break}}if(l===null)throw new se(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=dt(l));let u=l.images;if(!Array.isArray(u)||u.length!==1||typeof u[0]!="string"||u[0].length===0)throw new se(502,`image upstream returned ${Array.isArray(u)?u.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=u[0].startsWith("data:")?u[0].slice(u[0].indexOf(";base64,")+8):u[0],f=Buffer.from(c,"base64");if(Al(f)===null)throw new se(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${f.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function Tl(t,e){if(t instanceof se)return t;if(t instanceof qe)throw t;return t instanceof ie?new se(404,t.message):new se(502,on("image",t,e))}async function Ol(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 Gn(r,new se(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 Pl(t,e){t&&(t.outputUnits=e.images.length)}function Cl(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 Cf={model:!0,prompt:!0,response_format:!0,n:!0};async function Ll(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??xl;try{if(t.method!=="POST")throw new se(405,`${String(t.method)} is not supported on ${Sl}`);let s;try{s=JSON.parse((await Dr(t,o)).toString("utf8")||"{}")}catch(f){throw f instanceof Ie?new se(413,f.message):new se(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new se(400,"request body must be a JSON object");let i=s;for(let f of Object.keys(i))if(!Cf[f])throw new se(400,`request field "${f}" 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.`,f);let a=i.prompt;if(typeof a!="string"||a.trim().length===0)throw new se(400,"prompt is required and must be a non-empty string","prompt");let l=i.model===void 0?void 0:i.model;if(l!==void 0&&typeof l!="string")throw new se(400,"model must be a string","model");await El(n.turn,n.clients,l);let u=i.n??1;if(u!==1)throw new se(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new se(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 Ol(n.imageModels,l,"generation",e))return;let c=[{type:"input_text",text:a}];try{let f=await Il(n.clients,l,c,n.turn?He(n.turn):void 0,n.turn,r);Pl(n.turn,f),Cl(e,f)}catch(f){throw Tl(f,r)}}catch(s){if(s instanceof Ie){Gn(e,new se(413,s.message));return}if(s instanceof se){Gn(e,s);return}throw s}}var Lf={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ml(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??xl,s=n.maxImagePartBytes??Pf;try{if(t.method!=="POST")throw new se(405,`${String(t.method)} is not supported on ${Br}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new se(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await Fr(t,o)}catch(m){throw m instanceof Ie?new se(413,m.message):new se(400,String(m instanceof Error?m.message:m))}let l=a.get("prompt");if(typeof l!="string"||l.trim().length===0)throw new se(400,"prompt is required and must be a non-empty string field","prompt");let u=a.get("model");if(u!==null&&typeof u!="string")throw new se(400,"model must be a string field","model");let d=u===null?void 0:u;await El(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new se(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 m of a.keys())if(!Lf[m])throw new se(400,`form field "${m}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,m);let f=[];for(let m of["image","image[]"])for(let w of a.getAll(m)){if(!(w instanceof File))throw new se(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(w.size>s)throw new se(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let E=new Uint8Array(await w.arrayBuffer()),x=Al(E);if(x===null)throw new se(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);f.push({bytes:E,mime:x})}if(f.length===0)throw new se(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",l.length,l.length),!await Ol(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:l}];for(let{bytes:m,mime:w}of f)h.push({type:"input_image",image_url:`data:${w};base64,${Buffer.from(m).toString("base64")}`});try{let m=await Il(n.clients,d,h,n.turn?He(n.turn):void 0,n.turn,r);Pl(n.turn,m),Cl(e,m)}catch(m){throw Tl(m,r)}}catch(i){if(i instanceof Ie){Gn(e,new se(413,i.message));return}if(i instanceof se){Gn(e,i);return}throw i}}T();var Wn="/v1/audio/speech";function ql(t){return t===Wn}var $l=4096,Nl=18e4,Ul=5e3,Mf=64*1024*1024,Dl=8,Fl=5,Bl=1024*1024,dn="voice_applied",jr="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 ks(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 qr=class extends Z{constructor(e){super(502,e)}};function Gl(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 Wl(t){return new Z(502,`the runtime's ${dn} receipt ${JSON.stringify(t)} cannot be relayed as the ${jr} 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 $f(t,e,n){if(t){if(t.model=Ce({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 Jl(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}function Nf(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 Hl=new WeakMap,Hr=new WeakMap;function Uf(t,e){let n=Hr.get(t)??0;if(n>=Dl)throw new Z(503,`this model's speech queue is full \u2014 ${Dl} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Fl}s`,void 0,Fl);Hr.set(t,n+1);let r=Hl.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Hl.set(t,s),(async()=>{await r;try{return await e()}finally{Hr.set(t,(Hr.get(t)??1)-1),o()}})()}async function Df(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 te))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(()=>{clearTimeout(s)})}function Dt(t,e){if(t instanceof Z)return t;if(t instanceof qe)throw t;return t instanceof ie?new Z(404,t.message):new Z(502,on("speech",t,e))}async function jl(t,e,n,r,o,s,i,a,l,u){let d=u??(f=>console.error(f)),c=a??(()=>{});return Uf(e,async()=>{if(i?.()===!0)return null;let f=!1,h=!1,m=!1,w,E=new Promise(O=>{w=O}),x=[],v,_=!1,p=null,g=()=>{p!==null&&(clearTimeout(v),v=setTimeout(()=>{_=!0,p?.()},o.capMs))},y=()=>{h&&!m&&x.length>=o.quietRunFrames&&(m=!0,w())},S=e.onOutputAudio(O=>{let b=Buffer.from(O,"base64");if(b.byteLength===0)return;g();let C=_r(b);if(!f){if(C)return;f=!0}if(C){x.push(b),y();return}for(let $ of x)c($);x.length=0,c(b),y()}),A=null,P,R;try{R=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let b=()=>(clearTimeout(P),new Promise(U=>{P=setTimeout(U,s.capMs)})),C=b(),$=!1;for(;;){let U=R.next(),q=await Promise.race([U,C]);if(q===void 0){$=!0,U.catch(()=>{});break}if(q.done)break;let X=q.value;if(C=b(),X.type==="error"){let G=X.error??{};await R.return?.();let re=typeof G.message=="string"&&G.message.length>0&&ze(G.message)?G.message:null;throw re===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(X)}`),new Z(502,"the speech upstream failed while serving this request")):new Z(502,`speech upstream error: ${re}`)}if(X.type==="response.completed"){A=X.response??null,h=!0,l?.(A),y(),await R.return?.();break}}if(clearTimeout(P),$)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(A===null)throw new Z(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let M=new Promise(U=>{p=U});if(g(),await Promise.race([E,M]),clearTimeout(v),v=void 0,p=null,r.voice!==void 0){let U=A[dn];if(typeof U!="string"||U!==r.voice){let q=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof U=="string"?`${dn} ${JSON.stringify(U)}`:`no ${dn} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw m?new qr(q):new Z(502,q)}}if(!f)throw new Z(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(_&&!m&&x.length<1)throw new Z(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return A}catch(O){throw O instanceof qr||await Df(t,n,R,s.returnBoundMs),O}finally{clearTimeout(v),clearTimeout(P),S()}})}function Ff(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",jr)),t.write(a,l=>{l||(s+=a.byteLength,Jl(e,s))}),t.writableLength>Bl&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Bl} 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 l=a[dn];if(typeof l=="string"){if(!Gl(l))throw Wl(l);t.addTrailers({[jr]:l})}}await new Promise(l=>{t.end(()=>l())})}},fail:i}}async function Bf(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Dt(s,r)}return o?!0:(ks(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 Hf={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},jf="wav, pcm";async function Vl(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??Mf,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 ${Wn}`);let a;try{a=JSON.parse((await Dr(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof Ie?new Z(413,p.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 l=a;for(let p of Object.keys(l))if(!Hf[p])throw new Z(400,`request field "${p}" 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.`,p);let u=l.input;if(typeof u!="string"||u.trim().length===0)throw new Z(400,"input is required and must be a non-empty string","input");if(u.length>$l)throw new Z(400,`input is ${u.length} chars \u2014 over the ${$l}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=l.model===void 0?void 0:l.model;if(d!==void 0&&typeof d!="string")throw new Z(400,"model must be a string","model");let c=l.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 ${Wn} against a stale copy of the list`);let f;try{f=await n.clients.speechVoices(d)}catch(p){throw Dt(p,r)}if(f.defect!==null)throw new Z(500,`the voice set for this model cannot be resolved: ${f.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let h=typeof c=="string"?c:void 0;if(h!==void 0&&f.published.length>0&&!f.published.includes(h))throw new Z(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${f.published.join(", ")}`,"voice");let m=l.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new Z(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${jf} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(l.stream_format!==void 0&&typeof l.stream_format!="string")throw new Z(400,"stream_format, when present, must be a string","stream_format");let w=l.speed;if(w!==void 0){if(typeof w!="number"||!Number.isFinite(w))throw new Z(400,"speed, when present, must be a number","speed");if(w!==1)throw new Z(400,`speed=${JSON.stringify(w)} 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 E=l.instructions;if(E!==void 0){if(typeof E!="string")throw new Z(400,"instructions, when present, must be a string","instructions");if(E.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 $f(n.turn,n.clients,d);let x=Buffer.byteLength(JSON.stringify(l));if(n.stats?.request("audio_speech",x,x),!await Bf(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 v;try{v=await n.clients.speechSessionHandle(d)}catch(p){throw Dt(p,r)}let _;try{_=await n.clients.openAudioOn(v)}catch(p){throw Dt(p,r)}n.turn&&(n.turn.sessionId=_.sessionId);try{if(m==="wav"){let p=[],g=await jl(n.clients,_,v,{model:d,text:u,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Nl,returnBoundMs:n.turnReturnBoundMs??Ul},i,S=>p.push(S),S=>{n.turn&&(n.turn.outputSeconds=dt(S))},r);if(g===null||i())return;let y=Buffer.concat(p);if(h===void 0){let S=g[dn];if(typeof S=="string"){if(!Gl(S))throw Wl(S);e.setHeader(jr,S)}}Jl(n.turn,y.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Nf(y.byteLength),y]))}else{let p=Ff(e,n.turn,i,h===void 0),g;try{g=await jl(n.clients,_,v,{model:d,text:u,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Nl,returnBoundMs:n.turnReturnBoundMs??Ul},i,p.sink,y=>{n.turn&&(n.turn.outputSeconds=dt(y))},r)}catch(y){let S=Dt(y,r);if(!p.started())throw S;n.turn&&(n.turn.streamError=!0),p.fail(S);return}if(g===null)return;try{await p.finish(g)}catch(y){let S=Dt(y,r);n.turn&&(n.turn.streamError=!0),p.fail(S);return}}}catch(p){throw Dt(p,r)}}catch(a){if(a instanceof Ie){ks(e,new Z(413,a.message));return}if(a instanceof Z){ks(e,a);return}throw a}}T();var Gr="/v1/audio/transcriptions";function Kl(t){return t===Gr}var zl="/v1/audio/models",qf=16*1024*1024,Gf=64*1024*1024,ge=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Rs(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 Yl(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 Wf(t){if(!Yl(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 l=t[a+2]|t[a+3]<<8,u=(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:u,channels:l,bitsPerSample:d}}else if(s==="data"){let l=t.length-a;r=Math.min(i===0||i===4294967295?l:i,l)}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 Jf(t,e,n){if(t){if(t.model=Ce({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 Vf(t,e){t&&(t.outputUnits=e.seconds)}async function Kf(t,e,n,r,o,s,i){let a=i??(c=>console.error(c)),l=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),u=[],d=null;for await(let c of l){if(u.push(c),c.type==="error"){let f=c.error??{},h=typeof f.type=="string"?f.type:"upstream_error",m=typeof f.message=="string"&&f.message.length>0&&ze(f.message)?f.message:null;throw m===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new ge(h==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new ge(h==="invalid_request_error"?400:502,`transcription upstream error: ${m}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new ge(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=dt(d)),nn(u,d)}function Xl(t,e){if(t instanceof ge)return t;if(t instanceof qe)throw t;return t instanceof ie?new ge(404,t.message):new ge(502,on("transcription",t,e))}async function zf(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Xl(s,r)}return o?!0:(Rs(n,new ge(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 Yf=new Set(["file","model","language","response_format"]);async function Ql(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Gf,s=n.maxAudioPartBytes??qf;try{if(t.method!=="POST")throw new ge(405,`${String(t.method)} is not supported on ${Gr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new ge(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await Fr(t,o)}catch(v){throw v instanceof Ie?new ge(413,v.message):new ge(400,String(v instanceof Error?v.message:v))}let l=new Map;for(let v of a.keys()){if(!Yf.has(v))throw new ge(400,`form field "${v}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,v);l.set(v,(l.get(v)??0)+1)}for(let[v,_]of l)if(_>1)throw new ge(400,`form field "${v}" appears ${_} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,v);let u=a.get("model");if(u!==null&&typeof u!="string")throw new ge(400,"model must be a string field","model");let d=u===null?void 0:u,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new ge(400,"language, when present, must be a non-empty string","language");let f=c===null?void 0:c,h=a.get("response_format")??"json";if(h!=="json")throw new ge(400,`response_format ${JSON.stringify(h)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let m=a.get("file");if(!(m instanceof File))throw new ge(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>s)throw new ge(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let w=new Uint8Array(await m.arrayBuffer());if(!Yl(w))throw new ge(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 E=Wf(w);if(E===null)throw new ge(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 Jf(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",w.length,w.length),!await zf(n.transcriptionModels,d,e,r))return;let x=[{type:"input_audio",input_audio:{data:Buffer.from(w).toString("base64"),format:"wav"}}];try{let v=await Kf(n.clients,d,x,f,n.turn?He(n.turn):void 0,n.turn,r);Vf(n.turn,E),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:v}))}catch(v){throw Xl(v,r)}}catch(i){if(i instanceof Ie){Rs(e,new ge(413,i.message));return}if(i instanceof ge){Rs(e,i);return}throw i}}var Kr=require("@urun-sh/core");T();var xs="x-urun-profile",Jn="voice";var Ne=class extends Error{status=400},Xf=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Qf=/\s/;function Zf(t){return Xf.test(t)}function Es(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new Ne(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Zl(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 Ne(`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 Ne(`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 Ne(`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 eu(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 Ne(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let u=n.trim();if(u==="")throw new Ne(`the ${xs} header is empty \u2014 the only profile this lane accepts is "${Jn}" (omit the header for the ordinary lane)`);if(u!==Jn)throw new Ne(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${Jn}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Jn)throw new Ne(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Jn}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new Ne("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 Ne("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let l=a??{};return{flushMaxChars:Zl(l,"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:Zl(l,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Es(l,"sentence_flush",!0),includeReasoning:Es(l,"include_reasoning",!1),metadata:Es(l,"metadata",!1)}}var cn=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&&Zf(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(Qf.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 Ts(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function tm(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 Te(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function de(t,e,n,r="invalid_request_error",o){Te(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=rt(r),a=i??Ye(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 l=r?.code??null,u=o==="invalid_request_error"?400:l==="queue_timeout"?429:502;u===429&&t.setHeader("retry-after","30"),Te(t,u,{error:{message:a,type:o,code:l}})}function Qe(t,e,n,r){Te(t,e,{type:"error",error:{type:n,message:r}})}function pn(t,e,n){if(e==="anthropic"){Te(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}Te(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var nm=64*1024*1024,Vn=class extends Error{};async function tu(t,e=nm){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Vn(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ft(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 ru(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:null,o=r(n.input_tokens),s=r(n.output_tokens),i=l=>l??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let l={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:l}:{kind:"counts",usage:l}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function Wr(t){let e=ru(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function nu(t){let e=Wr(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:rm(t)},completion_tokens_details:{reasoning_tokens:0}}}function rm(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 om(t,e){let n=ru(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function sm(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=l=>{let u=n[l];return typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function im(t,e){let n=sm(e);n&&(t.timing=n),t.outputSeconds=dt(e)}function Bt(t,e){om(t,e),im(t,e)}async function zr(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 ou(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 am(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 Jr=class extends Error{};function lm(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 Jr(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function um(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:lm(n.role,n.content)})}return e}function As(t){return en(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 dm(t,e,n,r,o,s,i){let a=Mn(s.id),l=t.stream===!0;if(s.model=Ce(t),s.stream=l,await zr(s,e,typeof t.model=="string"?t.model:void 0),l){let v;try{v=await Nn({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(_){if(_ instanceof ie){pn(r,"openai",_);return}if(_ instanceof je){de(r,_.status,_.message);return}if(_ instanceof Ve||_ instanceof Ae){r.setHeader("retry-after","2"),de(r,503,_.message,"capacity_error");return}throw _}Ts(r);for await(let _ of v.events){if(_.type==="error"){s.streamError=!0;let p=_.error,g=rt(p),y=g??Ye(s.id);g===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(_)}`),r.write(`event: error
37
37
  data: ${JSON.stringify({error:{message:y,type:p?.type??"upstream_error",code:p?.code??null}})}
38
38
 
39
- `),r.end();return}v.type==="response.completed"&&Bt(s,v.response),r.write(`event: ${String(v.type??"message")}
40
- data: ${JSON.stringify(v)}
39
+ `),r.end();return}_.type==="response.completed"&&Bt(s,_.response),r.write(`event: ${String(_.type??"message")}
40
+ data: ${JSON.stringify(_)}
41
41
 
42
42
  `)}r.write(`data: [DONE]
43
43
 
44
- `),r.end();return}let u;try{u=nn(n,t)}catch(b){if(b instanceof je){de(r,b.status,b.message);return}throw b}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=Ce(t);o.model(c);let f=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await Zo(e,t,u,!1,He(s))}catch(b){if(b instanceof ie){cn(r,"openai",b);return}if(b instanceof je){de(r,b.status,b.message);return}if(b instanceof Ve||b instanceof Ae){r.setHeader("retry-after","2"),de(r,503,b.message,"capacity_error");return}throw b}let m=[],w=null;for await(let b of o.track(h,c,s)){if(m.push(b),b.type==="error"){Is(r,b,{inferenceId:s.id,operatorError:i});return}b.type==="response.completed"&&(w=b.response)}if(w==null){de(r,502,"upstream produced no response.completed event","upstream_error");return}Bt(s,w);let E=tn(m,w),x=$t(f,Zt(w).length,E);if(x){de(r,502,Mt(c,x),"upstream_error");return}d&&n.remember(a,u,Qo(w,E),d),Oe(r,200,{...w,id:a})}async function dm(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){de(n,400,"chat/completions requires a messages array");return}let l;try{l=Xl(s,t)}catch(R){if(R instanceof Ne){de(n,R.status,R.message);return}throw R}let u=String(t.model??"urun"),d=Ga(o.id),c;try{c=lm(a)}catch(R){if(R instanceof Gr){de(n,400,R.message);return}throw R}let f=Ce(t);r.model(f),o.model=f,o.stream=t.stream===!0,await Vr(o,e,typeof t.model=="string"?t.model:void 0);let h=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:c,stream:!0,tools:im(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}:{}},He(o))}catch(R){if(R instanceof ie){cn(n,"openai",R);return}if(R instanceof Ve||R instanceof Ae){n.setHeader("retry-after","2"),de(n,503,R.message,"capacity_error");return}throw R}if(t.stream===!0){l?em(n):As(n);let R=[],T=new _t,_="",C=l?new dn(l,N=>{n.write(`data: ${JSON.stringify(Ft(d,u,{content:N},null))}
44
+ `),r.end();return}let u;try{u=rn(n,t)}catch(v){if(v instanceof je){de(r,v.status,v.message);return}throw v}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=Ce(t);o.model(c);let f=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await ts(e,t,u,!1,He(s))}catch(v){if(v instanceof ie){pn(r,"openai",v);return}if(v instanceof je){de(r,v.status,v.message);return}if(v instanceof Ve||v instanceof Ae){r.setHeader("retry-after","2"),de(r,503,v.message,"capacity_error");return}throw v}let m=[],w=null;for await(let v of o.track(h,c,s)){if(m.push(v),v.type==="error"){Os(r,v,{inferenceId:s.id,operatorError:i});return}v.type==="response.completed"&&(w=v.response)}if(w==null){de(r,502,"upstream produced no response.completed event","upstream_error");return}Bt(s,w);let E=nn(m,w),x=$t(f,en(w).length,E);if(x){de(r,502,Mt(c,x),"upstream_error");return}d&&n.remember(a,u,es(w,E),d),Te(r,200,{...w,id:a})}async function cm(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){de(n,400,"chat/completions requires a messages array");return}let l;try{l=eu(s,t)}catch(R){if(R instanceof Ne){de(n,R.status,R.message);return}throw R}let u=String(t.model??"urun"),d=Va(o.id),c;try{c=um(a)}catch(R){if(R instanceof Jr){de(n,400,R.message);return}throw R}let f=Ce(t);r.model(f),o.model=f,o.stream=t.stream===!0,await zr(o,e,typeof t.model=="string"?t.model:void 0);let h=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:c,stream:!0,tools:am(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}:{}},He(o))}catch(R){if(R instanceof ie){pn(n,"openai",R);return}if(R instanceof Ve||R instanceof Ae){n.setHeader("retry-after","2"),de(n,503,R.message,"capacity_error");return}throw R}if(t.stream===!0){l?tm(n):Ts(n);let R=[],O=new _t,b="",C=l?new cn(l,M=>{n.write(`data: ${JSON.stringify(Ft(d,u,{content:M},null))}
45
45
 
46
- `)}):null,$=N=>{C?.flush(),n.write(N),n.end()};try{l?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
46
+ `)}):null,$=M=>{C?.flush(),n.write(M),n.end()};try{l?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
47
47
 
48
48
  `),n.write(`data: ${JSON.stringify(Ft(d,u,{role:"assistant"},null))}
49
49
 
50
- `);for await(let G of r.track(m,f,o)){R.push(G);let re=en(G);if(G.type==="response.output_text.delta"&&typeof G.delta=="string")_+=G.delta,C?C.push(G.delta):n.write(`data: ${JSON.stringify(Ft(d,u,{content:G.delta},null))}
50
+ `);for await(let G of r.track(m,f,o)){R.push(G);let re=tn(G);if(G.type==="response.output_text.delta"&&typeof G.delta=="string")b+=G.delta,C?C.push(G.delta):n.write(`data: ${JSON.stringify(Ft(d,u,{content:G.delta},null))}
51
51
 
52
52
  `);else if(G.type==="response.reasoning_text.delta"&&typeof G.delta=="string")(!l||l.includeReasoning)&&n.write(`data: ${JSON.stringify(Ft(d,u,{reasoning_content:G.delta},null))}
53
53
 
54
- `);else if(re){C?.flush();let{call:K,isNew:M}=T.add(re),ee=M?{index:re.tool_index,id:K.id??`call_${re.tool_index}`,type:"function",function:{name:K.name??"",arguments:re.delta}}:{index:re.tool_index,function:{arguments:re.delta}};n.write(`data: ${JSON.stringify(Ft(d,u,{tool_calls:[ee]},null))}
54
+ `);else if(re){C?.flush();let{call:K,isNew:N}=O.add(re),ee=N?{index:re.tool_index,id:K.id??`call_${re.tool_index}`,type:"function",function:{name:K.name??"",arguments:re.delta}}:{index:re.tool_index,function:{arguments:re.delta}};n.write(`data: ${JSON.stringify(Ft(d,u,{tool_calls:[ee]},null))}
55
55
 
56
- `)}else if(G.type==="error"){o.streamError=!0;let K=G.error??{},M=rt(K),ee=M??Ye(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(G)}`),$(`data: ${JSON.stringify({error:{message:ee,type:K.type??"upstream_error",code:K.code??null}})}
56
+ `)}else if(G.type==="error"){o.streamError=!0;let K=G.error??{},N=rt(K),ee=N??Ye(o.id);N===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(G)}`),$(`data: ${JSON.stringify({error:{message:ee,type:K.type??"upstream_error",code:K.code??null}})}
57
57
 
58
- `);return}}let N=Es(nt(R)),D=$t(h,T.size+N.length,_);if(D){o.streamError=!0,$(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Mt(f,D)}})}
58
+ `);return}}let M=As(nt(R)),U=$t(h,O.size+M.length,b);if(U){o.streamError=!0,$(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Mt(f,U)}})}
59
59
 
60
- `);return}C?.flush(),T.size===0&&N.length>0&&n.write(`data: ${JSON.stringify(Ft(d,u,{tool_calls:N},null))}
60
+ `);return}C?.flush(),O.size===0&&M.length>0&&n.write(`data: ${JSON.stringify(Ft(d,u,{tool_calls:M},null))}
61
61
 
62
- `);let q=T.size>0||N.length>0;n.write(`data: ${JSON.stringify(Ft(d,u,{},q?"tool_calls":"stop"))}
62
+ `);let q=O.size>0||M.length>0;n.write(`data: ${JSON.stringify(Ft(d,u,{},q?"tool_calls":"stop"))}
63
63
 
64
- `);let X=qr(nt(R));Bt(o,nt(R)),X&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:Zl(nt(R))})}
64
+ `);let X=Wr(nt(R));Bt(o,nt(R)),X&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:nu(nt(R))})}
65
65
 
66
66
  `),n.write(`data: [DONE]
67
67
 
68
- `),n.end();return}finally{C?.flush(),C?.dispose()}}let w="",E="",x=[],b=new _t;for await(let R of r.track(m,f,o)){x.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(w+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(E+=R.delta);let T=en(R);if(T&&b.add(T),R.type==="error"){Is(n,R,{inferenceId:o.id,operatorError:i});return}}let v=nt(x);Bt(o,v);let p=Es(v),g=p.length>0?p:Es({output:b.items()}),y=$t(h,g.length,w);if(y){de(n,502,Mt(f,y),"upstream_error");return}let S=g.map(({index:R,...T})=>T),A={role:"assistant",content:w||null},P=E||tu(v);P&&(A.reasoning_content=P),S.length>0&&(A.tool_calls=S),Oe(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:A,finish_reason:S.length>0?"tool_calls":"stop"}],usage:Zl(v)})}var Kr="sense-latest";async function cm(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){de(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:Kr,a=Ce({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){de(n,400,"systemone requires a state (string or JSON structure)");return}let l=t.questions;if(l===null||typeof l!="object"||Array.isArray(l)||Object.keys(l).length===0){de(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){de(n,400,"systemone media, when present, must be an array");return}let u=await nu(t,i,a,e,n,r,o,s);u!==null&&Oe(n,200,u.answer)}async function nu(t,e,n,r,o,s,i,a){let l={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=l;let u=performance.now();s.model(n),await Vr(i,r,e),l.resolve_ms=Math.round(performance.now()-u);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},He(i))}catch(x){if(x instanceof ie)return cn(o,"openai",x),null;if(x instanceof Ve||x instanceof Ae)return o.setHeader("retry-after","2"),de(o,503,x.message,"capacity_error"),null;throw x}l.dial_ms=Math.round(performance.now()-c);let f=[],h=null;try{for await(let x of s.track(d,n,i))if(h===null&&(h=performance.now(),l.first_event_ms=Math.round(h-c)),f.push(x),x.type==="error")return Is(o,x,{inferenceId:i.id,operatorError:a}),null}catch(x){if(x instanceof ie)return h!==null&&(l.stream_ms=Math.round(performance.now()-h)),cn(o,"openai",x),null;if(x instanceof Ve||x instanceof Ae)return h!==null&&(l.stream_ms=Math.round(performance.now()-h)),o.setHeader("retry-after","2"),de(o,503,x.message,"capacity_error"),null;throw h!==null&&(l.stream_ms=Math.round(performance.now()-h)),x}h!==null&&(l.stream_ms=Math.round(performance.now()-h));let m=nt(f);if(m==null)return de(o,502,"upstream produced no response.completed event","upstream_error"),null;Bt(i,m);let w=tn(f,m),E;try{E=JSON.parse(w)}catch{return de(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(E===null||typeof E!="object"||Array.isArray(E))return de(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof E=="object"&&E!==null&&!Array.isArray(E)&&"timing"in E){let x=E.timing;if(typeof x=="object"&&x!==null&&!Array.isArray(x)&&"question_fwd_ms"in x&&"head_ms"in x){let b=v=>typeof v=="number"&&Number.isFinite(v)&&v>=0?Math.round(v):null;l.question_fwd_ms=b(x.question_fwd_ms),l.head_ms=b(x.head_ms)}}return{answer:E,completed:m}}async function pm(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){de(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:Kr,a=Ce({model:i});o.model=a,o.stream=!1;let l;try{l=ml(t,i)}catch(f){if(f instanceof Q){de(n,400,f.message);return}throw f}let u=await nu(l.systemone,i,a,e,n,r,o,s);if(u===null)return;let d;try{d=yl(l.specs,u.answer)}catch(f){if(f instanceof Pe){de(n,502,f.message,"upstream_error");return}throw f}let c;try{c=wl(u.completed.usage)}catch(f){if(f instanceof Pe){de(n,502,f.message,"upstream_error");return}throw f}Oe(n,200,{model:i,answers:d,...c===null?{}:{usage:c}})}function fm(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Vn=class extends Error{};function Wr(t){return new Vn(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function mm(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 hm(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 Vn(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function gm(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Wr(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Wr(`tool_result > ${r}`);e+=String(n.text??"")}return e}function ym(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 Wr(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:gm(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Wr(a)}}return s(),r}function xs(t){return Zt(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 wm(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Qe(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){Qe(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Qe(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(A=>typeof A!="string"))){Qe(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),l=Wa(o.id),u=[],d;try{t.system&&u.push({role:"system",content:fm(t.system)});for(let A of i)u.push(...ym(A));d=hm(t.tool_choice)}catch(A){if(A instanceof Vn){Qe(n,400,"invalid_request_error",A.message);return}throw A}let c=Ce(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Vr(o,e,typeof t.model=="string"?t.model:void 0);let f=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:u,stream:!0,tools:mm(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},He(o))}catch(A){if(A instanceof ie){cn(n,"anthropic",A);return}if(A instanceof Ve||A instanceof Ae){n.setHeader("retry-after","2"),Qe(n,503,"capacity_error",A.message);return}throw A}let m=(A,P)=>{n.destroyed||n.write(`event: ${A}
68
+ `),n.end();return}finally{C?.flush(),C?.dispose()}}let w="",E="",x=[],v=new _t;for await(let R of r.track(m,f,o)){x.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(w+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(E+=R.delta);let O=tn(R);if(O&&v.add(O),R.type==="error"){Os(n,R,{inferenceId:o.id,operatorError:i});return}}let _=nt(x);Bt(o,_);let p=As(_),g=p.length>0?p:As({output:v.items()}),y=$t(h,g.length,w);if(y){de(n,502,Mt(f,y),"upstream_error");return}let S=g.map(({index:R,...O})=>O),A={role:"assistant",content:w||null},P=E||ou(_);P&&(A.reasoning_content=P),S.length>0&&(A.tool_calls=S),Te(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:A,finish_reason:S.length>0?"tool_calls":"stop"}],usage:nu(_)})}var Yr="sense-latest";async function pm(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){de(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:Yr,a=Ce({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){de(n,400,"systemone requires a state (string or JSON structure)");return}let l=t.questions;if(l===null||typeof l!="object"||Array.isArray(l)||Object.keys(l).length===0){de(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){de(n,400,"systemone media, when present, must be an array");return}let u=await su(t,i,a,e,n,r,o,s);u!==null&&Te(n,200,u.answer)}async function su(t,e,n,r,o,s,i,a){let l={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=l;let u=performance.now();s.model(n),await zr(i,r,e),l.resolve_ms=Math.round(performance.now()-u);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},He(i))}catch(x){if(x instanceof ie)return pn(o,"openai",x),null;if(x instanceof Ve||x instanceof Ae)return o.setHeader("retry-after","2"),de(o,503,x.message,"capacity_error"),null;throw x}l.dial_ms=Math.round(performance.now()-c);let f=[],h=null;try{for await(let x of s.track(d,n,i))if(h===null&&(h=performance.now(),l.first_event_ms=Math.round(h-c)),f.push(x),x.type==="error")return Os(o,x,{inferenceId:i.id,operatorError:a}),null}catch(x){if(x instanceof ie)return h!==null&&(l.stream_ms=Math.round(performance.now()-h)),pn(o,"openai",x),null;if(x instanceof Ve||x instanceof Ae)return h!==null&&(l.stream_ms=Math.round(performance.now()-h)),o.setHeader("retry-after","2"),de(o,503,x.message,"capacity_error"),null;throw h!==null&&(l.stream_ms=Math.round(performance.now()-h)),x}h!==null&&(l.stream_ms=Math.round(performance.now()-h));let m=nt(f);if(m==null)return de(o,502,"upstream produced no response.completed event","upstream_error"),null;Bt(i,m);let w=nn(f,m),E;try{E=JSON.parse(w)}catch{return de(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(E===null||typeof E!="object"||Array.isArray(E))return de(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof E=="object"&&E!==null&&!Array.isArray(E)&&"timing"in E){let x=E.timing;if(typeof x=="object"&&x!==null&&!Array.isArray(x)&&"question_fwd_ms"in x&&"head_ms"in x){let v=_=>typeof _=="number"&&Number.isFinite(_)&&_>=0?Math.round(_):null;l.question_fwd_ms=v(x.question_fwd_ms),l.head_ms=v(x.head_ms)}}return{answer:E,completed:m}}async function fm(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){de(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:Yr,a=Ce({model:i});o.model=a,o.stream=!1;let l;try{l=yl(t,i)}catch(f){if(f instanceof Q){de(n,400,f.message);return}throw f}let u=await su(l.systemone,i,a,e,n,r,o,s);if(u===null)return;let d;try{d=vl(l.specs,u.answer)}catch(f){if(f instanceof Pe){de(n,502,f.message,"upstream_error");return}throw f}let c;try{c=bl(u.completed.usage)}catch(f){if(f instanceof Pe){de(n,502,f.message,"upstream_error");return}throw f}Te(n,200,{model:i,answers:d,...c===null?{}:{usage:c}})}function mm(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Kn=class extends Error{};function Vr(t){return new Kn(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function hm(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 gm(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 Kn(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function ym(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Vr(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Vr(`tool_result > ${r}`);e+=String(n.text??"")}return e}function wm(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 Vr(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:ym(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Vr(a)}}return s(),r}function Is(t){return en(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 _m(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Qe(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){Qe(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Qe(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(A=>typeof A!="string"))){Qe(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),l=Ka(o.id),u=[],d;try{t.system&&u.push({role:"system",content:mm(t.system)});for(let A of i)u.push(...wm(A));d=gm(t.tool_choice)}catch(A){if(A instanceof Kn){Qe(n,400,"invalid_request_error",A.message);return}throw A}let c=Ce(t);r.model(c),o.model=c,o.stream=t.stream===!0,await zr(o,e,typeof t.model=="string"?t.model:void 0);let f=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:u,stream:!0,tools:hm(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},He(o))}catch(A){if(A instanceof ie){pn(n,"anthropic",A);return}if(A instanceof Ve||A instanceof Ae){n.setHeader("retry-after","2"),Qe(n,503,"capacity_error",A.message);return}throw A}let m=(A,P)=>{n.destroyed||n.write(`event: ${A}
69
69
  data: ${JSON.stringify({type:A,...P})}
70
70
 
71
- `)};if(t.stream===!0){let A=r.track(h,c,o);As(n),m("message_start",{message:{id:l,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let P=0,R="",T=0,_="none",C=()=>_,$=-1,N=-1,D=new _t,q=[],X=()=>{_!=="none"&&(_="none",m("content_block_stop",{index:$}))},G=(ce,me)=>{X(),_=ce,$=T++,m("content_block_start",{index:$,content_block:me})};for await(let ce of A){if(n.destroyed)break;q.push(ce);let me=en(ce);if(ce.type==="response.reasoning_text.delta"&&typeof ce.delta=="string")C()!=="thinking"&&G("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:$,delta:{type:"thinking_delta",thinking:ce.delta}});else if(ce.type==="response.output_text.delta"&&typeof ce.delta=="string")C()!=="text"&&G("text",{type:"text",text:""}),P+=1,R+=ce.delta,m("content_block_delta",{index:$,delta:{type:"text_delta",text:ce.delta}});else if(me){let{call:Me}=D.add(me);(C()!=="tool"||me.tool_index!==N)&&(N=me.tool_index,G("tool",{type:"tool_use",id:Me.id??`call_${me.tool_index}`,name:Me.name??"",input:{}})),me.delta&&m("content_block_delta",{index:$,delta:{type:"input_json_delta",partial_json:me.delta}})}else if(ce.type==="error"){o.streamError=!0;let Me=ce.error,it=rt(Me);it===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(ce)}`),m("error",{error:{type:"api_error",message:it??Ye(o.id)}}),n.end();return}}if(n.destroyed)return;let re=nt(q),K=Zt(re),M=$t(f,D.size+K.length,R);if(M){o.streamError=!0,m("error",{error:{type:"api_error",message:Mt(c,M)}}),n.end();return}X();let ee=[];if(D.size===0)try{ee=xs(re)}catch(ce){o.streamError=!0;let me=De(ce,{inferenceId:o.id});me.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(ce instanceof Error?ce.message:ce)}`),m("error",{error:{type:"api_error",message:me.message}}),n.end();return}T===0&&ee.length===0&&(G("text",{type:"text",text:""}),X()),ee.forEach(ce=>{let me=T++;m("content_block_start",{index:me,content_block:{...ce,input:{}}}),m("content_block_delta",{index:me,delta:{type:"input_json_delta",partial_json:JSON.stringify(ce.input??{})}}),m("content_block_stop",{index:me})});let Fe=D.size>0||ee.length>0,ue=qr(re);Bt(o,re),m("message_delta",{delta:{stop_reason:Fe?"tool_use":"end_turn"},usage:ue?{input_tokens:ue.input_tokens,output_tokens:ue.output_tokens}:{output_tokens:P}}),m("message_stop",{}),n.end();return}let w="",E="",x=[],b=new _t;for await(let A of r.track(h,c,o)){x.push(A),A.type==="response.output_text.delta"&&typeof A.delta=="string"&&(w+=A.delta),A.type==="response.reasoning_text.delta"&&typeof A.delta=="string"&&(E+=A.delta);let P=en(A);if(P&&b.add(P),A.type==="error"){let R=A.error,T=R?.type==="invalid_request_error",_=rt(R);_===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(A)}`),Qe(n,T?400:502,T?"invalid_request_error":"api_error",_??Ye(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let v=nt(x);Bt(o,v);let p;try{p=xs(v),p.length===0&&b.size>0&&(p=xs({output:b.items()}))}catch(A){let P=De(A,{inferenceId:o.id});P.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(A instanceof Error?A.message:A)}`),Qe(n,502,"api_error",P.message);return}let g=$t(f,p.length,w);if(g){Qe(n,502,"api_error",Mt(c,g));return}let y=[],S=E||tu(v);S&&y.push({type:"thinking",thinking:S}),(w||p.length===0)&&y.push({type:"text",text:w}),y.push(...p),Oe(n,200,{id:l,type:"message",role:"assistant",content:y,model:a,stop_reason:p.length>0?"tool_use":"end_turn",usage:qr(v)??{input_tokens:0,output_tokens:0}})}function _m(t){tt(process.stdout,t)}function ru(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??_m,a=t.operatorLog??(d=>console.error(d)),l=t.observe,u=new Ct;return(d,c)=>{let f=new URL(d.url??"/","http://localhost"),h=f.pathname==="/v1/messages"||f.pathname.startsWith("/v1/messages/"),m=(v,p,g,y,S)=>h?Qe(c,v,y,p):de(c,v,p,g,S),w=Xo(f.pathname),E=f.pathname.startsWith("/partners/"),x=w||E?{id:Pt(),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;x&&(c.setHeader(ja,x.id),c.once("close",()=>{let v=Ja({turn:x,method:d.method??"",path:f.pathname,res:c});i(Va(v)),l?.(v),ur({record:v,ledger:t.ledger??null,req:d})}));let b=()=>qa(f.pathname,x);(async()=>{if(d.method==="GET"&&f.pathname==="/healthz"){Oe(c,200,{ok:!0});return}if(d.method==="GET"&&f.pathname==="/stats"){Oe(c,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let v=f.pathname===cr?"canonical":f.pathname===On?"huggingface":null;if(v){if(d.method!=="POST"){m(405,`${f.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let S=t.usage;if(!S){m(501,`${f.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 A=S.authorize(d),P;try{P=await Ql(d,sa)}catch(_){if(_ instanceof Jn){m(413,_.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let R=_=>S.lookup(A,_),T;try{if(v==="canonical"){let _=ia(P),C=await R(_);pr(C,_),T={requests:C}}else T=await ua(P,R)}catch(_){if(_ instanceof wt){m(_.status,_.message,"invalid_request_error","invalid_request_error");return}throw _}Oe(c,200,T);return}if(d.method==="GET"&&f.pathname===Rt){let S=await s(d);if(x&&(x.org=S.tenant??null),!S.openRouterModels){m(501,`GET ${Rt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}Oe(c,200,await S.openRouterModels());return}if(f.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${f.pathname} \u2014 the partner surface currently carries ${On} and GET ${Rt}`,"invalid_request_error","not_found_error");return}let p=await s(d);if(x&&(x.org=p.tenant??null),d.method==="GET"&&f.pathname==="/v1/models"){if(f.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:Rt}),c.end();return}Oe(c,200,await p.listModels());return}if(d.method==="GET"&&f.pathname===bl){if(!p.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}Oe(c,200,await p.listImageModels());return}if(vl(f.pathname)){if(!p.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${f.pathname}`,"not_implemented","not_implemented_error");return}let S={clients:p,imageModels:p.supportsImages,stats:u,turn:b(),operatorLog:a};f.pathname===Dr?await Pl(d,c,S):await Tl(d,c,S);return}if(d.method==="GET"&&f.pathname===Jl){if(!p.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}Oe(c,200,await p.listSpeechToTextModels());return}if(Wl(f.pathname)){if(!p.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${jr}`,"not_implemented","not_implemented_error");return}let S={clients:p,transcriptionModels:p.supportsTranscription,stats:u,turn:b(),operatorLog:a};await zl(d,c,S);return}if(Bl(f.pathname)){if(!p.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Gn}`,"not_implemented","not_implemented_error");return}let S={clients:p,speechModels:p.supportsSpeech,stats:u,turn:b(),operatorLog:a};await Gl(d,c,S);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${f.pathname}`,"invalid_request_error","not_found_error");return}let g;try{g=await Ql(d)}catch(S){if(S instanceof Jn){m(413,S.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let y=Buffer.byteLength(JSON.stringify(g));if(f.pathname==="/v1/responses"){u.request("responses",y,y),await um(g,p,Mn(p),c,u,b(),a);return}if(f.pathname==="/v1/chat/completions"){u.request("chat_completions",y,y),await dm(g,p,c,u,b(),d.headers[Rs],a);return}if(f.pathname==="/v1/systemone"){u.request("systemone",y,y),await cm(g,p,c,u,b(),a);return}if(f.pathname==="/v1/decisions"){u.request("decisions",y,y),await pm(g,p,c,u,b(),a);return}if(f.pathname==="/v1/messages"){u.request("messages",y,y),await wm(g,p,c,u,b(),a);return}if(f.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",y,y),Qe(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${f.pathname}`,"invalid_request_error","not_found_error")})().catch(v=>{let p=String(v instanceof Error?v.message:v);if(!c.headersSent){let S=o?.(v)??null;if(S){S.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} classified failure; detail withheld from the caller: ${S.operatorDetail}`),m(S.status,p,S.openaiType,S.anthropicType,S.code);return}if(v instanceof Jr.SessionAllocationError){let P=Ar(v.code);if(P){let R=v.retryAfterSeconds??(P.status===429?30:void 0);R!==void 0&&c.setHeader("Retry-After",String(R)),m(P.status,Un(P,v.code??void 0),P.openaiType,P.anthropicType,P.code);return}}if(v instanceof Jr.SessionFailedError){let P=Ir(v);if(P){let R=P.status===429?30:void 0;R!==void 0&&c.setHeader("Retry-After",String(R)),m(P.status,Un(P,v.status.sessionId?`session ${v.status.sessionId}`:void 0),P.openaiType,P.anthropicType,P.code);return}}if(v instanceof we){m(502,p,"upstream_error","api_error");return}if(v instanceof Ke){v.retryable&&c.setHeader("Retry-After","1");let P=De(v,{inferenceId:x?.id??null});P.redacted&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} pre-head decision stream failure; raw error withheld from the caller: ${v instanceof Error?`${v.name}: ${v.message}`:Ge(v)}`),m(502,P.message,"upstream_error","api_error",v.code);return}if(v instanceof vt){c.setHeader("Retry-After",String(v.retryAfterSeconds)),m(v.status,p,v.status===429?"capacity_error":"upstream_error",v.status===429?"rate_limit_error":"overloaded_error",v.code);return}let A=De(v,{inferenceId:x?.id??null});A.redacted&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} failed; raw error withheld from the caller: ${v instanceof Error?`${v.name}: ${v.message}`:Ge(v)}`),m(500,A.message,"proxy_error","api_error","proxy_error");return}x&&(x.streamError=!0);let g=v instanceof Ke?v.code:null,y=De(v,{inferenceId:x?.id??null});y.redacted&&a(`[caller-message-boundary] the stream for ${f.pathname} failed after the head went out; raw error withheld from the caller: ${v instanceof Error?`${v.name}: ${v.message}`:Ge(v)}`),c.destroyed||(h?c.write(`event: error
71
+ `)};if(t.stream===!0){let A=r.track(h,c,o);Ts(n),m("message_start",{message:{id:l,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let P=0,R="",O=0,b="none",C=()=>b,$=-1,M=-1,U=new _t,q=[],X=()=>{b!=="none"&&(b="none",m("content_block_stop",{index:$}))},G=(ce,me)=>{X(),b=ce,$=O++,m("content_block_start",{index:$,content_block:me})};for await(let ce of A){if(n.destroyed)break;q.push(ce);let me=tn(ce);if(ce.type==="response.reasoning_text.delta"&&typeof ce.delta=="string")C()!=="thinking"&&G("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:$,delta:{type:"thinking_delta",thinking:ce.delta}});else if(ce.type==="response.output_text.delta"&&typeof ce.delta=="string")C()!=="text"&&G("text",{type:"text",text:""}),P+=1,R+=ce.delta,m("content_block_delta",{index:$,delta:{type:"text_delta",text:ce.delta}});else if(me){let{call:Me}=U.add(me);(C()!=="tool"||me.tool_index!==M)&&(M=me.tool_index,G("tool",{type:"tool_use",id:Me.id??`call_${me.tool_index}`,name:Me.name??"",input:{}})),me.delta&&m("content_block_delta",{index:$,delta:{type:"input_json_delta",partial_json:me.delta}})}else if(ce.type==="error"){o.streamError=!0;let Me=ce.error,it=rt(Me);it===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(ce)}`),m("error",{error:{type:"api_error",message:it??Ye(o.id)}}),n.end();return}}if(n.destroyed)return;let re=nt(q),K=en(re),N=$t(f,U.size+K.length,R);if(N){o.streamError=!0,m("error",{error:{type:"api_error",message:Mt(c,N)}}),n.end();return}X();let ee=[];if(U.size===0)try{ee=Is(re)}catch(ce){o.streamError=!0;let me=De(ce,{inferenceId:o.id});me.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(ce instanceof Error?ce.message:ce)}`),m("error",{error:{type:"api_error",message:me.message}}),n.end();return}O===0&&ee.length===0&&(G("text",{type:"text",text:""}),X()),ee.forEach(ce=>{let me=O++;m("content_block_start",{index:me,content_block:{...ce,input:{}}}),m("content_block_delta",{index:me,delta:{type:"input_json_delta",partial_json:JSON.stringify(ce.input??{})}}),m("content_block_stop",{index:me})});let Fe=U.size>0||ee.length>0,ue=Wr(re);Bt(o,re),m("message_delta",{delta:{stop_reason:Fe?"tool_use":"end_turn"},usage:ue?{input_tokens:ue.input_tokens,output_tokens:ue.output_tokens}:{output_tokens:P}}),m("message_stop",{}),n.end();return}let w="",E="",x=[],v=new _t;for await(let A of r.track(h,c,o)){x.push(A),A.type==="response.output_text.delta"&&typeof A.delta=="string"&&(w+=A.delta),A.type==="response.reasoning_text.delta"&&typeof A.delta=="string"&&(E+=A.delta);let P=tn(A);if(P&&v.add(P),A.type==="error"){let R=A.error,O=R?.type==="invalid_request_error",b=rt(R);b===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(A)}`),Qe(n,O?400:502,O?"invalid_request_error":"api_error",b??Ye(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let _=nt(x);Bt(o,_);let p;try{p=Is(_),p.length===0&&v.size>0&&(p=Is({output:v.items()}))}catch(A){let P=De(A,{inferenceId:o.id});P.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(A instanceof Error?A.message:A)}`),Qe(n,502,"api_error",P.message);return}let g=$t(f,p.length,w);if(g){Qe(n,502,"api_error",Mt(c,g));return}let y=[],S=E||ou(_);S&&y.push({type:"thinking",thinking:S}),(w||p.length===0)&&y.push({type:"text",text:w}),y.push(...p),Te(n,200,{id:l,type:"message",role:"assistant",content:y,model:a,stop_reason:p.length>0?"tool_use":"end_turn",usage:Wr(_)??{input_tokens:0,output_tokens:0}})}function vm(t){tt(process.stdout,t)}function iu(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??vm,a=t.operatorLog??(d=>console.error(d)),l=t.observe,u=new Ct;return(d,c)=>{let f=new URL(d.url??"/","http://localhost"),h=f.pathname==="/v1/messages"||f.pathname.startsWith("/v1/messages/"),m=(_,p,g,y,S)=>h?Qe(c,_,y,p):de(c,_,p,g,S),w=Zo(f.pathname),E=f.pathname.startsWith("/partners/"),x=w||E?{id:Pt(),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;x&&(c.setHeader(Wa,x.id),c.once("close",()=>{let _=za({turn:x,method:d.method??"",path:f.pathname,res:c});i(Ya(_)),l?.(_),dr({record:_,ledger:t.ledger??null,req:d})}));let v=()=>Ja(f.pathname,x);(async()=>{if(d.method==="GET"&&f.pathname==="/healthz"){Te(c,200,{ok:!0});return}if(d.method==="GET"&&f.pathname==="/stats"){Te(c,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let _=f.pathname===pr?"canonical":f.pathname===On?"huggingface":null;if(_){if(d.method!=="POST"){m(405,`${f.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let S=t.usage;if(!S){m(501,`${f.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 A=S.authorize(d),P;try{P=await tu(d,la)}catch(b){if(b instanceof Vn){m(413,b.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let R=b=>S.lookup(A,b),O;try{if(_==="canonical"){let b=ua(P),C=await R(b);fr(C,b),O={requests:C}}else O=await pa(P,R)}catch(b){if(b instanceof wt){m(b.status,b.message,"invalid_request_error","invalid_request_error");return}throw b}Te(c,200,O);return}if(d.method==="GET"&&f.pathname===Rt){let S=await s(d);if(x&&(x.org=S.tenant??null),!S.openRouterModels){m(501,`GET ${Rt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}Te(c,200,await S.openRouterModels());return}if(f.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${f.pathname} \u2014 the partner surface currently carries ${On} and GET ${Rt}`,"invalid_request_error","not_found_error");return}let p=await s(d);if(x&&(x.org=p.tenant??null),d.method==="GET"&&f.pathname==="/v1/models"){if(f.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:Rt}),c.end();return}Te(c,200,await p.listModels());return}if(d.method==="GET"&&f.pathname===Rl){if(!p.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}Te(c,200,await p.listImageModels());return}if(kl(f.pathname)){if(!p.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${f.pathname}`,"not_implemented","not_implemented_error");return}let S={clients:p,imageModels:p.supportsImages,stats:u,turn:v(),operatorLog:a};f.pathname===Br?await Ml(d,c,S):await Ll(d,c,S);return}if(d.method==="GET"&&f.pathname===zl){if(!p.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}Te(c,200,await p.listSpeechToTextModels());return}if(Kl(f.pathname)){if(!p.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Gr}`,"not_implemented","not_implemented_error");return}let S={clients:p,transcriptionModels:p.supportsTranscription,stats:u,turn:v(),operatorLog:a};await Ql(d,c,S);return}if(ql(f.pathname)){if(!p.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Wn}`,"not_implemented","not_implemented_error");return}let S={clients:p,speechModels:p.supportsSpeech,stats:u,turn:v(),operatorLog:a};await Vl(d,c,S);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${f.pathname}`,"invalid_request_error","not_found_error");return}let g;try{g=await tu(d)}catch(S){if(S instanceof Vn){m(413,S.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let y=Buffer.byteLength(JSON.stringify(g));if(f.pathname==="/v1/responses"){u.request("responses",y,y),await dm(g,p,$n(p),c,u,v(),a);return}if(f.pathname==="/v1/chat/completions"){u.request("chat_completions",y,y),await cm(g,p,c,u,v(),d.headers[xs],a);return}if(f.pathname==="/v1/systemone"){u.request("systemone",y,y),await pm(g,p,c,u,v(),a);return}if(f.pathname==="/v1/decisions"){u.request("decisions",y,y),await fm(g,p,c,u,v(),a);return}if(f.pathname==="/v1/messages"){u.request("messages",y,y),await _m(g,p,c,u,v(),a);return}if(f.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",y,y),Qe(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${f.pathname}`,"invalid_request_error","not_found_error")})().catch(_=>{let p=String(_ instanceof Error?_.message:_);if(!c.headersSent){let S=o?.(_)??null;if(S){S.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} classified failure; detail withheld from the caller: ${S.operatorDetail}`),m(S.status,p,S.openaiType,S.anthropicType,S.code);return}if(_ instanceof Kr.SessionAllocationError){let P=Tr(_.code);if(P){let R=_.retryAfterSeconds??(P.status===429?30:void 0);R!==void 0&&c.setHeader("Retry-After",String(R)),m(P.status,Dn(P,_.code??void 0),P.openaiType,P.anthropicType,P.code);return}}if(_ instanceof Kr.SessionFailedError){let P=Or(_);if(P){let R=P.status===429?30:void 0;R!==void 0&&c.setHeader("Retry-After",String(R)),m(P.status,Dn(P,_.status.sessionId?`session ${_.status.sessionId}`:void 0),P.openaiType,P.anthropicType,P.code);return}}if(_ instanceof we){m(502,p,"upstream_error","api_error");return}if(_ instanceof Ke){_.retryable&&c.setHeader("Retry-After","1");let P=De(_,{inferenceId:x?.id??null});P.redacted&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} pre-head decision stream failure; raw error withheld from the caller: ${_ instanceof Error?`${_.name}: ${_.message}`:Ge(_)}`),m(502,P.message,"upstream_error","api_error",_.code);return}if(_ instanceof vt){c.setHeader("Retry-After",String(_.retryAfterSeconds)),m(_.status,p,_.status===429?"capacity_error":"upstream_error",_.status===429?"rate_limit_error":"overloaded_error",_.code);return}let A=De(_,{inferenceId:x?.id??null});A.redacted&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} failed; raw error withheld from the caller: ${_ instanceof Error?`${_.name}: ${_.message}`:Ge(_)}`),m(500,A.message,"proxy_error","api_error","proxy_error");return}x&&(x.streamError=!0);let g=_ instanceof Ke?_.code:null,y=De(_,{inferenceId:x?.id??null});y.redacted&&a(`[caller-message-boundary] the stream for ${f.pathname} failed after the head went out; raw error withheld from the caller: ${_ instanceof Error?`${_.name}: ${_.message}`:Ge(_)}`),c.destroyed||(h?c.write(`event: error
72
72
  data: ${JSON.stringify({type:"error",error:{type:"api_error",message:y.message}})}
73
73
 
74
74
  `):c.write(`data: ${JSON.stringify({error:{message:y.message,type:"upstream_error",code:g}})}
75
75
 
76
- `)),c.end()})}}O();var ct=(t,e)=>Object.assign(new Error(e),{status:t}),Sm='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Ts=(t,e,n)=>new te(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Os=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof ie?ct(404,n.message):n}};async function ou(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw ct(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Sm}`);if(o==="transcription")throw ct(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 ct(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 ct(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 f;try{f=await t.supportsTranscription(n.stt)}catch(h){throw h instanceof ie?ct(404,h.message):h}if(!f)throw ct(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 f;try{f=await t.transcriptStreamFor(n.stt)}catch(h){throw h instanceof ie?ct(404,h.message):h}if(f!=="stt")throw ct(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \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 Os(t,n.stt),i=await Os(t,e),a=await Os(t,n.tts),l=await t.openAudioOn(s,r),u=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:f=>{let h=new AbortController;return d=h,km({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},f,h.signal,()=>{d===h&&(d=null)})}},cancelActiveTurn:()=>{let f=d;d=null,f?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:f=>{l.appendInputAudio(f)},onOutputAudio:f=>u.onOutputAudio(f),sessionId:u.sessionId}},turns:async function*(f){try{yield*t.openTurnsOn(s,f)}catch(h){throw h instanceof te?Ts("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function Ps(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Kn=class extends Error{};async function*km(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:l}=t;if(n?.aborted){r?.();return}let{output_modalities:u,...d}=e,c=e.output_modalities,f=!Array.isArray(c)||c.includes("audio"),h=!1,m=null,w=null,E=[],x=null,b=new Promise((T,_)=>{n&&n.addEventListener("abort",()=>_(new Kn),{once:!0})}),v=()=>h||n?.aborted===!0,p=async T=>{if(v())return;let _;try{_=await o.createResponseOn(i,{model:l.tts,input:[{role:"user",content:[{type:"input_text",text:T}]}],stream:!1,...l.voice!==void 0?{voice:l.voice}:{}})}catch($){throw $ instanceof te?Ts("tts",l.tts,$):$}let C=_[Symbol.asyncIterator]();w=C;try{for(;;){let $=C.next(),N;try{N=await Promise.race([$,b])}catch(q){if($.catch(()=>{}),q instanceof Kn)return;throw q}if(N.done)return;let D=N.value;if(D.type==="error"){let q=D.error&&typeof D.error.message=="string"?D.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(l.tts)}) errored: ${q}`)}if(D.type==="response.completed")return}}finally{w===C&&(w=null)}},g=async()=>{for(;E.length>0&&!v();){let T=E.shift();await p(T)}},y=T=>{if(T===""||v()||(E.push(T),x!==null))return;let _=g();x=_,_.then(()=>{x===_&&(x=null)},C=>{x===_&&(x=null),m??=C})},S=()=>{h=!0,E.length=0;let T=w;if(w=null,T){let _=T.return?.();_&&_.catch(()=>{})}},A=async()=>{for(;E.length>0||x!==null;){let T=x;if(T===null){await p(E.shift());continue}await T}},P=f?new dn({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},T=>y(T)):null,R=null;try{let T;try{T=await o.createResponseOn(s,d)}catch(C){throw C instanceof te?Ts("chat",a,C):C}let _=T[Symbol.asyncIterator]();try{for(;;){let C=_.next(),$;try{$=await Promise.race([C,b])}catch(q){if(C.catch(()=>{}),q instanceof Kn)break;throw q}if($.done)break;let N=$.value;if(v())return;let D=N;if(D.type==="error"){yield N;return}if(D.type==="response.output_text.delta"&&typeof D.delta=="string"){yield N,P?.push(D.delta);continue}if(D.type==="response.function_call_arguments.delta"){P?.flush(),yield N;continue}if(D.type==="response.completed"){R=N.response;continue}}}finally{Promise.resolve(_.return?.()).catch(()=>{})}P?.flush(),P?.dispose(),f&&await A(),R!==null&&(yield{type:"response.completed",response:R})}finally{P?.dispose(),S();try{if(m instanceof te)throw m}finally{r?.()}}}var We=(t,e)=>Object.assign(new Error(e),{status:t});function iu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function au(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}function lu(t){let e=new URL(t.url??"/","http://localhost").searchParams.get("session"),n=t.headers?.["x-urun-session"],r=(e??(typeof n=="string"?n:n?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var Rm='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function uu(t,e,n,r,o){if(!t.supportsAudio)throw We(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 s;try{s=await t.supportsAudio(e)}catch(h){throw h instanceof ie?We(404,h.message):h}if(!s){let h=null;if(t.realtimeCompanionsFor)try{h=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof ie?We(404,m.message):m}if(h!==null)return await ou(t,e,h,n,r);throw We(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 We(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(h){throw h instanceof ie?We(404,h.message):h}if(i&&!t.openTurnsOn)throw We(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let h;try{h=await t.transcriptStreamFor(e)}catch(m){throw m instanceof ie?We(404,m.message):m}if(h!=="stt")throw We(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(h)} \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 We(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Rm}`);if(r==="transcription"&&!i)throw We(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 a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(h){throw h instanceof Ae?We(503,h.message):h}let l=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,u=`conn_${(0,su.randomUUID)()}`,c={audio:await t.openAudioOn(a,n,u,o).catch(h=>{throw t.releaseSessionHandle?.(a),h})},f={clients:{createResponse:async h=>await t.createResponseOn(a,h,u)},voice:s,audioSession:c};return t.openVideoOn&&(f.video=()=>t.openVideoOn(a,n)),i&&(f.turns=h=>t.openTurnsOn(a,h)),r==="transcription"&&(f.intent="transcription"),t.releaseSessionHandle&&(f.release=()=>t.releaseSessionHandle(a)),(t.touchSessionPresence||t.detachSessionPresence)&&(f.presence={touch:h=>t.touchSessionPresence?.(a,h),detach:h=>t.detachSessionPresence?.(a,h)}),t.endDedicatedSession&&(f.endSession=()=>t.endDedicatedSession(a)),t.onSessionEnd&&(f.onSessionEnd=h=>t.onSessionEnd(a,h)),e!==void 0&&(f.model=e),l!==null&&(f.catalog=l),f}O();var Mu=require("@urun-sh/core"),$u=require("@urun-sh/core/internal"),Nu=Ee(require("ws"),1);O();var vu=require("http");O();var mu=require("http");O();function du(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),typeof o.model=="string"&&o.model&&(s.model=o.model),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 zr(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}O();O();function cu(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 pu=require("@urun-sh/core/internal");O();var Em="llm-resp";async function*Yr(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,l=r.get(a)??{};i.id&&(l.id=i.id),i.function?.name&&(l.name=i.function.name),r.set(a,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:l.id,name:l.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 cu(s);return}}}async function*Cs(t,e){let n=`${Em}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Yr(e,t.stream(n).messages())}finally{try{(0,pu.gcRequest)(t.doc("llm"),e)}catch{}}}var xm="/pooler/v1/inference",Ze=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},Am=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)},Im=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)}},hu=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)}),Om=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await hu(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 Ze(t.status,e,n,t.retryAfterSeconds)};async function Tm(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${xm}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Am(e),firstMessage:Im(e)}});return new Promise((a,l)=>{let u=(0,mu.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})});u.on("error",d=>l(new Ze(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var fu=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*Pm(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
76
+ `)),c.end()})}}T();var ct=(t,e)=>Object.assign(new Error(e),{status:t}),km='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Cs=(t,e,n)=>new te(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Ps=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof ie?ct(404,n.message):n}};async function au(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw ct(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${km}`);if(o==="transcription")throw ct(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 ct(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 ct(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 f;try{f=await t.supportsTranscription(n.stt)}catch(h){throw h instanceof ie?ct(404,h.message):h}if(!f)throw ct(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 f;try{f=await t.transcriptStreamFor(n.stt)}catch(h){throw h instanceof ie?ct(404,h.message):h}if(f!=="stt")throw ct(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \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 Ps(t,n.stt),i=await Ps(t,e),a=await Ps(t,n.tts),l=await t.openAudioOn(s,r),u=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:f=>{let h=new AbortController;return d=h,Rm({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},f,h.signal,()=>{d===h&&(d=null)})}},cancelActiveTurn:()=>{let f=d;d=null,f?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:f=>{l.appendInputAudio(f)},onOutputAudio:f=>u.onOutputAudio(f),sessionId:u.sessionId}},turns:async function*(f){try{yield*t.openTurnsOn(s,f)}catch(h){throw h instanceof te?Cs("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function Ls(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var zn=class extends Error{};async function*Rm(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:l}=t;if(n?.aborted){r?.();return}let{output_modalities:u,...d}=e,c=e.output_modalities,f=!Array.isArray(c)||c.includes("audio"),h=!1,m=null,w=null,E=[],x=null,v=new Promise((O,b)=>{n&&n.addEventListener("abort",()=>b(new zn),{once:!0})}),_=()=>h||n?.aborted===!0,p=async O=>{if(_())return;let b;try{b=await o.createResponseOn(i,{model:l.tts,input:[{role:"user",content:[{type:"input_text",text:O}]}],stream:!1,...l.voice!==void 0?{voice:l.voice}:{}})}catch($){throw $ instanceof te?Cs("tts",l.tts,$):$}let C=b[Symbol.asyncIterator]();w=C;try{for(;;){let $=C.next(),M;try{M=await Promise.race([$,v])}catch(q){if($.catch(()=>{}),q instanceof zn)return;throw q}if(M.done)return;let U=M.value;if(U.type==="error"){let q=U.error&&typeof U.error.message=="string"?U.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(l.tts)}) errored: ${q}`)}if(U.type==="response.completed")return}}finally{w===C&&(w=null)}},g=async()=>{for(;E.length>0&&!_();){let O=E.shift();await p(O)}},y=O=>{if(O===""||_()||(E.push(O),x!==null))return;let b=g();x=b,b.then(()=>{x===b&&(x=null)},C=>{x===b&&(x=null),m??=C})},S=()=>{h=!0,E.length=0;let O=w;if(w=null,O){let b=O.return?.();b&&b.catch(()=>{})}},A=async()=>{for(;E.length>0||x!==null;){let O=x;if(O===null){await p(E.shift());continue}await O}},P=f?new cn({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},O=>y(O)):null,R=null;try{let O;try{O=await o.createResponseOn(s,d)}catch(C){throw C instanceof te?Cs("chat",a,C):C}let b=O[Symbol.asyncIterator]();try{for(;;){let C=b.next(),$;try{$=await Promise.race([C,v])}catch(q){if(C.catch(()=>{}),q instanceof zn)break;throw q}if($.done)break;let M=$.value;if(_())return;let U=M;if(U.type==="error"){yield M;return}if(U.type==="response.output_text.delta"&&typeof U.delta=="string"){yield M,P?.push(U.delta);continue}if(U.type==="response.function_call_arguments.delta"){P?.flush(),yield M;continue}if(U.type==="response.completed"){R=M.response;continue}}}finally{Promise.resolve(b.return?.()).catch(()=>{})}P?.flush(),P?.dispose(),f&&await A(),R!==null&&(yield{type:"response.completed",response:R})}finally{P?.dispose(),S();try{if(m instanceof te)throw m}finally{r?.()}}}var We=(t,e)=>Object.assign(new Error(e),{status:t});function uu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function du(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}function cu(t){let e=new URL(t.url??"/","http://localhost").searchParams.get("session"),n=t.headers?.["x-urun-session"],r=(e??(typeof n=="string"?n:n?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var Em='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function pu(t,e,n,r,o){if(!t.supportsAudio)throw We(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 s;try{s=await t.supportsAudio(e)}catch(h){throw h instanceof ie?We(404,h.message):h}if(!s){let h=null;if(t.realtimeCompanionsFor)try{h=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof ie?We(404,m.message):m}if(h!==null)return await au(t,e,h,n,r);throw We(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 We(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(h){throw h instanceof ie?We(404,h.message):h}if(i&&!t.openTurnsOn)throw We(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let h;try{h=await t.transcriptStreamFor(e)}catch(m){throw m instanceof ie?We(404,m.message):m}if(h!=="stt")throw We(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(h)} \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 We(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Em}`);if(r==="transcription"&&!i)throw We(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 a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(h){throw h instanceof Ae?We(503,h.message):h}let l=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,u=`conn_${(0,lu.randomUUID)()}`,c={audio:await t.openAudioOn(a,n,u,o).catch(h=>{throw t.releaseSessionHandle?.(a),h})},f={clients:{createResponse:async h=>await t.createResponseOn(a,h,u)},voice:s,audioSession:c};return t.openVideoOn&&(f.video=()=>t.openVideoOn(a,n)),i&&(f.turns=h=>t.openTurnsOn(a,h)),r==="transcription"&&(f.intent="transcription"),t.releaseSessionHandle&&(f.release=()=>t.releaseSessionHandle(a)),(t.touchSessionPresence||t.detachSessionPresence)&&(f.presence={touch:h=>t.touchSessionPresence?.(a,h),detach:h=>t.detachSessionPresence?.(a,h)}),t.endDedicatedSession&&(f.endSession=()=>t.endDedicatedSession(a)),t.onSessionEnd&&(f.onSessionEnd=h=>t.onSessionEnd(a,h)),e!==void 0&&(f.model=e),l!==null&&(f.catalog=l),f}T();var Uu=require("@urun-sh/core"),Du=require("@urun-sh/core/internal"),Fu=Ee(require("ws"),1);T();var ku=require("http");T();var yu=require("http");T();function fu(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),typeof o.model=="string"&&o.model&&(s.model=o.model),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 Xr(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}T();T();function mu(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 hu=require("@urun-sh/core/internal");T();var xm="llm-resp";async function*Qr(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,l=r.get(a)??{};i.id&&(l.id=i.id),i.function?.name&&(l.name=i.function.name),r.set(a,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:l.id,name:l.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 mu(s);return}}}async function*Ms(t,e){let n=`${xm}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Qr(e,t.stream(n).messages())}finally{try{(0,hu.gcRequest)(t.doc("llm"),e)}catch{}}}var Am="/pooler/v1/inference",Ze=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},Im=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)},Tm=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)}},wu=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)}),Om=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await wu(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 Ze(t.status,e,n,t.retryAfterSeconds)};async function Pm(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${Am}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Im(e),firstMessage:Tm(e)}});return new Promise((a,l)=>{let u=(0,yu.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})});u.on("error",d=>l(new Ze(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var gu=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*Cm(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
77
77
 
78
- `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=fu(s);i!==null&&(yield i)}let n=fu(e);n!==null&&(yield n)}async function gu(t,e,n,r){let o=zr(e,n,r),s=o.model??"";if(s==="")throw new Ze(400,"missing_model","the pooler submit requires a model");let i=await Tm(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Om(i);let a=e.stream===!0?Yr(n,Pm(i)):await Cm(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Cm(t,e){let n=await hu(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 Ze(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Yr(e,(async function*(){yield o})())}O();var Lm=require("@urun-sh/core"),Mm=require("bullmq"),$m=require("crypto");var yu=12e4;var Nm="/pooler/v1/lanes/pick",Um="/pooler/v1/lanes/status",Dm=1e4,Yn=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function wu(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),u=(0,vu.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:o},d=>{let c=[];d.on("data",f=>c.push(f)),d.on("end",()=>{let f=Buffer.concat(c).toString("utf8"),h=null;try{h=f===""?null:JSON.parse(f)}catch{h=null}s({status:d.statusCode??0,json:h})}),d.on("error",f=>i(new Ze(502,"pooler_unreachable",`the pooler channel failed: ${f.message}`)))});u.on("timeout",()=>{u.destroy(new Yn(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),u.on("error",d=>i(new Ze(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(l)})}function _u(t,e,n,r){if(t===400&&Fm(e)?.code==="lane_target")return new Nt(n,r);if(t===503)return new Ae(n);let o=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: ${o}`)}function Fm(t){if(t===null||typeof t!="object")return null;let e=t.error;return e!==null&&typeof e=="object"?e:null}function bu(t){return{async pick({pool:e,app:n,fn:r,sharedApp:o,requestorOrgId:s,model:i,holdMs:a=0}){let l=Math.min(Math.max(Math.trunc(a),0),yu),u=await wu(t,"POST",Nm,{pool:e,app:n,fn:r,model:i,hold_ms:l,...o?{shared_app:!0}:{},...s?{requestor_org_id:s}:{}},l+Dm);if(u.status!==200)throw _u(u.status,u.json,e,i);return(u.json?.lanes??[]).filter(c=>typeof c.lane_id=="string"&&c.lane_id!==""&&typeof c.host=="string"&&c.host!=="").map(c=>({laneId:c.lane_id,host:c.host}))},async status(){let e=await wu(t,"GET",Um,void 0,5e3);if(e.status!==200)throw _u(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}O();O();O();async function Su(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)})}var ku=require("@urun-sh/core/internal");var Xr=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=zr(e,n,this.consumerId);return this.write(r),Cs(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=du(e,n,r,this.consumerId);return this.write(o),Cs(this.session,r)})}cancelTurn(e){try{(0,ku.gcRequest)(this.session.doc("llm"),e)}catch{}}async writeGated(e,n){try{await Su(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 Ru=0;function Hm(){return Ru+=1,`req_${Date.now().toString(36)}_${Ru.toString(36)}`}var Ht=class{transport;constructor(e,n){this.transport=new Xr(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Hm(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};O();var pn=Ee(require("yjs"),1),Eu=require("@urun-sh/core/internal"),jm=3e4;function qm(t){return(e,n,r)=>{let o=t(e);pn.applyUpdate(n,pn.encodeStateAsUpdate(o));let s=a=>pn.applyUpdate(o,a),i=a=>pn.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?qm(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 Eu.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},l=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*f(){let h=a(d);try{yield*h.messages()}finally{i.delete(d),await h.close()}}return{messages:()=>f(),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:l,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let f=d?.timeout??t.whenLiveTimeoutMs??jm;await new Promise((h,m)=>{let w=setTimeout(()=>{E(),m(new Error(`lane ${e} llm doc never synced within ${f}ms`))},f),E=c.onSynced(()=>{clearTimeout(w),d?.signal?.removeEventListener("abort",x),h()}),x=()=>{clearTimeout(w),E(),m(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",x,{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()}}}O();var jt=Ee(require("ws"),1),qt=require("@urun-sh/core"),xu="/stream/";function Au(t){if(!t.startsWith(xu))return null;let e=t.slice(xu.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 eo(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Qr(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>qt.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Zr=class{reassembler=new qt.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===qt.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})}}},$s=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.bytes+o.byteLength>Iu&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Iu} 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,l)=>a+l.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")}}},Iu=8*1024*1024,st=new $s;function Ou(t,e){let n=new Zr,r={send(o){st.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Qr(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(),st.detach(t,e,r)}};return st.attach(t,e,r),r}function Gm(t,e){return{deliver(n){e?.();try{t.send(n,{binary:!0})}catch(r){console.warn(`[lane-stream] socket send failed: ${String(r)}`)}},close(n,r){try{t.close(n,r)}catch{}}}}function Tu(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new jt.default(r,eo(e)),s=new Zr;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Qr(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);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(Qr(i),o.readyState!==jt.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 Ms(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
78
+ `);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=gu(s);i!==null&&(yield i)}let n=gu(e);n!==null&&(yield n)}async function _u(t,e,n,r){let o=Xr(e,n,r),s=o.model??"";if(s==="")throw new Ze(400,"missing_model","the pooler submit requires a model");let i=await Pm(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Om(i);let a=e.stream===!0?Qr(n,Cm(i)):await Lm(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Lm(t,e){let n=await wu(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 Ze(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Qr(e,(async function*(){yield o})())}T();var Mm=require("@urun-sh/core"),$m=require("bullmq"),Nm=require("crypto");var vu=12e4;var Um="/pooler/v1/lanes/pick",Dm="/pooler/v1/lanes/status",Fm=1e4,Xn=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function bu(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),u=(0,ku.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:o},d=>{let c=[];d.on("data",f=>c.push(f)),d.on("end",()=>{let f=Buffer.concat(c).toString("utf8"),h=null;try{h=f===""?null:JSON.parse(f)}catch{h=null}s({status:d.statusCode??0,json:h})}),d.on("error",f=>i(new Ze(502,"pooler_unreachable",`the pooler channel failed: ${f.message}`)))});u.on("timeout",()=>{u.destroy(new Xn(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),u.on("error",d=>i(new Ze(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(l)})}function Su(t,e,n,r){if(t===400&&Bm(e)?.code==="lane_target")return new Nt(n,r);if(t===503)return new Ae(n);let o=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: ${o}`)}function Bm(t){if(t===null||typeof t!="object")return null;let e=t.error;return e!==null&&typeof e=="object"?e:null}function Ru(t){return{async pick({pool:e,app:n,fn:r,sharedApp:o,requestorOrgId:s,model:i,holdMs:a=0}){let l=Math.min(Math.max(Math.trunc(a),0),vu),u=await bu(t,"POST",Um,{pool:e,app:n,fn:r,model:i,hold_ms:l,...o?{shared_app:!0}:{},...s?{requestor_org_id:s}:{}},l+Fm);if(u.status!==200)throw Su(u.status,u.json,e,i);return(u.json?.lanes??[]).filter(c=>typeof c.lane_id=="string"&&c.lane_id!==""&&typeof c.host=="string"&&c.host!=="").map(c=>({laneId:c.lane_id,host:c.host}))},async status(){let e=await bu(t,"GET",Dm,void 0,5e3);if(e.status!==200)throw Su(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}T();T();T();async function Eu(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)})}var xu=require("@urun-sh/core/internal");var Zr=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=Xr(e,n,this.consumerId);return this.write(r),Ms(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=fu(e,n,r,this.consumerId);return this.write(o),Ms(this.session,r)})}cancelTurn(e){try{(0,xu.gcRequest)(this.session.doc("llm"),e)}catch{}}async writeGated(e,n){try{await Eu(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 Au=0;function jm(){return Au+=1,`req_${Date.now().toString(36)}_${Au.toString(36)}`}var Ht=class{transport;constructor(e,n){this.transport=new Zr(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=jm(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};T();var fn=Ee(require("yjs"),1),Iu=require("@urun-sh/core/internal"),qm=3e4;function Gm(t){return(e,n,r)=>{let o=t(e);fn.applyUpdate(n,fn.encodeStateAsUpdate(o));let s=a=>fn.applyUpdate(o,a),i=a=>fn.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 $s(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Gm(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 Iu.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},l=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*f(){let h=a(d);try{yield*h.messages()}finally{i.delete(d),await h.close()}}return{messages:()=>f(),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:l,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let f=d?.timeout??t.whenLiveTimeoutMs??qm;await new Promise((h,m)=>{let w=setTimeout(()=>{E(),m(new Error(`lane ${e} llm doc never synced within ${f}ms`))},f),E=c.onSynced(()=>{clearTimeout(w),d?.signal?.removeEventListener("abort",x),h()}),x=()=>{clearTimeout(w),E(),m(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",x,{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()}}}T();var jt=Ee(require("ws"),1),qt=require("@urun-sh/core"),Tu="/stream/";function Ou(t){if(!t.startsWith(Tu))return null;let e=t.slice(Tu.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 no(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function eo(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>qt.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var to=class{reassembler=new qt.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===qt.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})}}},Us=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.bytes+o.byteLength>Pu&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Pu} 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,l)=>a+l.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")}}},Pu=8*1024*1024,st=new Us;function Cu(t,e){let n=new to,r={send(o){st.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{eo(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(),st.detach(t,e,r)}};return st.attach(t,e,r),r}function Wm(t,e){return{deliver(n){e?.();try{t.send(n,{binary:!0})}catch(r){console.warn(`[lane-stream] socket send failed: ${String(r)}`)}},close(n,r){try{t.close(n,r)}catch{}}}}function Lu(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new jt.default(r,no(e)),s=new to;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{eo(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);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(eo(i),o.readyState!==jt.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 Ns(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
79
79
  `;t.end(`HTTP/1.1 ${e} ${r}\r
80
80
  Connection: close\r
81
81
  Content-Type: text/plain; charset=utf-8\r
82
82
  Content-Length: ${Buffer.byteLength(o)}\r
83
83
  \r
84
- ${o}`)}function Pu(t,e){let n=e.heartbeatMs??3e4,r=e.streamLeaseMs??6e4,o=new jt.WebSocketServer({noServer:!0,handleProtocols:(m,w)=>{let E=Au(new URL(w.url??"/","http://localhost").pathname);if(!E)return!1;let x=eo(E.name);return m.has(x)?x:!1}}),s=new Map,i=new Set,a=!1,l=new Map,u=(m,w,E)=>{r>0&&l.set(m,{at:Date.now(),label:w,reap:E})},d=m=>{let w=l.get(m);w&&(w.at=Date.now())},c=r>0?setInterval(()=>{let m=Date.now();for(let[w,E]of l)m-E.at<r||(l.delete(w),console.warn(`[lane-stream] ${E.label}: lease expired (no data for ${r} ms) \u2014 terminating`),E.reap())},Math.max(10,Math.floor(r/4))):void 0;c?.unref?.();let f=(m,w,E,x)=>{let b={client:E,upstream:x,laneId:m,name:w};i.add(b);let v=p=>{if(i.delete(b)){l.delete(E),console.warn(`[lane-stream] ${m}/${w}: host-affinity pump torn down (${p})`);for(let g of[E,x])try{(g.readyState===jt.default.OPEN||g.readyState===jt.default.CONNECTING)&&g.close(1001,"lane stream pump closed")}catch{}}};if(u(E,`${m}/${w} pump`,()=>{for(let p of[E,x])try{p.terminate()}catch{}v("lease expired")}),n>0){let p=(g,y)=>{let S=!0,A=()=>{S=!0};g.on("pong",A),g.on("message",A);let P=setInterval(()=>{if(!S){console.warn(`[lane-stream] ${m}/${w}: pong timeout on ${y} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${y} dial never sends a close)`),clearInterval(P);try{g.terminate()}catch{}v(`${y} pong timeout`);return}S=!1;try{g.ping()}catch{}},n);P.unref?.();let R=()=>clearInterval(P);g.once("close",R),g.once("error",R)};p(E,"client"),p(x,"host")}E.on("message",p=>{d(E);try{x.send(p,{binary:!0})}catch(g){v(`upstream send failed: ${String(g)}`)}}),x.on("message",p=>{d(E);try{E.send(p,{binary:!0})}catch(g){v(`client send failed: ${String(g)}`)}}),E.on("close",()=>v("client socket closed")),E.on("error",()=>v("client socket error")),x.on("close",()=>v("host socket closed")),x.on("error",()=>v("host socket error"))},h=(m,w,E)=>{let x;try{x=new URL(m.url??"/","http://localhost")}catch{Ms(w,400,"malformed upgrade URL");return}w.on("error",()=>w.destroy());let b=Au(x.pathname);b&&(a||w.destroyed||(async()=>{let v=x.searchParams.get("token")??"",p=null;try{p=v===""?null:await e.verifyToken(v,b.laneId,b.name)}catch{p=null}if(p===null){Ms(w,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let g=await e.hostOf(b.laneId).catch(()=>null);if(g&&g!==e.selfAddress)try{let y=await e.podToPodDial(b.laneId,b.name,g);o.handleUpgrade(m,w,E,S=>{f(b.laneId,b.name,S,y)});return}catch(y){console.warn(`[lane-stream] ${b.laneId}/${b.name}: host dial to ${g} failed (${String(y)}) \u2014 falling back to the local relay`)}}o.handleUpgrade(m,w,E,g=>{let y=Gm(g,()=>d(g));if(s.set(g,y),st.attach(b.laneId,b.name,y),u(g,`${b.laneId}/${b.name}`,()=>g.terminate()),n>0){let A=!0,P=()=>{A=!0};g.on("pong",P),g.on("message",P);let R=setInterval(()=>{if(!A){console.warn(`[lane-stream] ${b.laneId}/${b.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(R),g.terminate();return}A=!1;try{g.ping()}catch{}},n);R.unref?.();let T=()=>clearInterval(R);g.once("close",T),g.once("error",T)}g.on("message",A=>{d(g);let P=new Uint8Array(A);try{Qr(P)}catch(R){console.warn(`[lane-stream] ${b.laneId}/${b.name}: dropped malformed envelope: ${String(R)}`);return}st.deliver(b.laneId,b.name,y,P),P[1]===qt.ENVELOPE_KIND.END&&st.detach(b.laneId,b.name,y)});let S=()=>{s.delete(g),l.delete(g),st.detach(b.laneId,b.name,y)};g.on("close",S),g.on("error",S)})})().catch(()=>{w.destroyed||Ms(w,500,"lane stream upgrade failed")}))};return t.on("upgrade",h),{async close(){a=!0,t.off("upgrade",h),clearInterval(c),l.clear(),st.clear();for(let m of s.values())m.close(1001,"lane stream host shutting down");s.clear();for(let m of i)for(let w of[m.client,m.upstream])try{w.close(1001,"lane stream host shutting down")}catch{}i.clear()}}}O();var St=require("crypto"),Wm=["sfu","urun-doc"],Lu="runtime:lease",Jm="lane:join",Vm="urun-runtime-key-v1";function Ns(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,St.createHmac)("sha256",t).update(`${Vm}|${e}`).digest("base64url")}var Km=120;function Cu(t){return Buffer.from(t).toString("base64url")}function zm(t,e,n){let r=Cu(JSON.stringify(t)),o=Cu(JSON.stringify(e)),s=(0,St.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function Xn(t,e,n=Km,r=Jm,o){let s=o?Ns(e,o):e;return Ym(t,s,n,r,o)}function Ym(t,e,n,r,o){let s=Math.floor(Date.now()/1e3);return zm({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,St.randomUUID)()},e)}function Us(t,e,n,r=Math.floor(Date.now()/1e3),o){let s=t.split(".");if(s.length!==3)return null;let[i,a,l]=s,u,d;try{u=JSON.parse(Buffer.from(i,"base64url").toString()),d=JSON.parse(Buffer.from(a,"base64url").toString())}catch{return null}if(u.alg!=="HS256")return null;let c;try{c=Buffer.from(l,"base64url")}catch{return null}let f=typeof d.tenant=="string"&&d.tenant!==""?d.tenant:void 0,h=[];if(f!==void 0?(h.push(Ns(n,f)),o&&h.push(Ns(o,f))):(h.push(n),o&&h.push(o)),!h.some(b=>{let v=(0,St.createHmac)("sha256",b).update(`${i}.${a}`).digest();return c.length===v.length&&(0,St.timingSafeEqual)(c,v)}))return null;let m=d.exp;if(typeof m!="number"||m<=r)return null;let w=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(w!==void 0&&Wm.some(b=>b===w||Array.isArray(w)&&w.includes(b))))return null;let x=d.session_id??d.sub;return typeof x!="string"||x!==e?null:{sessionId:x,aud:w,scope:typeof d.scope=="string"?d.scope:void 0,tenant:f,app:typeof d.app=="string"?d.app:void 0,fn:typeof d.fn=="string"?d.fn:void 0,exp:m}}O();var Xm=3,Qm="llm",Zm=new Set(["paused","error"]);function to(t,e,n){let r=t.doc(Qm),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,l=new Set,u=[],d=c=>{if(!i){i=c;for(let f of[...l])f(c);l.clear()}};return o&&u.push(r.onConnectionState(c=>{a&&(c.consecutiveFailures<Xm||d(new te(`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"?u.push(r.onSynced(()=>{a=!0})):s&&u.push(t.onPhase(c=>{if(c.name==="live"){a=!0;return}a&&Zm.has(c.name)&&d(new te(`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.`,{bindingLost:!0,reason:c.reason??null}))})),{gone:()=>i,onGone(c){return i?(c(i),()=>{}):(l.add(c),()=>l.delete(c))},dispose(){l.clear();for(let c of u.splice(0))c()}}}async function*Ds(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(l=>a(l))});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 eh(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new qe(`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??""}`}var th={"prod-usw2":["us-west1"]};function Uu(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=new Set,a=(m,w,E,x,b,v)=>{let p=E?A=>Ou(m,A):A=>Tu(m,A,{hostUrl:`ws://${x}/stream/${m}`,token:()=>Xn(m,t.tokenSecret,void 0,void 0,v)}),g=E?Ls({laneId:m,roomDoc:A=>t.roomDoc(m,A),streamEndpoint:p}):Ls({laneId:m,streamEndpoint:p,connector:(0,$u.createWebsocketDocConnector)({serverUrl:`ws://${x}/doc`,sessionId:m,token:()=>Xn(m,t.tokenSecret,void 0,void 0,v),WebSocketPolyfill:Nu.default})}),y=E?l(m):to(g,`lane:${m}`,{armOnFirstSync:!0}),S={session:g,responses:new Ht(g,{sessionTag:null}),gone:y,goneWatch:y,laneId:m,pool:w,inFlight:0,laneSession:g,self:E,host:x??"",mintedRelease:b??"",retireWhenIdle:!1};return n.set(m,S),y.onGone(()=>u(S)),S},l=m=>{let w=null,E=!1,x=new Set,b=p=>{if(!w){w=p;for(let g of[...x])g(p);x.clear()}},v=t.hostedSignal?.(m,p=>{if(p){E=!0;return}E&&b(new te(`the lane ${m} 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:()=>w,onGone(p){return w?(p(w),()=>{}):(x.add(p),()=>x.delete(p))},dispose(){v?.(),x.clear()}}},u=m=>{d(m)&&(n.delete(m.laneId),r.delete(m.laneId),m.goneWatch?.dispose(),st.forgetLane(m.laneId))},d=m=>{let w=m.laneId;return typeof w=="string"&&n.get(w)===m},c=m=>{d(m)&&(m.self&&!t.closeLane||(i.add(m.laneId),m.self&&t.closeLane?.(m.laneId),u(m)))},f=(m,w)=>{throw t.metrics?.observeLane503Fast(w??""),s.set(m,e()),new Ae(m)},h=async(m,w)=>{let E=eh(w);o.add(E);let x=e();try{let b=await t.laneWarmWaitMsFor?.(m,w)??t.laneColdWakeDefaultMs??0,v;try{v=await t.plane.pick({pool:E,app:w.appSlug,fn:w.fnName??"",model:m,holdMs:b,...w.sharedApp?{sharedApp:!0}:{},...w.sharedApp&&w.callerOrgId?{requestorOrgId:w.callerOrgId}:{}})}catch(P){throw P instanceof Yn?new Mu.SessionAllocationError(`lane pick hold expired for ${E}: ${P.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):P}t.metrics?.observeLaneReady(m??"",v.length);let p=await t.currentReleaseOf?.(w)??null,g=new Set(v.map(P=>P.laneId));for(let P of i)g.has(P)||i.delete(P);let S=v.filter(P=>{let R=n.get(P.laneId);return R!==void 0&&p!==null&&R.mintedRelease!==""&&R.mintedRelease!==p&&(R.retireWhenIdle=!0,R.inFlight===0)?(c(R),!1):!i.has(P.laneId)}).map(P=>({laneId:P.laneId,self:P.host===t.selfAddress,host:P.host,region:P.region})).sort((P,R)=>{let T=th[t.seatRegion??""]??[],_=new Map(T.map((N,D)=>[N,D])),C=T.length===0?0:(P.region!==void 0?_.get(P.region):void 0)??T.length,$=T.length===0?0:(R.region!==void 0?_.get(R.region):void 0)??T.length;return C!==$?C-$:P.self!==R.self?P.self?-1:1:(r.get(P.laneId)??0)-(r.get(R.laneId)??0)})[0];S||f(E,m);let A=n.get(S.laneId);return A?.goneWatch?.gone()&&(u(A),A=void 0),A&&(A.pool!==E||A.self!==S.self||A.host!==S.host)&&(u(A),A=void 0),A||(A=a(S.laneId,E,S.self,S.host,p,w.sharedOrgId??void 0)),A.inFlight+=1,r.set(S.laneId,(r.get(S.laneId)??0)+1),{app:E,entry:A,identity:{kind:"catalog",model_id:w.modelId??m??"",variant:w.variant??""}}}finally{t.metrics?.observeLanePick(m??"",e()-x)}};return{sessionFor(m,w){return h(m,w)},release(m){d(m)&&(m.inFlight=Math.max(0,m.inFlight-1),r.set(m.laneId,m.inFlight),m.inFlight===0&&m.retireWhenIdle&&c(m))},owns(m){return d(m)},entryFor(m){return n.get(m)??null},evict(m){d(m)&&(m.gone.dispose(),n.delete(m.laneId),r.set(m.laneId,0),m.laneSession.destroy())},async status(){let m=[...new Set([...o,...[...n.values()].map(x=>x.pool)])].sort(),w=await t.plane.status().catch(()=>[]),E=new Map(nh(w));return Promise.all(m.map(async x=>{let b=E.get(x)??{pool:x,lanes:[],lastDemandAt:null};return{pool:x,lanes:b.lanes,lastDemandAt:b.lastDemandAt,local:[...n.values()].filter(v=>v.pool===x).map(v=>({laneId:v.laneId,inFlight:v.inFlight,self:v.self,host:v.host})),lastRefusalAt:s.get(x)??null}}))},async close(){for(let m of n.values())m.gone.dispose(),m.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(m=>({pool:m.pool,laneId:m.laneId,inFlight:m.inFlight}))}}}function nh(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}O();var rh="urun:node-scheduler:apps:v1";function oh(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function Du(t){return async e=>{let n=oh(e);if(n===null)return null;try{let r=await t.hget(rh,n);if(r===null||r==="")return null;let o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let s=o.current_release_id;if(typeof s!="string")return null;let i=s.trim();return i===""?null:i}catch{return null}}}O();var Wu=require("ws");O();var Bu=Ee(require("yjs"),1),hn=Ee(require("y-protocols/sync"),1),pt=Ee(require("y-protocols/awareness"),1),ye=Ee(require("lib0/encoding"),1),gn=Ee(require("lib0/decoding"),1),Hu=Ee(require("lib0/map"),1),ju=Ee(require("lodash.debounce"),1);O();var Fu=()=>{};var ih=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,ah=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,lh=0,uh=1;var dh=process.env.GC!=="false"&&process.env.GC!=="0",ch=process.env.YPERSISTENCE,no=null;if(typeof ch=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var mn=new Map,ro=0,Bs=1,ph=(t,e,n)=>{let r=ye.createEncoder();ye.writeVarUint(r,ro),hn.writeUpdate(r,t);let o=ye.toUint8Array(r);n.conns.forEach((s,i)=>Qn(n,i,o))},Fs=class extends Bu.Doc{constructor(e){super({gc:dh}),this.name=e,this.conns=new Map,this.awareness=new pt.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 l=ye.createEncoder();ye.writeVarUint(l,Bs),ye.writeVarUint8Array(l,pt.encodeAwarenessUpdate(this.awareness,a));let u=ye.toUint8Array(l);this.conns.forEach((d,c)=>{Qn(this,c,u)})};this.awareness.on("update",n),this.on("update",ph),!1}},Hs=(t,e=!0)=>Hu.setIfUndefined(mn,t,()=>{let n=new Fs(t);return n.gc=e,no!==null&&no.bindState(t,n),mn.set(t,n),n}),fh=(t,e,n)=>{try{let r=ye.createEncoder(),o=gn.createDecoder(n);switch(gn.readVarUint(o)){case ro:ye.writeVarUint(r,ro),hn.readSyncMessage(o,r,e,t),ye.length(r)>1&&Qn(e,t,ye.toUint8Array(r));break;case Bs:{pt.applyAwarenessUpdate(e.awareness,gn.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},fn=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),pt.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&no!==null&&(no.writeState(t.name,t).then(()=>{t.destroy()}),mn.delete(t.name))}e.close()},Qn=(t,e,n)=>{e.readyState!==lh&&e.readyState!==uh&&fn(t,e);try{e.send(n,r=>{r!=null&&fn(t,e)})}catch{fn(t,e)}},mh=3e4,qu=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=Hs(n,r);o.conns.set(t,new Set),t.on("message",a=>fh(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&fn(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{fn(o,t),clearInterval(i)}}},mh);t.on("close",()=>{fn(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=ye.createEncoder();ye.writeVarUint(a,ro),hn.writeSyncStep1(a,o),Qn(o,t,ye.toUint8Array(a));let l=o.awareness.getStates();if(l.size>0){let u=ye.createEncoder();ye.writeVarUint(u,Bs),ye.writeVarUint8Array(u,pt.encodeAwarenessUpdate(o.awareness,Array.from(l.keys()))),Qn(o,t,ye.toUint8Array(u))}}};var js="/doc/",Ju=30,hh=1e4,Gu="llm";function gh(t){if(!t.startsWith(js))return null;let e=t.slice(js.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 yn(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
84
+ ${o}`)}function Mu(t,e){let n=e.heartbeatMs??3e4,r=e.streamLeaseMs??6e4,o=new jt.WebSocketServer({noServer:!0,handleProtocols:(m,w)=>{let E=Ou(new URL(w.url??"/","http://localhost").pathname);if(!E)return!1;let x=no(E.name);return m.has(x)?x:!1}}),s=new Map,i=new Set,a=!1,l=new Map,u=(m,w,E)=>{r>0&&l.set(m,{at:Date.now(),label:w,reap:E})},d=m=>{let w=l.get(m);w&&(w.at=Date.now())},c=r>0?setInterval(()=>{let m=Date.now();for(let[w,E]of l)m-E.at<r||(l.delete(w),console.warn(`[lane-stream] ${E.label}: lease expired (no data for ${r} ms) \u2014 terminating`),E.reap())},Math.max(10,Math.floor(r/4))):void 0;c?.unref?.();let f=(m,w,E,x)=>{let v={client:E,upstream:x,laneId:m,name:w};i.add(v);let _=p=>{if(i.delete(v)){l.delete(E),console.warn(`[lane-stream] ${m}/${w}: host-affinity pump torn down (${p})`);for(let g of[E,x])try{(g.readyState===jt.default.OPEN||g.readyState===jt.default.CONNECTING)&&g.close(1001,"lane stream pump closed")}catch{}}};if(u(E,`${m}/${w} pump`,()=>{for(let p of[E,x])try{p.terminate()}catch{}_("lease expired")}),n>0){let p=(g,y)=>{let S=!0,A=()=>{S=!0};g.on("pong",A),g.on("message",A);let P=setInterval(()=>{if(!S){console.warn(`[lane-stream] ${m}/${w}: pong timeout on ${y} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${y} dial never sends a close)`),clearInterval(P);try{g.terminate()}catch{}_(`${y} pong timeout`);return}S=!1;try{g.ping()}catch{}},n);P.unref?.();let R=()=>clearInterval(P);g.once("close",R),g.once("error",R)};p(E,"client"),p(x,"host")}E.on("message",p=>{d(E);try{x.send(p,{binary:!0})}catch(g){_(`upstream send failed: ${String(g)}`)}}),x.on("message",p=>{d(E);try{E.send(p,{binary:!0})}catch(g){_(`client send failed: ${String(g)}`)}}),E.on("close",()=>_("client socket closed")),E.on("error",()=>_("client socket error")),x.on("close",()=>_("host socket closed")),x.on("error",()=>_("host socket error"))},h=(m,w,E)=>{let x;try{x=new URL(m.url??"/","http://localhost")}catch{Ns(w,400,"malformed upgrade URL");return}w.on("error",()=>w.destroy());let v=Ou(x.pathname);v&&(a||w.destroyed||(async()=>{let _=x.searchParams.get("token")??"",p=null;try{p=_===""?null:await e.verifyToken(_,v.laneId,v.name)}catch{p=null}if(p===null){Ns(w,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let g=await e.hostOf(v.laneId).catch(()=>null);if(g&&g!==e.selfAddress)try{let y=await e.podToPodDial(v.laneId,v.name,g);o.handleUpgrade(m,w,E,S=>{f(v.laneId,v.name,S,y)});return}catch(y){console.warn(`[lane-stream] ${v.laneId}/${v.name}: host dial to ${g} failed (${String(y)}) \u2014 falling back to the local relay`)}}o.handleUpgrade(m,w,E,g=>{let y=Wm(g,()=>d(g));if(s.set(g,y),st.attach(v.laneId,v.name,y),u(g,`${v.laneId}/${v.name}`,()=>g.terminate()),n>0){let A=!0,P=()=>{A=!0};g.on("pong",P),g.on("message",P);let R=setInterval(()=>{if(!A){console.warn(`[lane-stream] ${v.laneId}/${v.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(R),g.terminate();return}A=!1;try{g.ping()}catch{}},n);R.unref?.();let O=()=>clearInterval(R);g.once("close",O),g.once("error",O)}g.on("message",A=>{d(g);let P=new Uint8Array(A);try{eo(P)}catch(R){console.warn(`[lane-stream] ${v.laneId}/${v.name}: dropped malformed envelope: ${String(R)}`);return}st.deliver(v.laneId,v.name,y,P),P[1]===qt.ENVELOPE_KIND.END&&st.detach(v.laneId,v.name,y)});let S=()=>{s.delete(g),l.delete(g),st.detach(v.laneId,v.name,y)};g.on("close",S),g.on("error",S)})})().catch(()=>{w.destroyed||Ns(w,500,"lane stream upgrade failed")}))};return t.on("upgrade",h),{async close(){a=!0,t.off("upgrade",h),clearInterval(c),l.clear(),st.clear();for(let m of s.values())m.close(1001,"lane stream host shutting down");s.clear();for(let m of i)for(let w of[m.client,m.upstream])try{w.close(1001,"lane stream host shutting down")}catch{}i.clear()}}}T();var St=require("crypto"),Jm=["sfu","urun-doc"],Nu="runtime:lease",Vm="lane:join",Km="urun-runtime-key-v1";function Ds(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,St.createHmac)("sha256",t).update(`${Km}|${e}`).digest("base64url")}var zm=120;function $u(t){return Buffer.from(t).toString("base64url")}function Ym(t,e,n){let r=$u(JSON.stringify(t)),o=$u(JSON.stringify(e)),s=(0,St.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function Qn(t,e,n=zm,r=Vm,o){let s=o?Ds(e,o):e;return Xm(t,s,n,r,o)}function Xm(t,e,n,r,o){let s=Math.floor(Date.now()/1e3);return Ym({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,St.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,l]=s,u,d;try{u=JSON.parse(Buffer.from(i,"base64url").toString()),d=JSON.parse(Buffer.from(a,"base64url").toString())}catch{return null}if(u.alg!=="HS256")return null;let c;try{c=Buffer.from(l,"base64url")}catch{return null}let f=typeof d.tenant=="string"&&d.tenant!==""?d.tenant:void 0,h=[];if(f!==void 0?(h.push(Ds(n,f)),o&&h.push(Ds(o,f))):(h.push(n),o&&h.push(o)),!h.some(v=>{let _=(0,St.createHmac)("sha256",v).update(`${i}.${a}`).digest();return c.length===_.length&&(0,St.timingSafeEqual)(c,_)}))return null;let m=d.exp;if(typeof m!="number"||m<=r)return null;let w=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(w!==void 0&&Jm.some(v=>v===w||Array.isArray(w)&&w.includes(v))))return null;let x=d.session_id??d.sub;return typeof x!="string"||x!==e?null:{sessionId:x,aud:w,scope:typeof d.scope=="string"?d.scope:void 0,tenant:f,app:typeof d.app=="string"?d.app:void 0,fn:typeof d.fn=="string"?d.fn:void 0,exp:m}}T();var Qm=3,Zm="llm",eh=new Set(["paused","error"]);function ro(t,e,n){let r=t.doc(Zm),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,l=new Set,u=[],d=c=>{if(!i){i=c;for(let f of[...l])f(c);l.clear()}};return o&&u.push(r.onConnectionState(c=>{a&&(c.consecutiveFailures<Qm||d(new te(`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"?u.push(r.onSynced(()=>{a=!0})):s&&u.push(t.onPhase(c=>{if(c.name==="live"){a=!0;return}a&&eh.has(c.name)&&d(new te(`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.`,{bindingLost:!0,reason:c.reason??null}))})),{gone:()=>i,onGone(c){return i?(c(i),()=>{}):(l.add(c),()=>l.delete(c))},dispose(){l.clear();for(let c of u.splice(0))c()}}}async function*Bs(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(l=>a(l))});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 th(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new qe(`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??""}`}var nh={"prod-usw2":["us-west1"]};function Bu(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=new Set,a=(m,w,E,x,v,_)=>{let p=E?A=>Cu(m,A):A=>Lu(m,A,{hostUrl:`ws://${x}/stream/${m}`,token:()=>Qn(m,t.tokenSecret,void 0,void 0,_)}),g=E?$s({laneId:m,roomDoc:A=>t.roomDoc(m,A),streamEndpoint:p}):$s({laneId:m,streamEndpoint:p,connector:(0,Du.createWebsocketDocConnector)({serverUrl:`ws://${x}/doc`,sessionId:m,token:()=>Qn(m,t.tokenSecret,void 0,void 0,_),WebSocketPolyfill:Fu.default})}),y=E?l(m):ro(g,`lane:${m}`,{armOnFirstSync:!0}),S={session:g,responses:new Ht(g,{sessionTag:null}),gone:y,goneWatch:y,laneId:m,pool:w,inFlight:0,laneSession:g,self:E,host:x??"",mintedRelease:v??"",retireWhenIdle:!1};return n.set(m,S),y.onGone(()=>u(S)),S},l=m=>{let w=null,E=!1,x=new Set,v=p=>{if(!w){w=p;for(let g of[...x])g(p);x.clear()}},_=t.hostedSignal?.(m,p=>{if(p){E=!0;return}E&&v(new te(`the lane ${m} 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:()=>w,onGone(p){return w?(p(w),()=>{}):(x.add(p),()=>x.delete(p))},dispose(){_?.(),x.clear()}}},u=m=>{d(m)&&(n.delete(m.laneId),r.delete(m.laneId),m.goneWatch?.dispose(),st.forgetLane(m.laneId))},d=m=>{let w=m.laneId;return typeof w=="string"&&n.get(w)===m},c=m=>{d(m)&&(m.self&&!t.closeLane||(i.add(m.laneId),m.self&&t.closeLane?.(m.laneId),u(m)))},f=(m,w)=>{throw t.metrics?.observeLane503Fast(w??""),s.set(m,e()),new Ae(m)},h=async(m,w)=>{let E=th(w);o.add(E);let x=e();try{let v=await t.laneWarmWaitMsFor?.(m,w)??t.laneColdWakeDefaultMs??0,_;try{_=await t.plane.pick({pool:E,app:w.appSlug,fn:w.fnName??"",model:m,holdMs:v,...w.sharedApp?{sharedApp:!0}:{},...w.sharedApp&&w.callerOrgId?{requestorOrgId:w.callerOrgId}:{}})}catch(P){throw P instanceof Xn?new Uu.SessionAllocationError(`lane pick hold expired for ${E}: ${P.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):P}t.metrics?.observeLaneReady(m??"",_.length);let p=await t.currentReleaseOf?.(w)??null,g=new Set(_.map(P=>P.laneId));for(let P of i)g.has(P)||i.delete(P);let S=_.filter(P=>{let R=n.get(P.laneId);return R!==void 0&&p!==null&&R.mintedRelease!==""&&R.mintedRelease!==p&&(R.retireWhenIdle=!0,R.inFlight===0)?(c(R),!1):!i.has(P.laneId)}).map(P=>({laneId:P.laneId,self:P.host===t.selfAddress,host:P.host,region:P.region})).sort((P,R)=>{let O=nh[t.seatRegion??""]??[],b=new Map(O.map((M,U)=>[M,U])),C=O.length===0?0:(P.region!==void 0?b.get(P.region):void 0)??O.length,$=O.length===0?0:(R.region!==void 0?b.get(R.region):void 0)??O.length;return C!==$?C-$:P.self!==R.self?P.self?-1:1:(r.get(P.laneId)??0)-(r.get(R.laneId)??0)})[0];S||f(E,m);let A=n.get(S.laneId);return A?.goneWatch?.gone()&&(u(A),A=void 0),A&&(A.pool!==E||A.self!==S.self||A.host!==S.host)&&(u(A),A=void 0),A||(A=a(S.laneId,E,S.self,S.host,p,w.sharedOrgId??void 0)),A.inFlight+=1,r.set(S.laneId,(r.get(S.laneId)??0)+1),{app:E,entry:A,identity:{kind:"catalog",model_id:w.modelId??m??"",variant:w.variant??""}}}finally{t.metrics?.observeLanePick(m??"",e()-x)}};return{sessionFor(m,w){return h(m,w)},release(m){d(m)&&(m.inFlight=Math.max(0,m.inFlight-1),r.set(m.laneId,m.inFlight),m.inFlight===0&&m.retireWhenIdle&&c(m))},owns(m){return d(m)},entryFor(m){return n.get(m)??null},evict(m){d(m)&&(m.gone.dispose(),n.delete(m.laneId),r.set(m.laneId,0),m.laneSession.destroy())},async status(){let m=[...new Set([...o,...[...n.values()].map(x=>x.pool)])].sort(),w=await t.plane.status().catch(()=>[]),E=new Map(rh(w));return Promise.all(m.map(async x=>{let v=E.get(x)??{pool:x,lanes:[],lastDemandAt:null};return{pool:x,lanes:v.lanes,lastDemandAt:v.lastDemandAt,local:[...n.values()].filter(_=>_.pool===x).map(_=>({laneId:_.laneId,inFlight:_.inFlight,self:_.self,host:_.host})),lastRefusalAt:s.get(x)??null}}))},async close(){for(let m of n.values())m.gone.dispose(),m.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(m=>({pool:m.pool,laneId:m.laneId,inFlight:m.inFlight}))}}}function rh(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}T();var oh="urun:node-scheduler:apps:v1";function sh(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function Hu(t){return async e=>{let n=sh(e);if(n===null)return null;try{let r=await t.hget(oh,n);if(r===null||r==="")return null;let o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let s=o.current_release_id;if(typeof s!="string")return null;let i=s.trim();return i===""?null:i}catch{return null}}}T();var Ku=require("ws");T();var qu=Ee(require("yjs"),1),gn=Ee(require("y-protocols/sync"),1),pt=Ee(require("y-protocols/awareness"),1),ye=Ee(require("lib0/encoding"),1),yn=Ee(require("lib0/decoding"),1),Gu=Ee(require("lib0/map"),1),Wu=Ee(require("lodash.debounce"),1);T();var ju=()=>{};var ah=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,lh=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,uh=0,dh=1;var ch=process.env.GC!=="false"&&process.env.GC!=="0",ph=process.env.YPERSISTENCE,oo=null;if(typeof ph=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var hn=new Map,so=0,js=1,fh=(t,e,n)=>{let r=ye.createEncoder();ye.writeVarUint(r,so),gn.writeUpdate(r,t);let o=ye.toUint8Array(r);n.conns.forEach((s,i)=>Zn(n,i,o))},Hs=class extends qu.Doc{constructor(e){super({gc:ch}),this.name=e,this.conns=new Map,this.awareness=new pt.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 l=ye.createEncoder();ye.writeVarUint(l,js),ye.writeVarUint8Array(l,pt.encodeAwarenessUpdate(this.awareness,a));let u=ye.toUint8Array(l);this.conns.forEach((d,c)=>{Zn(this,c,u)})};this.awareness.on("update",n),this.on("update",fh),!1}},qs=(t,e=!0)=>Gu.setIfUndefined(hn,t,()=>{let n=new Hs(t);return n.gc=e,oo!==null&&oo.bindState(t,n),hn.set(t,n),n}),mh=(t,e,n)=>{try{let r=ye.createEncoder(),o=yn.createDecoder(n);switch(yn.readVarUint(o)){case so:ye.writeVarUint(r,so),gn.readSyncMessage(o,r,e,t),ye.length(r)>1&&Zn(e,t,ye.toUint8Array(r));break;case js:{pt.applyAwarenessUpdate(e.awareness,yn.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},mn=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),pt.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&oo!==null&&(oo.writeState(t.name,t).then(()=>{t.destroy()}),hn.delete(t.name))}e.close()},Zn=(t,e,n)=>{e.readyState!==uh&&e.readyState!==dh&&mn(t,e);try{e.send(n,r=>{r!=null&&mn(t,e)})}catch{mn(t,e)}},hh=3e4,Ju=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=qs(n,r);o.conns.set(t,new Set),t.on("message",a=>mh(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&mn(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{mn(o,t),clearInterval(i)}}},hh);t.on("close",()=>{mn(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=ye.createEncoder();ye.writeVarUint(a,so),gn.writeSyncStep1(a,o),Zn(o,t,ye.toUint8Array(a));let l=o.awareness.getStates();if(l.size>0){let u=ye.createEncoder();ye.writeVarUint(u,js),ye.writeVarUint8Array(u,pt.encodeAwarenessUpdate(o.awareness,Array.from(l.keys()))),Zn(o,t,ye.toUint8Array(u))}}};var Gs="/doc/",zu=30,gh=1e4,Vu="llm";function yh(t){if(!t.startsWith(Gs))return null;let e=t.slice(Gs.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 wn(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
85
85
  `;t.end(`HTTP/1.1 ${e} ${r}\r
86
86
  Connection: close\r
87
87
  Content-Type: text/plain; charset=utf-8\r
88
88
  Content-Length: ${Buffer.byteLength(o)}\r
89
89
  \r
90
- ${o}`)}function Vu(t,e){let n=new Wu.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=p=>o.get(`${p}/${Gu}`)??0,a=p=>s.get(p)??0,l=new Map,u=new Map,d=new Set,c=new Set,f=new Map,h=new Map,m=4096,w=!1,E=(p,g,y)=>{let S=i(p)>0,A=a(p),P=A>0,R=`${p}/${g}`,T=o.get(R)??0;y>0?o.set(R,y):o.delete(R);let _=A+y-T;_>0?s.set(p,_):s.delete(p);let C=i(p)>0,$=_>0;if(S!==C){C?x(p):b(p);for(let N of l.get(p)??[])N(C)}P&&!$&&queueMicrotask(()=>{let N=`${p}/`;for(let[D,q]of[...mn.entries()])!D.startsWith(N)||q.conns.size>0||(mn.delete(D),q.destroy())})},x=p=>{if(!e.hostRegistry||u.has(p))return;let g=()=>{e.hostRegistry?.setHost(p,e.selfAddress).catch(()=>{})};g();let y=setInterval(g,hh);y.unref?.(),u.set(p,y)},b=p=>{let g=u.get(p);g&&(clearInterval(g),u.delete(p)),e.hostRegistry&&e.hostRegistry.delHost(p,e.selfAddress).catch(()=>{})},v=(p,g,y)=>{let S;try{S=new URL(p.url??"/","http://localhost")}catch{yn(g,400,"malformed upgrade URL");return}g.on("error",()=>g.destroy()),g.on("close",()=>c.delete(g));let A=gh(S.pathname);if(!A){if(S.pathname.startsWith(js)){yn(g,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(g);return}d.add(g);let P=!1;(async()=>{if(h.has(A.laneId)){yn(g,409,"lane retired \u2014 the app's release moved; a fresh lane serves it");return}let R=S.searchParams.get("token")??"",T=null;try{T=R===""?null:await e.verifyToken(R,A.laneId,A.docName)}catch{T=null}if(T===null){yn(g,401,"invalid or missing lane doc token");return}let _=T;if(_.tenant!==void 0&&e.laneTenantOf){let C=null;try{C=await e.laneTenantOf(A.laneId)}catch{C=null}if(C==null||C==="")e.onLaneTenantMissing?.();else if(_.tenant!==C){yn(g,403,"lane doc token org does not match the lane record");return}}w||g.destroyed||(P=!0,n.handleUpgrade(p,g,y,C=>{d.delete(g),r.add(C),C.on("close",()=>r.delete(C));let $=f.get(A.laneId);$||($=new Set,f.set(A.laneId,$)),$.add(C),C.on("close",()=>{$.delete(C),$.size===0&&f.delete(A.laneId)});let N=_.scope===Lu||_.scope===void 0&&typeof _.app=="string"&&typeof _.fn=="string"&&_.aud==="sfu";if(N){let q=`${A.laneId}/${A.docName}`,X=(o.get(q)??0)+1;E(A.laneId,A.docName,X),X>1&&A.docName===Gu&&e.hostRegistry?.setHost(A.laneId,e.selfAddress).catch(()=>{})}C.on("close",()=>{if(!N)return;let q=`${A.laneId}/${A.docName}`;E(A.laneId,A.docName,Math.max(0,(o.get(q)??1)-1))}),qu(C,p,{docName:`${A.laneId}/${A.docName}`,gc:!0})}))})().catch(()=>{!P&&!g.destroyed&&yn(g,500,"lane doc upgrade failed")}).finally(()=>d.delete(g))};return t.on("upgrade",v),{async close(){w=!0,t.off("upgrade",v);for(let g of[...u.keys()])b(g);await new Promise(g=>{if(r.size===0&&d.size===0){g();return}let y=r.size+d.size,S=()=>{y-=1,y<=0&&g()};for(let A of r)A.once("close",S);for(let A of d)A.once("close",S);for(let A of r)A.close(1001,"lane doc host shutting down");for(let A of d)A.destroy()}),o.clear(),s.clear(),l.clear()},roomDoc(p,g){return Hs(`${p}/${g}`,!0)},isHosted(p){return i(p)>0},onHostedChange(p,g){let y=l.get(p);return y||(y=new Set,l.set(p,y)),y.add(g),g(i(p)>0),()=>{y.delete(g)}},closeLane(p){if(h.set(p,!0),h.size>m){let g=h.keys().next().value;g!==void 0&&h.delete(g)}b(p);for(let g of f.get(p)??[])g.close(1001,`lane ${p} retired \u2014 the app's release moved`)}}}var gd=Ee(require("ws"),1);O();var yh="urun:catalog:v1";function Ku(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,s=null,i=async()=>{let l=await t.redis.hgetall(yh),u=[];for(let d of Object.values(l))try{u.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
91
- `)}return r=u,o=n(),u},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 yd=Ee(require("ioredis"),1);O();var er=require("@urun-sh/core"),ao=require("crypto"),zu="urun-session-gateway",wh="machine",_h=3e5;function Xu(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var ae=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},wn=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}},ft=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function lo(t){let e=(t??"").trim();if(e==="")throw new ae("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new ae("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var vh=60,bh=6e4,Sh=4096;function kh(t){return t===401||t===403}var tr=class{constructor(e){this.opts=e;this.mint=e.mint??er.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new ae("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<bh)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let o,s;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:vh});o=i.orgId,s={...i.billingAudience!==void 0?{billingAudience:i.billingAudience}:{},...i.creditsAdmissionOk!==void 0?{creditsAdmissionOk:i.creditsAdmissionOk}:{},...i.creditsRefusalReason!==void 0?{creditsRefusalReason:i.creditsRefusalReason}:{}}}catch(i){throw i instanceof er.ClientTokenError&&i.status===402?(this.cache.delete(e),new wn(i.code==="spend_cap_reached"||i.code==="insufficient_credits"?i.code:void 0)):i instanceof er.ClientTokenError&&kh(i.status)?(this.cache.delete(e),new ae(n==="user"?"the WorkOS user token was rejected by the control plane \u2014 check that the user belongs to an org with inference access":"the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new ft(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${i instanceof Error?i.message:String(i)}`)}if(!o)throw new ft(`the control plane verified the ${n==="user"?"user token":"API key"} but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)`);if(this.cache.size>=Sh){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:o,at:this.now(),...s}),{apiKey:e,orgId:o,credential:n,...s}}clear(){this.cache.clear()}};function Zn(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function Yu(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var oo=class{constructor(e,n,r,o){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=o}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof ft?r:this.unavailable(`the ${this.jwksNoun} at ${e} answered a body that is not JSON`)}}async keys(e,n){let r=this.entries.get(e);if(!n&&r!==void 0&&this.now()-r.at<_h)return r.keys;let o=this.inFlight.get(e);if(o!==void 0)return o;let s=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,s);let i=await s;return this.entries.set(e,{keys:i,at:this.now()}),i}async keyFor(e,n){let r=await this.keys(e,!1),o=n===""?void 0:r.find(s=>s.kid===n&&Yu(s));return o===void 0&&(r=await this.keys(e,!0),o=n===""?void 0:r.find(s=>s.kid===n&&Yu(s))),o}};function Qu(t,e,n){try{let r=(0,ao.createPublicKey)({key:n,format:"jwk"});return(0,ao.verify)("RSA-SHA256",t,r,e)}catch{return!1}}var so=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new oo(e.fetchImpl??fetch,e.now??Date.now,n=>new ft("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new ae("malformed machine token");let s,i;try{s=Zn(n),i=Zn(r)}catch{throw new ae("malformed machine token")}if(s.alg!=="RS256")throw new ae(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new ae(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(i.aud!==zu)throw new ae(`machine token audience must be ${zu} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==wh)throw new ae(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new ae("machine token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new ae("machine token is expired \u2014 re-mint and retry");let c=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,a);if(c===void 0)throw new ae(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Qu(f,h,c))throw new ae("machine token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new ae("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:u,credential:"machine"}}},Rh="https://api.workos.com/sso/jwks/";function Eh(t){return`${Rh}${t.slice(t.lastIndexOf("/")+1)}`}var qs=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new oo(e.fetchImpl??fetch,this.now,n=>new ft("the WorkOS issuer could not be reached to verify this user token \u2014 retry shortly",n),"WorkOS issuer's JWKS")}opts;cache;now;accepts(e){if(!Xu(e))return!1;try{let n=Zn(e.split(".")[1]??"").iss;return typeof n=="string"&&this.opts.issuers.includes(n)}catch{return!1}}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new ae("malformed user token");let s,i;try{s=Zn(n),i=Zn(r)}catch{throw new ae("malformed user token")}if(s.alg!=="RS256")throw new ae(`user token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new ae(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new ae("user token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new ae("user token is expired \u2014 re-authenticate and retry");let c=await this.cache.keyFor(Eh(l),a);if(c===void 0)throw new ae(`user token kid ${JSON.stringify(a)} is not in the WorkOS issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Qu(f,h,c))throw new ae("user token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new ae("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:u,credential:"user"}}},io=class{verifier;bindings;constructor(e){this.verifier=new qs({issuers:e.issuers,...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.now!==void 0?{now:e.now}:{}}),this.bindings=new tr({gatewayUrl:e.gatewayUrl,credential:"user",...e.now!==void 0?{now:e.now}:{},...e.mint!==void 0?{mint:e.mint}:{}})}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e),r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new ae("the control plane bound this user token to a different org than its org_id claim \u2014 refusing to route a request whose two sources of tenancy disagree");return{apiKey:n.apiKey,orgId:n.orgId,credential:"user",...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}}}};function Gs(t,e,n,r){if(Xu(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}O();var nr=require("crypto");O();var xe=require("@urun-sh/core");O();async function Zu(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()}O();var ed=require("@urun-sh/core"),Ws=2;function xh(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Ah(t){let e=t?.type;return e==="response.completed"||e==="error"}function td(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Ws;i++){let{app:a,entry:l,identity:u}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(l)??null,identity:u});let d=!1,c=!1;try{let f=await t.createStream(l,n);for await(let h of f){if(Ah(h)&&(d=!0),xh(h)){if(i>1)continue}else c=!0;yield h}}catch(f){if(f instanceof ed.SessionFailedError&&(f.kind==="never-live"||f.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,l,f)}catch{}throw f}if(i<Ws&&!c){await t.evict(a,l);continue}throw f}if(d)return;if(i<Ws&&!c){await t.evict(a,l);continue}return}})()}}var Ks=require("crypto");O();var Js=require("@urun-sh/core"),Ih="audio";function nd(t){let e=t.streamEndpoint(Ih);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,Js.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,Js.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}O();var rd=require("@urun-sh/core"),Oh="rt-video-in";function od(t){let e=t.streamEndpoint(Oh);return{sendInputFrame:async n=>{e.send((0,rd.encodeStreamEnvelope)(n))}}}var Ph=0,Ch=4,Lh=4;function id(t,e){let n=(i,a)=>{let l=(t[i]??"").trim();if(!l)return a;let u=Number.parseInt(l,10);if(!Number.isInteger(u)||u<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return u},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Ph;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,Ch));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Lh),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function Vs(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 ad(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,l=t.sessionStartOptions?.(n),u={...e.sharedApp?{sharedApp:!0}:{},...l,...r,presenceIdleMs:3e4},d=w=>({session:w,responses:new Ht(w),gone:to(w,n)});if(i.lane==="jwt"){let w=(0,xe.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(Vs(w,e.appSlug,a,u))}if(i.lane==="machine"||i.lane==="user"){let w=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:E}=i,x=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ks.randomUUID)(),b=(0,xe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,xe.createClientToken)(w,{baseUrl:E,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:x,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Vs(b,e.appSlug,a,u))}let{apiKey:c,gatewayUrl:f}=i,h=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ks.randomUUID)(),m=(0,xe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,xe.createClientToken)(c,{baseUrl:f,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:h,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Vs(m,e.appSlug,a,u))}function ld(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 zs(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 Mh=new Set(["error","paused"]);function Ys(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let l=ad(t,i,a);return t.onSessionOpen&&typeof l.session.id=="string"&&l.session.id!==""&&t.onSessionOpen(a,l.session.id),l.gone.onGone(()=>{r?.evict(a,l)}),l},s=new ir({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,callerOrgId:t.orgId,openSession:o,closeSession:async i=>{if(i.gone.dispose(),i.audioDispose?.(),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"?()=>Ni({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>Zu(n):null),listPrices:n?()=>vi(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return mi(i)}:e.lane==="api-key"?()=>hi({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:ld});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},gt({appSlug:t.defaultApp}))),s}function ud(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}
92
- `)},l=(d,c)=>{let f=o.get(c);if(f)return f;let h=new Rr({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,onLease:m=>m.session.activity?.(),openSlot:async m=>{let w=ad(t,d,c,{concurrencyKey:m.concurrencyKey});return w.gone.onGone(E=>E.bindingLost?h.evict(w):h.markSessionDead(w)),await co(w.session),a(`slot attached pool=${c} slot=${m.concurrencyKey} session=${w.session.id??"(no id)"}`),w},closeSlot:async m=>{m.gone.dispose(),m.audioDispose?.(),await m.session.end()},onDetach:(m,w)=>a(`slot detached pool=${c} slot=${m.concurrencyKey} reason=${w}`),terminalOpenFailure:m=>m instanceof xe.SessionFailedError&&zs(m)});return s.set(c,{target:d,env:n}),o.set(c,h),h},u=async(d,c)=>{let f=s.get(c);if(f)try{let h=await e.poolTuningFor(d);l(d,c).retune({min:h?.min??f.env.min,max:h?.max??f.env.max,inFlightCap:h?.in_flight_cap??f.env.inFlightCap,idleGraceMs:h?.idle_grace_s!==void 0?h.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:h?.warm_wait_s!==void 0?h.warm_wait_s*1e3:void 0})}catch(h){a(`pool tuning refresh failed pool=${c} reason=${h instanceof Error?h.message:String(h)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await l(d,gt(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),f=gt(c),h=l(c,f);await u(c,f);let m=await h.acquire({timeoutMs:h.requestWaitMs}),w=i.get(m.entry)??[];return w.push(m),i.set(m.entry,w),{app:f,entry:m.entry,identity:En(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await l(c,gt(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)u(c,d).then(()=>{let f=o.get(d);f&&f.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 $h(t){return(0,xe.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?xe.DEFAULT_WHEN_LIVE_TIMEOUT_MS:xe.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:xe.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function co(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:$h(t.phase),signal:e})}async function Nh(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()}async function sd(t){let e=t.phase?.name;if(e==="live"||e==="paused"){if(typeof t.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");t.detach();return}if(typeof t.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await t.end()}function uo(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Xs(t,e=_a,n,r,o=ns,s){let i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,d=new Map,c=new WeakMap,f=p=>{let g=p.session.id;return typeof g=="string"&&g.length>0?g:null},h="lane",m=p=>{let g=Et(p);if(!s||!g||g.app!==h)return null;let y=s.entryFor(g.key);if(!y)throw new te(`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}},w=async p=>m(p)?.entry??(await t.sessionForHandle(p)).entry,E=p=>{let g=i.get(p);if(!g){let y={waiting:0,gone:new AbortController};c.set(p,y),g=(async()=>{if(await co(p.session,y.gone.signal),y.gone.signal.aborted)throw uo(y.gone.signal);c.get(p)===y&&c.delete(p);let S=await wa(p.session,await e());return Object.assign(S,{sessionId:p.session.id})})(),i.set(p,g),g.then(S=>{i.get(p)===g&&(p.audioDispose=()=>S.dispose())},()=>{}),g.catch(()=>{i.get(p)===g&&i.delete(p)}),g.then(()=>{c.get(p)===y&&c.delete(p)},()=>{c.get(p)===y&&c.delete(p)})}return g},x=p=>{let g=u.get(p);return g||(g=(async()=>{let y=await E(p);return{appendInputAudio:(S,A)=>y.appendInputAudio(S,A),onOutputAudio:S=>y.onOutputAudio(S),sessionId:f(p)}})(),u.set(p,g),g.catch(()=>{u.get(p)===g&&u.delete(p)})),g},b=async(p,g,y,S=!1)=>{let A=()=>S?sd(p.session):Nh(p.session);if(y?.aborted){let T=c.get(p);throw(i.get(p)===void 0||T!==void 0&&T.waiting===0)&&await A().catch(()=>{}),uo(y)}let P=g(p),R=c.get(p);return R!==void 0&&R.waiting++,y===void 0?P:new Promise((T,_)=>{let C=()=>{R!==void 0&&--R.waiting===0&&c.get(p)===R&&(R.gone.abort(),c.delete(p),i.delete(p),u.delete(p),A().catch(()=>{})),_(uo(y))};y.addEventListener("abort",C,{once:!0});let $=()=>y.removeEventListener("abort",C);P.then(N=>{$(),T(N)},N=>{$(),_(N)})})},v=async(p,g,y)=>{try{return await y}catch(S){throw(S instanceof te||S instanceof xe.SessionFailedError&&zs(S))&&(t.evict(p,g),S instanceof xe.SessionFailedError&&n?.(p,S.kind==="never-live"?"never-live":"create-failed")),S}};return{createResponse:td({sessionFor:s?async p=>{let g=await t.resolveTargetFor(p);if(g.sharedApp)try{let y=await s.sessionFor(p,g);return{app:y.app,entry:y.entry,identity:y.identity}}catch(y){if(y instanceof Nt)return r?r.sessionFor(p):t.sessionFor(p);if(y instanceof Ze)return console.error(`[pooler-fallback] pooler channel failed for ${p} (${y.name} ${y.code}: ${y.message}) \u2014 serving via the per-request path`),r?r.sessionFor(p):t.sessionFor(p);throw y}return r?r.sessionFor(p):t.sessionFor(p)}:r?p=>r.sessionFor(p):p=>t.sessionFor(p),sessionIdOf:p=>f(p),evict:(p,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(p,g)},onAdmissionVerdict:(p,g,y)=>{zs(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(p,g),n?.(p,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(p,g)=>{try{await co(p.session);let y=Ya(Ds(await p.responses.responses.create(g),p.gone),o);if(!r&&!s)return y;let S=p;return(async function*(){try{yield*y}catch(P){throw Xa(P)&&(s&&s.owns(S)?s.evict(S):r&&(P instanceof te&&!P.bindingLost?r.markSessionDead(S):r.evict(S))),P}finally{s&&s.owns(S)?s.release(S):r?.end(S)}})()}catch(y){throw s&&s.owns(p)?s.release(p):r&&r.end(p),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(p,g)=>t.supportsImages(p,g),listImageModels:()=>t.imageModelList(),catalogIdentity:p=>t.catalogIdentityFor(p),servingAppSlug:async p=>await t.servingAppSlugFor(p),supportsAudio:p=>t.supportsAudio(p),supportsSpeech:p=>t.supportsSpeech(p),speechVoices:p=>t.speechVoices(p),supportsTranscription:p=>t.supportsTranscription(p),transcriptStreamFor:p=>t.transcriptStreamFor(p),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(p,g)=>{let{app:y,entry:S}=await t.sessionFor(p);return await v(y,S,b(S,E,g))},openAudioOn:async(p,g,y,S)=>{let A=m(p);if(A){let _=A.entry.session;return nd(_)}let{app:P,entry:R}=await t.sessionForHandle(p);if(S&&R.session.phase?.name!=="live"){let _=R.session.phase?.name;S({status:_==="queued"||_==="waiting_for_capacity"?_:"pending",reason:`the dial's session is ${_??"not yet admitted"} \u2014 the connection waits for admission`})}let T=Et(p)?.app.startsWith(yt)??!1;return await v(P,R,b(R,x,g,T))},openTurnsOn:async function*(p,g){if(g?.aborted)throw uo(g);let y=await w(p);yield*Ci(y.session,g)},openVideoOn:async p=>{let g=m(p);if(g)return od(g.entry.session);let{entry:y}=await t.sessionForHandle(p),S=a.get(y);return S||(S=Jo(y.session),a.set(y,S)),S},openVideo:async p=>{let{entry:g}=await t.sessionFor(p),y=a.get(g);return y||(y=Jo(g.session),a.set(g,y)),y},openVideoOut:async p=>{let{entry:g}=await t.sessionFor(p),y=l.get(g);return y||(y=ba(g.session),l.set(g,y)),y},sessionHandle:async p=>{if(s){let g=await t.resolveTargetFor(p);if(g.sharedApp){let y=await s.sessionFor(p,g),S=f(y.entry);if(S===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return xn(h,S)}}return(await t.handleFor(p)).handle},dedicatedSessionHandle:async p=>{if(!(await t.resolveTargetFor(p)).sharedApp)return(await t.handleFor(p)).handle;let{app:y,entry:S}=await t.dedicatedSessionFor(p);return xn(y,ld(S))},touchSessionPresence:(p,g)=>{(async()=>{let y=d.get(p);y||(y=new Map,d.set(p,y)),y.set(g,Date.now());let S=null;try{S=await w(p)}catch{return}S.session.activity?.()})()},detachSessionPresence:(p,g)=>{(async()=>{let y=d.get(p);if(y?.delete(g),y&&y.size===0&&d.delete(p),y&&y.size>0)return;let S=null;try{S=await w(p)}catch{return}S.session.presenceDetach?.()})()},releaseSessionHandle:p=>{let g=Et(p);if(!g)return;if(g.app.startsWith(yt)){(async()=>{let S=null;try{S=(await t.sessionForHandle(p)).entry}catch{return}await sd(S.session).catch(()=>{}),await t.evict(g.app,S)})();return}if(!s||g.app!==h)return;let y=s.entryFor(g.key);y&&s.release(y)},endDedicatedSession:async p=>{let g=Et(p);if(!g||!g.app.startsWith(yt))return;let y=null;try{y=(await t.sessionForHandle(p)).entry}catch{return}if(typeof y.session.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the app-close verb requires the @urun-sh/core Session terminal surface");let S=await y.session.end();return await t.evict(g.app,y),S},speechSessionHandle:async p=>(await t.speechHandleFor(p)).handle,evictSpeechSession:async p=>{let{app:g,entry:y}=await t.sessionForHandle(p);await t.evict(g,y)},createResponseOn:async(p,g,y)=>{let S=await w(p);await co(S.session);let A=y!==void 0&&m(p)?new Ht({...S.session,consumerId:y},{sessionTag:y}):S.responses;return Ds(await A.responses.create(g),S.gone)},onSessionEnd:async(p,g)=>{let y=m(p);if(y)return y.entry.gone.onGone(R=>g({timeLeftMs:null,reason:R.message}));let{entry:S}=await t.sessionForHandle(p),A=S.session;if(typeof A.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let P=!1;return A.onPhase(R=>{if(P||!Mh.has(R.name))return;P=!0;let T=A.endsAt??null;g({timeLeftMs:T?Math.max(0,T.getTime()-Date.now()):null,reason:R.reason??`session ${R.name}`})})}}}var Uh=512;function po(t){return`urun-inference-proxy-${(0,nr.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var fo=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,l)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await o.createResponse(a,l);let u=`px_${(0,nr.randomUUID)()}`;return gu(s,a,u,u)}})}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:qo,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:e.credential==="user"?{lane:"user",userToken: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:id(process.env,process.env.HOSTNAME)??void 0},r=Ys(n),o=n.decisionPool?ud(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(Xs(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>=Uh;){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("; ")}`)}},dd=512,Dh=1024,Qs=class extends Error{constructor(){super(`conversation capacity reached (${dd} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Fh(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(Vt))return{concurrencyKey:e};if(n.startsWith(Vt)||n.startsWith(yt))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(Vt)||n.startsWith(yt)||t.set(n,r)}}}function Bh(t,e,n,r,o){let s=Ys({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:qo,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:e.credential==="user"?{lane:"user",userToken: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",...Fh(r,o)});return{clients:Xs(s,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await s.closeAll()}}}var mo=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let o={id:n,subject:r!==void 0?`${po(e.apiKey)}:live`:`${po(e.apiKey)}:live:${n}`},s=new Map,i=this.opts.build?this.opts.build(e,o):Bh(this.opts,e,o,s,r);return{id:n,backhaul:i,attachments:0,nativeRefs:s}}attachEntry(e,n,r){let o=this.byCaller.get(e.apiKey);o===void 0&&(o=new Map,this.byCaller.set(e.apiKey,o));let s=o.get(n);if(s!==void 0)return o.delete(n),o.set(n,s),s.attachments+=1,s;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,o.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=dd;){let e=!1;for(let[n,r]of this.byCaller){for(let[o,s]of r)if(!(s.attachments>0)){r.delete(o),this.dropHandleIndexFor(n,o),s.backhaul.release().catch(()=>{}),e=!0;break}if(r.size===0&&this.byCaller.delete(n),e)break}if(!e)throw new Qs}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,o=!1,s=()=>(r===null&&(r=this.attachEntry(e,(0,nr.randomUUID)(),n)),r),i={createResponse:(a,l)=>s().backhaul.clients.createResponse(a,l),catalogIdentity:a=>s().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let l=s().backhaul.clients.servingAppSlug;if(l===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 l(a)},listModels:()=>s().backhaul.clients.listModels(),sessionHandle:a=>s().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let l=s().backhaul.clients.dedicatedSessionHandle;return l===void 0?s().backhaul.clients.sessionHandle(a):l(a)},releaseSessionHandle:a=>s().backhaul.clients.releaseSessionHandle?.(a),endDedicatedSession:a=>s().backhaul.clients.endDedicatedSession?.(a),touchSessionPresence:(a,l)=>s().backhaul.clients.touchSessionPresence?.(a,l),detachSessionPresence:(a,l)=>s().backhaul.clients.detachSessionPresence?.(a,l),createResponseOn:(a,l,u)=>s().backhaul.clients.createResponseOn(a,l,u),onSessionEnd:(a,l)=>s().backhaul.clients.onSessionEnd(a,l)};return i.openAudio=async(a,l)=>{let u=s().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(a,l)},i.openVideo=async a=>{let l=s().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(a)},i.openVideoOut=async a=>{let l=s().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(a)},i.supportsAudio=async a=>{let l=s().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(a)},i.supportsSpeech=async a=>{let l=s().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(a)},i.speechVoices=async a=>{let l=s().backhaul.clients.speechVoices;if(l===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 l(a)},i.speechSessionHandle=async a=>{let l=s().backhaul.clients.speechSessionHandle;if(l===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 l(a)},i.openAudioOn=async(a,l,u)=>{let d=s().backhaul.clients.openAudioOn;if(d===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 d(a,l,u)},i.openVideoOn=async(a,l)=>{let u=s().backhaul.clients.openVideoOn;if(u===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return u(a,l)},i.openTurnsOn=(a,l)=>{let u=s().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(a,l)},i.evictSpeechSession=async a=>{let l=s().backhaul.clients.evictSpeechSession;if(l===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 l(a)},i.supportsTranscription=async a=>{let l=s().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(a)},i.transcriptStreamFor=async a=>{let l=s().backhaul.clients.transcriptStreamFor;if(l===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 l(a)},i.listSpeechToTextModels=async()=>{let a=s().backhaul.clients.listSpeechToTextModels;if(a===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 a()},{clients:i,bindResumeHandle:a=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Dh;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async a=>{let l=this.byHandle.get(a),u=l===void 0?void 0:this.byCaller.get(l.apiKey),d=l===void 0||u===void 0?void 0:u.get(l.conversationId);if(l===void 0||d===void 0||l.apiKey!==e.apiKey)throw new te("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 r=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(o)return;o=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.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("; ")}`)}};O();var ho="/inference-usage",cd=25e3;var Hh=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function pd(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Hh.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 go=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${ho}`,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(cd)})}catch(i){throw new we(`the uRun usage surface (POST ${ho}) could not be reached within ${cd}ms: ${pd(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new ae("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new we(`the uRun usage surface (POST ${ho}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new we(`the uRun usage surface (POST ${ho}) answered HTTP ${o.status} with a body that is not JSON: ${pd(i)}`)}return la(s,this.opts.onRejectedRow)}};O();var jh="/inference-ledger",qh=1e4,yo=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},ti=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},Te=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},ni=class extends ae{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ri=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Gh=[["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",Zs],["output_minutes",Zs],["cost_nano_usd",Zs],["price_version",t=>t===null||typeof t=="string"]];function Wh(t){for(let[e,n]of Gh){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Jh(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"}:Wh(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Zs(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function ei(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Vh(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function fd(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 Kh(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&&fd(t.started_at,n.started_at)&&fd(t.completed_at,n.completed_at)&&ei(t.prompt_tokens,n.prompt_tokens)&&ei(t.completion_tokens,n.completion_tokens)&&ei(t.output_units,n.output_units)&&Vh(t.output_minutes,n.output_minutes)}function zh(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(`
93
- `)}async function Yh(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(zh(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Xh(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Te(`${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 Te(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new Te(`${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 Te(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=u=>{if(!(u in n))throw new Te(`${e} answered a row with no ${u} field: ${JSON.stringify(t)}`);let d=n[u];if(d===null)return null;if(typeof d!="string")throw new Te(`${e} answered a non-string ${u}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new Te(`${e} answered a BLANK ${u} (${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"),l=o!=null;if(l&&(i===null||a!==null))throw new Te(`${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(!l&&(i!==null||a===null))throw new Te(`${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 wo=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${jh}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Yh(n,this.opts.signing)}):JSON.stringify(n)}catch(u){throw new Te(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${u instanceof Error?u.message:String(u)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(qh)})}catch(u){throw new Te(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(s.status===409){let u=await s.text().catch(()=>""),d=Jh(u);throw d.status==="found"&&Kh(n,d.row)?new ti(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 yo(`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 yo(`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). ${u.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new ni("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 u=await s.text().catch(c=>`<body unreadable: ${c instanceof Error?c.message:String(c)}>`),d;try{let c=JSON.parse(u);if(c!==null&&typeof c=="object"&&"error"in c){let f=c.error;f!==null&&typeof f=="object"&&"code"in f&&(d=f.code)}}catch{}throw d==="ledger_signature_invalid"?new ri(`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: `+u.slice(0,400)):new Te(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${u.slice(0,400)}`)}let i;try{i=await s.json()}catch(u){throw new Te(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let a=i?.recorded;if(a===void 0)throw new Te(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=Xh(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new Te(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};var Qh=5e3,Zh=1e3,eg=1500,tg=3e3,ng="/api/client-tokens";function _o(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function md(t,e,n,r){_o(t,e,{error:{message:n,type:r}})}async function rg(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${ng}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(tg)});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 wd(t){let e=t.resolver??new tr({gatewayUrl:t.baseUrl}),n=t.machine?new so({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=t.userIssuers?new io({issuers:t.userIssuers,gatewayUrl:t.baseUrl}):null,o=new gr(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),s=null,i=null,a=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let _=new yd.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),C=Ku({redis:_});return{registry:Uu({selfAddress:t.lane.selfAddress,seatRegion:t.pooler.region,tokenSecret:t.lane.tokenSecret,plane:bu({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(N,D)=>s?.onHostedChange(N,D)??(()=>()=>{}),roomDoc:(N,D)=>{if(!s)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return s.roomDoc(N,D)},metrics:o,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(N,D)=>C.rows().then(q=>{let X=$o(q,D);return X?.warm_wait_s!==void 0?X.warm_wait_s*1e3:void 0}),currentReleaseOf:Du(_),closeLane:N=>s?.closeLane(N)}),catalog:C,redis:_}})(),l=t.registry??new fo({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry,pooler:t.pooler}),u=t.probeControlPlane??(()=>rg(t.baseUrl)),d=async()=>{let _=null;for(let N of l.decisionPools()){_=N;break}if(!_)return null;let C=_.stats();if(C.some(N=>N.draining))return{ok:!1,detail:"decision pool draining"};if(C.every(N=>N.attached===0&&N.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let $=await _.pingReady(eg);return{ok:$,detail:$?"a decision slot answered its session ping":"no decision slot answered its session ping"}},c=t.usageClient??new go({apiUrl:t.apiUrl}),f=t.ledgerClient??new wo({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),h=process.env.URUN_SHARED_ORG_ID?.trim(),m=process.env.URUN_SHARED_ORG_API_KEY?.trim();h&&m&&(async()=>{try{await l.decisionWarmerFor({orgId:h,apiKey:m})?.warmFor(Kr)}catch(_){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(_ instanceof Error?_.message:_)}
94
- `)}})();let w=async _=>Gs(lo(_.headers.authorization),e,n,r),E=async _=>{let C=await w(_);if(C.billingAudience==="platform"&&C.creditsAdmissionOk===!1){let $=C.creditsRefusalReason;throw new wn($==="spend_cap_reached"||$==="insufficient_credits"?$:void 0)}return C},x=_=>_ instanceof ae?{status:_.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:_ instanceof wn?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",..._.code!==void 0?{code:_.code}:{}}:_ instanceof ft?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:_.detail}:null,b={write:(_,C)=>f.write(lo(_.headers.authorization),C),observe:_=>o.observeLedger(_),...t.ledgerLog?{report:t.ledgerLog}:{}},v=ru({clients:async _=>l.clientsFor(await E(_)),usage:{authorize:_=>lo(_.headers.authorization),lookup:(_,C)=>c.lookup(_,C)},statusOf:x,...t.requestLog?{requestLog:t.requestLog}:{},observe:_=>o.observe(_),ledger:b}),p=fl({authorize:async _=>{await E(_)},...t.lane?{secret:t.lane.tokenSecret}:{}}),g=null,y=null,S=(0,hd.createServer)((_,C)=>{let $=new URL(_.url??"/","http://localhost");(async()=>{if(_.method==="GET"&&$.pathname==="/healthz"){_o(C,200,{ok:!0});return}if(_.method==="GET"&&$.pathname==="/readyz"){let q=Date.now();if((!g||q-g.at>=Qh)&&(g={at:q,...await u()}),!y||q-y.at>=Zh){let re=await d();y=re===null?{at:q,ok:!0,detail:null}:{at:q,ok:re.ok,detail:re.detail}}let X=(g?.ready??!1)&&y.ok,G=y.detail===null?g?.detail??"control plane not yet probed":`${g?.detail??"control plane not yet probed"}; ${y.detail}`;_o(C,X?200:503,{ok:X,control_plane:G});return}if(_.method==="GET"&&$.pathname==="/lanez"){_o(C,200,{pools:a?await a.registry.status():null});return}let N=$.pathname==="/v1"||$.pathname.startsWith("/v1/"),D=$.pathname.startsWith("/partners/");if(!N&&!D){md(C,404,`no route for ${_.method} ${$.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}await p(_,C)||v(_,C)})().catch(N=>{if(!C.headersSent){md(C,500,String(N instanceof Error?N.message:N),"proxy_error");return}C.end()})}),A=t.conversations??new mo({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry}),P=new WeakMap,R=[Yo(S,{authenticate:async _=>{let C=await Gs(_,e,n,r),$=A.connectionFor(C);return{clients:$.clients,scope:po(C.apiKey),onBindResumeHandle:$.bindResumeHandle,clientsForResume:$.clientsForResume,release:$.release}}}),as(S,{clients:async _=>l.clientsFor(await E(_)),statusOf:x}).close,Mr(S,{resolver:{resolve:async(_,C,$)=>{let N=await E(_),D=A.connectionFor(N,lu(_)),q;try{q=await uu(Ps(D.clients,t.realtimeCompanions),iu(_),C,au(_),$)}catch(re){throw D.release().catch(()=>{}),re}let X=q.release,G={...q,release:async()=>{await X?.(),await D.release()}};return P.set(G,N.orgId),G}},onSessionEnded:_=>{ur({record:{event:"inference_request",ts:new Date().toISOString(),inference_id:Pt(),method:"GET",path:"/v1/realtime",status:200,delivered:!0,stream_error:!1,model:_.binding.model??null,stream:null,org:P.get(_.binding)??null,duration_ms:_.connected_ms,ttft_ms:null,prompt_tokens:null,completion_tokens:null,output_units:null,output_minutes:null,output_seconds:null,session_seconds:_.connected_ms/1e3,session_id:_.binding.audioSession?.audio.sessionId??null,queue_ms:null,prefill_ms:null,decode_ms:null,total_ms:null,catalog:_.binding.catalog??{kind:"unresolved",reason:"the realtime binding carries no dial-time catalog identity (no billing-identity oracle wired, or the composite lane)"}},ledger:b,req:_.req})}})];if(t.lane&&a){let _=t.lane,C=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;s=Vu(S,{verifyToken:(N,D)=>Us(N,D,_.tokenSecret,void 0,C),selfAddress:_.selfAddress,laneTenantOf:N=>a.redis.get(`lane_tenant:${N}`),onLaneTenantMissing:()=>o.observeLaneDocTenantMissing(),previousTokenSecret:C,hostRegistry:{setHost:(N,D)=>a.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:${N}`,D,String(Ju)),delHost:N=>a.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${N}`,_.selfAddress)}}),i=Pu(S,{verifyToken:(N,D)=>Us(N,D,_.tokenSecret,void 0,C),selfAddress:_.selfAddress,hostOf:async N=>{let D=await a.redis.get(`lane_hosts:${N}`);return D&&D.trim()!==""?D.trim():null},podToPodDial:(N,D,q)=>new Promise((X,G)=>{(async()=>{let re=await a.redis.get(`lane_tenant:${N}`),K=Xn(N,_.tokenSecret,void 0,void 0,re||void 0),M=`ws://${q}/stream/${encodeURIComponent(N)}/${encodeURIComponent(D)}?token=${encodeURIComponent(K)}`,ee=new gd.default(M,eo(D));ee.once("open",()=>X(ee)),ee.once("error",G)})().catch(G)})});let $=a;R.push(async()=>{await s.close(),await i.close(),await $.registry.close(),$.redis.quit().catch(()=>{})})}S.on("upgrade",(_,C)=>{let $=new URL(_.url??"/","http://localhost");$.pathname===Sr||$.pathname===ss||$.pathname===Hn||s!==null&&$.pathname.startsWith("/doc/")||i!==null&&$.pathname.startsWith("/stream/")||C.destroyed||(C.write(`HTTP/1.1 404 Not Found\r
90
+ ${o}`)}function Yu(t,e){let n=new Ku.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=p=>o.get(`${p}/${Vu}`)??0,a=p=>s.get(p)??0,l=new Map,u=new Map,d=new Set,c=new Set,f=new Map,h=new Map,m=4096,w=!1,E=(p,g,y)=>{let S=i(p)>0,A=a(p),P=A>0,R=`${p}/${g}`,O=o.get(R)??0;y>0?o.set(R,y):o.delete(R);let b=A+y-O;b>0?s.set(p,b):s.delete(p);let C=i(p)>0,$=b>0;if(S!==C){C?x(p):v(p);for(let M of l.get(p)??[])M(C)}P&&!$&&queueMicrotask(()=>{let M=`${p}/`;for(let[U,q]of[...hn.entries()])!U.startsWith(M)||q.conns.size>0||(hn.delete(U),q.destroy())})},x=p=>{if(!e.hostRegistry||u.has(p))return;let g=()=>{e.hostRegistry?.setHost(p,e.selfAddress).catch(()=>{})};g();let y=setInterval(g,gh);y.unref?.(),u.set(p,y)},v=p=>{let g=u.get(p);g&&(clearInterval(g),u.delete(p)),e.hostRegistry&&e.hostRegistry.delHost(p,e.selfAddress).catch(()=>{})},_=(p,g,y)=>{let S;try{S=new URL(p.url??"/","http://localhost")}catch{wn(g,400,"malformed upgrade URL");return}g.on("error",()=>g.destroy()),g.on("close",()=>c.delete(g));let A=yh(S.pathname);if(!A){if(S.pathname.startsWith(Gs)){wn(g,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(g);return}d.add(g);let P=!1;(async()=>{if(h.has(A.laneId)){wn(g,409,"lane retired \u2014 the app's release moved; a fresh lane serves it");return}let R=S.searchParams.get("token")??"",O=null;try{O=R===""?null:await e.verifyToken(R,A.laneId,A.docName)}catch{O=null}if(O===null){wn(g,401,"invalid or missing lane doc token");return}let b=O;if(b.tenant!==void 0&&e.laneTenantOf){let C=null;try{C=await e.laneTenantOf(A.laneId)}catch{C=null}if(C==null||C==="")e.onLaneTenantMissing?.();else if(b.tenant!==C){wn(g,403,"lane doc token org does not match the lane record");return}}w||g.destroyed||(P=!0,n.handleUpgrade(p,g,y,C=>{d.delete(g),r.add(C),C.on("close",()=>r.delete(C));let $=f.get(A.laneId);$||($=new Set,f.set(A.laneId,$)),$.add(C),C.on("close",()=>{$.delete(C),$.size===0&&f.delete(A.laneId)});let M=b.scope===Nu||b.scope===void 0&&typeof b.app=="string"&&typeof b.fn=="string"&&b.aud==="sfu";if(M){let q=`${A.laneId}/${A.docName}`,X=(o.get(q)??0)+1;E(A.laneId,A.docName,X),X>1&&A.docName===Vu&&e.hostRegistry?.setHost(A.laneId,e.selfAddress).catch(()=>{})}C.on("close",()=>{if(!M)return;let q=`${A.laneId}/${A.docName}`;E(A.laneId,A.docName,Math.max(0,(o.get(q)??1)-1))}),Ju(C,p,{docName:`${A.laneId}/${A.docName}`,gc:!0})}))})().catch(()=>{!P&&!g.destroyed&&wn(g,500,"lane doc upgrade failed")}).finally(()=>d.delete(g))};return t.on("upgrade",_),{async close(){w=!0,t.off("upgrade",_);for(let g of[...u.keys()])v(g);await new Promise(g=>{if(r.size===0&&d.size===0){g();return}let y=r.size+d.size,S=()=>{y-=1,y<=0&&g()};for(let A of r)A.once("close",S);for(let A of d)A.once("close",S);for(let A of r)A.close(1001,"lane doc host shutting down");for(let A of d)A.destroy()}),o.clear(),s.clear(),l.clear()},roomDoc(p,g){return qs(`${p}/${g}`,!0)},isHosted(p){return i(p)>0},onHostedChange(p,g){let y=l.get(p);return y||(y=new Set,l.set(p,y)),y.add(g),g(i(p)>0),()=>{y.delete(g)}},closeLane(p){if(h.set(p,!0),h.size>m){let g=h.keys().next().value;g!==void 0&&h.delete(g)}v(p);for(let g of f.get(p)??[])g.close(1001,`lane ${p} retired \u2014 the app's release moved`)}}}var vd=Ee(require("ws"),1);T();var wh="urun:catalog:v1";function Xu(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,s=null,i=async()=>{let l=await t.redis.hgetall(wh),u=[];for(let d of Object.values(l))try{u.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
91
+ `)}return r=u,o=n(),u},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 bd=Ee(require("ioredis"),1);T();var tr=require("@urun-sh/core"),uo=require("crypto"),Qu="urun-session-gateway",_h="machine",vh=3e5;function td(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var ae=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},_n=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}},ft=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function co(t){let e=(t??"").trim();if(e==="")throw new ae("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new ae("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var bh=60,Sh=6e4,kh=4096;function Rh(t){return t===401||t===403}var nr=class{constructor(e){this.opts=e;this.mint=e.mint??tr.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new ae("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<Sh)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let o,s;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:bh});o=i.orgId,s={...i.billingAudience!==void 0?{billingAudience:i.billingAudience}:{},...i.creditsAdmissionOk!==void 0?{creditsAdmissionOk:i.creditsAdmissionOk}:{},...i.creditsRefusalReason!==void 0?{creditsRefusalReason:i.creditsRefusalReason}:{}}}catch(i){throw i instanceof tr.ClientTokenError&&i.status===402?(this.cache.delete(e),new _n(i.code==="spend_cap_reached"||i.code==="insufficient_credits"?i.code:void 0)):i instanceof tr.ClientTokenError&&Rh(i.status)?(this.cache.delete(e),new ae(n==="user"?"the WorkOS user token was rejected by the control plane \u2014 check that the user belongs to an org with inference access":"the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new ft(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${i instanceof Error?i.message:String(i)}`)}if(!o)throw new ft(`the control plane verified the ${n==="user"?"user token":"API key"} but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)`);if(this.cache.size>=kh){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:o,at:this.now(),...s}),{apiKey:e,orgId:o,credential:n,...s}}clear(){this.cache.clear()}};function er(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function Zu(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var io=class{constructor(e,n,r,o){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=o}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof ft?r:this.unavailable(`the ${this.jwksNoun} at ${e} answered a body that is not JSON`)}}async keys(e,n){let r=this.entries.get(e);if(!n&&r!==void 0&&this.now()-r.at<vh)return r.keys;let o=this.inFlight.get(e);if(o!==void 0)return o;let s=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,s);let i=await s;return this.entries.set(e,{keys:i,at:this.now()}),i}async keyFor(e,n){let r=await this.keys(e,!1),o=n===""?void 0:r.find(s=>s.kid===n&&Zu(s));return o===void 0&&(r=await this.keys(e,!0),o=n===""?void 0:r.find(s=>s.kid===n&&Zu(s))),o}};function nd(t,e,n){try{let r=(0,uo.createPublicKey)({key:n,format:"jwk"});return(0,uo.verify)("RSA-SHA256",t,r,e)}catch{return!1}}var ao=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new io(e.fetchImpl??fetch,e.now??Date.now,n=>new ft("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new ae("malformed machine token");let s,i;try{s=er(n),i=er(r)}catch{throw new ae("malformed machine token")}if(s.alg!=="RS256")throw new ae(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new ae(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(i.aud!==Qu)throw new ae(`machine token audience must be ${Qu} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==_h)throw new ae(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new ae("machine token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new ae("machine token is expired \u2014 re-mint and retry");let c=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,a);if(c===void 0)throw new ae(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!nd(f,h,c))throw new ae("machine token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new ae("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:u,credential:"machine"}}},Eh="https://api.workos.com/sso/jwks/";function xh(t){return`${Eh}${t.slice(t.lastIndexOf("/")+1)}`}var Ws=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new io(e.fetchImpl??fetch,this.now,n=>new ft("the WorkOS issuer could not be reached to verify this user token \u2014 retry shortly",n),"WorkOS issuer's JWKS")}opts;cache;now;accepts(e){if(!td(e))return!1;try{let n=er(e.split(".")[1]??"").iss;return typeof n=="string"&&this.opts.issuers.includes(n)}catch{return!1}}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new ae("malformed user token");let s,i;try{s=er(n),i=er(r)}catch{throw new ae("malformed user token")}if(s.alg!=="RS256")throw new ae(`user token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new ae(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new ae("user token carries no org_id \u2014 no tenancy to route by");let d=typeof i.sub=="string"?i.sub:"",c=typeof i.exp=="number"?i.exp:0;if(c<=Math.floor(this.now()/1e3))throw new ae("user token is expired \u2014 re-authenticate and retry");let f=await this.cache.keyFor(xh(l),a);if(f===void 0)throw new ae(`user token kid ${JSON.stringify(a)} is not in the WorkOS issuer's JWKS`);let h=Buffer.from(`${n}.${r}`,"ascii"),m=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!nd(h,m,f))throw new ae("user token signature failed verification");if(c<=Math.floor(this.now()/1e3))throw new ae("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:u,credential:"user",subject:d}}},Ah=5e3,Ih=1500,Th=4096,Gt=class extends Error{status=403;detail;constructor(e,n){super(e),this.name="MembershipRefusalError",this.detail=n}};function ed(){return new Gt("this account is not an active member of the organization \u2014 the membership may have been removed; sign out and sign back in")}var Js=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now,this.timeoutMs=e.timeoutMs??Ih}opts;cache=new Map;fetchImpl;now;timeoutMs;async assertActive(e,n){if(n==="")throw new Gt("the user token carries no subject \u2014 organization membership cannot be confirmed");let r=`${e}\0${n}`,o=this.cache.get(r);if(o!==void 0&&this.now()-o.at<Ah){if(!o.active)throw ed();return}let s=!1,i;try{let a=await this.fetchImpl(`${this.opts.url}/membership-check`,{method:"POST",headers:{authorization:`Bearer ${this.opts.token}`,"content-type":"application/json"},body:JSON.stringify({org_id:e,subject:n}),signal:AbortSignal.timeout(this.timeoutMs)});if(a.status!==200)i=`membership-check answered HTTP ${a.status}`;else try{let l=await a.json();l===null||typeof l!="object"||Array.isArray(l)||!("active"in l)||typeof l.active!="boolean"?i="membership-check answered a malformed body (expected {active: boolean})":s=l.active}catch(l){i=`membership-check answered a body that is not JSON (${l instanceof Error?l.message:String(l)})`}}catch(a){i=`membership-check failed (${a instanceof Error?a.message:String(a)})`}if(i!==void 0)throw new Gt("organization membership for this account could not be confirmed \u2014 try again shortly",i);if(this.cache.size>=Th){let a=this.cache.keys().next();a.done||this.cache.delete(a.value)}if(this.cache.set(r,{active:s,at:this.now()}),!s)throw ed()}},lo=class{verifier;bindings;memberGate;warnedGateDisabled=!1;constructor(e){this.verifier=new Ws({issuers:e.issuers,...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.now!==void 0?{now:e.now}:{}}),this.bindings=new nr({gatewayUrl:e.gatewayUrl,credential:"user",...e.now!==void 0?{now:e.now}:{},...e.mint!==void 0?{mint:e.mint}:{}}),this.memberGate=e.memberGate!==void 0?new Js(e.memberGate):null}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e);this.memberGate!==null?await this.memberGate.assertActive(n.orgId,n.subject):this.warnedGateDisabled||(this.warnedGateDisabled=!0,process.stderr.write(`[member-gate] member gate disabled \u2014 removed-member window remains open
92
+ `));let r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new ae("the control plane bound this user token to a different org than its org_id claim \u2014 refusing to route a request whose two sources of tenancy disagree");return{apiKey:n.apiKey,orgId:n.orgId,credential:"user",...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}}}};function Vs(t,e,n,r){if(td(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}T();var rr=require("crypto");T();var xe=require("@urun-sh/core");T();async function rd(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()}T();var od=require("@urun-sh/core"),Ks=2;function Oh(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Ph(t){let e=t?.type;return e==="response.completed"||e==="error"}function sd(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Ks;i++){let{app:a,entry:l,identity:u}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(l)??null,identity:u});let d=!1,c=!1;try{let f=await t.createStream(l,n);for await(let h of f){if(Ph(h)&&(d=!0),Oh(h)){if(i>1)continue}else c=!0;yield h}}catch(f){if(f instanceof od.SessionFailedError&&(f.kind==="never-live"||f.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,l,f)}catch{}throw f}if(i<Ks&&!c){await t.evict(a,l);continue}throw f}if(d)return;if(i<Ks&&!c){await t.evict(a,l);continue}return}})()}}var Xs=require("crypto");T();var zs=require("@urun-sh/core"),Ch="audio";function id(t){let e=t.streamEndpoint(Ch);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,zs.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,zs.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}T();var ad=require("@urun-sh/core"),Lh="rt-video-in";function ld(t){let e=t.streamEndpoint(Lh);return{sendInputFrame:async n=>{e.send((0,ad.encodeStreamEnvelope)(n))}}}var $h=0,Nh=4,Uh=4;function dd(t,e){let n=(i,a)=>{let l=(t[i]??"").trim();if(!l)return a;let u=Number.parseInt(l,10);if(!Number.isInteger(u)||u<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return u},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):$h;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,Nh));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Uh),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function Ys(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 cd(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,l=t.sessionStartOptions?.(n),u={...e.sharedApp?{sharedApp:!0}:{},...l,...r,presenceIdleMs:3e4},d=w=>({session:w,responses:new Ht(w),gone:ro(w,n)});if(i.lane==="jwt"){let w=(0,xe.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(Ys(w,e.appSlug,a,u))}if(i.lane==="machine"||i.lane==="user"){let w=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:E}=i,x=(typeof t.subject=="function"?t.subject():t.subject)??(0,Xs.randomUUID)(),v=(0,xe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,xe.createClientToken)(w,{baseUrl:E,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:x,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Ys(v,e.appSlug,a,u))}let{apiKey:c,gatewayUrl:f}=i,h=(typeof t.subject=="function"?t.subject():t.subject)??(0,Xs.randomUUID)(),m=(0,xe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,xe.createClientToken)(c,{baseUrl:f,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:h,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Ys(m,e.appSlug,a,u))}function pd(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 Qs(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 Dh=new Set(["error","paused"]);function Zs(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let l=cd(t,i,a);return t.onSessionOpen&&typeof l.session.id=="string"&&l.session.id!==""&&t.onSessionOpen(a,l.session.id),l.gone.onGone(()=>{r?.evict(a,l)}),l},s=new ar({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,callerOrgId:t.orgId,openSession:o,closeSession:async i=>{if(i.gone.dispose(),i.audioDispose?.(),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"?()=>Fi({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>rd(n):null),listPrices:n?()=>ki(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return yi(i)}:e.lane==="api-key"?()=>wi({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:pd});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},gt({appSlug:t.defaultApp}))),s}function fd(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}
93
+ `)},l=(d,c)=>{let f=o.get(c);if(f)return f;let h=new xr({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,onLease:m=>m.session.activity?.(),openSlot:async m=>{let w=cd(t,d,c,{concurrencyKey:m.concurrencyKey});return w.gone.onGone(E=>E.bindingLost?h.evict(w):h.markSessionDead(w)),await fo(w.session),a(`slot attached pool=${c} slot=${m.concurrencyKey} session=${w.session.id??"(no id)"}`),w},closeSlot:async m=>{m.gone.dispose(),m.audioDispose?.(),await m.session.end()},onDetach:(m,w)=>a(`slot detached pool=${c} slot=${m.concurrencyKey} reason=${w}`),terminalOpenFailure:m=>m instanceof xe.SessionFailedError&&Qs(m)});return s.set(c,{target:d,env:n}),o.set(c,h),h},u=async(d,c)=>{let f=s.get(c);if(f)try{let h=await e.poolTuningFor(d);l(d,c).retune({min:h?.min??f.env.min,max:h?.max??f.env.max,inFlightCap:h?.in_flight_cap??f.env.inFlightCap,idleGraceMs:h?.idle_grace_s!==void 0?h.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:h?.warm_wait_s!==void 0?h.warm_wait_s*1e3:void 0})}catch(h){a(`pool tuning refresh failed pool=${c} reason=${h instanceof Error?h.message:String(h)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await l(d,gt(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),f=gt(c),h=l(c,f);await u(c,f);let m=await h.acquire({timeoutMs:h.requestWaitMs}),w=i.get(m.entry)??[];return w.push(m),i.set(m.entry,w),{app:f,entry:m.entry,identity:xn(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await l(c,gt(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)u(c,d).then(()=>{let f=o.get(d);f&&f.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 Fh(t){return(0,xe.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?xe.DEFAULT_WHEN_LIVE_TIMEOUT_MS:xe.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:xe.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function fo(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:Fh(t.phase),signal:e})}async function Bh(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()}async function ud(t){let e=t.phase?.name;if(e==="live"||e==="paused"){if(typeof t.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");t.detach();return}if(typeof t.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await t.end()}function po(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function ei(t,e=Sa,n,r,o=os,s){let i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,d=new Map,c=new WeakMap,f=p=>{let g=p.session.id;return typeof g=="string"&&g.length>0?g:null},h="lane",m=p=>{let g=Et(p);if(!s||!g||g.app!==h)return null;let y=s.entryFor(g.key);if(!y)throw new te(`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}},w=async p=>m(p)?.entry??(await t.sessionForHandle(p)).entry,E=p=>{let g=i.get(p);if(!g){let y={waiting:0,gone:new AbortController};c.set(p,y),g=(async()=>{if(await fo(p.session,y.gone.signal),y.gone.signal.aborted)throw po(y.gone.signal);c.get(p)===y&&c.delete(p);let S=await ba(p.session,await e());return Object.assign(S,{sessionId:p.session.id})})(),i.set(p,g),g.then(S=>{i.get(p)===g&&(p.audioDispose=()=>S.dispose())},()=>{}),g.catch(()=>{i.get(p)===g&&i.delete(p)}),g.then(()=>{c.get(p)===y&&c.delete(p)},()=>{c.get(p)===y&&c.delete(p)})}return g},x=p=>{let g=u.get(p);return g||(g=(async()=>{let y=await E(p);return{appendInputAudio:(S,A)=>y.appendInputAudio(S,A),onOutputAudio:S=>y.onOutputAudio(S),sessionId:f(p)}})(),u.set(p,g),g.catch(()=>{u.get(p)===g&&u.delete(p)})),g},v=async(p,g,y,S=!1)=>{let A=()=>S?ud(p.session):Bh(p.session);if(y?.aborted){let O=c.get(p);throw(i.get(p)===void 0||O!==void 0&&O.waiting===0)&&await A().catch(()=>{}),po(y)}let P=g(p),R=c.get(p);return R!==void 0&&R.waiting++,y===void 0?P:new Promise((O,b)=>{let C=()=>{R!==void 0&&--R.waiting===0&&c.get(p)===R&&(R.gone.abort(),c.delete(p),i.delete(p),u.delete(p),A().catch(()=>{})),b(po(y))};y.addEventListener("abort",C,{once:!0});let $=()=>y.removeEventListener("abort",C);P.then(M=>{$(),O(M)},M=>{$(),b(M)})})},_=async(p,g,y)=>{try{return await y}catch(S){throw(S instanceof te||S instanceof xe.SessionFailedError&&Qs(S))&&(t.evict(p,g),S instanceof xe.SessionFailedError&&n?.(p,S.kind==="never-live"?"never-live":"create-failed")),S}};return{createResponse:sd({sessionFor:s?async p=>{let g=await t.resolveTargetFor(p);if(g.sharedApp)try{let y=await s.sessionFor(p,g);return{app:y.app,entry:y.entry,identity:y.identity}}catch(y){if(y instanceof Nt)return r?r.sessionFor(p):t.sessionFor(p);if(y instanceof Ze)return console.error(`[pooler-fallback] pooler channel failed for ${p} (${y.name} ${y.code}: ${y.message}) \u2014 serving via the per-request path`),r?r.sessionFor(p):t.sessionFor(p);throw y}return r?r.sessionFor(p):t.sessionFor(p)}:r?p=>r.sessionFor(p):p=>t.sessionFor(p),sessionIdOf:p=>f(p),evict:(p,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(p,g)},onAdmissionVerdict:(p,g,y)=>{Qs(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(p,g),n?.(p,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(p,g)=>{try{await fo(p.session);let y=Za(Bs(await p.responses.responses.create(g),p.gone),o);if(!r&&!s)return y;let S=p;return(async function*(){try{yield*y}catch(P){throw el(P)&&(s&&s.owns(S)?s.evict(S):r&&(P instanceof te&&!P.bindingLost?r.markSessionDead(S):r.evict(S))),P}finally{s&&s.owns(S)?s.release(S):r?.end(S)}})()}catch(y){throw s&&s.owns(p)?s.release(p):r&&r.end(p),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(p,g)=>t.supportsImages(p,g),listImageModels:()=>t.imageModelList(),catalogIdentity:p=>t.catalogIdentityFor(p),servingAppSlug:async p=>await t.servingAppSlugFor(p),supportsAudio:p=>t.supportsAudio(p),supportsSpeech:p=>t.supportsSpeech(p),speechVoices:p=>t.speechVoices(p),supportsTranscription:p=>t.supportsTranscription(p),transcriptStreamFor:p=>t.transcriptStreamFor(p),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(p,g)=>{let{app:y,entry:S}=await t.sessionFor(p);return await _(y,S,v(S,E,g))},openAudioOn:async(p,g,y,S)=>{let A=m(p);if(A){let b=A.entry.session;return id(b)}let{app:P,entry:R}=await t.sessionForHandle(p);if(S&&R.session.phase?.name!=="live"){let b=R.session.phase?.name;S({status:b==="queued"||b==="waiting_for_capacity"?b:"pending",reason:`the dial's session is ${b??"not yet admitted"} \u2014 the connection waits for admission`})}let O=Et(p)?.app.startsWith(yt)??!1;return await _(P,R,v(R,x,g,O))},openTurnsOn:async function*(p,g){if(g?.aborted)throw po(g);let y=await w(p);yield*$i(y.session,g)},openVideoOn:async p=>{let g=m(p);if(g)return ld(g.entry.session);let{entry:y}=await t.sessionForHandle(p),S=a.get(y);return S||(S=Ko(y.session),a.set(y,S)),S},openVideo:async p=>{let{entry:g}=await t.sessionFor(p),y=a.get(g);return y||(y=Ko(g.session),a.set(g,y)),y},openVideoOut:async p=>{let{entry:g}=await t.sessionFor(p),y=l.get(g);return y||(y=Ra(g.session),l.set(g,y)),y},sessionHandle:async p=>{if(s){let g=await t.resolveTargetFor(p);if(g.sharedApp){let y=await s.sessionFor(p,g),S=f(y.entry);if(S===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return An(h,S)}}return(await t.handleFor(p)).handle},dedicatedSessionHandle:async p=>{if(!(await t.resolveTargetFor(p)).sharedApp)return(await t.handleFor(p)).handle;let{app:y,entry:S}=await t.dedicatedSessionFor(p);return An(y,pd(S))},touchSessionPresence:(p,g)=>{(async()=>{let y=d.get(p);y||(y=new Map,d.set(p,y)),y.set(g,Date.now());let S=null;try{S=await w(p)}catch{return}S.session.activity?.()})()},detachSessionPresence:(p,g)=>{(async()=>{let y=d.get(p);if(y?.delete(g),y&&y.size===0&&d.delete(p),y&&y.size>0)return;let S=null;try{S=await w(p)}catch{return}S.session.presenceDetach?.()})()},releaseSessionHandle:p=>{let g=Et(p);if(!g)return;if(g.app.startsWith(yt)){(async()=>{let S=null;try{S=(await t.sessionForHandle(p)).entry}catch{return}await ud(S.session).catch(()=>{}),await t.evict(g.app,S)})();return}if(!s||g.app!==h)return;let y=s.entryFor(g.key);y&&s.release(y)},endDedicatedSession:async p=>{let g=Et(p);if(!g||!g.app.startsWith(yt))return;let y=null;try{y=(await t.sessionForHandle(p)).entry}catch{return}if(typeof y.session.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the app-close verb requires the @urun-sh/core Session terminal surface");let S=await y.session.end();return await t.evict(g.app,y),S},speechSessionHandle:async p=>(await t.speechHandleFor(p)).handle,evictSpeechSession:async p=>{let{app:g,entry:y}=await t.sessionForHandle(p);await t.evict(g,y)},createResponseOn:async(p,g,y)=>{let S=await w(p);await fo(S.session);let A=y!==void 0&&m(p)?new Ht({...S.session,consumerId:y},{sessionTag:y}):S.responses;return Bs(await A.responses.create(g),S.gone)},onSessionEnd:async(p,g)=>{let y=m(p);if(y)return y.entry.gone.onGone(R=>g({timeLeftMs:null,reason:R.message}));let{entry:S}=await t.sessionForHandle(p),A=S.session;if(typeof A.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let P=!1;return A.onPhase(R=>{if(P||!Dh.has(R.name))return;P=!0;let O=A.endsAt??null;g({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:R.reason??`session ${R.name}`})})}}}var Hh=512;function mo(t){return`urun-inference-proxy-${(0,rr.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var ho=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,l)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await o.createResponse(a,l);let u=`px_${(0,rr.randomUUID)()}`;return _u(s,a,u,u)}})}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:Wo,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:e.credential==="user"?{lane:"user",userToken: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:dd(process.env,process.env.HOSTNAME)??void 0},r=Zs(n),o=n.decisionPool?fd(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(ei(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>=Hh;){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("; ")}`)}},md=512,jh=1024,ti=class extends Error{constructor(){super(`conversation capacity reached (${md} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function qh(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(Kt))return{concurrencyKey:e};if(n.startsWith(Kt)||n.startsWith(yt))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(Kt)||n.startsWith(yt)||t.set(n,r)}}}function Gh(t,e,n,r,o){let s=Zs({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Wo,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:e.credential==="user"?{lane:"user",userToken: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",...qh(r,o)});return{clients:ei(s,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await s.closeAll()}}}var go=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let o={id:n,subject:r!==void 0?`${mo(e.apiKey)}:live`:`${mo(e.apiKey)}:live:${n}`},s=new Map,i=this.opts.build?this.opts.build(e,o):Gh(this.opts,e,o,s,r);return{id:n,backhaul:i,attachments:0,nativeRefs:s}}attachEntry(e,n,r){let o=this.byCaller.get(e.apiKey);o===void 0&&(o=new Map,this.byCaller.set(e.apiKey,o));let s=o.get(n);if(s!==void 0)return o.delete(n),o.set(n,s),s.attachments+=1,s;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,o.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=md;){let e=!1;for(let[n,r]of this.byCaller){for(let[o,s]of r)if(!(s.attachments>0)){r.delete(o),this.dropHandleIndexFor(n,o),s.backhaul.release().catch(()=>{}),e=!0;break}if(r.size===0&&this.byCaller.delete(n),e)break}if(!e)throw new ti}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,o=!1,s=()=>(r===null&&(r=this.attachEntry(e,(0,rr.randomUUID)(),n)),r),i={createResponse:(a,l)=>s().backhaul.clients.createResponse(a,l),catalogIdentity:a=>s().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let l=s().backhaul.clients.servingAppSlug;if(l===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 l(a)},listModels:()=>s().backhaul.clients.listModels(),sessionHandle:a=>s().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let l=s().backhaul.clients.dedicatedSessionHandle;return l===void 0?s().backhaul.clients.sessionHandle(a):l(a)},releaseSessionHandle:a=>s().backhaul.clients.releaseSessionHandle?.(a),endDedicatedSession:a=>s().backhaul.clients.endDedicatedSession?.(a),touchSessionPresence:(a,l)=>s().backhaul.clients.touchSessionPresence?.(a,l),detachSessionPresence:(a,l)=>s().backhaul.clients.detachSessionPresence?.(a,l),createResponseOn:(a,l,u)=>s().backhaul.clients.createResponseOn(a,l,u),onSessionEnd:(a,l)=>s().backhaul.clients.onSessionEnd(a,l)};return i.openAudio=async(a,l)=>{let u=s().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(a,l)},i.openVideo=async a=>{let l=s().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(a)},i.openVideoOut=async a=>{let l=s().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(a)},i.supportsAudio=async a=>{let l=s().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(a)},i.supportsSpeech=async a=>{let l=s().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(a)},i.speechVoices=async a=>{let l=s().backhaul.clients.speechVoices;if(l===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 l(a)},i.speechSessionHandle=async a=>{let l=s().backhaul.clients.speechSessionHandle;if(l===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 l(a)},i.openAudioOn=async(a,l,u)=>{let d=s().backhaul.clients.openAudioOn;if(d===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 d(a,l,u)},i.openVideoOn=async(a,l)=>{let u=s().backhaul.clients.openVideoOn;if(u===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return u(a,l)},i.openTurnsOn=(a,l)=>{let u=s().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(a,l)},i.evictSpeechSession=async a=>{let l=s().backhaul.clients.evictSpeechSession;if(l===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 l(a)},i.supportsTranscription=async a=>{let l=s().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(a)},i.transcriptStreamFor=async a=>{let l=s().backhaul.clients.transcriptStreamFor;if(l===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 l(a)},i.listSpeechToTextModels=async()=>{let a=s().backhaul.clients.listSpeechToTextModels;if(a===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 a()},{clients:i,bindResumeHandle:a=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=jh;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async a=>{let l=this.byHandle.get(a),u=l===void 0?void 0:this.byCaller.get(l.apiKey),d=l===void 0||u===void 0?void 0:u.get(l.conversationId);if(l===void 0||d===void 0||l.apiKey!==e.apiKey)throw new te("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 r=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(o)return;o=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.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("; ")}`)}};T();var yo="/inference-usage",hd=25e3;var Wh=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function gd(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Wh.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 wo=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${yo}`,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(hd)})}catch(i){throw new we(`the uRun usage surface (POST ${yo}) could not be reached within ${hd}ms: ${gd(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new ae("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new we(`the uRun usage surface (POST ${yo}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new we(`the uRun usage surface (POST ${yo}) answered HTTP ${o.status} with a body that is not JSON: ${gd(i)}`)}return ca(s,this.opts.onRejectedRow)}};T();var Jh="/inference-ledger",Vh=1e4,_o=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},oi=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"}},si=class extends ae{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ii=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Kh=[["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",ni],["output_minutes",ni],["cost_nano_usd",ni],["price_version",t=>t===null||typeof t=="string"]];function zh(t){for(let[e,n]of Kh){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Yh(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"}:zh(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function ni(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function ri(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Xh(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function yd(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 Qh(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&&yd(t.started_at,n.started_at)&&yd(t.completed_at,n.completed_at)&&ri(t.prompt_tokens,n.prompt_tokens)&&ri(t.completion_tokens,n.completion_tokens)&&ri(t.output_units,n.output_units)&&Xh(t.output_minutes,n.output_minutes)}function Zh(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(`
94
+ `)}async function eg(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(Zh(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function tg(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=u=>{if(!(u in n))throw new Oe(`${e} answered a row with no ${u} field: ${JSON.stringify(t)}`);let d=n[u];if(d===null)return null;if(typeof d!="string")throw new Oe(`${e} answered a non-string ${u}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new Oe(`${e} answered a BLANK ${u} (${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"),l=o!=null;if(l&&(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(!l&&(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 vo=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Jh}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await eg(n,this.opts.signing)}):JSON.stringify(n)}catch(u){throw new Oe(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${u instanceof Error?u.message:String(u)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(Vh)})}catch(u){throw new Oe(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(s.status===409){let u=await s.text().catch(()=>""),d=Yh(u);throw d.status==="found"&&Qh(n,d.row)?new oi(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 _o(`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 _o(`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). ${u.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new si("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 u=await s.text().catch(c=>`<body unreadable: ${c instanceof Error?c.message:String(c)}>`),d;try{let c=JSON.parse(u);if(c!==null&&typeof c=="object"&&"error"in c){let f=c.error;f!==null&&typeof f=="object"&&"code"in f&&(d=f.code)}}catch{}throw d==="ledger_signature_invalid"?new ii(`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: `+u.slice(0,400)):new Oe(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${u.slice(0,400)}`)}let i;try{i=await s.json()}catch(u){throw new Oe(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}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 l=tg(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new Oe(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};var ng=5e3,rg=1e3,og=1500,sg=3e3,ig="/api/client-tokens";function bo(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function wd(t,e,n,r){bo(t,e,{error:{message:n,type:r}})}async function ag(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${ig}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(sg)});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 Sd(t){let e=t.resolver??new nr({gatewayUrl:t.baseUrl}),n=t.machine?new ao({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=t.userIssuers?new lo({issuers:t.userIssuers,gatewayUrl:t.baseUrl,...t.memberGate?{memberGate:t.memberGate}:{}}):null,o=new yr(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),s=null,i=null,a=(()=>{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 b=new bd.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),C=Xu({redis:b});return{registry:Bu({selfAddress:t.lane.selfAddress,seatRegion:t.pooler.region,tokenSecret:t.lane.tokenSecret,plane:Ru({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(M,U)=>s?.onHostedChange(M,U)??(()=>()=>{}),roomDoc:(M,U)=>{if(!s)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return s.roomDoc(M,U)},metrics:o,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(M,U)=>C.rows().then(q=>{let X=Uo(q,U);return X?.warm_wait_s!==void 0?X.warm_wait_s*1e3:void 0}),currentReleaseOf:Hu(b),closeLane:M=>s?.closeLane(M)}),catalog:C,redis:b}})(),l=t.registry??new ho({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry,pooler:t.pooler}),u=t.probeControlPlane??(()=>ag(t.baseUrl)),d=async()=>{let b=null;for(let M of l.decisionPools()){b=M;break}if(!b)return null;let C=b.stats();if(C.some(M=>M.draining))return{ok:!1,detail:"decision pool draining"};if(C.every(M=>M.attached===0&&M.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let $=await b.pingReady(og);return{ok:$,detail:$?"a decision slot answered its session ping":"no decision slot answered its session ping"}},c=t.usageClient??new wo({apiUrl:t.apiUrl}),f=t.ledgerClient??new vo({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),h=process.env.URUN_SHARED_ORG_ID?.trim(),m=process.env.URUN_SHARED_ORG_API_KEY?.trim();h&&m&&(async()=>{try{await l.decisionWarmerFor({orgId:h,apiKey:m})?.warmFor(Yr)}catch(b){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(b instanceof Error?b.message:b)}
95
+ `)}})();let w=async b=>Vs(co(b.headers.authorization),e,n,r),E=async b=>{let C=await w(b);if(C.billingAudience==="platform"&&C.creditsAdmissionOk===!1){let $=C.creditsRefusalReason;throw new _n($==="spend_cap_reached"||$==="insufficient_credits"?$:void 0)}return C},x=b=>b instanceof ae?{status:b.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:b instanceof Gt?{status:403,openaiType:"authentication_error",anthropicType:"authentication_error",...b.detail!==void 0?{operatorDetail:b.detail}:{}}:b instanceof _n?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...b.code!==void 0?{code:b.code}:{}}:b instanceof ft?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:b.detail}:null,v={write:(b,C)=>f.write(co(b.headers.authorization),C),observe:b=>o.observeLedger(b),...t.ledgerLog?{report:t.ledgerLog}:{}},_=iu({clients:async b=>l.clientsFor(await E(b)),usage:{authorize:b=>co(b.headers.authorization),lookup:(b,C)=>c.lookup(b,C)},statusOf:x,...t.requestLog?{requestLog:t.requestLog}:{},observe:b=>o.observe(b),ledger:v}),p=gl({authorize:async b=>{await E(b)},...t.lane?{secret:t.lane.tokenSecret}:{}}),g=null,y=null,S=(0,_d.createServer)((b,C)=>{let $=new URL(b.url??"/","http://localhost");(async()=>{if(b.method==="GET"&&$.pathname==="/healthz"){bo(C,200,{ok:!0});return}if(b.method==="GET"&&$.pathname==="/readyz"){let q=Date.now();if((!g||q-g.at>=ng)&&(g={at:q,...await u()}),!y||q-y.at>=rg){let re=await d();y=re===null?{at:q,ok:!0,detail:null}:{at:q,ok:re.ok,detail:re.detail}}let X=(g?.ready??!1)&&y.ok,G=y.detail===null?g?.detail??"control plane not yet probed":`${g?.detail??"control plane not yet probed"}; ${y.detail}`;bo(C,X?200:503,{ok:X,control_plane:G});return}if(b.method==="GET"&&$.pathname==="/lanez"){bo(C,200,{pools:a?await a.registry.status():null});return}let M=$.pathname==="/v1"||$.pathname.startsWith("/v1/"),U=$.pathname.startsWith("/partners/");if(!M&&!U){wd(C,404,`no route for ${b.method} ${$.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}await p(b,C)||_(b,C)})().catch(M=>{if(!C.headersSent){wd(C,500,String(M instanceof Error?M.message:M),"proxy_error");return}C.end()})}),A=t.conversations??new go({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry}),P=new WeakMap,R=[Qo(S,{authenticate:async b=>{let C=await Vs(b,e,n,r),$=A.connectionFor(C);return{clients:$.clients,scope:mo(C.apiKey),onBindResumeHandle:$.bindResumeHandle,clientsForResume:$.clientsForResume,release:$.release}}}),us(S,{clients:async b=>l.clientsFor(await E(b)),statusOf:x}).close,Nr(S,{resolver:{resolve:async(b,C,$)=>{let M=await E(b),U=A.connectionFor(M,cu(b)),q;try{q=await pu(Ls(U.clients,t.realtimeCompanions),uu(b),C,du(b),$)}catch(re){throw U.release().catch(()=>{}),re}let X=q.release,G={...q,release:async()=>{await X?.(),await U.release()}};return P.set(G,M.orgId),G}},onSessionEnded:b=>{dr({record:{event:"inference_request",ts:new Date().toISOString(),inference_id:Pt(),method:"GET",path:"/v1/realtime",status:200,delivered:!0,stream_error:!1,model:b.binding.model??null,stream:null,org:P.get(b.binding)??null,duration_ms:b.connected_ms,ttft_ms:null,prompt_tokens:null,completion_tokens:null,output_units:null,output_minutes:null,output_seconds:null,session_seconds:b.connected_ms/1e3,session_id:b.binding.audioSession?.audio.sessionId??null,queue_ms:null,prefill_ms:null,decode_ms:null,total_ms:null,catalog:b.binding.catalog??{kind:"unresolved",reason:"the realtime binding carries no dial-time catalog identity (no billing-identity oracle wired, or the composite lane)"}},ledger:v,req:b.req})}})];if(t.lane&&a){let b=t.lane,C=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;s=Yu(S,{verifyToken:(M,U)=>Fs(M,U,b.tokenSecret,void 0,C),selfAddress:b.selfAddress,laneTenantOf:M=>a.redis.get(`lane_tenant:${M}`),onLaneTenantMissing:()=>o.observeLaneDocTenantMissing(),previousTokenSecret:C,hostRegistry:{setHost:(M,U)=>a.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:${M}`,U,String(zu)),delHost:M=>a.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${M}`,b.selfAddress)}}),i=Mu(S,{verifyToken:(M,U)=>Fs(M,U,b.tokenSecret,void 0,C),selfAddress:b.selfAddress,hostOf:async M=>{let U=await a.redis.get(`lane_hosts:${M}`);return U&&U.trim()!==""?U.trim():null},podToPodDial:(M,U,q)=>new Promise((X,G)=>{(async()=>{let re=await a.redis.get(`lane_tenant:${M}`),K=Qn(M,b.tokenSecret,void 0,void 0,re||void 0),N=`ws://${q}/stream/${encodeURIComponent(M)}/${encodeURIComponent(U)}?token=${encodeURIComponent(K)}`,ee=new vd.default(N,no(U));ee.once("open",()=>X(ee)),ee.once("error",G)})().catch(G)})});let $=a;R.push(async()=>{await s.close(),await i.close(),await $.registry.close(),$.redis.quit().catch(()=>{})})}S.on("upgrade",(b,C)=>{let $=new URL(b.url??"/","http://localhost");$.pathname===Rr||$.pathname===as||$.pathname===jn||s!==null&&$.pathname.startsWith("/doc/")||i!==null&&$.pathname.startsWith("/stream/")||C.destroyed||(C.write(`HTTP/1.1 404 Not Found\r
95
96
  Connection: close\r
96
97
  \r
97
- no WS route for ${$.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),C.destroy())});let T=async()=>{for(let _ of R)await _();await A.detachAll()};return{server:S,metricsServer:ca(o),metrics:o,edgeIdentityServer:ma(),registry:l,closeAll:()=>l.closeAll(),closeWebSockets:T}}async function _d(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await Yi()||Xi(),await e()}function og(){let t=null;return t=Hi({streams:et.default,note:e=>{t?.isDead("stderr")!==!0&&tt(et.default.stderr,e)}}),t}async function sg(){og();let t=ha(et.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:s}=wd(t);await new Promise((a,l)=>{e.once("error",l),e.listen(t.port,It,a)}),await new Promise((a,l)=>{n.once("error",l),n.listen(Bo,It,a)}),await new Promise((a,l)=>{r.once("error",l),r.listen(jo,It,a)}),et.default.stdout.write(`inference-proxy listening on http://${It}:${t.port}/v1 (metrics http://${It}:${Bo}${fr}, edge identity http://${It}:${jo}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
98
+ no WS route for ${$.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),C.destroy())});let O=async()=>{for(let b of R)await b();await A.detachAll()};return{server:S,metricsServer:ma(o),metrics:o,edgeIdentityServer:ya(),registry:l,closeAll:()=>l.closeAll(),closeWebSockets:O}}async function kd(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await Zi()||ea(),await e()}function lg(){let t=null;return t=Gi({streams:et.default,note:e=>{t?.isDead("stderr")!==!0&&tt(et.default.stderr,e)}}),t}async function ug(){lg();let t=wa(et.default.env),{server:e,metricsServer:n,edgeIdentityServer:r,closeAll:o,closeWebSockets:s}=Sd(t);await new Promise((a,l)=>{e.once("error",l),e.listen(t.port,It,a)}),await new Promise((a,l)=>{n.once("error",l),n.listen(jo,It,a)}),await new Promise((a,l)=>{r.once("error",l),r.listen(Go,It,a)}),et.default.stdout.write(`inference-proxy listening on http://${It}:${t.port}/v1 (metrics http://${It}:${jo}${mr}, edge identity http://${It}:${Go}, control plane ${t.baseUrl}, org API ${t.apiUrl}, catalog oracle ${t.catalog?"on":"off"})
98
99
  `);let i=async a=>{et.default.stdout.write(`inference-proxy: ${a} \u2014 draining
99
- `),await _d(e,o,s),await new Promise(l=>n.close(()=>l())),await new Promise(l=>r.close(()=>l()))};await new Promise(a=>{et.default.once("SIGINT",()=>{i("SIGINT").finally(a)}),et.default.once("SIGTERM",()=>{i("SIGTERM").finally(a)})})}sg().then(()=>et.default.exit(0),t=>{et.default.stderr.write(`inference-proxy: ${String(t instanceof Error?t.stack??t.message:t)}
100
+ `),await kd(e,o,s),await new Promise(l=>n.close(()=>l())),await new Promise(l=>r.close(()=>l()))};await new Promise(a=>{et.default.once("SIGINT",()=>{i("SIGINT").finally(a)}),et.default.once("SIGTERM",()=>{i("SIGTERM").finally(a)})})}ug().then(()=>et.default.exit(0),t=>{et.default.stderr.write(`inference-proxy: ${String(t instanceof Error?t.stack??t.message:t)}
100
101
  `),et.default.exit(1)});
101
102
  /*! Bundled license information:
102
103