@urun-sh/openai 0.6.43 → 0.6.44

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 (58) hide show
  1. package/dist/{ResponsesClient-2EsjJUz1.d.ts → ResponsesClient-75VdSOY-.d.ts} +1 -1
  2. package/dist/{ResponsesClient-BIcQ6p6Z.d.cts → ResponsesClient-BJDe9EBw.d.cts} +1 -1
  3. package/dist/chunk-64VO62LW.js +1 -0
  4. package/dist/chunk-7KRHHEKZ.js +1 -0
  5. package/dist/chunk-BA3NCMS5.js +6 -0
  6. package/dist/chunk-DMRZZTYI.js +4 -0
  7. package/dist/chunk-FNAZ2XBE.js +20 -0
  8. package/dist/chunk-G6AFKOVS.js +1 -0
  9. package/dist/{chunk-FF3RWDFM.js → chunk-HB5KNEY5.js} +1 -1
  10. package/dist/{chunk-ZCF6EV4Y.js → chunk-VQSCBUKT.js} +20 -19
  11. package/dist/{chunk-JMSVHETI.js → chunk-X5BLQXHK.js} +1 -1
  12. package/dist/chunk-XNRPTMSL.js +1 -0
  13. package/dist/chunk-Y774TOE7.js +2 -0
  14. package/dist/{composite-BoS9-74g.d.cts → composite-DM2sT1Sp.d.cts} +1 -1
  15. package/dist/{composite-D4_XPSas.d.ts → composite-DNNAm0PY.d.ts} +1 -1
  16. package/dist/gemini-live.cjs +2 -2
  17. package/dist/gemini-live.d.cts +4 -4
  18. package/dist/gemini-live.d.ts +4 -4
  19. package/dist/gemini-live.js +1 -1
  20. package/dist/hosted/bin.cjs +48 -47
  21. package/dist/hosted/bin.js +1 -1
  22. package/dist/hosted/index.cjs +43 -42
  23. package/dist/hosted/index.d.cts +4 -4
  24. package/dist/hosted/index.d.ts +4 -4
  25. package/dist/hosted/index.js +1 -1
  26. package/dist/index.cjs +1 -1
  27. package/dist/index.d.cts +4 -4
  28. package/dist/index.d.ts +4 -4
  29. package/dist/index.js +1 -1
  30. package/dist/pi-extension/index.cjs +7 -7
  31. package/dist/pi-extension/index.d.cts +2 -2
  32. package/dist/pi-extension/index.d.ts +2 -2
  33. package/dist/pi-extension/index.js +1 -1
  34. package/dist/pi-extension/standalone.cjs +41 -41
  35. package/dist/pooler/bin.cjs +25 -25
  36. package/dist/pooler/bin.js +24 -24
  37. package/dist/proxy/cli.cjs +48 -47
  38. package/dist/proxy/cli.js +1 -1
  39. package/dist/proxy/conformance-probe.js +1 -1
  40. package/dist/proxy/index.cjs +19 -18
  41. package/dist/proxy/index.d.cts +5 -5
  42. package/dist/proxy/index.d.ts +5 -5
  43. package/dist/proxy/index.js +1 -1
  44. package/dist/{translator-PsmsZT62.d.cts → translator-C6MpaZS-.d.cts} +1 -1
  45. package/dist/{translator-BemK1Of5.d.ts → translator-CaOqL-V8.d.ts} +1 -1
  46. package/dist/{types-CxWQ84Ew.d.cts → types-DiYzfHYN.d.cts} +2 -5
  47. package/dist/{types-CxWQ84Ew.d.ts → types-DiYzfHYN.d.ts} +1 -1
  48. package/dist/{video-out-DPLqpGbQ.d.cts → video-out-A8qMuI36.d.cts} +1 -1
  49. package/dist/{video-out-DkMqKSOi.d.ts → video-out-IoTqIbAw.d.ts} +1 -1
  50. package/package.json +1 -1
  51. package/dist/chunk-27HP3RMZ.js +0 -6
  52. package/dist/chunk-2NKCALKY.js +0 -22
  53. package/dist/chunk-2RO722HS.js +0 -2
  54. package/dist/chunk-7DUSLXPG.js +0 -1
  55. package/dist/chunk-BFIKVTQB.js +0 -1
  56. package/dist/chunk-GDH2D3S6.js +0 -1
  57. package/dist/chunk-MOX5FG2R.js +0 -1
  58. package/dist/chunk-YRBUHHI3.js +0 -2
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as Me}from"../chunk-LM4E5YM2.js";import{a as Q,b as Z,c as ee,d as te}from"../chunk-YRBUHHI3.js";import{a as X}from"../chunk-MJSK6W3W.js";import{s as N,t as z}from"../chunk-27HP3RMZ.js";import{a as J,b as W}from"../chunk-7DUSLXPG.js";import{j as q}from"../chunk-J3KCHTSA.js";import{b as Oe,c as p}from"../chunk-YSFSRI3D.js";p();var as=Oe(Me(),1);import R from"process";import{Redis as wt}from"ioredis";p();p();var $=`
2
+ import{a as Ce}from"../chunk-LM4E5YM2.js";import{a as te,b as ne,c as se,d as re}from"../chunk-Y774TOE7.js";import{a as X}from"../chunk-MJSK6W3W.js";import{c as W,v as N,w as z}from"../chunk-BA3NCMS5.js";import{a as Q,b as Z,d as ee}from"../chunk-XNRPTMSL.js";import{a as J}from"../chunk-7KRHHEKZ.js";import{j as q}from"../chunk-J3KCHTSA.js";import{b as Ge,c as p}from"../chunk-YSFSRI3D.js";p();var mn=Ge(Ce(),1);import b from"process";import{Redis as kt}from"ioredis";p();p();var D=`
3
3
  local slot, retired, meta, idx = KEYS[1], KEYS[2], KEYS[3], KEYS[4]
4
4
  local key, gen, now = ARGV[1], tonumber(ARGV[2]), ARGV[3]
