async-bulkhead-llm 3.7.0 → 3.9.0

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 (56) hide show
  1. package/README.md +282 -8
  2. package/dist/cjs/adaptive.cjs +128 -0
  3. package/dist/cjs/adaptive.cjs.map +1 -0
  4. package/dist/cjs/bulkhead.cjs +1063 -0
  5. package/dist/cjs/bulkhead.cjs.map +1 -0
  6. package/dist/cjs/dedup.cjs +111 -0
  7. package/dist/cjs/dedup.cjs.map +1 -0
  8. package/dist/cjs/errors.cjs +16 -0
  9. package/dist/cjs/errors.cjs.map +1 -0
  10. package/dist/cjs/estimators.cjs +205 -0
  11. package/dist/cjs/estimators.cjs.map +1 -0
  12. package/dist/cjs/index.cjs +27 -1123
  13. package/dist/cjs/index.cjs.map +1 -1
  14. package/dist/cjs/profiles.cjs +16 -0
  15. package/dist/cjs/profiles.cjs.map +1 -0
  16. package/dist/cjs/types.cjs +3 -0
  17. package/dist/cjs/types.cjs.map +1 -0
  18. package/dist/cjs/validation.cjs +39 -0
  19. package/dist/cjs/validation.cjs.map +1 -0
  20. package/dist/esm/adaptive.js +125 -0
  21. package/dist/esm/adaptive.js.map +1 -0
  22. package/dist/esm/bulkhead.js +1060 -0
  23. package/dist/esm/bulkhead.js.map +1 -0
  24. package/dist/esm/dedup.js +106 -0
  25. package/dist/esm/dedup.js.map +1 -0
  26. package/dist/esm/errors.js +12 -0
  27. package/dist/esm/errors.js.map +1 -0
  28. package/dist/esm/estimators.js +200 -0
  29. package/dist/esm/estimators.js.map +1 -0
  30. package/dist/esm/index.js +19 -1117
  31. package/dist/esm/index.js.map +1 -1
  32. package/dist/esm/profiles.js +13 -0
  33. package/dist/esm/profiles.js.map +1 -0
  34. package/dist/esm/types.js +2 -0
  35. package/dist/esm/types.js.map +1 -0
  36. package/dist/esm/validation.js +32 -0
  37. package/dist/esm/validation.js.map +1 -0
  38. package/dist/types/adaptive.d.ts +109 -0
  39. package/dist/types/adaptive.d.ts.map +1 -0
  40. package/dist/types/bulkhead.d.ts +31 -0
  41. package/dist/types/bulkhead.d.ts.map +1 -0
  42. package/dist/types/dedup.d.ts +32 -0
  43. package/dist/types/dedup.d.ts.map +1 -0
  44. package/dist/types/errors.d.ts +9 -0
  45. package/dist/types/errors.d.ts.map +1 -0
  46. package/dist/types/estimators.d.ts +91 -0
  47. package/dist/types/estimators.d.ts.map +1 -0
  48. package/dist/types/index.d.ts +27 -660
  49. package/dist/types/index.d.ts.map +1 -1
  50. package/dist/types/profiles.d.ts +11 -0
  51. package/dist/types/profiles.d.ts.map +1 -0
  52. package/dist/types/types.d.ts +666 -0
  53. package/dist/types/types.d.ts.map +1 -0
  54. package/dist/types/validation.d.ts +12 -0
  55. package/dist/types/validation.d.ts.map +1 -0
  56. package/package.json +1 -1
