async-bulkhead-llm 3.5.0 → 3.7.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.
package/README.md CHANGED
@@ -13,13 +13,18 @@ Designed for services that need to enforce **cost ceilings, concurrency limits,
13
13
  - ✅ **Token refund** — reclaim unused budget capacity from actual usage post-completion
14
14
  - ✅ **Model-aware estimation** — per-model character ratios for known providers
15
15
  - ✅ **Per-request model** — mixed-model routing through a single bulkhead
16
- - ✅ **Multimodal content** — text blocks counted, non-text blocks ignored
16
+ - ✅ **Multimodal content** — text blocks counted; opaque blocks ignored by default or charged a configurable per-block reservation (`opaqueBlockTokens`)
17
+ - ✅ **Full-request estimation** — `system` prompts counted natively; `extraInputTokens` carries caller-computed costs (tool schemas, provider-priced media)
18
+ - ✅ **Per-call reservation override** — gateways with their own estimate can bypass the estimator via `reservation` on `acquire()`/`run()`/`wouldAdmit()`
17
19
  - ✅ **Fail-fast by default** — shed load early, never silently queue
18
20
  - ✅ **Opinionated profiles** — `'interactive'` and `'batch'` presets with escape hatch
19
21
  - ✅ **In-flight deduplication** — identical requests share one LLM call; hashed keys, whole-request equality
20
22
  - ✅ **Custom dedup key + per-tenant scope** — bring your own equivalence function; `dedupScope` isolates tenants
21
23
  - ✅ **Streaming-safe deduplication** — single-consumer results are never silently shared; `shareResult` fan-out hook + per-call `dedup: false` opt-out
22
- - ✅ **Event hooks** — `on('admit' | 'reject' | 'release' | 'dedup', fn)`
24
+ - ✅ **Exact reservation preview** — `estimate()` exposes the reservation admission will use
25
+ - ✅ **Stable admission IDs** — correlate gateway requests, traces, usage, and release
26
+ - ✅ **Ordered usage events** — sequence-numbered hold changes for external coordinators
27
+ - ✅ **Event hooks** — `on('admit' | 'reject' | 'usage' | 'release' | 'dedup', fn)`
23
28
  - ✅ **Graceful shutdown** — `close()` + `drain()`
24
29
  - ✅ Optional **AbortSignal** and **timeout** cancellation
25
30
  - ✅ `bulkhead.run(request, fn)` — acquire + release handled automatically
