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