@urun-sh/openai 0.6.37 → 0.6.38

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,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var tn=Object.create;var Ge=Object.defineProperty;var nn=Object.getOwnPropertyDescriptor;var rn=Object.getOwnPropertyNames;var sn=Object.getPrototypeOf,on=Object.prototype.hasOwnProperty;var an=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(e=s(s=0)),e}catch(n){throw t=[n],n}};var ln=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var un=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of rn(e))!on.call(s,r)&&r!==t&&Ge(s,r,{get:()=>e[r],enumerable:!(n=nn(e,r))||n.enumerable});return s};var te=(s,e,t)=>(t=s!=null?tn(sn(s)):{},un(e||!s||!s.__esModule?Ge(t,"default",{value:s,enumerable:!0}):t,s));var S=an(()=>{"use strict"});var He=ln(()=>{"use strict";S();var je;(function(s){(function(e){var t=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:p(),n=r(s);typeof t.Reflect<"u"&&(n=r(t.Reflect,n)),e(n,t),typeof t.Reflect>"u"&&(t.Reflect=s);function r(y,R){return function(_,d){Object.defineProperty(y,_,{configurable:!0,writable:!0,value:d}),R&&R(_,d)}}function o(){try{return Function("return this;")()}catch{}}function l(){try{return(0,eval)("(function() { return this; })()")}catch{}}function p(){return o()||l()}})(function(e,t){var n=Object.prototype.hasOwnProperty,r=typeof Symbol=="function",o=r&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",l=r&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",p=typeof Object.create=="function",y={__proto__:[]}instanceof Array,R=!p&&!y,_={create:p?function(){return he(Object.create(null))}:y?function(){return he({__proto__:null})}:function(){return he({})},has:R?function(i,a){return n.call(i,a)}:function(i,a){return a in i},get:R?function(i,a){return n.call(i,a)?i[a]:void 0}:function(i,a){return i[a]}},d=Object.getPrototypeOf(Function),g=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:zt(),T=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Qt(),k=typeof WeakMap=="function"?WeakMap:Xt(),I=r?Symbol.for("@reflect-metadata:registry"):void 0,x=Vt(),A=Jt(x);function N(i,a,u,c){if(b(u)){if(!Ne(i))throw new TypeError;if(!Me(a))throw new TypeError;return Dt(i,a)}else{if(!Ne(i))throw new TypeError;if(!$(a))throw new TypeError;if(!$(c)&&!b(c)&&!J(c))throw new TypeError;return J(c)&&(c=void 0),u=G(u),Gt(i,a,u,c)}}e("decorate",N);function de(i,a){function u(c,w){if(!$(c))throw new TypeError;if(!b(w)&&!Bt(w))throw new TypeError;Te(i,a,c,w)}return u}e("metadata",de);function ee(i,a,u,c){if(!$(u))throw new TypeError;return b(c)||(c=G(c)),Te(i,a,u,c)}e("defineMetadata",ee);function Y(i,a,u){if(!$(a))throw new TypeError;return b(u)||(u=G(u)),Ee(i,a,u)}e("hasMetadata",Y);function Mt(i,a,u){if(!$(a))throw new TypeError;return b(u)||(u=G(u)),ce(i,a,u)}e("hasOwnMetadata",Mt);function $t(i,a,u){if(!$(a))throw new TypeError;return b(u)||(u=G(u)),ke(i,a,u)}e("getMetadata",$t);function Ct(i,a,u){if(!$(a))throw new TypeError;return b(u)||(u=G(u)),Pe(i,a,u)}e("getOwnMetadata",Ct);function Ut(i,a){if(!$(i))throw new TypeError;return b(a)||(a=G(a)),Ie(i,a)}e("getMetadataKeys",Ut);function Lt(i,a){if(!$(i))throw new TypeError;return b(a)||(a=G(a)),xe(i,a)}e("getOwnMetadataKeys",Lt);function qt(i,a,u){if(!$(a))throw new TypeError;if(b(u)||(u=G(u)),!$(a))throw new TypeError;b(u)||(u=G(u));var c=Q(a,u,!1);return b(c)?!1:c.OrdinaryDeleteMetadata(i,a,u)}e("deleteMetadata",qt);function Dt(i,a){for(var u=i.length-1;u>=0;--u){var c=i[u],w=c(a);if(!b(w)&&!J(w)){if(!Me(w))throw new TypeError;a=w}}return a}function Gt(i,a,u,c){for(var w=i.length-1;w>=0;--w){var C=i[w],L=C(a,u,c);if(!b(L)&&!J(L)){if(!$(L))throw new TypeError;c=L}}return c}function Ee(i,a,u){var c=ce(i,a,u);if(c)return!0;var w=fe(a);return J(w)?!1:Ee(i,w,u)}function ce(i,a,u){var c=Q(a,u,!1);return b(c)?!1:Oe(c.OrdinaryHasOwnMetadata(i,a,u))}function ke(i,a,u){var c=ce(i,a,u);if(c)return Pe(i,a,u);var w=fe(a);if(!J(w))return ke(i,w,u)}function Pe(i,a,u){var c=Q(a,u,!1);if(!b(c))return c.OrdinaryGetOwnMetadata(i,a,u)}function Te(i,a,u,c){var w=Q(u,c,!0);w.OrdinaryDefineOwnMetadata(i,a,u,c)}function Ie(i,a){var u=xe(i,a),c=fe(i);if(c===null)return u;var w=Ie(c,a);if(w.length<=0)return u;if(u.length<=0)return w;for(var C=new T,L=[],E=0,f=u;E<f.length;E++){var h=f[E],m=C.has(h);m||(C.add(h),L.push(h))}for(var v=0,P=w;v<P.length;v++){var h=P[v],m=C.has(h);m||(C.add(h),L.push(h))}return L}function xe(i,a){var u=Q(i,a,!1);return u?u.OrdinaryOwnMetadataKeys(i,a):[]}function Ae(i){if(i===null)return 1;switch(typeof i){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return i===null?1:6;default:return 6}}function b(i){return i===void 0}function J(i){return i===null}function jt(i){return typeof i=="symbol"}function $(i){return typeof i=="object"?i!==null:typeof i=="function"}function Ht(i,a){switch(Ae(i)){case 0:return i;case 1:return i;case 2:return i;case 3:return i;case 4:return i;case 5:return i}var u=a===3?"string":a===5?"number":"default",c=$e(i,o);if(c!==void 0){var w=c.call(i,u);if($(w))throw new TypeError;return w}return Ft(i,u==="default"?"number":u)}function Ft(i,a){if(a==="string"){var u=i.toString;if(W(u)){var c=u.call(i);if(!$(c))return c}var w=i.valueOf;if(W(w)){var c=w.call(i);if(!$(c))return c}}else{var w=i.valueOf;if(W(w)){var c=w.call(i);if(!$(c))return c}var C=i.toString;if(W(C)){var c=C.call(i);if(!$(c))return c}}throw new TypeError}function Oe(i){return!!i}function Kt(i){return""+i}function G(i){var a=Ht(i,3);return jt(a)?a:Kt(a)}function Ne(i){return Array.isArray?Array.isArray(i):i instanceof Object?i instanceof Array:Object.prototype.toString.call(i)==="[object Array]"}function W(i){return typeof i=="function"}function Me(i){return typeof i=="function"}function Bt(i){switch(Ae(i)){case 3:return!0;case 4:return!0;default:return!1}}function pe(i,a){return i===a||i!==i&&a!==a}function $e(i,a){var u=i[a];if(u!=null){if(!W(u))throw new TypeError;return u}}function Ce(i){var a=$e(i,l);if(!W(a))throw new TypeError;var u=a.call(i);if(!$(u))throw new TypeError;return u}function Ue(i){return i.value}function Le(i){var a=i.next();return a.done?!1:a}function qe(i){var a=i.return;a&&a.call(i)}function fe(i){var a=Object.getPrototypeOf(i);if(typeof i!="function"||i===d||a!==d)return a;var u=i.prototype,c=u&&Object.getPrototypeOf(u);if(c==null||c===Object.prototype)return a;var w=c.constructor;return typeof w!="function"||w===i?a:w}function Yt(){var i;!b(I)&&typeof t.Reflect<"u"&&!(I in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(i=Wt(t.Reflect));var a,u,c,w=new k,C={registerProvider:L,getProvider:f,setProvider:m};return C;function L(v){if(!Object.isExtensible(C))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case i===v:break;case b(a):a=v;break;case a===v:break;case b(u):u=v;break;case u===v:break;default:c===void 0&&(c=new T),c.add(v);break}}function E(v,P){if(!b(a)){if(a.isProviderFor(v,P))return a;if(!b(u)){if(u.isProviderFor(v,P))return a;if(!b(c))for(var O=Ce(c);;){var U=Le(O);if(!U)return;var D=Ue(U);if(D.isProviderFor(v,P))return qe(O),D}}}if(!b(i)&&i.isProviderFor(v,P))return i}function f(v,P){var O=w.get(v),U;return b(O)||(U=O.get(P)),b(U)&&(U=E(v,P),b(U)||(b(O)&&(O=new g,w.set(v,O)),O.set(P,U))),U}function h(v){if(b(v))throw new TypeError;return a===v||u===v||!b(c)&&c.has(v)}function m(v,P,O){if(!h(O))throw new Error("Metadata provider not registered.");var U=f(v,P);if(U!==O){if(!b(U))return!1;var D=w.get(v);b(D)&&(D=new g,w.set(v,D)),D.set(P,O)}return!0}}function Vt(){var i;return!b(I)&&$(t.Reflect)&&Object.isExtensible(t.Reflect)&&(i=t.Reflect[I]),b(i)&&(i=Yt()),!b(I)&&$(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,I,{enumerable:!1,configurable:!1,writable:!1,value:i}),i}function Jt(i){var a=new k,u={isProviderFor:function(h,m){var v=a.get(h);return b(v)?!1:v.has(m)},OrdinaryDefineOwnMetadata:L,OrdinaryHasOwnMetadata:w,OrdinaryGetOwnMetadata:C,OrdinaryOwnMetadataKeys:E,OrdinaryDeleteMetadata:f};return x.registerProvider(u),u;function c(h,m,v){var P=a.get(h),O=!1;if(b(P)){if(!v)return;P=new g,a.set(h,P),O=!0}var U=P.get(m);if(b(U)){if(!v)return;if(U=new g,P.set(m,U),!i.setProvider(h,m,u))throw P.delete(m),O&&a.delete(h),new Error("Wrong provider for target.")}return U}function w(h,m,v){var P=c(m,v,!1);return b(P)?!1:Oe(P.has(h))}function C(h,m,v){var P=c(m,v,!1);if(!b(P))return P.get(h)}function L(h,m,v,P){var O=c(v,P,!0);O.set(h,m)}function E(h,m){var v=[],P=c(h,m,!1);if(b(P))return v;for(var O=P.keys(),U=Ce(O),D=0;;){var De=Le(U);if(!De)return v.length=D,v;var Zt=Ue(De);try{v[D]=Zt}catch(en){try{qe(U)}finally{throw en}}D++}}function f(h,m,v){var P=c(m,v,!1);if(b(P)||!P.delete(h))return!1;if(P.size===0){var O=a.get(m);b(O)||(O.delete(v),O.size===0&&a.delete(O))}return!0}}function Wt(i){var a=i.defineMetadata,u=i.hasOwnMetadata,c=i.getOwnMetadata,w=i.getOwnMetadataKeys,C=i.deleteMetadata,L=new k,E={isProviderFor:function(f,h){var m=L.get(f);return!b(m)&&m.has(h)?!0:w(f,h).length?(b(m)&&(m=new T,L.set(f,m)),m.add(h),!0):!1},OrdinaryDefineOwnMetadata:a,OrdinaryHasOwnMetadata:u,OrdinaryGetOwnMetadata:c,OrdinaryOwnMetadataKeys:w,OrdinaryDeleteMetadata:C};return E}function Q(i,a,u){var c=x.getProvider(i,a);if(!b(c))return c;if(u){if(x.setProvider(i,a,A))return A;throw new Error("Illegal state.")}}function zt(){var i={},a=[],u=(function(){function E(f,h,m){this._index=0,this._keys=f,this._values=h,this._selector=m}return E.prototype["@@iterator"]=function(){return this},E.prototype[l]=function(){return this},E.prototype.next=function(){var f=this._index;if(f>=0&&f<this._keys.length){var h=this._selector(this._keys[f],this._values[f]);return f+1>=this._keys.length?(this._index=-1,this._keys=a,this._values=a):this._index++,{value:h,done:!1}}return{value:void 0,done:!0}},E.prototype.throw=function(f){throw this._index>=0&&(this._index=-1,this._keys=a,this._values=a),f},E.prototype.return=function(f){return this._index>=0&&(this._index=-1,this._keys=a,this._values=a),{value:f,done:!0}},E})(),c=(function(){function E(){this._keys=[],this._values=[],this._cacheKey=i,this._cacheIndex=-2}return Object.defineProperty(E.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),E.prototype.has=function(f){return this._find(f,!1)>=0},E.prototype.get=function(f){var h=this._find(f,!1);return h>=0?this._values[h]:void 0},E.prototype.set=function(f,h){var m=this._find(f,!0);return this._values[m]=h,this},E.prototype.delete=function(f){var h=this._find(f,!1);if(h>=0){for(var m=this._keys.length,v=h+1;v<m;v++)this._keys[v-1]=this._keys[v],this._values[v-1]=this._values[v];return this._keys.length--,this._values.length--,pe(f,this._cacheKey)&&(this._cacheKey=i,this._cacheIndex=-2),!0}return!1},E.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=i,this._cacheIndex=-2},E.prototype.keys=function(){return new u(this._keys,this._values,w)},E.prototype.values=function(){return new u(this._keys,this._values,C)},E.prototype.entries=function(){return new u(this._keys,this._values,L)},E.prototype["@@iterator"]=function(){return this.entries()},E.prototype[l]=function(){return this.entries()},E.prototype._find=function(f,h){if(!pe(this._cacheKey,f)){this._cacheIndex=-1;for(var m=0;m<this._keys.length;m++)if(pe(this._keys[m],f)){this._cacheIndex=m;break}}return this._cacheIndex<0&&h&&(this._cacheIndex=this._keys.length,this._keys.push(f),this._values.push(void 0)),this._cacheIndex},E})();return c;function w(E,f){return E}function C(E,f){return f}function L(E,f){return[E,f]}}function Qt(){var i=(function(){function a(){this._map=new g}return Object.defineProperty(a.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),a.prototype.has=function(u){return this._map.has(u)},a.prototype.add=function(u){return this._map.set(u,u),this},a.prototype.delete=function(u){return this._map.delete(u)},a.prototype.clear=function(){this._map.clear()},a.prototype.keys=function(){return this._map.keys()},a.prototype.values=function(){return this._map.keys()},a.prototype.entries=function(){return this._map.entries()},a.prototype["@@iterator"]=function(){return this.keys()},a.prototype[l]=function(){return this.keys()},a})();return i}function Xt(){var i=16,a=_.create(),u=c();return(function(){function f(){this._key=c()}return f.prototype.has=function(h){var m=w(h,!1);return m!==void 0?_.has(m,this._key):!1},f.prototype.get=function(h){var m=w(h,!1);return m!==void 0?_.get(m,this._key):void 0},f.prototype.set=function(h,m){var v=w(h,!0);return v[this._key]=m,this},f.prototype.delete=function(h){var m=w(h,!1);return m!==void 0?delete m[this._key]:!1},f.prototype.clear=function(){this._key=c()},f})();function c(){var f;do f="@@WeakMap@@"+E();while(_.has(a,f));return a[f]=!0,f}function w(f,h){if(!n.call(f,u)){if(!h)return;Object.defineProperty(f,u,{value:_.create()})}return f[u]}function C(f,h){for(var m=0;m<h;++m)f[m]=Math.random()*255|0;return f}function L(f){if(typeof Uint8Array=="function"){var h=new Uint8Array(f);return typeof crypto<"u"?crypto.getRandomValues(h):typeof msCrypto<"u"?msCrypto.getRandomValues(h):C(h,f),h}return C(new Array(f),f)}function E(){var f=L(i);f[6]=f[6]&79|64,f[8]=f[8]&191|128;for(var h="",m=0;m<i;++m){var v=f[m];(m===4||m===6||m===8)&&(h+="-"),v<16&&(h+="0"),h+=v.toString(16).toLowerCase()}return h}}function he(i){return i.__=void 0,delete i.__,i}})})(je||(je={}))});S();var Fs=te(He(),1),j=te(require("process"),1),Nt=require("ioredis");S();var fn=te(require("os"),1),hn=te(require("path"),1),gn=require("url"),mn=require("util");S();S();S();S();S();S();var H=class extends Error{};var yn=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Fe(s){let e=s?.code;return typeof e=="string"&&yn.has(e)}function ne(s,e){try{return s.write(e),!0}catch(t){if(Fe(t))return!1;throw t}}function Ke(s){let e={stdout:!1,stderr:!1},t=[];for(let n of["stdout","stderr"]){let r=s.streams[n],o=l=>{Fe(l)&&(e[n]=!0);let p=l?.code;try{s.note(`${new Date().toISOString()} urun compat: process.${n} died (${String(p??(l instanceof Error?l.message:l))}) \u2014 the terminal is gone; launcher output continues in this log only
3
- `)}catch{}};r.on("error",o),t.push([r,o])}return{isDead:n=>e[n],uninstall:()=>{for(let[n,r]of t)n.off("error",r)}}}S();S();var ge=`
2
+ "use strict";var tn=Object.create;var Ge=Object.defineProperty;var nn=Object.getOwnPropertyDescriptor;var rn=Object.getOwnPropertyNames;var sn=Object.getPrototypeOf,on=Object.prototype.hasOwnProperty;var an=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(e=s(s=0)),e}catch(n){throw t=[n],n}};var ln=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var un=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of rn(e))!on.call(s,r)&&r!==t&&Ge(s,r,{get:()=>e[r],enumerable:!(n=nn(e,r))||n.enumerable});return s};var te=(s,e,t)=>(t=s!=null?tn(sn(s)):{},un(e||!s||!s.__esModule?Ge(t,"default",{value:s,enumerable:!0}):t,s));var S=an(()=>{"use strict"});var He=ln(()=>{"use strict";S();var je;(function(s){(function(e){var t=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:p(),n=r(s);typeof t.Reflect<"u"&&(n=r(t.Reflect,n)),e(n,t),typeof t.Reflect>"u"&&(t.Reflect=s);function r(y,R){return function(_,d){Object.defineProperty(y,_,{configurable:!0,writable:!0,value:d}),R&&R(_,d)}}function i(){try{return Function("return this;")()}catch{}}function l(){try{return(0,eval)("(function() { return this; })()")}catch{}}function p(){return i()||l()}})(function(e,t){var n=Object.prototype.hasOwnProperty,r=typeof Symbol=="function",i=r&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",l=r&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",p=typeof Object.create=="function",y={__proto__:[]}instanceof Array,R=!p&&!y,_={create:p?function(){return he(Object.create(null))}:y?function(){return he({__proto__:null})}:function(){return he({})},has:R?function(o,a){return n.call(o,a)}:function(o,a){return a in o},get:R?function(o,a){return n.call(o,a)?o[a]:void 0}:function(o,a){return o[a]}},d=Object.getPrototypeOf(Function),g=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:zt(),T=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Qt(),k=typeof WeakMap=="function"?WeakMap:Xt(),I=r?Symbol.for("@reflect-metadata:registry"):void 0,x=Vt(),A=Jt(x);function N(o,a,u,c){if(b(u)){if(!Ne(o))throw new TypeError;if(!Me(a))throw new TypeError;return Dt(o,a)}else{if(!Ne(o))throw new TypeError;if(!$(a))throw new TypeError;if(!$(c)&&!b(c)&&!J(c))throw new TypeError;return J(c)&&(c=void 0),u=G(u),Gt(o,a,u,c)}}e("decorate",N);function de(o,a){function u(c,w){if(!$(c))throw new TypeError;if(!b(w)&&!Bt(w))throw new TypeError;Te(o,a,c,w)}return u}e("metadata",de);function ee(o,a,u,c){if(!$(u))throw new TypeError;return b(c)||(c=G(c)),Te(o,a,u,c)}e("defineMetadata",ee);function Y(o,a,u){if(!$(a))throw new TypeError;return b(u)||(u=G(u)),Ee(o,a,u)}e("hasMetadata",Y);function Mt(o,a,u){if(!$(a))throw new TypeError;return b(u)||(u=G(u)),ce(o,a,u)}e("hasOwnMetadata",Mt);function $t(o,a,u){if(!$(a))throw new TypeError;return b(u)||(u=G(u)),ke(o,a,u)}e("getMetadata",$t);function Ct(o,a,u){if(!$(a))throw new TypeError;return b(u)||(u=G(u)),Pe(o,a,u)}e("getOwnMetadata",Ct);function Ut(o,a){if(!$(o))throw new TypeError;return b(a)||(a=G(a)),Ie(o,a)}e("getMetadataKeys",Ut);function Lt(o,a){if(!$(o))throw new TypeError;return b(a)||(a=G(a)),xe(o,a)}e("getOwnMetadataKeys",Lt);function qt(o,a,u){if(!$(a))throw new TypeError;if(b(u)||(u=G(u)),!$(a))throw new TypeError;b(u)||(u=G(u));var c=Q(a,u,!1);return b(c)?!1:c.OrdinaryDeleteMetadata(o,a,u)}e("deleteMetadata",qt);function Dt(o,a){for(var u=o.length-1;u>=0;--u){var c=o[u],w=c(a);if(!b(w)&&!J(w)){if(!Me(w))throw new TypeError;a=w}}return a}function Gt(o,a,u,c){for(var w=o.length-1;w>=0;--w){var C=o[w],L=C(a,u,c);if(!b(L)&&!J(L)){if(!$(L))throw new TypeError;c=L}}return c}function Ee(o,a,u){var c=ce(o,a,u);if(c)return!0;var w=fe(a);return J(w)?!1:Ee(o,w,u)}function ce(o,a,u){var c=Q(a,u,!1);return b(c)?!1:Oe(c.OrdinaryHasOwnMetadata(o,a,u))}function ke(o,a,u){var c=ce(o,a,u);if(c)return Pe(o,a,u);var w=fe(a);if(!J(w))return ke(o,w,u)}function Pe(o,a,u){var c=Q(a,u,!1);if(!b(c))return c.OrdinaryGetOwnMetadata(o,a,u)}function Te(o,a,u,c){var w=Q(u,c,!0);w.OrdinaryDefineOwnMetadata(o,a,u,c)}function Ie(o,a){var u=xe(o,a),c=fe(o);if(c===null)return u;var w=Ie(c,a);if(w.length<=0)return u;if(u.length<=0)return w;for(var C=new T,L=[],E=0,f=u;E<f.length;E++){var h=f[E],m=C.has(h);m||(C.add(h),L.push(h))}for(var v=0,P=w;v<P.length;v++){var h=P[v],m=C.has(h);m||(C.add(h),L.push(h))}return L}function xe(o,a){var u=Q(o,a,!1);return u?u.OrdinaryOwnMetadataKeys(o,a):[]}function Ae(o){if(o===null)return 1;switch(typeof o){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return o===null?1:6;default:return 6}}function b(o){return o===void 0}function J(o){return o===null}function jt(o){return typeof o=="symbol"}function $(o){return typeof o=="object"?o!==null:typeof o=="function"}function Ht(o,a){switch(Ae(o)){case 0:return o;case 1:return o;case 2:return o;case 3:return o;case 4:return o;case 5:return o}var u=a===3?"string":a===5?"number":"default",c=$e(o,i);if(c!==void 0){var w=c.call(o,u);if($(w))throw new TypeError;return w}return Ft(o,u==="default"?"number":u)}function Ft(o,a){if(a==="string"){var u=o.toString;if(W(u)){var c=u.call(o);if(!$(c))return c}var w=o.valueOf;if(W(w)){var c=w.call(o);if(!$(c))return c}}else{var w=o.valueOf;if(W(w)){var c=w.call(o);if(!$(c))return c}var C=o.toString;if(W(C)){var c=C.call(o);if(!$(c))return c}}throw new TypeError}function Oe(o){return!!o}function Kt(o){return""+o}function G(o){var a=Ht(o,3);return jt(a)?a:Kt(a)}function Ne(o){return Array.isArray?Array.isArray(o):o instanceof Object?o instanceof Array:Object.prototype.toString.call(o)==="[object Array]"}function W(o){return typeof o=="function"}function Me(o){return typeof o=="function"}function Bt(o){switch(Ae(o)){case 3:return!0;case 4:return!0;default:return!1}}function pe(o,a){return o===a||o!==o&&a!==a}function $e(o,a){var u=o[a];if(u!=null){if(!W(u))throw new TypeError;return u}}function Ce(o){var a=$e(o,l);if(!W(a))throw new TypeError;var u=a.call(o);if(!$(u))throw new TypeError;return u}function Ue(o){return o.value}function Le(o){var a=o.next();return a.done?!1:a}function qe(o){var a=o.return;a&&a.call(o)}function fe(o){var a=Object.getPrototypeOf(o);if(typeof o!="function"||o===d||a!==d)return a;var u=o.prototype,c=u&&Object.getPrototypeOf(u);if(c==null||c===Object.prototype)return a;var w=c.constructor;return typeof w!="function"||w===o?a:w}function Yt(){var o;!b(I)&&typeof t.Reflect<"u"&&!(I in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(o=Wt(t.Reflect));var a,u,c,w=new k,C={registerProvider:L,getProvider:f,setProvider:m};return C;function L(v){if(!Object.isExtensible(C))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case o===v:break;case b(a):a=v;break;case a===v:break;case b(u):u=v;break;case u===v:break;default:c===void 0&&(c=new T),c.add(v);break}}function E(v,P){if(!b(a)){if(a.isProviderFor(v,P))return a;if(!b(u)){if(u.isProviderFor(v,P))return a;if(!b(c))for(var O=Ce(c);;){var U=Le(O);if(!U)return;var D=Ue(U);if(D.isProviderFor(v,P))return qe(O),D}}}if(!b(o)&&o.isProviderFor(v,P))return o}function f(v,P){var O=w.get(v),U;return b(O)||(U=O.get(P)),b(U)&&(U=E(v,P),b(U)||(b(O)&&(O=new g,w.set(v,O)),O.set(P,U))),U}function h(v){if(b(v))throw new TypeError;return a===v||u===v||!b(c)&&c.has(v)}function m(v,P,O){if(!h(O))throw new Error("Metadata provider not registered.");var U=f(v,P);if(U!==O){if(!b(U))return!1;var D=w.get(v);b(D)&&(D=new g,w.set(v,D)),D.set(P,O)}return!0}}function Vt(){var o;return!b(I)&&$(t.Reflect)&&Object.isExtensible(t.Reflect)&&(o=t.Reflect[I]),b(o)&&(o=Yt()),!b(I)&&$(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,I,{enumerable:!1,configurable:!1,writable:!1,value:o}),o}function Jt(o){var a=new k,u={isProviderFor:function(h,m){var v=a.get(h);return b(v)?!1:v.has(m)},OrdinaryDefineOwnMetadata:L,OrdinaryHasOwnMetadata:w,OrdinaryGetOwnMetadata:C,OrdinaryOwnMetadataKeys:E,OrdinaryDeleteMetadata:f};return x.registerProvider(u),u;function c(h,m,v){var P=a.get(h),O=!1;if(b(P)){if(!v)return;P=new g,a.set(h,P),O=!0}var U=P.get(m);if(b(U)){if(!v)return;if(U=new g,P.set(m,U),!o.setProvider(h,m,u))throw P.delete(m),O&&a.delete(h),new Error("Wrong provider for target.")}return U}function w(h,m,v){var P=c(m,v,!1);return b(P)?!1:Oe(P.has(h))}function C(h,m,v){var P=c(m,v,!1);if(!b(P))return P.get(h)}function L(h,m,v,P){var O=c(v,P,!0);O.set(h,m)}function E(h,m){var v=[],P=c(h,m,!1);if(b(P))return v;for(var O=P.keys(),U=Ce(O),D=0;;){var De=Le(U);if(!De)return v.length=D,v;var Zt=Ue(De);try{v[D]=Zt}catch(en){try{qe(U)}finally{throw en}}D++}}function f(h,m,v){var P=c(m,v,!1);if(b(P)||!P.delete(h))return!1;if(P.size===0){var O=a.get(m);b(O)||(O.delete(v),O.size===0&&a.delete(O))}return!0}}function Wt(o){var a=o.defineMetadata,u=o.hasOwnMetadata,c=o.getOwnMetadata,w=o.getOwnMetadataKeys,C=o.deleteMetadata,L=new k,E={isProviderFor:function(f,h){var m=L.get(f);return!b(m)&&m.has(h)?!0:w(f,h).length?(b(m)&&(m=new T,L.set(f,m)),m.add(h),!0):!1},OrdinaryDefineOwnMetadata:a,OrdinaryHasOwnMetadata:u,OrdinaryGetOwnMetadata:c,OrdinaryOwnMetadataKeys:w,OrdinaryDeleteMetadata:C};return E}function Q(o,a,u){var c=x.getProvider(o,a);if(!b(c))return c;if(u){if(x.setProvider(o,a,A))return A;throw new Error("Illegal state.")}}function zt(){var o={},a=[],u=(function(){function E(f,h,m){this._index=0,this._keys=f,this._values=h,this._selector=m}return E.prototype["@@iterator"]=function(){return this},E.prototype[l]=function(){return this},E.prototype.next=function(){var f=this._index;if(f>=0&&f<this._keys.length){var h=this._selector(this._keys[f],this._values[f]);return f+1>=this._keys.length?(this._index=-1,this._keys=a,this._values=a):this._index++,{value:h,done:!1}}return{value:void 0,done:!0}},E.prototype.throw=function(f){throw this._index>=0&&(this._index=-1,this._keys=a,this._values=a),f},E.prototype.return=function(f){return this._index>=0&&(this._index=-1,this._keys=a,this._values=a),{value:f,done:!0}},E})(),c=(function(){function E(){this._keys=[],this._values=[],this._cacheKey=o,this._cacheIndex=-2}return Object.defineProperty(E.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),E.prototype.has=function(f){return this._find(f,!1)>=0},E.prototype.get=function(f){var h=this._find(f,!1);return h>=0?this._values[h]:void 0},E.prototype.set=function(f,h){var m=this._find(f,!0);return this._values[m]=h,this},E.prototype.delete=function(f){var h=this._find(f,!1);if(h>=0){for(var m=this._keys.length,v=h+1;v<m;v++)this._keys[v-1]=this._keys[v],this._values[v-1]=this._values[v];return this._keys.length--,this._values.length--,pe(f,this._cacheKey)&&(this._cacheKey=o,this._cacheIndex=-2),!0}return!1},E.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=o,this._cacheIndex=-2},E.prototype.keys=function(){return new u(this._keys,this._values,w)},E.prototype.values=function(){return new u(this._keys,this._values,C)},E.prototype.entries=function(){return new u(this._keys,this._values,L)},E.prototype["@@iterator"]=function(){return this.entries()},E.prototype[l]=function(){return this.entries()},E.prototype._find=function(f,h){if(!pe(this._cacheKey,f)){this._cacheIndex=-1;for(var m=0;m<this._keys.length;m++)if(pe(this._keys[m],f)){this._cacheIndex=m;break}}return this._cacheIndex<0&&h&&(this._cacheIndex=this._keys.length,this._keys.push(f),this._values.push(void 0)),this._cacheIndex},E})();return c;function w(E,f){return E}function C(E,f){return f}function L(E,f){return[E,f]}}function Qt(){var o=(function(){function a(){this._map=new g}return Object.defineProperty(a.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),a.prototype.has=function(u){return this._map.has(u)},a.prototype.add=function(u){return this._map.set(u,u),this},a.prototype.delete=function(u){return this._map.delete(u)},a.prototype.clear=function(){this._map.clear()},a.prototype.keys=function(){return this._map.keys()},a.prototype.values=function(){return this._map.keys()},a.prototype.entries=function(){return this._map.entries()},a.prototype["@@iterator"]=function(){return this.keys()},a.prototype[l]=function(){return this.keys()},a})();return o}function Xt(){var o=16,a=_.create(),u=c();return(function(){function f(){this._key=c()}return f.prototype.has=function(h){var m=w(h,!1);return m!==void 0?_.has(m,this._key):!1},f.prototype.get=function(h){var m=w(h,!1);return m!==void 0?_.get(m,this._key):void 0},f.prototype.set=function(h,m){var v=w(h,!0);return v[this._key]=m,this},f.prototype.delete=function(h){var m=w(h,!1);return m!==void 0?delete m[this._key]:!1},f.prototype.clear=function(){this._key=c()},f})();function c(){var f;do f="@@WeakMap@@"+E();while(_.has(a,f));return a[f]=!0,f}function w(f,h){if(!n.call(f,u)){if(!h)return;Object.defineProperty(f,u,{value:_.create()})}return f[u]}function C(f,h){for(var m=0;m<h;++m)f[m]=Math.random()*255|0;return f}function L(f){if(typeof Uint8Array=="function"){var h=new Uint8Array(f);return typeof crypto<"u"?crypto.getRandomValues(h):typeof msCrypto<"u"?msCrypto.getRandomValues(h):C(h,f),h}return C(new Array(f),f)}function E(){var f=L(o);f[6]=f[6]&79|64,f[8]=f[8]&191|128;for(var h="",m=0;m<o;++m){var v=f[m];(m===4||m===6||m===8)&&(h+="-"),v<16&&(h+="0"),h+=v.toString(16).toLowerCase()}return h}}function he(o){return o.__=void 0,delete o.__,o}})})(je||(je={}))});S();var Ks=te(He(),1),j=te(require("process"),1),Nt=require("ioredis");S();var hn=te(require("os"),1),gn=te(require("path"),1),mn=require("url"),yn=require("util");S();var fn=require("crypto");S();S();S();S();S();var H=class extends Error{};var vn=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Fe(s){let e=s?.code;return typeof e=="string"&&vn.has(e)}function ne(s,e){try{return s.write(e),!0}catch(t){if(Fe(t))return!1;throw t}}function Ke(s){let e={stdout:!1,stderr:!1},t=[];for(let n of["stdout","stderr"]){let r=s.streams[n],i=l=>{Fe(l)&&(e[n]=!0);let p=l?.code;try{s.note(`${new Date().toISOString()} urun compat: process.${n} died (${String(p??(l instanceof Error?l.message:l))}) \u2014 the terminal is gone; launcher output continues in this log only
3
+ `)}catch{}};r.on("error",i),t.push([r,i])}return{isDead:n=>e[n],uninstall:()=>{for(let[n,r]of t)n.off("error",r)}}}S();S();var ge=`
4
4
  local slot, retired, meta = KEYS[1], KEYS[2], KEYS[3]