@@ -123,6 +128,83 @@ const result = await bulkhead.run(request, async () => {
123
128
 
124
129
  ---
125
130
 
131
+ ## What's New in v3.6 — Gateway coordination seams
132
+
133
+ ### Exact reservation preview
134
+
135
+ `estimate()` runs the same estimator and validation path as admission without
136
+ reserving capacity. This is useful when a gateway must acquire an external
137
+ lease before entering the local bulkhead:
138
+
139
+ ```ts
140
+ const reservation = bulkhead.estimate(request);
141
+ const lease = reservation
142
+ ? await redisLease.reserve(requestId, reservation.reserved)
143
+ : undefined;
144
+
145
+ const result = await bulkhead.acquire(request);
146
+ if (!result.ok) {
147
+ await lease?.release();
148
+ return reject(result.reason);
149
+ }
150
+ ```
151
+
152
+ The preview is advisory until admission occurs: do not mutate the request
153
+ between calls, and keep custom estimators deterministic. `null` means token
154
+ budgeting is disabled and the local bulkhead will reserve no tokens.
155
+
156
+ ### Stable admission identity
157
+
158
+ Every successful admission receives a UUID available on the acquire result,
159
+ token, run context, and lifecycle events:
160
+
161
+ ```ts
162
+ const result = await bulkhead.acquire(request);
163
+ if (result.ok) {
164
+ console.log(result.admissionId);
165
+ console.log(result.token.admissionId);
166
+ result.token.release();
167
+ }
168
+
169
+ await bulkhead.run(request, async (_signal, ctx) => {
170
+ trace.setAttribute('llm.admission_id', ctx!.admissionId);
171
+ return callYourLLMProvider(request);
172
+ });
173
+ ```
174
+
175
+ ### Ordered usage-change events
176
+
177
+ Effective cumulative `reportUsage()` updates emit a sequence-numbered event.
178
+ Stale or duplicate reports are clamped as before and do not emit:
179
+
180
+ ```ts
181
+ bulkhead.on('usage', (event) => {
182
+ // External stores can ignore an update whose sequence is not newer.
183
+ distributedLedger.adjust({
184
+ admissionId: event.admissionId,
185
+ sequence: event.sequence,
186
+ heldTokens: event.heldTokens,
187
+ });
188
+ });
189
+ ```
190
+
191
+ The event includes previous/current hold, delta, cumulative usage, priority,
192
+ output-cap state, and over-reservation status. Listeners remain synchronous;
193
+ enqueue network or storage work rather than blocking inside the callback.
194
+ For admission-critical distributed enforcement, use the returned report and
195
+ await the external update in the gateway's stream loop:
196
+
197
+ ```ts
198
+ const report = ctx!.reportUsage(cumulativeUsage);
199
+ await distributedLedger.setHold({
200
+ admissionId: report.admissionId,
201
+ sequence: report.sequence,
202
+ heldTokens: report.held,
203
+ });
204
+ ```
205
+
206
+ ---
207
+
126
208
  ## What's New in v3.2 — Gateway readiness
127
209
 
128
210
  v3.2 adds the admission-control primitives an AI gateway needs, all additive:
@@ -290,7 +372,8 @@ const bulkhead = createLLMBulkhead({
290
372
  });
291
373
  ```
292
374
 
293
- The default key now includes `messages`, `max_tokens`, and `model`. Return an empty string to opt a specific request out.
375
+ The default key covers the entire request object with stable key ordering.
376
+ Return an empty string to opt a specific request out.
294
377
 
295
378
  ### Event Hooks
296
379
 
@@ -304,7 +387,7 @@ const off = bulkhead.on('release', ({ reservedTokens, refundedTokens, usage }) =
304
387
  off(); // unsubscribe
305
388
  ```
306
389
 
307
- Events: `'admit'`, `'reject'`, `'release'`, `'dedup'`.
390
+ Events: `'admit'`, `'reject'`, `'usage'`, `'release'`, `'dedup'`.
308
391
 
309
392
  ### Graceful Shutdown
310
393
 
@@ -579,6 +662,8 @@ if (!r.ok) {
579
662
  return respond503(r.reason);
580
663
  }
581
664
 
665
+ console.log(`Admission: ${r.admissionId}`);
666
+
582
667
  try {
583
668
  const response = await callLLM(request);
584
669
  return response;
@@ -669,8 +754,8 @@ type LLMStats = {
669
754
 
670
755
  ```ts
671
756
  // Subscribe
672
- const off = bulkhead.on('admit', ({ request, reservedTokens }) => {
673
- console.log(`Admitted: ${reservedTokens} tokens reserved`);
757
+ const off = bulkhead.on('admit', ({ admissionId, reservedTokens }) => {
758
+ console.log(`${admissionId}: ${reservedTokens} tokens reserved`);
674
759
  });
675
760
 
676
761
  // Unsubscribe
@@ -679,12 +764,15 @@ off();
679
764
 
680
765
  | Event | Payload |
681
766
  |-----------|---------|
682
- | `admit` | `{ request, reservedTokens }` |
683
- | `reject` | `{ request, reason }` |
684
- | `release` | `{ request, reservedTokens, refundedTokens, usage? }` |
767
+ | `admit` | `{ request, admissionId, priority, reservedTokens }` |
768
+ | `reject` | `{ request, reason, detail? }` |
769
+ | `usage` | `{ request, admissionId, priority, sequence, reservedTokens, previousHeldTokens, heldTokens, deltaTokens, usage, outputCap, outputRemaining, overReservation }` |
770
+ | `release` | `{ request, admissionId, priority, reservedTokens, heldTokens, refundedTokens, usageSequence, usage? }` |
685
771
  | `dedup` | `{ request }` |
686
772
 
687
773
  Listeners are synchronous and fire-and-forget. Exceptions are silently caught.
774
+ Do not perform blocking network I/O in a listener; enqueue telemetry or lease
775
+ updates for asynchronous delivery.
688
776
 
689
777
  ---
690
778
 
@@ -711,10 +799,10 @@ type LLMBulkheadOptions = {
711
799
  timeoutMs?: number; // integer >= 0
712
800
  profile?: 'interactive' | 'batch' | LLMBulkheadPreset;
713
801
  tokenBudget?: {
714
- budget: number; // non-negative integer; 0 rejects all budget-gated admissions
715
- estimator?: TokenEstimator;
716
-
717
- outputCap?: number; // integer >= 0
802
+ budget: number; // non-negative integer; 0 rejects all budget-gated admissions
803
+ estimator?: TokenEstimator;
804
+ outputCap?: number; // integer >= 0
805
+ highPriorityReserve?: number; // integer >= 0 and <= initial budget
718
806
  };
719
807
  deduplication?: boolean | DeduplicationOptions;
720
808
  };
@@ -730,10 +818,11 @@ type DeduplicationOptions = {
730
818
  ```ts
731
819
  run<T>(
732
820
  request: LLMRequest,
733
- fn: (signal?: AbortSignal) => Promise<T>,
821
+ fn: (signal?: AbortSignal, ctx?: LLMRunContext) => Promise<T>,
734
822
  options?: {
735
823
  signal?: AbortSignal;
736
824
  timeoutMs?: number; // integer >= 0
825
+ priority?: 'normal' | 'high';
737
826
  getUsage?: (result: T) => TokenUsage | undefined;
738
827
  dedupScope?: string; // dedup isolation scope (e.g. tenant / API key)
739
828
  dedup?: boolean; // false = opt this call out of dedup (v3.5)
@@ -741,19 +830,52 @@ run<T>(
741
830
  ): Promise<T>
742
831
  ```
743
832
 
833
+ `ctx.admissionId` is the stable admission identifier. `ctx.reservation` is
834
+ the exact reservation used at admission (or `null` when token budgeting is
835
+ disabled), and `ctx.reportUsage()` reports cumulative streaming usage.
836
+
837
+ ### `bulkhead.estimate(request)`
838
+
839
+ ```ts
840
+ estimate(request: LLMRequest): LLMReservationEstimate | null
841
+
842
+ type LLMReservationEstimate = {
843
+ readonly input: number;
844
+ readonly maxOutput: number;
845
+ readonly reserved: number;
846
+ };
847
+ ```
848
+
849
+ Runs the same estimator and validation path as admission but does not reserve
850
+ capacity. Returns `null` when `tokenBudget` is not configured.
851
+
744
852
  ### `bulkhead.acquire(request, options?)`
745
853
 
746
854
  ```ts
747
855
  acquire(
748
856
  request: LLMRequest,
749
- options?: { signal?: AbortSignal; timeoutMs?: number /* integer >= 0 */ },
857
+ options?: {
858
+ signal?: AbortSignal;
859
+ timeoutMs?: number; // integer >= 0
860
+ priority?: 'normal' | 'high';
861
+ },
750
862
  ): Promise<LLMAcquireResult>
751
863
 
752
864
  type LLMAcquireResult =
753
- | { ok: true; token: LLMToken }
865
+ | {
866
+ ok: true;
867
+ admissionId: string;
868
+ reservation: LLMReservationEstimate | null;
869
+ token: LLMToken;
870
+ }
754
871
  | { ok: false; reason: LLMRejectReason };
755
872
 
756
- type LLMToken = { release(usage?: TokenUsage): void };
873
+ type LLMToken = {
874
+ readonly admissionId: string;
875
+ readonly reservation: LLMReservationEstimate | null;
876
+ reportUsage(usage: TokenUsage): UsageReport;
877
+ release(usage?: TokenUsage): void;
878
+ };
757
879
  ```
758
880
 
759
881
  ### `bulkhead.stats()`
@@ -792,8 +914,19 @@ type TextContentBlock = { type: 'text'; text: string };
792
914
  type OpaqueContentBlock = { type: string; [key: string]: unknown };
793
915
 
794
916
  type TokenEstimate = { input: number; maxOutput: number };
917
+ type LLMReservationEstimate = TokenEstimate & { reserved: number };
795
918
  type TokenEstimator = (request: LLMRequest) => TokenEstimate;
796
919
  type TokenUsage = { input: number; output: number };
920
+ type UsageReport = {
921
+ admissionId: string;
922
+ sequence: number;
923
+ reserved: number;
924
+ held: number;
925
+ consumed: number;
926
+ outputCap: number | null;
927
+ outputRemaining: number | null;
928
+ overReservation: boolean;
929
+ };
797
930
 
798
931
  type LLMRejectReason =
799
932
  | 'concurrency_limit'
@@ -801,13 +934,20 @@ type LLMRejectReason =
801
934
  | 'budget_limit'
802
935
  | 'timeout'
803
936
  | 'aborted'
804
- | 'shutdown';
937
+ | 'shutdown'
938
+ | 'unshareable_result';
805
939
  ```
806
940
 
807
941
  ---
808
942
 
809
943
  ## Migration
810
944
 
945
+ ### v3.5 → v3.6
946
+
947
+ No call-site changes are required. `admit` and `release` event payloads gained
948
+ additional fields, and `usage` is a new event type. Code that exhaustively
949
+ enumerates `LLMEventType` should add the new `usage` case.
950
+
811
951
  ### v2 → v3
812
952
 
813
953
  Update stats access from top-level fields to the `bulkhead` block:
@@ -861,4 +1001,4 @@ Token estimation is deliberately approximate. The refund mechanism improves budg
861
1001
 
862
1002
  ## License
863
1003
 
864
- Apache License 2.0 © 2026
1004
+ Apache License 2.0 © 2026
@@ -73,14 +73,33 @@ function extractTextLength(content) {
73
73
  return content.length;
74
74
  let len = 0;
75
75
  for (const block of content) {
76
- if (block.type === "text" &&
77
- "text" in block &&
78
- typeof block.text === "string") {
76
+ if (isTextBlock(block))
79
77
  len += block.text.length;
80
- }
81
78
  }
82
79
  return len;
83
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
+ }
84
103
  function resolveMaxOutput(request, fallback) {
85
104
  assertNonNegativeInteger(fallback, "outputCap");
86
105
  assertOptionalNonNegativeInteger(request.max_tokens, "request.max_tokens");
@@ -94,11 +113,17 @@ function resolveMaxOutput(request, fallback) {
94
113
  *
95
114
  * Accuracy: ±25% for English prose.
96
115
  * Suitable for load-shedding; not suitable for cost accounting.
116
+ *
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).
97
121
  */
98
122
  function naiveTokenEstimator(request) {
99
- const inputChars = request.messages.reduce((sum, m) => sum + extractTextLength(m.content), 0);
123
+ const inputChars = requestInputChars(request);
100
124
  return {
101
- input: Math.ceil(inputChars / NAIVE_CHAR_RATIO),
125
+ input: Math.ceil(inputChars / NAIVE_CHAR_RATIO) +
126
+ resolveExtraInputTokens(request),
102
127
  maxOutput: resolveMaxOutput(request, DEFAULT_OUTPUT_CAP),
103
128
  };
104
129
  }
@@ -136,13 +161,53 @@ const BUILT_IN_RATIOS = [
136
161
  ["gemini-2", 3.8],
137
162
  ["gemini-1.5", 3.8],
138
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
+ }
139
203
  function isModelAwareEstimatorOptions(value) {
140
204
  if (value == null || typeof value !== "object" || Array.isArray(value)) {
141
205
  return false;
142
206
  }
143
207
  return ("defaultModel" in value ||
144
208
  "outputCap" in value ||
145
- "onUnknownModel" in value);
209
+ "onUnknownModel" in value ||
210
+ "opaqueBlockTokens" in value);
146
211
  }
147
212
  function createModelAwareTokenEstimator(overridesOrOpts, maybeOpts) {
148
213
  const hasSingleOptionsArg = maybeOpts === undefined &&
@@ -155,6 +220,8 @@ function createModelAwareTokenEstimator(overridesOrOpts, maybeOpts) {
155
220
  : (maybeOpts ?? {});
156
221
  const outputCap = opts.outputCap ?? DEFAULT_OUTPUT_CAP;
157
222
  assertNonNegativeInteger(outputCap, "outputCap");
223
+ const opaqueBlockTokens = opts.opaqueBlockTokens;
224
+ validateOpaqueBlockTokens(opaqueBlockTokens);
158
225
  function lookupRatio(model) {
159
226
  // Exact overrides checked first (case-sensitive, then lowercased).
160
227
  if (overrides) {
@@ -180,9 +247,11 @@ function createModelAwareTokenEstimator(overridesOrOpts, maybeOpts) {
180
247
  return (request) => {
181
248
  const model = request.model ?? opts.defaultModel ?? "";
182
249
  const ratio = lookupRatio(model);
183
- const inputChars = request.messages.reduce((sum, m) => sum + extractTextLength(m.content), 0);
250
+ const inputChars = requestInputChars(request);
184
251
  return {
185
- input: Math.ceil(inputChars / ratio),
252
+ input: Math.ceil(inputChars / ratio) +
253
+ countOpaqueBlockTokens(request, opaqueBlockTokens) +
254
+ resolveExtraInputTokens(request),
186
255
  maxOutput: resolveMaxOutput(request, outputCap),
187
256
  };
188
257
  };
@@ -360,6 +429,7 @@ function createLLMBulkhead(opts) {
360
429
  admit: new Set(),
361
430
  reject: new Set(),
362
431
  release: new Set(),
432
+ usage: new Set(),
363
433
  dedup: new Set(),
364
434
  };
365
435
  function emit(event, payload) {
@@ -394,11 +464,54 @@ function createLLMBulkhead(opts) {
394
464
  return { promise, resolve, reject };
395
465
  }
396
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");
397
478
  if (!budget)
398
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
+ }
399
488
  const estimate = estimator(request);
400
489
  const reserved = validateTokenEstimate(estimate);
401
- return { input: estimate.input, maxOut: estimate.maxOutput, reserved };
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 };
402
515
  }
403
516
  function resolvePriority(priority) {
404
517
  if (priority === undefined)
@@ -624,18 +737,24 @@ function createLLMBulkhead(opts) {
624
737
  * reservation and optionally applies the refund, and so that
625
738
  * streaming callers can report cumulative usage mid-flight.
626
739
  */
627
- function wrapToken(base, parts, request) {
740
+ function wrapToken(base, parts, request, admissionId, priority) {
628
741
  let released = false;
629
742
  /** Tokens currently held against the budget for this request. */
630
743
  let held = parts?.reserved ?? 0;
631
744
  /** Last reported cumulative usage (monotonically clamped). */
632
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 });
633
750
  const snapshot = () => {
634
751
  const consumed = reported
635
752
  ? reported.input + reported.output
636
753
  : 0;
637
- const outputCap = parts ? parts.maxOut : null;
754
+ const outputCap = parts ? parts.maxOutput : null;
638
755
  return {
756
+ admissionId,
757
+ sequence: usageSequence,
639
758
  reserved: parts?.reserved ?? 0,
640
759
  held,
641
760
  consumed,
@@ -648,20 +767,25 @@ function createLLMBulkhead(opts) {
648
767
  };
649
768
  const reportUsage = (usage) => {
650
769
  const valid = validateTokenUsage(usage);
770
+ const previousReported = reported;
651
771
  // Clamp to monotonic non-decreasing per field — cumulative
652
772
  // stream usage never shrinks; a lower report is stale.
653
- reported = reported
773
+ reported = previousReported
654
774
  ? {
655
- input: Math.max(reported.input, valid.input),
656
- output: Math.max(reported.output, valid.output),
775
+ input: Math.max(previousReported.input, valid.input),
776
+ output: Math.max(previousReported.output, valid.output),
657
777
  }
658
778
  : valid;
779
+ const usageChanged = previousReported === undefined ||
780
+ reported.input !== previousReported.input ||
781
+ reported.output !== previousReported.output;
782
+ const previousHeldTokens = held;
659
783
  // Accounting only applies pre-release with a budget configured.
660
784
  if (!released && parts && budget) {
661
785
  // Hold = known input + the larger of (output ceiling, actual output).
662
786
  // Keeps the full output reservation while refunding input
663
787
  // over-estimates immediately; expands on output overrun.
664
- const newHold = reported.input + Math.max(parts.maxOut, reported.output);
788
+ const newHold = reported.input + Math.max(parts.maxOutput, reported.output);
665
789
  const delta = newHold - held;
666
790
  if (delta > 0) {
667
791
  inFlightTokens += delta;
@@ -674,9 +798,31 @@ function createLLMBulkhead(opts) {
674
798
  }
675
799
  held = newHold;
676
800
  }
677
- return snapshot();
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;
678
822
  };
679
823
  return {
824
+ admissionId,
825
+ reservation,
680
826
  reportUsage,
681
827
  release(usage) {
682
828
  if (released)
@@ -711,8 +857,12 @@ function createLLMBulkhead(opts) {
711
857
  noteLLMRelease();
712
858
  emit("release", {
713
859
  request,
860
+ admissionId,
861
+ priority,
714
862
  reservedTokens: parts?.reserved ?? 0,
863
+ heldTokens: heldAtRelease,
715
864
  refundedTokens: refunded,
865
+ usageSequence,
716
866
  ...(validUsage !== undefined && { usage: validUsage }),
717
867
  });
718
868
  }
@@ -723,9 +873,8 @@ function createLLMBulkhead(opts) {
723
873
  }
724
874
  // ---- Internal acquire ----
725
875
  async function _acquire(request, ao) {
726
- assertOptionalNonNegativeInteger(request.max_tokens, "request.max_tokens");
727
876
  const priority = resolvePriority(ao.priority);
728
- const parts = estimateParts(request);
877
+ const parts = resolveReservation(request, ao.reservation);
729
878
  const reserved = parts?.reserved ?? 0;
730
879
  const rejectWith = (reason) => {
731
880
  const detail = buildRejectDetail(reserved, priority);
@@ -747,9 +896,16 @@ function createLLMBulkhead(opts) {
747
896
  r.token.release();
748
897
  return rejectWith("budget_limit");
749
898
  }
899
+ const admissionId = (0, node_crypto_1.randomUUID)();
900
+ const token = wrapToken(r.token, parts, request, admissionId, priority);
750
901
  noteLLMAdmit();
751
- emit("admit", { request, reservedTokens: reserved });
752
- return { ok: true, token: wrapToken(r.token, parts, request) };
902
+ emit("admit", { request, admissionId, priority, reservedTokens: reserved });
903
+ return {
904
+ ok: true,
905
+ admissionId,
906
+ reservation: token.reservation,
907
+ token,
908
+ };
753
909
  }
754
910
  // ---- Public API ----
755
911
  /**
@@ -769,13 +925,17 @@ function createLLMBulkhead(opts) {
769
925
  * model pool). It does NOT reserve anything — the answer can change
770
926
  * before a subsequent `acquire()`/`run()` lands. Never treat `true`
771
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.
772
932
  */
773
933
  function wouldAdmit(request, opts = {}) {
774
934
  const priority = resolvePriority(opts.priority);
775
935
  const base = bulkhead.stats();
776
936
  if (base.closed)
777
937
  return { admit: false, reason: "shutdown" };
778
- const parts = estimateParts(request);
938
+ const parts = resolveReservation(request, opts.reservation);
779
939
  const reserved = parts?.reserved ?? 0;
780
940
  if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
781
941
  return { admit: false, reason: "budget_limit" };
@@ -852,6 +1012,8 @@ function createLLMBulkhead(opts) {
852
1012
  throw new LLMBulkheadRejectedError(r.reason, r.detail);
853
1013
  }
854
1014
  const ctx = {
1015
+ admissionId: r.admissionId,
1016
+ reservation: r.reservation,
855
1017
  reportUsage: (usage) => r.token.reportUsage(usage),
856
1018
  };
857
1019
  const work = (async () => {
@@ -953,6 +1115,16 @@ function createLLMBulkhead(opts) {
953
1115
  listeners[event].delete(listener);
954
1116
  };
955
1117
  }
956
- return { acquire, run, wouldAdmit, stats, setBudget, close, drain, on };
1118
+ return {
1119
+ estimate,
1120
+ acquire,
1121
+ run,
1122
+ wouldAdmit,
1123
+ stats,
1124
+ setBudget,
1125
+ close,
1126
+ drain,
1127
+ on,
1128
+ };
957
1129
  }
958
1130
  //# sourceMappingURL=index.cjs.map