package/dist/esm/index.js CHANGED
@@ -1,1122 +1,24 @@
1
- import { createBulkhead, } from "async-bulkhead-ts";
2
- import { createHash, randomUUID } from "node:crypto";
3
- export class LLMBulkheadRejectedError extends Error {
4
- reason;
5
- code = "LLM_BULKHEAD_REJECTED";
6
- detail;
7
- constructor(reason, detail) {
8
- super(`LLM bulkhead rejected: ${reason}`);
9
- this.reason = reason;
10
- this.name = "LLMBulkheadRejectedError";
11
- this.detail = detail;
12
- }
13
- }
14
1
  /**
15
- * Built-in presets for common deployment patterns.
16
- * Explicit options always override preset defaults.
17
- */
18
- export const PROFILES = {
19
- interactive: { maxQueue: 0 },
20
- batch: { maxQueue: 20, timeoutMs: 30_000 },
21
- };
22
- // ────────────────────────────────────────────
23
- // Estimator internals
24
- // ────────────────────────────────────────────
25
- const DEFAULT_OUTPUT_CAP = 2_048;
26
- const NAIVE_CHAR_RATIO = 4.0;
27
- function isNonNegativeInteger(value) {
28
- return Number.isFinite(value) && Number.isInteger(value) && value >= 0;
29
- }
30
- function assertNonNegativeInteger(value, name) {
31
- if (!isNonNegativeInteger(value)) {
32
- throw new Error(`${name} must be an integer >= 0`);
33
- }
34
- }
35
- function assertPositiveInteger(value, name) {
36
- if (!Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {
37
- throw new Error(`${name} must be a positive integer`);
38
- }
39
- }
40
- function assertOptionalNonNegativeInteger(value, name) {
41
- if (value !== undefined)
42
- assertNonNegativeInteger(value, name);
43
- }
44
- function validateTokenEstimate(estimate) {
45
- assertNonNegativeInteger(estimate.input, "token estimator input");
46
- assertNonNegativeInteger(estimate.maxOutput, "token estimator maxOutput");
47
- const needed = estimate.input + estimate.maxOutput;
48
- assertNonNegativeInteger(needed, "token reservation");
49
- return needed;
50
- }
51
- function validateTokenUsage(usage) {
52
- assertNonNegativeInteger(usage.input, "token usage input");
53
- assertNonNegativeInteger(usage.output, "token usage output");
54
- const actual = usage.input + usage.output;
55
- assertNonNegativeInteger(actual, "token usage total");
56
- return usage;
57
- }
58
- /**
59
- * Extract total character count from message content.
60
- * Handles both plain strings and multimodal content block arrays.
61
- * Non-text blocks are ignored (contribute 0 characters).
62
- */
63
- export function extractTextLength(content) {
64
- if (typeof content === "string")
65
- return content.length;
66
- let len = 0;
67
- for (const block of content) {
68
- if (isTextBlock(block))
69
- len += block.text.length;
70
- }
71
- return len;
72
- }
73
- /** A block counts as text iff `type === "text"` with a string `text`. */
74
- function isTextBlock(block) {
75
- return (block.type === "text" &&
76
- "text" in block &&
77
- typeof block.text === "string");
78
- }
79
- /**
80
- * Total characters across `messages[].content` and `system`.
81
- * The single character-count surface shared by both built-in estimators.
82
- */
83
- function requestInputChars(request) {
84
- let chars = request.messages.reduce((sum, m) => sum + extractTextLength(m.content), 0);
85
- if (request.system !== undefined) {
86
- chars += extractTextLength(request.system);
87
- }
88
- return chars;
89
- }
90
- /** Validated `request.extraInputTokens`, defaulting to 0. */
91
- function resolveExtraInputTokens(request) {
92
- assertOptionalNonNegativeInteger(request.extraInputTokens, "request.extraInputTokens");
93
- return request.extraInputTokens ?? 0;
94
- }
95
- function resolveMaxOutput(request, fallback) {
96
- assertNonNegativeInteger(fallback, "outputCap");
97
- assertOptionalNonNegativeInteger(request.max_tokens, "request.max_tokens");
98
- return request.max_tokens ?? fallback;
99
- }
100
- /**
101
- * Estimates token usage using a flat 4-characters-per-token ratio.
102
- *
103
- * Handles both plain string and multimodal content.
104
- * Non-text content blocks are ignored (treated as zero tokens).
105
- *
106
- * Accuracy: ±25% for English prose.
107
- * Suitable for load-shedding; not suitable for cost accounting.
108
- *
109
- * v3.7: counts `request.system` alongside message content and adds
110
- * `request.extraInputTokens` verbatim. Non-text blocks still contribute
111
- * zero characters (use the model-aware estimator's `opaqueBlockTokens`
112
- * for per-block surcharges).
113
- */
114
- export function naiveTokenEstimator(request) {
115
- const inputChars = requestInputChars(request);
116
- return {
117
- input: Math.ceil(inputChars / NAIVE_CHAR_RATIO) +
118
- resolveExtraInputTokens(request),
119
- maxOutput: resolveMaxOutput(request, DEFAULT_OUTPUT_CAP),
120
- };
121
- }
122
- /**
123
- * Per-model character-to-token ratios.
124
- * Flat array of [prefix, ratio] pairs — longest matching prefix wins.
125
- */
126
- const BUILT_IN_RATIOS = [
127
- // Anthropic — Claude 3.x
128
- ["claude-3-5-haiku", 3.8],
129
- ["claude-3-5-sonnet", 3.9],
130
- ["claude-3-opus", 3.9],
131
- ["claude-3-sonnet", 3.9],
132
- ["claude-3-haiku", 3.8],
133
- // Anthropic — Claude 4.x
134
- ["claude-sonnet-4", 3.9],
135
- ["claude-opus-4", 3.9],
136
- ["claude-haiku-4", 3.8],
137
- // Anthropic — Claude 4.5
138
- ["claude-sonnet-4-5", 3.9],
139
- ["claude-opus-4-5", 3.9],
140
- ["claude-haiku-4-5", 3.8],
141
- // OpenAI — GPT
142
- ["gpt-4o", 3.7],
143
- ["gpt-4-turbo", 3.7],
144
- ["gpt-4.1", 3.7],
145
- ["gpt-4", 3.7],
146
- ["gpt-3.5", 3.8],
147
- // OpenAI — reasoning
148
- ["o1", 3.7],
149
- ["o3", 3.7],
150
- ["o4-mini", 3.7],
151
- // Google — Gemini
152
- ["gemini-2.5", 3.8],
153
- ["gemini-2", 3.8],
154
- ["gemini-1.5", 3.8],
155
- ];
156
- function validateOpaqueBlockTokens(opt) {
157
- if (opt === undefined)
158
- return;
159
- if (typeof opt === "number") {
160
- assertNonNegativeInteger(opt, "opaqueBlockTokens");
161
- return;
162
- }
163
- assertOptionalNonNegativeInteger(opt.default, "opaqueBlockTokens.default");
164
- if (opt.byType) {
165
- for (const [type, tokens] of Object.entries(opt.byType)) {
166
- assertNonNegativeInteger(tokens, `opaqueBlockTokens.byType[${JSON.stringify(type)}]`);
167
- }
168
- }
169
- }
170
- function opaqueBlockCost(opt, type) {
171
- if (typeof opt === "number")
172
- return opt;
173
- return opt.byType?.[type] ?? opt.default ?? 0;
174
- }
175
- /** Sum of surcharges for every opaque block in messages + system. */
176
- function countOpaqueBlockTokens(request, opt) {
177
- if (opt === undefined)
178
- return 0;
179
- let total = 0;
180
- const scan = (content) => {
181
- if (typeof content === "string")
182
- return;
183
- for (const block of content) {
184
- if (isTextBlock(block))
185
- continue;
186
- total += opaqueBlockCost(opt, block.type);
187
- }
188
- };
189
- for (const m of request.messages)
190
- scan(m.content);
191
- if (request.system !== undefined)
192
- scan(request.system);
193
- return total;
194
- }
195
- function isModelAwareEstimatorOptions(value) {
196
- if (value == null || typeof value !== "object" || Array.isArray(value)) {
197
- return false;
198
- }
199
- return ("defaultModel" in value ||
200
- "outputCap" in value ||
201
- "onUnknownModel" in value ||
202
- "opaqueBlockTokens" in value);
203
- }
204
- export function createModelAwareTokenEstimator(overridesOrOpts, maybeOpts) {
205
- const hasSingleOptionsArg = maybeOpts === undefined &&
206
- isModelAwareEstimatorOptions(overridesOrOpts);
207
- const overrides = hasSingleOptionsArg
208
- ? undefined
209
- : overridesOrOpts;
210
- const opts = hasSingleOptionsArg
211
- ? overridesOrOpts
212
- : (maybeOpts ?? {});
213
- const outputCap = opts.outputCap ?? DEFAULT_OUTPUT_CAP;
214
- assertNonNegativeInteger(outputCap, "outputCap");
215
- const opaqueBlockTokens = opts.opaqueBlockTokens;
216
- validateOpaqueBlockTokens(opaqueBlockTokens);
217
- function lookupRatio(model) {
218
- // Exact overrides checked first (case-sensitive, then lowercased).
219
- if (overrides) {
220
- const exact = overrides[model] ?? overrides[model.toLowerCase()];
221
- if (exact != null)
222
- return exact;
223
- }
224
- // Prefix scan: lowercase, longest match wins.
225
- const normalized = model.toLowerCase();
226
- let bestLen = 0;
227
- let bestRatio = -1;
228
- for (const [prefix, ratio] of BUILT_IN_RATIOS) {
229
- if (normalized.startsWith(prefix) && prefix.length > bestLen) {
230
- bestLen = prefix.length;
231
- bestRatio = ratio;
232
- }
233
- }
234
- if (bestRatio > 0)
235
- return bestRatio;
236
- opts.onUnknownModel?.(model);
237
- return NAIVE_CHAR_RATIO;
238
- }
239
- return (request) => {
240
- const model = request.model ?? opts.defaultModel ?? "";
241
- const ratio = lookupRatio(model);
242
- const inputChars = requestInputChars(request);
243
- return {
244
- input: Math.ceil(inputChars / ratio) +
245
- countOpaqueBlockTokens(request, opaqueBlockTokens) +
246
- resolveExtraInputTokens(request),
247
- maxOutput: resolveMaxOutput(request, outputCap),
248
- };
249
- };
250
- }
251
- // ────────────────────────────────────────────
252
- // Option resolution
253
- // ────────────────────────────────────────────
254
- function resolvePreset(profile) {
255
- if (!profile)
256
- return {};
257
- if (typeof profile === "string")
258
- return PROFILES[profile];
259
- return profile;
260
- }
261
- function resolveDedup(opt) {
262
- if (!opt) {
263
- return { enabled: false, keyFn: defaultDedupKey, shareResult: undefined };
264
- }
265
- if (opt === true) {
266
- return { enabled: true, keyFn: defaultDedupKey, shareResult: undefined };
267
- }
268
- return {
269
- enabled: true,
270
- keyFn: opt.keyFn ?? defaultDedupKey,
271
- shareResult: opt.shareResult,
272
- };
273
- }
274
- /**
275
- * Shallow detection of single-consumer values that must not be handed
276
- * to more than one deduplication caller by reference:
2
+ * async-bulkhead-llm — public API surface.
277
3
  *
278
- * - Web `ReadableStream` (also matched structurally via `getReader`)
279
- * - Node streams (`pipe`)
280
- * - Async iterables (async generators, SDK stream wrappers) — plain
281
- * arrays/strings/objects are sync-iterable at most, so they never match
282
- * - `Response` with a non-null body (`fetch` responses; the body is a
283
- * `ReadableStream` and `.json()`/`.text()` can be called once)
4
+ * This entry point re-exports everything the package supports; the
5
+ * implementation lives in focused modules:
284
6
  *
285
- * Deliberately shallow: only the value itself is inspected, never
286
- * nested properties. False negatives (a stream inside a wrapper
287
- * object) fall back to today's share-by-reference behavior; false
288
- * positives are limited to caller types that genuinely advertise
289
- * stream/iterator protocols.
290
- */
291
- function isUnsafeToShare(value) {
292
- if (value === null || typeof value !== "object")
293
- return false;
294
- const v = value;
295
- if (typeof globalThis.ReadableStream === "function" &&
296
- value instanceof globalThis.ReadableStream) {
297
- return true;
298
- }
299
- if (typeof v["getReader"] === "function")
300
- return true;
301
- if (typeof v["pipe"] === "function")
302
- return true;
303
- if (Symbol.asyncIterator in v)
304
- return true;
305
- if (typeof globalThis.Response === "function" &&
306
- value instanceof globalThis.Response) {
307
- return value.body !== null;
308
- }
309
- return false;
310
- }
311
- /**
312
- * JSON.stringify with recursively sorted object keys, so structurally
313
- * identical requests serialize identically regardless of property
314
- * insertion order.
315
- */
316
- function stableStringify(value) {
317
- return JSON.stringify(value, (_key, v) => {
318
- if (v !== null && typeof v === "object" && !Array.isArray(v)) {
319
- const obj = v;
320
- const sorted = {};
321
- for (const k of Object.keys(obj).sort())
322
- sorted[k] = obj[k];
323
- return sorted;
324
- }
325
- return v;
326
- });
327
- }
328
- /**
329
- * Default deduplication key.
7
+ * - `types.ts` — request/result/options/stats/event types
8
+ * - `errors.ts` — `LLMBulkheadRejectedError`
9
+ * - `profiles.ts` — `PROFILES` presets
10
+ * - `estimators.ts` — naive + model-aware estimators, `extractTextLength`
11
+ * - `adaptive.ts` — `createAdaptiveTokenEstimator` (v3.8)
12
+ * - `dedup.ts` — deduplication internals (keying, share safety)
13
+ * - `validation.ts` — internal numeric/estimate/usage guards
14
+ * - `bulkhead.ts` — `createLLMBulkhead` (admission, budget, events)
330
15
  *
331
- * v3.4: serializes the **entire request** (stable key order) instead of
332
- * only `{messages, max_tokens, model}`. The old key silently conflated
333
- * requests that differed in any other field — e.g. identical messages
334
- * with `temperature: 0` vs `temperature: 1` shared one call and one
335
- * response. Missing a dedup opportunity is cheap; serving a response
336
- * generated under different parameters is a correctness bug, so the
337
- * default now errs entirely toward non-conflation.
338
- */
339
- function defaultDedupKey(request) {
340
- try {
341
- return stableStringify(request);
342
- }
343
- catch {
344
- return "";
345
- }
346
- }
347
- /**
348
- * Derive the map key actually stored for an in-flight entry:
349
- * `sha256(scope \0 rawKey)`. Hashing bounds per-entry key memory and
350
- * keeps prompt text out of the dedup map; the `\0` separator prevents
351
- * scope/key boundary ambiguity ("ab"+"c" vs "a"+"bc").
352
- */
353
- function hashDedupKey(scope, rawKey) {
354
- const h = createHash("sha256");
355
- h.update(scope);
356
- h.update("\u0000");
357
- h.update(rawKey);
358
- return h.digest("hex");
359
- }
360
- // ────────────────────────────────────────────
361
- // createLLMBulkhead
362
- // ────────────────────────────────────────────
363
- export function createLLMBulkhead(opts) {
364
- // ---- Validate ----
365
- if (typeof opts.model !== "string" || opts.model.trim() === "") {
366
- throw new Error("model must be a non-empty string");
367
- }
368
- assertPositiveInteger(opts.maxConcurrent, "maxConcurrent");
369
- // ---- Resolve profile defaults ----
370
- const preset = resolvePreset(opts.profile);
371
- const maxQueue = opts.maxQueue ?? preset.maxQueue ?? 0;
372
- const timeoutMs = opts.timeoutMs ?? preset.timeoutMs;
373
- assertNonNegativeInteger(maxQueue, "maxQueue");
374
- assertOptionalNonNegativeInteger(timeoutMs, "timeoutMs");
375
- if (opts.tokenBudget) {
376
- assertNonNegativeInteger(opts.tokenBudget.budget, "tokenBudget.budget");
377
- assertOptionalNonNegativeInteger(opts.tokenBudget.outputCap, "tokenBudget.outputCap");
378
- assertOptionalNonNegativeInteger(opts.tokenBudget.highPriorityReserve, "tokenBudget.highPriorityReserve");
379
- if (opts.tokenBudget.highPriorityReserve !== undefined &&
380
- opts.tokenBudget.highPriorityReserve > opts.tokenBudget.budget) {
381
- throw new Error("tokenBudget.highPriorityReserve must be <= tokenBudget.budget");
382
- }
383
- }
384
- // ---- Internal bulkhead from async-bulkhead-ts ----
385
- const bulkhead = createBulkhead({
386
- maxConcurrent: opts.maxConcurrent,
387
- maxQueue,
388
- });
389
- // ---- Token budget state ----
390
- const budget = opts.tokenBudget;
391
- const estimator = budget?.estimator ??
392
- createModelAwareTokenEstimator(undefined, {
393
- defaultModel: opts.model,
394
- outputCap: budget?.outputCap,
395
- });
396
- const highPriorityReserve = budget?.highPriorityReserve ?? 0;
397
- /**
398
- * Mutable budget ceiling, initialized from `tokenBudget.budget`.
399
- * `undefined` when `tokenBudget` was never configured — `setBudget()`
400
- * throws in that case rather than silently no-op'ing.
401
- * Mutated only by `setBudget()`. All admission math reads this value
402
- * (via `effectiveBudget()`), not the frozen `opts.tokenBudget.budget`,
403
- * so budget changes take effect on the very next admission check.
404
- */
405
- let currentBudget = budget?.budget;
406
- let inFlightTokens = 0;
407
- let totalReserved = 0;
408
- let totalConsumed = 0;
409
- let totalRefunded = 0;
410
- let totalOverrun = 0;
411
- let llmAdmitted = 0;
412
- let llmReleased = 0;
413
- let llmRejected = 0;
414
- const llmRejectedByReason = {};
415
- // ---- Deduplication state ----
416
- const dedup = resolveDedup(opts.deduplication);
417
- const dedupMap = new Map();
418
- let dedupHits = 0;
419
- // ---- Event emitter state ----
420
- const listeners = {
421
- admit: new Set(),
422
- reject: new Set(),
423
- release: new Set(),
424
- usage: new Set(),
425
- dedup: new Set(),
426
- };
427
- function emit(event, payload) {
428
- for (const fn of listeners[event]) {
429
- try {
430
- fn(payload);
431
- }
432
- catch {
433
- // listeners must not throw into the bulkhead
434
- }
435
- }
436
- }
437
- function noteLLMAdmit() {
438
- llmAdmitted++;
439
- }
440
- function noteLLMRelease() {
441
- llmReleased++;
442
- }
443
- function noteLLMReject(reason) {
444
- llmRejected++;
445
- llmRejectedByReason[reason] =
446
- (llmRejectedByReason[reason] ?? 0) + 1;
447
- }
448
- // ---- Internal helpers ----
449
- function createDeferred() {
450
- let resolve;
451
- let reject;
452
- const promise = new Promise((res, rej) => {
453
- resolve = res;
454
- reject = rej;
455
- });
456
- return { promise, resolve, reject };
457
- }
458
- function estimateParts(request) {
459
- return resolveReservation(request, undefined);
460
- }
461
- /**
462
- * Reservation used for admission: the caller's per-call `reservation`
463
- * override verbatim when provided, otherwise the estimator's output.
464
- * Both paths validate as non-negative integers. `null` when
465
- * `tokenBudget` is disabled (no reservation participates then, and
466
- * the override is deliberately ignored).
467
- */
468
- function resolveReservation(request, override) {
469
- assertOptionalNonNegativeInteger(request.max_tokens, "request.max_tokens");
470
- if (!budget)
471
- return null;
472
- if (override !== undefined) {
473
- const reserved = validateTokenEstimate(override);
474
- return {
475
- input: override.input,
476
- maxOutput: override.maxOutput,
477
- reserved,
478
- };
479
- }
480
- const estimate = estimator(request);
481
- const reserved = validateTokenEstimate(estimate);
482
- return {
483
- input: estimate.input,
484
- maxOutput: estimate.maxOutput,
485
- reserved,
486
- };
487
- }
488
- /**
489
- * Preview the exact token reservation that admission will calculate.
490
- *
491
- * This calls the same estimator and validation path as `acquire()`,
492
- * `run()`, and `wouldAdmit()`. It does not reserve capacity. Returns
493
- * `null` when `tokenBudget` is disabled because admission does not hold
494
- * tokens in that mode.
495
- *
496
- * Custom estimators should be deterministic: if either the request or
497
- * estimator output changes between `estimate()` and admission, the later
498
- * admission will correctly use the newly calculated value.
499
- *
500
- * A per-call `reservation` override passed to `acquire()` / `run()` /
501
- * `wouldAdmit()` bypasses the estimator and is NOT reflected here —
502
- * `estimate()` always previews the estimator path.
503
- */
504
- function estimate(request) {
505
- const parts = estimateParts(request);
506
- return parts === null ? null : { ...parts };
507
- }
508
- function resolvePriority(priority) {
509
- if (priority === undefined)
510
- return "normal";
511
- if (priority !== "high" && priority !== "normal") {
512
- throw new Error(`priority must be "high" or "normal"`);
513
- }
514
- return priority;
515
- }
516
- /**
517
- * Budget ceiling applicable to a request at the given priority.
518
- *
519
- * Construction validates `0 <= highPriorityReserve <= budget` (see the
520
- * `tokenBudget` validation block above) — that check catches config
521
- * typos once, at startup. It intentionally does *not* run again here.
522
- *
523
- * `setBudget()` can lower `currentBudget` below `highPriorityReserve` at
524
- * runtime (e.g. a lease-renewal ledger reporting a shrunk grant), and
525
- * that is allowed, not re-validated. Rejecting a renewal-driven update
526
- * would be wrong: the ledger's grant is reality — the bulkhead has no
527
- * standing to refuse it. So `currentBudget` can legitimately end up
528
- * smaller than `highPriorityReserve`.
529
- *
530
- * Consequence, deliberately embraced: `currentBudget! - highPriorityReserve`
531
- * would go negative in that state, so it is clamped to `0` here. That
532
- * means normal-priority admission is fully rejected (nothing fits under
533
- * a `0` ceiling) while high-priority admission is still checked against
534
- * the full (shrunk) `currentBudget` and can keep admitting whatever
535
- * capacity remains. That is exactly the right degraded behavior — the
536
- * entire purpose of `highPriorityReserve` is protecting interactive
537
- * traffic when capacity is scarce, and capacity has never been scarcer
538
- * than when the grant itself drops below the reserve.
539
- */
540
- function effectiveBudget(priority) {
541
- if (!budget)
542
- return Infinity;
543
- return priority === "high"
544
- ? currentBudget
545
- : Math.max(0, currentBudget - highPriorityReserve);
546
- }
547
- /**
548
- * Attempt token budget admission synchronously for a precomputed
549
- * reservation. Returns false if the priority-adjusted ceiling is
550
- * exceeded.
551
- */
552
- function tryReserveTokens(reserved, priority) {
553
- if (!budget)
554
- return true;
555
- if (inFlightTokens + reserved > effectiveBudget(priority))
556
- return false;
557
- inFlightTokens += reserved;
558
- totalReserved += reserved;
559
- return true;
560
- }
561
- function releaseTokens(held, usage) {
562
- let refunded = 0;
563
- if (usage && held > 0) {
564
- const actual = usage.input + usage.output;
565
- totalConsumed += actual;
566
- if (actual < held) {
567
- refunded = held - actual;
568
- totalRefunded += refunded;
569
- }
570
- }
571
- inFlightTokens = Math.max(0, inFlightTokens - held);
572
- return refunded;
573
- }
574
- /** Capacity snapshot for rejection results, events, and errors. */
575
- function buildRejectDetail(requested, priority) {
576
- const base = bulkhead.stats();
577
- const detail = {
578
- inFlight: base.inFlight,
579
- pending: base.pending,
580
- maxConcurrent: base.maxConcurrent,
581
- maxQueue: base.maxQueue,
582
- };
583
- if (budget) {
584
- const eff = effectiveBudget(priority);
585
- detail.tokenBudget = {
586
- budget: currentBudget,
587
- inFlightTokens,
588
- effectiveBudget: eff,
589
- available: Math.max(0, eff - inFlightTokens),
590
- requested,
591
- };
592
- }
593
- return detail;
594
- }
595
- /**
596
- * Update the token budget ceiling at runtime.
597
- *
598
- * Semantics (deliberate, not incidental):
599
- *
600
- * - **Raising takes effect immediately.** The very next admission check
601
- * reads the new ceiling via `effectiveBudget()` — no caching to
602
- * invalidate, no in-flight work touched.
603
- * - **Lowering below `inFlightTokens` is legal — shrink by attrition.**
604
- * No in-flight work is revoked or cancelled. New admissions reject
605
- * with `"budget_limit"` until enough in-flight work releases to bring
606
- * `inFlightTokens` back under the new ceiling. This mirrors the
607
- * library's existing overrun tolerance (`inFlightTokens` can already
608
- * exceed `budget` via `reportUsage()` overrun) — over-budget in-flight
609
- * state is an established, intentional condition, not an invariant
610
- * violation.
611
- * - **Throws if `tokenBudget` was never configured.** An explicit error
612
- * beats a silent no-op — there is no budget ceiling to adjust.
613
- * - **Validation:** `tokens` must be a non-negative integer.
614
- */
615
- function setBudget(tokens) {
616
- if (!budget) {
617
- throw new Error("setBudget requires tokenBudget to be configured at construction");
618
- }
619
- assertNonNegativeInteger(tokens, "tokens");
620
- currentBudget = tokens;
621
- }
622
- function normalizeAcquireOptions(ao) {
623
- const normalized = {};
624
- if (ao.signal !== undefined)
625
- normalized.signal = ao.signal;
626
- const effectiveTimeoutMs = ao.timeoutMs ?? timeoutMs;
627
- if (effectiveTimeoutMs !== undefined) {
628
- assertNonNegativeInteger(effectiveTimeoutMs, "timeoutMs");
629
- normalized.timeoutMs = effectiveTimeoutMs;
630
- }
631
- return normalized;
632
- }
633
- function noteDedupWaitRejection(request, reason) {
634
- noteLLMReject(reason);
635
- emit("reject", { request, reason });
636
- return new LLMBulkheadRejectedError(reason);
637
- }
638
- /**
639
- * Deliver a shared in-flight result to a deduplication follower.
640
- *
641
- * - With a `shareResult` hook: the hook decides what the follower
642
- * receives (called for every follower, safe results included).
643
- * Hook exceptions propagate to the follower as-is.
644
- * - Without a hook: single-consumer values (streams, `Response`
645
- * bodies, async iterables) are refused with
646
- * `"unshareable_result"` instead of being handed out by
647
- * reference — a locked stream downstream is a silent correctness
648
- * bug; a typed rejection at the bulkhead is actionable.
649
- *
650
- * The leader never passes through this function.
651
- */
652
- function deliverShared(value, request) {
653
- if (dedup.shareResult) {
654
- return dedup.shareResult(value);
655
- }
656
- if (isUnsafeToShare(value)) {
657
- throw noteDedupWaitRejection(request, "unshareable_result");
658
- }
659
- return value;
660
- }
661
- /**
662
- * Wait on another caller's in-flight shared call.
663
- *
664
- * v3.4: only an *explicitly passed* per-call `timeoutMs` caps this
665
- * wait. The bulkhead-level `timeoutMs` default is deliberately NOT
666
- * applied here — it is documented as a *queue-wait* timeout, and a
667
- * follower is not queued; it is waiting on a call that is already
668
- * running. Applying the default (e.g. the `batch` profile's 30s) made
669
- * every follower of a slow LLM call fail with `"timeout"` while the
670
- * leader succeeded, defeating deduplication exactly when calls are
671
- * long. `signal` continues to apply as before.
672
- */
673
- function waitForSharedDedup(shared, request, ao) {
674
- const signal = ao.signal;
675
- const effectiveTimeoutMs = ao.timeoutMs;
676
- if (effectiveTimeoutMs !== undefined) {
677
- assertNonNegativeInteger(effectiveTimeoutMs, "timeoutMs");
678
- }
679
- if (signal?.aborted) {
680
- return Promise.reject(noteDedupWaitRejection(request, "aborted"));
681
- }
682
- if (signal === undefined && effectiveTimeoutMs === undefined) {
683
- return shared.then((value) => deliverShared(value, request));
684
- }
685
- return new Promise((resolve, reject) => {
686
- let timeoutId;
687
- let settled = false;
688
- const cleanup = () => {
689
- if (timeoutId !== undefined)
690
- clearTimeout(timeoutId);
691
- if (signal !== undefined) {
692
- signal.removeEventListener("abort", onAbort);
693
- }
694
- };
695
- const settle = (fn) => {
696
- if (settled)
697
- return;
698
- settled = true;
699
- cleanup();
700
- fn();
701
- };
702
- const onAbort = () => {
703
- settle(() => {
704
- reject(noteDedupWaitRejection(request, "aborted"));
705
- });
706
- };
707
- if (signal !== undefined) {
708
- signal.addEventListener("abort", onAbort, { once: true });
709
- }
710
- if (effectiveTimeoutMs !== undefined) {
711
- timeoutId = setTimeout(() => {
712
- settle(() => {
713
- reject(noteDedupWaitRejection(request, "timeout"));
714
- });
715
- }, effectiveTimeoutMs);
716
- }
717
- void shared.then((value) => settle(() => {
718
- try {
719
- resolve(deliverShared(value, request));
720
- }
721
- catch (err) {
722
- reject(err);
723
- }
724
- }), (err) => settle(() => reject(err)));
725
- });
726
- }
727
- /**
728
- * Wraps a base Token so that release() also returns the token
729
- * reservation and optionally applies the refund, and so that
730
- * streaming callers can report cumulative usage mid-flight.
731
- */
732
- function wrapToken(base, parts, request, admissionId, priority) {
733
- let released = false;
734
- /** Tokens currently held against the budget for this request. */
735
- let held = parts?.reserved ?? 0;
736
- /** Last reported cumulative usage (monotonically clamped). */
737
- let reported;
738
- /** Monotonic sequence of effective pre-release usage updates. */
739
- let usageSequence = 0;
740
- /** Public copy: callers cannot mutate internal accounting parts. */
741
- const reservation = parts === null ? null : Object.freeze({ ...parts });
742
- const snapshot = () => {
743
- const consumed = reported
744
- ? reported.input + reported.output
745
- : 0;
746
- const outputCap = parts ? parts.maxOutput : null;
747
- return {
748
- admissionId,
749
- sequence: usageSequence,
750
- reserved: parts?.reserved ?? 0,
751
- held,
752
- consumed,
753
- outputCap,
754
- outputRemaining: outputCap === null
755
- ? null
756
- : Math.max(0, outputCap - (reported?.output ?? 0)),
757
- overReservation: parts ? consumed > parts.reserved : false,
758
- };
759
- };
760
- const reportUsage = (usage) => {
761
- const valid = validateTokenUsage(usage);
762
- const previousReported = reported;
763
- // Clamp to monotonic non-decreasing per field — cumulative
764
- // stream usage never shrinks; a lower report is stale.
765
- reported = previousReported
766
- ? {
767
- input: Math.max(previousReported.input, valid.input),
768
- output: Math.max(previousReported.output, valid.output),
769
- }
770
- : valid;
771
- const usageChanged = previousReported === undefined ||
772
- reported.input !== previousReported.input ||
773
- reported.output !== previousReported.output;
774
- const previousHeldTokens = held;
775
- // Accounting only applies pre-release with a budget configured.
776
- if (!released && parts && budget) {
777
- // Hold = known input + the larger of (output ceiling, actual output).
778
- // Keeps the full output reservation while refunding input
779
- // over-estimates immediately; expands on output overrun.
780
- const newHold = reported.input + Math.max(parts.maxOutput, reported.output);
781
- const delta = newHold - held;
782
- if (delta > 0) {
783
- inFlightTokens += delta;
784
- totalOverrun += delta;
785
- }
786
- else if (delta < 0) {
787
- const refund = -delta;
788
- inFlightTokens = Math.max(0, inFlightTokens - refund);
789
- totalRefunded += refund;
790
- }
791
- held = newHold;
792
- }
793
- if (!released && usageChanged) {
794
- usageSequence++;
795
- }
796
- const report = snapshot();
797
- if (!released && usageChanged) {
798
- emit("usage", {
799
- request,
800
- admissionId,
801
- priority,
802
- sequence: usageSequence,
803
- reservedTokens: parts?.reserved ?? 0,
804
- previousHeldTokens,
805
- heldTokens: held,
806
- deltaTokens: held - previousHeldTokens,
807
- usage: { ...reported },
808
- outputCap: report.outputCap,
809
- outputRemaining: report.outputRemaining,
810
- overReservation: report.overReservation,
811
- });
812
- }
813
- return report;
814
- };
815
- return {
816
- admissionId,
817
- reservation,
818
- reportUsage,
819
- release(usage) {
820
- if (released)
821
- return;
822
- released = true;
823
- let validUsage;
824
- let usageError;
825
- if (usage !== undefined) {
826
- try {
827
- validUsage = validateTokenUsage(usage);
828
- }
829
- catch (err) {
830
- usageError = err;
831
- }
832
- }
833
- // Fall back to the last mid-flight report when no (valid)
834
- // explicit usage is provided at release.
835
- if (validUsage === undefined && reported !== undefined) {
836
- validUsage = reported;
837
- }
838
- try {
839
- base.release();
840
- }
841
- finally {
842
- // Zero `held` before returning tokens: nothing is held against
843
- // the budget after release, and post-release `reportUsage()`
844
- // snapshots must reflect that (previously they reported the
845
- // stale pre-release hold).
846
- const heldAtRelease = held;
847
- held = 0;
848
- const refunded = releaseTokens(heldAtRelease, validUsage);
849
- noteLLMRelease();
850
- emit("release", {
851
- request,
852
- admissionId,
853
- priority,
854
- reservedTokens: parts?.reserved ?? 0,
855
- heldTokens: heldAtRelease,
856
- refundedTokens: refunded,
857
- usageSequence,
858
- ...(validUsage !== undefined && { usage: validUsage }),
859
- });
860
- }
861
- if (usageError !== undefined)
862
- throw usageError;
863
- },
864
- };
865
- }
866
- // ---- Internal acquire ----
867
- async function _acquire(request, ao) {
868
- const priority = resolvePriority(ao.priority);
869
- const parts = resolveReservation(request, ao.reservation);
870
- const reserved = parts?.reserved ?? 0;
871
- const rejectWith = (reason) => {
872
- const detail = buildRejectDetail(reserved, priority);
873
- noteLLMReject(reason);
874
- emit("reject", { request, reason, detail });
875
- return { ok: false, reason, detail };
876
- };
877
- // Token budget: pre-check before entering the queue.
878
- if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
879
- return rejectWith("budget_limit");
880
- }
881
- const mergedOptions = normalizeAcquireOptions(ao);
882
- const r = await bulkhead.acquire(mergedOptions);
883
- if (!r.ok) {
884
- return rejectWith(r.reason);
885
- }
886
- // Post-admission: reserve the precomputed amount now.
887
- if (!tryReserveTokens(reserved, priority)) {
888
- r.token.release();
889
- return rejectWith("budget_limit");
890
- }
891
- const admissionId = randomUUID();
892
- const token = wrapToken(r.token, parts, request, admissionId, priority);
893
- noteLLMAdmit();
894
- emit("admit", { request, admissionId, priority, reservedTokens: reserved });
895
- return {
896
- ok: true,
897
- admissionId,
898
- reservation: token.reservation,
899
- token,
900
- };
901
- }
902
- // ---- Public API ----
903
- /**
904
- * Acquire a slot manually.
905
- *
906
- * The returned token accepts optional `TokenUsage` at release time
907
- * to trigger the refund mechanism. For most use cases, prefer `run()`.
908
- */
909
- async function acquire(request, ao = {}) {
910
- return _acquire(request, ao);
911
- }
912
- /**
913
- * Advisory dry-run: would a request of this shape be admitted right
914
- * now at the given priority?
915
- *
916
- * This is a snapshot for routing decisions (e.g. pick a different
917
- * model pool). It does NOT reserve anything — the answer can change
918
- * before a subsequent `acquire()`/`run()` lands. Never treat `true`
919
- * as a guarantee.
920
- *
921
- * Accepts the same per-call `reservation` override as `acquire()` /
922
- * `run()` (v3.7); pass the identical value to both for a consistent
923
- * preview.
924
- */
925
- function wouldAdmit(request, opts = {}) {
926
- const priority = resolvePriority(opts.priority);
927
- const base = bulkhead.stats();
928
- if (base.closed)
929
- return { admit: false, reason: "shutdown" };
930
- const parts = resolveReservation(request, opts.reservation);
931
- const reserved = parts?.reserved ?? 0;
932
- if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
933
- return { admit: false, reason: "budget_limit" };
934
- }
935
- if (base.inFlight < base.maxConcurrent)
936
- return { admit: true };
937
- if (base.pending < base.maxQueue)
938
- return { admit: true };
939
- return {
940
- admit: false,
941
- reason: base.maxQueue > 0 ? "queue_limit" : "concurrency_limit",
942
- };
943
- }
944
- /**
945
- * Primary API. Acquire → call `fn` → release, automatically.
946
- *
947
- * Throws `LLMBulkheadRejectedError` on rejection.
948
- *
949
- * When `getUsage` is provided in options, it is called with the result
950
- * of `fn` to extract actual token usage. The refund mechanism then
951
- * returns the difference between the reservation and actual consumption
952
- * to the budget.
953
- *
954
- * Deduplication (when enabled) applies to `run()` only; `acquire()`
955
- * never deduplicates. A caller that joins an existing in-flight call
956
- * is capped only by its own `signal` and an *explicitly passed*
957
- * per-call `timeoutMs` — the bulkhead-level `timeoutMs` (a queue-wait
958
- * timeout) does not apply to that wait.
959
- */
960
- async function run(request, fn, ao = {}) {
961
- const { getUsage, dedupScope, dedup: perCallDedup, ...acquireOpts } = ao;
962
- // ---- Deduplication ----
963
- let dedupKey = "";
964
- if (dedup.enabled && perCallDedup !== false) {
965
- let rawKey;
966
- try {
967
- rawKey = dedup.keyFn(request);
968
- }
969
- catch {
970
- rawKey = "";
971
- }
972
- // "" opts out; only real keys are scoped + hashed.
973
- if (rawKey !== "") {
974
- dedupKey = hashDedupKey(dedupScope ?? "", rawKey);
975
- }
976
- }
977
- let deferred;
978
- let resultPromise;
979
- if (dedup.enabled && dedupKey !== "") {
980
- const existing = dedupMap.get(dedupKey);
981
- if (existing) {
982
- dedupHits++;
983
- emit("dedup", { request });
984
- return waitForSharedDedup(existing, request, acquireOpts);
985
- }
986
- deferred = createDeferred();
987
- resultPromise = deferred.promise;
988
- dedupMap.set(dedupKey, deferred.promise);
989
- const cleanup = () => {
990
- try {
991
- const p = dedupMap.get(dedupKey);
992
- if (p === deferred.promise)
993
- dedupMap.delete(dedupKey);
994
- }
995
- catch {
996
- // never throw from cleanup
997
- }
998
- };
999
- void deferred.promise.then(cleanup, cleanup);
1000
- }
1001
- try {
1002
- const r = await _acquire(request, acquireOpts);
1003
- if (!r.ok) {
1004
- throw new LLMBulkheadRejectedError(r.reason, r.detail);
1005
- }
1006
- const ctx = {
1007
- admissionId: r.admissionId,
1008
- reservation: r.reservation,
1009
- reportUsage: (usage) => r.token.reportUsage(usage),
1010
- };
1011
- const work = (async () => {
1012
- let result;
1013
- try {
1014
- result = await fn(ao.signal, ctx);
1015
- }
1016
- catch (err) {
1017
- r.token.release(); // no usage on error
1018
- throw err;
1019
- }
1020
- // Extract usage for refund.
1021
- let usage;
1022
- if (getUsage) {
1023
- try {
1024
- const extracted = getUsage(result);
1025
- usage =
1026
- extracted === undefined ? undefined : validateTokenUsage(extracted);
1027
- }
1028
- catch {
1029
- // bad getUsage must not break release
1030
- }
1031
- }
1032
- r.token.release(usage);
1033
- return result;
1034
- })();
1035
- if (deferred) {
1036
- void work.then((v) => deferred.resolve(v), (e) => deferred.reject(e));
1037
- return resultPromise;
1038
- }
1039
- return work;
1040
- }
1041
- catch (err) {
1042
- if (deferred) {
1043
- deferred.reject(err);
1044
- return resultPromise;
1045
- }
1046
- throw err;
1047
- }
1048
- }
1049
- /** Runtime stats. Optional fields are present only when the feature is enabled. */
1050
- function stats() {
1051
- const base = bulkhead.stats();
1052
- const result = {
1053
- bulkhead: base,
1054
- llm: {
1055
- admitted: llmAdmitted,
1056
- released: llmReleased,
1057
- rejected: llmRejected,
1058
- rejectedByReason: { ...llmRejectedByReason },
1059
- },
1060
- };
1061
- if (budget) {
1062
- result.tokenBudget = {
1063
- budget: currentBudget,
1064
- inFlightTokens,
1065
- available: Math.max(0, currentBudget - inFlightTokens),
1066
- totalReserved,
1067
- totalConsumed,
1068
- totalRefunded,
1069
- totalOverrun,
1070
- highPriorityReserve,
1071
- };
1072
- }
1073
- if (dedup.enabled) {
1074
- result.deduplication = {
1075
- active: dedupMap.size,
1076
- hits: dedupHits,
1077
- };
1078
- }
1079
- return result;
1080
- }
1081
- /**
1082
- * Stop admission permanently. All pending waiters in the underlying
1083
- * bulkhead are rejected with `'shutdown'`. Future `acquire`/`run`
1084
- * calls reject immediately. In-flight work is not interrupted.
1085
- */
1086
- function close() {
1087
- bulkhead.close();
1088
- }
1089
- /**
1090
- * Returns a promise that resolves when all in-flight work and
1091
- * pending waiters have completed. Works with or without `close()`.
1092
- * Compose as `close()` → `drain()` for graceful shutdown.
1093
- */
1094
- function drain() {
1095
- return bulkhead.drain();
1096
- }
1097
- /**
1098
- * Subscribe to a bulkhead lifecycle event.
1099
- * Returns an unsubscribe function.
1100
- *
1101
- * Listeners are called synchronously from the bulkhead's internal
1102
- * control flow. They must not throw — exceptions are silently caught.
1103
- */
1104
- function on(event, listener) {
1105
- listeners[event].add(listener);
1106
- return () => {
1107
- listeners[event].delete(listener);
1108
- };
1109
- }
1110
- return {
1111
- estimate,
1112
- acquire,
1113
- run,
1114
- wouldAdmit,
1115
- stats,
1116
- setBudget,
1117
- close,
1118
- drain,
1119
- on,
1120
- };
1121
- }
16
+ * Deep-importing the internal modules is not supported; the package
17
+ * `exports` map exposes only this entry point.
18
+ */
19
+ export { LLMBulkheadRejectedError } from "./errors.js";
20
+ export { PROFILES } from "./profiles.js";
21
+ export { createModelAwareTokenEstimator, extractTextLength, naiveTokenEstimator, } from "./estimators.js";
22
+ export { createAdaptiveTokenEstimator } from "./adaptive.js";
23
+ export { createLLMBulkhead } from "./bulkhead.js";
1122
24
  //# sourceMappingURL=index.js.map