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