@urun-sh/openai 0.6.30 → 0.6.32

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 (49) hide show
  1. package/dist/chunk-5473ZAQ4.js +17 -0
  2. package/dist/chunk-7OH7UJ2H.js +60 -0
  3. package/dist/chunk-CAR4AEQJ.js +1 -0
  4. package/dist/{chunk-76BZLCGT.js → chunk-GL7EWL3V.js} +1 -1
  5. package/dist/chunk-KTMDSM7F.js +2 -0
  6. package/dist/chunk-L6HTHDVV.js +1 -0
  7. package/dist/chunk-LM4E5YM2.js +19 -0
  8. package/dist/chunk-M3YMNU5P.js +6 -0
  9. package/dist/chunk-NN6TQQUG.js +1 -0
  10. package/dist/chunk-OOCRI7ZM.js +6 -0
  11. package/dist/chunk-PAYCMH5F.js +1 -0
  12. package/dist/{responses-turn-BGb_XPOa.d.ts → composite-DMawda97.d.ts} +125 -83
  13. package/dist/{responses-turn-DXrwiPJh.d.cts → composite-DtBebn0Y.d.cts} +545 -309
  14. package/dist/gemini-live.cjs +2 -2
  15. package/dist/gemini-live.d.cts +85 -105
  16. package/dist/gemini-live.d.ts +48 -48
  17. package/dist/gemini-live.js +1 -1
  18. package/dist/hosted/bin.cjs +56 -42
  19. package/dist/hosted/bin.js +4 -22
  20. package/dist/hosted/index.cjs +52 -38
  21. package/dist/hosted/index.d.cts +230 -7
  22. package/dist/hosted/index.d.ts +114 -3
  23. package/dist/hosted/index.js +1 -1
  24. package/dist/index.cjs +1 -1
  25. package/dist/index.d.cts +1 -1
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.js +1 -1
  28. package/dist/{models-DUdx_Y6X.d.cts → models-D7F0bLJ3.d.cts} +14 -0
  29. package/dist/{models-DUdx_Y6X.d.ts → models-D7F0bLJ3.d.ts} +6 -0
  30. package/dist/pi-extension/index.cjs +6 -6
  31. package/dist/pi-extension/index.js +1 -1
  32. package/dist/pi-extension/standalone.cjs +33 -33
  33. package/dist/pooler/bin.cjs +335 -0
  34. package/dist/pooler/bin.js +316 -0
  35. package/dist/proxy/cli.cjs +58 -53
  36. package/dist/proxy/cli.js +1 -1
  37. package/dist/proxy/conformance-probe.cjs +1 -0
  38. package/dist/proxy/conformance-probe.js +1 -0
  39. package/dist/proxy/index.cjs +31 -28
  40. package/dist/proxy/index.d.cts +315 -167
  41. package/dist/proxy/index.d.ts +85 -53
  42. package/dist/proxy/index.js +1 -1
  43. package/package.json +14 -4
  44. package/dist/chunk-55LV3IXW.js +0 -62
  45. package/dist/chunk-7V2JKPIG.js +0 -1
  46. package/dist/chunk-CUDFHFNX.js +0 -4
  47. package/dist/chunk-K23AZPI4.js +0 -1
  48. package/dist/chunk-OPMTYD3Z.js +0 -2
  49. package/dist/chunk-WUNJ3FMI.js +0 -8
