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