5
5
  -- The session-as-routing-identity schema (docs/pooler-session-registry.md
@@ -39,7 +39,7 @@ end
39
39
  redis.call('HINCRBY', meta, 'queued', 1)
40
40
  redis.call('SADD', idx, key)
41
41
  return 'ok'
42
- `,D=`
42
+ `,$=`
43
43
  local slot, genkey, retired, meta = KEYS[1], KEYS[2], KEYS[3], KEYS[4]
44
44
  local key, gen, sessionId, now = ARGV[1], tonumber(ARGV[2]), ARGV[3], ARGV[4]
45
45
  -- The session-registry schema (\xA72.3): ARGV[5] is the caller's OBSERVED
@@ -81,7 +81,7 @@ redis.call('HSET', slot, 'state', 'attached', 'sessionId', sessionId, 'since', n
81
81
  redis.call('HINCRBY', meta, 'queued', -1)
82
82
  redis.call('HINCRBY', meta, 'attached', 1)
83
83
  return 'ok'
84
- `,se=`
84
+ `,ie=`
85
85
  local slot, meta = KEYS[1], KEYS[2]
86
86
  local key, reason, now = ARGV[1], ARGV[2], ARGV[3]
87
87
  local state = redis.call('HGET', slot, 'state')
@@ -95,7 +95,7 @@ redis.call('HSET', slot, 'state', 'paused', 'since', now, 'lastReason', reason)
95
95
  redis.call('HINCRBY', meta, state, -1)
96
96
  redis.call('HINCRBY', meta, 'paused', 1)
97
97
  return 'ok'
98
- `,ne=`
98
+ `,oe=`
99
99
  local slot, genkey, retired, meta, newslot, idx = KEYS[1], KEYS[2], KEYS[3], KEYS[4], KEYS[5], KEYS[6]
100
100
  local oldKey, newKey, newGen = ARGV[1], ARGV[2], tonumber(ARGV[3])
101
101
  if redis.call('SISMEMBER', retired, oldKey) == 1 then
@@ -121,7 +121,7 @@ if redis.call('HSETNX', newslot, 'state', 'paused') == 1 then
121
121
  end
122
122
  redis.call('SADD', idx, newKey)
123
123
  return 'ok'
124
- `,re=`
124
+ `,ae=`
125
125
  local slot, meta = KEYS[1], KEYS[2]
126
126
  local key, now = ARGV[1], ARGV[2]
127
127
  local state = redis.call('HGET', slot, 'state')
@@ -142,7 +142,7 @@ redis.call('HSET', slot, 'state', 'ended', 'since', now)
142
142
  redis.call('HINCRBY', meta, state, -1)
143
143
  redis.call('HINCRBY', meta, 'ended', 1)
144
144
  return 'ok'
145
- `,ie=`
145
+ `,le=`
146
146
  local slot, meta = KEYS[1], KEYS[2]
147
147
  local key = ARGV[1]
148
148
  local state = redis.call('HGET', slot, 'state')
@@ -192,12 +192,12 @@ end
192
192
  redis.call('HINCRBY', slot, 'inFlight', 1)
193
193
  redis.call('HINCRBY', meta, 'inflight', 1)
194
194
  return 'ok'
195
- `,oe=`
195
+ `,ue=`
196
196
  local meta = KEYS[1]
197
197
  return (redis.call('HGET', meta, 'max') or '-1')
198
198
  .. '|' .. (redis.call('HGET', meta, 'cap') or '-1')
199
199
  .. '|' .. (redis.call('HGET', meta, 'config_version') or '0')
200
- `,ae=`
200
+ `,de=`
201
201
  local slot, meta = KEYS[1], KEYS[2]
202
202
  local key, now = ARGV[1], ARGV[2]
203
203
  local state = redis.call('HGET', slot, 'state')
@@ -214,7 +214,7 @@ end
214
214
  redis.call('HSET', slot, 'inFlight', f - 1, 'idleSince', now)
215
215
  redis.call('HINCRBY', meta, 'inflight', -1)
216
216
  return 'ok'
217
- `,le=`
217
+ `,ce=`
218
218
  local meta = KEYS[1]
219
219
  local max, cap = tonumber(ARGV[1]), tonumber(ARGV[2])
220
220
  if not max or max < 0 or not cap or cap < 1 then
@@ -223,7 +223,7 @@ end
223
223
  redis.call('HSET', meta, 'max', max, 'cap', cap)
224
224
  redis.call('HINCRBY', meta, 'config_version', 1)
225
225
  return 'ok'
226
- `,ue=`
226
+ `,he=`
227
227
  local meta = KEYS[1]
228
228
  local max, cap = tonumber(ARGV[1]), tonumber(ARGV[2])
229
229
  if not max or max < 0 or not cap or cap < 1 then
@@ -234,7 +234,7 @@ if redis.call('HSETNX', meta, 'max', max) == 0 then
234
234
  end
235
235
  redis.call('HSET', meta, 'cap', cap)
236
236
  return 'ok'
237
- `,de=`
237
+ `,me=`
238
238
  local prefix, idx, meta = ARGV[1], KEYS[1], KEYS[2]
239
239
  local cursor, pageSize = ARGV[2], tonumber(ARGV[3])
240
240
  local res = redis.call('SSCAN', idx, cursor, 'COUNT', pageSize)
@@ -254,29 +254,29 @@ for i = 1, #fields, 2 do
254
254
  m[#m + 1] = fields[i] .. '=' .. (fields[i + 1] or '')
255
255
  end
256
256
  return next .. '#' .. table.concat(m, ',') .. '#' .. table.concat(lines, '\\n')
257
- `,ce=`
257
+ `,pe=`
258
258
  local fields = redis.call('HGETALL', KEYS[1])
259
259
  local m = {}
260
260
  for i = 1, #fields, 2 do
261
261
  m[#m + 1] = fields[i] .. '=' .. (fields[i + 1] or '')
262
262
  end
263
263
  return table.concat(m, ',')
264
- `,he=`
264
+ `,fe=`
265
265
  local out = {}
266
266
  for i = 1, #ARGV do
267
267
  out[#out + 1] = (redis.call('HGET', ARGV[i], 'state') or 'none')
268
268
  .. '|' .. (redis.call('HGET', ARGV[i], 'inFlight') or '0')
269
269
  end
270
270
  return table.concat(out, '\\n')
271
- `,me=`
271
+ `,ge=`
272
272
  local gen = redis.call('GET', KEYS[1])
273
273
  if not gen then return '0' end
274
274
  return gen
275
- `,pe=`
275
+ `,ye=`
276
276
  local state = redis.call('HGET', KEYS[1], 'state')
277
277
  if not state then return 'none||' end
278
278
  return state .. '|' .. (redis.call('HGET', KEYS[1], 'sessionId') or '') .. '|' .. (redis.call('HGET', KEYS[1], 'lastReason') or '')
279
- `,fe=`
279
+ `,ve=`
280
280
  local slot = KEYS[1]
281
281
  local key, obsEpoch = ARGV[1], tonumber(ARGV[2])
282
282
  local state = redis.call('HGET', slot, 'state')
@@ -296,20 +296,20 @@ redis.call('HSET', slot,
296
296
  'cacheGen', ARGV[5],
297
297
  'capabilities', ARGV[6])
298
298
  return 'ok'
299
- `;var T=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},Le=100,ge=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},Ge=i=>(i===""?[]:i.split(`
300
- `)).map(e=>{let[t,s,n,r,o]=e.split("|");return{key:t,state:s,inFlight:Number(n),gen:Number(r),sessionId:o}});function w(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 _=()=>String(Date.now()),x=class{constructor(e,t){this.evalFn=e;this.pool=t}evalFn;pool;keys(e,t=!0,s=!0){let{base:n}=w(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 T(e,o,{pool:this.pool,...r})}idxKey(){return`sreg:${this.pool}:idx`}mint(e){let{gen:t}=w(e);return this.run("mint",$,[...this.keys(e,!1,!0),this.idxKey()],[e,t,_()],{slotKey:e,gen:t})}mintWith(e,t){let{gen:s}=w(e);return this.run("mint",$,[...this.keys(e,!1,!0),this.idxKey()],[e,s,_(),t.model,t.capabilities??"",t.cacheNs],{slotKey:e,gen:s,cacheNs:t.cacheNs})}attachWithEpoch(e,t,s){let{gen:n}=w(e);return this.run("attach",D,this.keys(e),[e,n,t,_(),s],{slotKey:e,gen:n,sessionId:t,observedEpoch:s})}publish(e,t,s){return this.run("publish",fe,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}=w(e);return this.run("attach",D,this.keys(e),[e,s,t,_()],{slotKey:e,gen:s,sessionId:t})}detach(e,t){return this.run("detach",se,this.keys(e,!1,!1),[e,t,_()],{slotKey:e,reason:t})}rotate(e,t){let{gen:s}=w(t),n=[...this.keys(e),`sreg:${this.pool}:slot:${t}`,this.idxKey()];return this.run("rotate",ne,n,[e,t,s,_()],{oldKey:e,newKey:t,newGen:s})}end(e){return this.run("end",re,this.keys(e,!1,!1),[e,_()],{slotKey:e})}lease(e){return this.run("lease",ie,this.keys(e,!1,!1),[e],{slotKey:e})}release(e){return this.run("release",ae,this.keys(e,!1,!1),[e,_()],{slotKey:e})}configure(e,t){return this.run("config",ue,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}retune(e,t){return this.run("retune",le,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}async tuning(){let e=await this.evalFn.eval(oe,[`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(A,s,[e,t.cap,t.configVersion]);if(n==="reject:cap-moved"){let r=await this.tuning();n=await this.evalFn.eval(A,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 T("grant",n,{pool:this.pool,slotKey:e})}async grantWithEpoch(e,t){let s=this.keys(e,!1,!1),n=await this.evalFn.eval(A,s,[e,t.cap,t.configVersion,t.epoch]);if(n==="reject:cap-moved"){let r=await this.tuning();n=await this.evalFn.eval(A,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 T("grant",n,{pool:this.pool,slotKey:e})}async snapshot(){let e=[],t=null,s="0";do{let n=await this.snapshotPage(s,Le);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(ce,[`sreg:${this.pool}:meta`],[]);return ge(e)}async snapshotPage(e,t){let s=`sreg:${this.pool}:slot:`,n=await this.evalFn.eval(de,[this.idxKey(),`sreg:${this.pool}:meta`],[s,e,t]),[r,o,l]=n.split("#");return{cursor:r,counts:ge(o??""),slots:Ge(l??"")}}async readRecords(e){if(e.length===0)return[];let t=`sreg:${this.pool}:slot:`,s=await this.evalFn.eval(he,[],e.map(n=>t+n));return(s===""?[]:s.split(`
301
- `)).map(n=>{let[r,o]=n.split("|");return{state:r,inFlight:Number(o)}})}async generation(e){let{base:t}=w(e),s=await this.evalFn.eval(me,[`sreg:${this.pool}:gen:${t}`],[]);return Number(s)}async record(e){let s=(await this.evalFn.eval(pe,[`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}}};p();var O=class{records=new Map;add(e){return this.records.set(e.request_id,{request:e,sessionId:"",attempt:1,dispatched:!1}),Promise.resolve()}dispatched(e,t,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})))}};p();p();var G=i=>`${i.systemPrompt??""}\0${i.firstMessage??""}`;function K(i){return i.promptCacheKey!==void 0&&i.promptCacheKey!==""?`k:${i.promptCacheKey}`:i.sessionHeader!==void 0&&i.sessionHeader!==""?`h:${i.sessionHeader}`:`p:${Ce(G(i))}`}function Ce(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 ye=512,He=4096,M=8,L=class{root={children:new Map,sessions:new Map};nodes=1;insert(e,t,s){let n=e.slice(0,ye),r=this.root;for(let o=0;o<n.length;o+=M){let l=n.slice(o,o+M),d=r.children.get(l);if(!d){if(this.nodes>=He)return;d={children:new Map,sessions:new Map},r.children.set(l,d),this.nodes+=1}d.sessions.set(t,s),r=d}}match(e,t){let s=e.slice(0,ye),n=this.root,r=null,o=0,l=0;for(;;){let d=null,c=-1;for(let[h,f]of n.sessions)t.has(h)&&(f>c||f===c&&d!==null&&h<d)&&(d=h,c=f);if(d!==null&&(r={sessionId:d,depth:o}),l>=s.length)break;let u=s.slice(l,l+M),a=n.children.get(u);if(!a)break;n=a,o+=u.length,l+=M}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 ve(i,e,t,s){if(e.length===0)return null;let n=new Map(e.map(u=>[u.sessionId,u])),r=u=>{let a=n.get(u);return a!==void 0&&a.backlog<s.backlogThreshold},o=new Set(n.keys()),l=s.sticky.get(K(i));if(l!==void 0&&r(l))return{sessionId:l,reason:"sticky"};let d=t.match(G(i),o);if(d!==null&&r(d.sessionId))return{sessionId:d.sessionId,reason:"prefix"};let c=null;for(let u of e)(c===null||u.backlog<c.backlog||u.backlog===c.backlog&&u.sessionId<c.sessionId)&&(c=u);return c===null?null:{sessionId:c.sessionId,reason:"load"}}p();var Ee="llm",Se="requests",Ue="llm-resp",j=(i,e,t,s=0)=>`decision:pooler-${i}-${e}`.replaceAll(":","-")+`:${t}`+(s>0?`:${s}`:""),Y=i=>{let{base:e,gen:t}=w(i);return`${e}:${t+1}`},be=i=>`${Ue}:${i}`,we="free_slots",V="inflight",F="live_seen",P=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 _e=new Set(["registry_error","failed","mint_failed","scaled_down","live_mark_failed","never_live_evicted","never_live_end_failed"]),$e=6e4,De=33e4,Ke=2,je=8,Ye=5e3,Ve=1e4,Fe=6e4,Be=5e3,Je=36e5,We={provisioning:!0,waiting_for_capacity:!0,connecting:!0},Re={idle:"bound",queued:"bound",unavailable:"bound",provisioning:"bound",waiting_for_capacity:"bound",connecting:"bound",live:"bound",degraded:"bound",paused:"unbound",error:"unbound",unknown:"unbound"},C=class i{pools=new Map;now;queueDeadlineMs;silenceDeadlineMs;maxAttempts;backlogThreshold;mint;limits;scaleUpWaitMs;mintCooldownMs;sessionIdleTtlMs;idleSweepMs;neverLiveEvictAfterMs;journal;registry;onEvent;closed=!1;sweepTimer=null;constructor(e){this.journal=e.journal,this.registry=e.registry??null,this.now=e.now??Date.now,this.queueDeadlineMs=e.queueDeadlineMs??$e,this.silenceDeadlineMs=e.silenceDeadlineMs??De,this.maxAttempts=e.maxAttempts??Ke,this.backlogThreshold=e.backlogThreshold??je,this.mint=e.mint,this.limits=e.limits??[],this.scaleUpWaitMs=e.scaleUpWaitMs??Ye,this.mintCooldownMs=e.mintCooldownMs??Ve,this.sessionIdleTtlMs=e.sessionIdleTtlMs??Fe,this.idleSweepMs=e.idleSweepMs??Be,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:Re[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 q(`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(Re[r]!=="bound"||!We[r])continue;let o=e.bornAt.get(n);if(o===void 0||s-o<t)continue;let l=e.sessions.indexOf(n);if(l===-1)continue;e.sessions.splice(l,1),this.detachSignals(e,n),e.radix.forget(n.sessionId),e.lastActivity.delete(n),e.bornAt.delete(n);let d=e.slotKeys.get(n.sessionId);d!==void 0&&(e.slotKeys.delete(n.sessionId),this.registryCall("end",d,()=>this.registry?.end(d))),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(u=>{this.onEvent({kind:"never_live_end_failed",pool:this.key(e.region,e.model),sessionId:n.sessionId,reason:u instanceof Error?u.message:String(u)})})}}limitsFor(e){return this.limits.find(t=>t.region===e.region&&t.model===e.model)??null}queuePressure(e){if(e.queue.length===0)return!1;let t=this.now();return e.queue.some(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(c=>c.session===n&&c.phase==="dispatched")||s-(e.lastActivity.get(n)??s)<this.sessionIdleTtlMs)continue;let l=e.sessions.indexOf(n);if(l===-1)continue;e.sessions.splice(l,1),this.detachSignals(e,n),e.radix.forget(n.sessionId),e.lastActivity.delete(n),e.bornAt.delete(n);let d=e.slotKeys.get(n.sessionId);d!==void 0&&(e.slotKeys.delete(n.sessionId),this.registryCall("end",d,()=>this.registry?.end(d))),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(c=>{this.onEvent({kind:"scaled_down_end_failed",pool:this.key(e.region,e.model),sessionId:n.sessionId,reason:c instanceof Error?c.message:String(c)})});return}}static poolKey(e,t){return`${e}:${t}`}async claimSlot(e,t,s){let n=j(e,t,s);if(this.registry===null)return n;for(let r=0;;r++){let o=await this.registry.generation(n),l=j(e,t,s,o),{state:d,sessionId:c,lastReason:u}=await this.registry.record(l);if(d==="none"||d==="paused"&&c===void 0&&u===void 0)try{return await this.registry.mint(l),l}catch(a){this.rethrowUnlessClaimRace(a,r);continue}else{let a=Y(l);try{await this.registry.rotate(l,a),await this.registry.mint(a)}catch(h){this.rethrowUnlessClaimRace(h,r);continue}return this.onEvent({kind:"slot_rotated",pool:this.key(e,t),slotKey:l,successor:a,reason:d==="paused"?"boot claim over an evicted slot's dead session":`boot claim over a previous pod's ${d} record`}),a}}}static CLAIM_RACE_VERDICTS=new Set(["reject:double-rotate","reject:generation-monotone","reject:retired-corpse-reuse","reject:mint-queued","reject:mint-attached"]);static CLAIM_RACE_ATTEMPTS=3;rethrowUnlessClaimRace(e,t){if(!(t+1<i.CLAIM_RACE_ATTEMPTS&&e instanceof T&&i.CLAIM_RACE_VERDICTS.has(e.verdict)))throw e}addSession(e,t,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:void 0,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 l={request:{request_id:r,region:e.region,model:e.model,affinity:{},payload:{},streaming:!1,enqueuedAt:0},sink:null,attempt:o.attempt,tried:new Set([s.sessionId]),session:s,phase:"dispatched",streamed:!1,deadlineAt:Number.POSITIVE_INFINITY,queueTimer:null,silenceTimer:void 0,queuedAt:this.now()};e.records.set(r,l),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:r,sessionId: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:void 0,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,Y(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 L,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=ve(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(d){this.lost(e,s,d);return}await this.journal.dispatched(s.request.request_id,t.sessionId,s.attempt);let o=K(s.request.affinity);e.sticky.set(o,t.sessionId),e.radix.insert(G(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 l=e.slotKeys.get(t.sessionId);l!==void 0&&this.registryCall("lease",l,()=>this.registry?.lease(l)),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 P(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 q&&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){clearTimeout(t.silenceTimer),t.silenceTimer=setTimeout(()=>{t.silenceTimer=void 0,t.phase==="dispatched"&&this.lost(e,t,new P(t.request.request_id,`silent past ${this.silenceDeadlineMs}ms`))},this.silenceDeadlineMs),t.silenceTimer.unref?.()}clearTimer(e,t){let s=t==="queue"?e.queueTimer:e.silenceTimer;s!==null&&(clearTimeout(s),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(s=>s.phase==="dispatched").length,sessions:t.sessions.length}))}}};p();var ze="0.0.0.0",Pe="serve";var I=(i,e)=>{let t=i[e];if(typeof t!="string"||t==="")throw new Error(`the pooler requires ${e} (external input) \u2014 refusing to start half-configured`);return t},Xe=(i,e)=>{if(i===null||typeof i!="object")throw new Error(`URUN_POOLER_TARGETS[${e}] must be an object`);let t=i,s=c=>{let u=t[c];if(typeof u!="string"||u==="")throw new Error(`URUN_POOLER_TARGETS[${e}].${c} is required`);return u},n=c=>{let u=t[c];if(typeof u!="number"||!Number.isInteger(u))throw new Error(`URUN_POOLER_TARGETS[${e}].${c} must be an integer`);return u},r,o;if(t.sessions!==void 0){let c=t.sessions;if(typeof c!="number"||!Number.isInteger(c)||c<1)throw new Error(`URUN_POOLER_TARGETS[${e}].sessions must be an integer >= 1`);if(t.min!==void 0||t.max!==void 0)throw new Error(`URUN_POOLER_TARGETS[${e}]: give either sessions or {min, max}, never both`);r=c,o=c}else{if(r=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)})`)}let l,d;if((t.lanePool!==void 0||t.laneMin!==void 0)&&(l=s("lanePool"),d=n("laneMin"),d<0))throw new Error(`URUN_POOLER_TARGETS[${e}].laneMin must be >= 0`);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,...l!==void 0?{lanePool:l,laneMin:d}:{}}};function ke(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(i,"URUN_BASE_URL"),n=I(i,"URUN_POOLER_TARGETS"),r;try{r=JSON.parse(n)}catch(l){throw new Error(`URUN_POOLER_TARGETS is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!Array.isArray(r)||r.length===0)throw new Error("URUN_POOLER_TARGETS must be a non-empty JSON array");let o=(i.URUN_LANE_DOC_HOST_URL??"").trim()||void 0;return{port:t,bindHost:ze,token:I(i,"URUN_POOLER_TOKEN"),baseUrl:s,apiUrl:i.URUN_API_URL!==void 0&&i.URUN_API_URL!==""?i.URUN_API_URL:`${s}/v1`,orgId:I(i,"URUN_ORG_ID"),apiKey:I(i,"URUN_API_KEY"),valkeyUrl:I(i,"URUN_VALKEY_URL"),laneDocHostUrl:o,targets:r.map(Xe)}}p();import{createServer as Qe}from"http";var Ze="/pooler/v1/inference",et="/readyz",tt="/metrics",st="/pooler/v1/lanes/pick",nt="/pooler/v1/lanes/status",rt=1e4,Te=16*1024*1024;function g(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 it(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 B=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
299
+ `;var T=class extends Error{constructor(t,n,s){super(`session registry violation (${t}): ${n} ${JSON.stringify(s)}`);this.op=t;this.verdict=n;this.context=s;this.name="RegistryViolation"}op;verdict;context},Ue=100,Ee=i=>{let e={attached:0,queued:0,paused:0,retired:0,ended:0,inflight:0};for(let t of i.split(",")){if(t==="")continue;let[n,s]=t.split("=");n in e&&(e[n]=Number(s))}return e},He=i=>(i===""?[]:i.split(`
300
+ `)).map(e=>{let[t,n,s,r,o]=e.split("|");return{key:t,state:n,inFlight:Number(s),gen:Number(r),sessionId:o}});function R(i){let e=i.split(":"),t=e[e.length-1],n=e[e.length-2];if(n!==void 0&&/^\d+$/.test(n)&&/^\d+$/.test(t))return{base:e.slice(0,-1).join(":"),index:Number(n),gen:Number(t)};if(!/^\d+$/.test(t))throw new Error(`session registry: malformed slot key "${i}" (expected decision:{replica}:{index}[:{gen}])`);return{base:i,index:Number(t),gen:0}}var _=()=>String(Date.now()),x=class{constructor(e,t){this.evalFn=e;this.pool=t}evalFn;pool;keys(e,t=!0,n=!0){let{base:s}=R(e),r=[`sreg:${this.pool}:slot:${e}`];return t&&r.push(`sreg:${this.pool}:gen:${s}`),n&&r.push(`sreg:${this.pool}:retired`),r.push(`sreg:${this.pool}:meta`),r}async run(e,t,n,s,r){let o=await this.evalFn.eval(t,n,s);if(o.startsWith("reject:"))throw new T(e,o,{pool:this.pool,...r})}idxKey(){return`sreg:${this.pool}:idx`}mint(e){let{gen:t}=R(e);return this.run("mint",D,[...this.keys(e,!1,!0),this.idxKey()],[e,t,_()],{slotKey:e,gen:t})}mintWith(e,t){let{gen:n}=R(e);return this.run("mint",D,[...this.keys(e,!1,!0),this.idxKey()],[e,n,_(),t.model,t.capabilities??"",t.cacheNs],{slotKey:e,gen:n,cacheNs:t.cacheNs})}attachWithEpoch(e,t,n){let{gen:s}=R(e);return this.run("attach",$,this.keys(e),[e,s,t,_(),n],{slotKey:e,gen:s,sessionId:t,observedEpoch:n})}publish(e,t,n){return this.run("publish",ve,this.keys(e,!1,!1),[e,t,n.maxConcurrent,n.queueDepth,n.cacheGen,n.capabilities??""],{slotKey:e,observedEpoch:t})}attach(e,t){let{gen:n}=R(e);return this.run("attach",$,this.keys(e),[e,n,t,_()],{slotKey:e,gen:n,sessionId:t})}detach(e,t){return this.run("detach",ie,this.keys(e,!1,!1),[e,t,_()],{slotKey:e,reason:t})}rotate(e,t){let{gen:n}=R(t),s=[...this.keys(e),`sreg:${this.pool}:slot:${t}`,this.idxKey()];return this.run("rotate",oe,s,[e,t,n,_()],{oldKey:e,newKey:t,newGen:n})}end(e){return this.run("end",ae,this.keys(e,!1,!1),[e,_()],{slotKey:e})}lease(e){return this.run("lease",le,this.keys(e,!1,!1),[e],{slotKey:e})}release(e){return this.run("release",de,this.keys(e,!1,!1),[e,_()],{slotKey:e})}configure(e,t){return this.run("config",he,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}retune(e,t){return this.run("retune",ce,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}async tuning(){let e=await this.evalFn.eval(ue,[`sreg:${this.pool}:meta`],[]),[t,n,s]=e.split("|");return{max:Number(t),inFlightCap:Number(n),configVersion:Number(s)}}async grant(e,t){let n=this.keys(e,!1,!1),s=await this.evalFn.eval(A,n,[e,t.cap,t.configVersion]);if(s==="reject:cap-moved"){let r=await this.tuning();s=await this.evalFn.eval(A,n,[e,r.inFlightCap,r.configVersion])}if(s==="ok")return{granted:!0};if(s==="reject:cap")return{granted:!1,reason:"cap-full"};if(s==="reject:cap-moved")return{granted:!1,reason:"cap-moved"};throw new T("grant",s,{pool:this.pool,slotKey:e})}async grantWithEpoch(e,t){let n=this.keys(e,!1,!1),s=await this.evalFn.eval(A,n,[e,t.cap,t.configVersion,t.epoch]);if(s==="reject:cap-moved"){let r=await this.tuning();s=await this.evalFn.eval(A,n,[e,r.inFlightCap,r.configVersion,t.epoch])}if(s==="ok")return{granted:!0};if(s==="reject:cap")return{granted:!1,reason:"cap-full"};if(s==="reject:cap-moved")return{granted:!1,reason:"cap-moved"};if(s==="reject:epoch")return{granted:!1,reason:"epoch-stale"};throw new T("grant",s,{pool:this.pool,slotKey:e})}async snapshot(){let e=[],t=null,n="0";do{let s=await this.snapshotPage(n,Ue);t===null&&(t=s.counts),e.push(...s.slots),n=s.cursor}while(n!=="0");return{counts:t,slots:e}}async counts(){let e=await this.evalFn.eval(pe,[`sreg:${this.pool}:meta`],[]);return Ee(e)}async snapshotPage(e,t){let n=`sreg:${this.pool}:slot:`,s=await this.evalFn.eval(me,[this.idxKey(),`sreg:${this.pool}:meta`],[n,e,t]),[r,o,l]=s.split("#");return{cursor:r,counts:Ee(o??""),slots:He(l??"")}}async readRecords(e){if(e.length===0)return[];let t=`sreg:${this.pool}:slot:`,n=await this.evalFn.eval(fe,[],e.map(s=>t+s));return(n===""?[]:n.split(`
301
+ `)).map(s=>{let[r,o]=s.split("|");return{state:r,inFlight:Number(o)}})}async generation(e){let{base:t}=R(e),n=await this.evalFn.eval(ge,[`sreg:${this.pool}:gen:${t}`],[]);return Number(n)}async record(e){let n=(await this.evalFn.eval(ye,[`sreg:${this.pool}:slot:${e}`],[])).split("|"),s=n[0],r=n[1]===""||n[1]===void 0?void 0:n[1],o=n.slice(2).join("|");return{state:s,sessionId:r,lastReason:o===""?void 0:o}}};p();var O=class{records=new Map;add(e){return this.records.set(e.request_id,{request:e,sessionId:"",attempt:1,dispatched:!1}),Promise.resolve()}dispatched(e,t,n){let s=this.records.get(e);return s&&(s.sessionId=t,s.attempt=n,s.dispatched=!0),Promise.resolve()}requeue(e,t){let n=this.records.get(e);return n&&(n.dispatched=!1,n.sessionId="",n.attempt=t),Promise.resolve()}finish(e){return this.records.delete(e),Promise.resolve()}queued(e,t){return Promise.resolve([...this.records.values()].filter(n=>!n.dispatched&&n.request.region===e&&n.request.model===t).map(n=>n.request))}inflight(){return Promise.resolve([...this.records.values()].filter(e=>e.dispatched).map(e=>({request:e.request,sessionId:e.sessionId,attempt:e.attempt})))}};p();p();var G=i=>`${i.systemPrompt??""}\0${i.firstMessage??""}`;function K(i){return i.promptCacheKey!==void 0&&i.promptCacheKey!==""?`k:${i.promptCacheKey}`:i.sessionHeader!==void 0&&i.sessionHeader!==""?`h:${i.sessionHeader}`:`p:${De(G(i))}`}function De(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}var Se=512,$e=4096,L=8,M=class{root={children:new Map,sessions:new Map};nodes=1;insert(e,t,n){let s=e.slice(0,Se),r=this.root;for(let o=0;o<s.length;o+=L){let l=s.slice(o,o+L),d=r.children.get(l);if(!d){if(this.nodes>=$e)return;d={children:new Map,sessions:new Map},r.children.set(l,d),this.nodes+=1}d.sessions.set(t,n),r=d}}match(e,t){let n=e.slice(0,Se),s=this.root,r=null,o=0,l=0;for(;;){let d=null,c=-1;for(let[h,f]of s.sessions)t.has(h)&&(f>c||f===c&&d!==null&&h<d)&&(d=h,c=f);if(d!==null&&(r={sessionId:d,depth:o}),l>=n.length)break;let u=n.slice(l,l+L),a=s.children.get(u);if(!a)break;s=a,o+=u.length,l+=L}return r}forget(e){let t=n=>{n.sessions.delete(e);for(let s of n.children.values())t(s)};t(this.root)}size(){return this.nodes}};function we(i,e,t,n){if(e.length===0)return null;let s=new Map(e.map(u=>[u.sessionId,u])),r=u=>{let a=s.get(u);return a!==void 0&&a.backlog<n.backlogThreshold},o=new Set(s.keys()),l=n.sticky.get(K(i));if(l!==void 0&&r(l))return{sessionId:l,reason:"sticky"};let d=t.match(G(i),o);if(d!==null&&r(d.sessionId))return{sessionId:d.sessionId,reason:"prefix"};let c=null;for(let u of e)(c===null||u.backlog<c.backlog||u.backlog===c.backlog&&u.sessionId<c.sessionId)&&(c=u);return c===null?null:{sessionId:c.sessionId,reason:"load"}}p();var Re="llm",be="requests",Ke="llm-resp",j=(i,e,t,n=0)=>`decision:pooler-${i}-${e}`.replaceAll(":","-")+`:${t}`+(n>0?`:${n}`:""),Y=i=>{let{base:e,gen:t}=R(i);return`${e}:${t+1}`},_e=i=>`${Ke}:${i}`,Pe="free_slots",V="inflight",F="live_seen",P=class extends Error{constructor(t,n){super(`reply stream for ${t} dropped before its terminal chunk${n?`: ${n}`:""}`);this.requestId=t;this.name="ReplyStreamDropped"}requestId};var Te=new Set(["registry_error","failed","mint_failed","scaled_down","live_mark_failed","never_live_evicted","never_live_end_failed"]),je=6e4,Ye=33e4,Ve=2,Fe=8,Be=5e3,Je=1e4,We=6e4,ze=5e3,Xe=36e5,Qe={provisioning:!0,waiting_for_capacity:!0,connecting:!0},ke={idle:"bound",queued:"bound",unavailable:"bound",provisioning:"bound",waiting_for_capacity:"bound",connecting:"bound",live:"bound",degraded:"bound",paused:"unbound",error:"unbound",unknown:"unbound"},C=class i{pools=new Map;now;queueDeadlineMs;silenceDeadlineMs;maxAttempts;backlogThreshold;mint;limits;scaleUpWaitMs;mintCooldownMs;sessionIdleTtlMs;idleSweepMs;neverLiveEvictAfterMs;journal;registry;onEvent;closed=!1;sweepTimer=null;constructor(e){this.journal=e.journal,this.registry=e.registry??null,this.now=e.now??Date.now,this.queueDeadlineMs=e.queueDeadlineMs??je,this.silenceDeadlineMs=e.silenceDeadlineMs??Ye,this.maxAttempts=e.maxAttempts??Ve,this.backlogThreshold=e.backlogThreshold??Fe,this.mint=e.mint,this.limits=e.limits??[],this.scaleUpWaitMs=e.scaleUpWaitMs??Be,this.mintCooldownMs=e.mintCooldownMs??Je,this.sessionIdleTtlMs=e.sessionIdleTtlMs??We,this.idleSweepMs=e.idleSweepMs??ze,this.neverLiveEvictAfterMs=e.neverLiveEvictAfterMs??Xe,this.onEvent=e.onEvent??(()=>{}),(this.mint!==void 0||this.limits.length>0)&&this.armSweep()}armSweep(){this.sweepTimer=setInterval(()=>this.sweep(),this.idleSweepMs),this.sweepTimer.unref?.()}sweep(){if(!this.closed)for(let e of this.pools.values()){let t=this.limitsFor(e);if(t===null)continue;this.evictUnbound(e),this.evictNeverLiveAcquiring(e);let n=e.queue.length===0;e.sessions.length<t.max&&this.queuePressure(e)?this.tryMint(e,"queue_pressure"):e.sessions.length<t.min&&this.tryMint(e,"min_floor"),n&&e.sessions.length>t.min&&this.scaleDownOldestIdle(e,t)}}servable(e){return e.gone()!==null?!1:ke[e.phaseName()]==="bound"?!0:!e.everLive()}evictUnbound(e){for(let t of[...e.sessions]){if(this.servable(t))continue;let n=t.phaseName();this.onEvent({kind:"sweep_evicted",pool:this.key(e.region,e.model),sessionId:t.sessionId,phase:n}),this.evict(e,t,new q(`the pool entry for ${t.sessionId} has no usable compute binding (phase "${n}") \u2014 the sweep's servability reconcile evicts it; the named session itself stays parked and attachable`))}}evictNeverLiveAcquiring(e){let t=this.neverLiveEvictAfterMs;if(t<=0)return;let n=this.now();for(let s of[...e.sessions]){if(s.gone()!==null||s.everLive())continue;let r=s.phaseName();if(ke[r]!=="bound"||!Qe[r])continue;let o=e.bornAt.get(s);if(o===void 0||n-o<t)continue;let l=e.sessions.indexOf(s);if(l===-1)continue;e.sessions.splice(l,1),this.detachSignals(e,s),e.radix.forget(s.sessionId),e.lastActivity.delete(s),e.bornAt.delete(s);let d=e.slotKeys.get(s.sessionId);d!==void 0&&(e.slotKeys.delete(s.sessionId),this.registryCall("end",d,()=>this.registry?.end(d))),this.onEvent({kind:"never_live_evicted",pool:this.key(e.region,e.model),sessionId:s.sessionId,phase:r,elapsedMs:n-o}),(s.namedSessionId()!==void 0?s.end():s.cancel()).catch(u=>{this.onEvent({kind:"never_live_end_failed",pool:this.key(e.region,e.model),sessionId:s.sessionId,reason:u instanceof Error?u.message:String(u)})})}}limitsFor(e){return this.limits.find(t=>t.region===e.region&&t.model===e.model)??null}queuePressure(e){if(e.queue.length===0)return!1;let t=this.now();return e.queue.some(n=>t-n.queuedAt>=this.scaleUpWaitMs)}tryMint(e,t){if(this.mint===void 0||this.closed||e.minting)return;let n=this.limitsFor(e);if(n===null||e.sessions.length>=n.max)return;let s=this.now();s-e.lastMintAt<this.mintCooldownMs||(e.lastMintAt=s,e.minting=!0,this.mintOnce(e,t).finally(()=>{e.minting=!1}))}async mintOnce(e,t){if(this.mint===void 0)return!1;let n=e.mintSeq++,s;try{s=await this.claimSlot(e.region,e.model,n)}catch(r){if(t==="boot_floor")throw r;return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:r instanceof Error?r.message:String(r)}),!1}try{let r=await this.mint(e.region,e.model,s);return this.closed?(await r.end().catch(()=>{}),!1):(this.addSession(e.region,e.model,r,s),this.onEvent({kind:"minted",pool:this.key(e.region,e.model),sessionId:r.sessionId,reason:t}),!0)}catch(r){return this.onEvent({kind:"mint_failed",pool:this.key(e.region,e.model),reason:r instanceof Error?r.message:String(r)}),!1}}async warm(){for(let e of this.limits){let t=this.poolOf(e.region,e.model);t.minting=!0;try{for(;t.sessions.length<e.min&&await this.mintOnce(t,"boot_floor"););}finally{t.minting=!1}}}scaleDownOldestIdle(e,t){let n=this.now();for(let s of e.sessions){if(s.gone()!==null||[...e.records.values()].some(c=>c.session===s&&c.phase==="dispatched")||n-(e.lastActivity.get(s)??n)<this.sessionIdleTtlMs)continue;let l=e.sessions.indexOf(s);if(l===-1)continue;e.sessions.splice(l,1),this.detachSignals(e,s),e.radix.forget(s.sessionId),e.lastActivity.delete(s),e.bornAt.delete(s);let d=e.slotKeys.get(s.sessionId);d!==void 0&&(e.slotKeys.delete(s.sessionId),this.registryCall("end",d,()=>this.registry?.end(d))),this.onEvent({kind:"scaled_down",pool:this.key(e.region,e.model),sessionId:s.sessionId,sessions:e.sessions.length,min:t.min}),s.end().catch(c=>{this.onEvent({kind:"scaled_down_end_failed",pool:this.key(e.region,e.model),sessionId:s.sessionId,reason:c instanceof Error?c.message:String(c)})});return}}static poolKey(e,t){return`${e}:${t}`}async claimSlot(e,t,n){let s=j(e,t,n);if(this.registry===null)return s;for(let r=0;;r++){let o=await this.registry.generation(s),l=j(e,t,n,o),{state:d,sessionId:c,lastReason:u}=await this.registry.record(l);if(d==="none"||d==="paused"&&c===void 0&&u===void 0)try{return await this.registry.mint(l),l}catch(a){this.rethrowUnlessClaimRace(a,r);continue}else{let a=Y(l);try{await this.registry.rotate(l,a),await this.registry.mint(a)}catch(h){this.rethrowUnlessClaimRace(h,r);continue}return this.onEvent({kind:"slot_rotated",pool:this.key(e,t),slotKey:l,successor:a,reason:d==="paused"?"boot claim over an evicted slot's dead session":`boot claim over a previous pod's ${d} record`}),a}}}static CLAIM_RACE_VERDICTS=new Set(["reject:double-rotate","reject:generation-monotone","reject:retired-corpse-reuse","reject:mint-queued","reject:mint-attached"]);static CLAIM_RACE_ATTEMPTS=3;rethrowUnlessClaimRace(e,t){if(!(t+1<i.CLAIM_RACE_ATTEMPTS&&e instanceof T&&i.CLAIM_RACE_VERDICTS.has(e.verdict)))throw e}addSession(e,t,n,s){let r=this.poolOf(e,t);r.sessions.push(n),r.lastActivity.set(n,this.now()),r.bornAt.set(n,this.now()),r.slotKeys.set(n.sessionId,s),n.whenLive().then(()=>{n.markLiveSeen().catch(o=>{this.onEvent({kind:"live_mark_failed",pool:this.key(e,t),sessionId:n.sessionId,reason:o instanceof Error?o.message:String(o)})}),this.registryCall("attach",s,()=>this.registry?.attach(s,n.sessionId))}).catch(o=>{this.onEvent({kind:"session_never_live",pool:this.key(e,t),sessionId:n.sessionId,reason:o instanceof Error?o.message:String(o)}),this.evict(r,n,o instanceof Error?o:new Error(String(o)))}),r.offs.set(n,[n.onDocChange(()=>{this.pump(r),this.adoptSettled(r)}),n.onGone(o=>this.evict(r,n,o))]),this.onEvent({kind:"session_added",pool:this.key(e,t),sessionId:n.sessionId}),this.start(r).then(()=>this.pump(r))}async start(e){if(!e.needsReconcile)return;e.needsReconcile=!1;let t=this.key(e.region,e.model);for(let n of await this.journal.inflight()){if(n.request.region!==e.region||n.request.model!==e.model)continue;let s=e.sessions.find(o=>o.sessionId===n.sessionId),r=s?.snapshot().inflight[n.request.request_id];if(s!==void 0){if(r?.status==="done"||r?.status==="error"){await this.journal.finish(n.request.request_id);continue}e.records.set(n.request.request_id,{request:n.request,sink:null,attempt:n.attempt,tried:new Set([n.sessionId]),session:s,phase:"dispatched",streamed:!1,deadlineAt:Number.POSITIVE_INFINITY,queueTimer:null,silenceTimer:void 0,queuedAt:this.now()}),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:n.request.request_id,sessionId:n.sessionId})}}for(let n of await this.journal.queued(e.region,e.model))await this.journal.finish(n.request_id),this.onEvent({kind:"reconciled_caller_gone",pool:t,requestId:n.request_id});for(let n of e.sessions){let s=n.snapshot();for(let[r,o]of Object.entries(s.inflight)){if(o.status==="done"||o.status==="error"||e.records.has(r))continue;let l={request:{request_id:r,region:e.region,model:e.model,affinity:{},payload:{},streaming:!1,enqueuedAt:0},sink:null,attempt:o.attempt,tried:new Set([n.sessionId]),session:n,phase:"dispatched",streamed:!1,deadlineAt:Number.POSITIVE_INFINITY,queueTimer:null,silenceTimer:void 0,queuedAt:this.now()};e.records.set(r,l),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:r,sessionId:n.sessionId})}}this.pump(e)}async submit(e,t){if(this.closed){t.head(),t.fail({status:503,code:"draining",message:"pooler is shutting down",retryAfterSeconds:5});return}let n=this.poolOf(e.region,e.model);await this.start(n);let s={request:e,sink:t,attempt:1,tried:new Set,session:null,phase:"queued",streamed:!1,deadlineAt:this.now()+this.queueDeadlineMs,queueTimer:null,silenceTimer:void 0,queuedAt:this.now()};n.records.set(e.request_id,s),n.queue.push(s),await this.journal.add(e),t.head(),this.armQueueTimer(n,s),this.onEvent({kind:"enqueued",pool:this.key(e.region,e.model),requestId:e.request_id}),this.pump(n),s.phase!=="finished"&&await new Promise(r=>{s.settle=r})}abandon(){this.closed=!0,this.sweepTimer!==null&&(clearInterval(this.sweepTimer),this.sweepTimer=null);for(let e of this.pools.values()){for(let t of e.records.values())this.clearTimers(t);for(let t of e.offs.values())for(let n of t)n();e.offs.clear(),e.sessions.length=0,e.queue.length=0,e.records.clear(),e.lastActivity.clear()}this.pools.clear()}async close(){this.closed=!0,this.sweepTimer!==null&&(clearInterval(this.sweepTimer),this.sweepTimer=null);for(let e of this.pools.values()){for(let n of e.records.values())this.clearTimers(n),n.phase!=="finished"&&this.settle(n,{status:503,code:"draining",message:"pooler is shutting down",retryAfterSeconds:5});for(let n of e.offs.values())for(let s of n)s();e.offs.clear(),e.lastActivity.clear(),e.bornAt.clear();for(let n of e.slotKeys.values())this.registryCall("rotate",n,()=>this.registry?.rotate(n,Y(n)));e.slotKeys.clear();let t=e.sessions.splice(0);await Promise.allSettled(t.map(n=>n.end()))}this.pools.clear()}poolOf(e,t){let n=i.poolKey(e,t),s=this.pools.get(n);return s||(s={region:e,model:t,sessions:[],records:new Map,queue:[],sticky:new Map,radix:new M,offs:new Map,slotKeys:new Map,needsReconcile:!0,lastMintAt:0,minting:!1,mintSeq:0,lastActivity:new Map,bornAt:new Map},this.pools.set(n,s)),s}key(e,t){return i.poolKey(e,t)}registryCall(e,t,n){let s=n();s!==void 0&&s.catch(r=>{this.onEvent({kind:"registry_error",reason:`${e}: ${r instanceof Error?r.message:String(r)}`,slotKey:t})})}creditFor(e,t){let n=t.snapshot(),s=0;for(let r of e.records.values()){if(r.session!==t||r.phase!=="dispatched")continue;let o=n.inflight[r.request.request_id];(o===void 0||o.status===void 0)&&(s+=1)}return Math.max(0,n.freeSlots-s)}backlogOf(e,t){let n=0;for(let s of e.records.values())s.session===t&&s.phase==="dispatched"&&(n+=1);return n}pump(e){if(this.closed)return;let t=!0;for(;t&&e.queue.length>0&&e.sessions.length>0;){t=!1;for(let n=0;n<e.queue.length;n++){let s=e.queue[n],r=this.pickFor(e,s);if(r!==null){e.queue.splice(n,1),this.dispatch(e,r,s),t=!0;break}}}e.queue.length>0&&this.queuePressure(e)&&this.tryMint(e,"queue_pressure")}pickFor(e,t){let n=e.sessions.filter(o=>this.servable(o)&&!t.tried.has(o.sessionId)&&this.creditFor(e,o)>0).map(o=>({sessionId:o.sessionId,backlog:this.backlogOf(e,o)})),s=we(t.request.affinity,n,e.radix,{backlogThreshold:this.backlogThreshold,sticky:e.sticky});if(s===null)return null;let r=e.sessions.find(o=>o.sessionId===s.sessionId)??null;return r!==null&&this.onEvent({kind:"picked",pool:this.key(e.region,e.model),requestId:t.request.request_id,sessionId:r.sessionId,reason:s.reason}),r}dispatch(e,t,n){n.phase="dispatched",n.session=t,n.tried.add(t.sessionId),e.lastActivity.set(t,this.now()),this.clearTimer(n,"queue"),n.deadlineAt=this.now()+this.silenceDeadlineMs;let s={request_id:n.request.request_id,consumer_id:n.request.request_id,payload:n.request.payload,stream:n.request.streaming};(async()=>{let r=t.reply(s.request_id);try{await t.markInflight(s.request_id,n.attempt),await t.push(s)}catch(d){this.lost(e,n,d);return}await this.journal.dispatched(n.request.request_id,t.sessionId,n.attempt);let o=K(n.request.affinity);e.sticky.set(o,t.sessionId),e.radix.insert(G(n.request.affinity),t.sessionId,this.now()),this.onEvent({kind:"dispatched",pool:this.key(e.region,e.model),requestId:n.request.request_id,sessionId:t.sessionId,attempt:n.attempt}),this.armSilenceTimer(e,n);let l=e.slotKeys.get(t.sessionId);l!==void 0&&this.registryCall("lease",l,()=>this.registry?.lease(l)),this.consume(e,n,r)})()}async consume(e,t,n){if(t.session!==null)try{for await(let s of n){if(t.phase==="finished")return;this.armSilenceTimer(e,t),t.streamed=!0;let r=t.sink;if(r!==null&&(await r.chunk(s),s.t==="response"||s.t==="error"||s.t==="end")){await this.finish(e,t);return}}this.lost(e,t,new P(t.request.request_id,"iterator ended without a terminal chunk"))}catch(s){this.lost(e,t,s)}}lost(e,t,n){if(t.phase==="finished")return;this.clearTimers(t);let s=n instanceof Error?n.message:String(n);this.onEvent({kind:"lost",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt,reason:s}),n instanceof q&&t.session!==null&&this.evict(e,t.session,n);let r=e.sessions.some(o=>this.servable(o)&&!t.tried.has(o.sessionId));if(!t.streamed&&t.attempt<this.maxAttempts&&r){t.attempt+=1,t.phase="queued",t.session=null,t.deadlineAt=this.now()+this.queueDeadlineMs,t.queuedAt=this.now(),e.queue.unshift(t),this.journal.requeue(t.request.request_id,t.attempt).catch(()=>{}),this.armQueueTimer(e,t),this.onEvent({kind:"retry",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt}),this.pump(e);return}this.settle(t,{status:502,code:t.streamed?"upstream_stream_lost":"upstream_error",message:t.streamed?"the upstream reply stream was lost after the response began":"the upstream reply stream was lost before the response began",retryAfterSeconds:1})}async finish(e,t){this.clearTimers(t),t.phase="finished",t.session!==null&&e.lastActivity.set(t.session,this.now()),this.releaseSlot(e,t,"release"),await this.journal.finish(t.request.request_id),t.session!==null&&t.session.clearRequest(t.request.request_id);let n=t.sink;n!==null&&n.done(),this.release(e,t),this.onEvent({kind:"finished",pool:this.key(e.region,e.model),requestId:t.request.request_id,attempt:t.attempt}),this.settlePromise(t)}settle(e,t){this.clearTimers(e);let n=e.session===null?void 0:this.poolOf(e.request.region,e.request.model).slotKeys.get(e.session.sessionId);n!==void 0&&this.registryCall("release",n,()=>this.registry?.release(n)),e.phase="finished",e.session!==null&&this.poolOf(e.request.region,e.request.model).lastActivity.set(e.session,this.now()),this.journal.finish(e.request.request_id).catch(()=>{}),e.session!==null&&e.session.clearRequest(e.request.request_id);let s=e.sink;s!==null&&s.fail(t),this.onEvent({kind:"failed",requestId:e.request.request_id,reason:t.code}),this.settlePromise(e)}settlePromise(e){let t=e.settle;e.settle=void 0,t?.()}release(e,t){e.records.get(t.request.request_id)===t&&e.records.delete(t.request.request_id)}releaseSlot(e,t,n){if(t.session===null)return;let s=e.slotKeys.get(t.session.sessionId);s!==void 0&&this.registryCall(n,s,()=>n==="release"?this.registry?.release(s):this.registry?.detach(s,"session evicted"))}detachSignals(e,t){let n=e.offs.get(t);if(n!==void 0){e.offs.delete(t);for(let s of n)s()}}evict(e,t,n){let s=e.sessions.indexOf(t);if(s===-1)return;e.sessions.splice(s,1),this.detachSignals(e,t),e.lastActivity.delete(t),e.bornAt.delete(t),e.radix.forget(t.sessionId);let r=e.slotKeys.get(t.sessionId);r!==void 0&&(e.slotKeys.delete(t.sessionId),this.registryCall("detach",r,()=>this.registry?.detach(r,n.message)));for(let o of[...e.records.values()])o.session===t&&o.phase!=="finished"&&this.lost(e,o,n)}adoptSettled(e){for(let t of e.sessions){let n=t.snapshot();for(let s of[...e.records.values()]){if(s.sink!==null||s.session!==t)continue;let r=n.inflight[s.request.request_id];(r?.status==="done"||r?.status==="error")&&(this.journal.finish(s.request.request_id).catch(()=>{}),this.release(e,s))}}}armQueueTimer(e,t){this.clearTimer(t,"queue");let n=Math.max(0,t.deadlineAt-this.now());t.queueTimer=setTimeout(()=>{t.phase==="queued"&&(this.onEvent({kind:"queue_timeout",requestId:t.request.request_id}),this.settle(t,{status:429,code:"queue_timeout",message:"no capacity for this model within the wait bound",retryAfterSeconds:30}),e.queue.splice(e.queue.indexOf(t),1))},n),t.queueTimer.unref?.()}armSilenceTimer(e,t){clearTimeout(t.silenceTimer),t.silenceTimer=setTimeout(()=>{t.silenceTimer=void 0,t.phase==="dispatched"&&this.lost(e,t,new P(t.request.request_id,`silent past ${this.silenceDeadlineMs}ms`))},this.silenceDeadlineMs),t.silenceTimer.unref?.()}clearTimer(e,t){let n=t==="queue"?e.queueTimer:e.silenceTimer;n!==null&&(clearTimeout(n),t==="queue"?e.queueTimer=null:e.silenceTimer=void 0)}clearTimers(e){this.clearTimer(e,"queue"),this.clearTimer(e,"silence")}stats(){return{pools:[...this.pools.entries()].map(([e,t])=>({pool:e,queued:t.queue.length,inflight:[...t.records.values()].filter(n=>n.phase==="dispatched").length,sessions:t.sessions.length}))}}};p();var Ze="0.0.0.0",Ie="serve";var I=(i,e)=>{let t=i[e];if(typeof t!="string"||t==="")throw new Error(`the pooler requires ${e} (external input) \u2014 refusing to start half-configured`);return t},et=(i,e)=>{if(i===null||typeof i!="object")throw new Error(`URUN_POOLER_TARGETS[${e}] must be an object`);let t=i,n=c=>{let u=t[c];if(typeof u!="string"||u==="")throw new Error(`URUN_POOLER_TARGETS[${e}].${c} is required`);return u},s=c=>{let u=t[c];if(typeof u!="number"||!Number.isInteger(u))throw new Error(`URUN_POOLER_TARGETS[${e}].${c} must be an integer`);return u},r,o;if(t.sessions!==void 0){let c=t.sessions;if(typeof c!="number"||!Number.isInteger(c)||c<1)throw new Error(`URUN_POOLER_TARGETS[${e}].sessions must be an integer >= 1`);if(t.min!==void 0||t.max!==void 0)throw new Error(`URUN_POOLER_TARGETS[${e}]: give either sessions or {min, max}, never both`);r=c,o=c}else{if(r=s("min"),o=s("max"),r<0)throw new Error(`URUN_POOLER_TARGETS[${e}].min must be >= 0 (0 scales to zero)`);if(o<1)throw new Error(`URUN_POOLER_TARGETS[${e}].max must be >= 1`);if(r>o)throw new Error(`URUN_POOLER_TARGETS[${e}]: min (${String(r)}) must not exceed max (${String(o)})`)}let l,d;if((t.lanePool!==void 0||t.laneMin!==void 0)&&(l=n("lanePool"),d=s("laneMin"),d<0))throw new Error(`URUN_POOLER_TARGETS[${e}].laneMin must be >= 0`);return{region:n("region"),model:n("model"),app:n("app"),fn:typeof t.fn=="string"&&t.fn!==""?t.fn:void 0,min:r,max:o,sharedApp:t.sharedApp===!0,...l!==void 0?{lanePool:l,laneMin:d}:{}}};function Ae(i){let e=i.PORT,t=e===void 0||e===""?8080:Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw new Error(`PORT must be a valid port number, got ${String(e)}`);let n=I(i,"URUN_BASE_URL"),s=I(i,"URUN_POOLER_TARGETS"),r;try{r=JSON.parse(s)}catch(l){throw new Error(`URUN_POOLER_TARGETS is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!Array.isArray(r)||r.length===0)throw new Error("URUN_POOLER_TARGETS must be a non-empty JSON array");let o=(i.URUN_LANE_DOC_HOST_URL??"").trim()||void 0;return{port:t,bindHost:Ze,token:I(i,"URUN_POOLER_TOKEN"),baseUrl:n,apiUrl:i.URUN_API_URL!==void 0&&i.URUN_API_URL!==""?i.URUN_API_URL:`${n}/v1`,orgId:I(i,"URUN_ORG_ID"),apiKey:I(i,"URUN_API_KEY"),valkeyUrl:I(i,"URUN_VALKEY_URL"),laneDocHostUrl:o,laneRuntimeKey:(i.URUN_LANE_RUNTIME_KEY??"").trim()||void 0,targets:r.map(et)}}p();import{createServer as tt}from"http";var nt="/pooler/v1/inference",st="/readyz",rt="/metrics",it="/pooler/v1/lanes/pick",ot="/pooler/v1/lanes/status",at=1e4,qe=16*1024*1024;function y(i,e,t,n,s){i.headersSent||(s!==void 0&&i.setHeader("retry-after",String(s)),i.writeHead(e,{"content-type":"application/json"}),i.end(JSON.stringify({error:{message:t,type:"pooler_error",code:n}})))}function lt(i){if(i===null||typeof i!="object")return{reason:"body must be a JSON object"};let e=i;if(typeof e.region!="string"||e.region==="")return{reason:"region is required"};if(typeof e.model!="string"||e.model==="")return{reason:"model is required"};if(typeof e.request_id!="string"||e.request_id==="")return{reason:"request_id is required"};if(e.payload===null||typeof e.payload!="object")return{reason:"payload must be an object"};let t=e.affinity??{};if(t===null||typeof t!="object")return{reason:"affinity must be an object"};let n=t,s=r=>typeof r=="string"&&r!==""?r:void 0;return{value:{streaming:e.streaming===!0,request:{request_id:e.request_id,region:e.region,model:e.model,payload:e.payload,affinity:{promptCacheKey:s(n.promptCacheKey??e.prompt_cache_key),sessionHeader:s(n.sessionHeader??e.session_header),systemPrompt:s(n.systemPrompt),firstMessage:s(n.firstMessage)},streaming:e.streaming===!0,enqueuedAt:Date.now()}}}}var B=class{constructor(e,t,n){this.res=e;this.streaming=t;this.keepaliveMs=n}res;streaming;keepaliveMs;keepalive=null;terminal=null;head(){this.streaming&&!this.res.headersSent&&(this.res.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive"}),this.keepalive=setInterval(()=>{this.res.writableEnded||this.res.write(`: keepalive
302
302
 
303
303
  `)},this.keepaliveMs),this.keepalive.unref?.())}async chunk(e){if(this.streaming){this.res.headersSent||this.head(),this.res.write(`data: ${JSON.stringify(e)}
304
304
 
305
305
  `);return}e.t!=="delta"&&(this.terminal=e)}done(){if(this.stopKeepalive(),this.streaming){this.res.write(`data: [DONE]
306
306
 
307
- `),this.res.end();return}if(this.terminal!==null&&this.terminal.t==="error"){let t=this.terminal.body,s=t!==null&&typeof t=="object"&&typeof t.message=="string"?String(t.message):"the upstream turn failed";g(this.res,502,s,"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){g(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}})}
307
+ `),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";y(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){y(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
308
 
309
309
  `),this.res.write(`data: [DONE]
310
310
 
311
- `),this.res.end()}stopKeepalive(){this.keepalive!==null&&clearInterval(this.keepalive),this.keepalive=null}};function Ie(i){return new Promise((e,t)=>{let s=0,n=[];i.on("data",r=>{if(s+=r.length,s>Te){t(new Error(`request body exceeds ${Te} bytes`)),i.destroy();return}n.push(r)}),i.on("end",()=>e(Buffer.concat(n).toString("utf8"))),i.on("error",t)})}function Ae(i){let e=i.keepaliveMs??rt,t=i.log??(()=>{}),s=Qe((n,r)=>{(async()=>{let o=new URL(n.url??"/","http://pooler.internal");if(n.method==="GET"&&o.pathname===et){r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({ok:!0,...i.pooler.stats()}));return}if(n.method==="GET"&&o.pathname===tt){let u=["# TYPE pooler_pool_queued gauge","# TYPE pooler_pool_inflight gauge","# TYPE pooler_pool_sessions gauge","# TYPE pooler_lane_demand_enqueued counter","# TYPE pooler_lane_demand_reaffirmed counter"];for(let a of i.pooler.stats().pools){let h=`pool="${a.pool}"`;u.push(`pooler_pool_queued{${h}} ${a.queued}`),u.push(`pooler_pool_inflight{${h}} ${a.inflight}`),u.push(`pooler_pool_sessions{${h}} ${a.sessions}`)}for(let a of i.lanePlane?.demandCounters()??[]){let h=`model="${a.model.replaceAll('"','\\"')}"`;u.push(`pooler_lane_demand_enqueued{${h}} ${a.enqueued}`),u.push(`pooler_lane_demand_reaffirmed{${h}} ${a.reaffirmed}`)}for(let a of i.lanePlane?.demandRefusals()??[])u.push(`pooler_lane_demand_refused{reason="${a.reason}"} ${a.count}`);r.writeHead(200,{"content-type":"text/plain; version=0.0.4"}),r.end(`${u.join(`
311
+ `),this.res.end()}stopKeepalive(){this.keepalive!==null&&clearInterval(this.keepalive),this.keepalive=null}};function Ne(i){return new Promise((e,t)=>{let n=0,s=[];i.on("data",r=>{if(n+=r.length,n>qe){t(new Error(`request body exceeds ${qe} bytes`)),i.destroy();return}s.push(r)}),i.on("end",()=>e(Buffer.concat(s).toString("utf8"))),i.on("error",t)})}function xe(i){let e=i.keepaliveMs??at,t=i.log??(()=>{}),n=tt((s,r)=>{(async()=>{let o=new URL(s.url??"/","http://pooler.internal");if(s.method==="GET"&&o.pathname===st){r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({ok:!0,...i.pooler.stats()}));return}if(s.method==="GET"&&o.pathname===rt){let u=["# TYPE pooler_pool_queued gauge","# TYPE pooler_pool_inflight gauge","# TYPE pooler_pool_sessions gauge","# TYPE pooler_lane_demand_enqueued counter","# TYPE pooler_lane_demand_reaffirmed counter"];for(let a of i.pooler.stats().pools){let h=`pool="${a.pool}"`;u.push(`pooler_pool_queued{${h}} ${a.queued}`),u.push(`pooler_pool_inflight{${h}} ${a.inflight}`),u.push(`pooler_pool_sessions{${h}} ${a.sessions}`)}for(let a of i.lanePlane?.demandCounters()??[]){let h=`model="${a.model.replaceAll('"','\\"')}"`;u.push(`pooler_lane_demand_enqueued{${h}} ${a.enqueued}`),u.push(`pooler_lane_demand_reaffirmed{${h}} ${a.reaffirmed}`)}for(let a of i.lanePlane?.demandRefusals()??[])u.push(`pooler_lane_demand_refused{reason="${a.reason}"} ${a.count}`);r.writeHead(200,{"content-type":"text/plain; version=0.0.4"}),r.end(`${u.join(`
312
312
  `)}
313
- `);return}if(i.lanePlane&&n.method==="GET"&&o.pathname===nt){if(n.headers.authorization!==`Bearer ${i.token}`){g(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===st){if(n.headers.authorization!==`Bearer ${i.token}`){g(r,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let u;try{u=JSON.parse(await Ie(n))}catch(y){g(r,400,y instanceof Error?y.message:String(y),"invalid_request");return}let a=u??{};if(typeof a.pool!="string"||a.pool===""){g(r,400,"pool is required","invalid_request");return}let h=a.hold_ms;if(h!==void 0&&(typeof h!="number"||!Number.isInteger(h)||h<0||h>Q)){g(r,400,"hold_ms must be an integer in 0..120000","invalid_request");return}let f=typeof a.model=="string"&&a.model!==""?a.model:void 0,b=typeof a.app=="string"&&a.app!==""?a.app:void 0,k=typeof a.fn=="string"&&a.fn!==""?a.fn:void 0,H=a.shared_app===!0?!0:void 0;try{let y=await i.lanePlane.pick({pool:a.pool,app:b,fn:k,sharedApp:H,model:f,holdMs:h??0});if(y.length===0){let m=i.lanePlane.demandFailure(a.pool);g(r,503,m?`no capacity available for this model right now, retry shortly (the demand mint last failed: ${m})`:"no capacity available for this model right now, retry shortly","lane_capacity",2);return}r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({lanes:y.map(m=>({lane_id:m.laneId,host:m.host}))}))}catch(y){t(`[pooler] lane pick for ${a.pool} failed: ${y instanceof Error?y.message:String(y)}`),g(r,500,"the pooler lane plane failed this pick","pooler_error")}return}if(n.method!=="POST"||o.pathname!==Ze){g(r,404,`no route for ${n.method??""} ${o.pathname}`,"not_found");return}if(n.headers.authorization!==`Bearer ${i.token}`){g(r,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let l;try{l=JSON.parse(await Ie(n))}catch(u){g(r,400,u instanceof Error?u.message:String(u),"invalid_request");return}let d=it(l);if("reason"in d){g(r,400,d.reason,"invalid_request");return}let c=new B(r,d.value.streaming,e);c.head();try{await i.pooler.submit(d.value.request,c)}catch(u){t(`[pooler] request ${d.value.request.request_id} failed unexpectedly: ${u instanceof Error?u.message:String(u)}`),c.fail({status:500,code:"pooler_error",message:"the pooler failed to serve this request"})}})()});return{server:s,close:()=>new Promise(n=>s.close(()=>n()))}}p();import{App as mt,createClientToken as pt}from"@urun-sh/core";p();import{STREAM_END as at}from"@urun-sh/core";var lt=new Set(["accepted","done","error"]);function ut(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 dt(i){if(i===null||typeof i!="object")return null;let e=i,t=e.status;return t!==void 0&&(typeof t!="string"||!lt.has(t))?null:{attempt:typeof e.attempt=="number"?e.attempt:0,...typeof t=="string"?{status:t}:{},...typeof e.error=="string"?{error:e.error}:{}}}function qe(i){let e=ut(i.get()),t=Number(e[we]??0),s={},n=e[V];if(n!==null&&typeof n=="object")for(let[r,o]of Object.entries(n)){let l=dt(o);l!==null&&(s[r]=l)}return{freeSlots:Number.isFinite(t)?t:0,inflight:s,liveSeen:e[F]===!0}}function ct(i){if(i===at)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*ht(i,e){let t=i.stream(be(e)),s=!1;try{for await(let n of t.messages()){let r=ct(n);if(r!==null&&(yield r,r.t!=="delta")){s=!0;return}}}catch(n){throw new P(e,n instanceof Error?n.message:String(n))}if(!s)throw new P(e,"the reply stream ended without a terminal chunk (urun-stream-v1 is at-most-once across a reconnect)")}function Ne(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(Ee),r=!1;return"onPhase"in e&&typeof e.onPhase=="function"&&e.onPhase(o=>{o.name==="live"&&(r=!0)}),{sessionId:t,snapshot:()=>qe(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||qe(n()).liveSeen,markLiveSeen:async()=>{await J(n(),15e3,"the durable live-seen mark"),n().set({[F]:!0})},whenLive:o=>e.whenLive(o),markInflight:(o,l)=>(n().set({[V]:{[o]:{attempt:l}}}),Promise.resolve()),push:o=>(n().set({[Se]:{[o.request_id]:{...o.payload,request_id:o.request_id,consumer_id:o.consumer_id,stream:o.stream}}}),Promise.resolve()),clearRequest:o=>{try{W(n(),o)}catch{}return Promise.resolve()},reply:o=>ht(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 xe(i){return async(e,t)=>{let s=e.fn??Pe,n=mt(e.app,{baseUrl:i.baseUrl,orgId:i.orgId,getAccessToken:async()=>(await pt(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}:{}},l=r.call(n,void 0,o);if(l===null||typeof l!="object")throw new Error(`app "${e.app}" function "${s}" returned no session`);let d=l;return Ne({session:d,sessionId:t,goneWatch:X(d,t,{armOnFirstSync:!0})})}}function Rt(){let i=null;i=z({streams:R,note:e=>{i?.isDead("stderr")!==!0&&N(R.stderr,e)}})}async function _t(){Rt();let i=ke(R.env),e=a=>{N(R.stdout,`${a}
314
- `)},t=new wt(i.valkeyUrl,{maxRetriesPerRequest:null}),s=new x({eval:(a,h,f)=>t.eval(a,h.length,...h,...f)},"pooler"),n=xe(i),r=new C({journal:new O,registry:s,queueDeadlineMs:6e4,silenceDeadlineMs:33e4,backlogThreshold:8,mint:(a,h,f)=>{let b=i.targets.find(k=>k.region===a&&k.model===h);return b===void 0?Promise.reject(new Error(`no pooler target for ${a}:${h} \u2014 refusing to mint`)):n(b,f)},limits:i.targets.map(({region:a,model:h,min:f,max:b})=>({region:a,model:h,min:f,max:b})),scaleUpWaitMs:5e3,mintCooldownMs:1e4,sessionIdleTtlMs:6e4,idleSweepMs:5e3,onEvent:a=>{_e.has(a.kind)&&e(`[pooler] ${a.kind} ${JSON.stringify(a)}`)}});await r.warm();let o=Object.fromEntries(i.targets.filter(a=>a.lanePool!==void 0&&(a.laneMin??0)>0).map(a=>[a.lanePool,a.laneMin??0])),l=i.laneDocHostUrl===void 0?void 0:Z({docHostUrl:i.laneDocHostUrl,redis:t,laneMinFor:a=>o[a]??0,admission:ee({baseUrl:i.baseUrl,apiKey:i.apiKey}),catalogIdentity:async a=>{if(a===void 0)return null;let h=await t.hgetall(te),f=[];for(let[m,v]of Object.entries(h))try{f.push({row:JSON.parse(v),field:m})}catch{}let b=m=>{let v=m.app_slug,U=m.function;return typeof v!="string"||v===""||typeof U!="string"||U===""?null:{app:v,fn:U,sharedApp:m.shared_org_id?!0:void 0}},k=f.find(m=>m.field===a);if(k){let m=b(k.row);if(m)return m}let H=a.includes(":")?a.slice(0,a.indexOf(":")):a,y=f.filter(m=>m.row.model_id===H).sort((m,v)=>m.field.localeCompare(v.field));for(let m of y){let v=b(m.row);if(v)return v}return null},onEvent:a=>{e(`[pooler] ${a.kind} ${JSON.stringify(a)}`)}}),{server:d,close:c}=Ae({pooler:r,token:i.token,lanePlane:l,log:e});await new Promise((a,h)=>{d.once("error",h),d.listen(i.port,i.bindHost,()=>a())}),e(`urun-pooler listening on http://${i.bindHost}:${i.port} (targets ${i.targets.map(a=>`${a.region}:${a.model} min=${a.min} max=${a.max}`).join(", ")})${l===void 0?"":" lanes=on"}`);let u=async a=>{e(`urun-pooler: ${a} \u2014 draining`),await c(),await r.close(),await l?.close(),await t.quit().catch(()=>{})};await new Promise(a=>{R.once("SIGINT",()=>{u("SIGINT").finally(a)}),R.once("SIGTERM",()=>{u("SIGTERM").finally(a)})})}_t().then(()=>R.exit(0),i=>{N(R.stderr,`urun-pooler failed: ${i instanceof Error?`${i.name}: ${i.message}`:String(i)}
315
- `),R.exit(1)});
313
+ `);return}if(i.lanePlane&&s.method==="GET"&&o.pathname===ot){if(s.headers.authorization!==`Bearer ${i.token}`){y(r,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({pools:await i.lanePlane.status()}));return}if(i.lanePlane&&s.method==="POST"&&o.pathname===it){if(s.headers.authorization!==`Bearer ${i.token}`){y(r,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let u;try{u=JSON.parse(await Ne(s))}catch(g){y(r,400,g instanceof Error?g.message:String(g),"invalid_request");return}let a=u??{};if(typeof a.pool!="string"||a.pool===""){y(r,400,"pool is required","invalid_request");return}let h=a.hold_ms;if(h!==void 0&&(typeof h!="number"||!Number.isInteger(h)||h<0||h>te)){y(r,400,"hold_ms must be an integer in 0..120000","invalid_request");return}let f=typeof a.model=="string"&&a.model!==""?a.model:void 0,w=typeof a.app=="string"&&a.app!==""?a.app:void 0,k=typeof a.fn=="string"&&a.fn!==""?a.fn:void 0,U=a.shared_app===!0?!0:void 0;try{let g=await i.lanePlane.pick({pool:a.pool,app:w,fn:k,sharedApp:U,model:f,holdMs:h??0});if(g.length===0){let m=i.lanePlane.demandFailure(a.pool);y(r,503,m?`no capacity available for this model right now, retry shortly (the demand mint last failed: ${m})`:"no capacity available for this model right now, retry shortly","lane_capacity",2);return}r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({lanes:g.map(m=>({lane_id:m.laneId,host:m.host}))}))}catch(g){if(g instanceof W){y(r,400,g.message,"lane_target");return}t(`[pooler] lane pick for ${a.pool} failed: ${g instanceof Error?g.message:String(g)}`),y(r,500,"the pooler lane plane failed this pick","pooler_error")}return}if(s.method!=="POST"||o.pathname!==nt){y(r,404,`no route for ${s.method??""} ${o.pathname}`,"not_found");return}if(s.headers.authorization!==`Bearer ${i.token}`){y(r,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let l;try{l=JSON.parse(await Ne(s))}catch(u){y(r,400,u instanceof Error?u.message:String(u),"invalid_request");return}let d=lt(l);if("reason"in d){y(r,400,d.reason,"invalid_request");return}let c=new B(r,d.value.streaming,e);c.head();try{await i.pooler.submit(d.value.request,c)}catch(u){t(`[pooler] request ${d.value.request.request_id} failed unexpectedly: ${u instanceof Error?u.message:String(u)}`),c.fail({status:500,code:"pooler_error",message:"the pooler failed to serve this request"})}})()});return{server:n,close:()=>new Promise(s=>n.close(()=>s()))}}p();import{App as yt,createClientToken as vt}from"@urun-sh/core";p();import{STREAM_END as dt}from"@urun-sh/core";import{gcRequest as ct}from"@urun-sh/core/internal";var ht=new Set(["accepted","done","error"]);function mt(i){if(i===null||typeof i!="object")return{};let e=i,t={};for(let[n,s]of Object.entries(e)){let r=s===null||typeof s!="object"?null:s.toJSON;t[n]=typeof r=="function"?r.call(s):s}return t}function pt(i){if(i===null||typeof i!="object")return null;let e=i,t=e.status;return t!==void 0&&(typeof t!="string"||!ht.has(t))?null:{attempt:typeof e.attempt=="number"?e.attempt:0,...typeof t=="string"?{status:t}:{},...typeof e.error=="string"?{error:e.error}:{}}}function Oe(i){let e=mt(i.get()),t=Number(e[Pe]??0),n={},s=e[V];if(s!==null&&typeof s=="object")for(let[r,o]of Object.entries(s)){let l=pt(o);l!==null&&(n[r]=l)}return{freeSlots:Number.isFinite(t)?t:0,inflight:n,liveSeen:e[F]===!0}}function ft(i){if(i===dt)return{t:"end"};if(i===null||typeof i!="object")return null;let e=i;return e.t==="delta"?{t:"delta",...typeof e.delta=="string"?{delta:e.delta}:{},...typeof e.reasoning=="string"?{reasoning:e.reasoning}:{},...e.tool_calls!==void 0?{tool_calls:e.tool_calls}:{}}:e.t==="response"||e.t==="error"?{t:e.t,body:e.body??i}:null}async function*gt(i,e){let t=i.stream(_e(e)),n=!1;try{for await(let s of t.messages()){let r=ft(s);if(r!==null&&(yield r,r.t!=="delta")){n=!0;return}}}catch(s){throw new P(e,s instanceof Error?s.message:String(s))}if(!n)throw new P(e,"the reply stream ended without a terminal chunk (urun-stream-v1 is at-most-once across a reconnect)")}function Le(i){let{session:e,sessionId:t,goneWatch:n}=i;if(typeof e.whenLive!="function")throw new Error(`pooler session ${t} exposes no whenLive \u2014 a request must never be pushed into a session whose admission is unproven (the cold-wake gate is a contract, not an option)`);if(typeof e.end!="function")throw new Error(`pooler session ${t} exposes no end \u2014 the pooler is the attached client and must be able to release it`);if(typeof e.cancel!="function")throw new Error(`pooler session ${t} exposes no cancel \u2014 the pooler's never-live eviction requires the admission-ticket cancel verb`);if(typeof e.phase!="object"||e.phase===null||typeof e.phase.name!="string")throw new Error(`pooler session ${t} exposes no phase surface \u2014 the servability probe reads core's own phase name live, and a wrapper must never fabricate one`);let s=()=>e.doc(Re),r=!1;return"onPhase"in e&&typeof e.onPhase=="function"&&e.onPhase(o=>{o.name==="live"&&(r=!0)}),{sessionId:t,snapshot:()=>Oe(s()),onDocChange:o=>s().on("change",()=>o()),onGone:o=>n.onGone(o),gone:()=>n.gone(),phaseName:()=>(e.phase.name==="live"&&(r=!0),e.phase.name),everLive:()=>r||Oe(s()).liveSeen,markLiveSeen:async()=>{await J(s(),15e3,"the durable live-seen mark"),s().set({[F]:!0})},whenLive:o=>e.whenLive(o),markInflight:(o,l)=>(s().set({[V]:{[o]:{attempt:l}}}),Promise.resolve()),push:o=>(s().set({[be]:{[o.request_id]:{...o.payload,request_id:o.request_id,consumer_id:o.consumer_id,stream:o.stream}}}),Promise.resolve()),clearRequest:o=>{try{ct(s(),o)}catch{}return Promise.resolve()},reply:o=>gt(e,o),end:async()=>{await e.end(),n.dispose()},cancel:async()=>{await e.cancel(),n.dispose()},namedSessionId:()=>typeof e.namedSessionId=="function"?e.namedSessionId():void 0}}function Me(i){return async(e,t)=>{let n=e.fn??Ie,s=yt(e.app,{baseUrl:i.baseUrl,orgId:i.orgId,getAccessToken:async()=>(await vt(i.apiKey,{baseUrl:i.baseUrl,expiresIn:300,allowedFunctions:[`${e.app}/${n}`],bindPrincipal:!0,...e.sharedApp?{sharedApp:!0}:{}})).token}),r=s[n];if(typeof r!="function")throw new Error(`app "${e.app}" has no function "${n}" \u2014 the pooler cannot dial a slot for it`);let o={concurrencyKey:t,...e.sharedApp?{sharedApp:!0}:{}},l=r.call(s,void 0,o);if(l===null||typeof l!="object")throw new Error(`app "${e.app}" function "${n}" returned no session`);let d=l;return Le({session:d,sessionId:t,goneWatch:X(d,t,{armOnFirstSync:!0})})}}function Tt(){let i=null;i=z({streams:b,note:e=>{i?.isDead("stderr")!==!0&&N(b.stderr,e)}})}async function It(){Tt();let i=Ae(b.env),e=a=>{N(b.stdout,`${a}
314
+ `)},t=new kt(i.valkeyUrl,{maxRetriesPerRequest:null}),n=new x({eval:(a,h,f)=>t.eval(a,h.length,...h,...f)},"pooler"),s=Me(i),r=new C({journal:new O,registry:n,queueDeadlineMs:6e4,silenceDeadlineMs:33e4,backlogThreshold:8,mint:(a,h,f)=>{let w=i.targets.find(k=>k.region===a&&k.model===h);return w===void 0?Promise.reject(new Error(`no pooler target for ${a}:${h} \u2014 refusing to mint`)):s(w,f)},limits:i.targets.map(({region:a,model:h,min:f,max:w})=>({region:a,model:h,min:f,max:w})),scaleUpWaitMs:5e3,mintCooldownMs:1e4,sessionIdleTtlMs:6e4,idleSweepMs:5e3,onEvent:a=>{Te.has(a.kind)&&e(`[pooler] ${a.kind} ${JSON.stringify(a)}`)}});await r.warm();let o=i.laneRuntimeKey,l=i.laneDocHostUrl===void 0?void 0:ne({docHostUrl:i.laneDocHostUrl,redis:t,targets:i.targets,admission:se({baseUrl:i.baseUrl,apiKey:i.apiKey}),...o?{mintRuntimeToken:a=>ee(a,i.orgId,o,Z,Q)}:{},catalogIdentity:async a=>{if(a===void 0)return null;let h=await t.hgetall(re),f=[];for(let[m,v]of Object.entries(h))try{f.push({row:JSON.parse(v),field:m})}catch{}let w=m=>{let v=m.app_slug,H=m.function;return typeof v!="string"||v===""||typeof H!="string"||H===""?null:{app:v,fn:H,sharedApp:m.shared_org_id?!0:void 0}},k=f.find(m=>m.field===a);if(k){let m=w(k.row);if(m)return m}let U=a.includes(":")?a.slice(0,a.indexOf(":")):a,g=f.filter(m=>m.row.model_id===U).sort((m,v)=>m.field.localeCompare(v.field));for(let m of g){let v=w(m.row);if(v)return v}return null},onEvent:a=>{e(`[pooler] ${a.kind} ${JSON.stringify(a)}`)}}),{server:d,close:c}=xe({pooler:r,token:i.token,lanePlane:l,log:e});await new Promise((a,h)=>{d.once("error",h),d.listen(i.port,i.bindHost,()=>a())}),e(`urun-pooler listening on http://${i.bindHost}:${i.port} (targets ${i.targets.map(a=>`${a.region}:${a.model} min=${a.min} max=${a.max}`).join(", ")})${l===void 0?"":" lanes=on"}`);let u=async a=>{e(`urun-pooler: ${a} \u2014 draining`),await c(),await r.close(),await l?.close(),await t.quit().catch(()=>{})};await new Promise(a=>{b.once("SIGINT",()=>{u("SIGINT").finally(a)}),b.once("SIGTERM",()=>{u("SIGTERM").finally(a)})})}It().then(()=>b.exit(0),i=>{N(b.stderr,`urun-pooler failed: ${i instanceof Error?`${i.name}: ${i.message}`:String(i)}
315
+ `),b.exit(1)});