@@ -0,0 +1,316 @@
1
+ #!/usr/bin/env node
2
+ import{a as Te}from"../chunk-LM4E5YM2.js";import{a as J}from"../chunk-L6HTHDVV.js";import{s as x,t as W}from"../chunk-M3YMNU5P.js";import{i as D}from"../chunk-OOCRI7ZM.js";import{b as Pe,c as f}from"../chunk-YSFSRI3D.js";f();var rn=Pe(Te(),1);import b from"process";import{Redis as Et}from"ioredis";f();f();var H=`
3
+ local slot, retired, meta = KEYS[1], KEYS[2], KEYS[3]
4
+ local key, gen, now = ARGV[1], tonumber(ARGV[2]), ARGV[3]
5
+ -- The session-as-routing-identity schema (docs/pooler-session-registry.md
6
+ -- \xA72.1): ARGV 4-6 carry {model, capabilities, cacheNs} when the caller
7
+ -- speaks the schema; absent (the pre-schema writer) keeps the old shape.
8
+ local model, capabilities, cacheNs = ARGV[4], ARGV[5], ARGV[6]
9
+ if redis.call('SISMEMBER', retired, key) == 1 then
10
+ return 'reject:retired-corpse-reuse'
11
+ end
12
+ local state = redis.call('HGET', slot, 'state')
13
+ if state then
14
+ if state == 'paused' then
15
+ redis.call('HSET', slot, 'state', 'queued', 'since', now, 'gen', gen)
16
+ -- The cache identity is new (cacheGen 0 again \u2014 a fresh cache) but the
17
+ -- CONNECTION epoch PERSISTS: a fencing token never decreases, or a
18
+ -- superseded connection that observed the reset-to-0 value re-validates
19
+ -- (the F6 hole \u2014 epoch fences ATTACH/GRANT/PUBLISH for every state).
20
+ if cacheNs then redis.call('HSET', slot, 'cacheNs', cacheNs, 'cacheGen', 0) end
21
+ redis.call('HINCRBY', meta, 'paused', -1)
22
+ redis.call('HINCRBY', meta, 'queued', 1)
23
+ return 'ok'
24
+ end
25
+ return 'reject:mint-' .. state
26
+ end
27
+ local live = (tonumber(redis.call('HGET', meta, 'attached') or 0)
28
+ + tonumber(redis.call('HGET', meta, 'queued') or 0)
29
+ + tonumber(redis.call('HGET', meta, 'paused') or 0))
30
+ local max = tonumber(redis.call('HGET', meta, 'max') or 0)
31
+ if max > 0 and live >= max then
32
+ return 'reject:max'
33
+ end
34
+ redis.call('HSET', slot, 'state', 'queued', 'gen', gen, 'inFlight', 0, 'since', now)
35
+ if cacheNs then
36
+ redis.call('HSET', slot, 'cacheNs', cacheNs, 'cacheGen', 0, 'epoch', 0,
37
+ 'model', model, 'capabilities', capabilities)
38
+ end
39
+ redis.call('HINCRBY', meta, 'queued', 1)
40
+ return 'ok'
41
+ `,U=`
42
+ local slot, genkey, retired, meta = KEYS[1], KEYS[2], KEYS[3], KEYS[4]
43
+ local key, gen, sessionId, now = ARGV[1], tonumber(ARGV[2]), ARGV[3], ARGV[4]
44
+ -- The session-registry schema (\xA72.3): ARGV[5] is the caller's OBSERVED
45
+ -- epoch \u2014 a re-attach whose observed epoch is stale is a superseded
46
+ -- connection claiming ownership; reject. ABSENT = the pre-schema caller
47
+ -- (compat seam, epoch check skipped).
48
+ local obsEpoch = tonumber(ARGV[5])
49
+ if redis.call('SISMEMBER', retired, key) == 1 then
50
+ return 'reject:retired-corpse-reuse'
51
+ end
52
+ local cur = tonumber(redis.call('GET', genkey) or 0)
53
+ if gen ~= cur then
54
+ return 'reject:generation'
55
+ end
56
+ local state = redis.call('HGET', slot, 'state')
57
+ if not state then
58
+ return 'reject:attach-without-mint'
59
+ end
60
+ -- THE EPOCH FENCE runs BEFORE the state gate (every state, queued
61
+ -- included): a stale observed epoch is a superseded connection claiming
62
+ -- ownership, whatever the record's current state \u2014 the queued path must
63
+ -- not be the hole the fence misses. ABSENT obsEpoch = the pre-schema
64
+ -- caller (compat seam, check skipped).
65
+ if obsEpoch ~= nil then
66
+ local curEpoch = tonumber(redis.call('HGET', slot, 'epoch') or 0)
67
+ if obsEpoch ~= curEpoch then
68
+ return 'reject:epoch'
69
+ end
70
+ end
71
+ if state ~= 'queued' then
72
+ return 'reject:attach-' .. state
73
+ end
74
+ -- The connection epoch (schema \xA72.3): the attach is the moment a new
75
+ -- connection becomes the record's owner \u2014 the epoch moves forward, the
76
+ -- cache generation with it (a new engine binding presumes the old KV gone).
77
+ redis.call('HINCRBY', slot, 'epoch', 1)
78
+ redis.call('HINCRBY', slot, 'cacheGen', 1)
79
+ redis.call('HSET', slot, 'state', 'attached', 'sessionId', sessionId, 'since', now, 'dead', 0)
80
+ redis.call('HINCRBY', meta, 'queued', -1)
81
+ redis.call('HINCRBY', meta, 'attached', 1)
82
+ return 'ok'
83
+ `,Q=`
84
+ local slot, meta = KEYS[1], KEYS[2]
85
+ local key, reason, now = ARGV[1], ARGV[2], ARGV[3]
86
+ local state = redis.call('HGET', slot, 'state')
87
+ if not state then
88
+ return 'reject:detach-unknown'
89
+ end
90
+ if state == 'ended' or state == 'retired' or state == 'paused' then
91
+ return 'ok'
92
+ end
93
+ redis.call('HSET', slot, 'state', 'paused', 'since', now, 'lastReason', reason)
94
+ redis.call('HINCRBY', meta, state, -1)
95
+ redis.call('HINCRBY', meta, 'paused', 1)
96
+ return 'ok'
97
+ `,z=`
98
+ local slot, genkey, retired, meta, newslot = KEYS[1], KEYS[2], KEYS[3], KEYS[4], KEYS[5]
99
+ local oldKey, newKey, newGen = ARGV[1], ARGV[2], tonumber(ARGV[3])
100
+ if redis.call('SISMEMBER', retired, oldKey) == 1 then
101
+ return 'reject:double-rotate'
102
+ end
103
+ local cur = tonumber(redis.call('GET', genkey) or 0)
104
+ if not (newGen > cur) then
105
+ return 'reject:generation-monotone'
106
+ end
107
+ redis.call('SET', genkey, newGen)
108
+ local state = redis.call('HGET', slot, 'state')
109
+ if state then
110
+ if state ~= 'ended' then
111
+ redis.call('HINCRBY', meta, state, -1)
112
+ redis.call('HINCRBY', meta, 'retired', 1)
113
+ end
114
+ redis.call('HSET', slot, 'state', 'retired', 'rotatedTo', newKey, 'since', ARGV[4])
115
+ end
116
+ redis.call('SADD', retired, oldKey)
117
+ if redis.call('HSETNX', newslot, 'state', 'paused') == 1 then
118
+ redis.call('HSET', newslot, 'gen', newGen, 'inFlight', 0, 'since', ARGV[4])
119
+ redis.call('HINCRBY', meta, 'paused', 1)
120
+ end
121
+ return 'ok'
122
+ `,X=`
123
+ local slot, meta = KEYS[1], KEYS[2]
124
+ local key, now = ARGV[1], ARGV[2]
125
+ local state = redis.call('HGET', slot, 'state')
126
+ if not state then
127
+ return 'reject:end-unknown'
128
+ end
129
+ if state == 'ended' then
130
+ return 'ok'
131
+ end
132
+ if state == 'retired' then
133
+ return 'reject:end-retired'
134
+ end
135
+ local retained = tonumber(redis.call('HGET', slot, 'inFlight') or 0)
136
+ if retained > 0 then
137
+ redis.call('HINCRBY', meta, 'inflight', -retained)
138
+ end
139
+ redis.call('HSET', slot, 'state', 'ended', 'since', now)
140
+ redis.call('HINCRBY', meta, state, -1)
141
+ redis.call('HINCRBY', meta, 'ended', 1)
142
+ return 'ok'
143
+ `,Z=`
144
+ local slot, meta = KEYS[1], KEYS[2]
145
+ local key = ARGV[1]
146
+ local state = redis.call('HGET', slot, 'state')
147
+ if state == 'ended' then
148
+ return 'ok'
149
+ end
150
+ if not state then
151
+ return 'reject:lease-unknown'
152
+ end
153
+ redis.call('HINCRBY', slot, 'inFlight', 1)
154
+ redis.call('HINCRBY', meta, 'inflight', 1)
155
+ return 'ok'
156
+ `,A=`
157
+ local slot, meta = KEYS[1], KEYS[2]
158
+ local key, obsCap, obsVer = ARGV[1], tonumber(ARGV[2]), tonumber(ARGV[3])
159
+ -- The session-registry schema (\xA72.3): ARGV[4] is the caller's OBSERVED
160
+ -- connection epoch. ABSENT = the pre-schema caller (compat seam): the
161
+ -- check is skipped, exactly as an old-shape record reads epoch 0.
162
+ local obsEpoch = tonumber(ARGV[4])
163
+ local state = redis.call('HGET', slot, 'state')
164
+ if not state then
165
+ return 'reject:grant-unknown'
166
+ end
167
+ if state == 'ended' then
168
+ return 'reject:grant-ended'
169
+ end
170
+ if state == 'retired' then
171
+ return 'reject:grant-retired'
172
+ end
173
+ local cap = tonumber(redis.call('HGET', meta, 'cap') or 0)
174
+ local ver = tonumber(redis.call('HGET', meta, 'config_version') or 0)
175
+ if obsCap ~= cap or obsVer ~= ver then
176
+ return 'reject:cap-moved'
177
+ end
178
+ -- The connection fence: a grant from a superseded connection rejects \u2014
179
+ -- the stale-owner-dispatch hole ref-design's epoch closes.
180
+ if obsEpoch ~= nil then
181
+ local curEpoch = tonumber(redis.call('HGET', slot, 'epoch') or 0)
182
+ if obsEpoch ~= curEpoch then
183
+ return 'reject:epoch'
184
+ end
185
+ end
186
+ local f = tonumber(redis.call('HGET', slot, 'inFlight') or 0)
187
+ if f + 1 > cap then
188
+ return 'reject:cap'
189
+ end
190
+ redis.call('HINCRBY', slot, 'inFlight', 1)
191
+ redis.call('HINCRBY', meta, 'inflight', 1)
192
+ return 'ok'
193
+ `,ee=`
194
+ local meta = KEYS[1]
195
+ return (redis.call('HGET', meta, 'max') or '-1')
196
+ .. '|' .. (redis.call('HGET', meta, 'cap') or '-1')
197
+ .. '|' .. (redis.call('HGET', meta, 'config_version') or '0')
198
+ `,te=`
199
+ local slot, meta = KEYS[1], KEYS[2]
200
+ local key, now = ARGV[1], ARGV[2]
201
+ local state = redis.call('HGET', slot, 'state')
202
+ if state == 'ended' then
203
+ return 'ok'
204
+ end
205
+ if not state then
206
+ return 'reject:release-unknown'
207
+ end
208
+ local f = tonumber(redis.call('HGET', slot, 'inFlight') or 0)
209
+ if f - 1 < 0 then
210
+ return 'reject:underflow'
211
+ end
212
+ redis.call('HSET', slot, 'inFlight', f - 1, 'idleSince', now)
213
+ redis.call('HINCRBY', meta, 'inflight', -1)
214
+ return 'ok'
215
+ `,ne=`
216
+ local meta = KEYS[1]
217
+ local max, cap = tonumber(ARGV[1]), tonumber(ARGV[2])
218
+ if not max or max < 0 or not cap or cap < 1 then
219
+ return 'reject:retune'
220
+ end
221
+ redis.call('HSET', meta, 'max', max, 'cap', cap)
222
+ redis.call('HINCRBY', meta, 'config_version', 1)
223
+ return 'ok'
224
+ `,se=`
225
+ local meta = KEYS[1]
226
+ local max, cap = tonumber(ARGV[1]), tonumber(ARGV[2])
227
+ if not max or max < 0 or not cap or cap < 1 then
228
+ return 'reject:config'
229
+ end
230
+ if redis.call('HSETNX', meta, 'max', max) == 0 then
231
+ return 'reject:config-exists'
232
+ end
233
+ redis.call('HSET', meta, 'cap', cap)
234
+ return 'ok'
235
+ `,re=`
236
+ local prefix, meta = ARGV[1], KEYS[1]
237
+ local cursor, pageSize = ARGV[2], tonumber(ARGV[3])
238
+ local lines = {}
239
+ local next = cursor
240
+ while true do
241
+ local res = redis.call('SCAN', next, 'MATCH', prefix .. '*', 'COUNT', pageSize)
242
+ next = res[1]
243
+ for _, k in ipairs(res[2]) do
244
+ lines[#lines + 1] = string.sub(k, #prefix + 1)
245
+ .. '|' .. (redis.call('HGET', k, 'state') or 'none')
246
+ .. '|' .. (redis.call('HGET', k, 'inFlight') or '0')
247
+ .. '|' .. (redis.call('HGET', k, 'gen') or '0')
248
+ .. '|' .. (redis.call('HGET', k, 'sessionId') or '')
249
+ end
250
+ if #lines >= pageSize or next == '0' then break end
251
+ end
252
+ local fields = redis.call('HGETALL', meta)
253
+ local m = {}
254
+ for i = 1, #fields, 2 do
255
+ m[#m + 1] = fields[i] .. '=' .. (fields[i + 1] or '')
256
+ end
257
+ return next .. '#' .. table.concat(m, ',') .. '#' .. table.concat(lines, '\\n')
258
+ `,ie=`
259
+ local fields = redis.call('HGETALL', KEYS[1])
260
+ local m = {}
261
+ for i = 1, #fields, 2 do
262
+ m[#m + 1] = fields[i] .. '=' .. (fields[i + 1] or '')
263
+ end
264
+ return table.concat(m, ',')
265
+ `,oe=`
266
+ local out = {}
267
+ for i = 1, #ARGV do
268
+ out[#out + 1] = (redis.call('HGET', ARGV[i], 'state') or 'none')
269
+ .. '|' .. (redis.call('HGET', ARGV[i], 'inFlight') or '0')
270
+ end
271
+ return table.concat(out, '\\n')
272
+ `,ae=`
273
+ local gen = redis.call('GET', KEYS[1])
274
+ if not gen then return '0' end
275
+ return gen
276
+ `,le=`
277
+ local state = redis.call('HGET', KEYS[1], 'state')
278
+ if not state then return 'none||' end
279
+ return state .. '|' .. (redis.call('HGET', KEYS[1], 'sessionId') or '') .. '|' .. (redis.call('HGET', KEYS[1], 'lastReason') or '')
280
+ `,ue=`
281
+ local slot = KEYS[1]
282
+ local key, obsEpoch = ARGV[1], tonumber(ARGV[2])
283
+ local state = redis.call('HGET', slot, 'state')
284
+ if not state then
285
+ return 'reject:publish-unknown'
286
+ end
287
+ if state == 'ended' then
288
+ return 'ok'
289
+ end
290
+ local cur = tonumber(redis.call('HGET', slot, 'epoch') or 0)
291
+ if obsEpoch ~= cur then
292
+ return 'reject:epoch'
293
+ end
294
+ redis.call('HSET', slot,
295
+ 'maxConcurrent', ARGV[3],
296
+ 'queueDepth', ARGV[4],
297
+ 'cacheGen', ARGV[5],
298
+ 'capabilities', ARGV[6])
299
+ return 'ok'
300
+ `;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},Ie=100,de=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},qe=i=>(i===""?[]:i.split(`
301
+ `)).map(e=>{let[t,n,s,r,o]=e.split("|");return{key:t,state:n,inFlight:Number(s),gen:Number(r),sessionId:o}});function _(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 k=()=>String(Date.now()),N=class{constructor(e,t){this.evalFn=e;this.pool=t}evalFn;pool;keys(e,t=!0,n=!0){let{base:s}=_(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})}mint(e){let{gen:t}=_(e);return this.run("mint",H,this.keys(e,!1,!0),[e,t,k()],{slotKey:e,gen:t})}mintWith(e,t){let{gen:n}=_(e);return this.run("mint",H,this.keys(e,!1,!0),[e,n,k(),t.model,t.capabilities??"",t.cacheNs],{slotKey:e,gen:n,cacheNs:t.cacheNs})}attachWithEpoch(e,t,n){let{gen:s}=_(e);return this.run("attach",U,this.keys(e),[e,s,t,k(),n],{slotKey:e,gen:s,sessionId:t,observedEpoch:n})}publish(e,t,n){return this.run("publish",ue,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}=_(e);return this.run("attach",U,this.keys(e),[e,n,t,k()],{slotKey:e,gen:n,sessionId:t})}detach(e,t){return this.run("detach",Q,this.keys(e,!1,!1),[e,t,k()],{slotKey:e,reason:t})}rotate(e,t){let{gen:n}=_(t),s=[...this.keys(e),`sreg:${this.pool}:slot:${t}`];return this.run("rotate",z,s,[e,t,n,k()],{oldKey:e,newKey:t,newGen:n})}end(e){return this.run("end",X,this.keys(e,!1,!1),[e,k()],{slotKey:e})}lease(e){return this.run("lease",Z,this.keys(e,!1,!1),[e],{slotKey:e})}release(e){return this.run("release",te,this.keys(e,!1,!1),[e,k()],{slotKey:e})}configure(e,t){return this.run("config",se,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}retune(e,t){return this.run("retune",ne,[`sreg:${this.pool}:meta`],[e,t],{max:e,inFlightCap:t})}async tuning(){let e=await this.evalFn.eval(ee,[`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,Ie);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(ie,[`sreg:${this.pool}:meta`],[]);return de(e)}async snapshotPage(e,t){let n=`sreg:${this.pool}:slot:`,s=await this.evalFn.eval(re,[`sreg:${this.pool}:meta`],[n,e,t]),[r,o,u]=s.split("#");return{cursor:r,counts:de(o??""),slots:qe(u??"")}}async readRecords(e){if(e.length===0)return[];let t=`sreg:${this.pool}:slot:`,n=await this.evalFn.eval(oe,[],e.map(s=>t+s));return(n===""?[]:n.split(`
302
+ `)).map(s=>{let[r,o]=s.split("|");return{state:r,inFlight:Number(o)}})}async generation(e){let{base:t}=_(e),n=await this.evalFn.eval(ae,[`sreg:${this.pool}:gen:${t}`],[]);return Number(n)}async record(e){let n=(await this.evalFn.eval(le,[`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}}};f();import{Queue as Ae}from"bullmq";import{randomUUID as xe}from"crypto";var Ne=3e4,Oe=60,Le=1e3;function ce(i){let e;try{e=JSON.parse(i)}catch{return null}if(typeof e!="object"||e===null||!("proxy_url"in e))return null;let t=e;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0}}function me(i){let e=i.now??Date.now,t=new Map,n=new Map,s=new Map,r=new Map,o=new Set,u=a=>{let d=t.get(a);return d||(d=i.queueFor?.(a)??c(a),t.set(a,d)),d},c=a=>{let d=i.redis,p=new Ae(a,{prefix:"bull:dispatch",connection:d});return{add:(h,v,g)=>p.add(h,v,g),reassertWaiting:async h=>{let g=(await p.getJobs(["waiting"])).filter(y=>y.data?.session_kind==="lane").sort((y,E)=>y.timestamp-E.timestamp);if(g.length===0)return{found:0};for(let y of g)try{await y.updateData({...y.data,demand_reaffirmed_at_ms:h})}catch{}for(let y of g.slice(1))try{await y.remove()}catch{}return{found:g.length}},close:()=>p.close()}},m=async a=>{let d=await i.redis.hgetall(`lanes:${a}`),p=[];for(let[g,y]of Object.entries(d)){let E=ce(y);E&&E.proxy_url===i.docHostUrl&&p.push(g)}if(p.length===0)return[];let h=await i.redis.mget(...p.map(g=>`lane_hosts:${g}`)),v=[];return p.forEach((g,y)=>{let E=h[y];E&&v.push({laneId:g,host:E})}),v},l=async(a,d)=>{let p=n.get(a)??0,h=e();if(h-p<Ne)return;n.set(a,h);let v=u(a);if((await v.reassertWaiting(e()).catch(E=>{throw n.delete(a),E})).found>0){r.set(d??"",(r.get(d??"")??0)+1),i.onEvent?.({kind:"lane_demand_reaffirmed",pool:a,model:d});return}let y=`lane-${xe().replaceAll("-","")}`;await v.add("session",{session_id:y,logical_id:y,incarnation:h,session_kind:"lane",lane_id:y,session_server_url:i.docHostUrl,proxy_url:i.docHostUrl,session_idle_timeout_seconds:Oe,thread_key:"lane",demand_reaffirmed_at_ms:e()},{jobId:`${y}#${h}`,attempts:3}),s.set(d??"",(s.get(d??"")??0)+1),i.onEvent?.({kind:"lane_demand_enqueued",pool:a,model:d})};return{async pick({pool:a,model:d,holdMs:p=0}){o.add(a);let h=async()=>{try{await l(a,d)}catch(E){n.delete(a),i.onEvent?.({kind:"lane_demand_failed",pool:a,model:d,reason:E instanceof Error?E.message:String(E)})}},v=async()=>{try{return await m(a)}catch{return[]}},g=await v();if(g.length>0)return g;await h();let y=e()+p;for(;e()<y;){if(await new Promise(E=>setTimeout(E,Le)),g=await v(),g.length>0)return g;await h()}return[]},async status(){let a=[...o].sort();return Promise.all(a.map(async d=>{let p=[];try{let h=await i.redis.hgetall(`lanes:${d}`),v=Object.keys(h),g=v.length===0?[]:await i.redis.mget(...v.map(E=>`lane_hosts:${E}`)),y=e();p=v.map((E,ke)=>{let B=h[E],q=B===void 0?null:ce(B);return{laneId:E,occupantId:q?.occupant_id??"",capacity:q?.capacity??0,heartbeatAgeMs:q===null?null:y-q.heartbeat_ms,advertisedHere:q?.proxy_url===i.docHostUrl,hosted:!!g[ke]}})}catch{}return{pool:d,lanes:p,lastDemandAt:n.get(d)??null}}))},demandCounters(){return[...new Set([...s.keys(),...r.keys()])].sort().map(d=>({model:d,enqueued:s.get(d)??0,reaffirmed:r.get(d)??0}))},async close(){await Promise.all([...t.values()].map(a=>a.close().catch(()=>{}))),t.clear()}}}f();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})))}};f();f();var G=i=>`${i.systemPrompt??""}\0${i.firstMessage??""}`;function $(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 he=512,Ge=4096,L=8,C=class{root={children:new Map,sessions:new Map};nodes=1;insert(e,t,n){let s=e.slice(0,he),r=this.root;for(let o=0;o<s.length;o+=L){let u=s.slice(o,o+L),c=r.children.get(u);if(!c){if(this.nodes>=Ge)return;c={children:new Map,sessions:new Map},r.children.set(u,c),this.nodes+=1}c.sessions.set(t,n),r=c}}match(e,t){let n=e.slice(0,he),s=this.root,r=null,o=0,u=0;for(;;){let c=null,m=-1;for(let[d,p]of s.sessions)t.has(d)&&(p>m||p===m&&c!==null&&d<c)&&(c=d,m=p);if(c!==null&&(r={sessionId:c,depth:o}),u>=n.length)break;let l=n.slice(u,u+L),a=s.children.get(l);if(!a)break;s=a,o+=l.length,u+=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 pe(i,e,t,n){if(e.length===0)return null;let s=new Map(e.map(l=>[l.sessionId,l])),r=l=>{let a=s.get(l);return a!==void 0&&a.backlog<n.backlogThreshold},o=new Set(s.keys()),u=n.sticky.get($(i));if(u!==void 0&&r(u))return{sessionId:u,reason:"sticky"};let c=t.match(G(i),o);if(c!==null&&r(c.sessionId))return{sessionId:c.sessionId,reason:"prefix"};let m=null;for(let l of e)(m===null||l.backlog<m.backlog||l.backlog===m.backlog&&l.sessionId<m.sessionId)&&(m=l);return m===null?null:{sessionId:m.sessionId,reason:"load"}}f();var fe="llm",j="requests",Me="llm-resp",F=(i,e,t,n=0)=>`decision:pooler-${i}-${e}`.replaceAll(":","-")+`:${t}`+(n>0?`:${n}`:""),Y=i=>{let{base:e,gen:t}=_(i);return`${e}:${t+1}`},ge=i=>`${Me}:${i}`,ye="free_slots",K="inflight",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 De=6e4,He=33e4,Ue=2,$e=8,je=5e3,Fe=1e4,Ye=6e4,Ke=5e3,M=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??De,this.silenceDeadlineMs=e.silenceDeadlineMs??He,this.maxAttempts=e.maxAttempts??Ue,this.backlogThreshold=e.backlogThreshold??$e,this.mint=e.mint,this.limits=e.limits??[],this.scaleUpWaitMs=e.scaleUpWaitMs??je,this.mintCooldownMs=e.mintCooldownMs??Fe,this.sessionIdleTtlMs=e.sessionIdleTtlMs??Ye,this.idleSweepMs=e.idleSweepMs??Ke,this.onEvent=e.onEvent??(()=>{}),(this.mint!==void 0||this.limits.length>0)&&this.armSweep()}armSweep(){this.sweepTimer=setInterval(()=>this.sweep(),this.idleSweepMs),this.sweepTimer.unref?.()}sweep(){if(!this.closed)for(let e of this.pools.values()){let t=this.limitsFor(e);if(t===null)continue;let n=e.queue.length===0;e.sessions.length<t.max&&this.queuePressure(e)?this.tryMint(e,"queue_pressure"):e.sessions.length<t.min&&this.tryMint(e,"min_floor"),n&&e.sessions.length>t.min&&this.scaleDownOldestIdle(e,t)}}limitsFor(e){return this.limits.find(t=>t.region===e.region&&t.model===e.model)??null}queuePressure(e){if(e.queue.length===0)return!1;let t=this.now();return e.queue.some(n=>t-n.queuedAt>=this.scaleUpWaitMs)}tryMint(e,t){if(this.mint===void 0||this.closed||e.minting)return;let n=this.limitsFor(e);if(n===null||e.sessions.length>=n.max)return;let 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(m=>m.session===s&&m.phase==="dispatched")||n-(e.lastActivity.get(s)??n)<this.sessionIdleTtlMs)continue;let u=e.sessions.indexOf(s);if(u===-1)continue;e.sessions.splice(u,1),e.radix.forget(s.sessionId),e.lastActivity.delete(s);let c=e.slotKeys.get(s.sessionId);c!==void 0&&(e.slotKeys.delete(s.sessionId),this.registryCall("end",c,()=>this.registry?.end(c))),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(m=>{this.onEvent({kind:"scaled_down_end_failed",pool:this.key(e.region,e.model),sessionId:s.sessionId,reason:m instanceof Error?m.message:String(m)})});return}}static poolKey(e,t){return`${e}:${t}`}async claimSlot(e,t,n){let s=F(e,t,n);if(this.registry===null)return s;for(let r=0;;r++){let o=await this.registry.generation(s),u=F(e,t,n,o),{state:c,sessionId:m,lastReason:l}=await this.registry.record(u);if(c==="none"||c==="paused"&&m===void 0&&l===void 0)try{return await this.registry.mint(u),u}catch(a){this.rethrowUnlessClaimRace(a,r);continue}else{let a=Y(u);try{await this.registry.rotate(u,a),await this.registry.mint(a)}catch(d){this.rethrowUnlessClaimRace(d,r);continue}return this.onEvent({kind:"slot_rotated",pool:this.key(e,t),slotKey:u,successor:a,reason:c==="paused"?"boot claim over an evicted slot's dead session":`boot claim over a previous pod's ${c} 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.slotKeys.set(n.sessionId,s),n.whenLive().then(()=>{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)})}),r.offs.push(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:null,queuedAt:this.now()}),this.onEvent({kind:"reconciled_inflight",pool:t,requestId:n.request.request_id,sessionId:n.sessionId})}}for(let n of await this.journal.queued(e.region,e.model))await this.journal.finish(n.request_id),this.onEvent({kind:"reconciled_caller_gone",pool:t,requestId:n.request_id});for(let n of e.sessions){let 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 u={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:null,queuedAt:this.now()};e.records.set(r,u),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:null,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)t();e.offs.length=0,e.sessions.length=0,e.queue.length=0,e.records.clear(),e.lastActivity.clear()}this.pools.clear()}async close(){this.closed=!0,this.sweepTimer!==null&&(clearInterval(this.sweepTimer),this.sweepTimer=null);for(let e of this.pools.values()){for(let n of e.records.values())this.clearTimers(n),n.phase!=="finished"&&this.settle(n,{status:503,code:"draining",message:"pooler is shutting down",retryAfterSeconds:5});for(let n of e.offs)n();e.offs.length=0,e.lastActivity.clear();for(let n of e.slotKeys.values())this.registryCall("rotate",n,()=>this.registry?.rotate(n,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 C,offs:[],slotKeys:new Map,needsReconcile:!0,lastMintAt:0,minting:!1,mintSeq:0,lastActivity: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=>o.gone()===null&&!t.tried.has(o.sessionId)&&this.creditFor(e,o)>0).map(o=>({sessionId:o.sessionId,backlog:this.backlogOf(e,o)})),s=pe(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(c){this.lost(e,n,c);return}await this.journal.dispatched(n.request.request_id,t.sessionId,n.attempt);let o=$(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 u=e.slotKeys.get(t.sessionId);u!==void 0&&this.registryCall("lease",u,()=>this.registry?.lease(u)),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 D&&t.session!==null&&this.evict(e,t.session,n);let r=e.sessions.some(o=>o.gone()===null&&!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"))}evict(e,t,n){let s=e.sessions.indexOf(t);if(s===-1)return;e.sessions.splice(s,1),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,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){t.silenceTimer===null&&(t.silenceTimer=setTimeout(()=>{t.silenceTimer=null,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=null)}clearTimers(e){this.clearTimer(e,"queue"),this.clearTimer(e,"silence")}stats(){return{pools:[...this.pools.entries()].map(([e,t])=>({pool:e,queued:t.queue.length,inflight:[...t.records.values()].filter(n=>n.phase==="dispatched").length,sessions:t.sessions.length}))}}};f();var Ve="0.0.0.0",Ee="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},Be=(i,e)=>{if(i===null||typeof i!="object")throw new Error(`URUN_POOLER_TARGETS[${e}] must be an object`);let t=i,n=u=>{let c=t[u];if(typeof c!="string"||c==="")throw new Error(`URUN_POOLER_TARGETS[${e}].${u} is required`);return c},s=u=>{let c=t[u];if(typeof c!="number"||!Number.isInteger(c))throw new Error(`URUN_POOLER_TARGETS[${e}].${u} must be an integer`);return c},r,o;if(t.sessions!==void 0){let u=t.sessions;if(typeof u!="number"||!Number.isInteger(u)||u<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=u,o=u}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)})`)}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}};function ve(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(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(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:(i.URUN_LANE_DOC_HOST_URL??"").trim()||void 0,targets:r.map(Be)}}f();import{createServer as We}from"http";var Je="/pooler/v1/inference",Qe="/readyz",ze="/metrics",Xe="/pooler/v1/lanes/pick",Ze="/pooler/v1/lanes/status",et=1e4,Se=16*1024*1024;function S(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 tt(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 V=class{constructor(e,t,n){this.res=e;this.streaming=t;this.keepaliveMs=n}res;streaming;keepaliveMs;keepalive=null;terminal=null;head(){this.streaming&&!this.res.headersSent&&(this.res.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive"}),this.keepalive=setInterval(()=>{this.res.writableEnded||this.res.write(`: keepalive
303
+
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
+
306
+ `);return}e.t!=="delta"&&(this.terminal=e)}done(){if(this.stopKeepalive(),this.streaming){this.res.write(`data: [DONE]
307
+
308
+ `),this.res.end();return}if(this.terminal!==null&&this.terminal.t==="error"){let t=this.terminal.body,n=t!==null&&typeof t=="object"&&typeof t.message=="string"?String(t.message):"the upstream turn failed";S(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){S(this.res,e.status,e.message,e.code,e.retryAfterSeconds);return}this.res.write(`data: ${JSON.stringify({error:{message:e.message,type:"pooler_error",code:e.code}})}
309
+
310
+ `),this.res.write(`data: [DONE]
311
+
312
+ `),this.res.end()}stopKeepalive(){this.keepalive!==null&&clearInterval(this.keepalive),this.keepalive=null}};function we(i){return new Promise((e,t)=>{let n=0,s=[];i.on("data",r=>{if(n+=r.length,n>Se){t(new Error(`request body exceeds ${Se} bytes`)),i.destroy();return}s.push(r)}),i.on("end",()=>e(Buffer.concat(s).toString("utf8"))),i.on("error",t)})}function Re(i){let e=i.keepaliveMs??et,t=i.log??(()=>{}),n=We((s,r)=>{(async()=>{let o=new URL(s.url??"/","http://pooler.internal");if(s.method==="GET"&&o.pathname===Qe){r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({ok:!0,...i.pooler.stats()}));return}if(s.method==="GET"&&o.pathname===ze){let l=["# 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 d=`pool="${a.pool}"`;l.push(`pooler_pool_queued{${d}} ${a.queued}`),l.push(`pooler_pool_inflight{${d}} ${a.inflight}`),l.push(`pooler_pool_sessions{${d}} ${a.sessions}`)}for(let a of i.lanePlane?.demandCounters()??[]){let d=`model="${a.model.replaceAll('"','\\"')}"`;l.push(`pooler_lane_demand_enqueued{${d}} ${a.enqueued}`),l.push(`pooler_lane_demand_reaffirmed{${d}} ${a.reaffirmed}`)}r.writeHead(200,{"content-type":"text/plain; version=0.0.4"}),r.end(`${l.join(`
313
+ `)}
314
+ `);return}if(i.lanePlane&&s.method==="GET"&&o.pathname===Ze){if(s.headers.authorization!==`Bearer ${i.token}`){S(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===Xe){if(s.headers.authorization!==`Bearer ${i.token}`){S(r,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let l;try{l=JSON.parse(await we(s))}catch(h){S(r,400,h instanceof Error?h.message:String(h),"invalid_request");return}let a=l??{};if(typeof a.pool!="string"||a.pool===""){S(r,400,"pool is required","invalid_request");return}let d=a.hold_ms;if(d!==void 0&&(typeof d!="number"||!Number.isInteger(d)||d<0||d>12e4)){S(r,400,"hold_ms must be an integer in 0..120000","invalid_request");return}let p=typeof a.model=="string"&&a.model!==""?a.model:void 0;try{let h=await i.lanePlane.pick({pool:a.pool,model:p,holdMs:d??0});if(h.length===0){S(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:h.map(v=>({lane_id:v.laneId,host:v.host}))}))}catch(h){t(`[pooler] lane pick for ${a.pool} failed: ${h instanceof Error?h.message:String(h)}`),S(r,500,"the pooler lane plane failed this pick","pooler_error")}return}if(s.method!=="POST"||o.pathname!==Je){S(r,404,`no route for ${s.method??""} ${o.pathname}`,"not_found");return}if(s.headers.authorization!==`Bearer ${i.token}`){S(r,401,"the pooler channel requires the in-cluster bearer token","unauthorized");return}let u;try{u=JSON.parse(await we(s))}catch(l){S(r,400,l instanceof Error?l.message:String(l),"invalid_request");return}let c=tt(u);if("reason"in c){S(r,400,c.reason,"invalid_request");return}let m=new V(r,c.value.streaming,e);m.head();try{await i.pooler.submit(c.value.request,m)}catch(l){t(`[pooler] request ${c.value.request.request_id} failed unexpectedly: ${l instanceof Error?l.message:String(l)}`),m.fail({status:500,code:"pooler_error",message:"the pooler failed to serve this request"})}})()});return{server:n,close:()=>new Promise(s=>n.close(()=>s()))}}f();import{App as ut,createClientToken as dt}from"@urun-sh/core";f();import{STREAM_END as nt}from"@urun-sh/core";var st=new Set(["accepted","done","error"]);function rt(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 it(i){if(i===null||typeof i!="object")return null;let e=i,t=e.status;return t!==void 0&&(typeof t!="string"||!st.has(t))?null:{attempt:typeof e.attempt=="number"?e.attempt:0,...typeof t=="string"?{status:t}:{},...typeof e.error=="string"?{error:e.error}:{}}}function ot(i){let e=rt(i.get()),t=Number(e[ye]??0),n={},s=e[K];if(s!==null&&typeof s=="object")for(let[r,o]of Object.entries(s)){let u=it(o);u!==null&&(n[r]=u)}return{freeSlots:Number.isFinite(t)?t:0,inflight:n}}function at(i){if(i===nt)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*lt(i,e){let t=i.stream(ge(e)),n=!1;try{for await(let s of t.messages()){let r=at(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 _e(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`);let s=()=>e.doc(fe);return{sessionId:t,snapshot:()=>ot(s()),onDocChange:r=>s().on("change",()=>r()),onGone:r=>n.onGone(r),gone:()=>n.gone(),whenLive:r=>e.whenLive(r),markInflight:(r,o)=>(s().set({[K]:{[r]:{attempt:o}}}),Promise.resolve()),push:r=>(s().set({[j]:{[r.request_id]:{...r.payload,request_id:r.request_id,consumer_id:r.consumer_id,stream:r.stream}}}),Promise.resolve()),clearRequest:r=>{try{s().set({[j]:{[r]:null}})}catch{}return Promise.resolve()},reply:r=>lt(e,r),end:async()=>{await e.end(),n.dispose()}}}function be(i){return async(e,t)=>{let n=e.fn??Ee,s=ut(e.app,{baseUrl:i.baseUrl,orgId:i.orgId,getAccessToken:async()=>(await dt(i.apiKey,{baseUrl:i.baseUrl,expiresIn:300,allowedFunctions:[`${e.app}/${n}`],...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}:{}},u=r.call(s,void 0,o);if(u===null||typeof u!="object")throw new Error(`app "${e.app}" function "${n}" returned no session`);let c=u;return _e({session:c,sessionId:t,goneWatch:J(c,t,{armOnFirstSync:!0})})}}function vt(){let i=null;i=W({streams:b,note:e=>{i?.isDead("stderr")!==!0&&x(b.stderr,e)}})}async function St(){vt();let i=ve(b.env),e=l=>{x(b.stdout,`${l}
315
+ `)},t=new Et(i.valkeyUrl,{maxRetriesPerRequest:null}),n=new N({eval:(l,a,d)=>t.eval(l,a.length,...a,...d)},"pooler"),s=be(i),r=new M({journal:new O,registry:n,queueDeadlineMs:6e4,silenceDeadlineMs:33e4,backlogThreshold:8,mint:(l,a,d)=>{let p=i.targets.find(h=>h.region===l&&h.model===a);return p===void 0?Promise.reject(new Error(`no pooler target for ${l}:${a} \u2014 refusing to mint`)):s(p,d)},limits:i.targets.map(({region:l,model:a,min:d,max:p})=>({region:l,model:a,min:d,max:p})),scaleUpWaitMs:5e3,mintCooldownMs:1e4,sessionIdleTtlMs:6e4,idleSweepMs:5e3,onEvent:l=>{(l.kind==="registry_error"||l.kind==="failed"||l.kind==="mint_failed"||l.kind==="scaled_down")&&e(`[pooler] ${l.kind} ${JSON.stringify(l)}`)}});await r.warm();let o=i.laneDocHostUrl===void 0?void 0:me({docHostUrl:i.laneDocHostUrl,redis:t}),{server:u,close:c}=Re({pooler:r,token:i.token,lanePlane:o,log:e});await new Promise((l,a)=>{u.once("error",a),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(", ")})${o===void 0?"":" lanes=on"}`);let m=async l=>{e(`urun-pooler: ${l} \u2014 draining`),await c(),await r.close(),await o?.close(),await t.quit().catch(()=>{})};await new Promise(l=>{b.once("SIGINT",()=>{m("SIGINT").finally(l)}),b.once("SIGTERM",()=>{m("SIGTERM").finally(l)})})}St().then(()=>b.exit(0),i=>{x(b.stderr,`urun-pooler failed: ${i instanceof Error?`${i.name}: ${i.message}`:String(i)}
316
+ `),b.exit(1)});