@urun-sh/openai 0.6.40 → 0.6.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-G5VRFFBE.js → chunk-IFYB6QUQ.js} +18 -18
- package/dist/{chunk-L6CT7ZVO.js → chunk-OZ7HE3VG.js} +1 -1
- package/dist/{chunk-PT5N7AY7.js → chunk-QNJKRB7Q.js} +1 -1
- package/dist/{chunk-BWYY4IPR.js → chunk-XKCWX72M.js} +1 -1
- package/dist/hosted/bin.cjs +27 -27
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +26 -26
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +2 -2
- package/dist/pooler/bin.cjs +10 -10
- package/dist/pooler/bin.js +10 -10
- package/dist/proxy/cli.cjs +26 -26
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +22 -22
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
package/dist/pooler/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as
|
|
2
|
+
import{a as Ae}from"../chunk-LM4E5YM2.js";import{a as z,b as X}from"../chunk-G7CSAISC.js";import{a as F}from"../chunk-L4QBHSVY.js";import{s as I,t as V}from"../chunk-XKCWX72M.js";import{a as B,b as W,d as J}from"../chunk-KKCUIOL4.js";import{a as Y}from"../chunk-7KRHHEKZ.js";import{j as T}from"../chunk-HPUX2H65.js";import{b as Ie,c as m}from"../chunk-YSFSRI3D.js";m();var ts=Ie(Ae(),1);import S from"process";import{Redis as yt}from"ioredis";m();m();var M=`
|
|
3
3
|
local slot, retired, meta = KEYS[1], KEYS[2], KEYS[3]
|
|
4
4
|
local key, gen, now = ARGV[1], tonumber(ARGV[2]), ARGV[3]
|
|
5
5
|
-- The session-as-routing-identity schema (docs/pooler-session-registry.md
|
|
@@ -38,7 +38,7 @@ if cacheNs then
|
|
|
38
38
|
end
|
|
39
39
|
redis.call('HINCRBY', meta, 'queued', 1)
|
|
40
40
|
return 'ok'
|
|
41
|
-
`,
|
|
41
|
+
`,G=`
|
|
42
42
|
local slot, genkey, retired, meta = KEYS[1], KEYS[2], KEYS[3], KEYS[4]
|
|
43
43
|
local key, gen, sessionId, now = ARGV[1], tonumber(ARGV[2]), ARGV[3], ARGV[4]
|
|
44
44
|
-- The session-registry schema (\xA72.3): ARGV[5] is the caller's OBSERVED
|
|
@@ -273,11 +273,11 @@ return table.concat(out, '\\n')
|
|
|
273
273
|
local gen = redis.call('GET', KEYS[1])
|
|
274
274
|
if not gen then return '0' end
|
|
275
275
|
return gen
|
|
276
|
-
`,
|
|
276
|
+
`,de=`
|
|
277
277
|
local state = redis.call('HGET', KEYS[1], 'state')
|
|
278
278
|
if not state then return 'none||' end
|
|
279
279
|
return state .. '|' .. (redis.call('HGET', KEYS[1], 'sessionId') or '') .. '|' .. (redis.call('HGET', KEYS[1], 'lastReason') or '')
|
|
280
|
-
`,
|
|
280
|
+
`,ce=`
|
|
281
281
|
local slot = KEYS[1]
|
|
282
282
|
local key, obsEpoch = ARGV[1], tonumber(ARGV[2])
|
|
283
283
|
local state = redis.call('HGET', slot, 'state')
|
|
@@ -297,9 +297,9 @@ redis.call('HSET', slot,
|
|
|
297
297
|
'cacheGen', ARGV[5],
|
|
298
298
|
'capabilities', ARGV[6])
|
|
299
299
|
return 'ok'
|
|
300
|
-
`;var w=class extends Error{constructor(t,s,n){super(`session registry violation (${t}): ${s} ${JSON.stringify(n)}`);this.op=t;this.verdict=s;this.context=n;this.name="RegistryViolation"}op;verdict;context},qe=100,he=i=>{let e={attached:0,queued:0,paused:0,retired:0,ended:0,inflight:0};for(let t of i.split(",")){if(t==="")continue;let[s,n]=t.split("=");s in e&&(e[s]=Number(n))}return e},
|
|
301
|
-
`)).map(e=>{let[t,s,n,r,o]=e.split("|");return{key:t,state:s,inFlight:Number(n),gen:Number(r),sessionId:o}});function E(i){let e=i.split(":"),t=e[e.length-1],s=e[e.length-2];if(s!==void 0&&/^\d+$/.test(s)&&/^\d+$/.test(t))return{base:e.slice(0,-1).join(":"),index:Number(s),gen:Number(t)};if(!/^\d+$/.test(t))throw new Error(`session registry: malformed slot key "${i}" (expected decision:{replica}:{index}[:{gen}])`);return{base:i,index:Number(t),gen:0}}var R=()=>String(Date.now()),
|
|
302
|
-
`)).map(n=>{let[r,o]=n.split("|");return{state:r,inFlight:Number(o)}})}async generation(e){let{base:t}=E(e),s=await this.evalFn.eval(ue,[`sreg:${this.pool}:gen:${t}`],[]);return Number(s)}async record(e){let s=(await this.evalFn.eval(ce,[`sreg:${this.pool}:slot:${e}`],[])).split("|"),n=s[0],r=s[1]===""||s[1]===void 0?void 0:s[1],o=s.slice(2).join("|");return{state:n,sessionId:r,lastReason:o===""?void 0:o}}};m();var A=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,s){let n=this.records.get(e);return n&&(n.sessionId=t,n.attempt=s,n.dispatched=!0),Promise.resolve()}requeue(e,t){let s=this.records.get(e);return s&&(s.dispatched=!1,s.sessionId="",s.attempt=t),Promise.resolve()}finish(e){return this.records.delete(e),Promise.resolve()}queued(e,t){return Promise.resolve([...this.records.values()].filter(s=>!s.dispatched&&s.request.region===e&&s.request.model===t).map(s=>s.request))}inflight(){return Promise.resolve([...this.records.values()].filter(e=>e.dispatched).map(e=>({request:e.request,sessionId:e.sessionId,attempt:e.attempt})))}};m();m();var O=i=>`${i.systemPrompt??""}\0${i.firstMessage??""}`;function C(i){return i.promptCacheKey!==void 0&&i.promptCacheKey!==""?`k:${i.promptCacheKey}`:i.sessionHeader!==void 0&&i.sessionHeader!==""?`h:${i.sessionHeader}`:`p:${Ne(O(i))}`}function Ne(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}var me=512,xe=4096,N=8,x=class{root={children:new Map,sessions:new Map};nodes=1;insert(e,t,s){let n=e.slice(0,me),r=this.root;for(let o=0;o<n.length;o+=N){let a=n.slice(o,o+N),u=r.children.get(a);if(!u){if(this.nodes>=xe)return;u={children:new Map,sessions:new Map},r.children.set(a,u),this.nodes+=1}u.sessions.set(t,s),r=u}}match(e,t){let s=e.slice(0,me),n=this.root,r=null,o=0,a=0;for(;;){let u=null,h=-1;for(let[d,g]of n.sessions)t.has(d)&&(g>h||g===h&&u!==null&&d<u)&&(u=d,h=g);if(u!==null&&(r={sessionId:u,depth:o}),a>=s.length)break;let c=s.slice(a,a+N),l=n.children.get(c);if(!l)break;n=l,o+=c.length,a+=N}return r}forget(e){let t=s=>{s.sessions.delete(e);for(let n of s.children.values())t(n)};t(this.root)}size(){return this.nodes}};function pe(i,e,t,s){if(e.length===0)return null;let n=new Map(e.map(c=>[c.sessionId,c])),r=c=>{let l=n.get(c);return l!==void 0&&l.backlog<s.backlogThreshold},o=new Set(n.keys()),a=s.sticky.get(C(i));if(a!==void 0&&r(a))return{sessionId:a,reason:"sticky"};let u=t.match(O(i),o);if(u!==null&&r(u.sessionId))return{sessionId:u.sessionId,reason:"prefix"};let h=null;for(let c of e)(h===null||c.backlog<h.backlog||c.backlog===h.backlog&&c.sessionId<h.sessionId)&&(h=c);return h===null?null:{sessionId:h.sessionId,reason:"load"}}m();var fe="llm",U="requests",Oe="llm-resp",H=(i,e,t,s=0)=>`decision:pooler-${i}-${e}`.replaceAll(":","-")+`:${t}`+(s>0?`:${s}`:""),D=i=>{let{base:e,gen:t}=E(i);return`${e}:${t+1}`},ge=i=>`${Oe}:${i}`,ye="free_slots",$="inflight",j="live_seen",b=class extends Error{constructor(t,s){super(`reply stream for ${t} dropped before its terminal chunk${s?`: ${s}`:""}`);this.requestId=t;this.name="ReplyStreamDropped"}requestId};var ve=new Set(["registry_error","failed","mint_failed","scaled_down","live_mark_failed"]),Ge=6e4,Le=33e4,Me=2,Ce=8,Ue=5e3,He=1e4,De=6e4,$e=5e3,je={idle:"bound",queued:"bound",unavailable:"bound",provisioning:"bound",waiting_for_capacity:"bound",connecting:"bound",live:"bound",degraded:"bound",paused:"unbound",error:"unbound",unknown:"unbound"},G=class i{pools=new Map;now;queueDeadlineMs;silenceDeadlineMs;maxAttempts;backlogThreshold;mint;limits;scaleUpWaitMs;mintCooldownMs;sessionIdleTtlMs;idleSweepMs;journal;registry;onEvent;closed=!1;sweepTimer=null;constructor(e){this.journal=e.journal,this.registry=e.registry??null,this.now=e.now??Date.now,this.queueDeadlineMs=e.queueDeadlineMs??Ge,this.silenceDeadlineMs=e.silenceDeadlineMs??Le,this.maxAttempts=e.maxAttempts??Me,this.backlogThreshold=e.backlogThreshold??Ce,this.mint=e.mint,this.limits=e.limits??[],this.scaleUpWaitMs=e.scaleUpWaitMs??Ue,this.mintCooldownMs=e.mintCooldownMs??He,this.sessionIdleTtlMs=e.sessionIdleTtlMs??De,this.idleSweepMs=e.idleSweepMs??$e,this.onEvent=e.onEvent??(()=>{}),(this.mint!==void 0||this.limits.length>0)&&this.armSweep()}armSweep(){this.sweepTimer=setInterval(()=>this.sweep(),this.idleSweepMs),this.sweepTimer.unref?.()}sweep(){if(!this.closed)for(let e of this.pools.values()){let t=this.limitsFor(e);if(t===null)continue;this.evictUnbound(e);let s=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"),s&&e.sessions.length>t.min&&this.scaleDownOldestIdle(e,t)}}servable(e){return e.gone()!==null?!1:je[e.phaseName()]==="bound"?!0:!e.everLive()}evictUnbound(e){for(let t of[...e.sessions]){if(this.servable(t))continue;let s=t.phaseName();this.onEvent({kind:"sweep_evicted",pool:this.key(e.region,e.model),sessionId:t.sessionId,phase:s}),this.evict(e,t,new T(`the pool entry for ${t.sessionId} has no usable compute binding (phase "${s}") \u2014 the sweep's servability reconcile evicts it; the named session itself stays parked and attachable`))}}limitsFor(e){return this.limits.find(t=>t.region===e.region&&t.model===e.model)??null}queuePressure(e){if(e.queue.length===0)return!1;let t=this.now();return e.queue.some(s=>t-s.queuedAt>=this.scaleUpWaitMs)}tryMint(e,t){if(this.mint===void 0||this.closed||e.minting)return;let s=this.limitsFor(e);if(s===null||e.sessions.length>=s.max)return;let n=this.now();n-e.lastMintAt<this.mintCooldownMs||(e.lastMintAt=n,e.minting=!0,this.mintOnce(e,t).finally(()=>{e.minting=!1}))}async mintOnce(e,t){if(this.mint===void 0)return!1;let s=e.mintSeq++,n;try{n=await this.claimSlot(e.region,e.model,s)}catch(r){if(t==="boot_floor")throw r;return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:r instanceof Error?r.message:String(r)}),!1}try{let r=await this.mint(e.region,e.model,n);return this.closed?(await r.end().catch(()=>{}),!1):(this.addSession(e.region,e.model,r,n),this.onEvent({kind:"minted",pool:this.key(e.region,e.model),sessionId:r.sessionId,reason:t}),!0)}catch(r){return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:r instanceof Error?r.message:String(r)}),!1}}async warm(){for(let e of this.limits){let t=this.poolOf(e.region,e.model);t.minting=!0;try{for(;t.sessions.length<e.min&&await this.mintOnce(t,"boot_floor"););}finally{t.minting=!1}}}scaleDownOldestIdle(e,t){let s=this.now();for(let n of e.sessions){if(n.gone()!==null||[...e.records.values()].some(h=>h.session===n&&h.phase==="dispatched")||s-(e.lastActivity.get(n)??s)<this.sessionIdleTtlMs)continue;let a=e.sessions.indexOf(n);if(a===-1)continue;e.sessions.splice(a,1),this.detachSignals(e,n),e.radix.forget(n.sessionId),e.lastActivity.delete(n);let u=e.slotKeys.get(n.sessionId);u!==void 0&&(e.slotKeys.delete(n.sessionId),this.registryCall("end",u,()=>this.registry?.end(u))),this.onEvent({kind:"scaled_down",pool:this.key(e.region,e.model),sessionId:n.sessionId,sessions:e.sessions.length,min:t.min}),n.end().catch(h=>{this.onEvent({kind:"scaled_down_end_failed",pool:this.key(e.region,e.model),sessionId:n.sessionId,reason:h instanceof Error?h.message:String(h)})});return}}static poolKey(e,t){return`${e}:${t}`}async claimSlot(e,t,s){let n=H(e,t,s);if(this.registry===null)return n;for(let r=0;;r++){let o=await this.registry.generation(n),a=H(e,t,s,o),{state:u,sessionId:h,lastReason:c}=await this.registry.record(a);if(u==="none"||u==="paused"&&h===void 0&&c===void 0)try{return await this.registry.mint(a),a}catch(l){this.rethrowUnlessClaimRace(l,r);continue}else{let l=D(a);try{await this.registry.rotate(a,l),await this.registry.mint(l)}catch(d){this.rethrowUnlessClaimRace(d,r);continue}return this.onEvent({kind:"slot_rotated",pool:this.key(e,t),slotKey:a,successor:l,reason:u==="paused"?"boot claim over an evicted slot's dead session":`boot claim over a previous pod's ${u} record`}),l}}}static CLAIM_RACE_VERDICTS=new Set(["reject:double-rotate","reject:generation-monotone","reject:retired-corpse-reuse","reject:mint-queued","reject:mint-attached"]);static CLAIM_RACE_ATTEMPTS=3;rethrowUnlessClaimRace(e,t){if(!(t+1<i.CLAIM_RACE_ATTEMPTS&&e instanceof w&&i.CLAIM_RACE_VERDICTS.has(e.verdict)))throw e}addSession(e,t,s,n){let r=this.poolOf(e,t);r.sessions.push(s),r.lastActivity.set(s,this.now()),r.slotKeys.set(s.sessionId,n),s.whenLive().then(()=>{s.markLiveSeen().catch(o=>{this.onEvent({kind:"live_mark_failed",pool:this.key(e,t),sessionId:s.sessionId,reason:o instanceof Error?o.message:String(o)})}),this.registryCall("attach",n,()=>this.registry?.attach(n,s.sessionId))}).catch(o=>{this.onEvent({kind:"session_never_live",pool:this.key(e,t),sessionId:s.sessionId,reason:o instanceof Error?o.message:String(o)}),this.evict(r,s,o instanceof Error?o:new Error(String(o)))}),r.offs.set(s,[s.onDocChange(()=>{this.pump(r),this.adoptSettled(r)}),s.onGone(o=>this.evict(r,s,o))]),this.onEvent({kind:"session_added",pool:this.key(e,t),sessionId:s.sessionId}),this.start(r).then(()=>this.pump(r))}async start(e){if(!e.needsReconcile)return;e.needsReconcile=!1;let t=this.key(e.region,e.model);for(let s of await this.journal.inflight()){if(s.request.region!==e.region||s.request.model!==e.model)continue;let n=e.sessions.find(o=>o.sessionId===s.sessionId),r=n?.snapshot().inflight[s.request.request_id];if(n!==void 0){if(r?.status==="done"||r?.status==="error"){await this.journal.finish(s.request.request_id);continue}e.records.set(s.request.request_id,{request:s.request,sink:null,attempt:s.attempt,tried:new Set([s.sessionId]),session:n,phase:"dispatched",streamed:!1,deadlineAt:Number.POSITIVE_INFINITY,queueTimer:null,silenceTimer:null,queuedAt:this.now()}),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:s.request.request_id,sessionId:s.sessionId})}}for(let s of await this.journal.queued(e.region,e.model))await this.journal.finish(s.request_id),this.onEvent({kind:"reconciled_caller_gone",pool:t,requestId:s.request_id});for(let s of e.sessions){let n=s.snapshot();for(let[r,o]of Object.entries(n.inflight)){if(o.status==="done"||o.status==="error"||e.records.has(r))continue;let a={request:{request_id:r,region:e.region,model:e.model,affinity:{},payload:{},streaming:!1,enqueuedAt:0},sink:null,attempt:o.attempt,tried:new Set([s.sessionId]),session:s,phase:"dispatched",streamed:!1,deadlineAt:Number.POSITIVE_INFINITY,queueTimer:null,silenceTimer:null,queuedAt:this.now()};e.records.set(r,a),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:r,sessionId:s.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 s=this.poolOf(e.region,e.model);await this.start(s);let n={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()};s.records.set(e.request_id,n),s.queue.push(n),await this.journal.add(e),t.head(),this.armQueueTimer(s,n),this.onEvent({kind:"enqueued",pool:this.key(e.region,e.model),requestId:e.request_id}),this.pump(s),n.phase!=="finished"&&await new Promise(r=>{n.settle=r})}abandon(){this.closed=!0,this.sweepTimer!==null&&(clearInterval(this.sweepTimer),this.sweepTimer=null);for(let e of this.pools.values()){for(let t of e.records.values())this.clearTimers(t);for(let t of e.offs.values())for(let s of t)s();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 s of e.records.values())this.clearTimers(s),s.phase!=="finished"&&this.settle(s,{status:503,code:"draining",message:"pooler is shutting down",retryAfterSeconds:5});for(let s of e.offs.values())for(let n of s)n();e.offs.clear(),e.lastActivity.clear();for(let s of e.slotKeys.values())this.registryCall("rotate",s,()=>this.registry?.rotate(s,D(s)));e.slotKeys.clear();let t=e.sessions.splice(0);await Promise.allSettled(t.map(s=>s.end()))}this.pools.clear()}poolOf(e,t){let s=i.poolKey(e,t),n=this.pools.get(s);return n||(n={region:e,model:t,sessions:[],records:new Map,queue:[],sticky:new Map,radix:new x,offs:new Map,slotKeys:new Map,needsReconcile:!0,lastMintAt:0,minting:!1,mintSeq:0,lastActivity:new Map},this.pools.set(s,n)),n}key(e,t){return i.poolKey(e,t)}registryCall(e,t,s){let n=s();n!==void 0&&n.catch(r=>{this.onEvent({kind:"registry_error",reason:`${e}: ${r instanceof Error?r.message:String(r)}`,slotKey:t})})}creditFor(e,t){let s=t.snapshot(),n=0;for(let r of e.records.values()){if(r.session!==t||r.phase!=="dispatched")continue;let o=s.inflight[r.request.request_id];(o===void 0||o.status===void 0)&&(n+=1)}return Math.max(0,s.freeSlots-n)}backlogOf(e,t){let s=0;for(let n of e.records.values())n.session===t&&n.phase==="dispatched"&&(s+=1);return s}pump(e){if(this.closed)return;let t=!0;for(;t&&e.queue.length>0&&e.sessions.length>0;){t=!1;for(let s=0;s<e.queue.length;s++){let n=e.queue[s],r=this.pickFor(e,n);if(r!==null){e.queue.splice(s,1),this.dispatch(e,r,n),t=!0;break}}}e.queue.length>0&&this.queuePressure(e)&&this.tryMint(e,"queue_pressure")}pickFor(e,t){let s=e.sessions.filter(o=>this.servable(o)&&!t.tried.has(o.sessionId)&&this.creditFor(e,o)>0).map(o=>({sessionId:o.sessionId,backlog:this.backlogOf(e,o)})),n=pe(t.request.affinity,s,e.radix,{backlogThreshold:this.backlogThreshold,sticky:e.sticky});if(n===null)return null;let r=e.sessions.find(o=>o.sessionId===n.sessionId)??null;return r!==null&&this.onEvent({kind:"picked",pool:this.key(e.region,e.model),requestId:t.request.request_id,sessionId:r.sessionId,reason:n.reason}),r}dispatch(e,t,s){s.phase="dispatched",s.session=t,s.tried.add(t.sessionId),e.lastActivity.set(t,this.now()),this.clearTimer(s,"queue"),s.deadlineAt=this.now()+this.silenceDeadlineMs;let n={request_id:s.request.request_id,consumer_id:s.request.request_id,payload:s.request.payload,stream:s.request.streaming};(async()=>{let r=t.reply(n.request_id);try{await t.markInflight(n.request_id,s.attempt),await t.push(n)}catch(u){this.lost(e,s,u);return}await this.journal.dispatched(s.request.request_id,t.sessionId,s.attempt);let o=C(s.request.affinity);e.sticky.set(o,t.sessionId),e.radix.insert(O(s.request.affinity),t.sessionId,this.now()),this.onEvent({kind:"dispatched",pool:this.key(e.region,e.model),requestId:s.request.request_id,sessionId:t.sessionId,attempt:s.attempt}),this.armSilenceTimer(e,s);let a=e.slotKeys.get(t.sessionId);a!==void 0&&this.registryCall("lease",a,()=>this.registry?.lease(a)),this.consume(e,s,r)})()}async consume(e,t,s){if(t.session!==null)try{for await(let n of s){if(t.phase==="finished")return;this.armSilenceTimer(e,t),t.streamed=!0;let r=t.sink;if(r!==null&&(await r.chunk(n),n.t==="response"||n.t==="error"||n.t==="end")){await this.finish(e,t);return}}this.lost(e,t,new b(t.request.request_id,"iterator ended without a terminal chunk"))}catch(n){this.lost(e,t,n)}}lost(e,t,s){if(t.phase==="finished")return;this.clearTimers(t);let n=s instanceof Error?s.message:String(s);this.onEvent({kind:"lost",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt,reason:n}),s instanceof T&&t.session!==null&&this.evict(e,t.session,s);let r=e.sessions.some(o=>this.servable(o)&&!t.tried.has(o.sessionId));if(!t.streamed&&t.attempt<this.maxAttempts&&r){t.attempt+=1,t.phase="queued",t.session=null,t.deadlineAt=this.now()+this.queueDeadlineMs,t.queuedAt=this.now(),e.queue.unshift(t),this.journal.requeue(t.request.request_id,t.attempt).catch(()=>{}),this.armQueueTimer(e,t),this.onEvent({kind:"retry",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt}),this.pump(e);return}this.settle(t,{status:502,code:t.streamed?"upstream_stream_lost":"upstream_error",message:t.streamed?"the upstream reply stream was lost after the response began":"the upstream reply stream was lost before the response began",retryAfterSeconds:1})}async finish(e,t){this.clearTimers(t),t.phase="finished",t.session!==null&&e.lastActivity.set(t.session,this.now()),this.releaseSlot(e,t,"release"),await this.journal.finish(t.request.request_id),t.session!==null&&t.session.clearRequest(t.request.request_id);let s=t.sink;s!==null&&s.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 s=e.session===null?void 0:this.poolOf(e.request.region,e.request.model).slotKeys.get(e.session.sessionId);s!==void 0&&this.registryCall("release",s,()=>this.registry?.release(s)),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 n=e.sink;n!==null&&n.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,s){if(t.session===null)return;let n=e.slotKeys.get(t.session.sessionId);n!==void 0&&this.registryCall(s,n,()=>s==="release"?this.registry?.release(n):this.registry?.detach(n,"session evicted"))}detachSignals(e,t){let s=e.offs.get(t);if(s!==void 0){e.offs.delete(t);for(let n of s)n()}}evict(e,t,s){let n=e.sessions.indexOf(t);if(n===-1)return;e.sessions.splice(n,1),this.detachSignals(e,t),e.lastActivity.delete(t),e.radix.forget(t.sessionId);let r=e.slotKeys.get(t.sessionId);r!==void 0&&(e.slotKeys.delete(t.sessionId),this.registryCall("detach",r,()=>this.registry?.detach(r,s.message)));for(let o of[...e.records.values()])o.session===t&&o.phase!=="finished"&&this.lost(e,o,s)}adoptSettled(e){for(let t of e.sessions){let s=t.snapshot();for(let n of[...e.records.values()]){if(n.sink!==null||n.session!==t)continue;let r=s.inflight[n.request.request_id];(r?.status==="done"||r?.status==="error")&&(this.journal.finish(n.request.request_id).catch(()=>{}),this.release(e,n))}}}armQueueTimer(e,t){this.clearTimer(t,"queue");let s=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))},s),t.queueTimer.unref?.()}armSilenceTimer(e,t){t.silenceTimer===null&&(t.silenceTimer=setTimeout(()=>{t.silenceTimer=null,t.phase==="dispatched"&&this.lost(e,t,new b(t.request.request_id,`silent past ${this.silenceDeadlineMs}ms`))},this.silenceDeadlineMs),t.silenceTimer.unref?.())}clearTimer(e,t){let s=t==="queue"?e.queueTimer:e.silenceTimer;s!==null&&(clearTimeout(s),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(s=>s.phase==="dispatched").length,sessions:t.sessions.length}))}}};m();var Ke="0.0.0.0",Ee="serve";var _=(i,e)=>{let t=i[e];if(typeof t!="string"||t==="")throw new Error(`the pooler requires ${e} (external input) \u2014 refusing to start half-configured`);return t},Ye=(i,e)=>{if(i===null||typeof i!="object")throw new Error(`URUN_POOLER_TARGETS[${e}] must be an object`);let t=i,s=a=>{let u=t[a];if(typeof u!="string"||u==="")throw new Error(`URUN_POOLER_TARGETS[${e}].${a} is required`);return u},n=a=>{let u=t[a];if(typeof u!="number"||!Number.isInteger(u))throw new Error(`URUN_POOLER_TARGETS[${e}].${a} must be an integer`);return u},r,o;if(t.sessions!==void 0){let a=t.sessions;if(typeof a!="number"||!Number.isInteger(a)||a<1)throw new Error(`URUN_POOLER_TARGETS[${e}].sessions must be an integer >= 1`);if(t.min!==void 0||t.max!==void 0)throw new Error(`URUN_POOLER_TARGETS[${e}]: give either sessions or {min, max}, never both`);r=a,o=a}else{if(r=n("min"),o=n("max"),r<0)throw new Error(`URUN_POOLER_TARGETS[${e}].min must be >= 0 (0 scales to zero)`);if(o<1)throw new Error(`URUN_POOLER_TARGETS[${e}].max must be >= 1`);if(r>o)throw new Error(`URUN_POOLER_TARGETS[${e}]: min (${String(r)}) must not exceed max (${String(o)})`)}return{region:s("region"),model:s("model"),app:s("app"),fn:typeof t.fn=="string"&&t.fn!==""?t.fn:void 0,min:r,max:o,sharedApp:t.sharedApp===!0}};function Se(i){let e=i.PORT,t=e===void 0||e===""?8080:Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw new Error(`PORT must be a valid port number, got ${String(e)}`);let s=_(i,"URUN_BASE_URL"),n=_(i,"URUN_POOLER_TARGETS"),r;try{r=JSON.parse(n)}catch(o){throw new Error(`URUN_POOLER_TARGETS is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}if(!Array.isArray(r)||r.length===0)throw new Error("URUN_POOLER_TARGETS must be a non-empty JSON array");return{port:t,bindHost:Ke,token:_(i,"URUN_POOLER_TOKEN"),baseUrl:s,apiUrl:i.URUN_API_URL!==void 0&&i.URUN_API_URL!==""?i.URUN_API_URL:`${s}/v1`,orgId:_(i,"URUN_ORG_ID"),apiKey:_(i,"URUN_API_KEY"),valkeyUrl:_(i,"URUN_VALKEY_URL"),laneDocHostUrl:(i.URUN_LANE_DOC_HOST_URL??"").trim()||void 0,laneRuntimeKey:(i.URUN_LANE_RUNTIME_KEY??"").trim()||void 0,targets:r.map(Ye)}}m();import{createServer as Ve}from"http";var Fe="/pooler/v1/inference",Be="/readyz",We="/metrics",Je="/pooler/v1/lanes/pick",ze="/pooler/v1/lanes/status",Xe=1e4,Re=16*1024*1024;function f(i,e,t,s,n){i.headersSent||(n!==void 0&&i.setHeader("retry-after",String(n)),i.writeHead(e,{"content-type":"application/json"}),i.end(JSON.stringify({error:{message:t,type:"pooler_error",code:s}})))}function Qe(i){if(i===null||typeof i!="object")return{reason:"body must be a JSON object"};let e=i;if(typeof e.region!="string"||e.region==="")return{reason:"region is required"};if(typeof e.model!="string"||e.model==="")return{reason:"model is required"};if(typeof e.request_id!="string"||e.request_id==="")return{reason:"request_id is required"};if(e.payload===null||typeof e.payload!="object")return{reason:"payload must be an object"};let t=e.affinity??{};if(t===null||typeof t!="object")return{reason:"affinity must be an object"};let s=t,n=r=>typeof r=="string"&&r!==""?r:void 0;return{value:{streaming:e.streaming===!0,request:{request_id:e.request_id,region:e.region,model:e.model,payload:e.payload,affinity:{promptCacheKey:n(s.promptCacheKey??e.prompt_cache_key),sessionHeader:n(s.sessionHeader??e.session_header),systemPrompt:n(s.systemPrompt),firstMessage:n(s.firstMessage)},streaming:e.streaming===!0,enqueuedAt:Date.now()}}}}var K=class{constructor(e,t,s){this.res=e;this.streaming=t;this.keepaliveMs=s}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 w=class extends Error{constructor(t,s,n){super(`session registry violation (${t}): ${s} ${JSON.stringify(n)}`);this.op=t;this.verdict=s;this.context=n;this.name="RegistryViolation"}op;verdict;context},qe=100,he=i=>{let e={attached:0,queued:0,paused:0,retired:0,ended:0,inflight:0};for(let t of i.split(",")){if(t==="")continue;let[s,n]=t.split("=");s in e&&(e[s]=Number(n))}return e},Ne=i=>(i===""?[]:i.split(`
|
|
301
|
+
`)).map(e=>{let[t,s,n,r,o]=e.split("|");return{key:t,state:s,inFlight:Number(n),gen:Number(r),sessionId:o}});function E(i){let e=i.split(":"),t=e[e.length-1],s=e[e.length-2];if(s!==void 0&&/^\d+$/.test(s)&&/^\d+$/.test(t))return{base:e.slice(0,-1).join(":"),index:Number(s),gen:Number(t)};if(!/^\d+$/.test(t))throw new Error(`session registry: malformed slot key "${i}" (expected decision:{replica}:{index}[:{gen}])`);return{base:i,index:Number(t),gen:0}}var R=()=>String(Date.now()),A=class{constructor(e,t){this.evalFn=e;this.pool=t}evalFn;pool;keys(e,t=!0,s=!0){let{base:n}=E(e),r=[`sreg:${this.pool}:slot:${e}`];return t&&r.push(`sreg:${this.pool}:gen:${n}`),s&&r.push(`sreg:${this.pool}:retired`),r.push(`sreg:${this.pool}:meta`),r}async run(e,t,s,n,r){let o=await this.evalFn.eval(t,s,n);if(o.startsWith("reject:"))throw new w(e,o,{pool:this.pool,...r})}mint(e){let{gen:t}=E(e);return this.run("mint",M,this.keys(e,!1,!0),[e,t,R()],{slotKey:e,gen:t})}mintWith(e,t){let{gen:s}=E(e);return this.run("mint",M,this.keys(e,!1,!0),[e,s,R(),t.model,t.capabilities??"",t.cacheNs],{slotKey:e,gen:s,cacheNs:t.cacheNs})}attachWithEpoch(e,t,s){let{gen:n}=E(e);return this.run("attach",G,this.keys(e),[e,n,t,R(),s],{slotKey:e,gen:n,sessionId:t,observedEpoch:s})}publish(e,t,s){return this.run("publish",ce,this.keys(e,!1,!1),[e,t,s.maxConcurrent,s.queueDepth,s.cacheGen,s.capabilities??""],{slotKey:e,observedEpoch:t})}attach(e,t){let{gen:s}=E(e);return this.run("attach",G,this.keys(e),[e,s,t,R()],{slotKey:e,gen:s,sessionId:t})}detach(e,t){return this.run("detach",Q,this.keys(e,!1,!1),[e,t,R()],{slotKey:e,reason:t})}rotate(e,t){let{gen:s}=E(t),n=[...this.keys(e),`sreg:${this.pool}:slot:${t}`];return this.run("rotate",Z,n,[e,t,s,R()],{oldKey:e,newKey:t,newGen:s})}end(e){return this.run("end",ee,this.keys(e,!1,!1),[e,R()],{slotKey:e})}lease(e){return this.run("lease",te,this.keys(e,!1,!1),[e],{slotKey:e})}release(e){return this.run("release",ne,this.keys(e,!1,!1),[e,R()],{slotKey:e})}configure(e,t){return this.run("config",ie,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}retune(e,t){return this.run("retune",re,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}async tuning(){let e=await this.evalFn.eval(se,[`sreg:${this.pool}:meta`],[]),[t,s,n]=e.split("|");return{max:Number(t),inFlightCap:Number(s),configVersion:Number(n)}}async grant(e,t){let s=this.keys(e,!1,!1),n=await this.evalFn.eval(k,s,[e,t.cap,t.configVersion]);if(n==="reject:cap-moved"){let r=await this.tuning();n=await this.evalFn.eval(k,s,[e,r.inFlightCap,r.configVersion])}if(n==="ok")return{granted:!0};if(n==="reject:cap")return{granted:!1,reason:"cap-full"};if(n==="reject:cap-moved")return{granted:!1,reason:"cap-moved"};throw new w("grant",n,{pool:this.pool,slotKey:e})}async grantWithEpoch(e,t){let s=this.keys(e,!1,!1),n=await this.evalFn.eval(k,s,[e,t.cap,t.configVersion,t.epoch]);if(n==="reject:cap-moved"){let r=await this.tuning();n=await this.evalFn.eval(k,s,[e,r.inFlightCap,r.configVersion,t.epoch])}if(n==="ok")return{granted:!0};if(n==="reject:cap")return{granted:!1,reason:"cap-full"};if(n==="reject:cap-moved")return{granted:!1,reason:"cap-moved"};if(n==="reject:epoch")return{granted:!1,reason:"epoch-stale"};throw new w("grant",n,{pool:this.pool,slotKey:e})}async snapshot(){let e=[],t=null,s="0";do{let n=await this.snapshotPage(s,qe);t===null&&(t=n.counts),e.push(...n.slots),s=n.cursor}while(s!=="0");return{counts:t,slots:e}}async counts(){let e=await this.evalFn.eval(ae,[`sreg:${this.pool}:meta`],[]);return he(e)}async snapshotPage(e,t){let s=`sreg:${this.pool}:slot:`,n=await this.evalFn.eval(oe,[`sreg:${this.pool}:meta`],[s,e,t]),[r,o,a]=n.split("#");return{cursor:r,counts:he(o??""),slots:Ne(a??"")}}async readRecords(e){if(e.length===0)return[];let t=`sreg:${this.pool}:slot:`,s=await this.evalFn.eval(le,[],e.map(n=>t+n));return(s===""?[]:s.split(`
|
|
302
|
+
`)).map(n=>{let[r,o]=n.split("|");return{state:r,inFlight:Number(o)}})}async generation(e){let{base:t}=E(e),s=await this.evalFn.eval(ue,[`sreg:${this.pool}:gen:${t}`],[]);return Number(s)}async record(e){let s=(await this.evalFn.eval(de,[`sreg:${this.pool}:slot:${e}`],[])).split("|"),n=s[0],r=s[1]===""||s[1]===void 0?void 0:s[1],o=s.slice(2).join("|");return{state:n,sessionId:r,lastReason:o===""?void 0:o}}};m();var q=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,s){let n=this.records.get(e);return n&&(n.sessionId=t,n.attempt=s,n.dispatched=!0),Promise.resolve()}requeue(e,t){let s=this.records.get(e);return s&&(s.dispatched=!1,s.sessionId="",s.attempt=t),Promise.resolve()}finish(e){return this.records.delete(e),Promise.resolve()}queued(e,t){return Promise.resolve([...this.records.values()].filter(s=>!s.dispatched&&s.request.region===e&&s.request.model===t).map(s=>s.request))}inflight(){return Promise.resolve([...this.records.values()].filter(e=>e.dispatched).map(e=>({request:e.request,sessionId:e.sessionId,attempt:e.attempt})))}};m();m();var O=i=>`${i.systemPrompt??""}\0${i.firstMessage??""}`;function C(i){return i.promptCacheKey!==void 0&&i.promptCacheKey!==""?`k:${i.promptCacheKey}`:i.sessionHeader!==void 0&&i.sessionHeader!==""?`h:${i.sessionHeader}`:`p:${xe(O(i))}`}function xe(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}var me=512,Oe=4096,N=8,x=class{root={children:new Map,sessions:new Map};nodes=1;insert(e,t,s){let n=e.slice(0,me),r=this.root;for(let o=0;o<n.length;o+=N){let a=n.slice(o,o+N),u=r.children.get(a);if(!u){if(this.nodes>=Oe)return;u={children:new Map,sessions:new Map},r.children.set(a,u),this.nodes+=1}u.sessions.set(t,s),r=u}}match(e,t){let s=e.slice(0,me),n=this.root,r=null,o=0,a=0;for(;;){let u=null,h=-1;for(let[c,g]of n.sessions)t.has(c)&&(g>h||g===h&&u!==null&&c<u)&&(u=c,h=g);if(u!==null&&(r={sessionId:u,depth:o}),a>=s.length)break;let d=s.slice(a,a+N),l=n.children.get(d);if(!l)break;n=l,o+=d.length,a+=N}return r}forget(e){let t=s=>{s.sessions.delete(e);for(let n of s.children.values())t(n)};t(this.root)}size(){return this.nodes}};function pe(i,e,t,s){if(e.length===0)return null;let n=new Map(e.map(d=>[d.sessionId,d])),r=d=>{let l=n.get(d);return l!==void 0&&l.backlog<s.backlogThreshold},o=new Set(n.keys()),a=s.sticky.get(C(i));if(a!==void 0&&r(a))return{sessionId:a,reason:"sticky"};let u=t.match(O(i),o);if(u!==null&&r(u.sessionId))return{sessionId:u.sessionId,reason:"prefix"};let h=null;for(let d of e)(h===null||d.backlog<h.backlog||d.backlog===h.backlog&&d.sessionId<h.sessionId)&&(h=d);return h===null?null:{sessionId:h.sessionId,reason:"load"}}m();var fe="llm",U="requests",Le="llm-resp",H=(i,e,t,s=0)=>`decision:pooler-${i}-${e}`.replaceAll(":","-")+`:${t}`+(s>0?`:${s}`:""),D=i=>{let{base:e,gen:t}=E(i);return`${e}:${t+1}`},ge=i=>`${Le}:${i}`,ye="free_slots",$="inflight",K="live_seen",b=class extends Error{constructor(t,s){super(`reply stream for ${t} dropped before its terminal chunk${s?`: ${s}`:""}`);this.requestId=t;this.name="ReplyStreamDropped"}requestId};var Ee=new Set(["registry_error","failed","mint_failed","scaled_down","live_mark_failed","never_live_evicted","never_live_end_failed"]),Me=6e4,Ge=33e4,Ce=2,Ue=8,He=5e3,De=1e4,$e=6e4,Ke=5e3,je=36e5,Ye={provisioning:!0,waiting_for_capacity:!0,connecting:!0},ve={idle:"bound",queued:"bound",unavailable:"bound",provisioning:"bound",waiting_for_capacity:"bound",connecting:"bound",live:"bound",degraded:"bound",paused:"unbound",error:"unbound",unknown:"unbound"},L=class i{pools=new Map;now;queueDeadlineMs;silenceDeadlineMs;maxAttempts;backlogThreshold;mint;limits;scaleUpWaitMs;mintCooldownMs;sessionIdleTtlMs;idleSweepMs;neverLiveEvictAfterMs;journal;registry;onEvent;closed=!1;sweepTimer=null;constructor(e){this.journal=e.journal,this.registry=e.registry??null,this.now=e.now??Date.now,this.queueDeadlineMs=e.queueDeadlineMs??Me,this.silenceDeadlineMs=e.silenceDeadlineMs??Ge,this.maxAttempts=e.maxAttempts??Ce,this.backlogThreshold=e.backlogThreshold??Ue,this.mint=e.mint,this.limits=e.limits??[],this.scaleUpWaitMs=e.scaleUpWaitMs??He,this.mintCooldownMs=e.mintCooldownMs??De,this.sessionIdleTtlMs=e.sessionIdleTtlMs??$e,this.idleSweepMs=e.idleSweepMs??Ke,this.neverLiveEvictAfterMs=e.neverLiveEvictAfterMs??je,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 s=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"),s&&e.sessions.length>t.min&&this.scaleDownOldestIdle(e,t)}}servable(e){return e.gone()!==null?!1:ve[e.phaseName()]==="bound"?!0:!e.everLive()}evictUnbound(e){for(let t of[...e.sessions]){if(this.servable(t))continue;let s=t.phaseName();this.onEvent({kind:"sweep_evicted",pool:this.key(e.region,e.model),sessionId:t.sessionId,phase:s}),this.evict(e,t,new T(`the pool entry for ${t.sessionId} has no usable compute binding (phase "${s}") \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 s=this.now();for(let n of[...e.sessions]){if(n.gone()!==null||n.everLive())continue;let r=n.phaseName();if(ve[r]!=="bound"||!Ye[r])continue;let o=e.bornAt.get(n);if(o===void 0||s-o<t)continue;let a=e.sessions.indexOf(n);if(a===-1)continue;e.sessions.splice(a,1),this.detachSignals(e,n),e.radix.forget(n.sessionId),e.lastActivity.delete(n),e.bornAt.delete(n);let u=e.slotKeys.get(n.sessionId);u!==void 0&&(e.slotKeys.delete(n.sessionId),this.registryCall("end",u,()=>this.registry?.end(u))),this.onEvent({kind:"never_live_evicted",pool:this.key(e.region,e.model),sessionId:n.sessionId,phase:r,elapsedMs:s-o}),(n.namedSessionId()!==void 0?n.end():n.cancel()).catch(d=>{this.onEvent({kind:"never_live_end_failed",pool:this.key(e.region,e.model),sessionId:n.sessionId,reason:d instanceof Error?d.message:String(d)})})}}limitsFor(e){return this.limits.find(t=>t.region===e.region&&t.model===e.model)??null}queuePressure(e){if(e.queue.length===0)return!1;let t=this.now();return e.queue.some(s=>t-s.queuedAt>=this.scaleUpWaitMs)}tryMint(e,t){if(this.mint===void 0||this.closed||e.minting)return;let s=this.limitsFor(e);if(s===null||e.sessions.length>=s.max)return;let n=this.now();n-e.lastMintAt<this.mintCooldownMs||(e.lastMintAt=n,e.minting=!0,this.mintOnce(e,t).finally(()=>{e.minting=!1}))}async mintOnce(e,t){if(this.mint===void 0)return!1;let s=e.mintSeq++,n;try{n=await this.claimSlot(e.region,e.model,s)}catch(r){if(t==="boot_floor")throw r;return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:r instanceof Error?r.message:String(r)}),!1}try{let r=await this.mint(e.region,e.model,n);return this.closed?(await r.end().catch(()=>{}),!1):(this.addSession(e.region,e.model,r,n),this.onEvent({kind:"minted",pool:this.key(e.region,e.model),sessionId:r.sessionId,reason:t}),!0)}catch(r){return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:r instanceof Error?r.message:String(r)}),!1}}async warm(){for(let e of this.limits){let t=this.poolOf(e.region,e.model);t.minting=!0;try{for(;t.sessions.length<e.min&&await this.mintOnce(t,"boot_floor"););}finally{t.minting=!1}}}scaleDownOldestIdle(e,t){let s=this.now();for(let n of e.sessions){if(n.gone()!==null||[...e.records.values()].some(h=>h.session===n&&h.phase==="dispatched")||s-(e.lastActivity.get(n)??s)<this.sessionIdleTtlMs)continue;let a=e.sessions.indexOf(n);if(a===-1)continue;e.sessions.splice(a,1),this.detachSignals(e,n),e.radix.forget(n.sessionId),e.lastActivity.delete(n),e.bornAt.delete(n);let u=e.slotKeys.get(n.sessionId);u!==void 0&&(e.slotKeys.delete(n.sessionId),this.registryCall("end",u,()=>this.registry?.end(u))),this.onEvent({kind:"scaled_down",pool:this.key(e.region,e.model),sessionId:n.sessionId,sessions:e.sessions.length,min:t.min}),n.end().catch(h=>{this.onEvent({kind:"scaled_down_end_failed",pool:this.key(e.region,e.model),sessionId:n.sessionId,reason:h instanceof Error?h.message:String(h)})});return}}static poolKey(e,t){return`${e}:${t}`}async claimSlot(e,t,s){let n=H(e,t,s);if(this.registry===null)return n;for(let r=0;;r++){let o=await this.registry.generation(n),a=H(e,t,s,o),{state:u,sessionId:h,lastReason:d}=await this.registry.record(a);if(u==="none"||u==="paused"&&h===void 0&&d===void 0)try{return await this.registry.mint(a),a}catch(l){this.rethrowUnlessClaimRace(l,r);continue}else{let l=D(a);try{await this.registry.rotate(a,l),await this.registry.mint(l)}catch(c){this.rethrowUnlessClaimRace(c,r);continue}return this.onEvent({kind:"slot_rotated",pool:this.key(e,t),slotKey:a,successor:l,reason:u==="paused"?"boot claim over an evicted slot's dead session":`boot claim over a previous pod's ${u} record`}),l}}}static CLAIM_RACE_VERDICTS=new Set(["reject:double-rotate","reject:generation-monotone","reject:retired-corpse-reuse","reject:mint-queued","reject:mint-attached"]);static CLAIM_RACE_ATTEMPTS=3;rethrowUnlessClaimRace(e,t){if(!(t+1<i.CLAIM_RACE_ATTEMPTS&&e instanceof w&&i.CLAIM_RACE_VERDICTS.has(e.verdict)))throw e}addSession(e,t,s,n){let r=this.poolOf(e,t);r.sessions.push(s),r.lastActivity.set(s,this.now()),r.bornAt.set(s,this.now()),r.slotKeys.set(s.sessionId,n),s.whenLive().then(()=>{s.markLiveSeen().catch(o=>{this.onEvent({kind:"live_mark_failed",pool:this.key(e,t),sessionId:s.sessionId,reason:o instanceof Error?o.message:String(o)})}),this.registryCall("attach",n,()=>this.registry?.attach(n,s.sessionId))}).catch(o=>{this.onEvent({kind:"session_never_live",pool:this.key(e,t),sessionId:s.sessionId,reason:o instanceof Error?o.message:String(o)}),this.evict(r,s,o instanceof Error?o:new Error(String(o)))}),r.offs.set(s,[s.onDocChange(()=>{this.pump(r),this.adoptSettled(r)}),s.onGone(o=>this.evict(r,s,o))]),this.onEvent({kind:"session_added",pool:this.key(e,t),sessionId:s.sessionId}),this.start(r).then(()=>this.pump(r))}async start(e){if(!e.needsReconcile)return;e.needsReconcile=!1;let t=this.key(e.region,e.model);for(let s of await this.journal.inflight()){if(s.request.region!==e.region||s.request.model!==e.model)continue;let n=e.sessions.find(o=>o.sessionId===s.sessionId),r=n?.snapshot().inflight[s.request.request_id];if(n!==void 0){if(r?.status==="done"||r?.status==="error"){await this.journal.finish(s.request.request_id);continue}e.records.set(s.request.request_id,{request:s.request,sink:null,attempt:s.attempt,tried:new Set([s.sessionId]),session:n,phase:"dispatched",streamed:!1,deadlineAt:Number.POSITIVE_INFINITY,queueTimer:null,silenceTimer:null,queuedAt:this.now()}),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:s.request.request_id,sessionId:s.sessionId})}}for(let s of await this.journal.queued(e.region,e.model))await this.journal.finish(s.request_id),this.onEvent({kind:"reconciled_caller_gone",pool:t,requestId:s.request_id});for(let s of e.sessions){let n=s.snapshot();for(let[r,o]of Object.entries(n.inflight)){if(o.status==="done"||o.status==="error"||e.records.has(r))continue;let a={request:{request_id:r,region:e.region,model:e.model,affinity:{},payload:{},streaming:!1,enqueuedAt:0},sink:null,attempt:o.attempt,tried:new Set([s.sessionId]),session:s,phase:"dispatched",streamed:!1,deadlineAt:Number.POSITIVE_INFINITY,queueTimer:null,silenceTimer:null,queuedAt:this.now()};e.records.set(r,a),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:r,sessionId:s.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 s=this.poolOf(e.region,e.model);await this.start(s);let n={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()};s.records.set(e.request_id,n),s.queue.push(n),await this.journal.add(e),t.head(),this.armQueueTimer(s,n),this.onEvent({kind:"enqueued",pool:this.key(e.region,e.model),requestId:e.request_id}),this.pump(s),n.phase!=="finished"&&await new Promise(r=>{n.settle=r})}abandon(){this.closed=!0,this.sweepTimer!==null&&(clearInterval(this.sweepTimer),this.sweepTimer=null);for(let e of this.pools.values()){for(let t of e.records.values())this.clearTimers(t);for(let t of e.offs.values())for(let s of t)s();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 s of e.records.values())this.clearTimers(s),s.phase!=="finished"&&this.settle(s,{status:503,code:"draining",message:"pooler is shutting down",retryAfterSeconds:5});for(let s of e.offs.values())for(let n of s)n();e.offs.clear(),e.lastActivity.clear(),e.bornAt.clear();for(let s of e.slotKeys.values())this.registryCall("rotate",s,()=>this.registry?.rotate(s,D(s)));e.slotKeys.clear();let t=e.sessions.splice(0);await Promise.allSettled(t.map(s=>s.end()))}this.pools.clear()}poolOf(e,t){let s=i.poolKey(e,t),n=this.pools.get(s);return n||(n={region:e,model:t,sessions:[],records:new Map,queue:[],sticky:new Map,radix:new x,offs:new Map,slotKeys:new Map,needsReconcile:!0,lastMintAt:0,minting:!1,mintSeq:0,lastActivity:new Map,bornAt:new Map},this.pools.set(s,n)),n}key(e,t){return i.poolKey(e,t)}registryCall(e,t,s){let n=s();n!==void 0&&n.catch(r=>{this.onEvent({kind:"registry_error",reason:`${e}: ${r instanceof Error?r.message:String(r)}`,slotKey:t})})}creditFor(e,t){let s=t.snapshot(),n=0;for(let r of e.records.values()){if(r.session!==t||r.phase!=="dispatched")continue;let o=s.inflight[r.request.request_id];(o===void 0||o.status===void 0)&&(n+=1)}return Math.max(0,s.freeSlots-n)}backlogOf(e,t){let s=0;for(let n of e.records.values())n.session===t&&n.phase==="dispatched"&&(s+=1);return s}pump(e){if(this.closed)return;let t=!0;for(;t&&e.queue.length>0&&e.sessions.length>0;){t=!1;for(let s=0;s<e.queue.length;s++){let n=e.queue[s],r=this.pickFor(e,n);if(r!==null){e.queue.splice(s,1),this.dispatch(e,r,n),t=!0;break}}}e.queue.length>0&&this.queuePressure(e)&&this.tryMint(e,"queue_pressure")}pickFor(e,t){let s=e.sessions.filter(o=>this.servable(o)&&!t.tried.has(o.sessionId)&&this.creditFor(e,o)>0).map(o=>({sessionId:o.sessionId,backlog:this.backlogOf(e,o)})),n=pe(t.request.affinity,s,e.radix,{backlogThreshold:this.backlogThreshold,sticky:e.sticky});if(n===null)return null;let r=e.sessions.find(o=>o.sessionId===n.sessionId)??null;return r!==null&&this.onEvent({kind:"picked",pool:this.key(e.region,e.model),requestId:t.request.request_id,sessionId:r.sessionId,reason:n.reason}),r}dispatch(e,t,s){s.phase="dispatched",s.session=t,s.tried.add(t.sessionId),e.lastActivity.set(t,this.now()),this.clearTimer(s,"queue"),s.deadlineAt=this.now()+this.silenceDeadlineMs;let n={request_id:s.request.request_id,consumer_id:s.request.request_id,payload:s.request.payload,stream:s.request.streaming};(async()=>{let r=t.reply(n.request_id);try{await t.markInflight(n.request_id,s.attempt),await t.push(n)}catch(u){this.lost(e,s,u);return}await this.journal.dispatched(s.request.request_id,t.sessionId,s.attempt);let o=C(s.request.affinity);e.sticky.set(o,t.sessionId),e.radix.insert(O(s.request.affinity),t.sessionId,this.now()),this.onEvent({kind:"dispatched",pool:this.key(e.region,e.model),requestId:s.request.request_id,sessionId:t.sessionId,attempt:s.attempt}),this.armSilenceTimer(e,s);let a=e.slotKeys.get(t.sessionId);a!==void 0&&this.registryCall("lease",a,()=>this.registry?.lease(a)),this.consume(e,s,r)})()}async consume(e,t,s){if(t.session!==null)try{for await(let n of s){if(t.phase==="finished")return;this.armSilenceTimer(e,t),t.streamed=!0;let r=t.sink;if(r!==null&&(await r.chunk(n),n.t==="response"||n.t==="error"||n.t==="end")){await this.finish(e,t);return}}this.lost(e,t,new b(t.request.request_id,"iterator ended without a terminal chunk"))}catch(n){this.lost(e,t,n)}}lost(e,t,s){if(t.phase==="finished")return;this.clearTimers(t);let n=s instanceof Error?s.message:String(s);this.onEvent({kind:"lost",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt,reason:n}),s instanceof T&&t.session!==null&&this.evict(e,t.session,s);let r=e.sessions.some(o=>this.servable(o)&&!t.tried.has(o.sessionId));if(!t.streamed&&t.attempt<this.maxAttempts&&r){t.attempt+=1,t.phase="queued",t.session=null,t.deadlineAt=this.now()+this.queueDeadlineMs,t.queuedAt=this.now(),e.queue.unshift(t),this.journal.requeue(t.request.request_id,t.attempt).catch(()=>{}),this.armQueueTimer(e,t),this.onEvent({kind:"retry",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt}),this.pump(e);return}this.settle(t,{status:502,code:t.streamed?"upstream_stream_lost":"upstream_error",message:t.streamed?"the upstream reply stream was lost after the response began":"the upstream reply stream was lost before the response began",retryAfterSeconds:1})}async finish(e,t){this.clearTimers(t),t.phase="finished",t.session!==null&&e.lastActivity.set(t.session,this.now()),this.releaseSlot(e,t,"release"),await this.journal.finish(t.request.request_id),t.session!==null&&t.session.clearRequest(t.request.request_id);let s=t.sink;s!==null&&s.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 s=e.session===null?void 0:this.poolOf(e.request.region,e.request.model).slotKeys.get(e.session.sessionId);s!==void 0&&this.registryCall("release",s,()=>this.registry?.release(s)),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 n=e.sink;n!==null&&n.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,s){if(t.session===null)return;let n=e.slotKeys.get(t.session.sessionId);n!==void 0&&this.registryCall(s,n,()=>s==="release"?this.registry?.release(n):this.registry?.detach(n,"session evicted"))}detachSignals(e,t){let s=e.offs.get(t);if(s!==void 0){e.offs.delete(t);for(let n of s)n()}}evict(e,t,s){let n=e.sessions.indexOf(t);if(n===-1)return;e.sessions.splice(n,1),this.detachSignals(e,t),e.lastActivity.delete(t),e.bornAt.delete(t),e.radix.forget(t.sessionId);let r=e.slotKeys.get(t.sessionId);r!==void 0&&(e.slotKeys.delete(t.sessionId),this.registryCall("detach",r,()=>this.registry?.detach(r,s.message)));for(let o of[...e.records.values()])o.session===t&&o.phase!=="finished"&&this.lost(e,o,s)}adoptSettled(e){for(let t of e.sessions){let s=t.snapshot();for(let n of[...e.records.values()]){if(n.sink!==null||n.session!==t)continue;let r=s.inflight[n.request.request_id];(r?.status==="done"||r?.status==="error")&&(this.journal.finish(n.request.request_id).catch(()=>{}),this.release(e,n))}}}armQueueTimer(e,t){this.clearTimer(t,"queue");let s=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))},s),t.queueTimer.unref?.()}armSilenceTimer(e,t){t.silenceTimer===null&&(t.silenceTimer=setTimeout(()=>{t.silenceTimer=null,t.phase==="dispatched"&&this.lost(e,t,new b(t.request.request_id,`silent past ${this.silenceDeadlineMs}ms`))},this.silenceDeadlineMs),t.silenceTimer.unref?.())}clearTimer(e,t){let s=t==="queue"?e.queueTimer:e.silenceTimer;s!==null&&(clearTimeout(s),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(s=>s.phase==="dispatched").length,sessions:t.sessions.length}))}}};m();var Ve="0.0.0.0",Se="serve";var _=(i,e)=>{let t=i[e];if(typeof t!="string"||t==="")throw new Error(`the pooler requires ${e} (external input) \u2014 refusing to start half-configured`);return t},Fe=(i,e)=>{if(i===null||typeof i!="object")throw new Error(`URUN_POOLER_TARGETS[${e}] must be an object`);let t=i,s=a=>{let u=t[a];if(typeof u!="string"||u==="")throw new Error(`URUN_POOLER_TARGETS[${e}].${a} is required`);return u},n=a=>{let u=t[a];if(typeof u!="number"||!Number.isInteger(u))throw new Error(`URUN_POOLER_TARGETS[${e}].${a} must be an integer`);return u},r,o;if(t.sessions!==void 0){let a=t.sessions;if(typeof a!="number"||!Number.isInteger(a)||a<1)throw new Error(`URUN_POOLER_TARGETS[${e}].sessions must be an integer >= 1`);if(t.min!==void 0||t.max!==void 0)throw new Error(`URUN_POOLER_TARGETS[${e}]: give either sessions or {min, max}, never both`);r=a,o=a}else{if(r=n("min"),o=n("max"),r<0)throw new Error(`URUN_POOLER_TARGETS[${e}].min must be >= 0 (0 scales to zero)`);if(o<1)throw new Error(`URUN_POOLER_TARGETS[${e}].max must be >= 1`);if(r>o)throw new Error(`URUN_POOLER_TARGETS[${e}]: min (${String(r)}) must not exceed max (${String(o)})`)}return{region:s("region"),model:s("model"),app:s("app"),fn:typeof t.fn=="string"&&t.fn!==""?t.fn:void 0,min:r,max:o,sharedApp:t.sharedApp===!0}};function Re(i){let e=i.PORT,t=e===void 0||e===""?8080:Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw new Error(`PORT must be a valid port number, got ${String(e)}`);let s=_(i,"URUN_BASE_URL"),n=_(i,"URUN_POOLER_TARGETS"),r;try{r=JSON.parse(n)}catch(o){throw new Error(`URUN_POOLER_TARGETS is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}if(!Array.isArray(r)||r.length===0)throw new Error("URUN_POOLER_TARGETS must be a non-empty JSON array");return{port:t,bindHost:Ve,token:_(i,"URUN_POOLER_TOKEN"),baseUrl:s,apiUrl:i.URUN_API_URL!==void 0&&i.URUN_API_URL!==""?i.URUN_API_URL:`${s}/v1`,orgId:_(i,"URUN_ORG_ID"),apiKey:_(i,"URUN_API_KEY"),valkeyUrl:_(i,"URUN_VALKEY_URL"),laneDocHostUrl:(i.URUN_LANE_DOC_HOST_URL??"").trim()||void 0,laneRuntimeKey:(i.URUN_LANE_RUNTIME_KEY??"").trim()||void 0,targets:r.map(Fe)}}m();import{createServer as Be}from"http";var We="/pooler/v1/inference",Je="/readyz",ze="/metrics",Xe="/pooler/v1/lanes/pick",Qe="/pooler/v1/lanes/status",Ze=1e4,be=16*1024*1024;function f(i,e,t,s,n){i.headersSent||(n!==void 0&&i.setHeader("retry-after",String(n)),i.writeHead(e,{"content-type":"application/json"}),i.end(JSON.stringify({error:{message:t,type:"pooler_error",code:s}})))}function et(i){if(i===null||typeof i!="object")return{reason:"body must be a JSON object"};let e=i;if(typeof e.region!="string"||e.region==="")return{reason:"region is required"};if(typeof e.model!="string"||e.model==="")return{reason:"model is required"};if(typeof e.request_id!="string"||e.request_id==="")return{reason:"request_id is required"};if(e.payload===null||typeof e.payload!="object")return{reason:"payload must be an object"};let t=e.affinity??{};if(t===null||typeof t!="object")return{reason:"affinity must be an object"};let s=t,n=r=>typeof r=="string"&&r!==""?r:void 0;return{value:{streaming:e.streaming===!0,request:{request_id:e.request_id,region:e.region,model:e.model,payload:e.payload,affinity:{promptCacheKey:n(s.promptCacheKey??e.prompt_cache_key),sessionHeader:n(s.sessionHeader??e.session_header),systemPrompt:n(s.systemPrompt),firstMessage:n(s.firstMessage)},streaming:e.streaming===!0,enqueuedAt:Date.now()}}}}var j=class{constructor(e,t,s){this.res=e;this.streaming=t;this.keepaliveMs=s}res;streaming;keepaliveMs;keepalive=null;terminal=null;head(){this.streaming&&!this.res.headersSent&&(this.res.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive"}),this.keepalive=setInterval(()=>{this.res.writableEnded||this.res.write(`: keepalive
|
|
303
303
|
|
|
304
304
|
`)},this.keepaliveMs),this.keepalive.unref?.())}async chunk(e){if(this.streaming){this.res.headersSent||this.head(),this.res.write(`data: ${JSON.stringify(e)}
|
|
305
305
|
|
|
@@ -309,8 +309,8 @@ return 'ok'
|
|
|
309
309
|
|
|
310
310
|
`),this.res.write(`data: [DONE]
|
|
311
311
|
|
|
312
|
-
`),this.res.end()}stopKeepalive(){this.keepalive!==null&&clearInterval(this.keepalive),this.keepalive=null}};function
|
|
312
|
+
`),this.res.end()}stopKeepalive(){this.keepalive!==null&&clearInterval(this.keepalive),this.keepalive=null}};function we(i){return new Promise((e,t)=>{let s=0,n=[];i.on("data",r=>{if(s+=r.length,s>be){t(new Error(`request body exceeds ${be} bytes`)),i.destroy();return}n.push(r)}),i.on("end",()=>e(Buffer.concat(n).toString("utf8"))),i.on("error",t)})}function _e(i){let e=i.keepaliveMs??Ze,t=i.log??(()=>{}),s=Be((n,r)=>{(async()=>{let o=new URL(n.url??"/","http://pooler.internal");if(n.method==="GET"&&o.pathname===Je){r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({ok:!0,...i.pooler.stats()}));return}if(n.method==="GET"&&o.pathname===ze){let d=["# TYPE pooler_pool_queued gauge","# TYPE pooler_pool_inflight gauge","# TYPE pooler_pool_sessions gauge","# TYPE pooler_lane_demand_enqueued counter","# TYPE pooler_lane_demand_reaffirmed counter"];for(let l of i.pooler.stats().pools){let c=`pool="${l.pool}"`;d.push(`pooler_pool_queued{${c}} ${l.queued}`),d.push(`pooler_pool_inflight{${c}} ${l.inflight}`),d.push(`pooler_pool_sessions{${c}} ${l.sessions}`)}for(let l of i.lanePlane?.demandCounters()??[]){let c=`model="${l.model.replaceAll('"','\\"')}"`;d.push(`pooler_lane_demand_enqueued{${c}} ${l.enqueued}`),d.push(`pooler_lane_demand_reaffirmed{${c}} ${l.reaffirmed}`)}r.writeHead(200,{"content-type":"text/plain; version=0.0.4"}),r.end(`${d.join(`
|
|
313
313
|
`)}
|
|
314
|
-
`);return}if(i.lanePlane&&n.method==="GET"&&o.pathname===
|
|
315
|
-
`)},t=new
|
|
314
|
+
`);return}if(i.lanePlane&&n.method==="GET"&&o.pathname===Qe){if(n.headers.authorization!==`Bearer ${i.token}`){f(r,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({pools:await i.lanePlane.status()}));return}if(i.lanePlane&&n.method==="POST"&&o.pathname===Xe){if(n.headers.authorization!==`Bearer ${i.token}`){f(r,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let d;try{d=JSON.parse(await we(n))}catch(p){f(r,400,p instanceof Error?p.message:String(p),"invalid_request");return}let l=d??{};if(typeof l.pool!="string"||l.pool===""){f(r,400,"pool is required","invalid_request");return}let c=l.hold_ms;if(c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<0||c>z)){f(r,400,"hold_ms must be an integer in 0..120000","invalid_request");return}let g=typeof l.model=="string"&&l.model!==""?l.model:void 0;try{let p=await i.lanePlane.pick({pool:l.pool,model:g,holdMs:c??0});if(p.length===0){f(r,503,"no capacity available for this model right now, retry shortly","lane_capacity",2);return}r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({lanes:p.map(P=>({lane_id:P.laneId,host:P.host}))}))}catch(p){t(`[pooler] lane pick for ${l.pool} failed: ${p instanceof Error?p.message:String(p)}`),f(r,500,"the pooler lane plane failed this pick","pooler_error")}return}if(n.method!=="POST"||o.pathname!==We){f(r,404,`no route for ${n.method??""} ${o.pathname}`,"not_found");return}if(n.headers.authorization!==`Bearer ${i.token}`){f(r,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let a;try{a=JSON.parse(await we(n))}catch(d){f(r,400,d instanceof Error?d.message:String(d),"invalid_request");return}let u=et(a);if("reason"in u){f(r,400,u.reason,"invalid_request");return}let h=new j(r,u.value.streaming,e);h.head();try{await i.pooler.submit(u.value.request,h)}catch(d){t(`[pooler] request ${u.value.request.request_id} failed unexpectedly: ${d instanceof Error?d.message:String(d)}`),h.fail({status:500,code:"pooler_error",message:"the pooler failed to serve this request"})}})()});return{server:s,close:()=>new Promise(n=>s.close(()=>n()))}}m();import{App as lt,createClientToken as ut}from"@urun-sh/core";m();import{STREAM_END as st}from"@urun-sh/core";var nt=new Set(["accepted","done","error"]);function rt(i){if(i===null||typeof i!="object")return{};let e=i,t={};for(let[s,n]of Object.entries(e)){let r=n===null||typeof n!="object"?null:n.toJSON;t[s]=typeof r=="function"?r.call(n):n}return t}function it(i){if(i===null||typeof i!="object")return null;let e=i,t=e.status;return t!==void 0&&(typeof t!="string"||!nt.has(t))?null:{attempt:typeof e.attempt=="number"?e.attempt:0,...typeof t=="string"?{status:t}:{},...typeof e.error=="string"?{error:e.error}:{}}}function Pe(i){let e=rt(i.get()),t=Number(e[ye]??0),s={},n=e[$];if(n!==null&&typeof n=="object")for(let[r,o]of Object.entries(n)){let a=it(o);a!==null&&(s[r]=a)}return{freeSlots:Number.isFinite(t)?t:0,inflight:s,liveSeen:e[K]===!0}}function ot(i){if(i===st)return{t:"end"};if(i===null||typeof i!="object")return null;let e=i;return e.t==="delta"?{t:"delta",...typeof e.delta=="string"?{delta:e.delta}:{},...typeof e.reasoning=="string"?{reasoning:e.reasoning}:{},...e.tool_calls!==void 0?{tool_calls:e.tool_calls}:{}}:e.t==="response"||e.t==="error"?{t:e.t,body:e.body??i}:null}async function*at(i,e){let t=i.stream(ge(e)),s=!1;try{for await(let n of t.messages()){let r=ot(n);if(r!==null&&(yield r,r.t!=="delta")){s=!0;return}}}catch(n){throw new b(e,n instanceof Error?n.message:String(n))}if(!s)throw new b(e,"the reply stream ended without a terminal chunk (urun-stream-v1 is at-most-once across a reconnect)")}function ke(i){let{session:e,sessionId:t,goneWatch:s}=i;if(typeof e.whenLive!="function")throw new Error(`pooler session ${t} exposes no whenLive \u2014 a request must never be pushed into a session whose admission is unproven (the cold-wake gate is a contract, not an option)`);if(typeof e.end!="function")throw new Error(`pooler session ${t} exposes no end \u2014 the pooler is the attached client and must be able to release it`);if(typeof e.cancel!="function")throw new Error(`pooler session ${t} exposes no cancel \u2014 the pooler's never-live eviction requires the admission-ticket cancel verb`);if(typeof e.phase!="object"||e.phase===null||typeof e.phase.name!="string")throw new Error(`pooler session ${t} exposes no phase surface \u2014 the servability probe reads core's own phase name live, and a wrapper must never fabricate one`);let n=()=>e.doc(fe),r=!1;return"onPhase"in e&&typeof e.onPhase=="function"&&e.onPhase(o=>{o.name==="live"&&(r=!0)}),{sessionId:t,snapshot:()=>Pe(n()),onDocChange:o=>n().on("change",()=>o()),onGone:o=>s.onGone(o),gone:()=>s.gone(),phaseName:()=>(e.phase.name==="live"&&(r=!0),e.phase.name),everLive:()=>r||Pe(n()).liveSeen,markLiveSeen:async()=>{await Y(n(),15e3,"the durable live-seen mark"),n().set({[K]:!0})},whenLive:o=>e.whenLive(o),markInflight:(o,a)=>(n().set({[$]:{[o]:{attempt:a}}}),Promise.resolve()),push:o=>(n().set({[U]:{[o.request_id]:{...o.payload,request_id:o.request_id,consumer_id:o.consumer_id,stream:o.stream}}}),Promise.resolve()),clearRequest:o=>{try{n().set({[U]:{[o]:null}})}catch{}return Promise.resolve()},reply:o=>at(e,o),end:async()=>{await e.end(),s.dispose()},cancel:async()=>{await e.cancel(),s.dispose()},namedSessionId:()=>typeof e.namedSessionId=="function"?e.namedSessionId():void 0}}function Te(i){return async(e,t)=>{let s=e.fn??Se,n=lt(e.app,{baseUrl:i.baseUrl,orgId:i.orgId,getAccessToken:async()=>(await ut(i.apiKey,{baseUrl:i.baseUrl,expiresIn:300,allowedFunctions:[`${e.app}/${s}`],bindPrincipal:!0,...e.sharedApp?{sharedApp:!0}:{}})).token}),r=n[s];if(typeof r!="function")throw new Error(`app "${e.app}" has no function "${s}" \u2014 the pooler cannot dial a slot for it`);let o={concurrencyKey:t,...e.sharedApp?{sharedApp:!0}:{}},a=r.call(n,void 0,o);if(a===null||typeof a!="object")throw new Error(`app "${e.app}" function "${s}" returned no session`);let u=a;return ke({session:u,sessionId:t,goneWatch:F(u,t,{armOnFirstSync:!0})})}}function vt(){let i=null;i=V({streams:S,note:e=>{i?.isDead("stderr")!==!0&&I(S.stderr,e)}})}async function Et(){vt();let i=Re(S.env),e=l=>{I(S.stdout,`${l}
|
|
315
|
+
`)},t=new yt(i.valkeyUrl,{maxRetriesPerRequest:null}),s=new A({eval:(l,c,g)=>t.eval(l,c.length,...c,...g)},"pooler"),n=Te(i),r=new L({journal:new q,registry:s,queueDeadlineMs:6e4,silenceDeadlineMs:33e4,backlogThreshold:8,mint:(l,c,g)=>{let p=i.targets.find(P=>P.region===l&&P.model===c);return p===void 0?Promise.reject(new Error(`no pooler target for ${l}:${c} \u2014 refusing to mint`)):n(p,g)},limits:i.targets.map(({region:l,model:c,min:g,max:p})=>({region:l,model:c,min:g,max:p})),scaleUpWaitMs:5e3,mintCooldownMs:1e4,sessionIdleTtlMs:6e4,idleSweepMs:5e3,onEvent:l=>{Ee.has(l.kind)&&e(`[pooler] ${l.kind} ${JSON.stringify(l)}`)}});await r.warm();let o=i.laneRuntimeKey,a=i.laneDocHostUrl===void 0?void 0:X({docHostUrl:i.laneDocHostUrl,redis:t,...o?{mintRuntimeToken:l=>J(l,i.orgId,o,W,B)}:{}}),{server:u,close:h}=_e({pooler:r,token:i.token,lanePlane:a,log:e});await new Promise((l,c)=>{u.once("error",c),u.listen(i.port,i.bindHost,()=>l())}),e(`urun-pooler listening on http://${i.bindHost}:${i.port} (targets ${i.targets.map(l=>`${l.region}:${l.model} min=${l.min} max=${l.max}`).join(", ")})${a===void 0?"":" lanes=on"}`);let d=async l=>{e(`urun-pooler: ${l} \u2014 draining`),await h(),await r.close(),await a?.close(),await t.quit().catch(()=>{})};await new Promise(l=>{S.once("SIGINT",()=>{d("SIGINT").finally(l)}),S.once("SIGTERM",()=>{d("SIGTERM").finally(l)})})}Et().then(()=>S.exit(0),i=>{I(S.stderr,`urun-pooler failed: ${i instanceof Error?`${i.name}: ${i.message}`:String(i)}
|
|
316
316
|
`),S.exit(1)});
|