5
5
  local key, gen, now = ARGV[1], tonumber(ARGV[2]), ARGV[3]
6
6
  -- The session-as-routing-identity schema (docs/pooler-session-registry.md
@@ -298,9 +298,9 @@ redis.call('HSET', slot,
298
298
  'cacheGen', ARGV[5],
299
299
  'capabilities', ARGV[6])
300
300
  return 'ok'
301
- `;var V=class extends Error{constructor(t,n,r){super(`session registry violation (${t}): ${n} ${JSON.stringify(r)}`);this.op=t;this.verdict=n;this.context=r;this.name="RegistryViolation"}op;verdict;context},vn=100,ot=s=>{let e={attached:0,queued:0,paused:0,retired:0,ended:0,inflight:0};for(let t of s.split(",")){if(t==="")continue;let[n,r]=t.split("=");n in e&&(e[n]=Number(r))}return e},wn=s=>(s===""?[]:s.split(`
302
- `)).map(e=>{let[t,n,r,o,l]=e.split("|");return{key:t,state:n,inFlight:Number(r),gen:Number(o),sessionId:l}});function F(s){let e=s.split(":"),t=e[e.length-1],n=e[e.length-2];if(n!==void 0&&/^\d+$/.test(n)&&/^\d+$/.test(t))return{base:e.slice(0,-1).join(":"),index:Number(n),gen:Number(t)};if(!/^\d+$/.test(t))throw new Error(`session registry: malformed slot key "${s}" (expected decision:{replica}:{index}[:{gen}])`);return{base:s,index:Number(t),gen:0}}var K=()=>String(Date.now()),re=class{constructor(e,t){this.evalFn=e;this.pool=t}evalFn;pool;keys(e,t=!0,n=!0){let{base:r}=F(e),o=[`sreg:${this.pool}:slot:${e}`];return t&&o.push(`sreg:${this.pool}:gen:${r}`),n&&o.push(`sreg:${this.pool}:retired`),o.push(`sreg:${this.pool}:meta`),o}async run(e,t,n,r,o){let l=await this.evalFn.eval(t,n,r);if(l.startsWith("reject:"))throw new V(e,l,{pool:this.pool,...o})}mint(e){let{gen:t}=F(e);return this.run("mint",ge,this.keys(e,!1,!0),[e,t,K()],{slotKey:e,gen:t})}mintWith(e,t){let{gen:n}=F(e);return this.run("mint",ge,this.keys(e,!1,!0),[e,n,K(),t.model,t.capabilities??"",t.cacheNs],{slotKey:e,gen:n,cacheNs:t.cacheNs})}attachWithEpoch(e,t,n){let{gen:r}=F(e);return this.run("attach",me,this.keys(e),[e,r,t,K(),n],{slotKey:e,gen:r,sessionId:t,observedEpoch:n})}publish(e,t,n){return this.run("publish",st,this.keys(e,!1,!1),[e,t,n.maxConcurrent,n.queueDepth,n.cacheGen,n.capabilities??""],{slotKey:e,observedEpoch:t})}attach(e,t){let{gen:n}=F(e);return this.run("attach",me,this.keys(e),[e,n,t,K()],{slotKey:e,gen:n,sessionId:t})}detach(e,t){return this.run("detach",Be,this.keys(e,!1,!1),[e,t,K()],{slotKey:e,reason:t})}rotate(e,t){let{gen:n}=F(t),r=[...this.keys(e),`sreg:${this.pool}:slot:${t}`];return this.run("rotate",Ye,r,[e,t,n,K()],{oldKey:e,newKey:t,newGen:n})}end(e){return this.run("end",Ve,this.keys(e,!1,!1),[e,K()],{slotKey:e})}lease(e){return this.run("lease",Je,this.keys(e,!1,!1),[e],{slotKey:e})}release(e){return this.run("release",ze,this.keys(e,!1,!1),[e,K()],{slotKey:e})}configure(e,t){return this.run("config",Xe,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}retune(e,t){return this.run("retune",Qe,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}async tuning(){let e=await this.evalFn.eval(We,[`sreg:${this.pool}:meta`],[]),[t,n,r]=e.split("|");return{max:Number(t),inFlightCap:Number(n),configVersion:Number(r)}}async grant(e,t){let n=this.keys(e,!1,!1),r=await this.evalFn.eval(X,n,[e,t.cap,t.configVersion]);if(r==="reject:cap-moved"){let o=await this.tuning();r=await this.evalFn.eval(X,n,[e,o.inFlightCap,o.configVersion])}if(r==="ok")return{granted:!0};if(r==="reject:cap")return{granted:!1,reason:"cap-full"};if(r==="reject:cap-moved")return{granted:!1,reason:"cap-moved"};throw new V("grant",r,{pool:this.pool,slotKey:e})}async grantWithEpoch(e,t){let n=this.keys(e,!1,!1),r=await this.evalFn.eval(X,n,[e,t.cap,t.configVersion,t.epoch]);if(r==="reject:cap-moved"){let o=await this.tuning();r=await this.evalFn.eval(X,n,[e,o.inFlightCap,o.configVersion,t.epoch])}if(r==="ok")return{granted:!0};if(r==="reject:cap")return{granted:!1,reason:"cap-full"};if(r==="reject:cap-moved")return{granted:!1,reason:"cap-moved"};if(r==="reject:epoch")return{granted:!1,reason:"epoch-stale"};throw new V("grant",r,{pool:this.pool,slotKey:e})}async snapshot(){let e=[],t=null,n="0";do{let r=await this.snapshotPage(n,vn);t===null&&(t=r.counts),e.push(...r.slots),n=r.cursor}while(n!=="0");return{counts:t,slots:e}}async counts(){let e=await this.evalFn.eval(et,[`sreg:${this.pool}:meta`],[]);return ot(e)}async snapshotPage(e,t){let n=`sreg:${this.pool}:slot:`,r=await this.evalFn.eval(Ze,[`sreg:${this.pool}:meta`],[n,e,t]),[o,l,p]=r.split("#");return{cursor:o,counts:ot(l??""),slots:wn(p??"")}}async readRecords(e){if(e.length===0)return[];let t=`sreg:${this.pool}:slot:`,n=await this.evalFn.eval(tt,[],e.map(r=>t+r));return(n===""?[]:n.split(`
303
- `)).map(r=>{let[o,l]=r.split("|");return{state:o,inFlight:Number(l)}})}async generation(e){let{base:t}=F(e),n=await this.evalFn.eval(nt,[`sreg:${this.pool}:gen:${t}`],[]);return Number(n)}async record(e){let n=(await this.evalFn.eval(rt,[`sreg:${this.pool}:slot:${e}`],[])).split("|"),r=n[0],o=n[1]===""||n[1]===void 0?void 0:n[1],l=n.slice(2).join("|");return{state:r,sessionId:o,lastReason:l===""?void 0:l}}};S();var at=require("bullmq"),lt=require("crypto"),_n=3e4,Sn=60,bn=1e3;function it(s){let e;try{e=JSON.parse(s)}catch{return null}if(typeof e!="object"||e===null||!("proxy_url"in e))return null;let t=e;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0}}function ut(s){let e=s.now??Date.now,t=new Map,n=new Map,r=new Map,o=new Map,l=new Set,p=d=>{let g=t.get(d);return g||(g=s.queueFor?.(d)??y(d),t.set(d,g)),g},y=d=>{let g=s.redis,T=new at.Queue(d,{prefix:"bull:dispatch",connection:g});return{add:(k,I,x)=>T.add(k,I,x),reassertWaiting:async k=>{let x=(await T.getJobs(["waiting"])).filter(A=>A.data?.session_kind==="lane").sort((A,N)=>A.timestamp-N.timestamp);if(x.length===0)return{found:0};for(let A of x)try{await A.updateData({...A.data,demand_reaffirmed_at_ms:k,...s.mintRuntimeToken?{runtime_token:s.mintRuntimeToken(String(A.data.session_id))}:{}})}catch{}for(let A of x.slice(1))try{await A.remove()}catch{}return{found:x.length}},close:()=>T.close()}},R=async d=>{let g=await s.redis.hgetall(`lanes:${d}`),T=[];for(let[x,A]of Object.entries(g)){let N=it(A);N&&N.proxy_url===s.docHostUrl&&T.push(x)}if(T.length===0)return[];let k=await s.redis.mget(...T.map(x=>`lane_hosts:${x}`)),I=[];return T.forEach((x,A)=>{let N=k[A];N&&I.push({laneId:x,host:N})}),I},_=async(d,g)=>{let T=n.get(d)??0,k=e();if(k-T<_n)return;n.set(d,k);let I=p(d);if((await I.reassertWaiting(e()).catch(N=>{throw n.delete(d),N})).found>0){o.set(g??"",(o.get(g??"")??0)+1),s.onEvent?.({kind:"lane_demand_reaffirmed",pool:d,model:g});return}let A=`lane-${(0,lt.randomUUID)().replaceAll("-","")}`;await I.add("session",{session_id:A,logical_id:A,incarnation:k,session_kind:"lane",lane_id:A,session_server_url:s.docHostUrl,proxy_url:s.docHostUrl,session_idle_timeout_seconds:Sn,thread_key:"lane",demand_reaffirmed_at_ms:e(),...s.mintRuntimeToken?{runtime_token:s.mintRuntimeToken(A)}:{}},{jobId:`${A}#${k}`,attempts:3}),r.set(g??"",(r.get(g??"")??0)+1),s.onEvent?.({kind:"lane_demand_enqueued",pool:d,model:g})};return{async pick({pool:d,model:g,holdMs:T=0}){l.add(d);let k=async()=>{try{await _(d,g)}catch(N){n.delete(d),s.onEvent?.({kind:"lane_demand_failed",pool:d,model:g,reason:N instanceof Error?N.message:String(N)})}},I=async()=>{try{return await R(d)}catch{return[]}},x=await I();if(x.length>0)return x;await k();let A=e()+T;for(;e()<A;){if(await new Promise(N=>setTimeout(N,bn)),x=await I(),x.length>0)return x;await k()}return[]},async status(){let d=[...l].sort();return Promise.all(d.map(async g=>{let T=[];try{let k=await s.redis.hgetall(`lanes:${g}`),I=Object.keys(k),x=I.length===0?[]:await s.redis.mget(...I.map(N=>`lane_hosts:${N}`)),A=e();T=I.map((N,de)=>{let ee=k[N],Y=ee===void 0?null:it(ee);return{laneId:N,occupantId:Y?.occupant_id??"",capacity:Y?.capacity??0,heartbeatAgeMs:Y===null?null:A-Y.heartbeat_ms,advertisedHere:Y?.proxy_url===s.docHostUrl,hosted:!!x[de]}})}catch{}return{pool:g,lanes:T,lastDemandAt:n.get(g)??null}}))},demandCounters(){return[...new Set([...r.keys(),...o.keys()])].sort().map(g=>({model:g,enqueued:r.get(g)??0,reaffirmed:o.get(g)??0}))},async close(){await Promise.all([...t.values()].map(d=>d.close().catch(()=>{}))),t.clear()}}}S();var Z=require("crypto");var ct="runtime:lease",Rn="lane:join";var En=120,pt=1440*60;function dt(s){return Buffer.from(s).toString("base64url")}function kn(s,e,t){let n=dt(JSON.stringify(s)),r=dt(JSON.stringify(e)),o=(0,Z.createHmac)("sha256",t).update(`${n}.${r}`).digest("base64url");return`${n}.${r}.${o}`}function ft(s,e,t,n=En,r=Rn){return Pn(s,t,n,r,e)}function Pn(s,e,t,n,r){let o=Math.floor(Date.now()/1e3);return kn({alg:"HS256",typ:"JWT"},{session_id:s,aud:"sfu",sub:s,scope:n,...r?{tenant:r}:{},iat:o,exp:o+t,jti:(0,Z.randomUUID)()},e)}S();var se=class{records=new Map;add(e){return this.records.set(e.request_id,{request:e,sessionId:"",attempt:1,dispatched:!1}),Promise.resolve()}dispatched(e,t,n){let r=this.records.get(e);return r&&(r.sessionId=t,r.attempt=n,r.dispatched=!0),Promise.resolve()}requeue(e,t){let n=this.records.get(e);return n&&(n.dispatched=!1,n.sessionId="",n.attempt=t),Promise.resolve()}finish(e){return this.records.delete(e),Promise.resolve()}queued(e,t){return Promise.resolve([...this.records.values()].filter(n=>!n.dispatched&&n.request.region===e&&n.request.model===t).map(n=>n.request))}inflight(){return Promise.resolve([...this.records.values()].filter(e=>e.dispatched).map(e=>({request:e.request,sessionId:e.sessionId,attempt:e.attempt})))}};S();S();var ae=s=>`${s.systemPrompt??""}\0${s.firstMessage??""}`;function ye(s){return s.promptCacheKey!==void 0&&s.promptCacheKey!==""?`k:${s.promptCacheKey}`:s.sessionHeader!==void 0&&s.sessionHeader!==""?`h:${s.sessionHeader}`:`p:${Tn(ae(s))}`}function Tn(s){let e=2166136261;for(let t=0;t<s.length;t++)e^=s.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}var ht=512,In=4096,oe=8,ie=class{root={children:new Map,sessions:new Map};nodes=1;insert(e,t,n){let r=e.slice(0,ht),o=this.root;for(let l=0;l<r.length;l+=oe){let p=r.slice(l,l+oe),y=o.children.get(p);if(!y){if(this.nodes>=In)return;y={children:new Map,sessions:new Map},o.children.set(p,y),this.nodes+=1}y.sessions.set(t,n),o=y}}match(e,t){let n=e.slice(0,ht),r=this.root,o=null,l=0,p=0;for(;;){let y=null,R=-1;for(let[g,T]of r.sessions)t.has(g)&&(T>R||T===R&&y!==null&&g<y)&&(y=g,R=T);if(y!==null&&(o={sessionId:y,depth:l}),p>=n.length)break;let _=n.slice(p,p+oe),d=r.children.get(_);if(!d)break;r=d,l+=_.length,p+=oe}return o}forget(e){let t=n=>{n.sessions.delete(e);for(let r of n.children.values())t(r)};t(this.root)}size(){return this.nodes}};function gt(s,e,t,n){if(e.length===0)return null;let r=new Map(e.map(_=>[_.sessionId,_])),o=_=>{let d=r.get(_);return d!==void 0&&d.backlog<n.backlogThreshold},l=new Set(r.keys()),p=n.sticky.get(ye(s));if(p!==void 0&&o(p))return{sessionId:p,reason:"sticky"};let y=t.match(ae(s),l);if(y!==null&&o(y.sessionId))return{sessionId:y.sessionId,reason:"prefix"};let R=null;for(let _ of e)(R===null||_.backlog<R.backlog||_.backlog===R.backlog&&_.sessionId<R.sessionId)&&(R=_);return R===null?null:{sessionId:R.sessionId,reason:"load"}}S();var mt="llm",ve="requests",xn="llm-resp",we=(s,e,t,n=0)=>`decision:pooler-${s}-${e}`.replaceAll(":","-")+`:${t}`+(n>0?`:${n}`:""),_e=s=>{let{base:e,gen:t}=F(s);return`${e}:${t+1}`},yt=s=>`${xn}:${s}`,vt="free_slots",Se="inflight",be="live_seen",B=class extends Error{constructor(t,n){super(`reply stream for ${t} dropped before its terminal chunk${n?`: ${n}`:""}`);this.requestId=t;this.name="ReplyStreamDropped"}requestId};var wt=new Set(["registry_error","failed","mint_failed","scaled_down","live_mark_failed"]),An=6e4,On=33e4,Nn=2,Mn=8,$n=5e3,Cn=1e4,Un=6e4,Ln=5e3,qn={idle:"bound",queued:"bound",unavailable:"bound",provisioning:"bound",waiting_for_capacity:"bound",connecting:"bound",live:"bound",degraded:"bound",paused:"unbound",error:"unbound",unknown:"unbound"},le=class s{pools=new Map;now;queueDeadlineMs;silenceDeadlineMs;maxAttempts;backlogThreshold;mint;limits;scaleUpWaitMs;mintCooldownMs;sessionIdleTtlMs;idleSweepMs;journal;registry;onEvent;closed=!1;sweepTimer=null;constructor(e){this.journal=e.journal,this.registry=e.registry??null,this.now=e.now??Date.now,this.queueDeadlineMs=e.queueDeadlineMs??An,this.silenceDeadlineMs=e.silenceDeadlineMs??On,this.maxAttempts=e.maxAttempts??Nn,this.backlogThreshold=e.backlogThreshold??Mn,this.mint=e.mint,this.limits=e.limits??[],this.scaleUpWaitMs=e.scaleUpWaitMs??$n,this.mintCooldownMs=e.mintCooldownMs??Cn,this.sessionIdleTtlMs=e.sessionIdleTtlMs??Un,this.idleSweepMs=e.idleSweepMs??Ln,this.onEvent=e.onEvent??(()=>{}),(this.mint!==void 0||this.limits.length>0)&&this.armSweep()}armSweep(){this.sweepTimer=setInterval(()=>this.sweep(),this.idleSweepMs),this.sweepTimer.unref?.()}sweep(){if(!this.closed)for(let e of this.pools.values()){let t=this.limitsFor(e);if(t===null)continue;this.evictUnbound(e);let n=e.queue.length===0;e.sessions.length<t.max&&this.queuePressure(e)?this.tryMint(e,"queue_pressure"):e.sessions.length<t.min&&this.tryMint(e,"min_floor"),n&&e.sessions.length>t.min&&this.scaleDownOldestIdle(e,t)}}servable(e){return e.gone()!==null?!1:qn[e.phaseName()]==="bound"?!0:!e.everLive()}evictUnbound(e){for(let t of[...e.sessions]){if(this.servable(t))continue;let n=t.phaseName();this.onEvent({kind:"sweep_evicted",pool:this.key(e.region,e.model),sessionId:t.sessionId,phase:n}),this.evict(e,t,new H(`the pool entry for ${t.sessionId} has no usable compute binding (phase "${n}") \u2014 the sweep's servability reconcile evicts it; the named session itself stays parked and attachable`))}}limitsFor(e){return this.limits.find(t=>t.region===e.region&&t.model===e.model)??null}queuePressure(e){if(e.queue.length===0)return!1;let t=this.now();return e.queue.some(n=>t-n.queuedAt>=this.scaleUpWaitMs)}tryMint(e,t){if(this.mint===void 0||this.closed||e.minting)return;let n=this.limitsFor(e);if(n===null||e.sessions.length>=n.max)return;let r=this.now();r-e.lastMintAt<this.mintCooldownMs||(e.lastMintAt=r,e.minting=!0,this.mintOnce(e,t).finally(()=>{e.minting=!1}))}async mintOnce(e,t){if(this.mint===void 0)return!1;let n=e.mintSeq++,r;try{r=await this.claimSlot(e.region,e.model,n)}catch(o){if(t==="boot_floor")throw o;return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:o instanceof Error?o.message:String(o)}),!1}try{let o=await this.mint(e.region,e.model,r);return this.closed?(await o.end().catch(()=>{}),!1):(this.addSession(e.region,e.model,o,r),this.onEvent({kind:"minted",pool:this.key(e.region,e.model),sessionId:o.sessionId,reason:t}),!0)}catch(o){return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:o instanceof Error?o.message:String(o)}),!1}}async warm(){for(let e of this.limits){let t=this.poolOf(e.region,e.model);t.minting=!0;try{for(;t.sessions.length<e.min&&await this.mintOnce(t,"boot_floor"););}finally{t.minting=!1}}}scaleDownOldestIdle(e,t){let n=this.now();for(let r of e.sessions){if(r.gone()!==null||[...e.records.values()].some(R=>R.session===r&&R.phase==="dispatched")||n-(e.lastActivity.get(r)??n)<this.sessionIdleTtlMs)continue;let p=e.sessions.indexOf(r);if(p===-1)continue;e.sessions.splice(p,1),this.detachSignals(e,r),e.radix.forget(r.sessionId),e.lastActivity.delete(r);let y=e.slotKeys.get(r.sessionId);y!==void 0&&(e.slotKeys.delete(r.sessionId),this.registryCall("end",y,()=>this.registry?.end(y))),this.onEvent({kind:"scaled_down",pool:this.key(e.region,e.model),sessionId:r.sessionId,sessions:e.sessions.length,min:t.min}),r.end().catch(R=>{this.onEvent({kind:"scaled_down_end_failed",pool:this.key(e.region,e.model),sessionId:r.sessionId,reason:R instanceof Error?R.message:String(R)})});return}}static poolKey(e,t){return`${e}:${t}`}async claimSlot(e,t,n){let r=we(e,t,n);if(this.registry===null)return r;for(let o=0;;o++){let l=await this.registry.generation(r),p=we(e,t,n,l),{state:y,sessionId:R,lastReason:_}=await this.registry.record(p);if(y==="none"||y==="paused"&&R===void 0&&_===void 0)try{return await this.registry.mint(p),p}catch(d){this.rethrowUnlessClaimRace(d,o);continue}else{let d=_e(p);try{await this.registry.rotate(p,d),await this.registry.mint(d)}catch(g){this.rethrowUnlessClaimRace(g,o);continue}return this.onEvent({kind:"slot_rotated",pool:this.key(e,t),slotKey:p,successor:d,reason:y==="paused"?"boot claim over an evicted slot's dead session":`boot claim over a previous pod's ${y} record`}),d}}}static CLAIM_RACE_VERDICTS=new Set(["reject:double-rotate","reject:generation-monotone","reject:retired-corpse-reuse","reject:mint-queued","reject:mint-attached"]);static CLAIM_RACE_ATTEMPTS=3;rethrowUnlessClaimRace(e,t){if(!(t+1<s.CLAIM_RACE_ATTEMPTS&&e instanceof V&&s.CLAIM_RACE_VERDICTS.has(e.verdict)))throw e}addSession(e,t,n,r){let o=this.poolOf(e,t);o.sessions.push(n),o.lastActivity.set(n,this.now()),o.slotKeys.set(n.sessionId,r),n.whenLive().then(()=>{n.markLiveSeen().catch(l=>{this.onEvent({kind:"live_mark_failed",pool:this.key(e,t),sessionId:n.sessionId,reason:l instanceof Error?l.message:String(l)})}),this.registryCall("attach",r,()=>this.registry?.attach(r,n.sessionId))}).catch(l=>{this.onEvent({kind:"session_never_live",pool:this.key(e,t),sessionId:n.sessionId,reason:l instanceof Error?l.message:String(l)}),this.evict(o,n,l instanceof Error?l:new Error(String(l)))}),o.offs.set(n,[n.onDocChange(()=>{this.pump(o),this.adoptSettled(o)}),n.onGone(l=>this.evict(o,n,l))]),this.onEvent({kind:"session_added",pool:this.key(e,t),sessionId:n.sessionId}),this.start(o).then(()=>this.pump(o))}async start(e){if(!e.needsReconcile)return;e.needsReconcile=!1;let t=this.key(e.region,e.model);for(let n of await this.journal.inflight()){if(n.request.region!==e.region||n.request.model!==e.model)continue;let r=e.sessions.find(l=>l.sessionId===n.sessionId),o=r?.snapshot().inflight[n.request.request_id];if(r!==void 0){if(o?.status==="done"||o?.status==="error"){await this.journal.finish(n.request.request_id);continue}e.records.set(n.request.request_id,{request:n.request,sink:null,attempt:n.attempt,tried:new Set([n.sessionId]),session:r,phase:"dispatched",streamed:!1,deadlineAt:Number.POSITIVE_INFINITY,queueTimer:null,silenceTimer:null,queuedAt:this.now()}),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:n.request.request_id,sessionId:n.sessionId})}}for(let n of await this.journal.queued(e.region,e.model))await this.journal.finish(n.request_id),this.onEvent({kind:"reconciled_caller_gone",pool:t,requestId:n.request_id});for(let n of e.sessions){let r=n.snapshot();for(let[o,l]of Object.entries(r.inflight)){if(l.status==="done"||l.status==="error"||e.records.has(o))continue;let p={request:{request_id:o,region:e.region,model:e.model,affinity:{},payload:{},streaming:!1,enqueuedAt:0},sink:null,attempt:l.attempt,tried:new Set([n.sessionId]),session:n,phase:"dispatched",streamed:!1,deadlineAt:Number.POSITIVE_INFINITY,queueTimer:null,silenceTimer:null,queuedAt:this.now()};e.records.set(o,p),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:o,sessionId:n.sessionId})}}this.pump(e)}async submit(e,t){if(this.closed){t.head(),t.fail({status:503,code:"draining",message:"pooler is shutting down",retryAfterSeconds:5});return}let n=this.poolOf(e.region,e.model);await this.start(n);let r={request:e,sink:t,attempt:1,tried:new Set,session:null,phase:"queued",streamed:!1,deadlineAt:this.now()+this.queueDeadlineMs,queueTimer:null,silenceTimer:null,queuedAt:this.now()};n.records.set(e.request_id,r),n.queue.push(r),await this.journal.add(e),t.head(),this.armQueueTimer(n,r),this.onEvent({kind:"enqueued",pool:this.key(e.region,e.model),requestId:e.request_id}),this.pump(n),r.phase!=="finished"&&await new Promise(o=>{r.settle=o})}abandon(){this.closed=!0,this.sweepTimer!==null&&(clearInterval(this.sweepTimer),this.sweepTimer=null);for(let e of this.pools.values()){for(let t of e.records.values())this.clearTimers(t);for(let t of e.offs.values())for(let n of t)n();e.offs.clear(),e.sessions.length=0,e.queue.length=0,e.records.clear(),e.lastActivity.clear()}this.pools.clear()}async close(){this.closed=!0,this.sweepTimer!==null&&(clearInterval(this.sweepTimer),this.sweepTimer=null);for(let e of this.pools.values()){for(let n of e.records.values())this.clearTimers(n),n.phase!=="finished"&&this.settle(n,{status:503,code:"draining",message:"pooler is shutting down",retryAfterSeconds:5});for(let n of e.offs.values())for(let r of n)r();e.offs.clear(),e.lastActivity.clear();for(let n of e.slotKeys.values())this.registryCall("rotate",n,()=>this.registry?.rotate(n,_e(n)));e.slotKeys.clear();let t=e.sessions.splice(0);await Promise.allSettled(t.map(n=>n.end()))}this.pools.clear()}poolOf(e,t){let n=s.poolKey(e,t),r=this.pools.get(n);return r||(r={region:e,model:t,sessions:[],records:new Map,queue:[],sticky:new Map,radix:new ie,offs:new Map,slotKeys:new Map,needsReconcile:!0,lastMintAt:0,minting:!1,mintSeq:0,lastActivity:new Map},this.pools.set(n,r)),r}key(e,t){return s.poolKey(e,t)}registryCall(e,t,n){let r=n();r!==void 0&&r.catch(o=>{this.onEvent({kind:"registry_error",reason:`${e}: ${o instanceof Error?o.message:String(o)}`,slotKey:t})})}creditFor(e,t){let n=t.snapshot(),r=0;for(let o of e.records.values()){if(o.session!==t||o.phase!=="dispatched")continue;let l=n.inflight[o.request.request_id];(l===void 0||l.status===void 0)&&(r+=1)}return Math.max(0,n.freeSlots-r)}backlogOf(e,t){let n=0;for(let r of e.records.values())r.session===t&&r.phase==="dispatched"&&(n+=1);return n}pump(e){if(this.closed)return;let t=!0;for(;t&&e.queue.length>0&&e.sessions.length>0;){t=!1;for(let n=0;n<e.queue.length;n++){let r=e.queue[n],o=this.pickFor(e,r);if(o!==null){e.queue.splice(n,1),this.dispatch(e,o,r),t=!0;break}}}e.queue.length>0&&this.queuePressure(e)&&this.tryMint(e,"queue_pressure")}pickFor(e,t){let n=e.sessions.filter(l=>this.servable(l)&&!t.tried.has(l.sessionId)&&this.creditFor(e,l)>0).map(l=>({sessionId:l.sessionId,backlog:this.backlogOf(e,l)})),r=gt(t.request.affinity,n,e.radix,{backlogThreshold:this.backlogThreshold,sticky:e.sticky});if(r===null)return null;let o=e.sessions.find(l=>l.sessionId===r.sessionId)??null;return o!==null&&this.onEvent({kind:"picked",pool:this.key(e.region,e.model),requestId:t.request.request_id,sessionId:o.sessionId,reason:r.reason}),o}dispatch(e,t,n){n.phase="dispatched",n.session=t,n.tried.add(t.sessionId),e.lastActivity.set(t,this.now()),this.clearTimer(n,"queue"),n.deadlineAt=this.now()+this.silenceDeadlineMs;let r={request_id:n.request.request_id,consumer_id:n.request.request_id,payload:n.request.payload,stream:n.request.streaming};(async()=>{let o=t.reply(r.request_id);try{await t.markInflight(r.request_id,n.attempt),await t.push(r)}catch(y){this.lost(e,n,y);return}await this.journal.dispatched(n.request.request_id,t.sessionId,n.attempt);let l=ye(n.request.affinity);e.sticky.set(l,t.sessionId),e.radix.insert(ae(n.request.affinity),t.sessionId,this.now()),this.onEvent({kind:"dispatched",pool:this.key(e.region,e.model),requestId:n.request.request_id,sessionId:t.sessionId,attempt:n.attempt}),this.armSilenceTimer(e,n);let p=e.slotKeys.get(t.sessionId);p!==void 0&&this.registryCall("lease",p,()=>this.registry?.lease(p)),this.consume(e,n,o)})()}async consume(e,t,n){if(t.session!==null)try{for await(let r of n){if(t.phase==="finished")return;this.armSilenceTimer(e,t),t.streamed=!0;let o=t.sink;if(o!==null&&(await o.chunk(r),r.t==="response"||r.t==="error"||r.t==="end")){await this.finish(e,t);return}}this.lost(e,t,new B(t.request.request_id,"iterator ended without a terminal chunk"))}catch(r){this.lost(e,t,r)}}lost(e,t,n){if(t.phase==="finished")return;this.clearTimers(t);let r=n instanceof Error?n.message:String(n);this.onEvent({kind:"lost",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt,reason:r}),n instanceof H&&t.session!==null&&this.evict(e,t.session,n);let o=e.sessions.some(l=>this.servable(l)&&!t.tried.has(l.sessionId));if(!t.streamed&&t.attempt<this.maxAttempts&&o){t.attempt+=1,t.phase="queued",t.session=null,t.deadlineAt=this.now()+this.queueDeadlineMs,t.queuedAt=this.now(),e.queue.unshift(t),this.journal.requeue(t.request.request_id,t.attempt).catch(()=>{}),this.armQueueTimer(e,t),this.onEvent({kind:"retry",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt}),this.pump(e);return}this.settle(t,{status:502,code:t.streamed?"upstream_stream_lost":"upstream_error",message:t.streamed?"the upstream reply stream was lost after the response began":"the upstream reply stream was lost before the response began",retryAfterSeconds:1})}async finish(e,t){this.clearTimers(t),t.phase="finished",t.session!==null&&e.lastActivity.set(t.session,this.now()),this.releaseSlot(e,t,"release"),await this.journal.finish(t.request.request_id),t.session!==null&&t.session.clearRequest(t.request.request_id);let n=t.sink;n!==null&&n.done(),this.release(e,t),this.onEvent({kind:"finished",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt}),this.settlePromise(t)}settle(e,t){this.clearTimers(e);let n=e.session===null?void 0:this.poolOf(e.request.region,e.request.model).slotKeys.get(e.session.sessionId);n!==void 0&&this.registryCall("release",n,()=>this.registry?.release(n)),e.phase="finished",e.session!==null&&this.poolOf(e.request.region,e.request.model).lastActivity.set(e.session,this.now()),this.journal.finish(e.request.request_id).catch(()=>{}),e.session!==null&&e.session.clearRequest(e.request.request_id);let r=e.sink;r!==null&&r.fail(t),this.onEvent({kind:"failed",requestId:e.request.request_id,reason:t.code}),this.settlePromise(e)}settlePromise(e){let t=e.settle;e.settle=void 0,t?.()}release(e,t){e.records.get(t.request.request_id)===t&&e.records.delete(t.request.request_id)}releaseSlot(e,t,n){if(t.session===null)return;let r=e.slotKeys.get(t.session.sessionId);r!==void 0&&this.registryCall(n,r,()=>n==="release"?this.registry?.release(r):this.registry?.detach(r,"session evicted"))}detachSignals(e,t){let n=e.offs.get(t);if(n!==void 0){e.offs.delete(t);for(let r of n)r()}}evict(e,t,n){let r=e.sessions.indexOf(t);if(r===-1)return;e.sessions.splice(r,1),this.detachSignals(e,t),e.lastActivity.delete(t),e.radix.forget(t.sessionId);let o=e.slotKeys.get(t.sessionId);o!==void 0&&(e.slotKeys.delete(t.sessionId),this.registryCall("detach",o,()=>this.registry?.detach(o,n.message)));for(let l of[...e.records.values()])l.session===t&&l.phase!=="finished"&&this.lost(e,l,n)}adoptSettled(e){for(let t of e.sessions){let n=t.snapshot();for(let r of[...e.records.values()]){if(r.sink!==null||r.session!==t)continue;let o=n.inflight[r.request.request_id];(o?.status==="done"||o?.status==="error")&&(this.journal.finish(r.request.request_id).catch(()=>{}),this.release(e,r))}}}armQueueTimer(e,t){this.clearTimer(t,"queue");let n=Math.max(0,t.deadlineAt-this.now());t.queueTimer=setTimeout(()=>{t.phase==="queued"&&(this.onEvent({kind:"queue_timeout",requestId:t.request.request_id}),this.settle(t,{status:429,code:"queue_timeout",message:"no capacity for this model within the wait bound",retryAfterSeconds:30}),e.queue.splice(e.queue.indexOf(t),1))},n),t.queueTimer.unref?.()}armSilenceTimer(e,t){t.silenceTimer===null&&(t.silenceTimer=setTimeout(()=>{t.silenceTimer=null,t.phase==="dispatched"&&this.lost(e,t,new B(t.request.request_id,`silent past ${this.silenceDeadlineMs}ms`))},this.silenceDeadlineMs),t.silenceTimer.unref?.())}clearTimer(e,t){let n=t==="queue"?e.queueTimer:e.silenceTimer;n!==null&&(clearTimeout(n),t==="queue"?e.queueTimer=null:e.silenceTimer=null)}clearTimers(e){this.clearTimer(e,"queue"),this.clearTimer(e,"silence")}stats(){return{pools:[...this.pools.entries()].map(([e,t])=>({pool:e,queued:t.queue.length,inflight:[...t.records.values()].filter(n=>n.phase==="dispatched").length,sessions:t.sessions.length}))}}};S();var Dn="0.0.0.0",_t="serve";var z=(s,e)=>{let t=s[e];if(typeof t!="string"||t==="")throw new Error(`the pooler requires ${e} (external input) \u2014 refusing to start half-configured`);return t},Gn=(s,e)=>{if(s===null||typeof s!="object")throw new Error(`URUN_POOLER_TARGETS[${e}] must be an object`);let t=s,n=p=>{let y=t[p];if(typeof y!="string"||y==="")throw new Error(`URUN_POOLER_TARGETS[${e}].${p} is required`);return y},r=p=>{let y=t[p];if(typeof y!="number"||!Number.isInteger(y))throw new Error(`URUN_POOLER_TARGETS[${e}].${p} must be an integer`);return y},o,l;if(t.sessions!==void 0){let p=t.sessions;if(typeof p!="number"||!Number.isInteger(p)||p<1)throw new Error(`URUN_POOLER_TARGETS[${e}].sessions must be an integer >= 1`);if(t.min!==void 0||t.max!==void 0)throw new Error(`URUN_POOLER_TARGETS[${e}]: give either sessions or {min, max}, never both`);o=p,l=p}else{if(o=r("min"),l=r("max"),o<0)throw new Error(`URUN_POOLER_TARGETS[${e}].min must be >= 0 (0 scales to zero)`);if(l<1)throw new Error(`URUN_POOLER_TARGETS[${e}].max must be >= 1`);if(o>l)throw new Error(`URUN_POOLER_TARGETS[${e}]: min (${String(o)}) must not exceed max (${String(l)})`)}return{region:n("region"),model:n("model"),app:n("app"),fn:typeof t.fn=="string"&&t.fn!==""?t.fn:void 0,min:o,max:l,sharedApp:t.sharedApp===!0}};function St(s){let e=s.PORT,t=e===void 0||e===""?8080:Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw new Error(`PORT must be a valid port number, got ${String(e)}`);let n=z(s,"URUN_BASE_URL"),r=z(s,"URUN_POOLER_TARGETS"),o;try{o=JSON.parse(r)}catch(l){throw new Error(`URUN_POOLER_TARGETS is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!Array.isArray(o)||o.length===0)throw new Error("URUN_POOLER_TARGETS must be a non-empty JSON array");return{port:t,bindHost:Dn,token:z(s,"URUN_POOLER_TOKEN"),baseUrl:n,apiUrl:s.URUN_API_URL!==void 0&&s.URUN_API_URL!==""?s.URUN_API_URL:`${n}/v1`,orgId:z(s,"URUN_ORG_ID"),apiKey:z(s,"URUN_API_KEY"),valkeyUrl:z(s,"URUN_VALKEY_URL"),laneDocHostUrl:(s.URUN_LANE_DOC_HOST_URL??"").trim()||void 0,laneRuntimeKey:(s.URUN_LANE_RUNTIME_KEY??"").trim()||void 0,targets:o.map(Gn)}}S();var Et=require("http"),jn="/pooler/v1/inference",Hn="/readyz",Fn="/metrics",Kn="/pooler/v1/lanes/pick",Bn="/pooler/v1/lanes/status",Yn=1e4,bt=16*1024*1024;function q(s,e,t,n,r){s.headersSent||(r!==void 0&&s.setHeader("retry-after",String(r)),s.writeHead(e,{"content-type":"application/json"}),s.end(JSON.stringify({error:{message:t,type:"pooler_error",code:n}})))}function Vn(s){if(s===null||typeof s!="object")return{reason:"body must be a JSON object"};let e=s;if(typeof e.region!="string"||e.region==="")return{reason:"region is required"};if(typeof e.model!="string"||e.model==="")return{reason:"model is required"};if(typeof e.request_id!="string"||e.request_id==="")return{reason:"request_id is required"};if(e.payload===null||typeof e.payload!="object")return{reason:"payload must be an object"};let t=e.affinity??{};if(t===null||typeof t!="object")return{reason:"affinity must be an object"};let n=t,r=o=>typeof o=="string"&&o!==""?o:void 0;return{value:{streaming:e.streaming===!0,request:{request_id:e.request_id,region:e.region,model:e.model,payload:e.payload,affinity:{promptCacheKey:r(n.promptCacheKey??e.prompt_cache_key),sessionHeader:r(n.sessionHeader??e.session_header),systemPrompt:r(n.systemPrompt),firstMessage:r(n.firstMessage)},streaming:e.streaming===!0,enqueuedAt:Date.now()}}}}var Re=class{constructor(e,t,n){this.res=e;this.streaming=t;this.keepaliveMs=n}res;streaming;keepaliveMs;keepalive=null;terminal=null;head(){this.streaming&&!this.res.headersSent&&(this.res.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive"}),this.keepalive=setInterval(()=>{this.res.writableEnded||this.res.write(`: keepalive
301
+ `;var V=class extends Error{constructor(t,n,r){super(`session registry violation (${t}): ${n} ${JSON.stringify(r)}`);this.op=t;this.verdict=n;this.context=r;this.name="RegistryViolation"}op;verdict;context},wn=100,it=s=>{let e={attached:0,queued:0,paused:0,retired:0,ended:0,inflight:0};for(let t of s.split(",")){if(t==="")continue;let[n,r]=t.split("=");n in e&&(e[n]=Number(r))}return e},_n=s=>(s===""?[]:s.split(`
302
+ `)).map(e=>{let[t,n,r,i,l]=e.split("|");return{key:t,state:n,inFlight:Number(r),gen:Number(i),sessionId:l}});function F(s){let e=s.split(":"),t=e[e.length-1],n=e[e.length-2];if(n!==void 0&&/^\d+$/.test(n)&&/^\d+$/.test(t))return{base:e.slice(0,-1).join(":"),index:Number(n),gen:Number(t)};if(!/^\d+$/.test(t))throw new Error(`session registry: malformed slot key "${s}" (expected decision:{replica}:{index}[:{gen}])`);return{base:s,index:Number(t),gen:0}}var K=()=>String(Date.now()),re=class{constructor(e,t){this.evalFn=e;this.pool=t}evalFn;pool;keys(e,t=!0,n=!0){let{base:r}=F(e),i=[`sreg:${this.pool}:slot:${e}`];return t&&i.push(`sreg:${this.pool}:gen:${r}`),n&&i.push(`sreg:${this.pool}:retired`),i.push(`sreg:${this.pool}:meta`),i}async run(e,t,n,r,i){let l=await this.evalFn.eval(t,n,r);if(l.startsWith("reject:"))throw new V(e,l,{pool:this.pool,...i})}mint(e){let{gen:t}=F(e);return this.run("mint",ge,this.keys(e,!1,!0),[e,t,K()],{slotKey:e,gen:t})}mintWith(e,t){let{gen:n}=F(e);return this.run("mint",ge,this.keys(e,!1,!0),[e,n,K(),t.model,t.capabilities??"",t.cacheNs],{slotKey:e,gen:n,cacheNs:t.cacheNs})}attachWithEpoch(e,t,n){let{gen:r}=F(e);return this.run("attach",me,this.keys(e),[e,r,t,K(),n],{slotKey:e,gen:r,sessionId:t,observedEpoch:n})}publish(e,t,n){return this.run("publish",st,this.keys(e,!1,!1),[e,t,n.maxConcurrent,n.queueDepth,n.cacheGen,n.capabilities??""],{slotKey:e,observedEpoch:t})}attach(e,t){let{gen:n}=F(e);return this.run("attach",me,this.keys(e),[e,n,t,K()],{slotKey:e,gen:n,sessionId:t})}detach(e,t){return this.run("detach",Be,this.keys(e,!1,!1),[e,t,K()],{slotKey:e,reason:t})}rotate(e,t){let{gen:n}=F(t),r=[...this.keys(e),`sreg:${this.pool}:slot:${t}`];return this.run("rotate",Ye,r,[e,t,n,K()],{oldKey:e,newKey:t,newGen:n})}end(e){return this.run("end",Ve,this.keys(e,!1,!1),[e,K()],{slotKey:e})}lease(e){return this.run("lease",Je,this.keys(e,!1,!1),[e],{slotKey:e})}release(e){return this.run("release",ze,this.keys(e,!1,!1),[e,K()],{slotKey:e})}configure(e,t){return this.run("config",Xe,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}retune(e,t){return this.run("retune",Qe,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}async tuning(){let e=await this.evalFn.eval(We,[`sreg:${this.pool}:meta`],[]),[t,n,r]=e.split("|");return{max:Number(t),inFlightCap:Number(n),configVersion:Number(r)}}async grant(e,t){let n=this.keys(e,!1,!1),r=await this.evalFn.eval(X,n,[e,t.cap,t.configVersion]);if(r==="reject:cap-moved"){let i=await this.tuning();r=await this.evalFn.eval(X,n,[e,i.inFlightCap,i.configVersion])}if(r==="ok")return{granted:!0};if(r==="reject:cap")return{granted:!1,reason:"cap-full"};if(r==="reject:cap-moved")return{granted:!1,reason:"cap-moved"};throw new V("grant",r,{pool:this.pool,slotKey:e})}async grantWithEpoch(e,t){let n=this.keys(e,!1,!1),r=await this.evalFn.eval(X,n,[e,t.cap,t.configVersion,t.epoch]);if(r==="reject:cap-moved"){let i=await this.tuning();r=await this.evalFn.eval(X,n,[e,i.inFlightCap,i.configVersion,t.epoch])}if(r==="ok")return{granted:!0};if(r==="reject:cap")return{granted:!1,reason:"cap-full"};if(r==="reject:cap-moved")return{granted:!1,reason:"cap-moved"};if(r==="reject:epoch")return{granted:!1,reason:"epoch-stale"};throw new V("grant",r,{pool:this.pool,slotKey:e})}async snapshot(){let e=[],t=null,n="0";do{let r=await this.snapshotPage(n,wn);t===null&&(t=r.counts),e.push(...r.slots),n=r.cursor}while(n!=="0");return{counts:t,slots:e}}async counts(){let e=await this.evalFn.eval(et,[`sreg:${this.pool}:meta`],[]);return it(e)}async snapshotPage(e,t){let n=`sreg:${this.pool}:slot:`,r=await this.evalFn.eval(Ze,[`sreg:${this.pool}:meta`],[n,e,t]),[i,l,p]=r.split("#");return{cursor:i,counts:it(l??""),slots:_n(p??"")}}async readRecords(e){if(e.length===0)return[];let t=`sreg:${this.pool}:slot:`,n=await this.evalFn.eval(tt,[],e.map(r=>t+r));return(n===""?[]:n.split(`
303
+ `)).map(r=>{let[i,l]=r.split("|");return{state:i,inFlight:Number(l)}})}async generation(e){let{base:t}=F(e),n=await this.evalFn.eval(nt,[`sreg:${this.pool}:gen:${t}`],[]);return Number(n)}async record(e){let n=(await this.evalFn.eval(rt,[`sreg:${this.pool}:slot:${e}`],[])).split("|"),r=n[0],i=n[1]===""||n[1]===void 0?void 0:n[1],l=n.slice(2).join("|");return{state:r,sessionId:i,lastReason:l===""?void 0:l}}};S();var at=require("bullmq"),lt=require("crypto"),Sn=3e4,bn=60,Rn=1e3;function ot(s){let e;try{e=JSON.parse(s)}catch{return null}if(typeof e!="object"||e===null||!("proxy_url"in e))return null;let t=e;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0}}function ut(s){let e=s.now??Date.now,t=new Map,n=new Map,r=new Map,i=new Map,l=new Set,p=d=>{let g=t.get(d);return g||(g=s.queueFor?.(d)??y(d),t.set(d,g)),g},y=d=>{let g=s.redis,T=new at.Queue(d,{prefix:"bull:dispatch",connection:g});return{add:(k,I,x)=>T.add(k,I,x),reassertWaiting:async k=>{let x=(await T.getJobs(["waiting"])).filter(A=>A.data?.session_kind==="lane").sort((A,N)=>A.timestamp-N.timestamp);if(x.length===0)return{found:0};for(let A of x)try{await A.updateData({...A.data,demand_reaffirmed_at_ms:k,...s.mintRuntimeToken?{runtime_token:s.mintRuntimeToken(String(A.data.session_id))}:{}})}catch{}for(let A of x.slice(1))try{await A.remove()}catch{}return{found:x.length}},close:()=>T.close()}},R=async d=>{let g=await s.redis.hgetall(`lanes:${d}`),T=[];for(let[x,A]of Object.entries(g)){let N=ot(A);N&&N.proxy_url===s.docHostUrl&&T.push(x)}if(T.length===0)return[];let k=await s.redis.mget(...T.map(x=>`lane_hosts:${x}`)),I=[];return T.forEach((x,A)=>{let N=k[A];N&&I.push({laneId:x,host:N})}),I},_=async(d,g)=>{let T=n.get(d)??0,k=e();if(k-T<Sn)return;n.set(d,k);let I=p(d);if((await I.reassertWaiting(e()).catch(N=>{throw n.delete(d),N})).found>0){i.set(g??"",(i.get(g??"")??0)+1),s.onEvent?.({kind:"lane_demand_reaffirmed",pool:d,model:g});return}let A=`lane-${(0,lt.randomUUID)().replaceAll("-","")}`;await I.add("session",{session_id:A,logical_id:A,incarnation:k,session_kind:"lane",lane_id:A,session_server_url:s.docHostUrl,proxy_url:s.docHostUrl,session_idle_timeout_seconds:bn,thread_key:"lane",demand_reaffirmed_at_ms:e(),...s.mintRuntimeToken?{runtime_token:s.mintRuntimeToken(A)}:{}},{jobId:`${A}#${k}`,attempts:3}),r.set(g??"",(r.get(g??"")??0)+1),s.onEvent?.({kind:"lane_demand_enqueued",pool:d,model:g})};return{async pick({pool:d,model:g,holdMs:T=0}){l.add(d);let k=async()=>{try{await _(d,g)}catch(N){n.delete(d),s.onEvent?.({kind:"lane_demand_failed",pool:d,model:g,reason:N instanceof Error?N.message:String(N)})}},I=async()=>{try{return await R(d)}catch{return[]}},x=await I();if(x.length>0)return x;await k();let A=e()+T;for(;e()<A;){if(await new Promise(N=>setTimeout(N,Rn)),x=await I(),x.length>0)return x;await k()}return[]},async status(){let d=[...l].sort();return Promise.all(d.map(async g=>{let T=[];try{let k=await s.redis.hgetall(`lanes:${g}`),I=Object.keys(k),x=I.length===0?[]:await s.redis.mget(...I.map(N=>`lane_hosts:${N}`)),A=e();T=I.map((N,de)=>{let ee=k[N],Y=ee===void 0?null:ot(ee);return{laneId:N,occupantId:Y?.occupant_id??"",capacity:Y?.capacity??0,heartbeatAgeMs:Y===null?null:A-Y.heartbeat_ms,advertisedHere:Y?.proxy_url===s.docHostUrl,hosted:!!x[de]}})}catch{}return{pool:g,lanes:T,lastDemandAt:n.get(g)??null}}))},demandCounters(){return[...new Set([...r.keys(),...i.keys()])].sort().map(g=>({model:g,enqueued:r.get(g)??0,reaffirmed:i.get(g)??0}))},async close(){await Promise.all([...t.values()].map(d=>d.close().catch(()=>{}))),t.clear()}}}S();var Z=require("crypto");var ct="runtime:lease",En="lane:join";var kn=120,pt=1440*60;function dt(s){return Buffer.from(s).toString("base64url")}function Pn(s,e,t){let n=dt(JSON.stringify(s)),r=dt(JSON.stringify(e)),i=(0,Z.createHmac)("sha256",t).update(`${n}.${r}`).digest("base64url");return`${n}.${r}.${i}`}function ft(s,e,t,n=kn,r=En){return Tn(s,t,n,r,e)}function Tn(s,e,t,n,r){let i=Math.floor(Date.now()/1e3);return Pn({alg:"HS256",typ:"JWT"},{session_id:s,aud:"sfu",sub:s,scope:n,...r?{tenant:r}:{},iat:i,exp:i+t,jti:(0,Z.randomUUID)()},e)}S();var se=class{records=new Map;add(e){return this.records.set(e.request_id,{request:e,sessionId:"",attempt:1,dispatched:!1}),Promise.resolve()}dispatched(e,t,n){let r=this.records.get(e);return r&&(r.sessionId=t,r.attempt=n,r.dispatched=!0),Promise.resolve()}requeue(e,t){let n=this.records.get(e);return n&&(n.dispatched=!1,n.sessionId="",n.attempt=t),Promise.resolve()}finish(e){return this.records.delete(e),Promise.resolve()}queued(e,t){return Promise.resolve([...this.records.values()].filter(n=>!n.dispatched&&n.request.region===e&&n.request.model===t).map(n=>n.request))}inflight(){return Promise.resolve([...this.records.values()].filter(e=>e.dispatched).map(e=>({request:e.request,sessionId:e.sessionId,attempt:e.attempt})))}};S();S();var ae=s=>`${s.systemPrompt??""}\0${s.firstMessage??""}`;function ye(s){return s.promptCacheKey!==void 0&&s.promptCacheKey!==""?`k:${s.promptCacheKey}`:s.sessionHeader!==void 0&&s.sessionHeader!==""?`h:${s.sessionHeader}`:`p:${In(ae(s))}`}function In(s){let e=2166136261;for(let t=0;t<s.length;t++)e^=s.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}var ht=512,xn=4096,ie=8,oe=class{root={children:new Map,sessions:new Map};nodes=1;insert(e,t,n){let r=e.slice(0,ht),i=this.root;for(let l=0;l<r.length;l+=ie){let p=r.slice(l,l+ie),y=i.children.get(p);if(!y){if(this.nodes>=xn)return;y={children:new Map,sessions:new Map},i.children.set(p,y),this.nodes+=1}y.sessions.set(t,n),i=y}}match(e,t){let n=e.slice(0,ht),r=this.root,i=null,l=0,p=0;for(;;){let y=null,R=-1;for(let[g,T]of r.sessions)t.has(g)&&(T>R||T===R&&y!==null&&g<y)&&(y=g,R=T);if(y!==null&&(i={sessionId:y,depth:l}),p>=n.length)break;let _=n.slice(p,p+ie),d=r.children.get(_);if(!d)break;r=d,l+=_.length,p+=ie}return i}forget(e){let t=n=>{n.sessions.delete(e);for(let r of n.children.values())t(r)};t(this.root)}size(){return this.nodes}};function gt(s,e,t,n){if(e.length===0)return null;let r=new Map(e.map(_=>[_.sessionId,_])),i=_=>{let d=r.get(_);return d!==void 0&&d.backlog<n.backlogThreshold},l=new Set(r.keys()),p=n.sticky.get(ye(s));if(p!==void 0&&i(p))return{sessionId:p,reason:"sticky"};let y=t.match(ae(s),l);if(y!==null&&i(y.sessionId))return{sessionId:y.sessionId,reason:"prefix"};let R=null;for(let _ of e)(R===null||_.backlog<R.backlog||_.backlog===R.backlog&&_.sessionId<R.sessionId)&&(R=_);return R===null?null:{sessionId:R.sessionId,reason:"load"}}S();var mt="llm",ve="requests",An="llm-resp",we=(s,e,t,n=0)=>`decision:pooler-${s}-${e}`.replaceAll(":","-")+`:${t}`+(n>0?`:${n}`:""),_e=s=>{let{base:e,gen:t}=F(s);return`${e}:${t+1}`},yt=s=>`${An}:${s}`,vt="free_slots",Se="inflight",be="live_seen",B=class extends Error{constructor(t,n){super(`reply stream for ${t} dropped before its terminal chunk${n?`: ${n}`:""}`);this.requestId=t;this.name="ReplyStreamDropped"}requestId};var wt=new Set(["registry_error","failed","mint_failed","scaled_down","live_mark_failed"]),On=6e4,Nn=33e4,Mn=2,$n=8,Cn=5e3,Un=1e4,Ln=6e4,qn=5e3,Dn={idle:"bound",queued:"bound",unavailable:"bound",provisioning:"bound",waiting_for_capacity:"bound",connecting:"bound",live:"bound",degraded:"bound",paused:"unbound",error:"unbound",unknown:"unbound"},le=class s{pools=new Map;now;queueDeadlineMs;silenceDeadlineMs;maxAttempts;backlogThreshold;mint;limits;scaleUpWaitMs;mintCooldownMs;sessionIdleTtlMs;idleSweepMs;journal;registry;onEvent;closed=!1;sweepTimer=null;constructor(e){this.journal=e.journal,this.registry=e.registry??null,this.now=e.now??Date.now,this.queueDeadlineMs=e.queueDeadlineMs??On,this.silenceDeadlineMs=e.silenceDeadlineMs??Nn,this.maxAttempts=e.maxAttempts??Mn,this.backlogThreshold=e.backlogThreshold??$n,this.mint=e.mint,this.limits=e.limits??[],this.scaleUpWaitMs=e.scaleUpWaitMs??Cn,this.mintCooldownMs=e.mintCooldownMs??Un,this.sessionIdleTtlMs=e.sessionIdleTtlMs??Ln,this.idleSweepMs=e.idleSweepMs??qn,this.onEvent=e.onEvent??(()=>{}),(this.mint!==void 0||this.limits.length>0)&&this.armSweep()}armSweep(){this.sweepTimer=setInterval(()=>this.sweep(),this.idleSweepMs),this.sweepTimer.unref?.()}sweep(){if(!this.closed)for(let e of this.pools.values()){let t=this.limitsFor(e);if(t===null)continue;this.evictUnbound(e);let n=e.queue.length===0;e.sessions.length<t.max&&this.queuePressure(e)?this.tryMint(e,"queue_pressure"):e.sessions.length<t.min&&this.tryMint(e,"min_floor"),n&&e.sessions.length>t.min&&this.scaleDownOldestIdle(e,t)}}servable(e){return e.gone()!==null?!1:Dn[e.phaseName()]==="bound"?!0:!e.everLive()}evictUnbound(e){for(let t of[...e.sessions]){if(this.servable(t))continue;let n=t.phaseName();this.onEvent({kind:"sweep_evicted",pool:this.key(e.region,e.model),sessionId:t.sessionId,phase:n}),this.evict(e,t,new H(`the pool entry for ${t.sessionId} has no usable compute binding (phase "${n}") \u2014 the sweep's servability reconcile evicts it; the named session itself stays parked and attachable`))}}limitsFor(e){return this.limits.find(t=>t.region===e.region&&t.model===e.model)??null}queuePressure(e){if(e.queue.length===0)return!1;let t=this.now();return e.queue.some(n=>t-n.queuedAt>=this.scaleUpWaitMs)}tryMint(e,t){if(this.mint===void 0||this.closed||e.minting)return;let n=this.limitsFor(e);if(n===null||e.sessions.length>=n.max)return;let r=this.now();r-e.lastMintAt<this.mintCooldownMs||(e.lastMintAt=r,e.minting=!0,this.mintOnce(e,t).finally(()=>{e.minting=!1}))}async mintOnce(e,t){if(this.mint===void 0)return!1;let n=e.mintSeq++,r;try{r=await this.claimSlot(e.region,e.model,n)}catch(i){if(t==="boot_floor")throw i;return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:i instanceof Error?i.message:String(i)}),!1}try{let i=await this.mint(e.region,e.model,r);return this.closed?(await i.end().catch(()=>{}),!1):(this.addSession(e.region,e.model,i,r),this.onEvent({kind:"minted",pool:this.key(e.region,e.model),sessionId:i.sessionId,reason:t}),!0)}catch(i){return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:i instanceof Error?i.message:String(i)}),!1}}async warm(){for(let e of this.limits){let t=this.poolOf(e.region,e.model);t.minting=!0;try{for(;t.sessions.length<e.min&&await this.mintOnce(t,"boot_floor"););}finally{t.minting=!1}}}scaleDownOldestIdle(e,t){let n=this.now();for(let r of e.sessions){if(r.gone()!==null||[...e.records.values()].some(R=>R.session===r&&R.phase==="dispatched")||n-(e.lastActivity.get(r)??n)<this.sessionIdleTtlMs)continue;let p=e.sessions.indexOf(r);if(p===-1)continue;e.sessions.splice(p,1),this.detachSignals(e,r),e.radix.forget(r.sessionId),e.lastActivity.delete(r);let y=e.slotKeys.get(r.sessionId);y!==void 0&&(e.slotKeys.delete(r.sessionId),this.registryCall("end",y,()=>this.registry?.end(y))),this.onEvent({kind:"scaled_down",pool:this.key(e.region,e.model),sessionId:r.sessionId,sessions:e.sessions.length,min:t.min}),r.end().catch(R=>{this.onEvent({kind:"scaled_down_end_failed",pool:this.key(e.region,e.model),sessionId:r.sessionId,reason:R instanceof Error?R.message:String(R)})});return}}static poolKey(e,t){return`${e}:${t}`}async claimSlot(e,t,n){let r=we(e,t,n);if(this.registry===null)return r;for(let i=0;;i++){let l=await this.registry.generation(r),p=we(e,t,n,l),{state:y,sessionId:R,lastReason:_}=await this.registry.record(p);if(y==="none"||y==="paused"&&R===void 0&&_===void 0)try{return await this.registry.mint(p),p}catch(d){this.rethrowUnlessClaimRace(d,i);continue}else{let d=_e(p);try{await this.registry.rotate(p,d),await this.registry.mint(d)}catch(g){this.rethrowUnlessClaimRace(g,i);continue}return this.onEvent({kind:"slot_rotated",pool:this.key(e,t),slotKey:p,successor:d,reason:y==="paused"?"boot claim over an evicted slot's dead session":`boot claim over a previous pod's ${y} record`}),d}}}static CLAIM_RACE_VERDICTS=new Set(["reject:double-rotate","reject:generation-monotone","reject:retired-corpse-reuse","reject:mint-queued","reject:mint-attached"]);static CLAIM_RACE_ATTEMPTS=3;rethrowUnlessClaimRace(e,t){if(!(t+1<s.CLAIM_RACE_ATTEMPTS&&e instanceof V&&s.CLAIM_RACE_VERDICTS.has(e.verdict)))throw e}addSession(e,t,n,r){let i=this.poolOf(e,t);i.sessions.push(n),i.lastActivity.set(n,this.now()),i.slotKeys.set(n.sessionId,r),n.whenLive().then(()=>{n.markLiveSeen().catch(l=>{this.onEvent({kind:"live_mark_failed",pool:this.key(e,t),sessionId:n.sessionId,reason:l instanceof Error?l.message:String(l)})}),this.registryCall("attach",r,()=>this.registry?.attach(r,n.sessionId))}).catch(l=>{this.onEvent({kind:"session_never_live",pool:this.key(e,t),sessionId:n.sessionId,reason:l instanceof Error?l.message:String(l)}),this.evict(i,n,l instanceof Error?l:new Error(String(l)))}),i.offs.set(n,[n.onDocChange(()=>{this.pump(i),this.adoptSettled(i)}),n.onGone(l=>this.evict(i,n,l))]),this.onEvent({kind:"session_added",pool:this.key(e,t),sessionId:n.sessionId}),this.start(i).then(()=>this.pump(i))}async start(e){if(!e.needsReconcile)return;e.needsReconcile=!1;let t=this.key(e.region,e.model);for(let n of await this.journal.inflight()){if(n.request.region!==e.region||n.request.model!==e.model)continue;let r=e.sessions.find(l=>l.sessionId===n.sessionId),i=r?.snapshot().inflight[n.request.request_id];if(r!==void 0){if(i?.status==="done"||i?.status==="error"){await this.journal.finish(n.request.request_id);continue}e.records.set(n.request.request_id,{request:n.request,sink:null,attempt:n.attempt,tried:new Set([n.sessionId]),session:r,phase:"dispatched",streamed:!1,deadlineAt:Number.POSITIVE_INFINITY,queueTimer:null,silenceTimer:null,queuedAt:this.now()}),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:n.request.request_id,sessionId:n.sessionId})}}for(let n of await this.journal.queued(e.region,e.model))await this.journal.finish(n.request_id),this.onEvent({kind:"reconciled_caller_gone",pool:t,requestId:n.request_id});for(let n of e.sessions){let r=n.snapshot();for(let[i,l]of Object.entries(r.inflight)){if(l.status==="done"||l.status==="error"||e.records.has(i))continue;let p={request:{request_id:i,region:e.region,model:e.model,affinity:{},payload:{},streaming:!1,enqueuedAt:0},sink:null,attempt:l.attempt,tried:new Set([n.sessionId]),session:n,phase:"dispatched",streamed:!1,deadlineAt:Number.POSITIVE_INFINITY,queueTimer:null,silenceTimer:null,queuedAt:this.now()};e.records.set(i,p),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:i,sessionId:n.sessionId})}}this.pump(e)}async submit(e,t){if(this.closed){t.head(),t.fail({status:503,code:"draining",message:"pooler is shutting down",retryAfterSeconds:5});return}let n=this.poolOf(e.region,e.model);await this.start(n);let r={request:e,sink:t,attempt:1,tried:new Set,session:null,phase:"queued",streamed:!1,deadlineAt:this.now()+this.queueDeadlineMs,queueTimer:null,silenceTimer:null,queuedAt:this.now()};n.records.set(e.request_id,r),n.queue.push(r),await this.journal.add(e),t.head(),this.armQueueTimer(n,r),this.onEvent({kind:"enqueued",pool:this.key(e.region,e.model),requestId:e.request_id}),this.pump(n),r.phase!=="finished"&&await new Promise(i=>{r.settle=i})}abandon(){this.closed=!0,this.sweepTimer!==null&&(clearInterval(this.sweepTimer),this.sweepTimer=null);for(let e of this.pools.values()){for(let t of e.records.values())this.clearTimers(t);for(let t of e.offs.values())for(let n of t)n();e.offs.clear(),e.sessions.length=0,e.queue.length=0,e.records.clear(),e.lastActivity.clear()}this.pools.clear()}async close(){this.closed=!0,this.sweepTimer!==null&&(clearInterval(this.sweepTimer),this.sweepTimer=null);for(let e of this.pools.values()){for(let n of e.records.values())this.clearTimers(n),n.phase!=="finished"&&this.settle(n,{status:503,code:"draining",message:"pooler is shutting down",retryAfterSeconds:5});for(let n of e.offs.values())for(let r of n)r();e.offs.clear(),e.lastActivity.clear();for(let n of e.slotKeys.values())this.registryCall("rotate",n,()=>this.registry?.rotate(n,_e(n)));e.slotKeys.clear();let t=e.sessions.splice(0);await Promise.allSettled(t.map(n=>n.end()))}this.pools.clear()}poolOf(e,t){let n=s.poolKey(e,t),r=this.pools.get(n);return r||(r={region:e,model:t,sessions:[],records:new Map,queue:[],sticky:new Map,radix:new oe,offs:new Map,slotKeys:new Map,needsReconcile:!0,lastMintAt:0,minting:!1,mintSeq:0,lastActivity:new Map},this.pools.set(n,r)),r}key(e,t){return s.poolKey(e,t)}registryCall(e,t,n){let r=n();r!==void 0&&r.catch(i=>{this.onEvent({kind:"registry_error",reason:`${e}: ${i instanceof Error?i.message:String(i)}`,slotKey:t})})}creditFor(e,t){let n=t.snapshot(),r=0;for(let i of e.records.values()){if(i.session!==t||i.phase!=="dispatched")continue;let l=n.inflight[i.request.request_id];(l===void 0||l.status===void 0)&&(r+=1)}return Math.max(0,n.freeSlots-r)}backlogOf(e,t){let n=0;for(let r of e.records.values())r.session===t&&r.phase==="dispatched"&&(n+=1);return n}pump(e){if(this.closed)return;let t=!0;for(;t&&e.queue.length>0&&e.sessions.length>0;){t=!1;for(let n=0;n<e.queue.length;n++){let r=e.queue[n],i=this.pickFor(e,r);if(i!==null){e.queue.splice(n,1),this.dispatch(e,i,r),t=!0;break}}}e.queue.length>0&&this.queuePressure(e)&&this.tryMint(e,"queue_pressure")}pickFor(e,t){let n=e.sessions.filter(l=>this.servable(l)&&!t.tried.has(l.sessionId)&&this.creditFor(e,l)>0).map(l=>({sessionId:l.sessionId,backlog:this.backlogOf(e,l)})),r=gt(t.request.affinity,n,e.radix,{backlogThreshold:this.backlogThreshold,sticky:e.sticky});if(r===null)return null;let i=e.sessions.find(l=>l.sessionId===r.sessionId)??null;return i!==null&&this.onEvent({kind:"picked",pool:this.key(e.region,e.model),requestId:t.request.request_id,sessionId:i.sessionId,reason:r.reason}),i}dispatch(e,t,n){n.phase="dispatched",n.session=t,n.tried.add(t.sessionId),e.lastActivity.set(t,this.now()),this.clearTimer(n,"queue"),n.deadlineAt=this.now()+this.silenceDeadlineMs;let r={request_id:n.request.request_id,consumer_id:n.request.request_id,payload:n.request.payload,stream:n.request.streaming};(async()=>{let i=t.reply(r.request_id);try{await t.markInflight(r.request_id,n.attempt),await t.push(r)}catch(y){this.lost(e,n,y);return}await this.journal.dispatched(n.request.request_id,t.sessionId,n.attempt);let l=ye(n.request.affinity);e.sticky.set(l,t.sessionId),e.radix.insert(ae(n.request.affinity),t.sessionId,this.now()),this.onEvent({kind:"dispatched",pool:this.key(e.region,e.model),requestId:n.request.request_id,sessionId:t.sessionId,attempt:n.attempt}),this.armSilenceTimer(e,n);let p=e.slotKeys.get(t.sessionId);p!==void 0&&this.registryCall("lease",p,()=>this.registry?.lease(p)),this.consume(e,n,i)})()}async consume(e,t,n){if(t.session!==null)try{for await(let r of n){if(t.phase==="finished")return;this.armSilenceTimer(e,t),t.streamed=!0;let i=t.sink;if(i!==null&&(await i.chunk(r),r.t==="response"||r.t==="error"||r.t==="end")){await this.finish(e,t);return}}this.lost(e,t,new B(t.request.request_id,"iterator ended without a terminal chunk"))}catch(r){this.lost(e,t,r)}}lost(e,t,n){if(t.phase==="finished")return;this.clearTimers(t);let r=n instanceof Error?n.message:String(n);this.onEvent({kind:"lost",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt,reason:r}),n instanceof H&&t.session!==null&&this.evict(e,t.session,n);let i=e.sessions.some(l=>this.servable(l)&&!t.tried.has(l.sessionId));if(!t.streamed&&t.attempt<this.maxAttempts&&i){t.attempt+=1,t.phase="queued",t.session=null,t.deadlineAt=this.now()+this.queueDeadlineMs,t.queuedAt=this.now(),e.queue.unshift(t),this.journal.requeue(t.request.request_id,t.attempt).catch(()=>{}),this.armQueueTimer(e,t),this.onEvent({kind:"retry",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt}),this.pump(e);return}this.settle(t,{status:502,code:t.streamed?"upstream_stream_lost":"upstream_error",message:t.streamed?"the upstream reply stream was lost after the response began":"the upstream reply stream was lost before the response began",retryAfterSeconds:1})}async finish(e,t){this.clearTimers(t),t.phase="finished",t.session!==null&&e.lastActivity.set(t.session,this.now()),this.releaseSlot(e,t,"release"),await this.journal.finish(t.request.request_id),t.session!==null&&t.session.clearRequest(t.request.request_id);let n=t.sink;n!==null&&n.done(),this.release(e,t),this.onEvent({kind:"finished",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt}),this.settlePromise(t)}settle(e,t){this.clearTimers(e);let n=e.session===null?void 0:this.poolOf(e.request.region,e.request.model).slotKeys.get(e.session.sessionId);n!==void 0&&this.registryCall("release",n,()=>this.registry?.release(n)),e.phase="finished",e.session!==null&&this.poolOf(e.request.region,e.request.model).lastActivity.set(e.session,this.now()),this.journal.finish(e.request.request_id).catch(()=>{}),e.session!==null&&e.session.clearRequest(e.request.request_id);let r=e.sink;r!==null&&r.fail(t),this.onEvent({kind:"failed",requestId:e.request.request_id,reason:t.code}),this.settlePromise(e)}settlePromise(e){let t=e.settle;e.settle=void 0,t?.()}release(e,t){e.records.get(t.request.request_id)===t&&e.records.delete(t.request.request_id)}releaseSlot(e,t,n){if(t.session===null)return;let r=e.slotKeys.get(t.session.sessionId);r!==void 0&&this.registryCall(n,r,()=>n==="release"?this.registry?.release(r):this.registry?.detach(r,"session evicted"))}detachSignals(e,t){let n=e.offs.get(t);if(n!==void 0){e.offs.delete(t);for(let r of n)r()}}evict(e,t,n){let r=e.sessions.indexOf(t);if(r===-1)return;e.sessions.splice(r,1),this.detachSignals(e,t),e.lastActivity.delete(t),e.radix.forget(t.sessionId);let i=e.slotKeys.get(t.sessionId);i!==void 0&&(e.slotKeys.delete(t.sessionId),this.registryCall("detach",i,()=>this.registry?.detach(i,n.message)));for(let l of[...e.records.values()])l.session===t&&l.phase!=="finished"&&this.lost(e,l,n)}adoptSettled(e){for(let t of e.sessions){let n=t.snapshot();for(let r of[...e.records.values()]){if(r.sink!==null||r.session!==t)continue;let i=n.inflight[r.request.request_id];(i?.status==="done"||i?.status==="error")&&(this.journal.finish(r.request.request_id).catch(()=>{}),this.release(e,r))}}}armQueueTimer(e,t){this.clearTimer(t,"queue");let n=Math.max(0,t.deadlineAt-this.now());t.queueTimer=setTimeout(()=>{t.phase==="queued"&&(this.onEvent({kind:"queue_timeout",requestId:t.request.request_id}),this.settle(t,{status:429,code:"queue_timeout",message:"no capacity for this model within the wait bound",retryAfterSeconds:30}),e.queue.splice(e.queue.indexOf(t),1))},n),t.queueTimer.unref?.()}armSilenceTimer(e,t){t.silenceTimer===null&&(t.silenceTimer=setTimeout(()=>{t.silenceTimer=null,t.phase==="dispatched"&&this.lost(e,t,new B(t.request.request_id,`silent past ${this.silenceDeadlineMs}ms`))},this.silenceDeadlineMs),t.silenceTimer.unref?.())}clearTimer(e,t){let n=t==="queue"?e.queueTimer:e.silenceTimer;n!==null&&(clearTimeout(n),t==="queue"?e.queueTimer=null:e.silenceTimer=null)}clearTimers(e){this.clearTimer(e,"queue"),this.clearTimer(e,"silence")}stats(){return{pools:[...this.pools.entries()].map(([e,t])=>({pool:e,queued:t.queue.length,inflight:[...t.records.values()].filter(n=>n.phase==="dispatched").length,sessions:t.sessions.length}))}}};S();var Gn="0.0.0.0",_t="serve";var z=(s,e)=>{let t=s[e];if(typeof t!="string"||t==="")throw new Error(`the pooler requires ${e} (external input) \u2014 refusing to start half-configured`);return t},jn=(s,e)=>{if(s===null||typeof s!="object")throw new Error(`URUN_POOLER_TARGETS[${e}] must be an object`);let t=s,n=p=>{let y=t[p];if(typeof y!="string"||y==="")throw new Error(`URUN_POOLER_TARGETS[${e}].${p} is required`);return y},r=p=>{let y=t[p];if(typeof y!="number"||!Number.isInteger(y))throw new Error(`URUN_POOLER_TARGETS[${e}].${p} must be an integer`);return y},i,l;if(t.sessions!==void 0){let p=t.sessions;if(typeof p!="number"||!Number.isInteger(p)||p<1)throw new Error(`URUN_POOLER_TARGETS[${e}].sessions must be an integer >= 1`);if(t.min!==void 0||t.max!==void 0)throw new Error(`URUN_POOLER_TARGETS[${e}]: give either sessions or {min, max}, never both`);i=p,l=p}else{if(i=r("min"),l=r("max"),i<0)throw new Error(`URUN_POOLER_TARGETS[${e}].min must be >= 0 (0 scales to zero)`);if(l<1)throw new Error(`URUN_POOLER_TARGETS[${e}].max must be >= 1`);if(i>l)throw new Error(`URUN_POOLER_TARGETS[${e}]: min (${String(i)}) must not exceed max (${String(l)})`)}return{region:n("region"),model:n("model"),app:n("app"),fn:typeof t.fn=="string"&&t.fn!==""?t.fn:void 0,min:i,max:l,sharedApp:t.sharedApp===!0}};function St(s){let e=s.PORT,t=e===void 0||e===""?8080:Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw new Error(`PORT must be a valid port number, got ${String(e)}`);let n=z(s,"URUN_BASE_URL"),r=z(s,"URUN_POOLER_TARGETS"),i;try{i=JSON.parse(r)}catch(l){throw new Error(`URUN_POOLER_TARGETS is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!Array.isArray(i)||i.length===0)throw new Error("URUN_POOLER_TARGETS must be a non-empty JSON array");return{port:t,bindHost:Gn,token:z(s,"URUN_POOLER_TOKEN"),baseUrl:n,apiUrl:s.URUN_API_URL!==void 0&&s.URUN_API_URL!==""?s.URUN_API_URL:`${n}/v1`,orgId:z(s,"URUN_ORG_ID"),apiKey:z(s,"URUN_API_KEY"),valkeyUrl:z(s,"URUN_VALKEY_URL"),laneDocHostUrl:(s.URUN_LANE_DOC_HOST_URL??"").trim()||void 0,laneRuntimeKey:(s.URUN_LANE_RUNTIME_KEY??"").trim()||void 0,targets:i.map(jn)}}S();var Et=require("http"),Hn="/pooler/v1/inference",Fn="/readyz",Kn="/metrics",Bn="/pooler/v1/lanes/pick",Yn="/pooler/v1/lanes/status",Vn=1e4,bt=16*1024*1024;function q(s,e,t,n,r){s.headersSent||(r!==void 0&&s.setHeader("retry-after",String(r)),s.writeHead(e,{"content-type":"application/json"}),s.end(JSON.stringify({error:{message:t,type:"pooler_error",code:n}})))}function Jn(s){if(s===null||typeof s!="object")return{reason:"body must be a JSON object"};let e=s;if(typeof e.region!="string"||e.region==="")return{reason:"region is required"};if(typeof e.model!="string"||e.model==="")return{reason:"model is required"};if(typeof e.request_id!="string"||e.request_id==="")return{reason:"request_id is required"};if(e.payload===null||typeof e.payload!="object")return{reason:"payload must be an object"};let t=e.affinity??{};if(t===null||typeof t!="object")return{reason:"affinity must be an object"};let n=t,r=i=>typeof i=="string"&&i!==""?i:void 0;return{value:{streaming:e.streaming===!0,request:{request_id:e.request_id,region:e.region,model:e.model,payload:e.payload,affinity:{promptCacheKey:r(n.promptCacheKey??e.prompt_cache_key),sessionHeader:r(n.sessionHeader??e.session_header),systemPrompt:r(n.systemPrompt),firstMessage:r(n.firstMessage)},streaming:e.streaming===!0,enqueuedAt:Date.now()}}}}var Re=class{constructor(e,t,n){this.res=e;this.streaming=t;this.keepaliveMs=n}res;streaming;keepaliveMs;keepalive=null;terminal=null;head(){this.streaming&&!this.res.headersSent&&(this.res.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive"}),this.keepalive=setInterval(()=>{this.res.writableEnded||this.res.write(`: keepalive
304
304
 
305
305
  `)},this.keepaliveMs),this.keepalive.unref?.())}async chunk(e){if(this.streaming){this.res.headersSent||this.head(),this.res.write(`data: ${JSON.stringify(e)}
306
306
 
@@ -310,10 +310,10 @@ return 'ok'
310
310
 
311
311
  `),this.res.write(`data: [DONE]
312
312
 
313
- `),this.res.end()}stopKeepalive(){this.keepalive!==null&&clearInterval(this.keepalive),this.keepalive=null}};function Rt(s){return new Promise((e,t)=>{let n=0,r=[];s.on("data",o=>{if(n+=o.length,n>bt){t(new Error(`request body exceeds ${bt} bytes`)),s.destroy();return}r.push(o)}),s.on("end",()=>e(Buffer.concat(r).toString("utf8"))),s.on("error",t)})}function kt(s){let e=s.keepaliveMs??Yn,t=s.log??(()=>{}),n=(0,Et.createServer)((r,o)=>{(async()=>{let l=new URL(r.url??"/","http://pooler.internal");if(r.method==="GET"&&l.pathname===Hn){o.writeHead(200,{"content-type":"application/json"}),o.end(JSON.stringify({ok:!0,...s.pooler.stats()}));return}if(r.method==="GET"&&l.pathname===Fn){let _=["# TYPE pooler_pool_queued gauge","# TYPE pooler_pool_inflight gauge","# TYPE pooler_pool_sessions gauge","# TYPE pooler_lane_demand_enqueued counter","# TYPE pooler_lane_demand_reaffirmed counter"];for(let d of s.pooler.stats().pools){let g=`pool="${d.pool}"`;_.push(`pooler_pool_queued{${g}} ${d.queued}`),_.push(`pooler_pool_inflight{${g}} ${d.inflight}`),_.push(`pooler_pool_sessions{${g}} ${d.sessions}`)}for(let d of s.lanePlane?.demandCounters()??[]){let g=`model="${d.model.replaceAll('"','\\"')}"`;_.push(`pooler_lane_demand_enqueued{${g}} ${d.enqueued}`),_.push(`pooler_lane_demand_reaffirmed{${g}} ${d.reaffirmed}`)}o.writeHead(200,{"content-type":"text/plain; version=0.0.4"}),o.end(`${_.join(`
313
+ `),this.res.end()}stopKeepalive(){this.keepalive!==null&&clearInterval(this.keepalive),this.keepalive=null}};function Rt(s){return new Promise((e,t)=>{let n=0,r=[];s.on("data",i=>{if(n+=i.length,n>bt){t(new Error(`request body exceeds ${bt} bytes`)),s.destroy();return}r.push(i)}),s.on("end",()=>e(Buffer.concat(r).toString("utf8"))),s.on("error",t)})}function kt(s){let e=s.keepaliveMs??Vn,t=s.log??(()=>{}),n=(0,Et.createServer)((r,i)=>{(async()=>{let l=new URL(r.url??"/","http://pooler.internal");if(r.method==="GET"&&l.pathname===Fn){i.writeHead(200,{"content-type":"application/json"}),i.end(JSON.stringify({ok:!0,...s.pooler.stats()}));return}if(r.method==="GET"&&l.pathname===Kn){let _=["# TYPE pooler_pool_queued gauge","# TYPE pooler_pool_inflight gauge","# TYPE pooler_pool_sessions gauge","# TYPE pooler_lane_demand_enqueued counter","# TYPE pooler_lane_demand_reaffirmed counter"];for(let d of s.pooler.stats().pools){let g=`pool="${d.pool}"`;_.push(`pooler_pool_queued{${g}} ${d.queued}`),_.push(`pooler_pool_inflight{${g}} ${d.inflight}`),_.push(`pooler_pool_sessions{${g}} ${d.sessions}`)}for(let d of s.lanePlane?.demandCounters()??[]){let g=`model="${d.model.replaceAll('"','\\"')}"`;_.push(`pooler_lane_demand_enqueued{${g}} ${d.enqueued}`),_.push(`pooler_lane_demand_reaffirmed{${g}} ${d.reaffirmed}`)}i.writeHead(200,{"content-type":"text/plain; version=0.0.4"}),i.end(`${_.join(`
314
314
  `)}
315
- `);return}if(s.lanePlane&&r.method==="GET"&&l.pathname===Bn){if(r.headers.authorization!==`Bearer ${s.token}`){q(o,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}o.writeHead(200,{"content-type":"application/json"}),o.end(JSON.stringify({pools:await s.lanePlane.status()}));return}if(s.lanePlane&&r.method==="POST"&&l.pathname===Kn){if(r.headers.authorization!==`Bearer ${s.token}`){q(o,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let _;try{_=JSON.parse(await Rt(r))}catch(k){q(o,400,k instanceof Error?k.message:String(k),"invalid_request");return}let d=_??{};if(typeof d.pool!="string"||d.pool===""){q(o,400,"pool is required","invalid_request");return}let g=d.hold_ms;if(g!==void 0&&(typeof g!="number"||!Number.isInteger(g)||g<0||g>12e4)){q(o,400,"hold_ms must be an integer in 0..120000","invalid_request");return}let T=typeof d.model=="string"&&d.model!==""?d.model:void 0;try{let k=await s.lanePlane.pick({pool:d.pool,model:T,holdMs:g??0});if(k.length===0){q(o,503,"no capacity available for this model right now, retry shortly","lane_capacity",2);return}o.writeHead(200,{"content-type":"application/json"}),o.end(JSON.stringify({lanes:k.map(I=>({lane_id:I.laneId,host:I.host}))}))}catch(k){t(`[pooler] lane pick for ${d.pool} failed: ${k instanceof Error?k.message:String(k)}`),q(o,500,"the pooler lane plane failed this pick","pooler_error")}return}if(r.method!=="POST"||l.pathname!==jn){q(o,404,`no route for ${r.method??""} ${l.pathname}`,"not_found");return}if(r.headers.authorization!==`Bearer ${s.token}`){q(o,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let p;try{p=JSON.parse(await Rt(r))}catch(_){q(o,400,_ instanceof Error?_.message:String(_),"invalid_request");return}let y=Vn(p);if("reason"in y){q(o,400,y.reason,"invalid_request");return}let R=new Re(o,y.value.streaming,e);R.head();try{await s.pooler.submit(y.value.request,R)}catch(_){t(`[pooler] request ${y.value.request.request_id} failed unexpectedly: ${_ instanceof Error?_.message:String(_)}`),R.fail({status:500,code:"pooler_error",message:"the pooler failed to serve this request"})}})()});return{server:n,close:()=>new Promise(r=>n.close(()=>r()))}}S();var ue=require("@urun-sh/core");S();var Jn=3,Wn="llm",zn=new Set(["paused","error"]);function Pt(s,e,t){let n=s.doc(Wn),r=typeof n.onConnectionState=="function",o=typeof s.onPhase=="function";if(!r&&!o)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let l=null,p=!1,y=new Set,R=[],_=d=>{if(!l){l=d;for(let g of[...y])g(d);y.clear()}};return r&&R.push(n.onConnectionState(d=>{p&&(d.consecutiveFailures<Jn||_(new H(`the pooled session for app "${e}" is gone: its doc backhaul failed ${d.consecutiveFailures} consecutive times (last close ${d.lastCloseCode===null?"by provider liveness reap":`code ${d.lastCloseCode}`}${d.lastCloseReason?`, reason ${JSON.stringify(d.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),t?.armOnFirstSync===!0&&typeof n.onSynced=="function"?R.push(n.onSynced(()=>{p=!0})):o&&R.push(s.onPhase(d=>{if(d.name==="live"){p=!0;return}p&&zn.has(d.name)&&_(new H(`the pooled session for app "${e}" lost its compute binding (phase "${d.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>l,onGone(d){return l?(d(l),()=>{}):(y.add(d),()=>y.delete(d))},dispose(){y.clear();for(let d of R.splice(0))d()}}}S();var xt=require("@urun-sh/core");S();async function Tt(s,e,t){if(s.synced===!0||typeof s.onSynced!="function")return;let n;await new Promise((r,o)=>{let l=s.onSynced(()=>{clearTimeout(n),r()});n=setTimeout(()=>{l(),o(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${t} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}var Xn=new Set(["accepted","done","error"]);function Zn(s){if(s===null||typeof s!="object")return{};let e=s,t={};for(let[n,r]of Object.entries(e)){let o=r===null||typeof r!="object"?null:r.toJSON;t[n]=typeof o=="function"?o.call(r):r}return t}function er(s){if(s===null||typeof s!="object")return null;let e=s,t=e.status;return t!==void 0&&(typeof t!="string"||!Xn.has(t))?null:{attempt:typeof e.attempt=="number"?e.attempt:0,...typeof t=="string"?{status:t}:{},...typeof e.error=="string"?{error:e.error}:{}}}function It(s){let e=Zn(s.get()),t=Number(e[vt]??0),n={},r=e[Se];if(r!==null&&typeof r=="object")for(let[o,l]of Object.entries(r)){let p=er(l);p!==null&&(n[o]=p)}return{freeSlots:Number.isFinite(t)?t:0,inflight:n,liveSeen:e[be]===!0}}function tr(s){if(s===xt.STREAM_END)return{t:"end"};if(s===null||typeof s!="object")return null;let e=s;return e.t==="delta"?{t:"delta",...typeof e.delta=="string"?{delta:e.delta}:{},...typeof e.reasoning=="string"?{reasoning:e.reasoning}:{},...e.tool_calls!==void 0?{tool_calls:e.tool_calls}:{}}:e.t==="response"||e.t==="error"?{t:e.t,body:e.body??s}:null}async function*nr(s,e){let t=s.stream(yt(e)),n=!1;try{for await(let r of t.messages()){let o=tr(r);if(o!==null&&(yield o,o.t!=="delta")){n=!0;return}}}catch(r){throw new B(e,r instanceof Error?r.message:String(r))}if(!n)throw new B(e,"the reply stream ended without a terminal chunk (urun-stream-v1 is at-most-once across a reconnect)")}function At(s){let{session:e,sessionId:t,goneWatch:n}=s;if(typeof e.whenLive!="function")throw new Error(`pooler session ${t} exposes no whenLive \u2014 a request must never be pushed into a session whose admission is unproven (the cold-wake gate is a contract, not an option)`);if(typeof e.end!="function")throw new Error(`pooler session ${t} exposes no end \u2014 the pooler is the attached client and must be able to release it`);if(typeof e.phase!="object"||e.phase===null||typeof e.phase.name!="string")throw new Error(`pooler session ${t} exposes no phase surface \u2014 the servability probe reads core's own phase name live, and a wrapper must never fabricate one`);let r=()=>e.doc(mt),o=!1;return"onPhase"in e&&typeof e.onPhase=="function"&&e.onPhase(l=>{l.name==="live"&&(o=!0)}),{sessionId:t,snapshot:()=>It(r()),onDocChange:l=>r().on("change",()=>l()),onGone:l=>n.onGone(l),gone:()=>n.gone(),phaseName:()=>(e.phase.name==="live"&&(o=!0),e.phase.name),everLive:()=>o||It(r()).liveSeen,markLiveSeen:async()=>{await Tt(r(),15e3,"the durable live-seen mark"),r().set({[be]:!0})},whenLive:l=>e.whenLive(l),markInflight:(l,p)=>(r().set({[Se]:{[l]:{attempt:p}}}),Promise.resolve()),push:l=>(r().set({[ve]:{[l.request_id]:{...l.payload,request_id:l.request_id,consumer_id:l.consumer_id,stream:l.stream}}}),Promise.resolve()),clearRequest:l=>{try{r().set({[ve]:{[l]:null}})}catch{}return Promise.resolve()},reply:l=>nr(e,l),end:async()=>{await e.end(),n.dispose()}}}function Ot(s){return async(e,t)=>{let n=e.fn??_t,r=(0,ue.App)(e.app,{baseUrl:s.baseUrl,orgId:s.orgId,getAccessToken:async()=>(await(0,ue.createClientToken)(s.apiKey,{baseUrl:s.baseUrl,expiresIn:300,allowedFunctions:[`${e.app}/${n}`],bindPrincipal:!0,...e.sharedApp?{sharedApp:!0}:{}})).token}),o=r[n];if(typeof o!="function")throw new Error(`app "${e.app}" has no function "${n}" \u2014 the pooler cannot dial a slot for it`);let l={concurrencyKey:t,...e.sharedApp?{sharedApp:!0}:{}},p=o.call(r,void 0,l);if(p===null||typeof p!="object")throw new Error(`app "${e.app}" function "${n}" returned no session`);let y=p;return At({session:y,sessionId:t,goneWatch:Pt(y,t,{armOnFirstSync:!0})})}}function dr(){let s=null;s=Ke({streams:j.default,note:e=>{s?.isDead("stderr")!==!0&&ne(j.default.stderr,e)}})}async function cr(){dr();let s=St(j.default.env),e=d=>{ne(j.default.stdout,`${d}
316
- `)},t=new Nt.Redis(s.valkeyUrl,{maxRetriesPerRequest:null}),n=new re({eval:(d,g,T)=>t.eval(d,g.length,...g,...T)},"pooler"),r=Ot(s),o=new le({journal:new se,registry:n,queueDeadlineMs:6e4,silenceDeadlineMs:33e4,backlogThreshold:8,mint:(d,g,T)=>{let k=s.targets.find(I=>I.region===d&&I.model===g);return k===void 0?Promise.reject(new Error(`no pooler target for ${d}:${g} \u2014 refusing to mint`)):r(k,T)},limits:s.targets.map(({region:d,model:g,min:T,max:k})=>({region:d,model:g,min:T,max:k})),scaleUpWaitMs:5e3,mintCooldownMs:1e4,sessionIdleTtlMs:6e4,idleSweepMs:5e3,onEvent:d=>{wt.has(d.kind)&&e(`[pooler] ${d.kind} ${JSON.stringify(d)}`)}});await o.warm();let l=s.laneRuntimeKey,p=s.laneDocHostUrl===void 0?void 0:ut({docHostUrl:s.laneDocHostUrl,redis:t,...l?{mintRuntimeToken:d=>ft(d,s.orgId,l,pt,ct)}:{}}),{server:y,close:R}=kt({pooler:o,token:s.token,lanePlane:p,log:e});await new Promise((d,g)=>{y.once("error",g),y.listen(s.port,s.bindHost,()=>d())}),e(`urun-pooler listening on http://${s.bindHost}:${s.port} (targets ${s.targets.map(d=>`${d.region}:${d.model} min=${d.min} max=${d.max}`).join(", ")})${p===void 0?"":" lanes=on"}`);let _=async d=>{e(`urun-pooler: ${d} \u2014 draining`),await R(),await o.close(),await p?.close(),await t.quit().catch(()=>{})};await new Promise(d=>{j.default.once("SIGINT",()=>{_("SIGINT").finally(d)}),j.default.once("SIGTERM",()=>{_("SIGTERM").finally(d)})})}cr().then(()=>j.default.exit(0),s=>{ne(j.default.stderr,`urun-pooler failed: ${s instanceof Error?`${s.name}: ${s.message}`:String(s)}
315
+ `);return}if(s.lanePlane&&r.method==="GET"&&l.pathname===Yn){if(r.headers.authorization!==`Bearer ${s.token}`){q(i,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}i.writeHead(200,{"content-type":"application/json"}),i.end(JSON.stringify({pools:await s.lanePlane.status()}));return}if(s.lanePlane&&r.method==="POST"&&l.pathname===Bn){if(r.headers.authorization!==`Bearer ${s.token}`){q(i,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let _;try{_=JSON.parse(await Rt(r))}catch(k){q(i,400,k instanceof Error?k.message:String(k),"invalid_request");return}let d=_??{};if(typeof d.pool!="string"||d.pool===""){q(i,400,"pool is required","invalid_request");return}let g=d.hold_ms;if(g!==void 0&&(typeof g!="number"||!Number.isInteger(g)||g<0||g>12e4)){q(i,400,"hold_ms must be an integer in 0..120000","invalid_request");return}let T=typeof d.model=="string"&&d.model!==""?d.model:void 0;try{let k=await s.lanePlane.pick({pool:d.pool,model:T,holdMs:g??0});if(k.length===0){q(i,503,"no capacity available for this model right now, retry shortly","lane_capacity",2);return}i.writeHead(200,{"content-type":"application/json"}),i.end(JSON.stringify({lanes:k.map(I=>({lane_id:I.laneId,host:I.host}))}))}catch(k){t(`[pooler] lane pick for ${d.pool} failed: ${k instanceof Error?k.message:String(k)}`),q(i,500,"the pooler lane plane failed this pick","pooler_error")}return}if(r.method!=="POST"||l.pathname!==Hn){q(i,404,`no route for ${r.method??""} ${l.pathname}`,"not_found");return}if(r.headers.authorization!==`Bearer ${s.token}`){q(i,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let p;try{p=JSON.parse(await Rt(r))}catch(_){q(i,400,_ instanceof Error?_.message:String(_),"invalid_request");return}let y=Jn(p);if("reason"in y){q(i,400,y.reason,"invalid_request");return}let R=new Re(i,y.value.streaming,e);R.head();try{await s.pooler.submit(y.value.request,R)}catch(_){t(`[pooler] request ${y.value.request.request_id} failed unexpectedly: ${_ instanceof Error?_.message:String(_)}`),R.fail({status:500,code:"pooler_error",message:"the pooler failed to serve this request"})}})()});return{server:n,close:()=>new Promise(r=>n.close(()=>r()))}}S();var ue=require("@urun-sh/core");S();var Wn=3,zn="llm",Qn=new Set(["paused","error"]);function Pt(s,e,t){let n=s.doc(zn),r=typeof n.onConnectionState=="function",i=typeof s.onPhase=="function";if(!r&&!i)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 l=null,p=!1,y=new Set,R=[],_=d=>{if(!l){l=d;for(let g of[...y])g(d);y.clear()}};return r&&R.push(n.onConnectionState(d=>{p&&(d.consecutiveFailures<Wn||_(new H(`the pooled session for app "${e}" is gone: its doc backhaul failed ${d.consecutiveFailures} consecutive times (last close ${d.lastCloseCode===null?"by provider liveness reap":`code ${d.lastCloseCode}`}${d.lastCloseReason?`, reason ${JSON.stringify(d.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),t?.armOnFirstSync===!0&&typeof n.onSynced=="function"?R.push(n.onSynced(()=>{p=!0})):i&&R.push(s.onPhase(d=>{if(d.name==="live"){p=!0;return}p&&Qn.has(d.name)&&_(new H(`the pooled session for app "${e}" lost its compute binding (phase "${d.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>l,onGone(d){return l?(d(l),()=>{}):(y.add(d),()=>y.delete(d))},dispose(){y.clear();for(let d of R.splice(0))d()}}}S();var xt=require("@urun-sh/core");S();async function Tt(s,e,t){if(s.synced===!0||typeof s.onSynced!="function")return;let n;await new Promise((r,i)=>{let l=s.onSynced(()=>{clearTimeout(n),r()});n=setTimeout(()=>{l(),i(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${t} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}var Zn=new Set(["accepted","done","error"]);function er(s){if(s===null||typeof s!="object")return{};let e=s,t={};for(let[n,r]of Object.entries(e)){let i=r===null||typeof r!="object"?null:r.toJSON;t[n]=typeof i=="function"?i.call(r):r}return t}function tr(s){if(s===null||typeof s!="object")return null;let e=s,t=e.status;return t!==void 0&&(typeof t!="string"||!Zn.has(t))?null:{attempt:typeof e.attempt=="number"?e.attempt:0,...typeof t=="string"?{status:t}:{},...typeof e.error=="string"?{error:e.error}:{}}}function It(s){let e=er(s.get()),t=Number(e[vt]??0),n={},r=e[Se];if(r!==null&&typeof r=="object")for(let[i,l]of Object.entries(r)){let p=tr(l);p!==null&&(n[i]=p)}return{freeSlots:Number.isFinite(t)?t:0,inflight:n,liveSeen:e[be]===!0}}function nr(s){if(s===xt.STREAM_END)return{t:"end"};if(s===null||typeof s!="object")return null;let e=s;return e.t==="delta"?{t:"delta",...typeof e.delta=="string"?{delta:e.delta}:{},...typeof e.reasoning=="string"?{reasoning:e.reasoning}:{},...e.tool_calls!==void 0?{tool_calls:e.tool_calls}:{}}:e.t==="response"||e.t==="error"?{t:e.t,body:e.body??s}:null}async function*rr(s,e){let t=s.stream(yt(e)),n=!1;try{for await(let r of t.messages()){let i=nr(r);if(i!==null&&(yield i,i.t!=="delta")){n=!0;return}}}catch(r){throw new B(e,r instanceof Error?r.message:String(r))}if(!n)throw new B(e,"the reply stream ended without a terminal chunk (urun-stream-v1 is at-most-once across a reconnect)")}function At(s){let{session:e,sessionId:t,goneWatch:n}=s;if(typeof e.whenLive!="function")throw new Error(`pooler session ${t} exposes no whenLive \u2014 a request must never be pushed into a session whose admission is unproven (the cold-wake gate is a contract, not an option)`);if(typeof e.end!="function")throw new Error(`pooler session ${t} exposes no end \u2014 the pooler is the attached client and must be able to release it`);if(typeof e.phase!="object"||e.phase===null||typeof e.phase.name!="string")throw new Error(`pooler session ${t} exposes no phase surface \u2014 the servability probe reads core's own phase name live, and a wrapper must never fabricate one`);let r=()=>e.doc(mt),i=!1;return"onPhase"in e&&typeof e.onPhase=="function"&&e.onPhase(l=>{l.name==="live"&&(i=!0)}),{sessionId:t,snapshot:()=>It(r()),onDocChange:l=>r().on("change",()=>l()),onGone:l=>n.onGone(l),gone:()=>n.gone(),phaseName:()=>(e.phase.name==="live"&&(i=!0),e.phase.name),everLive:()=>i||It(r()).liveSeen,markLiveSeen:async()=>{await Tt(r(),15e3,"the durable live-seen mark"),r().set({[be]:!0})},whenLive:l=>e.whenLive(l),markInflight:(l,p)=>(r().set({[Se]:{[l]:{attempt:p}}}),Promise.resolve()),push:l=>(r().set({[ve]:{[l.request_id]:{...l.payload,request_id:l.request_id,consumer_id:l.consumer_id,stream:l.stream}}}),Promise.resolve()),clearRequest:l=>{try{r().set({[ve]:{[l]:null}})}catch{}return Promise.resolve()},reply:l=>rr(e,l),end:async()=>{await e.end(),n.dispose()}}}function Ot(s){return async(e,t)=>{let n=e.fn??_t,r=(0,ue.App)(e.app,{baseUrl:s.baseUrl,orgId:s.orgId,getAccessToken:async()=>(await(0,ue.createClientToken)(s.apiKey,{baseUrl:s.baseUrl,expiresIn:300,allowedFunctions:[`${e.app}/${n}`],bindPrincipal:!0,...e.sharedApp?{sharedApp:!0}:{}})).token}),i=r[n];if(typeof i!="function")throw new Error(`app "${e.app}" has no function "${n}" \u2014 the pooler cannot dial a slot for it`);let l={concurrencyKey:t,...e.sharedApp?{sharedApp:!0}:{}},p=i.call(r,void 0,l);if(p===null||typeof p!="object")throw new Error(`app "${e.app}" function "${n}" returned no session`);let y=p;return At({session:y,sessionId:t,goneWatch:Pt(y,t,{armOnFirstSync:!0})})}}function cr(){let s=null;s=Ke({streams:j.default,note:e=>{s?.isDead("stderr")!==!0&&ne(j.default.stderr,e)}})}async function pr(){cr();let s=St(j.default.env),e=d=>{ne(j.default.stdout,`${d}
316
+ `)},t=new Nt.Redis(s.valkeyUrl,{maxRetriesPerRequest:null}),n=new re({eval:(d,g,T)=>t.eval(d,g.length,...g,...T)},"pooler"),r=Ot(s),i=new le({journal:new se,registry:n,queueDeadlineMs:6e4,silenceDeadlineMs:33e4,backlogThreshold:8,mint:(d,g,T)=>{let k=s.targets.find(I=>I.region===d&&I.model===g);return k===void 0?Promise.reject(new Error(`no pooler target for ${d}:${g} \u2014 refusing to mint`)):r(k,T)},limits:s.targets.map(({region:d,model:g,min:T,max:k})=>({region:d,model:g,min:T,max:k})),scaleUpWaitMs:5e3,mintCooldownMs:1e4,sessionIdleTtlMs:6e4,idleSweepMs:5e3,onEvent:d=>{wt.has(d.kind)&&e(`[pooler] ${d.kind} ${JSON.stringify(d)}`)}});await i.warm();let l=s.laneRuntimeKey,p=s.laneDocHostUrl===void 0?void 0:ut({docHostUrl:s.laneDocHostUrl,redis:t,...l?{mintRuntimeToken:d=>ft(d,s.orgId,l,pt,ct)}:{}}),{server:y,close:R}=kt({pooler:i,token:s.token,lanePlane:p,log:e});await new Promise((d,g)=>{y.once("error",g),y.listen(s.port,s.bindHost,()=>d())}),e(`urun-pooler listening on http://${s.bindHost}:${s.port} (targets ${s.targets.map(d=>`${d.region}:${d.model} min=${d.min} max=${d.max}`).join(", ")})${p===void 0?"":" lanes=on"}`);let _=async d=>{e(`urun-pooler: ${d} \u2014 draining`),await R(),await i.close(),await p?.close(),await t.quit().catch(()=>{})};await new Promise(d=>{j.default.once("SIGINT",()=>{_("SIGINT").finally(d)}),j.default.once("SIGTERM",()=>{_("SIGTERM").finally(d)})})}pr().then(()=>j.default.exit(0),s=>{ne(j.default.stderr,`urun-pooler failed: ${s instanceof Error?`${s.name}: ${s.message}`:String(s)}
317
317
  `),j.default.exit(1)});
318
318
  /*! Bundled license information:
319
319
 
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as Le}from"../chunk-LM4E5YM2.js";import{a as z}from"../chunk-GQTWIDJ6.js";import{s as x,t as Q}from"../chunk-LLFROK6B.js";import{a as X,b as Z,d as ee}from"../chunk-KKCUIOL4.js";import{a as J}from"../chunk-7KRHHEKZ.js";import{j as N}from"../chunk-6K7NOPD5.js";import{b as Oe,c as f}from"../chunk-YSFSRI3D.js";f();var pn=Oe(Le(),1);import b from"process";import{Redis as Pt}from"ioredis";f();f();var U=`
2
+ import{a as Le}from"../chunk-LM4E5YM2.js";import{a as z}from"../chunk-5MH6NSR2.js";import{s as x,t as Q}from"../chunk-B26FENQ3.js";import{a as X,b as Z,d as ee}from"../chunk-KKCUIOL4.js";import{a as J}from"../chunk-7KRHHEKZ.js";import{j as N}from"../chunk-7AI75MPZ.js";import{b as Oe,c as f}from"../chunk-YSFSRI3D.js";f();var pn=Oe(Le(),1);import b from"process";import{Redis as Pt}from"ioredis";f();f();var U=`
3
3
  local slot, retired, meta = KEYS[1], KEYS[2], KEYS[3]
4
4
  local key, gen, now = ARGV[1], tonumber(ARGV[2]), ARGV[3]
5
5
  -- The session-as-routing-identity schema (docs/pooler-session-registry.md