@urun-sh/openai 0.6.33 → 0.6.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/chunk-5VMB5HKE.js +17 -0
  2. package/dist/chunk-6K7NOPD5.js +6 -0
  3. package/dist/chunk-7KRHHEKZ.js +1 -0
  4. package/dist/chunk-ETX6IX25.js +1 -0
  5. package/dist/{chunk-GL7EWL3V.js → chunk-EV4DZCHN.js} +1 -1
  6. package/dist/{chunk-L6HTHDVV.js → chunk-GQTWIDJ6.js} +1 -1
  7. package/dist/{chunk-NL3UBLXV.js → chunk-ITPXS7D4.js} +2 -2
  8. package/dist/{chunk-GR3UAW6P.js → chunk-LOPBORFM.js} +1 -1
  9. package/dist/chunk-UO6N5FH7.js +2 -0
  10. package/dist/{composite-CwfOOT0b.d.cts → composite-DGytPb8F.d.cts} +10 -8
  11. package/dist/gemini-live.cjs +2 -2
  12. package/dist/gemini-live.d.cts +0 -26
  13. package/dist/gemini-live.d.ts +0 -5
  14. package/dist/gemini-live.js +1 -1
  15. package/dist/hosted/bin.cjs +44 -44
  16. package/dist/hosted/bin.js +1 -1
  17. package/dist/hosted/index.cjs +38 -38
  18. package/dist/hosted/index.d.cts +44 -1
  19. package/dist/hosted/index.d.ts +9 -1
  20. package/dist/hosted/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/pi-extension/index.cjs +7 -7
  24. package/dist/pi-extension/index.js +1 -1
  25. package/dist/pi-extension/standalone.cjs +41 -41
  26. package/dist/pooler/bin.cjs +24 -24
  27. package/dist/pooler/bin.js +23 -23
  28. package/dist/proxy/cli.cjs +37 -37
  29. package/dist/proxy/cli.js +1 -1
  30. package/dist/proxy/index.cjs +13 -13
  31. package/dist/proxy/index.d.cts +2 -2
  32. package/dist/proxy/index.d.ts +2 -2
  33. package/dist/proxy/index.js +1 -1
  34. package/package.json +2 -2
  35. package/dist/chunk-7D2HMQFC.js +0 -2
  36. package/dist/chunk-NN6TQQUG.js +0 -1
  37. package/dist/chunk-OOCRI7ZM.js +0 -6
  38. package/dist/chunk-PBKCUSTI.js +0 -17
  39. /package/dist/{composite-D9VDruCV.d.ts → composite-D4oZXeX4.d.ts} +0 -0
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Vt=Object.create;var Le=Object.defineProperty;var Bt=Object.getOwnPropertyDescriptor;var Jt=Object.getOwnPropertyNames;var Wt=Object.getPrototypeOf,zt=Object.prototype.hasOwnProperty;var Qt=(o,e,t)=>()=>{if(t)throw t[0];try{return o&&(e=o(o=0)),e}catch(n){throw t=[n],n}};var Xt=(o,e)=>()=>{try{return e||o((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var Zt=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jt(e))!zt.call(o,r)&&r!==t&&Le(o,r,{get:()=>e[r],enumerable:!(n=Bt(e,r))||n.enumerable});return o};var ee=(o,e,t)=>(t=o!=null?Vt(Wt(o)):{},Zt(e||!o||!o.__esModule?Le(t,"default",{value:o,enumerable:!0}):t,o));var b=Qt(()=>{"use strict"});var Ge=Xt(()=>{"use strict";b();var De;(function(o){(function(e){var t=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:h(),n=r(o);typeof t.Reflect<"u"&&(n=r(t.Reflect,n)),e(n,t),typeof t.Reflect>"u"&&(t.Reflect=o);function r(y,R){return function(p,d){Object.defineProperty(y,p,{configurable:!0,writable:!0,value:d}),R&&R(p,d)}}function s(){try{return Function("return this;")()}catch{}}function u(){try{return(0,eval)("(function() { return this; })()")}catch{}}function h(){return s()||u()}})(function(e,t){var n=Object.prototype.hasOwnProperty,r=typeof Symbol=="function",s=r&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",u=r&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",h=typeof Object.create=="function",y={__proto__:[]}instanceof Array,R=!h&&!y,p={create:h?function(){return fe(Object.create(null))}:y?function(){return fe({__proto__:null})}:function(){return fe({})},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),w=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:jt(),T=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ht(),P=typeof WeakMap=="function"?WeakMap:Ft(),x=r?Symbol.for("@reflect-metadata:registry"):void 0,I=Lt(),O=Dt(I);function M(i,a,l,c){if(S(l)){if(!Ae(i))throw new TypeError;if(!Oe(a))throw new TypeError;return At(i,a)}else{if(!Ae(i))throw new TypeError;if(!N(a))throw new TypeError;if(!N(c)&&!S(c)&&!J(c))throw new TypeError;return J(c)&&(c=void 0),l=G(l),Ot(i,a,l,c)}}e("decorate",M);function ue(i,a){function l(c,_){if(!N(c))throw new TypeError;if(!S(_)&&!Ut(_))throw new TypeError;ke(i,a,c,_)}return l}e("metadata",ue);function Z(i,a,l,c){if(!N(l))throw new TypeError;return S(c)||(c=G(c)),ke(i,a,l,c)}e("defineMetadata",Z);function V(i,a,l){if(!N(a))throw new TypeError;return S(l)||(l=G(l)),be(i,a,l)}e("hasMetadata",V);function Et(i,a,l){if(!N(a))throw new TypeError;return S(l)||(l=G(l)),de(i,a,l)}e("hasOwnMetadata",Et);function kt(i,a,l){if(!N(a))throw new TypeError;return S(l)||(l=G(l)),Re(i,a,l)}e("getMetadata",kt);function Pt(i,a,l){if(!N(a))throw new TypeError;return S(l)||(l=G(l)),Ee(i,a,l)}e("getOwnMetadata",Pt);function Tt(i,a){if(!N(i))throw new TypeError;return S(a)||(a=G(a)),Pe(i,a)}e("getMetadataKeys",Tt);function It(i,a){if(!N(i))throw new TypeError;return S(a)||(a=G(a)),Te(i,a)}e("getOwnMetadataKeys",It);function xt(i,a,l){if(!N(a))throw new TypeError;if(S(l)||(l=G(l)),!N(a))throw new TypeError;S(l)||(l=G(l));var c=Q(a,l,!1);return S(c)?!1:c.OrdinaryDeleteMetadata(i,a,l)}e("deleteMetadata",xt);function At(i,a){for(var l=i.length-1;l>=0;--l){var c=i[l],_=c(a);if(!S(_)&&!J(_)){if(!Oe(_))throw new TypeError;a=_}}return a}function Ot(i,a,l,c){for(var _=i.length-1;_>=0;--_){var C=i[_],q=C(a,l,c);if(!S(q)&&!J(q)){if(!N(q))throw new TypeError;c=q}}return c}function be(i,a,l){var c=de(i,a,l);if(c)return!0;var _=pe(a);return J(_)?!1:be(i,_,l)}function de(i,a,l){var c=Q(a,l,!1);return S(c)?!1:xe(c.OrdinaryHasOwnMetadata(i,a,l))}function Re(i,a,l){var c=de(i,a,l);if(c)return Ee(i,a,l);var _=pe(a);if(!J(_))return Re(i,_,l)}function Ee(i,a,l){var c=Q(a,l,!1);if(!S(c))return c.OrdinaryGetOwnMetadata(i,a,l)}function ke(i,a,l,c){var _=Q(l,c,!0);_.OrdinaryDefineOwnMetadata(i,a,l,c)}function Pe(i,a){var l=Te(i,a),c=pe(i);if(c===null)return l;var _=Pe(c,a);if(_.length<=0)return l;if(l.length<=0)return _;for(var C=new T,q=[],E=0,f=l;E<f.length;E++){var g=f[E],m=C.has(g);m||(C.add(g),q.push(g))}for(var v=0,k=_;v<k.length;v++){var g=k[v],m=C.has(g);m||(C.add(g),q.push(g))}return q}function Te(i,a){var l=Q(i,a,!1);return l?l.OrdinaryOwnMetadataKeys(i,a):[]}function Ie(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 S(i){return i===void 0}function J(i){return i===null}function Mt(i){return typeof i=="symbol"}function N(i){return typeof i=="object"?i!==null:typeof i=="function"}function Nt(i,a){switch(Ie(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 l=a===3?"string":a===5?"number":"default",c=Me(i,s);if(c!==void 0){var _=c.call(i,l);if(N(_))throw new TypeError;return _}return Ct(i,l==="default"?"number":l)}function Ct(i,a){if(a==="string"){var l=i.toString;if(W(l)){var c=l.call(i);if(!N(c))return c}var _=i.valueOf;if(W(_)){var c=_.call(i);if(!N(c))return c}}else{var _=i.valueOf;if(W(_)){var c=_.call(i);if(!N(c))return c}var C=i.toString;if(W(C)){var c=C.call(i);if(!N(c))return c}}throw new TypeError}function xe(i){return!!i}function $t(i){return""+i}function G(i){var a=Nt(i,3);return Mt(a)?a:$t(a)}function Ae(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 Oe(i){return typeof i=="function"}function Ut(i){switch(Ie(i)){case 3:return!0;case 4:return!0;default:return!1}}function ce(i,a){return i===a||i!==i&&a!==a}function Me(i,a){var l=i[a];if(l!=null){if(!W(l))throw new TypeError;return l}}function Ne(i){var a=Me(i,u);if(!W(a))throw new TypeError;var l=a.call(i);if(!N(l))throw new TypeError;return l}function Ce(i){return i.value}function $e(i){var a=i.next();return a.done?!1:a}function Ue(i){var a=i.return;a&&a.call(i)}function pe(i){var a=Object.getPrototypeOf(i);if(typeof i!="function"||i===d||a!==d)return a;var l=i.prototype,c=l&&Object.getPrototypeOf(l);if(c==null||c===Object.prototype)return a;var _=c.constructor;return typeof _!="function"||_===i?a:_}function qt(){var i;!S(x)&&typeof t.Reflect<"u"&&!(x in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(i=Gt(t.Reflect));var a,l,c,_=new P,C={registerProvider:q,getProvider:f,setProvider:m};return C;function q(v){if(!Object.isExtensible(C))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case i===v:break;case S(a):a=v;break;case a===v:break;case S(l):l=v;break;case l===v:break;default:c===void 0&&(c=new T),c.add(v);break}}function E(v,k){if(!S(a)){if(a.isProviderFor(v,k))return a;if(!S(l)){if(l.isProviderFor(v,k))return a;if(!S(c))for(var A=Ne(c);;){var $=$e(A);if(!$)return;var D=Ce($);if(D.isProviderFor(v,k))return Ue(A),D}}}if(!S(i)&&i.isProviderFor(v,k))return i}function f(v,k){var A=_.get(v),$;return S(A)||($=A.get(k)),S($)&&($=E(v,k),S($)||(S(A)&&(A=new w,_.set(v,A)),A.set(k,$))),$}function g(v){if(S(v))throw new TypeError;return a===v||l===v||!S(c)&&c.has(v)}function m(v,k,A){if(!g(A))throw new Error("Metadata provider not registered.");var $=f(v,k);if($!==A){if(!S($))return!1;var D=_.get(v);S(D)&&(D=new w,_.set(v,D)),D.set(k,A)}return!0}}function Lt(){var i;return!S(x)&&N(t.Reflect)&&Object.isExtensible(t.Reflect)&&(i=t.Reflect[x]),S(i)&&(i=qt()),!S(x)&&N(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,x,{enumerable:!1,configurable:!1,writable:!1,value:i}),i}function Dt(i){var a=new P,l={isProviderFor:function(g,m){var v=a.get(g);return S(v)?!1:v.has(m)},OrdinaryDefineOwnMetadata:q,OrdinaryHasOwnMetadata:_,OrdinaryGetOwnMetadata:C,OrdinaryOwnMetadataKeys:E,OrdinaryDeleteMetadata:f};return I.registerProvider(l),l;function c(g,m,v){var k=a.get(g),A=!1;if(S(k)){if(!v)return;k=new w,a.set(g,k),A=!0}var $=k.get(m);if(S($)){if(!v)return;if($=new w,k.set(m,$),!i.setProvider(g,m,l))throw k.delete(m),A&&a.delete(g),new Error("Wrong provider for target.")}return $}function _(g,m,v){var k=c(m,v,!1);return S(k)?!1:xe(k.has(g))}function C(g,m,v){var k=c(m,v,!1);if(!S(k))return k.get(g)}function q(g,m,v,k){var A=c(v,k,!0);A.set(g,m)}function E(g,m){var v=[],k=c(g,m,!1);if(S(k))return v;for(var A=k.keys(),$=Ne(A),D=0;;){var qe=$e($);if(!qe)return v.length=D,v;var Kt=Ce(qe);try{v[D]=Kt}catch(Yt){try{Ue($)}finally{throw Yt}}D++}}function f(g,m,v){var k=c(m,v,!1);if(S(k)||!k.delete(g))return!1;if(k.size===0){var A=a.get(m);S(A)||(A.delete(v),A.size===0&&a.delete(A))}return!0}}function Gt(i){var a=i.defineMetadata,l=i.hasOwnMetadata,c=i.getOwnMetadata,_=i.getOwnMetadataKeys,C=i.deleteMetadata,q=new P,E={isProviderFor:function(f,g){var m=q.get(f);return!S(m)&&m.has(g)?!0:_(f,g).length?(S(m)&&(m=new T,q.set(f,m)),m.add(g),!0):!1},OrdinaryDefineOwnMetadata:a,OrdinaryHasOwnMetadata:l,OrdinaryGetOwnMetadata:c,OrdinaryOwnMetadataKeys:_,OrdinaryDeleteMetadata:C};return E}function Q(i,a,l){var c=I.getProvider(i,a);if(!S(c))return c;if(l){if(I.setProvider(i,a,O))return O;throw new Error("Illegal state.")}}function jt(){var i={},a=[],l=(function(){function E(f,g,m){this._index=0,this._keys=f,this._values=g,this._selector=m}return E.prototype["@@iterator"]=function(){return this},E.prototype[u]=function(){return this},E.prototype.next=function(){var f=this._index;if(f>=0&&f<this._keys.length){var g=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:g,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 g=this._find(f,!1);return g>=0?this._values[g]:void 0},E.prototype.set=function(f,g){var m=this._find(f,!0);return this._values[m]=g,this},E.prototype.delete=function(f){var g=this._find(f,!1);if(g>=0){for(var m=this._keys.length,v=g+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--,ce(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 l(this._keys,this._values,_)},E.prototype.values=function(){return new l(this._keys,this._values,C)},E.prototype.entries=function(){return new l(this._keys,this._values,q)},E.prototype["@@iterator"]=function(){return this.entries()},E.prototype[u]=function(){return this.entries()},E.prototype._find=function(f,g){if(!ce(this._cacheKey,f)){this._cacheIndex=-1;for(var m=0;m<this._keys.length;m++)if(ce(this._keys[m],f)){this._cacheIndex=m;break}}return this._cacheIndex<0&&g&&(this._cacheIndex=this._keys.length,this._keys.push(f),this._values.push(void 0)),this._cacheIndex},E})();return c;function _(E,f){return E}function C(E,f){return f}function q(E,f){return[E,f]}}function Ht(){var i=(function(){function a(){this._map=new w}return Object.defineProperty(a.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),a.prototype.has=function(l){return this._map.has(l)},a.prototype.add=function(l){return this._map.set(l,l),this},a.prototype.delete=function(l){return this._map.delete(l)},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[u]=function(){return this.keys()},a})();return i}function Ft(){var i=16,a=p.create(),l=c();return(function(){function f(){this._key=c()}return f.prototype.has=function(g){var m=_(g,!1);return m!==void 0?p.has(m,this._key):!1},f.prototype.get=function(g){var m=_(g,!1);return m!==void 0?p.get(m,this._key):void 0},f.prototype.set=function(g,m){var v=_(g,!0);return v[this._key]=m,this},f.prototype.delete=function(g){var m=_(g,!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(p.has(a,f));return a[f]=!0,f}function _(f,g){if(!n.call(f,l)){if(!g)return;Object.defineProperty(f,l,{value:p.create()})}return f[l]}function C(f,g){for(var m=0;m<g;++m)f[m]=Math.random()*255|0;return f}function q(f){if(typeof Uint8Array=="function"){var g=new Uint8Array(f);return typeof crypto<"u"?crypto.getRandomValues(g):typeof msCrypto<"u"?msCrypto.getRandomValues(g):C(g,f),g}return C(new Array(f),f)}function E(){var f=q(i);f[6]=f[6]&79|64,f[8]=f[8]&191|128;for(var g="",m=0;m<i;++m){var v=f[m];(m===4||m===6||m===8)&&(g+="-"),v<16&&(g+="0"),g+=v.toString(16).toLowerCase()}return g}}function fe(i){return i.__=void 0,delete i.__,i}})})(De||(De={}))});b();var Es=ee(Ge(),1),j=ee(require("process"),1),Rt=require("ioredis");b();var rn=ee(require("os"),1),sn=ee(require("path"),1),on=require("url"),an=require("util");b();b();b();b();b();b();var F=class extends Error{};var ln=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function je(o){let e=o?.code;return typeof e=="string"&&ln.has(e)}function te(o,e){try{return o.write(e),!0}catch(t){if(je(t))return!1;throw t}}function He(o){let e={stdout:!1,stderr:!1},t=[];for(let n of["stdout","stderr"]){let r=o.streams[n],s=u=>{je(u)&&(e[n]=!0);let h=u?.code;try{o.note(`${new Date().toISOString()} urun compat: process.${n} died (${String(h??(u instanceof Error?u.message:u))}) \u2014 the terminal is gone; launcher output continues in this log only
3
- `)}catch{}};r.on("error",s),t.push([r,s])}return{isDead:n=>e[n],uninstall:()=>{for(let[n,r]of t)n.off("error",r)}}}b();b();var he=`
2
+ "use strict";var zt=Object.create;var De=Object.defineProperty;var Qt=Object.getOwnPropertyDescriptor;var Xt=Object.getOwnPropertyNames;var Zt=Object.getPrototypeOf,en=Object.prototype.hasOwnProperty;var tn=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(e=s(s=0)),e}catch(n){throw t=[n],n}};var nn=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var rn=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Xt(e))!en.call(s,r)&&r!==t&&De(s,r,{get:()=>e[r],enumerable:!(n=Qt(e,r))||n.enumerable});return s};var ee=(s,e,t)=>(t=s!=null?zt(Zt(s)):{},rn(e||!s||!s.__esModule?De(t,"default",{value:s,enumerable:!0}):t,s));var b=tn(()=>{"use strict"});var je=nn(()=>{"use strict";b();var Ge;(function(s){(function(e){var t=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:h(),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(p,d){Object.defineProperty(y,p,{configurable:!0,writable:!0,value:d}),R&&R(p,d)}}function o(){try{return Function("return this;")()}catch{}}function l(){try{return(0,eval)("(function() { return this; })()")}catch{}}function h(){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",h=typeof Object.create=="function",y={__proto__:[]}instanceof Array,R=!h&&!y,p={create:h?function(){return fe(Object.create(null))}:y?function(){return fe({__proto__:null})}:function(){return fe({})},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),v=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Yt(),T=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Vt(),P=typeof WeakMap=="function"?WeakMap:Bt(),x=r?Symbol.for("@reflect-metadata:registry"):void 0,I=Ht(),O=Ft(I);function M(i,a,u,c){if(S(u)){if(!Oe(i))throw new TypeError;if(!Me(a))throw new TypeError;return $t(i,a)}else{if(!Oe(i))throw new TypeError;if(!N(a))throw new TypeError;if(!N(c)&&!S(c)&&!J(c))throw new TypeError;return J(c)&&(c=void 0),u=G(u),Ct(i,a,u,c)}}e("decorate",M);function ue(i,a){function u(c,_){if(!N(c))throw new TypeError;if(!S(_)&&!Gt(_))throw new TypeError;Pe(i,a,c,_)}return u}e("metadata",ue);function Z(i,a,u,c){if(!N(u))throw new TypeError;return S(c)||(c=G(c)),Pe(i,a,u,c)}e("defineMetadata",Z);function V(i,a,u){if(!N(a))throw new TypeError;return S(u)||(u=G(u)),Re(i,a,u)}e("hasMetadata",V);function It(i,a,u){if(!N(a))throw new TypeError;return S(u)||(u=G(u)),de(i,a,u)}e("hasOwnMetadata",It);function xt(i,a,u){if(!N(a))throw new TypeError;return S(u)||(u=G(u)),Ee(i,a,u)}e("getMetadata",xt);function At(i,a,u){if(!N(a))throw new TypeError;return S(u)||(u=G(u)),ke(i,a,u)}e("getOwnMetadata",At);function Ot(i,a){if(!N(i))throw new TypeError;return S(a)||(a=G(a)),Te(i,a)}e("getMetadataKeys",Ot);function Mt(i,a){if(!N(i))throw new TypeError;return S(a)||(a=G(a)),Ie(i,a)}e("getOwnMetadataKeys",Mt);function Nt(i,a,u){if(!N(a))throw new TypeError;if(S(u)||(u=G(u)),!N(a))throw new TypeError;S(u)||(u=G(u));var c=Q(a,u,!1);return S(c)?!1:c.OrdinaryDeleteMetadata(i,a,u)}e("deleteMetadata",Nt);function $t(i,a){for(var u=i.length-1;u>=0;--u){var c=i[u],_=c(a);if(!S(_)&&!J(_)){if(!Me(_))throw new TypeError;a=_}}return a}function Ct(i,a,u,c){for(var _=i.length-1;_>=0;--_){var $=i[_],L=$(a,u,c);if(!S(L)&&!J(L)){if(!N(L))throw new TypeError;c=L}}return c}function Re(i,a,u){var c=de(i,a,u);if(c)return!0;var _=pe(a);return J(_)?!1:Re(i,_,u)}function de(i,a,u){var c=Q(a,u,!1);return S(c)?!1:Ae(c.OrdinaryHasOwnMetadata(i,a,u))}function Ee(i,a,u){var c=de(i,a,u);if(c)return ke(i,a,u);var _=pe(a);if(!J(_))return Ee(i,_,u)}function ke(i,a,u){var c=Q(a,u,!1);if(!S(c))return c.OrdinaryGetOwnMetadata(i,a,u)}function Pe(i,a,u,c){var _=Q(u,c,!0);_.OrdinaryDefineOwnMetadata(i,a,u,c)}function Te(i,a){var u=Ie(i,a),c=pe(i);if(c===null)return u;var _=Te(c,a);if(_.length<=0)return u;if(u.length<=0)return _;for(var $=new T,L=[],E=0,f=u;E<f.length;E++){var m=f[E],g=$.has(m);g||($.add(m),L.push(m))}for(var w=0,k=_;w<k.length;w++){var m=k[w],g=$.has(m);g||($.add(m),L.push(m))}return L}function Ie(i,a){var u=Q(i,a,!1);return u?u.OrdinaryOwnMetadataKeys(i,a):[]}function xe(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 S(i){return i===void 0}function J(i){return i===null}function Ut(i){return typeof i=="symbol"}function N(i){return typeof i=="object"?i!==null:typeof i=="function"}function Lt(i,a){switch(xe(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=Ne(i,o);if(c!==void 0){var _=c.call(i,u);if(N(_))throw new TypeError;return _}return qt(i,u==="default"?"number":u)}function qt(i,a){if(a==="string"){var u=i.toString;if(W(u)){var c=u.call(i);if(!N(c))return c}var _=i.valueOf;if(W(_)){var c=_.call(i);if(!N(c))return c}}else{var _=i.valueOf;if(W(_)){var c=_.call(i);if(!N(c))return c}var $=i.toString;if(W($)){var c=$.call(i);if(!N(c))return c}}throw new TypeError}function Ae(i){return!!i}function Dt(i){return""+i}function G(i){var a=Lt(i,3);return Ut(a)?a:Dt(a)}function Oe(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 Gt(i){switch(xe(i)){case 3:return!0;case 4:return!0;default:return!1}}function ce(i,a){return i===a||i!==i&&a!==a}function Ne(i,a){var u=i[a];if(u!=null){if(!W(u))throw new TypeError;return u}}function $e(i){var a=Ne(i,l);if(!W(a))throw new TypeError;var u=a.call(i);if(!N(u))throw new TypeError;return u}function Ce(i){return i.value}function Ue(i){var a=i.next();return a.done?!1:a}function Le(i){var a=i.return;a&&a.call(i)}function pe(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 _=c.constructor;return typeof _!="function"||_===i?a:_}function jt(){var i;!S(x)&&typeof t.Reflect<"u"&&!(x in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(i=Kt(t.Reflect));var a,u,c,_=new P,$={registerProvider:L,getProvider:f,setProvider:g};return $;function L(w){if(!Object.isExtensible($))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case i===w:break;case S(a):a=w;break;case a===w:break;case S(u):u=w;break;case u===w:break;default:c===void 0&&(c=new T),c.add(w);break}}function E(w,k){if(!S(a)){if(a.isProviderFor(w,k))return a;if(!S(u)){if(u.isProviderFor(w,k))return a;if(!S(c))for(var A=$e(c);;){var C=Ue(A);if(!C)return;var D=Ce(C);if(D.isProviderFor(w,k))return Le(A),D}}}if(!S(i)&&i.isProviderFor(w,k))return i}function f(w,k){var A=_.get(w),C;return S(A)||(C=A.get(k)),S(C)&&(C=E(w,k),S(C)||(S(A)&&(A=new v,_.set(w,A)),A.set(k,C))),C}function m(w){if(S(w))throw new TypeError;return a===w||u===w||!S(c)&&c.has(w)}function g(w,k,A){if(!m(A))throw new Error("Metadata provider not registered.");var C=f(w,k);if(C!==A){if(!S(C))return!1;var D=_.get(w);S(D)&&(D=new v,_.set(w,D)),D.set(k,A)}return!0}}function Ht(){var i;return!S(x)&&N(t.Reflect)&&Object.isExtensible(t.Reflect)&&(i=t.Reflect[x]),S(i)&&(i=jt()),!S(x)&&N(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,x,{enumerable:!1,configurable:!1,writable:!1,value:i}),i}function Ft(i){var a=new P,u={isProviderFor:function(m,g){var w=a.get(m);return S(w)?!1:w.has(g)},OrdinaryDefineOwnMetadata:L,OrdinaryHasOwnMetadata:_,OrdinaryGetOwnMetadata:$,OrdinaryOwnMetadataKeys:E,OrdinaryDeleteMetadata:f};return I.registerProvider(u),u;function c(m,g,w){var k=a.get(m),A=!1;if(S(k)){if(!w)return;k=new v,a.set(m,k),A=!0}var C=k.get(g);if(S(C)){if(!w)return;if(C=new v,k.set(g,C),!i.setProvider(m,g,u))throw k.delete(g),A&&a.delete(m),new Error("Wrong provider for target.")}return C}function _(m,g,w){var k=c(g,w,!1);return S(k)?!1:Ae(k.has(m))}function $(m,g,w){var k=c(g,w,!1);if(!S(k))return k.get(m)}function L(m,g,w,k){var A=c(w,k,!0);A.set(m,g)}function E(m,g){var w=[],k=c(m,g,!1);if(S(k))return w;for(var A=k.keys(),C=$e(A),D=0;;){var qe=Ue(C);if(!qe)return w.length=D,w;var Jt=Ce(qe);try{w[D]=Jt}catch(Wt){try{Le(C)}finally{throw Wt}}D++}}function f(m,g,w){var k=c(g,w,!1);if(S(k)||!k.delete(m))return!1;if(k.size===0){var A=a.get(g);S(A)||(A.delete(w),A.size===0&&a.delete(A))}return!0}}function Kt(i){var a=i.defineMetadata,u=i.hasOwnMetadata,c=i.getOwnMetadata,_=i.getOwnMetadataKeys,$=i.deleteMetadata,L=new P,E={isProviderFor:function(f,m){var g=L.get(f);return!S(g)&&g.has(m)?!0:_(f,m).length?(S(g)&&(g=new T,L.set(f,g)),g.add(m),!0):!1},OrdinaryDefineOwnMetadata:a,OrdinaryHasOwnMetadata:u,OrdinaryGetOwnMetadata:c,OrdinaryOwnMetadataKeys:_,OrdinaryDeleteMetadata:$};return E}function Q(i,a,u){var c=I.getProvider(i,a);if(!S(c))return c;if(u){if(I.setProvider(i,a,O))return O;throw new Error("Illegal state.")}}function Yt(){var i={},a=[],u=(function(){function E(f,m,g){this._index=0,this._keys=f,this._values=m,this._selector=g}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 m=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:m,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 m=this._find(f,!1);return m>=0?this._values[m]:void 0},E.prototype.set=function(f,m){var g=this._find(f,!0);return this._values[g]=m,this},E.prototype.delete=function(f){var m=this._find(f,!1);if(m>=0){for(var g=this._keys.length,w=m+1;w<g;w++)this._keys[w-1]=this._keys[w],this._values[w-1]=this._values[w];return this._keys.length--,this._values.length--,ce(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,_)},E.prototype.values=function(){return new u(this._keys,this._values,$)},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,m){if(!ce(this._cacheKey,f)){this._cacheIndex=-1;for(var g=0;g<this._keys.length;g++)if(ce(this._keys[g],f)){this._cacheIndex=g;break}}return this._cacheIndex<0&&m&&(this._cacheIndex=this._keys.length,this._keys.push(f),this._values.push(void 0)),this._cacheIndex},E})();return c;function _(E,f){return E}function $(E,f){return f}function L(E,f){return[E,f]}}function Vt(){var i=(function(){function a(){this._map=new v}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 Bt(){var i=16,a=p.create(),u=c();return(function(){function f(){this._key=c()}return f.prototype.has=function(m){var g=_(m,!1);return g!==void 0?p.has(g,this._key):!1},f.prototype.get=function(m){var g=_(m,!1);return g!==void 0?p.get(g,this._key):void 0},f.prototype.set=function(m,g){var w=_(m,!0);return w[this._key]=g,this},f.prototype.delete=function(m){var g=_(m,!1);return g!==void 0?delete g[this._key]:!1},f.prototype.clear=function(){this._key=c()},f})();function c(){var f;do f="@@WeakMap@@"+E();while(p.has(a,f));return a[f]=!0,f}function _(f,m){if(!n.call(f,u)){if(!m)return;Object.defineProperty(f,u,{value:p.create()})}return f[u]}function $(f,m){for(var g=0;g<m;++g)f[g]=Math.random()*255|0;return f}function L(f){if(typeof Uint8Array=="function"){var m=new Uint8Array(f);return typeof crypto<"u"?crypto.getRandomValues(m):typeof msCrypto<"u"?msCrypto.getRandomValues(m):$(m,f),m}return $(new Array(f),f)}function E(){var f=L(i);f[6]=f[6]&79|64,f[8]=f[8]&191|128;for(var m="",g=0;g<i;++g){var w=f[g];(g===4||g===6||g===8)&&(m+="-"),w<16&&(m+="0"),m+=w.toString(16).toLowerCase()}return m}}function fe(i){return i.__=void 0,delete i.__,i}})})(Ge||(Ge={}))});b();var Ms=ee(je(),1),j=ee(require("process"),1),Tt=require("ioredis");b();var ln=ee(require("os"),1),un=ee(require("path"),1),dn=require("url"),cn=require("util");b();b();b();b();b();b();var H=class extends Error{};var pn=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function He(s){let e=s?.code;return typeof e=="string"&&pn.has(e)}function te(s,e){try{return s.write(e),!0}catch(t){if(He(t))return!1;throw t}}function Fe(s){let e={stdout:!1,stderr:!1},t=[];for(let n of["stdout","stderr"]){let r=s.streams[n],o=l=>{He(l)&&(e[n]=!0);let h=l?.code;try{s.note(`${new Date().toISOString()} urun compat: process.${n} died (${String(h??(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)}}}b();b();var he=`
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
@@ -39,7 +39,7 @@ if cacheNs then
39
39
  end
40
40
  redis.call('HINCRBY', meta, 'queued', 1)
41
41
  return 'ok'
42
- `,ge=`
42
+ `,me=`
43
43
  local slot, genkey, retired, meta = KEYS[1], KEYS[2], KEYS[3], KEYS[4]
44
44
  local key, gen, sessionId, now = ARGV[1], tonumber(ARGV[2]), ARGV[3], ARGV[4]
45
45
  -- The session-registry schema (\xA72.3): ARGV[5] is the caller's OBSERVED
@@ -81,7 +81,7 @@ redis.call('HSET', slot, 'state', 'attached', 'sessionId', sessionId, 'since', n
81
81
  redis.call('HINCRBY', meta, 'queued', -1)
82
82
  redis.call('HINCRBY', meta, 'attached', 1)
83
83
  return 'ok'
84
- `,Fe=`
84
+ `,Ke=`
85
85
  local slot, meta = KEYS[1], KEYS[2]
86
86
  local key, reason, now = ARGV[1], ARGV[2], ARGV[3]
87
87
  local state = redis.call('HGET', slot, 'state')
@@ -95,7 +95,7 @@ redis.call('HSET', slot, 'state', 'paused', 'since', now, 'lastReason', reason)
95
95
  redis.call('HINCRBY', meta, state, -1)
96
96
  redis.call('HINCRBY', meta, 'paused', 1)
97
97
  return 'ok'
98
- `,Ke=`
98
+ `,Ye=`
99
99
  local slot, genkey, retired, meta, newslot = KEYS[1], KEYS[2], KEYS[3], KEYS[4], KEYS[5]
100
100
  local oldKey, newKey, newGen = ARGV[1], ARGV[2], tonumber(ARGV[3])
101
101
  if redis.call('SISMEMBER', retired, oldKey) == 1 then
@@ -120,7 +120,7 @@ if redis.call('HSETNX', newslot, 'state', 'paused') == 1 then
120
120
  redis.call('HINCRBY', meta, 'paused', 1)
121
121
  end
122
122
  return 'ok'
123
- `,Ye=`
123
+ `,Ve=`
124
124
  local slot, meta = KEYS[1], KEYS[2]
125
125
  local key, now = ARGV[1], ARGV[2]
126
126
  local state = redis.call('HGET', slot, 'state')
@@ -141,7 +141,7 @@ redis.call('HSET', slot, 'state', 'ended', 'since', now)
141
141
  redis.call('HINCRBY', meta, state, -1)
142
142
  redis.call('HINCRBY', meta, 'ended', 1)
143
143
  return 'ok'
144
- `,Ve=`
144
+ `,Be=`
145
145
  local slot, meta = KEYS[1], KEYS[2]
146
146
  local key = ARGV[1]
147
147
  local state = redis.call('HGET', slot, 'state')
@@ -191,12 +191,12 @@ end
191
191
  redis.call('HINCRBY', slot, 'inFlight', 1)
192
192
  redis.call('HINCRBY', meta, 'inflight', 1)
193
193
  return 'ok'
194
- `,Be=`
194
+ `,Je=`
195
195
  local meta = KEYS[1]
196
196
  return (redis.call('HGET', meta, 'max') or '-1')
197
197
  .. '|' .. (redis.call('HGET', meta, 'cap') or '-1')
198
198
  .. '|' .. (redis.call('HGET', meta, 'config_version') or '0')
199
- `,Je=`
199
+ `,We=`
200
200
  local slot, meta = KEYS[1], KEYS[2]
201
201
  local key, now = ARGV[1], ARGV[2]
202
202
  local state = redis.call('HGET', slot, 'state')
@@ -213,7 +213,7 @@ end
213
213
  redis.call('HSET', slot, 'inFlight', f - 1, 'idleSince', now)
214
214
  redis.call('HINCRBY', meta, 'inflight', -1)
215
215
  return 'ok'
216
- `,We=`
216
+ `,ze=`
217
217
  local meta = KEYS[1]
218
218
  local max, cap = tonumber(ARGV[1]), tonumber(ARGV[2])
219
219
  if not max or max < 0 or not cap or cap < 1 then
@@ -222,7 +222,7 @@ end
222
222
  redis.call('HSET', meta, 'max', max, 'cap', cap)
223
223
  redis.call('HINCRBY', meta, 'config_version', 1)
224
224
  return 'ok'
225
- `,ze=`
225
+ `,Qe=`
226
226
  local meta = KEYS[1]
227
227
  local max, cap = tonumber(ARGV[1]), tonumber(ARGV[2])
228
228
  if not max or max < 0 or not cap or cap < 1 then
@@ -233,7 +233,7 @@ if redis.call('HSETNX', meta, 'max', max) == 0 then
233
233
  end
234
234
  redis.call('HSET', meta, 'cap', cap)
235
235
  return 'ok'
236
- `,Qe=`
236
+ `,Xe=`
237
237
  local prefix, meta = ARGV[1], KEYS[1]
238
238
  local cursor, pageSize = ARGV[2], tonumber(ARGV[3])
239
239
  local lines = {}
@@ -256,29 +256,29 @@ for i = 1, #fields, 2 do
256
256
  m[#m + 1] = fields[i] .. '=' .. (fields[i + 1] or '')
257
257
  end
258
258
  return next .. '#' .. table.concat(m, ',') .. '#' .. table.concat(lines, '\\n')
259
- `,Xe=`
259
+ `,Ze=`
260
260
  local fields = redis.call('HGETALL', KEYS[1])
261
261
  local m = {}
262
262
  for i = 1, #fields, 2 do
263
263
  m[#m + 1] = fields[i] .. '=' .. (fields[i + 1] or '')
264
264
  end
265
265
  return table.concat(m, ',')
266
- `,Ze=`
266
+ `,et=`
267
267
  local out = {}
268
268
  for i = 1, #ARGV do
269
269
  out[#out + 1] = (redis.call('HGET', ARGV[i], 'state') or 'none')
270
270
  .. '|' .. (redis.call('HGET', ARGV[i], 'inFlight') or '0')
271
271
  end
272
272
  return table.concat(out, '\\n')
273
- `,et=`
273
+ `,tt=`
274
274
  local gen = redis.call('GET', KEYS[1])
275
275
  if not gen then return '0' end
276
276
  return gen
277
- `,tt=`
277
+ `,nt=`
278
278
  local state = redis.call('HGET', KEYS[1], 'state')
279
279
  if not state then return 'none||' end
280
280
  return state .. '|' .. (redis.call('HGET', KEYS[1], 'sessionId') or '') .. '|' .. (redis.call('HGET', KEYS[1], 'lastReason') or '')
281
- `,nt=`
281
+ `,rt=`
282
282
  local slot = KEYS[1]
283
283
  local key, obsEpoch = ARGV[1], tonumber(ARGV[2])
284
284
  local state = redis.call('HGET', slot, 'state')
@@ -298,22 +298,22 @@ redis.call('HSET', slot,
298
298
  'cacheGen', ARGV[5],
299
299
  'capabilities', ARGV[6])
300
300
  return 'ok'
301
- `;var B=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},un=100,rt=o=>{let e={attached:0,queued:0,paused:0,retired:0,ended:0,inflight:0};for(let t of o.split(",")){if(t==="")continue;let[n,r]=t.split("=");n in e&&(e[n]=Number(r))}return e},dn=o=>(o===""?[]:o.split(`
302
- `)).map(e=>{let[t,n,r,s,u]=e.split("|");return{key:t,state:n,inFlight:Number(r),gen:Number(s),sessionId:u}});function H(o){let e=o.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 "${o}" (expected decision:{replica}:{index}[:{gen}])`);return{base:o,index:Number(t),gen:0}}var K=()=>String(Date.now()),ne=class{constructor(e,t){this.evalFn=e;this.pool=t}evalFn;pool;keys(e,t=!0,n=!0){let{base:r}=H(e),s=[`sreg:${this.pool}:slot:${e}`];return t&&s.push(`sreg:${this.pool}:gen:${r}`),n&&s.push(`sreg:${this.pool}:retired`),s.push(`sreg:${this.pool}:meta`),s}async run(e,t,n,r,s){let u=await this.evalFn.eval(t,n,r);if(u.startsWith("reject:"))throw new B(e,u,{pool:this.pool,...s})}mint(e){let{gen:t}=H(e);return this.run("mint",he,this.keys(e,!1,!0),[e,t,K()],{slotKey:e,gen:t})}mintWith(e,t){let{gen:n}=H(e);return this.run("mint",he,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}=H(e);return this.run("attach",ge,this.keys(e),[e,r,t,K(),n],{slotKey:e,gen:r,sessionId:t,observedEpoch:n})}publish(e,t,n){return this.run("publish",nt,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}=H(e);return this.run("attach",ge,this.keys(e),[e,n,t,K()],{slotKey:e,gen:n,sessionId:t})}detach(e,t){return this.run("detach",Fe,this.keys(e,!1,!1),[e,t,K()],{slotKey:e,reason:t})}rotate(e,t){let{gen:n}=H(t),r=[...this.keys(e),`sreg:${this.pool}:slot:${t}`];return this.run("rotate",Ke,r,[e,t,n,K()],{oldKey:e,newKey:t,newGen:n})}end(e){return this.run("end",Ye,this.keys(e,!1,!1),[e,K()],{slotKey:e})}lease(e){return this.run("lease",Ve,this.keys(e,!1,!1),[e],{slotKey:e})}release(e){return this.run("release",Je,this.keys(e,!1,!1),[e,K()],{slotKey:e})}configure(e,t){return this.run("config",ze,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}retune(e,t){return this.run("retune",We,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}async tuning(){let e=await this.evalFn.eval(Be,[`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 s=await this.tuning();r=await this.evalFn.eval(X,n,[e,s.inFlightCap,s.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 B("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 s=await this.tuning();r=await this.evalFn.eval(X,n,[e,s.inFlightCap,s.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 B("grant",r,{pool:this.pool,slotKey:e})}async snapshot(){let e=[],t=null,n="0";do{let r=await this.snapshotPage(n,un);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(Xe,[`sreg:${this.pool}:meta`],[]);return rt(e)}async snapshotPage(e,t){let n=`sreg:${this.pool}:slot:`,r=await this.evalFn.eval(Qe,[`sreg:${this.pool}:meta`],[n,e,t]),[s,u,h]=r.split("#");return{cursor:s,counts:rt(u??""),slots:dn(h??"")}}async readRecords(e){if(e.length===0)return[];let t=`sreg:${this.pool}:slot:`,n=await this.evalFn.eval(Ze,[],e.map(r=>t+r));return(n===""?[]:n.split(`
303
- `)).map(r=>{let[s,u]=r.split("|");return{state:s,inFlight:Number(u)}})}async generation(e){let{base:t}=H(e),n=await this.evalFn.eval(et,[`sreg:${this.pool}:gen:${t}`],[]);return Number(n)}async record(e){let n=(await this.evalFn.eval(tt,[`sreg:${this.pool}:slot:${e}`],[])).split("|"),r=n[0],s=n[1]===""||n[1]===void 0?void 0:n[1],u=n.slice(2).join("|");return{state:r,sessionId:s,lastReason:u===""?void 0:u}}};b();var ot=require("bullmq"),it=require("crypto"),cn=3e4,pn=60,fn=1e3;function st(o){let e;try{e=JSON.parse(o)}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 at(o){let e=o.now??Date.now,t=new Map,n=new Map,r=new Map,s=new Map,u=new Set,h=d=>{let w=t.get(d);return w||(w=o.queueFor?.(d)??y(d),t.set(d,w)),w},y=d=>{let w=o.redis,T=new ot.Queue(d,{prefix:"bull:dispatch",connection:w});return{add:(P,x,I)=>T.add(P,x,I),reassertWaiting:async P=>{let I=(await T.getJobs(["waiting"])).filter(O=>O.data?.session_kind==="lane").sort((O,M)=>O.timestamp-M.timestamp);if(I.length===0)return{found:0};for(let O of I)try{await O.updateData({...O.data,demand_reaffirmed_at_ms:P})}catch{}for(let O of I.slice(1))try{await O.remove()}catch{}return{found:I.length}},close:()=>T.close()}},R=async d=>{let w=await o.redis.hgetall(`lanes:${d}`),T=[];for(let[I,O]of Object.entries(w)){let M=st(O);M&&M.proxy_url===o.docHostUrl&&T.push(I)}if(T.length===0)return[];let P=await o.redis.mget(...T.map(I=>`lane_hosts:${I}`)),x=[];return T.forEach((I,O)=>{let M=P[O];M&&x.push({laneId:I,host:M})}),x},p=async(d,w)=>{let T=n.get(d)??0,P=e();if(P-T<cn)return;n.set(d,P);let x=h(d);if((await x.reassertWaiting(e()).catch(M=>{throw n.delete(d),M})).found>0){s.set(w??"",(s.get(w??"")??0)+1),o.onEvent?.({kind:"lane_demand_reaffirmed",pool:d,model:w});return}let O=`lane-${(0,it.randomUUID)().replaceAll("-","")}`;await x.add("session",{session_id:O,logical_id:O,incarnation:P,session_kind:"lane",lane_id:O,session_server_url:o.docHostUrl,proxy_url:o.docHostUrl,session_idle_timeout_seconds:pn,thread_key:"lane",demand_reaffirmed_at_ms:e()},{jobId:`${O}#${P}`,attempts:3}),r.set(w??"",(r.get(w??"")??0)+1),o.onEvent?.({kind:"lane_demand_enqueued",pool:d,model:w})};return{async pick({pool:d,model:w,holdMs:T=0}){u.add(d);let P=async()=>{try{await p(d,w)}catch(M){n.delete(d),o.onEvent?.({kind:"lane_demand_failed",pool:d,model:w,reason:M instanceof Error?M.message:String(M)})}},x=async()=>{try{return await R(d)}catch{return[]}},I=await x();if(I.length>0)return I;await P();let O=e()+T;for(;e()<O;){if(await new Promise(M=>setTimeout(M,fn)),I=await x(),I.length>0)return I;await P()}return[]},async status(){let d=[...u].sort();return Promise.all(d.map(async w=>{let T=[];try{let P=await o.redis.hgetall(`lanes:${w}`),x=Object.keys(P),I=x.length===0?[]:await o.redis.mget(...x.map(M=>`lane_hosts:${M}`)),O=e();T=x.map((M,ue)=>{let Z=P[M],V=Z===void 0?null:st(Z);return{laneId:M,occupantId:V?.occupant_id??"",capacity:V?.capacity??0,heartbeatAgeMs:V===null?null:O-V.heartbeat_ms,advertisedHere:V?.proxy_url===o.docHostUrl,hosted:!!I[ue]}})}catch{}return{pool:w,lanes:T,lastDemandAt:n.get(w)??null}}))},demandCounters(){return[...new Set([...r.keys(),...s.keys()])].sort().map(w=>({model:w,enqueued:r.get(w)??0,reaffirmed:s.get(w)??0}))},async close(){await Promise.all([...t.values()].map(d=>d.close().catch(()=>{}))),t.clear()}}}b();var re=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})))}};b();b();var ie=o=>`${o.systemPrompt??""}\0${o.firstMessage??""}`;function me(o){return o.promptCacheKey!==void 0&&o.promptCacheKey!==""?`k:${o.promptCacheKey}`:o.sessionHeader!==void 0&&o.sessionHeader!==""?`h:${o.sessionHeader}`:`p:${hn(ie(o))}`}function hn(o){let e=2166136261;for(let t=0;t<o.length;t++)e^=o.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}var lt=512,gn=4096,se=8,oe=class{root={children:new Map,sessions:new Map};nodes=1;insert(e,t,n){let r=e.slice(0,lt),s=this.root;for(let u=0;u<r.length;u+=se){let h=r.slice(u,u+se),y=s.children.get(h);if(!y){if(this.nodes>=gn)return;y={children:new Map,sessions:new Map},s.children.set(h,y),this.nodes+=1}y.sessions.set(t,n),s=y}}match(e,t){let n=e.slice(0,lt),r=this.root,s=null,u=0,h=0;for(;;){let y=null,R=-1;for(let[w,T]of r.sessions)t.has(w)&&(T>R||T===R&&y!==null&&w<y)&&(y=w,R=T);if(y!==null&&(s={sessionId:y,depth:u}),h>=n.length)break;let p=n.slice(h,h+se),d=r.children.get(p);if(!d)break;r=d,u+=p.length,h+=se}return s}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 ut(o,e,t,n){if(e.length===0)return null;let r=new Map(e.map(p=>[p.sessionId,p])),s=p=>{let d=r.get(p);return d!==void 0&&d.backlog<n.backlogThreshold},u=new Set(r.keys()),h=n.sticky.get(me(o));if(h!==void 0&&s(h))return{sessionId:h,reason:"sticky"};let y=t.match(ie(o),u);if(y!==null&&s(y.sessionId))return{sessionId:y.sessionId,reason:"prefix"};let R=null;for(let p of e)(R===null||p.backlog<R.backlog||p.backlog===R.backlog&&p.sessionId<R.sessionId)&&(R=p);return R===null?null:{sessionId:R.sessionId,reason:"load"}}b();var dt="llm",ye="requests",mn="llm-resp",we=(o,e,t,n=0)=>`decision:pooler-${o}-${e}`.replaceAll(":","-")+`:${t}`+(n>0?`:${n}`:""),ve=o=>{let{base:e,gen:t}=H(o);return`${e}:${t+1}`},ct=o=>`${mn}:${o}`,pt="free_slots",_e="inflight",Y=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 yn=6e4,wn=33e4,vn=2,_n=8,Sn=5e3,bn=1e4,Rn=6e4,En=5e3,ae=class o{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??yn,this.silenceDeadlineMs=e.silenceDeadlineMs??wn,this.maxAttempts=e.maxAttempts??vn,this.backlogThreshold=e.backlogThreshold??_n,this.mint=e.mint,this.limits=e.limits??[],this.scaleUpWaitMs=e.scaleUpWaitMs??Sn,this.mintCooldownMs=e.mintCooldownMs??bn,this.sessionIdleTtlMs=e.sessionIdleTtlMs??Rn,this.idleSweepMs=e.idleSweepMs??En,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;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)}}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(s){if(t==="boot_floor")throw s;return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:s instanceof Error?s.message:String(s)}),!1}try{let s=await this.mint(e.region,e.model,r);return this.closed?(await s.end().catch(()=>{}),!1):(this.addSession(e.region,e.model,s,r),this.onEvent({kind:"minted",pool:this.key(e.region,e.model),sessionId:s.sessionId,reason:t}),!0)}catch(s){return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:s instanceof Error?s.message:String(s)}),!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 h=e.sessions.indexOf(r);if(h===-1)continue;e.sessions.splice(h,1),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 s=0;;s++){let u=await this.registry.generation(r),h=we(e,t,n,u),{state:y,sessionId:R,lastReason:p}=await this.registry.record(h);if(y==="none"||y==="paused"&&R===void 0&&p===void 0)try{return await this.registry.mint(h),h}catch(d){this.rethrowUnlessClaimRace(d,s);continue}else{let d=ve(h);try{await this.registry.rotate(h,d),await this.registry.mint(d)}catch(w){this.rethrowUnlessClaimRace(w,s);continue}return this.onEvent({kind:"slot_rotated",pool:this.key(e,t),slotKey:h,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<o.CLAIM_RACE_ATTEMPTS&&e instanceof B&&o.CLAIM_RACE_VERDICTS.has(e.verdict)))throw e}addSession(e,t,n,r){let s=this.poolOf(e,t);s.sessions.push(n),s.lastActivity.set(n,this.now()),s.slotKeys.set(n.sessionId,r),n.whenLive().then(()=>{this.registryCall("attach",r,()=>this.registry?.attach(r,n.sessionId))}).catch(u=>{this.onEvent({kind:"session_never_live",pool:this.key(e,t),sessionId:n.sessionId,reason:u instanceof Error?u.message:String(u)})}),s.offs.push(n.onDocChange(()=>{this.pump(s),this.adoptSettled(s)}),n.onGone(u=>this.evict(s,n,u))),this.onEvent({kind:"session_added",pool:this.key(e,t),sessionId:n.sessionId}),this.start(s).then(()=>this.pump(s))}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(u=>u.sessionId===n.sessionId),s=r?.snapshot().inflight[n.request.request_id];if(r!==void 0){if(s?.status==="done"||s?.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[s,u]of Object.entries(r.inflight)){if(u.status==="done"||u.status==="error"||e.records.has(s))continue;let h={request:{request_id:s,region:e.region,model:e.model,affinity:{},payload:{},streaming:!1,enqueuedAt:0},sink:null,attempt:u.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(s,h),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:s,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(s=>{r.settle=s})}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)t();e.offs.length=0,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)n();e.offs.length=0,e.lastActivity.clear();for(let n of e.slotKeys.values())this.registryCall("rotate",n,()=>this.registry?.rotate(n,ve(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=o.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:[],slotKeys:new Map,needsReconcile:!0,lastMintAt:0,minting:!1,mintSeq:0,lastActivity:new Map},this.pools.set(n,r)),r}key(e,t){return o.poolKey(e,t)}registryCall(e,t,n){let r=n();r!==void 0&&r.catch(s=>{this.onEvent({kind:"registry_error",reason:`${e}: ${s instanceof Error?s.message:String(s)}`,slotKey:t})})}creditFor(e,t){let n=t.snapshot(),r=0;for(let s of e.records.values()){if(s.session!==t||s.phase!=="dispatched")continue;let u=n.inflight[s.request.request_id];(u===void 0||u.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],s=this.pickFor(e,r);if(s!==null){e.queue.splice(n,1),this.dispatch(e,s,r),t=!0;break}}}e.queue.length>0&&this.queuePressure(e)&&this.tryMint(e,"queue_pressure")}pickFor(e,t){let n=e.sessions.filter(u=>u.gone()===null&&!t.tried.has(u.sessionId)&&this.creditFor(e,u)>0).map(u=>({sessionId:u.sessionId,backlog:this.backlogOf(e,u)})),r=ut(t.request.affinity,n,e.radix,{backlogThreshold:this.backlogThreshold,sticky:e.sticky});if(r===null)return null;let s=e.sessions.find(u=>u.sessionId===r.sessionId)??null;return s!==null&&this.onEvent({kind:"picked",pool:this.key(e.region,e.model),requestId:t.request.request_id,sessionId:s.sessionId,reason:r.reason}),s}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 s=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 u=me(n.request.affinity);e.sticky.set(u,t.sessionId),e.radix.insert(ie(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 h=e.slotKeys.get(t.sessionId);h!==void 0&&this.registryCall("lease",h,()=>this.registry?.lease(h)),this.consume(e,n,s)})()}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 s=t.sink;if(s!==null&&(await s.chunk(r),r.t==="response"||r.t==="error"||r.t==="end")){await this.finish(e,t);return}}this.lost(e,t,new Y(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 F&&t.session!==null&&this.evict(e,t.session,n);let s=e.sessions.some(u=>u.gone()===null&&!t.tried.has(u.sessionId));if(!t.streamed&&t.attempt<this.maxAttempts&&s){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"))}evict(e,t,n){let r=e.sessions.indexOf(t);if(r===-1)return;e.sessions.splice(r,1),e.lastActivity.delete(t),e.radix.forget(t.sessionId);let s=e.slotKeys.get(t.sessionId);s!==void 0&&(e.slotKeys.delete(t.sessionId),this.registryCall("detach",s,()=>this.registry?.detach(s,n.message)));for(let u of[...e.records.values()])u.session===t&&u.phase!=="finished"&&this.lost(e,u,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 s=n.inflight[r.request.request_id];(s?.status==="done"||s?.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 Y(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}))}}};b();var kn="0.0.0.0",ft="serve";var z=(o,e)=>{let t=o[e];if(typeof t!="string"||t==="")throw new Error(`the pooler requires ${e} (external input) \u2014 refusing to start half-configured`);return t},Pn=(o,e)=>{if(o===null||typeof o!="object")throw new Error(`URUN_POOLER_TARGETS[${e}] must be an object`);let t=o,n=h=>{let y=t[h];if(typeof y!="string"||y==="")throw new Error(`URUN_POOLER_TARGETS[${e}].${h} is required`);return y},r=h=>{let y=t[h];if(typeof y!="number"||!Number.isInteger(y))throw new Error(`URUN_POOLER_TARGETS[${e}].${h} must be an integer`);return y},s,u;if(t.sessions!==void 0){let h=t.sessions;if(typeof h!="number"||!Number.isInteger(h)||h<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`);s=h,u=h}else{if(s=r("min"),u=r("max"),s<0)throw new Error(`URUN_POOLER_TARGETS[${e}].min must be >= 0 (0 scales to zero)`);if(u<1)throw new Error(`URUN_POOLER_TARGETS[${e}].max must be >= 1`);if(s>u)throw new Error(`URUN_POOLER_TARGETS[${e}]: min (${String(s)}) must not exceed max (${String(u)})`)}return{region:n("region"),model:n("model"),app:n("app"),fn:typeof t.fn=="string"&&t.fn!==""?t.fn:void 0,min:s,max:u,sharedApp:t.sharedApp===!0}};function ht(o){let e=o.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(o,"URUN_BASE_URL"),r=z(o,"URUN_POOLER_TARGETS"),s;try{s=JSON.parse(r)}catch(u){throw new Error(`URUN_POOLER_TARGETS is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!Array.isArray(s)||s.length===0)throw new Error("URUN_POOLER_TARGETS must be a non-empty JSON array");return{port:t,bindHost:kn,token:z(o,"URUN_POOLER_TOKEN"),baseUrl:n,apiUrl:o.URUN_API_URL!==void 0&&o.URUN_API_URL!==""?o.URUN_API_URL:`${n}/v1`,orgId:z(o,"URUN_ORG_ID"),apiKey:z(o,"URUN_API_KEY"),valkeyUrl:z(o,"URUN_VALKEY_URL"),laneDocHostUrl:(o.URUN_LANE_DOC_HOST_URL??"").trim()||void 0,targets:s.map(Pn)}}b();var yt=require("http"),Tn="/pooler/v1/inference",In="/readyz",xn="/metrics",An="/pooler/v1/lanes/pick",On="/pooler/v1/lanes/status",Mn=1e4,gt=16*1024*1024;function L(o,e,t,n,r){o.headersSent||(r!==void 0&&o.setHeader("retry-after",String(r)),o.writeHead(e,{"content-type":"application/json"}),o.end(JSON.stringify({error:{message:t,type:"pooler_error",code:n}})))}function Nn(o){if(o===null||typeof o!="object")return{reason:"body must be a JSON object"};let e=o;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=s=>typeof s=="string"&&s!==""?s: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 Se=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 B=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},fn=100,st=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},hn=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()),ne=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 B(e,l,{pool:this.pool,...o})}mint(e){let{gen:t}=F(e);return this.run("mint",he,this.keys(e,!1,!0),[e,t,K()],{slotKey:e,gen:t})}mintWith(e,t){let{gen:n}=F(e);return this.run("mint",he,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",rt,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",Ke,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",Be,this.keys(e,!1,!1),[e],{slotKey:e})}release(e){return this.run("release",We,this.keys(e,!1,!1),[e,K()],{slotKey:e})}configure(e,t){return this.run("config",Qe,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}retune(e,t){return this.run("retune",ze,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}async tuning(){let e=await this.evalFn.eval(Je,[`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 B("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 B("grant",r,{pool:this.pool,slotKey:e})}async snapshot(){let e=[],t=null,n="0";do{let r=await this.snapshotPage(n,fn);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(Ze,[`sreg:${this.pool}:meta`],[]);return st(e)}async snapshotPage(e,t){let n=`sreg:${this.pool}:slot:`,r=await this.evalFn.eval(Xe,[`sreg:${this.pool}:meta`],[n,e,t]),[o,l,h]=r.split("#");return{cursor:o,counts:st(l??""),slots:hn(h??"")}}async readRecords(e){if(e.length===0)return[];let t=`sreg:${this.pool}:slot:`,n=await this.evalFn.eval(et,[],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(tt,[`sreg:${this.pool}:gen:${t}`],[]);return Number(n)}async record(e){let n=(await this.evalFn.eval(nt,[`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}}};b();var it=require("bullmq"),at=require("crypto"),mn=3e4,gn=60,yn=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 lt(s){let e=s.now??Date.now,t=new Map,n=new Map,r=new Map,o=new Map,l=new Set,h=d=>{let v=t.get(d);return v||(v=s.queueFor?.(d)??y(d),t.set(d,v)),v},y=d=>{let v=s.redis,T=new it.Queue(d,{prefix:"bull:dispatch",connection:v});return{add:(P,x,I)=>T.add(P,x,I),reassertWaiting:async P=>{let I=(await T.getJobs(["waiting"])).filter(O=>O.data?.session_kind==="lane").sort((O,M)=>O.timestamp-M.timestamp);if(I.length===0)return{found:0};for(let O of I)try{await O.updateData({...O.data,demand_reaffirmed_at_ms:P})}catch{}for(let O of I.slice(1))try{await O.remove()}catch{}return{found:I.length}},close:()=>T.close()}},R=async d=>{let v=await s.redis.hgetall(`lanes:${d}`),T=[];for(let[I,O]of Object.entries(v)){let M=ot(O);M&&M.proxy_url===s.docHostUrl&&T.push(I)}if(T.length===0)return[];let P=await s.redis.mget(...T.map(I=>`lane_hosts:${I}`)),x=[];return T.forEach((I,O)=>{let M=P[O];M&&x.push({laneId:I,host:M})}),x},p=async(d,v)=>{let T=n.get(d)??0,P=e();if(P-T<mn)return;n.set(d,P);let x=h(d);if((await x.reassertWaiting(e()).catch(M=>{throw n.delete(d),M})).found>0){o.set(v??"",(o.get(v??"")??0)+1),s.onEvent?.({kind:"lane_demand_reaffirmed",pool:d,model:v});return}let O=`lane-${(0,at.randomUUID)().replaceAll("-","")}`;await x.add("session",{session_id:O,logical_id:O,incarnation:P,session_kind:"lane",lane_id:O,session_server_url:s.docHostUrl,proxy_url:s.docHostUrl,session_idle_timeout_seconds:gn,thread_key:"lane",demand_reaffirmed_at_ms:e()},{jobId:`${O}#${P}`,attempts:3}),r.set(v??"",(r.get(v??"")??0)+1),s.onEvent?.({kind:"lane_demand_enqueued",pool:d,model:v})};return{async pick({pool:d,model:v,holdMs:T=0}){l.add(d);let P=async()=>{try{await p(d,v)}catch(M){n.delete(d),s.onEvent?.({kind:"lane_demand_failed",pool:d,model:v,reason:M instanceof Error?M.message:String(M)})}},x=async()=>{try{return await R(d)}catch{return[]}},I=await x();if(I.length>0)return I;await P();let O=e()+T;for(;e()<O;){if(await new Promise(M=>setTimeout(M,yn)),I=await x(),I.length>0)return I;await P()}return[]},async status(){let d=[...l].sort();return Promise.all(d.map(async v=>{let T=[];try{let P=await s.redis.hgetall(`lanes:${v}`),x=Object.keys(P),I=x.length===0?[]:await s.redis.mget(...x.map(M=>`lane_hosts:${M}`)),O=e();T=x.map((M,ue)=>{let Z=P[M],V=Z===void 0?null:ot(Z);return{laneId:M,occupantId:V?.occupant_id??"",capacity:V?.capacity??0,heartbeatAgeMs:V===null?null:O-V.heartbeat_ms,advertisedHere:V?.proxy_url===s.docHostUrl,hosted:!!I[ue]}})}catch{}return{pool:v,lanes:T,lastDemandAt:n.get(v)??null}}))},demandCounters(){return[...new Set([...r.keys(),...o.keys()])].sort().map(v=>({model:v,enqueued:r.get(v)??0,reaffirmed:o.get(v)??0}))},async close(){await Promise.all([...t.values()].map(d=>d.close().catch(()=>{}))),t.clear()}}}b();var re=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})))}};b();b();var ie=s=>`${s.systemPrompt??""}\0${s.firstMessage??""}`;function ge(s){return s.promptCacheKey!==void 0&&s.promptCacheKey!==""?`k:${s.promptCacheKey}`:s.sessionHeader!==void 0&&s.sessionHeader!==""?`h:${s.sessionHeader}`:`p:${vn(ie(s))}`}function vn(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 ut=512,wn=4096,se=8,oe=class{root={children:new Map,sessions:new Map};nodes=1;insert(e,t,n){let r=e.slice(0,ut),o=this.root;for(let l=0;l<r.length;l+=se){let h=r.slice(l,l+se),y=o.children.get(h);if(!y){if(this.nodes>=wn)return;y={children:new Map,sessions:new Map},o.children.set(h,y),this.nodes+=1}y.sessions.set(t,n),o=y}}match(e,t){let n=e.slice(0,ut),r=this.root,o=null,l=0,h=0;for(;;){let y=null,R=-1;for(let[v,T]of r.sessions)t.has(v)&&(T>R||T===R&&y!==null&&v<y)&&(y=v,R=T);if(y!==null&&(o={sessionId:y,depth:l}),h>=n.length)break;let p=n.slice(h,h+se),d=r.children.get(p);if(!d)break;r=d,l+=p.length,h+=se}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 dt(s,e,t,n){if(e.length===0)return null;let r=new Map(e.map(p=>[p.sessionId,p])),o=p=>{let d=r.get(p);return d!==void 0&&d.backlog<n.backlogThreshold},l=new Set(r.keys()),h=n.sticky.get(ge(s));if(h!==void 0&&o(h))return{sessionId:h,reason:"sticky"};let y=t.match(ie(s),l);if(y!==null&&o(y.sessionId))return{sessionId:y.sessionId,reason:"prefix"};let R=null;for(let p of e)(R===null||p.backlog<R.backlog||p.backlog===R.backlog&&p.sessionId<R.sessionId)&&(R=p);return R===null?null:{sessionId:R.sessionId,reason:"load"}}b();var ct="llm",ye="requests",_n="llm-resp",ve=(s,e,t,n=0)=>`decision:pooler-${s}-${e}`.replaceAll(":","-")+`:${t}`+(n>0?`:${n}`:""),we=s=>{let{base:e,gen:t}=F(s);return`${e}:${t+1}`},pt=s=>`${_n}:${s}`,ft="free_slots",_e="inflight",Se="live_seen",Y=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 ht=new Set(["registry_error","failed","mint_failed","scaled_down","live_mark_failed"]),Sn=6e4,bn=33e4,Rn=2,En=8,kn=5e3,Pn=1e4,Tn=6e4,In=5e3,xn={idle:"bound",queued:"bound",unavailable:"bound",provisioning:"bound",waiting_for_capacity:"bound",connecting:"bound",live:"bound",paused:"unbound",error:"unbound",unknown:"unbound"},ae=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??Sn,this.silenceDeadlineMs=e.silenceDeadlineMs??bn,this.maxAttempts=e.maxAttempts??Rn,this.backlogThreshold=e.backlogThreshold??En,this.mint=e.mint,this.limits=e.limits??[],this.scaleUpWaitMs=e.scaleUpWaitMs??kn,this.mintCooldownMs=e.mintCooldownMs??Pn,this.sessionIdleTtlMs=e.sessionIdleTtlMs??Tn,this.idleSweepMs=e.idleSweepMs??In,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:xn[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 h=e.sessions.indexOf(r);if(h===-1)continue;e.sessions.splice(h,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=ve(e,t,n);if(this.registry===null)return r;for(let o=0;;o++){let l=await this.registry.generation(r),h=ve(e,t,n,l),{state:y,sessionId:R,lastReason:p}=await this.registry.record(h);if(y==="none"||y==="paused"&&R===void 0&&p===void 0)try{return await this.registry.mint(h),h}catch(d){this.rethrowUnlessClaimRace(d,o);continue}else{let d=we(h);try{await this.registry.rotate(h,d),await this.registry.mint(d)}catch(v){this.rethrowUnlessClaimRace(v,o);continue}return this.onEvent({kind:"slot_rotated",pool:this.key(e,t),slotKey:h,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 B&&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 h={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,h),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,we(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(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=dt(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=ge(n.request.affinity);e.sticky.set(l,t.sessionId),e.radix.insert(ie(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 h=e.slotKeys.get(t.sessionId);h!==void 0&&this.registryCall("lease",h,()=>this.registry?.lease(h)),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 Y(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 Y(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}))}}};b();var An="0.0.0.0",mt="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},On=(s,e)=>{if(s===null||typeof s!="object")throw new Error(`URUN_POOLER_TARGETS[${e}] must be an object`);let t=s,n=h=>{let y=t[h];if(typeof y!="string"||y==="")throw new Error(`URUN_POOLER_TARGETS[${e}].${h} is required`);return y},r=h=>{let y=t[h];if(typeof y!="number"||!Number.isInteger(y))throw new Error(`URUN_POOLER_TARGETS[${e}].${h} must be an integer`);return y},o,l;if(t.sessions!==void 0){let h=t.sessions;if(typeof h!="number"||!Number.isInteger(h)||h<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=h,l=h}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 gt(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:An,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,targets:o.map(On)}}b();var wt=require("http"),Mn="/pooler/v1/inference",Nn="/readyz",$n="/metrics",Cn="/pooler/v1/lanes/pick",Un="/pooler/v1/lanes/status",Ln=1e4,yt=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 qn(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 be=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
 
307
307
  `);return}e.t!=="delta"&&(this.terminal=e)}done(){if(this.stopKeepalive(),this.streaming){this.res.write(`data: [DONE]
308
308
 
309
- `),this.res.end();return}if(this.terminal!==null&&this.terminal.t==="error"){let t=this.terminal.body,n=t!==null&&typeof t=="object"&&typeof t.message=="string"?String(t.message):"the upstream turn failed";L(this.res,502,n,"upstream_error");return}let e=this.terminal!==null&&this.terminal.t!=="delta"?this.terminal:{t:"response",body:{}};this.res.writeHead(200,{"content-type":"application/json"}),this.res.end(JSON.stringify(e))}fail(e){if(this.stopKeepalive(),!this.streaming||!this.res.headersSent){L(this.res,e.status,e.message,e.code,e.retryAfterSeconds);return}this.res.write(`data: ${JSON.stringify({error:{message:e.message,type:"pooler_error",code:e.code}})}
309
+ `),this.res.end();return}if(this.terminal!==null&&this.terminal.t==="error"){let t=this.terminal.body,n=t!==null&&typeof t=="object"&&typeof t.message=="string"?String(t.message):"the upstream turn failed";q(this.res,502,n,"upstream_error");return}let e=this.terminal!==null&&this.terminal.t!=="delta"?this.terminal:{t:"response",body:{}};this.res.writeHead(200,{"content-type":"application/json"}),this.res.end(JSON.stringify(e))}fail(e){if(this.stopKeepalive(),!this.streaming||!this.res.headersSent){q(this.res,e.status,e.message,e.code,e.retryAfterSeconds);return}this.res.write(`data: ${JSON.stringify({error:{message:e.message,type:"pooler_error",code:e.code}})}
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 mt(o){return new Promise((e,t)=>{let n=0,r=[];o.on("data",s=>{if(n+=s.length,n>gt){t(new Error(`request body exceeds ${gt} bytes`)),o.destroy();return}r.push(s)}),o.on("end",()=>e(Buffer.concat(r).toString("utf8"))),o.on("error",t)})}function wt(o){let e=o.keepaliveMs??Mn,t=o.log??(()=>{}),n=(0,yt.createServer)((r,s)=>{(async()=>{let u=new URL(r.url??"/","http://pooler.internal");if(r.method==="GET"&&u.pathname===In){s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({ok:!0,...o.pooler.stats()}));return}if(r.method==="GET"&&u.pathname===xn){let p=["# 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 o.pooler.stats().pools){let w=`pool="${d.pool}"`;p.push(`pooler_pool_queued{${w}} ${d.queued}`),p.push(`pooler_pool_inflight{${w}} ${d.inflight}`),p.push(`pooler_pool_sessions{${w}} ${d.sessions}`)}for(let d of o.lanePlane?.demandCounters()??[]){let w=`model="${d.model.replaceAll('"','\\"')}"`;p.push(`pooler_lane_demand_enqueued{${w}} ${d.enqueued}`),p.push(`pooler_lane_demand_reaffirmed{${w}} ${d.reaffirmed}`)}s.writeHead(200,{"content-type":"text/plain; version=0.0.4"}),s.end(`${p.join(`
313
+ `),this.res.end()}stopKeepalive(){this.keepalive!==null&&clearInterval(this.keepalive),this.keepalive=null}};function vt(s){return new Promise((e,t)=>{let n=0,r=[];s.on("data",o=>{if(n+=o.length,n>yt){t(new Error(`request body exceeds ${yt} bytes`)),s.destroy();return}r.push(o)}),s.on("end",()=>e(Buffer.concat(r).toString("utf8"))),s.on("error",t)})}function _t(s){let e=s.keepaliveMs??Ln,t=s.log??(()=>{}),n=(0,wt.createServer)((r,o)=>{(async()=>{let l=new URL(r.url??"/","http://pooler.internal");if(r.method==="GET"&&l.pathname===Nn){o.writeHead(200,{"content-type":"application/json"}),o.end(JSON.stringify({ok:!0,...s.pooler.stats()}));return}if(r.method==="GET"&&l.pathname===$n){let p=["# 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 v=`pool="${d.pool}"`;p.push(`pooler_pool_queued{${v}} ${d.queued}`),p.push(`pooler_pool_inflight{${v}} ${d.inflight}`),p.push(`pooler_pool_sessions{${v}} ${d.sessions}`)}for(let d of s.lanePlane?.demandCounters()??[]){let v=`model="${d.model.replaceAll('"','\\"')}"`;p.push(`pooler_lane_demand_enqueued{${v}} ${d.enqueued}`),p.push(`pooler_lane_demand_reaffirmed{${v}} ${d.reaffirmed}`)}o.writeHead(200,{"content-type":"text/plain; version=0.0.4"}),o.end(`${p.join(`
314
314
  `)}
315
- `);return}if(o.lanePlane&&r.method==="GET"&&u.pathname===On){if(r.headers.authorization!==`Bearer ${o.token}`){L(s,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({pools:await o.lanePlane.status()}));return}if(o.lanePlane&&r.method==="POST"&&u.pathname===An){if(r.headers.authorization!==`Bearer ${o.token}`){L(s,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let p;try{p=JSON.parse(await mt(r))}catch(P){L(s,400,P instanceof Error?P.message:String(P),"invalid_request");return}let d=p??{};if(typeof d.pool!="string"||d.pool===""){L(s,400,"pool is required","invalid_request");return}let w=d.hold_ms;if(w!==void 0&&(typeof w!="number"||!Number.isInteger(w)||w<0||w>12e4)){L(s,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 P=await o.lanePlane.pick({pool:d.pool,model:T,holdMs:w??0});if(P.length===0){L(s,503,"no capacity available for this model right now, retry shortly","lane_capacity",2);return}s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({lanes:P.map(x=>({lane_id:x.laneId,host:x.host}))}))}catch(P){t(`[pooler] lane pick for ${d.pool} failed: ${P instanceof Error?P.message:String(P)}`),L(s,500,"the pooler lane plane failed this pick","pooler_error")}return}if(r.method!=="POST"||u.pathname!==Tn){L(s,404,`no route for ${r.method??""} ${u.pathname}`,"not_found");return}if(r.headers.authorization!==`Bearer ${o.token}`){L(s,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let h;try{h=JSON.parse(await mt(r))}catch(p){L(s,400,p instanceof Error?p.message:String(p),"invalid_request");return}let y=Nn(h);if("reason"in y){L(s,400,y.reason,"invalid_request");return}let R=new Se(s,y.value.streaming,e);R.head();try{await o.pooler.submit(y.value.request,R)}catch(p){t(`[pooler] request ${y.value.request.request_id} failed unexpectedly: ${p instanceof Error?p.message:String(p)}`),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()))}}b();var le=require("@urun-sh/core");b();var Cn=3,$n="llm",Un=new Set(["paused","error"]);function vt(o,e,t){let n=o.doc($n),r=typeof n.onConnectionState=="function",s=typeof o.onPhase=="function";if(!r&&!s)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let u=null,h=!1,y=new Set,R=[],p=d=>{if(!u){u=d;for(let w of[...y])w(d);y.clear()}};return r&&R.push(n.onConnectionState(d=>{h&&(d.consecutiveFailures<Cn||p(new F(`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(()=>{h=!0})):s&&R.push(o.onPhase(d=>{if(d.name==="live"){h=!0;return}h&&Un.has(d.name)&&p(new F(`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:()=>u,onGone(d){return u?(d(u),()=>{}):(y.add(d),()=>y.delete(d))},dispose(){y.clear();for(let d of R.splice(0))d()}}}b();var _t=require("@urun-sh/core");var qn=new Set(["accepted","done","error"]);function Ln(o){if(o===null||typeof o!="object")return{};let e=o,t={};for(let[n,r]of Object.entries(e)){let s=r===null||typeof r!="object"?null:r.toJSON;t[n]=typeof s=="function"?s.call(r):r}return t}function Dn(o){if(o===null||typeof o!="object")return null;let e=o,t=e.status;return t!==void 0&&(typeof t!="string"||!qn.has(t))?null:{attempt:typeof e.attempt=="number"?e.attempt:0,...typeof t=="string"?{status:t}:{},...typeof e.error=="string"?{error:e.error}:{}}}function Gn(o){let e=Ln(o.get()),t=Number(e[pt]??0),n={},r=e[_e];if(r!==null&&typeof r=="object")for(let[s,u]of Object.entries(r)){let h=Dn(u);h!==null&&(n[s]=h)}return{freeSlots:Number.isFinite(t)?t:0,inflight:n}}function jn(o){if(o===_t.STREAM_END)return{t:"end"};if(o===null||typeof o!="object")return null;let e=o;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??o}:null}async function*Hn(o,e){let t=o.stream(ct(e)),n=!1;try{for await(let r of t.messages()){let s=jn(r);if(s!==null&&(yield s,s.t!=="delta")){n=!0;return}}}catch(r){throw new Y(e,r instanceof Error?r.message:String(r))}if(!n)throw new Y(e,"the reply stream ended without a terminal chunk (urun-stream-v1 is at-most-once across a reconnect)")}function St(o){let{session:e,sessionId:t,goneWatch:n}=o;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`);let r=()=>e.doc(dt);return{sessionId:t,snapshot:()=>Gn(r()),onDocChange:s=>r().on("change",()=>s()),onGone:s=>n.onGone(s),gone:()=>n.gone(),whenLive:s=>e.whenLive(s),markInflight:(s,u)=>(r().set({[_e]:{[s]:{attempt:u}}}),Promise.resolve()),push:s=>(r().set({[ye]:{[s.request_id]:{...s.payload,request_id:s.request_id,consumer_id:s.consumer_id,stream:s.stream}}}),Promise.resolve()),clearRequest:s=>{try{r().set({[ye]:{[s]:null}})}catch{}return Promise.resolve()},reply:s=>Hn(e,s),end:async()=>{await e.end(),n.dispose()}}}function bt(o){return async(e,t)=>{let n=e.fn??ft,r=(0,le.App)(e.app,{baseUrl:o.baseUrl,orgId:o.orgId,getAccessToken:async()=>(await(0,le.createClientToken)(o.apiKey,{baseUrl:o.baseUrl,expiresIn:300,allowedFunctions:[`${e.app}/${n}`],...e.sharedApp?{sharedApp:!0}:{}})).token}),s=r[n];if(typeof s!="function")throw new Error(`app "${e.app}" has no function "${n}" \u2014 the pooler cannot dial a slot for it`);let u={concurrencyKey:t,...e.sharedApp?{sharedApp:!0}:{}},h=s.call(r,void 0,u);if(h===null||typeof h!="object")throw new Error(`app "${e.app}" function "${n}" returned no session`);let y=h;return St({session:y,sessionId:t,goneWatch:vt(y,t,{armOnFirstSync:!0})})}}function zn(){let o=null;o=He({streams:j.default,note:e=>{o?.isDead("stderr")!==!0&&te(j.default.stderr,e)}})}async function Qn(){zn();let o=ht(j.default.env),e=p=>{te(j.default.stdout,`${p}
316
- `)},t=new Rt.Redis(o.valkeyUrl,{maxRetriesPerRequest:null}),n=new ne({eval:(p,d,w)=>t.eval(p,d.length,...d,...w)},"pooler"),r=bt(o),s=new ae({journal:new re,registry:n,queueDeadlineMs:6e4,silenceDeadlineMs:33e4,backlogThreshold:8,mint:(p,d,w)=>{let T=o.targets.find(P=>P.region===p&&P.model===d);return T===void 0?Promise.reject(new Error(`no pooler target for ${p}:${d} \u2014 refusing to mint`)):r(T,w)},limits:o.targets.map(({region:p,model:d,min:w,max:T})=>({region:p,model:d,min:w,max:T})),scaleUpWaitMs:5e3,mintCooldownMs:1e4,sessionIdleTtlMs:6e4,idleSweepMs:5e3,onEvent:p=>{(p.kind==="registry_error"||p.kind==="failed"||p.kind==="mint_failed"||p.kind==="scaled_down")&&e(`[pooler] ${p.kind} ${JSON.stringify(p)}`)}});await s.warm();let u=o.laneDocHostUrl===void 0?void 0:at({docHostUrl:o.laneDocHostUrl,redis:t}),{server:h,close:y}=wt({pooler:s,token:o.token,lanePlane:u,log:e});await new Promise((p,d)=>{h.once("error",d),h.listen(o.port,o.bindHost,()=>p())}),e(`urun-pooler listening on http://${o.bindHost}:${o.port} (targets ${o.targets.map(p=>`${p.region}:${p.model} min=${p.min} max=${p.max}`).join(", ")})${u===void 0?"":" lanes=on"}`);let R=async p=>{e(`urun-pooler: ${p} \u2014 draining`),await y(),await s.close(),await u?.close(),await t.quit().catch(()=>{})};await new Promise(p=>{j.default.once("SIGINT",()=>{R("SIGINT").finally(p)}),j.default.once("SIGTERM",()=>{R("SIGTERM").finally(p)})})}Qn().then(()=>j.default.exit(0),o=>{te(j.default.stderr,`urun-pooler failed: ${o instanceof Error?`${o.name}: ${o.message}`:String(o)}
315
+ `);return}if(s.lanePlane&&r.method==="GET"&&l.pathname===Un){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===Cn){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 vt(r))}catch(P){q(o,400,P instanceof Error?P.message:String(P),"invalid_request");return}let d=p??{};if(typeof d.pool!="string"||d.pool===""){q(o,400,"pool is required","invalid_request");return}let v=d.hold_ms;if(v!==void 0&&(typeof v!="number"||!Number.isInteger(v)||v<0||v>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 P=await s.lanePlane.pick({pool:d.pool,model:T,holdMs:v??0});if(P.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:P.map(x=>({lane_id:x.laneId,host:x.host}))}))}catch(P){t(`[pooler] lane pick for ${d.pool} failed: ${P instanceof Error?P.message:String(P)}`),q(o,500,"the pooler lane plane failed this pick","pooler_error")}return}if(r.method!=="POST"||l.pathname!==Mn){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 h;try{h=JSON.parse(await vt(r))}catch(p){q(o,400,p instanceof Error?p.message:String(p),"invalid_request");return}let y=qn(h);if("reason"in y){q(o,400,y.reason,"invalid_request");return}let R=new be(o,y.value.streaming,e);R.head();try{await s.pooler.submit(y.value.request,R)}catch(p){t(`[pooler] request ${y.value.request.request_id} failed unexpectedly: ${p instanceof Error?p.message:String(p)}`),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()))}}b();var le=require("@urun-sh/core");b();var Dn=3,Gn="llm",jn=new Set(["paused","error"]);function St(s,e,t){let n=s.doc(Gn),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,h=!1,y=new Set,R=[],p=d=>{if(!l){l=d;for(let v of[...y])v(d);y.clear()}};return r&&R.push(n.onConnectionState(d=>{h&&(d.consecutiveFailures<Dn||p(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(()=>{h=!0})):o&&R.push(s.onPhase(d=>{if(d.name==="live"){h=!0;return}h&&jn.has(d.name)&&p(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()}}}b();var Et=require("@urun-sh/core");b();async function bt(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 Fn=new Set(["accepted","done","error"]);function Kn(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 Yn(s){if(s===null||typeof s!="object")return null;let e=s,t=e.status;return t!==void 0&&(typeof t!="string"||!Fn.has(t))?null:{attempt:typeof e.attempt=="number"?e.attempt:0,...typeof t=="string"?{status:t}:{},...typeof e.error=="string"?{error:e.error}:{}}}function Rt(s){let e=Kn(s.get()),t=Number(e[ft]??0),n={},r=e[_e];if(r!==null&&typeof r=="object")for(let[o,l]of Object.entries(r)){let h=Yn(l);h!==null&&(n[o]=h)}return{freeSlots:Number.isFinite(t)?t:0,inflight:n,liveSeen:e[Se]===!0}}function Vn(s){if(s===Et.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*Bn(s,e){let t=s.stream(pt(e)),n=!1;try{for await(let r of t.messages()){let o=Vn(r);if(o!==null&&(yield o,o.t!=="delta")){n=!0;return}}}catch(r){throw new Y(e,r instanceof Error?r.message:String(r))}if(!n)throw new Y(e,"the reply stream ended without a terminal chunk (urun-stream-v1 is at-most-once across a reconnect)")}function kt(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(ct),o=!1;return"onPhase"in e&&typeof e.onPhase=="function"&&e.onPhase(l=>{l.name==="live"&&(o=!0)}),{sessionId:t,snapshot:()=>Rt(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||Rt(r()).liveSeen,markLiveSeen:async()=>{await bt(r(),15e3,"the durable live-seen mark"),r().set({[Se]:!0})},whenLive:l=>e.whenLive(l),markInflight:(l,h)=>(r().set({[_e]:{[l]:{attempt:h}}}),Promise.resolve()),push:l=>(r().set({[ye]:{[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({[ye]:{[l]:null}})}catch{}return Promise.resolve()},reply:l=>Bn(e,l),end:async()=>{await e.end(),n.dispose()}}}function Pt(s){return async(e,t)=>{let n=e.fn??mt,r=(0,le.App)(e.app,{baseUrl:s.baseUrl,orgId:s.orgId,getAccessToken:async()=>(await(0,le.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}:{}},h=o.call(r,void 0,l);if(h===null||typeof h!="object")throw new Error(`app "${e.app}" function "${n}" returned no session`);let y=h;return kt({session:y,sessionId:t,goneWatch:St(y,t,{armOnFirstSync:!0})})}}function tr(){let s=null;s=Fe({streams:j.default,note:e=>{s?.isDead("stderr")!==!0&&te(j.default.stderr,e)}})}async function nr(){tr();let s=gt(j.default.env),e=p=>{te(j.default.stdout,`${p}
316
+ `)},t=new Tt.Redis(s.valkeyUrl,{maxRetriesPerRequest:null}),n=new ne({eval:(p,d,v)=>t.eval(p,d.length,...d,...v)},"pooler"),r=Pt(s),o=new ae({journal:new re,registry:n,queueDeadlineMs:6e4,silenceDeadlineMs:33e4,backlogThreshold:8,mint:(p,d,v)=>{let T=s.targets.find(P=>P.region===p&&P.model===d);return T===void 0?Promise.reject(new Error(`no pooler target for ${p}:${d} \u2014 refusing to mint`)):r(T,v)},limits:s.targets.map(({region:p,model:d,min:v,max:T})=>({region:p,model:d,min:v,max:T})),scaleUpWaitMs:5e3,mintCooldownMs:1e4,sessionIdleTtlMs:6e4,idleSweepMs:5e3,onEvent:p=>{ht.has(p.kind)&&e(`[pooler] ${p.kind} ${JSON.stringify(p)}`)}});await o.warm();let l=s.laneDocHostUrl===void 0?void 0:lt({docHostUrl:s.laneDocHostUrl,redis:t}),{server:h,close:y}=_t({pooler:o,token:s.token,lanePlane:l,log:e});await new Promise((p,d)=>{h.once("error",d),h.listen(s.port,s.bindHost,()=>p())}),e(`urun-pooler listening on http://${s.bindHost}:${s.port} (targets ${s.targets.map(p=>`${p.region}:${p.model} min=${p.min} max=${p.max}`).join(", ")})${l===void 0?"":" lanes=on"}`);let R=async p=>{e(`urun-pooler: ${p} \u2014 draining`),await y(),await o.close(),await l?.close(),await t.quit().catch(()=>{})};await new Promise(p=>{j.default.once("SIGINT",()=>{R("SIGINT").finally(p)}),j.default.once("SIGTERM",()=>{R("SIGTERM").finally(p)})})}nr().then(()=>j.default.exit(0),s=>{te(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