@urun-sh/openai 0.6.41 → 0.6.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/{ResponsesClient-gfg7qUoE.d.ts → ResponsesClient-2EsjJUz1.d.ts} +1 -1
  2. package/dist/{ResponsesClient-6QsC7NPJ.d.cts → ResponsesClient-BIcQ6p6Z.d.cts} +1 -1
  3. package/dist/{chunk-ILYHXVNZ.js → chunk-27HP3RMZ.js} +1 -1
  4. package/dist/chunk-2NKCALKY.js +22 -0
  5. package/dist/chunk-2RO722HS.js +2 -0
  6. package/dist/chunk-7DUSLXPG.js +1 -0
  7. package/dist/chunk-BFIKVTQB.js +1 -0
  8. package/dist/{chunk-4NMMWAKD.js → chunk-FF3RWDFM.js} +1 -1
  9. package/dist/chunk-GDH2D3S6.js +1 -0
  10. package/dist/chunk-J3KCHTSA.js +6 -0
  11. package/dist/{chunk-QTHFMDZY.js → chunk-JMSVHETI.js} +1 -1
  12. package/dist/{chunk-L4QBHSVY.js → chunk-MJSK6W3W.js} +1 -1
  13. package/dist/chunk-MOX5FG2R.js +1 -0
  14. package/dist/chunk-YRBUHHI3.js +2 -0
  15. package/dist/chunk-ZCF6EV4Y.js +65 -0
  16. package/dist/{composite-B-F2J0NK.d.cts → composite-BoS9-74g.d.cts} +320 -4
  17. package/dist/{composite-B--rGI5m.d.ts → composite-D4_XPSas.d.ts} +91 -4
  18. package/dist/gemini-live.cjs +2 -2
  19. package/dist/gemini-live.d.cts +4 -4
  20. package/dist/gemini-live.d.ts +4 -4
  21. package/dist/gemini-live.js +1 -1
  22. package/dist/hosted/bin.cjs +44 -43
  23. package/dist/hosted/bin.js +1 -1
  24. package/dist/hosted/index.cjs +43 -42
  25. package/dist/hosted/index.d.cts +54 -10
  26. package/dist/hosted/index.d.ts +11 -5
  27. package/dist/hosted/index.js +1 -1
  28. package/dist/index.cjs +1 -1
  29. package/dist/index.d.cts +4 -4
  30. package/dist/index.d.ts +4 -4
  31. package/dist/index.js +1 -1
  32. package/dist/pi-extension/index.cjs +7 -7
  33. package/dist/pi-extension/index.d.cts +2 -2
  34. package/dist/pi-extension/index.d.ts +2 -2
  35. package/dist/pi-extension/index.js +1 -1
  36. package/dist/pi-extension/standalone.cjs +55 -55
  37. package/dist/pooler/bin.cjs +40 -41
  38. package/dist/pooler/bin.js +39 -40
  39. package/dist/proxy/cli.cjs +54 -53
  40. package/dist/proxy/cli.js +1 -1
  41. package/dist/proxy/conformance-probe.cjs +1 -1
  42. package/dist/proxy/conformance-probe.js +1 -1
  43. package/dist/proxy/index.cjs +33 -32
  44. package/dist/proxy/index.d.cts +37 -214
  45. package/dist/proxy/index.d.ts +17 -65
  46. package/dist/proxy/index.js +1 -1
  47. package/dist/{translator-BqpmZ-vh.d.ts → translator-BemK1Of5.d.ts} +1 -1
  48. package/dist/{translator-Dox25ky9.d.cts → translator-PsmsZT62.d.cts} +1 -1
  49. package/dist/{types-CHPtJx6d.d.cts → types-CxWQ84Ew.d.cts} +5 -0
  50. package/dist/{types-CHPtJx6d.d.ts → types-CxWQ84Ew.d.ts} +2 -0
  51. package/dist/{video-out-DnCKUUO2.d.cts → video-out-DPLqpGbQ.d.cts} +17 -3
  52. package/dist/{video-out-REmiQMBJ.d.ts → video-out-DkMqKSOi.d.ts} +6 -2
  53. package/package.json +2 -2
  54. package/dist/chunk-7KRHHEKZ.js +0 -1
  55. package/dist/chunk-G7CSAISC.js +0 -1
  56. package/dist/chunk-GX243AIV.js +0 -1
  57. package/dist/chunk-HBKAN6PP.js +0 -2
  58. package/dist/chunk-HPUX2H65.js +0 -6
  59. package/dist/chunk-KKCUIOL4.js +0 -1
  60. package/dist/chunk-PAAFRUQZ.js +0 -64
  61. package/dist/chunk-VVQSFACF.js +0 -23
  62. package/dist/chunk-Z3QCHKJB.js +0 -1
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var rn=Object.create;var Ge=Object.defineProperty;var sn=Object.getOwnPropertyDescriptor;var on=Object.getOwnPropertyNames;var an=Object.getPrototypeOf,ln=Object.prototype.hasOwnProperty;var un=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(e=s(s=0)),e}catch(n){throw t=[n],n}};var dn=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var cn=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of on(e))!ln.call(s,r)&&r!==t&&Ge(s,r,{get:()=>e[r],enumerable:!(n=sn(e,r))||n.enumerable});return s};var te=(s,e,t)=>(t=s!=null?rn(an(s)):{},cn(e||!s||!s.__esModule?Ge(t,"default",{value:s,enumerable:!0}):t,s));var S=un(()=>{"use strict"});var He=dn(()=>{"use strict";S();var je;(function(s){(function(e){var t=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:p(),n=r(s);typeof t.Reflect<"u"&&(n=r(t.Reflect,n)),e(n,t),typeof t.Reflect>"u"&&(t.Reflect=s);function r(g,R){return function(_,d){Object.defineProperty(g,_,{configurable:!0,writable:!0,value:d}),R&&R(_,d)}}function i(){try{return Function("return this;")()}catch{}}function l(){try{return(0,eval)("(function() { return this; })()")}catch{}}function p(){return i()||l()}})(function(e,t){var n=Object.prototype.hasOwnProperty,r=typeof Symbol=="function",i=r&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",l=r&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",p=typeof Object.create=="function",g={__proto__:[]}instanceof Array,R=!p&&!g,_={create:p?function(){return he(Object.create(null))}:g?function(){return he({__proto__:null})}:function(){return he({})},has:R?function(o,a){return n.call(o,a)}:function(o,a){return a in o},get:R?function(o,a){return n.call(o,a)?o[a]:void 0}:function(o,a){return o[a]}},d=Object.getPrototypeOf(Function),m=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Xt(),T=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Zt(),k=typeof WeakMap=="function"?WeakMap:en(),I=r?Symbol.for("@reflect-metadata:registry"):void 0,x=Wt(),A=zt(x);function N(o,a,u,c){if(b(u)){if(!Ne(o))throw new TypeError;if(!Me(a))throw new TypeError;return jt(o,a)}else{if(!Ne(o))throw new TypeError;if(!$(a))throw new TypeError;if(!$(c)&&!b(c)&&!J(c))throw new TypeError;return J(c)&&(c=void 0),u=G(u),Ht(o,a,u,c)}}e("decorate",N);function de(o,a){function u(c,w){if(!$(c))throw new TypeError;if(!b(w)&&!Yt(w))throw new TypeError;Te(o,a,c,w)}return u}e("metadata",de);function ee(o,a,u,c){if(!$(u))throw new TypeError;return b(c)||(c=G(c)),Te(o,a,u,c)}e("defineMetadata",ee);function B(o,a,u){if(!$(a))throw new TypeError;return b(u)||(u=G(u)),Ee(o,a,u)}e("hasMetadata",B);function Ct(o,a,u){if(!$(a))throw new TypeError;return b(u)||(u=G(u)),ce(o,a,u)}e("hasOwnMetadata",Ct);function Lt(o,a,u){if(!$(a))throw new TypeError;return b(u)||(u=G(u)),ke(o,a,u)}e("getMetadata",Lt);function Ut(o,a,u){if(!$(a))throw new TypeError;return b(u)||(u=G(u)),Pe(o,a,u)}e("getOwnMetadata",Ut);function qt(o,a){if(!$(o))throw new TypeError;return b(a)||(a=G(a)),Ie(o,a)}e("getMetadataKeys",qt);function Dt(o,a){if(!$(o))throw new TypeError;return b(a)||(a=G(a)),xe(o,a)}e("getOwnMetadataKeys",Dt);function Gt(o,a,u){if(!$(a))throw new TypeError;if(b(u)||(u=G(u)),!$(a))throw new TypeError;b(u)||(u=G(u));var c=Q(a,u,!1);return b(c)?!1:c.OrdinaryDeleteMetadata(o,a,u)}e("deleteMetadata",Gt);function jt(o,a){for(var u=o.length-1;u>=0;--u){var c=o[u],w=c(a);if(!b(w)&&!J(w)){if(!Me(w))throw new TypeError;a=w}}return a}function Ht(o,a,u,c){for(var w=o.length-1;w>=0;--w){var C=o[w],U=C(a,u,c);if(!b(U)&&!J(U)){if(!$(U))throw new TypeError;c=U}}return c}function Ee(o,a,u){var c=ce(o,a,u);if(c)return!0;var w=fe(a);return J(w)?!1:Ee(o,w,u)}function ce(o,a,u){var c=Q(a,u,!1);return b(c)?!1:Oe(c.OrdinaryHasOwnMetadata(o,a,u))}function ke(o,a,u){var c=ce(o,a,u);if(c)return Pe(o,a,u);var w=fe(a);if(!J(w))return ke(o,w,u)}function Pe(o,a,u){var c=Q(a,u,!1);if(!b(c))return c.OrdinaryGetOwnMetadata(o,a,u)}function Te(o,a,u,c){var w=Q(u,c,!0);w.OrdinaryDefineOwnMetadata(o,a,u,c)}function Ie(o,a){var u=xe(o,a),c=fe(o);if(c===null)return u;var w=Ie(c,a);if(w.length<=0)return u;if(u.length<=0)return w;for(var C=new T,U=[],E=0,f=u;E<f.length;E++){var h=f[E],y=C.has(h);y||(C.add(h),U.push(h))}for(var v=0,P=w;v<P.length;v++){var h=P[v],y=C.has(h);y||(C.add(h),U.push(h))}return U}function xe(o,a){var u=Q(o,a,!1);return u?u.OrdinaryOwnMetadataKeys(o,a):[]}function Ae(o){if(o===null)return 1;switch(typeof o){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return o===null?1:6;default:return 6}}function b(o){return o===void 0}function J(o){return o===null}function Ft(o){return typeof o=="symbol"}function $(o){return typeof o=="object"?o!==null:typeof o=="function"}function Kt(o,a){switch(Ae(o)){case 0:return o;case 1:return o;case 2:return o;case 3:return o;case 4:return o;case 5:return o}var u=a===3?"string":a===5?"number":"default",c=$e(o,i);if(c!==void 0){var w=c.call(o,u);if($(w))throw new TypeError;return w}return Vt(o,u==="default"?"number":u)}function Vt(o,a){if(a==="string"){var u=o.toString;if(W(u)){var c=u.call(o);if(!$(c))return c}var w=o.valueOf;if(W(w)){var c=w.call(o);if(!$(c))return c}}else{var w=o.valueOf;if(W(w)){var c=w.call(o);if(!$(c))return c}var C=o.toString;if(W(C)){var c=C.call(o);if(!$(c))return c}}throw new TypeError}function Oe(o){return!!o}function Bt(o){return""+o}function G(o){var a=Kt(o,3);return Ft(a)?a:Bt(a)}function Ne(o){return Array.isArray?Array.isArray(o):o instanceof Object?o instanceof Array:Object.prototype.toString.call(o)==="[object Array]"}function W(o){return typeof o=="function"}function Me(o){return typeof o=="function"}function Yt(o){switch(Ae(o)){case 3:return!0;case 4:return!0;default:return!1}}function pe(o,a){return o===a||o!==o&&a!==a}function $e(o,a){var u=o[a];if(u!=null){if(!W(u))throw new TypeError;return u}}function Ce(o){var a=$e(o,l);if(!W(a))throw new TypeError;var u=a.call(o);if(!$(u))throw new TypeError;return u}function Le(o){return o.value}function Ue(o){var a=o.next();return a.done?!1:a}function qe(o){var a=o.return;a&&a.call(o)}function fe(o){var a=Object.getPrototypeOf(o);if(typeof o!="function"||o===d||a!==d)return a;var u=o.prototype,c=u&&Object.getPrototypeOf(u);if(c==null||c===Object.prototype)return a;var w=c.constructor;return typeof w!="function"||w===o?a:w}function Jt(){var o;!b(I)&&typeof t.Reflect<"u"&&!(I in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(o=Qt(t.Reflect));var a,u,c,w=new k,C={registerProvider:U,getProvider:f,setProvider:y};return C;function U(v){if(!Object.isExtensible(C))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case o===v:break;case b(a):a=v;break;case a===v:break;case b(u):u=v;break;case u===v:break;default:c===void 0&&(c=new T),c.add(v);break}}function E(v,P){if(!b(a)){if(a.isProviderFor(v,P))return a;if(!b(u)){if(u.isProviderFor(v,P))return a;if(!b(c))for(var O=Ce(c);;){var L=Ue(O);if(!L)return;var D=Le(L);if(D.isProviderFor(v,P))return qe(O),D}}}if(!b(o)&&o.isProviderFor(v,P))return o}function f(v,P){var O=w.get(v),L;return b(O)||(L=O.get(P)),b(L)&&(L=E(v,P),b(L)||(b(O)&&(O=new m,w.set(v,O)),O.set(P,L))),L}function h(v){if(b(v))throw new TypeError;return a===v||u===v||!b(c)&&c.has(v)}function y(v,P,O){if(!h(O))throw new Error("Metadata provider not registered.");var L=f(v,P);if(L!==O){if(!b(L))return!1;var D=w.get(v);b(D)&&(D=new m,w.set(v,D)),D.set(P,O)}return!0}}function Wt(){var o;return!b(I)&&$(t.Reflect)&&Object.isExtensible(t.Reflect)&&(o=t.Reflect[I]),b(o)&&(o=Jt()),!b(I)&&$(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,I,{enumerable:!1,configurable:!1,writable:!1,value:o}),o}function zt(o){var a=new k,u={isProviderFor:function(h,y){var v=a.get(h);return b(v)?!1:v.has(y)},OrdinaryDefineOwnMetadata:U,OrdinaryHasOwnMetadata:w,OrdinaryGetOwnMetadata:C,OrdinaryOwnMetadataKeys:E,OrdinaryDeleteMetadata:f};return x.registerProvider(u),u;function c(h,y,v){var P=a.get(h),O=!1;if(b(P)){if(!v)return;P=new m,a.set(h,P),O=!0}var L=P.get(y);if(b(L)){if(!v)return;if(L=new m,P.set(y,L),!o.setProvider(h,y,u))throw P.delete(y),O&&a.delete(h),new Error("Wrong provider for target.")}return L}function w(h,y,v){var P=c(y,v,!1);return b(P)?!1:Oe(P.has(h))}function C(h,y,v){var P=c(y,v,!1);if(!b(P))return P.get(h)}function U(h,y,v,P){var O=c(v,P,!0);O.set(h,y)}function E(h,y){var v=[],P=c(h,y,!1);if(b(P))return v;for(var O=P.keys(),L=Ce(O),D=0;;){var De=Ue(L);if(!De)return v.length=D,v;var tn=Le(De);try{v[D]=tn}catch(nn){try{qe(L)}finally{throw nn}}D++}}function f(h,y,v){var P=c(y,v,!1);if(b(P)||!P.delete(h))return!1;if(P.size===0){var O=a.get(y);b(O)||(O.delete(v),O.size===0&&a.delete(O))}return!0}}function Qt(o){var a=o.defineMetadata,u=o.hasOwnMetadata,c=o.getOwnMetadata,w=o.getOwnMetadataKeys,C=o.deleteMetadata,U=new k,E={isProviderFor:function(f,h){var y=U.get(f);return!b(y)&&y.has(h)?!0:w(f,h).length?(b(y)&&(y=new T,U.set(f,y)),y.add(h),!0):!1},OrdinaryDefineOwnMetadata:a,OrdinaryHasOwnMetadata:u,OrdinaryGetOwnMetadata:c,OrdinaryOwnMetadataKeys:w,OrdinaryDeleteMetadata:C};return E}function Q(o,a,u){var c=x.getProvider(o,a);if(!b(c))return c;if(u){if(x.setProvider(o,a,A))return A;throw new Error("Illegal state.")}}function Xt(){var o={},a=[],u=(function(){function E(f,h,y){this._index=0,this._keys=f,this._values=h,this._selector=y}return E.prototype["@@iterator"]=function(){return this},E.prototype[l]=function(){return this},E.prototype.next=function(){var f=this._index;if(f>=0&&f<this._keys.length){var h=this._selector(this._keys[f],this._values[f]);return f+1>=this._keys.length?(this._index=-1,this._keys=a,this._values=a):this._index++,{value:h,done:!1}}return{value:void 0,done:!0}},E.prototype.throw=function(f){throw this._index>=0&&(this._index=-1,this._keys=a,this._values=a),f},E.prototype.return=function(f){return this._index>=0&&(this._index=-1,this._keys=a,this._values=a),{value:f,done:!0}},E})(),c=(function(){function E(){this._keys=[],this._values=[],this._cacheKey=o,this._cacheIndex=-2}return Object.defineProperty(E.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),E.prototype.has=function(f){return this._find(f,!1)>=0},E.prototype.get=function(f){var h=this._find(f,!1);return h>=0?this._values[h]:void 0},E.prototype.set=function(f,h){var y=this._find(f,!0);return this._values[y]=h,this},E.prototype.delete=function(f){var h=this._find(f,!1);if(h>=0){for(var y=this._keys.length,v=h+1;v<y;v++)this._keys[v-1]=this._keys[v],this._values[v-1]=this._values[v];return this._keys.length--,this._values.length--,pe(f,this._cacheKey)&&(this._cacheKey=o,this._cacheIndex=-2),!0}return!1},E.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=o,this._cacheIndex=-2},E.prototype.keys=function(){return new u(this._keys,this._values,w)},E.prototype.values=function(){return new u(this._keys,this._values,C)},E.prototype.entries=function(){return new u(this._keys,this._values,U)},E.prototype["@@iterator"]=function(){return this.entries()},E.prototype[l]=function(){return this.entries()},E.prototype._find=function(f,h){if(!pe(this._cacheKey,f)){this._cacheIndex=-1;for(var y=0;y<this._keys.length;y++)if(pe(this._keys[y],f)){this._cacheIndex=y;break}}return this._cacheIndex<0&&h&&(this._cacheIndex=this._keys.length,this._keys.push(f),this._values.push(void 0)),this._cacheIndex},E})();return c;function w(E,f){return E}function C(E,f){return f}function U(E,f){return[E,f]}}function Zt(){var o=(function(){function a(){this._map=new m}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 en(){var o=16,a=_.create(),u=c();return(function(){function f(){this._key=c()}return f.prototype.has=function(h){var y=w(h,!1);return y!==void 0?_.has(y,this._key):!1},f.prototype.get=function(h){var y=w(h,!1);return y!==void 0?_.get(y,this._key):void 0},f.prototype.set=function(h,y){var v=w(h,!0);return v[this._key]=y,this},f.prototype.delete=function(h){var y=w(h,!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@@"+E();while(_.has(a,f));return a[f]=!0,f}function w(f,h){if(!n.call(f,u)){if(!h)return;Object.defineProperty(f,u,{value:_.create()})}return f[u]}function C(f,h){for(var y=0;y<h;++y)f[y]=Math.random()*255|0;return f}function U(f){if(typeof Uint8Array=="function"){var h=new Uint8Array(f);return typeof crypto<"u"?crypto.getRandomValues(h):typeof msCrypto<"u"?msCrypto.getRandomValues(h):C(h,f),h}return C(new Array(f),f)}function E(){var f=U(o);f[6]=f[6]&79|64,f[8]=f[8]&191|128;for(var h="",y=0;y<o;++y){var v=f[y];(y===4||y===6||y===8)&&(h+="-"),v<16&&(h+="0"),h+=v.toString(16).toLowerCase()}return h}}function he(o){return o.__=void 0,delete o.__,o}})})(je||(je={}))});S();var Js=te(He(),1),j=te(require("process"),1),$t=require("ioredis");S();var mn=te(require("os"),1),yn=te(require("path"),1),vn=require("url"),wn=require("util");S();var gn=require("crypto");S();S();S();S();S();var H=class extends Error{};var _n=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Fe(s){let e=s?.code;return typeof e=="string"&&_n.has(e)}function ne(s,e){try{return s.write(e),!0}catch(t){if(Fe(t))return!1;throw t}}function Ke(s){let e={stdout:!1,stderr:!1},t=[];for(let n of["stdout","stderr"]){let r=s.streams[n],i=l=>{Fe(l)&&(e[n]=!0);let p=l?.code;try{s.note(`${new Date().toISOString()} urun compat: process.${n} died (${String(p??(l instanceof Error?l.message:l))}) \u2014 the terminal is gone; launcher output continues in this log only
3
- `)}catch{}};r.on("error",i),t.push([r,i])}return{isDead:n=>e[n],uninstall:()=>{for(let[n,r]of t)n.off("error",r)}}}S();S();var ge=`
4
- local slot, retired, meta = KEYS[1], KEYS[2], KEYS[3]
2
+ "use strict";var an=Object.create;var Be=Object.defineProperty;var ln=Object.getOwnPropertyDescriptor;var un=Object.getOwnPropertyNames;var dn=Object.getPrototypeOf,cn=Object.prototype.hasOwnProperty;var pn=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(e=s(s=0)),e}catch(n){throw t=[n],n}};var fn=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var hn=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of un(e))!cn.call(s,r)&&r!==t&&Be(s,r,{get:()=>e[r],enumerable:!(n=ln(e,r))||n.enumerable});return s};var le=(s,e,t)=>(t=s!=null?an(dn(s)):{},hn(e||!s||!s.__esModule?Be(t,"default",{value:s,enumerable:!0}):t,s));var b=pn(()=>{"use strict"});var We=fn(()=>{"use strict";b();var Je;(function(s){(function(e){var t=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:p(),n=r(s);typeof t.Reflect<"u"&&(n=r(t.Reflect,n)),e(n,t),typeof t.Reflect>"u"&&(t.Reflect=s);function r(m,v){return function(h,d){Object.defineProperty(m,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",m={__proto__:[]}instanceof Array,v=!p&&!m,h={create:p?function(){return be(Object.create(null))}:m?function(){return be({__proto__:null})}:function(){return be({})},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),R=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:tn(),$=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:nn(),S=typeof WeakMap=="function"?WeakMap:rn(),k=r?Symbol.for("@reflect-metadata:registry"):void 0,N=Xt(),O=Zt(N);function T(o,a,u,c){if(E(u)){if(!De(o))throw new TypeError;if(!Ge(a))throw new TypeError;return X(o,a)}else{if(!De(o))throw new TypeError;if(!L(a))throw new TypeError;if(!L(c)&&!E(c)&&!ne(c))throw new TypeError;return ne(c)&&(c=void 0),u=Y(u),we(o,a,u,c)}}e("decorate",T);function A(o,a){function u(c,_){if(!L(c))throw new TypeError;if(!E(_)&&!zt(_))throw new TypeError;Ce(o,a,c,_)}return u}e("metadata",A);function x(o,a,u,c){if(!L(u))throw new TypeError;return E(c)||(c=Y(c)),Ce(o,a,u,c)}e("defineMetadata",x);function G(o,a,u){if(!L(a))throw new TypeError;return E(u)||(u=Y(u)),Oe(o,a,u)}e("hasMetadata",G);function D(o,a,u){if(!L(a))throw new TypeError;return E(u)||(u=Y(u)),ve(o,a,u)}e("hasOwnMetadata",D);function V(o,a,u){if(!L(a))throw new TypeError;return E(u)||(u=Y(u)),Me(o,a,u)}e("getMetadata",V);function F(o,a,u){if(!L(a))throw new TypeError;return E(u)||(u=Y(u)),Ne(o,a,u)}e("getOwnMetadata",F);function z(o,a){if(!L(o))throw new TypeError;return E(a)||(a=Y(a)),$e(o,a)}e("getMetadataKeys",z);function Q(o,a){if(!L(o))throw new TypeError;return E(a)||(a=Y(a)),Le(o,a)}e("getOwnMetadataKeys",Q);function ae(o,a,u){if(!L(a))throw new TypeError;if(E(u)||(u=Y(u)),!L(a))throw new TypeError;E(u)||(u=Y(u));var c=ie(a,u,!1);return E(c)?!1:c.OrdinaryDeleteMetadata(o,a,u)}e("deleteMetadata",ae);function X(o,a){for(var u=o.length-1;u>=0;--u){var c=o[u],_=c(a);if(!E(_)&&!ne(_)){if(!Ge(_))throw new TypeError;a=_}}return a}function we(o,a,u,c){for(var _=o.length-1;_>=0;--_){var U=o[_],j=U(a,u,c);if(!E(j)&&!ne(j)){if(!L(j))throw new TypeError;c=j}}return c}function Oe(o,a,u){var c=ve(o,a,u);if(c)return!0;var _=Se(a);return ne(_)?!1:Oe(o,_,u)}function ve(o,a,u){var c=ie(a,u,!1);return E(c)?!1:qe(c.OrdinaryHasOwnMetadata(o,a,u))}function Me(o,a,u){var c=ve(o,a,u);if(c)return Ne(o,a,u);var _=Se(a);if(!ne(_))return Me(o,_,u)}function Ne(o,a,u){var c=ie(a,u,!1);if(!E(c))return c.OrdinaryGetOwnMetadata(o,a,u)}function Ce(o,a,u,c){var _=ie(u,c,!0);_.OrdinaryDefineOwnMetadata(o,a,u,c)}function $e(o,a){var u=Le(o,a),c=Se(o);if(c===null)return u;var _=$e(c,a);if(_.length<=0)return u;if(u.length<=0)return _;for(var U=new $,j=[],P=0,f=u;P<f.length;P++){var g=f[P],y=U.has(g);y||(U.add(g),j.push(g))}for(var w=0,I=_;w<I.length;w++){var g=I[w],y=U.has(g);y||(U.add(g),j.push(g))}return j}function Le(o,a){var u=ie(o,a,!1);return u?u.OrdinaryOwnMetadataKeys(o,a):[]}function Ue(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 E(o){return o===void 0}function ne(o){return o===null}function Yt(o){return typeof o=="symbol"}function L(o){return typeof o=="object"?o!==null:typeof o=="function"}function Bt(o,a){switch(Ue(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=je(o,i);if(c!==void 0){var _=c.call(o,u);if(L(_))throw new TypeError;return _}return Jt(o,u==="default"?"number":u)}function Jt(o,a){if(a==="string"){var u=o.toString;if(re(u)){var c=u.call(o);if(!L(c))return c}var _=o.valueOf;if(re(_)){var c=_.call(o);if(!L(c))return c}}else{var _=o.valueOf;if(re(_)){var c=_.call(o);if(!L(c))return c}var U=o.toString;if(re(U)){var c=U.call(o);if(!L(c))return c}}throw new TypeError}function qe(o){return!!o}function Wt(o){return""+o}function Y(o){var a=Bt(o,3);return Yt(a)?a:Wt(a)}function De(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 Ge(o){return typeof o=="function"}function zt(o){switch(Ue(o)){case 3:return!0;case 4:return!0;default:return!1}}function _e(o,a){return o===a||o!==o&&a!==a}function je(o,a){var u=o[a];if(u!=null){if(!re(u))throw new TypeError;return u}}function Fe(o){var a=je(o,l);if(!re(a))throw new TypeError;var u=a.call(o);if(!L(u))throw new TypeError;return u}function He(o){return o.value}function Ke(o){var a=o.next();return a.done?!1:a}function Ve(o){var a=o.return;a&&a.call(o)}function Se(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 _=c.constructor;return typeof _!="function"||_===o?a:_}function Qt(){var o;!E(k)&&typeof t.Reflect<"u"&&!(k in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(o=en(t.Reflect));var a,u,c,_=new S,U={registerProvider:j,getProvider:f,setProvider:y};return U;function j(w){if(!Object.isExtensible(U))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case o===w:break;case E(a):a=w;break;case a===w:break;case E(u):u=w;break;case u===w:break;default:c===void 0&&(c=new $),c.add(w);break}}function P(w,I){if(!E(a)){if(a.isProviderFor(w,I))return a;if(!E(u)){if(u.isProviderFor(w,I))return a;if(!E(c))for(var M=Fe(c);;){var q=Ke(M);if(!q)return;var K=He(q);if(K.isProviderFor(w,I))return Ve(M),K}}}if(!E(o)&&o.isProviderFor(w,I))return o}function f(w,I){var M=_.get(w),q;return E(M)||(q=M.get(I)),E(q)&&(q=P(w,I),E(q)||(E(M)&&(M=new R,_.set(w,M)),M.set(I,q))),q}function g(w){if(E(w))throw new TypeError;return a===w||u===w||!E(c)&&c.has(w)}function y(w,I,M){if(!g(M))throw new Error("Metadata provider not registered.");var q=f(w,I);if(q!==M){if(!E(q))return!1;var K=_.get(w);E(K)&&(K=new R,_.set(w,K)),K.set(I,M)}return!0}}function Xt(){var o;return!E(k)&&L(t.Reflect)&&Object.isExtensible(t.Reflect)&&(o=t.Reflect[k]),E(o)&&(o=Qt()),!E(k)&&L(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,k,{enumerable:!1,configurable:!1,writable:!1,value:o}),o}function Zt(o){var a=new S,u={isProviderFor:function(g,y){var w=a.get(g);return E(w)?!1:w.has(y)},OrdinaryDefineOwnMetadata:j,OrdinaryHasOwnMetadata:_,OrdinaryGetOwnMetadata:U,OrdinaryOwnMetadataKeys:P,OrdinaryDeleteMetadata:f};return N.registerProvider(u),u;function c(g,y,w){var I=a.get(g),M=!1;if(E(I)){if(!w)return;I=new R,a.set(g,I),M=!0}var q=I.get(y);if(E(q)){if(!w)return;if(q=new R,I.set(y,q),!o.setProvider(g,y,u))throw I.delete(y),M&&a.delete(g),new Error("Wrong provider for target.")}return q}function _(g,y,w){var I=c(y,w,!1);return E(I)?!1:qe(I.has(g))}function U(g,y,w){var I=c(y,w,!1);if(!E(I))return I.get(g)}function j(g,y,w,I){var M=c(w,I,!0);M.set(g,y)}function P(g,y){var w=[],I=c(g,y,!1);if(E(I))return w;for(var M=I.keys(),q=Fe(M),K=0;;){var Ye=Ke(q);if(!Ye)return w.length=K,w;var sn=He(Ye);try{w[K]=sn}catch(on){try{Ve(q)}finally{throw on}}K++}}function f(g,y,w){var I=c(y,w,!1);if(E(I)||!I.delete(g))return!1;if(I.size===0){var M=a.get(y);E(M)||(M.delete(w),M.size===0&&a.delete(M))}return!0}}function en(o){var a=o.defineMetadata,u=o.hasOwnMetadata,c=o.getOwnMetadata,_=o.getOwnMetadataKeys,U=o.deleteMetadata,j=new S,P={isProviderFor:function(f,g){var y=j.get(f);return!E(y)&&y.has(g)?!0:_(f,g).length?(E(y)&&(y=new $,j.set(f,y)),y.add(g),!0):!1},OrdinaryDefineOwnMetadata:a,OrdinaryHasOwnMetadata:u,OrdinaryGetOwnMetadata:c,OrdinaryOwnMetadataKeys:_,OrdinaryDeleteMetadata:U};return P}function ie(o,a,u){var c=N.getProvider(o,a);if(!E(c))return c;if(u){if(N.setProvider(o,a,O))return O;throw new Error("Illegal state.")}}function tn(){var o={},a=[],u=(function(){function P(f,g,y){this._index=0,this._keys=f,this._values=g,this._selector=y}return P.prototype["@@iterator"]=function(){return this},P.prototype[l]=function(){return this},P.prototype.next=function(){var f=this._index;if(f>=0&&f<this._keys.length){var g=this._selector(this._keys[f],this._values[f]);return f+1>=this._keys.length?(this._index=-1,this._keys=a,this._values=a):this._index++,{value:g,done:!1}}return{value:void 0,done:!0}},P.prototype.throw=function(f){throw this._index>=0&&(this._index=-1,this._keys=a,this._values=a),f},P.prototype.return=function(f){return this._index>=0&&(this._index=-1,this._keys=a,this._values=a),{value:f,done:!0}},P})(),c=(function(){function P(){this._keys=[],this._values=[],this._cacheKey=o,this._cacheIndex=-2}return Object.defineProperty(P.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),P.prototype.has=function(f){return this._find(f,!1)>=0},P.prototype.get=function(f){var g=this._find(f,!1);return g>=0?this._values[g]:void 0},P.prototype.set=function(f,g){var y=this._find(f,!0);return this._values[y]=g,this},P.prototype.delete=function(f){var g=this._find(f,!1);if(g>=0){for(var y=this._keys.length,w=g+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--,_e(f,this._cacheKey)&&(this._cacheKey=o,this._cacheIndex=-2),!0}return!1},P.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=o,this._cacheIndex=-2},P.prototype.keys=function(){return new u(this._keys,this._values,_)},P.prototype.values=function(){return new u(this._keys,this._values,U)},P.prototype.entries=function(){return new u(this._keys,this._values,j)},P.prototype["@@iterator"]=function(){return this.entries()},P.prototype[l]=function(){return this.entries()},P.prototype._find=function(f,g){if(!_e(this._cacheKey,f)){this._cacheIndex=-1;for(var y=0;y<this._keys.length;y++)if(_e(this._keys[y],f)){this._cacheIndex=y;break}}return this._cacheIndex<0&&g&&(this._cacheIndex=this._keys.length,this._keys.push(f),this._values.push(void 0)),this._cacheIndex},P})();return c;function _(P,f){return P}function U(P,f){return f}function j(P,f){return[P,f]}}function nn(){var o=(function(){function a(){this._map=new R}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 rn(){var o=16,a=h.create(),u=c();return(function(){function f(){this._key=c()}return f.prototype.has=function(g){var y=_(g,!1);return y!==void 0?h.has(y,this._key):!1},f.prototype.get=function(g){var y=_(g,!1);return y!==void 0?h.get(y,this._key):void 0},f.prototype.set=function(g,y){var w=_(g,!0);return w[this._key]=y,this},f.prototype.delete=function(g){var y=_(g,!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@@"+P();while(h.has(a,f));return a[f]=!0,f}function _(f,g){if(!n.call(f,u)){if(!g)return;Object.defineProperty(f,u,{value:h.create()})}return f[u]}function U(f,g){for(var y=0;y<g;++y)f[y]=Math.random()*255|0;return f}function j(f){if(typeof Uint8Array=="function"){var g=new Uint8Array(f);return typeof crypto<"u"?crypto.getRandomValues(g):typeof msCrypto<"u"?msCrypto.getRandomValues(g):U(g,f),g}return U(new Array(f),f)}function P(){var f=j(o);f[6]=f[6]&79|64,f[8]=f[8]&191|128;for(var g="",y=0;y<o;++y){var w=f[y];(y===4||y===6||y===8)&&(g+="-"),w<16&&(g+="0"),g+=w.toString(16).toLowerCase()}return g}}function be(o){return o.__=void 0,delete o.__,o}})})(Je||(Je={}))});b();var Qs=le(We(),1),B=le(require("process"),1),Vt=require("ioredis");b();var vn=le(require("os"),1),_n=le(require("path"),1),Sn=require("url"),bn=require("util");b();var wn=require("crypto");b();b();b();b();b();var J=class extends Error{};var Rn=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function ze(s){let e=s?.code;return typeof e=="string"&&Rn.has(e)}function ue(s,e){try{return s.write(e),!0}catch(t){if(ze(t))return!1;throw t}}function Qe(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
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();var Xe="urun:catalog:v1";b();b();var Re=`
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]
6
6
  -- The session-as-routing-identity schema (docs/pooler-session-registry.md
7
7
  -- \xA72.1): ARGV 4-6 carry {model, capabilities, cacheNs} when the caller
@@ -38,8 +38,9 @@ if cacheNs then
38
38
  'model', model, 'capabilities', capabilities)
39
39
  end
40
40
  redis.call('HINCRBY', meta, 'queued', 1)
41
+ redis.call('SADD', idx, key)
41
42
  return 'ok'
42
- `,me=`
43
+ `,Ee=`
43
44
  local slot, genkey, retired, meta = KEYS[1], KEYS[2], KEYS[3], KEYS[4]
44
45
  local key, gen, sessionId, now = ARGV[1], tonumber(ARGV[2]), ARGV[3], ARGV[4]
45
46
  -- The session-registry schema (\xA72.3): ARGV[5] is the caller's OBSERVED
@@ -81,7 +82,7 @@ redis.call('HSET', slot, 'state', 'attached', 'sessionId', sessionId, 'since', n
81
82
  redis.call('HINCRBY', meta, 'queued', -1)
82
83
  redis.call('HINCRBY', meta, 'attached', 1)
83
84
  return 'ok'
84
- `,Ve=`
85
+ `,Ze=`
85
86
  local slot, meta = KEYS[1], KEYS[2]
86
87
  local key, reason, now = ARGV[1], ARGV[2], ARGV[3]
87
88
  local state = redis.call('HGET', slot, 'state')
@@ -95,8 +96,8 @@ redis.call('HSET', slot, 'state', 'paused', 'since', now, 'lastReason', reason)
95
96
  redis.call('HINCRBY', meta, state, -1)
96
97
  redis.call('HINCRBY', meta, 'paused', 1)
97
98
  return 'ok'
98
- `,Be=`
99
- local slot, genkey, retired, meta, newslot = KEYS[1], KEYS[2], KEYS[3], KEYS[4], KEYS[5]
99
+ `,et=`
100
+ local slot, genkey, retired, meta, newslot, idx = KEYS[1], KEYS[2], KEYS[3], KEYS[4], KEYS[5], KEYS[6]
100
101
  local oldKey, newKey, newGen = ARGV[1], ARGV[2], tonumber(ARGV[3])
101
102
  if redis.call('SISMEMBER', retired, oldKey) == 1 then
102
103
  return 'reject:double-rotate'
@@ -119,8 +120,9 @@ if redis.call('HSETNX', newslot, 'state', 'paused') == 1 then
119
120
  redis.call('HSET', newslot, 'gen', newGen, 'inFlight', 0, 'since', ARGV[4])
120
121
  redis.call('HINCRBY', meta, 'paused', 1)
121
122
  end
123
+ redis.call('SADD', idx, newKey)
122
124
  return 'ok'
123
- `,Ye=`
125
+ `,tt=`
124
126
  local slot, meta = KEYS[1], KEYS[2]
125
127
  local key, now = ARGV[1], ARGV[2]
126
128
  local state = redis.call('HGET', slot, 'state')
@@ -141,7 +143,7 @@ redis.call('HSET', slot, 'state', 'ended', 'since', now)
141
143
  redis.call('HINCRBY', meta, state, -1)
142
144
  redis.call('HINCRBY', meta, 'ended', 1)
143
145
  return 'ok'
144
- `,Je=`
146
+ `,nt=`
145
147
  local slot, meta = KEYS[1], KEYS[2]
146
148
  local key = ARGV[1]
147
149
  local state = redis.call('HGET', slot, 'state')
@@ -154,7 +156,7 @@ end
154
156
  redis.call('HINCRBY', slot, 'inFlight', 1)
155
157
  redis.call('HINCRBY', meta, 'inflight', 1)
156
158
  return 'ok'
157
- `,X=`
159
+ `,oe=`
158
160
  local slot, meta = KEYS[1], KEYS[2]
159
161
  local key, obsCap, obsVer = ARGV[1], tonumber(ARGV[2]), tonumber(ARGV[3])
160
162
  -- The session-registry schema (\xA72.3): ARGV[4] is the caller's OBSERVED
@@ -191,12 +193,12 @@ end
191
193
  redis.call('HINCRBY', slot, 'inFlight', 1)
192
194
  redis.call('HINCRBY', meta, 'inflight', 1)
193
195
  return 'ok'
194
- `,We=`
196
+ `,rt=`
195
197
  local meta = KEYS[1]
196
198
  return (redis.call('HGET', meta, 'max') or '-1')
197
199
  .. '|' .. (redis.call('HGET', meta, 'cap') or '-1')
198
200
  .. '|' .. (redis.call('HGET', meta, 'config_version') or '0')
199
- `,ze=`
201
+ `,st=`
200
202
  local slot, meta = KEYS[1], KEYS[2]
201
203
  local key, now = ARGV[1], ARGV[2]
202
204
  local state = redis.call('HGET', slot, 'state')
@@ -213,7 +215,7 @@ end
213
215
  redis.call('HSET', slot, 'inFlight', f - 1, 'idleSince', now)
214
216
  redis.call('HINCRBY', meta, 'inflight', -1)
215
217
  return 'ok'
216
- `,Qe=`
218
+ `,it=`
217
219
  local meta = KEYS[1]
218
220
  local max, cap = tonumber(ARGV[1]), tonumber(ARGV[2])
219
221
  if not max or max < 0 or not cap or cap < 1 then
@@ -222,7 +224,7 @@ end
222
224
  redis.call('HSET', meta, 'max', max, 'cap', cap)
223
225
  redis.call('HINCRBY', meta, 'config_version', 1)
224
226
  return 'ok'
225
- `,Xe=`
227
+ `,ot=`
226
228
  local meta = KEYS[1]
227
229
  local max, cap = tonumber(ARGV[1]), tonumber(ARGV[2])
228
230
  if not max or max < 0 or not cap or cap < 1 then
@@ -233,22 +235,19 @@ if redis.call('HSETNX', meta, 'max', max) == 0 then
233
235
  end
234
236
  redis.call('HSET', meta, 'cap', cap)
235
237
  return 'ok'
236
- `,Ze=`
237
- local prefix, meta = ARGV[1], KEYS[1]
238
+ `,at=`
239
+ local prefix, idx, meta = ARGV[1], KEYS[1], KEYS[2]
238
240
  local cursor, pageSize = ARGV[2], tonumber(ARGV[3])
241
+ local res = redis.call('SSCAN', idx, cursor, 'COUNT', pageSize)
242
+ local next = res[1]
239
243
  local lines = {}
240
- local next = cursor
241
- while true do
242
- local res = redis.call('SCAN', next, 'MATCH', prefix .. '*', 'COUNT', pageSize)
243
- next = res[1]
244
- for _, k in ipairs(res[2]) do
245
- lines[#lines + 1] = string.sub(k, #prefix + 1)
246
- .. '|' .. (redis.call('HGET', k, 'state') or 'none')
247
- .. '|' .. (redis.call('HGET', k, 'inFlight') or '0')
248
- .. '|' .. (redis.call('HGET', k, 'gen') or '0')
249
- .. '|' .. (redis.call('HGET', k, 'sessionId') or '')
250
- end
251
- if #lines >= pageSize or next == '0' then break end
244
+ for _, k in ipairs(res[2]) do
245
+ local hk = prefix .. k
246
+ lines[#lines + 1] = k
247
+ .. '|' .. (redis.call('HGET', hk, 'state') or 'none')
248
+ .. '|' .. (redis.call('HGET', hk, 'inFlight') or '0')
249
+ .. '|' .. (redis.call('HGET', hk, 'gen') or '0')
250
+ .. '|' .. (redis.call('HGET', hk, 'sessionId') or '')
252
251
  end
253
252
  local fields = redis.call('HGETALL', meta)
254
253
  local m = {}
@@ -256,29 +255,29 @@ for i = 1, #fields, 2 do
256
255
  m[#m + 1] = fields[i] .. '=' .. (fields[i + 1] or '')
257
256
  end
258
257
  return next .. '#' .. table.concat(m, ',') .. '#' .. table.concat(lines, '\\n')
259
- `,et=`
258
+ `,lt=`
260
259
  local fields = redis.call('HGETALL', KEYS[1])
261
260
  local m = {}
262
261
  for i = 1, #fields, 2 do
263
262
  m[#m + 1] = fields[i] .. '=' .. (fields[i + 1] or '')
264
263
  end
265
264
  return table.concat(m, ',')
266
- `,tt=`
265
+ `,ut=`
267
266
  local out = {}
268
267
  for i = 1, #ARGV do
269
268
  out[#out + 1] = (redis.call('HGET', ARGV[i], 'state') or 'none')
270
269
  .. '|' .. (redis.call('HGET', ARGV[i], 'inFlight') or '0')
271
270
  end
272
271
  return table.concat(out, '\\n')
273
- `,nt=`
272
+ `,dt=`
274
273
  local gen = redis.call('GET', KEYS[1])
275
274
  if not gen then return '0' end
276
275
  return gen
277
- `,rt=`
276
+ `,ct=`
278
277
  local state = redis.call('HGET', KEYS[1], 'state')
279
278
  if not state then return 'none||' end
280
279
  return state .. '|' .. (redis.call('HGET', KEYS[1], 'sessionId') or '') .. '|' .. (redis.call('HGET', KEYS[1], 'lastReason') or '')
281
- `,st=`
280
+ `,pt=`
282
281
  local slot = KEYS[1]
283
282
  local key, obsEpoch = ARGV[1], tonumber(ARGV[2])
284
283
  local state = redis.call('HGET', slot, 'state')
@@ -298,23 +297,23 @@ redis.call('HSET', slot,
298
297
  'cacheGen', ARGV[5],
299
298
  'capabilities', ARGV[6])
300
299
  return 'ok'
301
- `;var Y=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},Sn=100,it=s=>{let e={attached:0,queued:0,paused:0,retired:0,ended:0,inflight:0};for(let t of s.split(",")){if(t==="")continue;let[n,r]=t.split("=");n in e&&(e[n]=Number(r))}return e},bn=s=>(s===""?[]:s.split(`
302
- `)).map(e=>{let[t,n,r,i,l]=e.split("|");return{key:t,state:n,inFlight:Number(r),gen:Number(i),sessionId:l}});function F(s){let e=s.split(":"),t=e[e.length-1],n=e[e.length-2];if(n!==void 0&&/^\d+$/.test(n)&&/^\d+$/.test(t))return{base:e.slice(0,-1).join(":"),index:Number(n),gen:Number(t)};if(!/^\d+$/.test(t))throw new Error(`session registry: malformed slot key "${s}" (expected decision:{replica}:{index}[:{gen}])`);return{base:s,index:Number(t),gen:0}}var K=()=>String(Date.now()),re=class{constructor(e,t){this.evalFn=e;this.pool=t}evalFn;pool;keys(e,t=!0,n=!0){let{base:r}=F(e),i=[`sreg:${this.pool}:slot:${e}`];return t&&i.push(`sreg:${this.pool}:gen:${r}`),n&&i.push(`sreg:${this.pool}:retired`),i.push(`sreg:${this.pool}:meta`),i}async run(e,t,n,r,i){let l=await this.evalFn.eval(t,n,r);if(l.startsWith("reject:"))throw new Y(e,l,{pool:this.pool,...i})}mint(e){let{gen:t}=F(e);return this.run("mint",ge,this.keys(e,!1,!0),[e,t,K()],{slotKey:e,gen:t})}mintWith(e,t){let{gen:n}=F(e);return this.run("mint",ge,this.keys(e,!1,!0),[e,n,K(),t.model,t.capabilities??"",t.cacheNs],{slotKey:e,gen:n,cacheNs:t.cacheNs})}attachWithEpoch(e,t,n){let{gen:r}=F(e);return this.run("attach",me,this.keys(e),[e,r,t,K(),n],{slotKey:e,gen:r,sessionId:t,observedEpoch:n})}publish(e,t,n){return this.run("publish",st,this.keys(e,!1,!1),[e,t,n.maxConcurrent,n.queueDepth,n.cacheGen,n.capabilities??""],{slotKey:e,observedEpoch:t})}attach(e,t){let{gen:n}=F(e);return this.run("attach",me,this.keys(e),[e,n,t,K()],{slotKey:e,gen:n,sessionId:t})}detach(e,t){return this.run("detach",Ve,this.keys(e,!1,!1),[e,t,K()],{slotKey:e,reason:t})}rotate(e,t){let{gen:n}=F(t),r=[...this.keys(e),`sreg:${this.pool}:slot:${t}`];return this.run("rotate",Be,r,[e,t,n,K()],{oldKey:e,newKey:t,newGen:n})}end(e){return this.run("end",Ye,this.keys(e,!1,!1),[e,K()],{slotKey:e})}lease(e){return this.run("lease",Je,this.keys(e,!1,!1),[e],{slotKey:e})}release(e){return this.run("release",ze,this.keys(e,!1,!1),[e,K()],{slotKey:e})}configure(e,t){return this.run("config",Xe,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}retune(e,t){return this.run("retune",Qe,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}async tuning(){let e=await this.evalFn.eval(We,[`sreg:${this.pool}:meta`],[]),[t,n,r]=e.split("|");return{max:Number(t),inFlightCap:Number(n),configVersion:Number(r)}}async grant(e,t){let n=this.keys(e,!1,!1),r=await this.evalFn.eval(X,n,[e,t.cap,t.configVersion]);if(r==="reject:cap-moved"){let i=await this.tuning();r=await this.evalFn.eval(X,n,[e,i.inFlightCap,i.configVersion])}if(r==="ok")return{granted:!0};if(r==="reject:cap")return{granted:!1,reason:"cap-full"};if(r==="reject:cap-moved")return{granted:!1,reason:"cap-moved"};throw new Y("grant",r,{pool:this.pool,slotKey:e})}async grantWithEpoch(e,t){let n=this.keys(e,!1,!1),r=await this.evalFn.eval(X,n,[e,t.cap,t.configVersion,t.epoch]);if(r==="reject:cap-moved"){let i=await this.tuning();r=await this.evalFn.eval(X,n,[e,i.inFlightCap,i.configVersion,t.epoch])}if(r==="ok")return{granted:!0};if(r==="reject:cap")return{granted:!1,reason:"cap-full"};if(r==="reject:cap-moved")return{granted:!1,reason:"cap-moved"};if(r==="reject:epoch")return{granted:!1,reason:"epoch-stale"};throw new Y("grant",r,{pool:this.pool,slotKey:e})}async snapshot(){let e=[],t=null,n="0";do{let r=await this.snapshotPage(n,Sn);t===null&&(t=r.counts),e.push(...r.slots),n=r.cursor}while(n!=="0");return{counts:t,slots:e}}async counts(){let e=await this.evalFn.eval(et,[`sreg:${this.pool}:meta`],[]);return it(e)}async snapshotPage(e,t){let n=`sreg:${this.pool}:slot:`,r=await this.evalFn.eval(Ze,[`sreg:${this.pool}:meta`],[n,e,t]),[i,l,p]=r.split("#");return{cursor:i,counts:it(l??""),slots:bn(p??"")}}async readRecords(e){if(e.length===0)return[];let t=`sreg:${this.pool}:slot:`,n=await this.evalFn.eval(tt,[],e.map(r=>t+r));return(n===""?[]:n.split(`
303
- `)).map(r=>{let[i,l]=r.split("|");return{state:i,inFlight:Number(l)}})}async generation(e){let{base:t}=F(e),n=await this.evalFn.eval(nt,[`sreg:${this.pool}:gen:${t}`],[]);return Number(n)}async record(e){let n=(await this.evalFn.eval(rt,[`sreg:${this.pool}:slot:${e}`],[])).split("|"),r=n[0],i=n[1]===""||n[1]===void 0?void 0:n[1],l=n.slice(2).join("|");return{state:r,sessionId:i,lastReason:l===""?void 0:l}}};S();var at=require("bullmq"),lt=require("crypto"),Rn=3e4,En=60,kn=1e3,ut=12e4;function ot(s){let e;try{e=JSON.parse(s)}catch{return null}if(typeof e!="object"||e===null||!("proxy_url"in e))return null;let t=e;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0}}function dt(s){let e=s.now??Date.now,t=new Map,n=new Map,r=new Map,i=new Map,l=new Set,p=d=>{let m=t.get(d);return m||(m=s.queueFor?.(d)??g(d),t.set(d,m)),m},g=d=>{let m=s.redis,T=new at.Queue(d,{prefix:"bull:dispatch",connection:m});return{add:(k,I,x)=>T.add(k,I,x),reassertWaiting:async k=>{let x=(await T.getJobs(["waiting"])).filter(A=>A.data?.session_kind==="lane").sort((A,N)=>A.timestamp-N.timestamp);if(x.length===0)return{found:0};for(let A of x)try{await A.updateData({...A.data,demand_reaffirmed_at_ms:k,...s.mintRuntimeToken?{runtime_token:s.mintRuntimeToken(String(A.data.session_id))}:{}})}catch{}for(let A of x.slice(1))try{await A.remove()}catch{}return{found:x.length}},close:()=>T.close()}},R=async d=>{let m=await s.redis.hgetall(`lanes:${d}`),T=[];for(let[x,A]of Object.entries(m)){let N=ot(A);N&&N.proxy_url===s.docHostUrl&&T.push(x)}if(T.length===0)return[];let k=await s.redis.mget(...T.map(x=>`lane_hosts:${x}`)),I=[];return T.forEach((x,A)=>{let N=k[A];N&&I.push({laneId:x,host:N})}),I},_=async(d,m)=>{let T=n.get(d)??0,k=e();if(k-T<Rn)return;n.set(d,k);let I=p(d);if((await I.reassertWaiting(e()).catch(N=>{throw n.delete(d),N})).found>0){i.set(m??"",(i.get(m??"")??0)+1),s.onEvent?.({kind:"lane_demand_reaffirmed",pool:d,model:m});return}let A=`lane-${(0,lt.randomUUID)().replaceAll("-","")}`;await I.add("session",{session_id:A,logical_id:A,incarnation:k,session_kind:"lane",lane_id:A,session_server_url:s.docHostUrl,proxy_url:s.docHostUrl,session_idle_timeout_seconds:En,thread_key:"lane",demand_reaffirmed_at_ms:e(),...s.mintRuntimeToken?{runtime_token:s.mintRuntimeToken(A)}:{}},{jobId:`${A}#${k}`,attempts:3}),r.set(m??"",(r.get(m??"")??0)+1),s.onEvent?.({kind:"lane_demand_enqueued",pool:d,model:m})};return{async pick({pool:d,model:m,holdMs:T=0}){l.add(d);let k=async()=>{try{await _(d,m)}catch(N){n.delete(d),s.onEvent?.({kind:"lane_demand_failed",pool:d,model:m,reason:N instanceof Error?N.message:String(N)})}},I=async()=>{try{return await R(d)}catch{return[]}},x=await I();if(x.length>0)return x;await k();let A=e()+T;for(;e()<A;){if(await new Promise(N=>setTimeout(N,kn)),x=await I(),x.length>0)return x;await k()}return[]},async status(){let d=[...l].sort();return Promise.all(d.map(async m=>{let T=[];try{let k=await s.redis.hgetall(`lanes:${m}`),I=Object.keys(k),x=I.length===0?[]:await s.redis.mget(...I.map(N=>`lane_hosts:${N}`)),A=e();T=I.map((N,de)=>{let ee=k[N],B=ee===void 0?null:ot(ee);return{laneId:N,occupantId:B?.occupant_id??"",capacity:B?.capacity??0,heartbeatAgeMs:B===null?null:A-B.heartbeat_ms,advertisedHere:B?.proxy_url===s.docHostUrl,hosted:!!x[de]}})}catch{}return{pool:m,lanes:T,lastDemandAt:n.get(m)??null}}))},demandCounters(){return[...new Set([...r.keys(),...i.keys()])].sort().map(m=>({model:m,enqueued:r.get(m)??0,reaffirmed:i.get(m)??0}))},async close(){await Promise.all([...t.values()].map(d=>d.close().catch(()=>{}))),t.clear()}}}S();var Z=require("crypto");var pt="runtime:lease",Pn="lane:join";var Tn=120,ft=1440*60;function ct(s){return Buffer.from(s).toString("base64url")}function In(s,e,t){let n=ct(JSON.stringify(s)),r=ct(JSON.stringify(e)),i=(0,Z.createHmac)("sha256",t).update(`${n}.${r}`).digest("base64url");return`${n}.${r}.${i}`}function ht(s,e,t,n=Tn,r=Pn){return xn(s,t,n,r,e)}function xn(s,e,t,n,r){let i=Math.floor(Date.now()/1e3);return In({alg:"HS256",typ:"JWT"},{session_id:s,aud:"sfu",sub:s,scope:n,...r?{tenant:r}:{},iat:i,exp:i+t,jti:(0,Z.randomUUID)()},e)}S();var se=class{records=new Map;add(e){return this.records.set(e.request_id,{request:e,sessionId:"",attempt:1,dispatched:!1}),Promise.resolve()}dispatched(e,t,n){let r=this.records.get(e);return r&&(r.sessionId=t,r.attempt=n,r.dispatched=!0),Promise.resolve()}requeue(e,t){let n=this.records.get(e);return n&&(n.dispatched=!1,n.sessionId="",n.attempt=t),Promise.resolve()}finish(e){return this.records.delete(e),Promise.resolve()}queued(e,t){return Promise.resolve([...this.records.values()].filter(n=>!n.dispatched&&n.request.region===e&&n.request.model===t).map(n=>n.request))}inflight(){return Promise.resolve([...this.records.values()].filter(e=>e.dispatched).map(e=>({request:e.request,sessionId:e.sessionId,attempt:e.attempt})))}};S();S();var ae=s=>`${s.systemPrompt??""}\0${s.firstMessage??""}`;function ye(s){return s.promptCacheKey!==void 0&&s.promptCacheKey!==""?`k:${s.promptCacheKey}`:s.sessionHeader!==void 0&&s.sessionHeader!==""?`h:${s.sessionHeader}`:`p:${An(ae(s))}`}function An(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 gt=512,On=4096,ie=8,oe=class{root={children:new Map,sessions:new Map};nodes=1;insert(e,t,n){let r=e.slice(0,gt),i=this.root;for(let l=0;l<r.length;l+=ie){let p=r.slice(l,l+ie),g=i.children.get(p);if(!g){if(this.nodes>=On)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,gt),r=this.root,i=null,l=0,p=0;for(;;){let g=null,R=-1;for(let[m,T]of r.sessions)t.has(m)&&(T>R||T===R&&g!==null&&m<g)&&(g=m,R=T);if(g!==null&&(i={sessionId:g,depth:l}),p>=n.length)break;let _=n.slice(p,p+ie),d=r.children.get(_);if(!d)break;r=d,l+=_.length,p+=ie}return i}forget(e){let t=n=>{n.sessions.delete(e);for(let r of n.children.values())t(r)};t(this.root)}size(){return this.nodes}};function mt(s,e,t,n){if(e.length===0)return null;let r=new Map(e.map(_=>[_.sessionId,_])),i=_=>{let d=r.get(_);return d!==void 0&&d.backlog<n.backlogThreshold},l=new Set(r.keys()),p=n.sticky.get(ye(s));if(p!==void 0&&i(p))return{sessionId:p,reason:"sticky"};let g=t.match(ae(s),l);if(g!==null&&i(g.sessionId))return{sessionId:g.sessionId,reason:"prefix"};let R=null;for(let _ of e)(R===null||_.backlog<R.backlog||_.backlog===R.backlog&&_.sessionId<R.sessionId)&&(R=_);return R===null?null:{sessionId:R.sessionId,reason:"load"}}S();var yt="llm",ve="requests",Nn="llm-resp",we=(s,e,t,n=0)=>`decision:pooler-${s}-${e}`.replaceAll(":","-")+`:${t}`+(n>0?`:${n}`:""),_e=s=>{let{base:e,gen:t}=F(s);return`${e}:${t+1}`},vt=s=>`${Nn}:${s}`,wt="free_slots",Se="inflight",be="live_seen",V=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 St=new Set(["registry_error","failed","mint_failed","scaled_down","live_mark_failed","never_live_evicted","never_live_end_failed"]),Mn=6e4,$n=33e4,Cn=2,Ln=8,Un=5e3,qn=1e4,Dn=6e4,Gn=5e3,jn=36e5,Hn={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"},le=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??Mn,this.silenceDeadlineMs=e.silenceDeadlineMs??$n,this.maxAttempts=e.maxAttempts??Cn,this.backlogThreshold=e.backlogThreshold??Ln,this.mint=e.mint,this.limits=e.limits??[],this.scaleUpWaitMs=e.scaleUpWaitMs??Un,this.mintCooldownMs=e.mintCooldownMs??qn,this.sessionIdleTtlMs=e.sessionIdleTtlMs??Dn,this.idleSweepMs=e.idleSweepMs??Gn,this.neverLiveEvictAfterMs=e.neverLiveEvictAfterMs??jn,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 H(`the pool entry for ${t.sessionId} has no usable compute binding (phase "${n}") \u2014 the sweep's servability reconcile evicts it; the named session itself stays parked and attachable`))}}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"||!Hn[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(_=>{this.onEvent({kind:"never_live_end_failed",pool:this.key(e.region,e.model),sessionId:r.sessionId,reason:_ instanceof Error?_.message:String(_)})})}}limitsFor(e){return this.limits.find(t=>t.region===e.region&&t.model===e.model)??null}queuePressure(e){if(e.queue.length===0)return!1;let t=this.now();return e.queue.some(n=>t-n.queuedAt>=this.scaleUpWaitMs)}tryMint(e,t){if(this.mint===void 0||this.closed||e.minting)return;let n=this.limitsFor(e);if(n===null||e.sessions.length>=n.max)return;let r=this.now();r-e.lastMintAt<this.mintCooldownMs||(e.lastMintAt=r,e.minting=!0,this.mintOnce(e,t).finally(()=>{e.minting=!1}))}async mintOnce(e,t){if(this.mint===void 0)return!1;let n=e.mintSeq++,r;try{r=await this.claimSlot(e.region,e.model,n)}catch(i){if(t==="boot_floor")throw i;return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:i instanceof Error?i.message:String(i)}),!1}try{let i=await this.mint(e.region,e.model,r);return this.closed?(await i.end().catch(()=>{}),!1):(this.addSession(e.region,e.model,i,r),this.onEvent({kind:"minted",pool:this.key(e.region,e.model),sessionId:i.sessionId,reason:t}),!0)}catch(i){return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:i instanceof Error?i.message:String(i)}),!1}}async warm(){for(let e of this.limits){let t=this.poolOf(e.region,e.model);t.minting=!0;try{for(;t.sessions.length<e.min&&await this.mintOnce(t,"boot_floor"););}finally{t.minting=!1}}}scaleDownOldestIdle(e,t){let n=this.now();for(let r of e.sessions){if(r.gone()!==null||[...e.records.values()].some(R=>R.session===r&&R.phase==="dispatched")||n-(e.lastActivity.get(r)??n)<this.sessionIdleTtlMs)continue;let p=e.sessions.indexOf(r);if(p===-1)continue;e.sessions.splice(p,1),this.detachSignals(e,r),e.radix.forget(r.sessionId),e.lastActivity.delete(r),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(R=>{this.onEvent({kind:"scaled_down_end_failed",pool:this.key(e.region,e.model),sessionId:r.sessionId,reason:R instanceof Error?R.message:String(R)})});return}}static poolKey(e,t){return`${e}:${t}`}async claimSlot(e,t,n){let r=we(e,t,n);if(this.registry===null)return r;for(let i=0;;i++){let l=await this.registry.generation(r),p=we(e,t,n,l),{state:g,sessionId:R,lastReason:_}=await this.registry.record(p);if(g==="none"||g==="paused"&&R===void 0&&_===void 0)try{return await this.registry.mint(p),p}catch(d){this.rethrowUnlessClaimRace(d,i);continue}else{let d=_e(p);try{await this.registry.rotate(p,d),await this.registry.mint(d)}catch(m){this.rethrowUnlessClaimRace(m,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 Y&&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:null,queuedAt:this.now()}),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:n.request.request_id,sessionId:n.sessionId})}}for(let n of await this.journal.queued(e.region,e.model))await this.journal.finish(n.request_id),this.onEvent({kind:"reconciled_caller_gone",pool:t,requestId:n.request_id});for(let n of e.sessions){let r=n.snapshot();for(let[i,l]of Object.entries(r.inflight)){if(l.status==="done"||l.status==="error"||e.records.has(i))continue;let p={request:{request_id:i,region:e.region,model:e.model,affinity:{},payload:{},streaming:!1,enqueuedAt:0},sink:null,attempt:l.attempt,tried:new Set([n.sessionId]),session:n,phase:"dispatched",streamed:!1,deadlineAt:Number.POSITIVE_INFINITY,queueTimer:null,silenceTimer:null,queuedAt:this.now()};e.records.set(i,p),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:i,sessionId:n.sessionId})}}this.pump(e)}async submit(e,t){if(this.closed){t.head(),t.fail({status:503,code:"draining",message:"pooler is shutting down",retryAfterSeconds:5});return}let n=this.poolOf(e.region,e.model);await this.start(n);let r={request:e,sink:t,attempt:1,tried:new Set,session:null,phase:"queued",streamed:!1,deadlineAt:this.now()+this.queueDeadlineMs,queueTimer:null,silenceTimer:null,queuedAt:this.now()};n.records.set(e.request_id,r),n.queue.push(r),await this.journal.add(e),t.head(),this.armQueueTimer(n,r),this.onEvent({kind:"enqueued",pool:this.key(e.region,e.model),requestId:e.request_id}),this.pump(n),r.phase!=="finished"&&await new Promise(i=>{r.settle=i})}abandon(){this.closed=!0,this.sweepTimer!==null&&(clearInterval(this.sweepTimer),this.sweepTimer=null);for(let e of this.pools.values()){for(let t of e.records.values())this.clearTimers(t);for(let t of e.offs.values())for(let n of t)n();e.offs.clear(),e.sessions.length=0,e.queue.length=0,e.records.clear(),e.lastActivity.clear()}this.pools.clear()}async close(){this.closed=!0,this.sweepTimer!==null&&(clearInterval(this.sweepTimer),this.sweepTimer=null);for(let e of this.pools.values()){for(let n of e.records.values())this.clearTimers(n),n.phase!=="finished"&&this.settle(n,{status:503,code:"draining",message:"pooler is shutting down",retryAfterSeconds:5});for(let n of e.offs.values())for(let r of n)r();e.offs.clear(),e.lastActivity.clear(),e.bornAt.clear();for(let n of e.slotKeys.values())this.registryCall("rotate",n,()=>this.registry?.rotate(n,_e(n)));e.slotKeys.clear();let t=e.sessions.splice(0);await Promise.allSettled(t.map(n=>n.end()))}this.pools.clear()}poolOf(e,t){let n=s.poolKey(e,t),r=this.pools.get(n);return r||(r={region:e,model:t,sessions:[],records:new Map,queue:[],sticky:new Map,radix:new oe,offs:new Map,slotKeys:new Map,needsReconcile:!0,lastMintAt:0,minting:!1,mintSeq:0,lastActivity:new Map,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=mt(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=ye(n.request.affinity);e.sticky.set(l,t.sessionId),e.radix.insert(ae(n.request.affinity),t.sessionId,this.now()),this.onEvent({kind:"dispatched",pool:this.key(e.region,e.model),requestId:n.request.request_id,sessionId:t.sessionId,attempt:n.attempt}),this.armSilenceTimer(e,n);let p=e.slotKeys.get(t.sessionId);p!==void 0&&this.registryCall("lease",p,()=>this.registry?.lease(p)),this.consume(e,n,i)})()}async consume(e,t,n){if(t.session!==null)try{for await(let r of n){if(t.phase==="finished")return;this.armSilenceTimer(e,t),t.streamed=!0;let i=t.sink;if(i!==null&&(await i.chunk(r),r.t==="response"||r.t==="error"||r.t==="end")){await this.finish(e,t);return}}this.lost(e,t,new V(t.request.request_id,"iterator ended without a terminal chunk"))}catch(r){this.lost(e,t,r)}}lost(e,t,n){if(t.phase==="finished")return;this.clearTimers(t);let r=n instanceof Error?n.message:String(n);this.onEvent({kind:"lost",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt,reason:r}),n instanceof H&&t.session!==null&&this.evict(e,t.session,n);let i=e.sessions.some(l=>this.servable(l)&&!t.tried.has(l.sessionId));if(!t.streamed&&t.attempt<this.maxAttempts&&i){t.attempt+=1,t.phase="queued",t.session=null,t.deadlineAt=this.now()+this.queueDeadlineMs,t.queuedAt=this.now(),e.queue.unshift(t),this.journal.requeue(t.request.request_id,t.attempt).catch(()=>{}),this.armQueueTimer(e,t),this.onEvent({kind:"retry",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt}),this.pump(e);return}this.settle(t,{status:502,code:t.streamed?"upstream_stream_lost":"upstream_error",message:t.streamed?"the upstream reply stream was lost after the response began":"the upstream reply stream was lost before the response began",retryAfterSeconds:1})}async finish(e,t){this.clearTimers(t),t.phase="finished",t.session!==null&&e.lastActivity.set(t.session,this.now()),this.releaseSlot(e,t,"release"),await this.journal.finish(t.request.request_id),t.session!==null&&t.session.clearRequest(t.request.request_id);let n=t.sink;n!==null&&n.done(),this.release(e,t),this.onEvent({kind:"finished",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt}),this.settlePromise(t)}settle(e,t){this.clearTimers(e);let n=e.session===null?void 0:this.poolOf(e.request.region,e.request.model).slotKeys.get(e.session.sessionId);n!==void 0&&this.registryCall("release",n,()=>this.registry?.release(n)),e.phase="finished",e.session!==null&&this.poolOf(e.request.region,e.request.model).lastActivity.set(e.session,this.now()),this.journal.finish(e.request.request_id).catch(()=>{}),e.session!==null&&e.session.clearRequest(e.request.request_id);let r=e.sink;r!==null&&r.fail(t),this.onEvent({kind:"failed",requestId:e.request.request_id,reason:t.code}),this.settlePromise(e)}settlePromise(e){let t=e.settle;e.settle=void 0,t?.()}release(e,t){e.records.get(t.request.request_id)===t&&e.records.delete(t.request.request_id)}releaseSlot(e,t,n){if(t.session===null)return;let r=e.slotKeys.get(t.session.sessionId);r!==void 0&&this.registryCall(n,r,()=>n==="release"?this.registry?.release(r):this.registry?.detach(r,"session evicted"))}detachSignals(e,t){let n=e.offs.get(t);if(n!==void 0){e.offs.delete(t);for(let r of n)r()}}evict(e,t,n){let r=e.sessions.indexOf(t);if(r===-1)return;e.sessions.splice(r,1),this.detachSignals(e,t),e.lastActivity.delete(t),e.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){t.silenceTimer===null&&(t.silenceTimer=setTimeout(()=>{t.silenceTimer=null,t.phase==="dispatched"&&this.lost(e,t,new V(t.request.request_id,`silent past ${this.silenceDeadlineMs}ms`))},this.silenceDeadlineMs),t.silenceTimer.unref?.())}clearTimer(e,t){let n=t==="queue"?e.queueTimer:e.silenceTimer;n!==null&&(clearTimeout(n),t==="queue"?e.queueTimer=null:e.silenceTimer=null)}clearTimers(e){this.clearTimer(e,"queue"),this.clearTimer(e,"silence")}stats(){return{pools:[...this.pools.entries()].map(([e,t])=>({pool:e,queued:t.queue.length,inflight:[...t.records.values()].filter(n=>n.phase==="dispatched").length,sessions:t.sessions.length}))}}};S();var Fn="0.0.0.0",bt="serve";var z=(s,e)=>{let t=s[e];if(typeof t!="string"||t==="")throw new Error(`the pooler requires ${e} (external input) \u2014 refusing to start half-configured`);return t},Kn=(s,e)=>{if(s===null||typeof s!="object")throw new Error(`URUN_POOLER_TARGETS[${e}] must be an object`);let t=s,n=p=>{let g=t[p];if(typeof g!="string"||g==="")throw new Error(`URUN_POOLER_TARGETS[${e}].${p} is required`);return g},r=p=>{let g=t[p];if(typeof g!="number"||!Number.isInteger(g))throw new Error(`URUN_POOLER_TARGETS[${e}].${p} must be an integer`);return g},i,l;if(t.sessions!==void 0){let p=t.sessions;if(typeof p!="number"||!Number.isInteger(p)||p<1)throw new Error(`URUN_POOLER_TARGETS[${e}].sessions must be an integer >= 1`);if(t.min!==void 0||t.max!==void 0)throw new Error(`URUN_POOLER_TARGETS[${e}]: give either sessions or {min, max}, never both`);i=p,l=p}else{if(i=r("min"),l=r("max"),i<0)throw new Error(`URUN_POOLER_TARGETS[${e}].min must be >= 0 (0 scales to zero)`);if(l<1)throw new Error(`URUN_POOLER_TARGETS[${e}].max must be >= 1`);if(i>l)throw new Error(`URUN_POOLER_TARGETS[${e}]: min (${String(i)}) must not exceed max (${String(l)})`)}return{region:n("region"),model:n("model"),app:n("app"),fn:typeof t.fn=="string"&&t.fn!==""?t.fn:void 0,min:i,max:l,sharedApp:t.sharedApp===!0}};function Rt(s){let e=s.PORT,t=e===void 0||e===""?8080:Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw new Error(`PORT must be a valid port number, got ${String(e)}`);let n=z(s,"URUN_BASE_URL"),r=z(s,"URUN_POOLER_TARGETS"),i;try{i=JSON.parse(r)}catch(l){throw new Error(`URUN_POOLER_TARGETS is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!Array.isArray(i)||i.length===0)throw new Error("URUN_POOLER_TARGETS must be a non-empty JSON array");return{port:t,bindHost:Fn,token:z(s,"URUN_POOLER_TOKEN"),baseUrl:n,apiUrl:s.URUN_API_URL!==void 0&&s.URUN_API_URL!==""?s.URUN_API_URL:`${n}/v1`,orgId:z(s,"URUN_ORG_ID"),apiKey:z(s,"URUN_API_KEY"),valkeyUrl:z(s,"URUN_VALKEY_URL"),laneDocHostUrl:(s.URUN_LANE_DOC_HOST_URL??"").trim()||void 0,laneRuntimeKey:(s.URUN_LANE_RUNTIME_KEY??"").trim()||void 0,targets:i.map(Kn)}}S();var Pt=require("http");var Vn="/pooler/v1/inference",Bn="/readyz",Yn="/metrics",Jn="/pooler/v1/lanes/pick",Wn="/pooler/v1/lanes/status",zn=1e4,Et=16*1024*1024;function q(s,e,t,n,r){s.headersSent||(r!==void 0&&s.setHeader("retry-after",String(r)),s.writeHead(e,{"content-type":"application/json"}),s.end(JSON.stringify({error:{message:t,type:"pooler_error",code:n}})))}function Qn(s){if(s===null||typeof s!="object")return{reason:"body must be a JSON object"};let e=s;if(typeof e.region!="string"||e.region==="")return{reason:"region is required"};if(typeof e.model!="string"||e.model==="")return{reason:"model is required"};if(typeof e.request_id!="string"||e.request_id==="")return{reason:"request_id is required"};if(e.payload===null||typeof e.payload!="object")return{reason:"payload must be an object"};let t=e.affinity??{};if(t===null||typeof t!="object")return{reason:"affinity must be an object"};let n=t,r=i=>typeof i=="string"&&i!==""?i:void 0;return{value:{streaming:e.streaming===!0,request:{request_id:e.request_id,region:e.region,model:e.model,payload:e.payload,affinity:{promptCacheKey:r(n.promptCacheKey??e.prompt_cache_key),sessionHeader:r(n.sessionHeader??e.session_header),systemPrompt:r(n.systemPrompt),firstMessage:r(n.firstMessage)},streaming:e.streaming===!0,enqueuedAt:Date.now()}}}}var Re=class{constructor(e,t,n){this.res=e;this.streaming=t;this.keepaliveMs=n}res;streaming;keepaliveMs;keepalive=null;terminal=null;head(){this.streaming&&!this.res.headersSent&&(this.res.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive"}),this.keepalive=setInterval(()=>{this.res.writableEnded||this.res.write(`: keepalive
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},En=100,ft=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},kn=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()),de=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",Re,[...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",Re,[...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",Ee,this.keys(e),[e,r,t,Z(),n],{slotKey:e,gen:r,sessionId:t,observedEpoch:n})}publish(e,t,n){return this.run("publish",pt,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",Ee,this.keys(e),[e,n,t,Z()],{slotKey:e,gen:n,sessionId:t})}detach(e,t){return this.run("detach",Ze,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",et,r,[e,t,n,Z()],{oldKey:e,newKey:t,newGen:n})}end(e){return this.run("end",tt,this.keys(e,!1,!1),[e,Z()],{slotKey:e})}lease(e){return this.run("lease",nt,this.keys(e,!1,!1),[e],{slotKey:e})}release(e){return this.run("release",st,this.keys(e,!1,!1),[e,Z()],{slotKey:e})}configure(e,t){return this.run("config",ot,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}retune(e,t){return this.run("retune",it,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}async tuning(){let e=await this.evalFn.eval(rt,[`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(oe,n,[e,t.cap,t.configVersion]);if(r==="reject:cap-moved"){let i=await this.tuning();r=await this.evalFn.eval(oe,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(oe,n,[e,t.cap,t.configVersion,t.epoch]);if(r==="reject:cap-moved"){let i=await this.tuning();r=await this.evalFn.eval(oe,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,En);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(lt,[`sreg:${this.pool}:meta`],[]);return ft(e)}async snapshotPage(e,t){let n=`sreg:${this.pool}:slot:`,r=await this.evalFn.eval(at,[this.idxKey(),`sreg:${this.pool}:meta`],[n,e,t]),[i,l,p]=r.split("#");return{cursor:i,counts:ft(l??""),slots:kn(p??"")}}async readRecords(e){if(e.length===0)return[];let t=`sreg:${this.pool}:slot:`,n=await this.evalFn.eval(ut,[],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(dt,[`sreg:${this.pool}:gen:${t}`],[]);return Number(n)}async record(e){let n=(await this.evalFn.eval(ct,[`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 yt=require("@urun-sh/core"),wt=require("bullmq"),vt=require("crypto"),ht=3e4;var Pn=1e3,_t=12e4;function gt(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 ce=class extends Error{};async function mt(s,e){let t;try{await Promise.race([s,new Promise(n=>{t=setTimeout(n,Math.max(0,e))})])}finally{clearTimeout(t)}}function St(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,m=new Map,v=new Set,h=S=>{let k=t.get(S);return k||(k=s.queueFor?.(S)??d(S),t.set(S,k)),k},d=S=>{let k=s.redis,N=new wt.Queue(S,{prefix:"bull:dispatch",connection:k});return{reassertWaiting:async O=>{let A=(await N.getJobs(["waiting"])).filter(x=>x.data?.session_kind==="lane").sort((x,G)=>x.timestamp-G.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:()=>N.close()}},R=async S=>{let k=await s.redis.hgetall(`lanes:${S}`),N=[],O=new Map;for(let[x,G]of Object.entries(k)){let D=gt(G);D&&D.proxy_url===s.docHostUrl&&(N.push(x),O.set(x,D.region))}if(N.length===0)return[];let T=await s.redis.mget(...N.map(x=>`lane_hosts:${x}`)),A=[];return N.forEach((x,G)=>{let D=T[G];D&&A.push({laneId:x,host:D,region:O.get(x)})}),A},$=async(S,k,N,O,T)=>{let A=N,x=O,G=T;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,G=X.sharedApp??G;else{let we=r.get(S)??0;if(e()-we<ht)return;throw r.set(S,e()),new ce("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 D=n.get(S)??0,V=e();if(V-D<ht)return;if(n.set(S,V),(await h(S).reassertWaiting(e()).catch(X=>{throw n.delete(S),X})).found>0){l.set(k??"",(l.get(k??"")??0)+1),s.onEvent?.({kind:"lane_demand_reaffirmed",pool:S,model:k});return}let Q=`lane-${(0,vt.randomUUID)().replaceAll("-","")}`,ae=await s.admission.createLaneSession({pool:S,app:A,fn:x,...G?{sharedApp:!0}:{},laneId:Q,laneHostUrl:s.docHostUrl});if(ae.sessionId!==Q)throw new Error(`session-api lane admission returned session_id "${ae.sessionId}" for requested logical_id "${Q}" \u2014 refusing to fork the lane identity`);i.set(k??"",(i.get(k??"")??0)+1),m.delete(S),s.onEvent?.({kind:"lane_demand_enqueued",pool:S,model:k})};return{async pick({pool:S,app:k,fn:N,sharedApp:O,model:T,holdMs:A=0}){v.add(S);let x=async()=>{try{await $(S,T,k,N,O)}catch(F){let z=F instanceof Error?F.message:String(F),Q=F instanceof ce?"identity":"admission";p.set(Q,(p.get(Q)??0)+1),m.set(S,z),s.onEvent?.({kind:"lane_demand_failed",pool:S,model:T,reason:z})}},G=async()=>{try{return await R(S)}catch{return[]}},D=await G();if(D.length>0){let F=s.laneMinFor?.(S)??0;return F>D.length&&(async()=>{for(let z=D.length;z<F;z++)await x()})(),D}let V=e()+A;for(await mt(x(),A);e()<V;){if(await new Promise(F=>setTimeout(F,Pn)),D=await G(),D.length>0)return D;await mt(x(),V-e())}return[]},async status(){let S=[...v].sort();return Promise.all(S.map(async k=>{let N=[];try{let O=await s.redis.hgetall(`lanes:${k}`),T=Object.keys(O),A=T.length===0?[]:await s.redis.mget(...T.map(G=>`lane_hosts:${G}`)),x=e();N=T.map((G,D)=>{let V=O[G],F=V===void 0?null:gt(V);return{laneId:G,occupantId:F?.occupant_id??"",capacity:F?.capacity??0,heartbeatAgeMs:F===null?null:x-F.heartbeat_ms,advertisedHere:F?.proxy_url===s.docHostUrl,hosted:!!A[D]}})}catch{}return{pool:k,lanes:N,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(([S],[k])=>S.localeCompare(k)).map(([S,k])=>({reason:S,count:k}))},demandFailure(S){return m.get(S)??null},async close(){await Promise.all([...t.values()].map(S=>S.close().catch(()=>{}))),t.clear()}}}var Tn=4e3,In=5e3;function xn(s){return(e,t)=>s(e,{...t,signal:AbortSignal.timeout(Tn)})}function bt(s){return{createLaneSession:async({pool:e,app:t,fn:n,sharedApp:r,laneId:i,laneHostUrl:l})=>{let p=await(0,yt.createClientToken)(s.apiKey,{baseUrl:s.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${n}`],bindPrincipal:!0,...r?{sharedApp:!0}:{},fetch:xn(s.fetch??globalThis.fetch)}),m=s.fetch??globalThis.fetch,v;try{v=await m(`${s.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(In),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(R){throw new Error(`session-api lane admission for ${i} (app ${t}/${n}) failed: ${R instanceof Error?R.message:String(R)}`)}let h={};try{h=await v.json()}catch{}let d=h.session_id;if(v.status!==200||h.status!=="allocated"||typeof d!="string"){let R=typeof h.message=="string"?h.message:`HTTP ${v.status}`;throw new Error(`session-api lane admission refused for ${i} (app ${t}/${n}): ${R}`)}return{sessionId:d}}}}b();var pe=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 ge=s=>`${s.systemPrompt??""}\0${s.firstMessage??""}`;function ke(s){return s.promptCacheKey!==void 0&&s.promptCacheKey!==""?`k:${s.promptCacheKey}`:s.sessionHeader!==void 0&&s.sessionHeader!==""?`h:${s.sessionHeader}`:`p:${An(ge(s))}`}function An(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 Rt=512,On=4096,fe=8,he=class{root={children:new Map,sessions:new Map};nodes=1;insert(e,t,n){let r=e.slice(0,Rt),i=this.root;for(let l=0;l<r.length;l+=fe){let p=r.slice(l,l+fe),m=i.children.get(p);if(!m){if(this.nodes>=On)return;m={children:new Map,sessions:new Map},i.children.set(p,m),this.nodes+=1}m.sessions.set(t,n),i=m}}match(e,t){let n=e.slice(0,Rt),r=this.root,i=null,l=0,p=0;for(;;){let m=null,v=-1;for(let[R,$]of r.sessions)t.has(R)&&($>v||$===v&&m!==null&&R<m)&&(m=R,v=$);if(m!==null&&(i={sessionId:m,depth:l}),p>=n.length)break;let h=n.slice(p,p+fe),d=r.children.get(h);if(!d)break;r=d,l+=h.length,p+=fe}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 Et(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(ke(s));if(p!==void 0&&i(p))return{sessionId:p,reason:"sticky"};let m=t.match(ge(s),l);if(m!==null&&i(m.sessionId))return{sessionId:m.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 kt="llm",Pt="requests",Mn="llm-resp",Pe=(s,e,t,n=0)=>`decision:pooler-${s}-${e}`.replaceAll(":","-")+`:${t}`+(n>0?`:${n}`:""),Te=s=>{let{base:e,gen:t}=W(s);return`${e}:${t+1}`},Tt=s=>`${Mn}:${s}`,It="free_slots",Ie="inflight",xe="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 At=new Set(["registry_error","failed","mint_failed","scaled_down","live_mark_failed","never_live_evicted","never_live_end_failed"]),Nn=6e4,Cn=33e4,$n=2,Ln=8,Un=5e3,qn=1e4,Dn=6e4,Gn=5e3,jn=36e5,Fn={provisioning:!0,waiting_for_capacity:!0,connecting:!0},xt={idle:"bound",queued:"bound",unavailable:"bound",provisioning:"bound",waiting_for_capacity:"bound",connecting:"bound",live:"bound",degraded:"bound",paused:"unbound",error:"unbound",unknown:"unbound"},me=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??Nn,this.silenceDeadlineMs=e.silenceDeadlineMs??Cn,this.maxAttempts=e.maxAttempts??$n,this.backlogThreshold=e.backlogThreshold??Ln,this.mint=e.mint,this.limits=e.limits??[],this.scaleUpWaitMs=e.scaleUpWaitMs??Un,this.mintCooldownMs=e.mintCooldownMs??qn,this.sessionIdleTtlMs=e.sessionIdleTtlMs??Dn,this.idleSweepMs=e.idleSweepMs??Gn,this.neverLiveEvictAfterMs=e.neverLiveEvictAfterMs??jn,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:xt[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(xt[i]!=="bound"||!Fn[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 m=e.slotKeys.get(r.sessionId);m!==void 0&&(e.slotKeys.delete(r.sessionId),this.registryCall("end",m,()=>this.registry?.end(m))),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 m=e.slotKeys.get(r.sessionId);m!==void 0&&(e.slotKeys.delete(r.sessionId),this.registryCall("end",m,()=>this.registry?.end(m))),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=Pe(e,t,n);if(this.registry===null)return r;for(let i=0;;i++){let l=await this.registry.generation(r),p=Pe(e,t,n,l),{state:m,sessionId:v,lastReason:h}=await this.registry.record(p);if(m==="none"||m==="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=Te(p);try{await this.registry.rotate(p,d),await this.registry.mint(d)}catch(R){this.rethrowUnlessClaimRace(R,i);continue}return this.onEvent({kind:"slot_rotated",pool:this.key(e,t),slotKey:p,successor:d,reason:m==="paused"?"boot claim over an evicted slot's dead session":`boot claim over a previous pod's ${m} 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,Te(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 he,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=Et(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(m){this.lost(e,n,m);return}await this.journal.dispatched(n.request.request_id,t.sessionId,n.attempt);let l=ke(n.request.affinity);e.sticky.set(l,t.sessionId),e.radix.insert(ge(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 Hn="0.0.0.0",Ot="serve";var se=(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},Kn=(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,m;if((t.lanePool!==void 0||t.laneMin!==void 0)&&(p=n("lanePool"),m=r("laneMin"),m<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:m}:{}}};function Mt(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=se(s,"URUN_BASE_URL"),r=se(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:Hn,token:se(s,"URUN_POOLER_TOKEN"),baseUrl:n,apiUrl:s.URUN_API_URL!==void 0&&s.URUN_API_URL!==""?s.URUN_API_URL:`${n}/v1`,orgId:se(s,"URUN_ORG_ID"),apiKey:se(s,"URUN_API_KEY"),valkeyUrl:se(s,"URUN_VALKEY_URL"),laneDocHostUrl:l,targets:i.map(Kn)}}b();var $t=require("http");var Vn="/pooler/v1/inference",Yn="/readyz",Bn="/metrics",Jn="/pooler/v1/lanes/pick",Wn="/pooler/v1/lanes/status",zn=1e4,Nt=16*1024*1024;function H(s,e,t,n,r){s.headersSent||(r!==void 0&&s.setHeader("retry-after",String(r)),s.writeHead(e,{"content-type":"application/json"}),s.end(JSON.stringify({error:{message:t,type:"pooler_error",code:n}})))}function Qn(s){if(s===null||typeof s!="object")return{reason:"body must be a JSON object"};let e=s;if(typeof e.region!="string"||e.region==="")return{reason:"region is required"};if(typeof e.model!="string"||e.model==="")return{reason:"model is required"};if(typeof e.request_id!="string"||e.request_id==="")return{reason:"request_id is required"};if(e.payload===null||typeof e.payload!="object")return{reason:"payload must be an object"};let t=e.affinity??{};if(t===null||typeof t!="object")return{reason:"affinity must be an object"};let n=t,r=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 Ae=class{constructor(e,t,n){this.res=e;this.streaming=t;this.keepaliveMs=n}res;streaming;keepaliveMs;keepalive=null;terminal=null;head(){this.streaming&&!this.res.headersSent&&(this.res.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive"}),this.keepalive=setInterval(()=>{this.res.writableEnded||this.res.write(`: keepalive
304
303
 
305
304
  `)},this.keepaliveMs),this.keepalive.unref?.())}async chunk(e){if(this.streaming){this.res.headersSent||this.head(),this.res.write(`data: ${JSON.stringify(e)}
306
305
 
307
306
  `);return}e.t!=="delta"&&(this.terminal=e)}done(){if(this.stopKeepalive(),this.streaming){this.res.write(`data: [DONE]
308
307
 
309
- `),this.res.end();return}if(this.terminal!==null&&this.terminal.t==="error"){let t=this.terminal.body,n=t!==null&&typeof t=="object"&&typeof t.message=="string"?String(t.message):"the upstream turn failed";q(this.res,502,n,"upstream_error");return}let e=this.terminal!==null&&this.terminal.t!=="delta"?this.terminal:{t:"response",body:{}};this.res.writeHead(200,{"content-type":"application/json"}),this.res.end(JSON.stringify(e))}fail(e){if(this.stopKeepalive(),!this.streaming||!this.res.headersSent){q(this.res,e.status,e.message,e.code,e.retryAfterSeconds);return}this.res.write(`data: ${JSON.stringify({error:{message:e.message,type:"pooler_error",code:e.code}})}
308
+ `),this.res.end();return}if(this.terminal!==null&&this.terminal.t==="error"){let t=this.terminal.body,n=t!==null&&typeof t=="object"&&typeof t.message=="string"?String(t.message):"the upstream turn failed";H(this.res,502,n,"upstream_error");return}let e=this.terminal!==null&&this.terminal.t!=="delta"?this.terminal:{t:"response",body:{}};this.res.writeHead(200,{"content-type":"application/json"}),this.res.end(JSON.stringify(e))}fail(e){if(this.stopKeepalive(),!this.streaming||!this.res.headersSent){H(this.res,e.status,e.message,e.code,e.retryAfterSeconds);return}this.res.write(`data: ${JSON.stringify({error:{message:e.message,type:"pooler_error",code:e.code}})}
310
309
 
311
310
  `),this.res.write(`data: [DONE]
312
311
 
313
- `),this.res.end()}stopKeepalive(){this.keepalive!==null&&clearInterval(this.keepalive),this.keepalive=null}};function kt(s){return new Promise((e,t)=>{let n=0,r=[];s.on("data",i=>{if(n+=i.length,n>Et){t(new Error(`request body exceeds ${Et} bytes`)),s.destroy();return}r.push(i)}),s.on("end",()=>e(Buffer.concat(r).toString("utf8"))),s.on("error",t)})}function Tt(s){let e=s.keepaliveMs??zn,t=s.log??(()=>{}),n=(0,Pt.createServer)((r,i)=>{(async()=>{let l=new URL(r.url??"/","http://pooler.internal");if(r.method==="GET"&&l.pathname===Bn){i.writeHead(200,{"content-type":"application/json"}),i.end(JSON.stringify({ok:!0,...s.pooler.stats()}));return}if(r.method==="GET"&&l.pathname===Yn){let _=["# TYPE pooler_pool_queued gauge","# TYPE pooler_pool_inflight gauge","# TYPE pooler_pool_sessions gauge","# TYPE pooler_lane_demand_enqueued counter","# TYPE pooler_lane_demand_reaffirmed counter"];for(let d of s.pooler.stats().pools){let m=`pool="${d.pool}"`;_.push(`pooler_pool_queued{${m}} ${d.queued}`),_.push(`pooler_pool_inflight{${m}} ${d.inflight}`),_.push(`pooler_pool_sessions{${m}} ${d.sessions}`)}for(let d of s.lanePlane?.demandCounters()??[]){let m=`model="${d.model.replaceAll('"','\\"')}"`;_.push(`pooler_lane_demand_enqueued{${m}} ${d.enqueued}`),_.push(`pooler_lane_demand_reaffirmed{${m}} ${d.reaffirmed}`)}i.writeHead(200,{"content-type":"text/plain; version=0.0.4"}),i.end(`${_.join(`
312
+ `),this.res.end()}stopKeepalive(){this.keepalive!==null&&clearInterval(this.keepalive),this.keepalive=null}};function Ct(s){return new Promise((e,t)=>{let n=0,r=[];s.on("data",i=>{if(n+=i.length,n>Nt){t(new Error(`request body exceeds ${Nt} bytes`)),s.destroy();return}r.push(i)}),s.on("end",()=>e(Buffer.concat(r).toString("utf8"))),s.on("error",t)})}function Lt(s){let e=s.keepaliveMs??zn,t=s.log??(()=>{}),n=(0,$t.createServer)((r,i)=>{(async()=>{let l=new URL(r.url??"/","http://pooler.internal");if(r.method==="GET"&&l.pathname===Yn){i.writeHead(200,{"content-type":"application/json"}),i.end(JSON.stringify({ok:!0,...s.pooler.stats()}));return}if(r.method==="GET"&&l.pathname===Bn){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 R=`pool="${d.pool}"`;h.push(`pooler_pool_queued{${R}} ${d.queued}`),h.push(`pooler_pool_inflight{${R}} ${d.inflight}`),h.push(`pooler_pool_sessions{${R}} ${d.sessions}`)}for(let d of s.lanePlane?.demandCounters()??[]){let R=`model="${d.model.replaceAll('"','\\"')}"`;h.push(`pooler_lane_demand_enqueued{${R}} ${d.enqueued}`),h.push(`pooler_lane_demand_reaffirmed{${R}} ${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(`
314
313
  `)}
315
- `);return}if(s.lanePlane&&r.method==="GET"&&l.pathname===Wn){if(r.headers.authorization!==`Bearer ${s.token}`){q(i,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}i.writeHead(200,{"content-type":"application/json"}),i.end(JSON.stringify({pools:await s.lanePlane.status()}));return}if(s.lanePlane&&r.method==="POST"&&l.pathname===Jn){if(r.headers.authorization!==`Bearer ${s.token}`){q(i,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let _;try{_=JSON.parse(await kt(r))}catch(k){q(i,400,k instanceof Error?k.message:String(k),"invalid_request");return}let d=_??{};if(typeof d.pool!="string"||d.pool===""){q(i,400,"pool is required","invalid_request");return}let m=d.hold_ms;if(m!==void 0&&(typeof m!="number"||!Number.isInteger(m)||m<0||m>ut)){q(i,400,"hold_ms must be an integer in 0..120000","invalid_request");return}let T=typeof d.model=="string"&&d.model!==""?d.model:void 0;try{let k=await s.lanePlane.pick({pool:d.pool,model:T,holdMs:m??0});if(k.length===0){q(i,503,"no capacity available for this model right now, retry shortly","lane_capacity",2);return}i.writeHead(200,{"content-type":"application/json"}),i.end(JSON.stringify({lanes:k.map(I=>({lane_id:I.laneId,host:I.host}))}))}catch(k){t(`[pooler] lane pick for ${d.pool} failed: ${k instanceof Error?k.message:String(k)}`),q(i,500,"the pooler lane plane failed this pick","pooler_error")}return}if(r.method!=="POST"||l.pathname!==Vn){q(i,404,`no route for ${r.method??""} ${l.pathname}`,"not_found");return}if(r.headers.authorization!==`Bearer ${s.token}`){q(i,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let p;try{p=JSON.parse(await kt(r))}catch(_){q(i,400,_ instanceof Error?_.message:String(_),"invalid_request");return}let g=Qn(p);if("reason"in g){q(i,400,g.reason,"invalid_request");return}let R=new Re(i,g.value.streaming,e);R.head();try{await s.pooler.submit(g.value.request,R)}catch(_){t(`[pooler] request ${g.value.request.request_id} failed unexpectedly: ${_ instanceof Error?_.message:String(_)}`),R.fail({status:500,code:"pooler_error",message:"the pooler failed to serve this request"})}})()});return{server:n,close:()=>new Promise(r=>n.close(()=>r()))}}S();var ue=require("@urun-sh/core");S();var Xn=3,Zn="llm",er=new Set(["paused","error"]);function It(s,e,t){let n=s.doc(Zn),r=typeof n.onConnectionState=="function",i=typeof s.onPhase=="function";if(!r&&!i)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let l=null,p=!1,g=new Set,R=[],_=d=>{if(!l){l=d;for(let m of[...g])m(d);g.clear()}};return r&&R.push(n.onConnectionState(d=>{p&&(d.consecutiveFailures<Xn||_(new H(`the pooled session for app "${e}" is gone: its doc backhaul failed ${d.consecutiveFailures} consecutive times (last close ${d.lastCloseCode===null?"by provider liveness reap":`code ${d.lastCloseCode}`}${d.lastCloseReason?`, reason ${JSON.stringify(d.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),t?.armOnFirstSync===!0&&typeof n.onSynced=="function"?R.push(n.onSynced(()=>{p=!0})):i&&R.push(s.onPhase(d=>{if(d.name==="live"){p=!0;return}p&&er.has(d.name)&&_(new H(`the pooled session for app "${e}" lost its compute binding (phase "${d.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>l,onGone(d){return l?(d(l),()=>{}):(g.add(d),()=>g.delete(d))},dispose(){g.clear();for(let d of R.splice(0))d()}}}S();var Ot=require("@urun-sh/core");S();async function xt(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 nr=new Set(["accepted","done","error"]);function rr(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 sr(s){if(s===null||typeof s!="object")return null;let e=s,t=e.status;return t!==void 0&&(typeof t!="string"||!nr.has(t))?null:{attempt:typeof e.attempt=="number"?e.attempt:0,...typeof t=="string"?{status:t}:{},...typeof e.error=="string"?{error:e.error}:{}}}function At(s){let e=rr(s.get()),t=Number(e[wt]??0),n={},r=e[Se];if(r!==null&&typeof r=="object")for(let[i,l]of Object.entries(r)){let p=sr(l);p!==null&&(n[i]=p)}return{freeSlots:Number.isFinite(t)?t:0,inflight:n,liveSeen:e[be]===!0}}function ir(s){if(s===Ot.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*or(s,e){let t=s.stream(vt(e)),n=!1;try{for await(let r of t.messages()){let i=ir(r);if(i!==null&&(yield i,i.t!=="delta")){n=!0;return}}}catch(r){throw new V(e,r instanceof Error?r.message:String(r))}if(!n)throw new V(e,"the reply stream ended without a terminal chunk (urun-stream-v1 is at-most-once across a reconnect)")}function Nt(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(yt),i=!1;return"onPhase"in e&&typeof e.onPhase=="function"&&e.onPhase(l=>{l.name==="live"&&(i=!0)}),{sessionId:t,snapshot:()=>At(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||At(r()).liveSeen,markLiveSeen:async()=>{await xt(r(),15e3,"the durable live-seen mark"),r().set({[be]:!0})},whenLive:l=>e.whenLive(l),markInflight:(l,p)=>(r().set({[Se]:{[l]:{attempt:p}}}),Promise.resolve()),push:l=>(r().set({[ve]:{[l.request_id]:{...l.payload,request_id:l.request_id,consumer_id:l.consumer_id,stream:l.stream}}}),Promise.resolve()),clearRequest:l=>{try{r().set({[ve]:{[l]:null}})}catch{}return Promise.resolve()},reply:l=>or(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 Mt(s){return async(e,t)=>{let n=e.fn??bt,r=(0,ue.App)(e.app,{baseUrl:s.baseUrl,orgId:s.orgId,getAccessToken:async()=>(await(0,ue.createClientToken)(s.apiKey,{baseUrl:s.baseUrl,expiresIn:300,allowedFunctions:[`${e.app}/${n}`],bindPrincipal:!0,...e.sharedApp?{sharedApp:!0}:{}})).token}),i=r[n];if(typeof i!="function")throw new Error(`app "${e.app}" has no function "${n}" \u2014 the pooler cannot dial a slot for it`);let l={concurrencyKey:t,...e.sharedApp?{sharedApp:!0}:{}},p=i.call(r,void 0,l);if(p===null||typeof p!="object")throw new Error(`app "${e.app}" function "${n}" returned no session`);let g=p;return Nt({session:g,sessionId:t,goneWatch:It(g,t,{armOnFirstSync:!0})})}}function hr(){let s=null;s=Ke({streams:j.default,note:e=>{s?.isDead("stderr")!==!0&&ne(j.default.stderr,e)}})}async function gr(){hr();let s=Rt(j.default.env),e=d=>{ne(j.default.stdout,`${d}
316
- `)},t=new $t.Redis(s.valkeyUrl,{maxRetriesPerRequest:null}),n=new re({eval:(d,m,T)=>t.eval(d,m.length,...m,...T)},"pooler"),r=Mt(s),i=new le({journal:new se,registry:n,queueDeadlineMs:6e4,silenceDeadlineMs:33e4,backlogThreshold:8,mint:(d,m,T)=>{let k=s.targets.find(I=>I.region===d&&I.model===m);return k===void 0?Promise.reject(new Error(`no pooler target for ${d}:${m} \u2014 refusing to mint`)):r(k,T)},limits:s.targets.map(({region:d,model:m,min:T,max:k})=>({region:d,model:m,min:T,max:k})),scaleUpWaitMs:5e3,mintCooldownMs:1e4,sessionIdleTtlMs:6e4,idleSweepMs:5e3,onEvent:d=>{St.has(d.kind)&&e(`[pooler] ${d.kind} ${JSON.stringify(d)}`)}});await i.warm();let l=s.laneRuntimeKey,p=s.laneDocHostUrl===void 0?void 0:dt({docHostUrl:s.laneDocHostUrl,redis:t,...l?{mintRuntimeToken:d=>ht(d,s.orgId,l,ft,pt)}:{}}),{server:g,close:R}=Tt({pooler:i,token:s.token,lanePlane:p,log:e});await new Promise((d,m)=>{g.once("error",m),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(", ")})${p===void 0?"":" lanes=on"}`);let _=async d=>{e(`urun-pooler: ${d} \u2014 draining`),await R(),await i.close(),await p?.close(),await t.quit().catch(()=>{})};await new Promise(d=>{j.default.once("SIGINT",()=>{_("SIGINT").finally(d)}),j.default.once("SIGTERM",()=>{_("SIGTERM").finally(d)})})}gr().then(()=>j.default.exit(0),s=>{ne(j.default.stderr,`urun-pooler failed: ${s instanceof Error?`${s.name}: ${s.message}`:String(s)}
317
- `),j.default.exit(1)});
314
+ `);return}if(s.lanePlane&&r.method==="GET"&&l.pathname===Wn){if(r.headers.authorization!==`Bearer ${s.token}`){H(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===Jn){if(r.headers.authorization!==`Bearer ${s.token}`){H(i,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let h;try{h=JSON.parse(await Ct(r))}catch(O){H(i,400,O instanceof Error?O.message:String(O),"invalid_request");return}let d=h??{};if(typeof d.pool!="string"||d.pool===""){H(i,400,"pool is required","invalid_request");return}let R=d.hold_ms;if(R!==void 0&&(typeof R!="number"||!Number.isInteger(R)||R<0||R>_t)){H(i,400,"hold_ms must be an integer in 0..120000","invalid_request");return}let $=typeof d.model=="string"&&d.model!==""?d.model:void 0,S=typeof d.app=="string"&&d.app!==""?d.app:void 0,k=typeof d.fn=="string"&&d.fn!==""?d.fn:void 0,N=d.shared_app===!0?!0:void 0;try{let O=await s.lanePlane.pick({pool:d.pool,app:S,fn:k,sharedApp:N,model:$,holdMs:R??0});if(O.length===0){let T=s.lanePlane.demandFailure(d.pool);H(i,503,T?`no capacity available for this model right now, retry shortly (the demand mint last failed: ${T})`:"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(T=>({lane_id:T.laneId,host:T.host}))}))}catch(O){t(`[pooler] lane pick for ${d.pool} failed: ${O instanceof Error?O.message:String(O)}`),H(i,500,"the pooler lane plane failed this pick","pooler_error")}return}if(r.method!=="POST"||l.pathname!==Vn){H(i,404,`no route for ${r.method??""} ${l.pathname}`,"not_found");return}if(r.headers.authorization!==`Bearer ${s.token}`){H(i,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let p;try{p=JSON.parse(await Ct(r))}catch(h){H(i,400,h instanceof Error?h.message:String(h),"invalid_request");return}let m=Qn(p);if("reason"in m){H(i,400,m.reason,"invalid_request");return}let v=new Ae(i,m.value.streaming,e);v.head();try{await s.pooler.submit(m.value.request,v)}catch(h){t(`[pooler] request ${m.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 ye=require("@urun-sh/core");b();var Xn=3,Zn="llm",er=new Set(["paused","error"]);function Ut(s,e,t){let n=s.doc(Zn),r=typeof n.onConnectionState=="function",i=typeof s.onPhase=="function";if(!r&&!i)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let l=null,p=!1,m=new Set,v=[],h=d=>{if(!l){l=d;for(let R of[...m])R(d);m.clear()}};return r&&v.push(n.onConnectionState(d=>{p&&(d.consecutiveFailures<Xn||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(()=>{p=!0})):i&&v.push(s.onPhase(d=>{if(d.name==="live"){p=!0;return}p&&er.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.`))})),{gone:()=>l,onGone(d){return l?(d(l),()=>{}):(m.add(d),()=>m.delete(d))},dispose(){m.clear();for(let d of v.splice(0))d()}}}b();var Ft=require("@urun-sh/core");b();async function qt(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)})}b();var Dt=require("@urun-sh/core/internal");function Gt(s,e){let t=s.delete;if(typeof t=="function"){(0,Dt.gcRequest)({get:n=>s.get(n),delete:n=>t.call(s,n),on:(n,r)=>s.on(n,r)},e);return}s.set({requests:{[e]:null}})}var nr=new Set(["accepted","done","error"]);function rr(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 sr(s){if(s===null||typeof s!="object")return null;let e=s,t=e.status;return t!==void 0&&(typeof t!="string"||!nr.has(t))?null:{attempt:typeof e.attempt=="number"?e.attempt:0,...typeof t=="string"?{status:t}:{},...typeof e.error=="string"?{error:e.error}:{}}}function jt(s){let e=rr(s.get()),t=Number(e[It]??0),n={},r=e[Ie];if(r!==null&&typeof r=="object")for(let[i,l]of Object.entries(r)){let p=sr(l);p!==null&&(n[i]=p)}return{freeSlots:Number.isFinite(t)?t:0,inflight:n,liveSeen:e[xe]===!0}}function ir(s){if(s===Ft.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*or(s,e){let t=s.stream(Tt(e)),n=!1;try{for await(let r of t.messages()){let i=ir(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 Ht(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(kt),i=!1;return"onPhase"in e&&typeof e.onPhase=="function"&&e.onPhase(l=>{l.name==="live"&&(i=!0)}),{sessionId:t,snapshot:()=>jt(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||jt(r()).liveSeen,markLiveSeen:async()=>{await qt(r(),15e3,"the durable live-seen mark"),r().set({[xe]:!0})},whenLive:l=>e.whenLive(l),markInflight:(l,p)=>(r().set({[Ie]:{[l]:{attempt:p}}}),Promise.resolve()),push:l=>(r().set({[Pt]:{[l.request_id]:{...l.payload,request_id:l.request_id,consumer_id:l.consumer_id,stream:l.stream}}}),Promise.resolve()),clearRequest:l=>{try{Gt(r(),l)}catch{}return Promise.resolve()},reply:l=>or(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 Kt(s){return async(e,t)=>{let n=e.fn??Ot,r=(0,ye.App)(e.app,{baseUrl:s.baseUrl,orgId:s.orgId,getAccessToken:async()=>(await(0,ye.createClientToken)(s.apiKey,{baseUrl:s.baseUrl,expiresIn:300,allowedFunctions:[`${e.app}/${n}`],bindPrincipal:!0,...e.sharedApp?{sharedApp:!0}:{}})).token}),i=r[n];if(typeof i!="function")throw new Error(`app "${e.app}" has no function "${n}" \u2014 the pooler cannot dial a slot for it`);let l={concurrencyKey:t,...e.sharedApp?{sharedApp:!0}:{}},p=i.call(r,void 0,l);if(p===null||typeof p!="object")throw new Error(`app "${e.app}" function "${n}" returned no session`);let m=p;return Ht({session:m,sessionId:t,goneWatch:Ut(m,t,{armOnFirstSync:!0})})}}function hr(){let s=null;s=Qe({streams:B.default,note:e=>{s?.isDead("stderr")!==!0&&ue(B.default.stderr,e)}})}async function gr(){hr();let s=Mt(B.default.env),e=d=>{ue(B.default.stdout,`${d}
315
+ `)},t=new Vt.Redis(s.valkeyUrl,{maxRetriesPerRequest:null}),n=new de({eval:(d,R,$)=>t.eval(d,R.length,...R,...$)},"pooler"),r=Kt(s),i=new me({journal:new pe,registry:n,queueDeadlineMs:6e4,silenceDeadlineMs:33e4,backlogThreshold:8,mint:(d,R,$)=>{let S=s.targets.find(k=>k.region===d&&k.model===R);return S===void 0?Promise.reject(new Error(`no pooler target for ${d}:${R} \u2014 refusing to mint`)):r(S,$)},limits:s.targets.map(({region:d,model:R,min:$,max:S})=>({region:d,model:R,min:$,max:S})),scaleUpWaitMs:5e3,mintCooldownMs:1e4,sessionIdleTtlMs:6e4,idleSweepMs:5e3,onEvent:d=>{At.has(d.kind)&&e(`[pooler] ${d.kind} ${JSON.stringify(d)}`)}});await i.warm();let l=Object.fromEntries(s.targets.filter(d=>d.lanePool!==void 0&&(d.laneMin??0)>0).map(d=>[d.lanePool,d.laneMin??0])),p=s.laneDocHostUrl===void 0?void 0:St({docHostUrl:s.laneDocHostUrl,redis:t,laneMinFor:d=>l[d]??0,admission:bt({baseUrl:s.baseUrl,apiKey:s.apiKey}),catalogIdentity:async d=>{if(d===void 0)return null;let R=await t.hgetall(Xe),$=[];for(let[T,A]of Object.entries(R))try{$.push({row:JSON.parse(A),field:T})}catch{}let S=T=>{let A=T.app_slug,x=T.function;return typeof A!="string"||A===""||typeof x!="string"||x===""?null:{app:A,fn:x,sharedApp:T.shared_org_id?!0:void 0}},k=$.find(T=>T.field===d);if(k){let T=S(k.row);if(T)return T}let N=d.includes(":")?d.slice(0,d.indexOf(":")):d,O=$.filter(T=>T.row.model_id===N).sort((T,A)=>T.field.localeCompare(A.field));for(let T of O){let A=S(T.row);if(A)return A}return null},onEvent:d=>{e(`[pooler] ${d.kind} ${JSON.stringify(d)}`)}}),{server:m,close:v}=Lt({pooler:i,token:s.token,lanePlane:p,log:e});await new Promise((d,R)=>{m.once("error",R),m.listen(s.port,s.bindHost,()=>d())}),e(`urun-pooler listening on http://${s.bindHost}:${s.port} (targets ${s.targets.map(d=>`${d.region}:${d.model} min=${d.min} max=${d.max}`).join(", ")})${p===void 0?"":" lanes=on"}`);let h=async d=>{e(`urun-pooler: ${d} \u2014 draining`),await v(),await i.close(),await p?.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)})})}gr().then(()=>B.default.exit(0),s=>{ue(B.default.stderr,`urun-pooler failed: ${s instanceof Error?`${s.name}: ${s.message}`:String(s)}
316
+ `),B.default.exit(1)});
318
317
  /*! Bundled license information:
319
318
 
320
319
  reflect-metadata/Reflect.js: