async-bulkhead-llm 3.15.0 → 3.15.2

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 (3) hide show
  1. package/CHANGELOG.md +967 -0
  2. package/README.md +140 -1768
  3. package/package.json +10 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,967 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
6
+ and adheres to [Semantic Versioning](https://semver.org/).
7
+
8
+ ---
9
+
10
+ ## [3.15.2] - 2026-08-17
11
+
12
+ Documentation-only release. No runtime code changed and the public API is
13
+ identical to 3.15.1; no upgrade action is required.
14
+
15
+ ### Changed
16
+
17
+ * **README rewritten for first-time readers.** The README is now a short
18
+ landing page (what the library does, install, quick start, token limits,
19
+ handling rejections, shutdown) instead of a 1,850-line reference. The
20
+ thirteen stacked "What's New in vX" sections have been removed from it;
21
+ per-release detail lives in this changelog, and the topical content moved
22
+ into `guides/`.
23
+
24
+ * **Long-form documentation moved to `guides/`.** Eleven guides now carry the
25
+ material previously inlined in the README: how admission works, token budget
26
+ and estimation, streaming and reconciliation, admission classes, runtime
27
+ limits and reconfiguration, observe mode, deduplication, gateway
28
+ integration, stats and events, comparison, and migration. Content was moved
29
+ rather than rewritten.
30
+
31
+ * **Hand-maintained API reference retired.** The `## API Reference` section is
32
+ replaced by the generated TypeDoc reference, which is derived from the
33
+ source types and therefore cannot drift from the code.
34
+
35
+ ### Added
36
+
37
+ * **TypeDoc documentation site.** `npm run docs` generates a static site into
38
+ `docs/` from `src/index.ts`, with the README as the landing page and the
39
+ `guides/` files and this changelog rendered as site pages. Added
40
+ `docs:watch` for local iteration and `docs:coverage` to report symbols
41
+ missing TSDoc comments.
42
+
43
+ * **GitHub Pages publishing.** `.github/workflows/docs.yml` builds the site on
44
+ every pull request and deploys it from `main`. Publishing requires the
45
+ repository Pages source to be set to "GitHub Actions". Generated output is
46
+ git-ignored and built in CI rather than committed.
47
+
48
+ ### Fixed
49
+
50
+ * **`npm run lint` no longer fails after a docs build.** `eslint .` linted
51
+ TypeDoc's generated browser assets under `docs/`, producing 367 errors on
52
+ any working tree where documentation had been generated. `docs/**` and
53
+ `coverage/**` are now ignored by ESLint.
54
+
55
+ * **Removed the cost-ceiling claim.** Earlier documentation described
56
+ `tokenBudget` as enforcing a "cost ceiling" that stops requests "before you
57
+ pay for them." That was wrong. The budget is a ceiling on tokens reserved
58
+ concurrently: admission compares `inFlightTokens + reserved` against the
59
+ budget, and the entire reservation is released when the request completes.
60
+ It bounds in-flight commitment, not cumulative spend, and a given budget
61
+ places no limit on total tokens consumed over time. The documentation now
62
+ states this explicitly, consistent with the library's long-standing
63
+ no-cost-accounting non-goal. No behavior changed — only the description of
64
+ it.
65
+
66
+ * **Broken documentation links.** The README's `./LICENSE` and `./SECURITY.md`
67
+ links resolved correctly on GitHub but not in the generated site; both now
68
+ use absolute repository URLs so they work from GitHub, npm, and the
69
+ documentation site.
70
+
71
+ ### Compatibility
72
+
73
+ * No API, behavior, or dependency changes for consumers. The published tarball
74
+ contents are unchanged apart from the rewritten `README.md`. `guides/` and
75
+ the documentation tooling are development-only and are not published.
76
+
77
+ ## [3.15.1] - 2026-08-06
78
+
79
+ ### Fixed
80
+
81
+ * **npm package documentation.** The publish manifest now explicitly includes
82
+ `README.md`, `LICENSE`, and `CHANGELOG.md` so the npm registry package page
83
+ and downloaded package consistently contain the release documentation.
84
+
85
+ ## [3.15.0] - 2026-08-06
86
+
87
+ ### Added
88
+
89
+ * **Protected admission-class floors.** Admission classes may reserve strict
90
+ local concurrency with `protectedConcurrent` and strict in-flight token
91
+ capacity with `protectedInFlightTokens`. The sum of configured floors must
92
+ fit inside the corresponding global limit, and a class floor may not exceed
93
+ its hard class ceiling.
94
+
95
+ * **Shared-capacity borrowing.** Capacity remaining after all protected floors
96
+ forms a shared pool. A class consumes its floor first and may then borrow from
97
+ the shared remainder, subject to its class ceilings, global limits, and the
98
+ priority-adjusted token budget.
99
+
100
+ * **Protection-aware rejection detail.** Requests rejected to preserve another
101
+ class's floor report `constraint: "admission_class_protection"` and include
102
+ shared concurrency/token capacity plus protected and borrowed class usage.
103
+
104
+ * **Borrowing telemetry.** `stats().admissionClasses.shared` exposes the shared
105
+ remainder. Per-class stats expose current protected and borrowed usage,
106
+ cumulative admissions using shared concurrency, and cumulative reservation
107
+ tokens placed in shared capacity.
108
+
109
+ ### Changed
110
+
111
+ * **Non-revoking floor reconfiguration.** Floor changes are installed atomically
112
+ with the existing versioned admission snapshot. Increasing a floor never
113
+ revokes active work; new borrowing pauses until normal completion restores
114
+ the protected capacity by attrition.
115
+
116
+ ### Compatibility
117
+
118
+ * This is an additive minor release. Omitting both protected-floor fields
119
+ preserves v3.14 admission behavior. Exact object-shape assertions must allow
120
+ the new stats, rejection-detail, limit, and capacity-constraint fields.
121
+ * Protected floors are strict reservations and are not automatically lent while
122
+ idle. Demand-aware cross-class lending remains a gateway/control-plane policy
123
+ implemented by applying a newer limit snapshot.
124
+
125
+ ## [3.14.0] - 2026-08-04
126
+
127
+ ### Added
128
+
129
+ * **Bounded admission classes.** `admissionClasses` configures a fixed table of
130
+ policy-class IDs with optional hard `maxConcurrent` and
131
+ `maxInFlightTokens` ceilings. Calls select a class with `admissionClass` or
132
+ fall back to `defaultClass`; unknown IDs throw instead of creating
133
+ unbounded runtime state.
134
+
135
+ * **Hierarchical capacity decisions.** Successful admission must fit both the
136
+ enclosing global limits and the selected class limits. Class ceilings are
137
+ fail-fast, use shrink-by-attrition under reconfiguration, and remain atomic
138
+ with global concurrency and token accounting.
139
+
140
+ * **Class-aware progressive accounting.** Reservations, progressive usage
141
+ refunds, output overruns, and final release settlement update global and
142
+ class token holds together.
143
+
144
+ * **Class-aware telemetry.** Successful results, tokens, run contexts, usage
145
+ reports, lifecycle events, capacity details, and observe-mode bypasses carry
146
+ `admissionClass` when configured. Capacity details identify the binding
147
+ `constraint` as `global` or `admission_class`, and
148
+ `stats().admissionClasses` reports bounded per-class counters.
149
+
150
+ * **Class-safe deduplication.** Admission class is an automatic deduplication
151
+ partition when classes are configured, preventing one class from inheriting
152
+ another class's admission decision or queue position. Class IDs are validated
153
+ before the dedup follower fast path, and dedup/rejection events retain class
154
+ attribution.
155
+
156
+ * **Atomic class-limit updates.** `LLMAdmissionLimits.admissionClasses` updates
157
+ every construction-time class in the same versioned snapshot as global
158
+ concurrency, queue, token budget, and priority reserve. Runtime updates may
159
+ change numeric ceilings but cannot add or remove class keys.
160
+
161
+ ### Compatibility
162
+
163
+ * This is an additive minor release. Existing behavior and object shapes remain
164
+ unchanged when `admissionClasses` is omitted.
165
+ * Admission classes are bounded policy buckets, not an authentication layer or
166
+ a replacement for tenant-scoped deduplication. Identity mapping, weighted
167
+ fairness, protected-floor lending, and distributed coordination remain the
168
+ responsibility of the gateway/control plane.
169
+
170
+ ## [3.13.0] - 2026-08-01
171
+
172
+ ### Added
173
+
174
+ * **Progressive reservation reconciliation.** `reportUsage()` accepts an
175
+ optional `remainingOutputTokens` plus `safetyMarginTokens` declaration.
176
+ Gateways can release processed input and already-generated output capacity
177
+ during a live stream while retaining explicit future-output headroom.
178
+ * Progressive updates retain cumulative-usage monotonicity, preserve output
179
+ overrun protection, emit sequence-numbered usage events, and remain no-op
180
+ accounting in observe-mode bypasses.
181
+
182
+ ## [3.12.0] - 2026-07-26
183
+
184
+ ### Added
185
+
186
+ * **Fail-closed construction.** `createLLMBulkhead()` now accepts
187
+ `maxConcurrent: 0`, allowing gateways to start with no admission capacity and
188
+ remain closed until an external control plane installs a higher-revision
189
+ snapshot. Runtime zero-capacity behavior is unchanged: new work is rejected
190
+ with `concurrency_limit`, while later expansion begins admitting immediately.
191
+
192
+ ## [3.11.1] - 2026-07-24
193
+
194
+ ### Security
195
+
196
+ * Refreshed the development dependency lockfile so the ESLint/minimatch toolchain
197
+ uses `brace-expansion` 5.0.8, resolving the reported high-severity audit
198
+ finding. This dependency is development-only; the runtime dependency graph is
199
+ unchanged.
200
+
201
+ ### Fixed
202
+
203
+ * Published the finalized v3.11 contents under a new immutable package version
204
+ after the v3.11.0 registry tarball produced an integrity mismatch. Consumers
205
+ should install v3.11.1 rather than retrying the conflicting v3.11.0 artifact.
206
+
207
+ * Updated the strict admit-capacity snapshot test to include the additive
208
+ `limitRevision: 0` field introduced in v3.11.
209
+
210
+ ## [3.11.0] - 2026-07-24
211
+
212
+ ### Added
213
+
214
+ * **Admission-linearized limit revisions.** Successful `acquire()` results,
215
+ `LLMToken`, `LLMRunContext`, `UsageReport`, and admitted/bypassed lifecycle
216
+ events now carry an immutable `limitRevision` captured after both the
217
+ concurrency slot and token reservation are held.
218
+
219
+ * **Revisioned rejection snapshots.** `LLMRejectDetail.limitRevision` and the
220
+ `reject` event identify the exact limit snapshot used for the capacity
221
+ decision, allowing gateways to report authoritative revisions without a
222
+ later `limits()` lookup.
223
+
224
+ ### Fixed
225
+
226
+ * A synchronous `admit` listener can apply a newer limit snapshot before the
227
+ `run()` callback starts. The callback, usage events, and release event now
228
+ retain the original admission revision instead of being relabeled with the
229
+ newer configuration.
230
+
231
+ ## [3.10.0] - 2026-07-23
232
+
233
+ ### Added
234
+
235
+ * **Atomic, versioned admission-limit reconfiguration.**
236
+ `bulkhead.applyLimits(snapshot)` replaces `maxConcurrent`, `maxQueue`,
237
+ `tokenBudget.budget`, and `tokenBudget.highPriorityReserve` as one complete
238
+ snapshot. Updates require a strictly increasing non-negative safe-integer
239
+ `revision`; equal or lower revisions return
240
+ `{ applied: false, reason: "stale_revision" }` without mutation.
241
+
242
+ * **Runtime concurrency and queue changes.** Lower ceilings use
243
+ shrink-by-attrition: in-flight work and already accepted waiters are not
244
+ cancelled. Raising concurrency pumps accepted waiters immediately. A
245
+ runtime `maxConcurrent: 0` acts as a fail-fast kill switch for new work.
246
+
247
+ * **Limit inspection and telemetry.** `bulkhead.limits()` and
248
+ `stats().limits` expose the currently applied frozen snapshot.
249
+ `initialRevision` seeds the constructor state, and the new `reconfigure`
250
+ event contains the previous and current snapshots.
251
+
252
+ ### Changed
253
+
254
+ * `setBudget(tokens)` remains backward compatible but now delegates to a
255
+ complete local reconfiguration and advances the revision by one. Distributed
256
+ control-plane integrations should use `applyLimits()` exclusively so one
257
+ authority owns the revision stream.
258
+
259
+ * The internal concurrency gate now supports dynamic `maxConcurrent` and
260
+ `maxQueue` while preserving the public stats and rejection semantics used by
261
+ the LLM bulkhead.
262
+
263
+ ## [3.9.0] - 2026-07-22
264
+
265
+ ### Added
266
+
267
+ * **First-class observe mode for `run()`.** Pass `{ mode: "observe" }` to
268
+ execute work without holding concurrency or token capacity when admission
269
+ would reject for `budget_limit`, `concurrency_limit`, `queue_limit`, or
270
+ `timeout`. The default remains `{ mode: "enforce" }`. `shadowReasons` can
271
+ narrow the bypassable capacity reasons; shutdown, caller cancellation, and
272
+ unsafe deduplication fan-out remain hard failures and cannot be shadowed.
273
+
274
+ * **Admitted-versus-bypassed run context.** `LLMRunContext.admission` is
275
+ `"admitted"` or `"bypassed"`. Bypassed executions receive a stable
276
+ `shadow-...` identifier, the exact evaluated reservation, and optional
277
+ `bypassReason` / `bypassDetail`. `reportUsage()` remains available and
278
+ returns normal `UsageReport` snapshots without altering capacity accounting.
279
+
280
+ * **Observe telemetry.** `stats().observe` reports bypass counts, race
281
+ bypasses, reasons, and final usage totals. New `bypass`, `bypassUsage`, and
282
+ `bypassRelease` events expose the same lifecycle without misrepresenting
283
+ bypassed work as admitted or released capacity.
284
+
285
+ ### Changed
286
+
287
+ * Observe mode performs an exact advisory check before authoritative admission.
288
+ Obvious capacity rejections bypass immediately; a later queue timeout or
289
+ post-slot budget race is also bypassed and counted as `raceBypassed`. The
290
+ same resolved reservation is reused across both checks.
291
+
292
+ ## [3.8.0] - 2026-07-21
293
+
294
+ ### Added
295
+
296
+ * **Bounded drain: `drain({ timeoutMs })`.** The no-argument form keeps its
297
+ `Promise<void>` contract unchanged. With a deadline, the promise always
298
+ *resolves* (never rejects) with an `LLMDrainResult` —
299
+ `{ drained: true, inFlight: 0, pending: 0 }` when everything completed in
300
+ time, or `{ drained: false, inFlight, pending }` with the outstanding
301
+ counts at the moment the deadline elapsed. The deadline never cancels or
302
+ interrupts in-flight work and leaves accounting untouched: work that
303
+ finishes later still releases normally. Intended for shutdown paths that
304
+ must log what they are abandoning and proceed, rather than parking
305
+ forever behind one stuck upstream stream. `timeoutMs` must be a
306
+ non-negative integer; `0` is an immediate "is it drained right now?"
307
+ snapshot.
308
+
309
+ * **`wouldAdmit(request, { detail: true })`.** Opt in to receive the same
310
+ `LLMRejectDetail` capacity snapshot that real rejections carry — on
311
+ every outcome, including `admit: true`, where it describes the capacity
312
+ the request would be admitted against (`requested` is the reservation
313
+ this request needs). Routing layers choosing between pools want the
314
+ numbers, not just the boolean. Omitted by default, so the result shape
315
+ and cost are unchanged for existing callers (results still deep-equal
316
+ `{ admit: true }` etc.).
317
+
318
+ * **`estimate()` results round-trip as the `reservation` override.** The
319
+ per-call override now accepts `LLMReservationOverride`
320
+ (`TokenEstimate & { reserved?: number }`), so the frozen object returned
321
+ by `bulkhead.estimate()` can be passed back verbatim — no need to strip
322
+ `reserved` first. When `reserved` is present it is validated as a
323
+ consistency check: it must equal `input + maxOutput`, otherwise
324
+ admission throws. This catches hand-built overrides whose cached
325
+ `reserved` drifted from edited parts. Plain `{ input, maxOutput }`
326
+ overrides (the 3.7 shape) are unchanged.
327
+
328
+ * **`createAdaptiveTokenEstimator()` — self-calibrating estimation.** A
329
+ wrapper around `createModelAwareTokenEstimator` that closes the feedback
330
+ loop between estimates and reality. Feed it actual usage from completed
331
+ calls via `observe(request, usage)` (typically wired to the bulkhead's
332
+ `release` event); it maintains a per-model EWMA of
333
+ `actual input / estimated input` and multiplies future *input*
334
+ estimates by that factor — clamped to
335
+ `[minCorrection, maxCorrection]` (default `[0.5, 2]`) and applied only
336
+ after `minSamples` observations (default 5). Output reservations are
337
+ never corrected: `max_tokens` / `outputCap` is a ceiling, not an
338
+ estimate. Observations always measure against the *uncorrected* base
339
+ estimate, so the loop does not compound through its own corrections.
340
+ Tracked models are bounded (`maxModels`, default 64, oldest-inserted
341
+ evicted); `corrections()` exposes the calibration state for stats
342
+ endpoints and `reset(model?)` clears it. Calibration is in-memory and
343
+ per-instance — share one instance per bulkhead.
344
+
345
+ ### Changed
346
+
347
+ * **`wouldAdmit()` validates before the shutdown check.** The request (and
348
+ any `reservation` override) is now validated *before* the closed fast
349
+ path, matching `acquire()`'s ordering — an invalid request (e.g. a
350
+ negative `max_tokens`) now throws even when the bulkhead is closed,
351
+ instead of returning `{ admit: false, reason: "shutdown" }`. Valid
352
+ requests against a closed bulkhead behave exactly as before.
353
+
354
+ ### Internal
355
+
356
+ * **Source split into focused modules.** The former single-file
357
+ `src/index.ts` (~2,400 lines) is now a barrel over `types.ts`,
358
+ `errors.ts`, `profiles.ts`, `validation.ts`, `estimators.ts`,
359
+ `adaptive.ts`, `dedup.ts`, and `bulkhead.ts`. No public API change:
360
+ the package entry point re-exports the identical surface (verified
361
+ against the pre-split build), and the `exports` map still exposes
362
+ only the entry point — deep imports of the internal modules remain
363
+ unsupported. `dist/` now contains one file per module for ESM, CJS
364
+ (`.cjs`, with local requires rewritten), and declarations.
365
+
366
+ ### Notes
367
+
368
+ * All changes are additive and backward compatible for valid inputs:
369
+ `drain()` without arguments, `wouldAdmit()` without `detail`, and
370
+ `{ input, maxOutput }` reservation overrides behave exactly as in
371
+ 3.7.0. The only observable difference is the validation-ordering change
372
+ above, which affects invalid requests on closed bulkheads only.
373
+
374
+ ---
375
+
376
+ ## [3.7.0] - 2026-07-20
377
+
378
+ ### Added
379
+
380
+ * **`LLMRequest.system`** — optional system prompt (string or content-block
381
+ array), counted by both built-in estimators exactly like message content.
382
+ Previously, callers had to fold the system prompt into a synthetic message
383
+ for it to participate in estimation, which also distorted events, logs,
384
+ and deduplication keys.
385
+
386
+ * **`LLMRequest.extraInputTokens`** — a first-class channel for input tokens
387
+ the character-based estimators cannot see (tool schemas kept outside
388
+ `messages`, provider-priced media, etc.). Built-in estimators add the
389
+ value verbatim; custom estimators may honor or ignore it. Must be a
390
+ non-negative integer. Because it is an ordinary request field, it
391
+ participates in the default deduplication key — requests differing only
392
+ here are never conflated. This replaces the pattern of smuggling
393
+ out-of-band token costs through wrapper estimators or hidden properties.
394
+
395
+ * **`opaqueBlockTokens` on `createModelAwareTokenEstimator`** — a
396
+ configurable input-token surcharge for opaque (non-text) content blocks:
397
+ either a flat number per block, or `{ default?, byType? }` keyed by
398
+ `block.type`. Applies to blocks in `messages[].content` and `system`
399
+ arrays; validated at estimator creation. Without it, opaque blocks
400
+ contribute 0 input tokens (unchanged default) — an image-heavy request
401
+ estimates as nearly free, which is the wrong direction for admission
402
+ control. Malformed text blocks (`type: "text"` without a string `text`)
403
+ are treated as opaque, erring toward over-reservation.
404
+
405
+ * **Per-call reservation override** — `reservation?: TokenEstimate` on
406
+ `acquire()` / `run()` options and on `wouldAdmit()` options. When
407
+ provided with `tokenBudget` configured, admission reserves
408
+ `input + maxOutput` from the override verbatim and skips the estimator
409
+ for that call. Intended for gateways that already compute a more accurate
410
+ estimate from the full provider request than any character-ratio
411
+ estimator could. Validated as non-negative integers; ignored when
412
+ `tokenBudget` is not configured; not reflected by `estimate()`, which
413
+ always previews the estimator path.
414
+
415
+ ### Notes
416
+
417
+ * All changes are additive and backward compatible: requests without the
418
+ new fields, and estimators without the new option, behave exactly as in
419
+ 3.6.0. Requests that do carry `system` / `extraInputTokens` produce
420
+ different default deduplication keys than hand-rolled 3.6.0 projections
421
+ of the same prompt — as intended, since those fields now distinguish
422
+ requests.
423
+
424
+ ### Added
425
+
426
+ * **Exact reservation preview via `bulkhead.estimate(request)`.** The new
427
+ method runs the same estimator and validation path used by
428
+ `acquire()`, `run()`, and `wouldAdmit()`, returning
429
+ `{ input, maxOutput, reserved }` without acquiring capacity. It returns
430
+ `null` when token-budget admission is disabled. This gives gateways and
431
+ external capacity coordinators one authoritative reservation calculation
432
+ instead of forcing them to duplicate estimator logic.
433
+
434
+ * **Stable admission IDs.** Every successful admission now receives a
435
+ process-unique UUID exposed on the successful `acquire()` result,
436
+ `LLMToken`, `LLMRunContext`, and the `admit` / `release` lifecycle events.
437
+ Admission events also expose the resolved priority, and release events now
438
+ include the pre-release held-token count plus the final usage-event
439
+ sequence. These fields let gateways correlate HTTP requests, traces,
440
+ distributed leases, usage updates, and release records without maintaining
441
+ fragile side maps.
442
+
443
+ * **Ordered `usage` lifecycle events.** Effective cumulative
444
+ `reportUsage()` updates now emit an event containing the admission ID,
445
+ priority, monotonically increasing per-admission sequence, previous/current
446
+ hold, hold delta, cumulative usage, output-cap state, and over-reservation
447
+ status. Duplicate or stale reports that do not increase either cumulative
448
+ usage field are suppressed. Sequence numbers allow external coordinators to
449
+ reject duplicate or out-of-order updates safely. The returned `UsageReport`
450
+ now also includes `admissionId` and the current `sequence`, so a gateway can
451
+ await an external absolute-hold update before forwarding more streamed data.
452
+
453
+ ### Changed
454
+
455
+ * `LLMEventMap["admit"]` and `LLMEventMap["release"]` include additional
456
+ correlation and accounting fields. Existing listener behavior is unchanged;
457
+ the additions are backward-compatible for consumers that read only the
458
+ previous fields.
459
+
460
+ * `request.max_tokens` validation is centralized in the shared reservation
461
+ path, so `estimate()`, `wouldAdmit()`, `acquire()`, and `run()` now validate
462
+ it consistently even when a custom estimator ignores that field.
463
+
464
+ ---
465
+
466
+ ## [3.5.0] - 2026-07-19
467
+
468
+ ### Fixed
469
+
470
+ * **Deduplication no longer silently hands followers a single-consumer
471
+ result.** Dedup shares the leader's resolved value with every follower
472
+ by reference. For plain JSON results that is correct, but for streaming
473
+ results — `ReadableStream`, Node `Readable`, async iterables, `Response`
474
+ bodies — the shared object can only be consumed once: whichever caller
475
+ read first won, and the rest received a locked or drained stream, with
476
+ no error at the bulkhead. Followers whose shared result is detected as
477
+ single-consumer now reject with
478
+ `LLMBulkheadRejectedError("unshareable_result")` (new reject reason,
479
+ counted in `stats().llm.rejectedByReason` and emitted via the `reject`
480
+ event, without capacity detail — like other dedup-wait rejections).
481
+ The **leader is never affected** and always receives the original
482
+ result. Detection is deliberately shallow: only the result value itself
483
+ is inspected, so a stream nested inside a wrapper object is still
484
+ shared by reference as before.
485
+
486
+ ### Added
487
+
488
+ * **`deduplication.shareResult` fan-out hook.** Called once per follower
489
+ with the leader's resolved result; its return value is what that
490
+ follower receives. This is the seam for making streaming dedup
491
+ *work* rather than merely fail loudly — e.g.
492
+ `shareResult: (r) => (r as Response).clone()` for `fetch` responses, or
493
+ a tee/replay of your provider stream. When provided, the hook runs for
494
+ every follower delivery (safe results included) and the
495
+ single-consumer detection is bypassed — the hook owns fan-out policy.
496
+ A throwing hook rejects that follower with the thrown error as-is;
497
+ leader and other followers are unaffected.
498
+
499
+ * **Per-call `dedup: false` on `run()` options.** Opts a single call out
500
+ of deduplication entirely — it neither joins an existing in-flight
501
+ call nor registers as joinable. Intended for streaming routes on a
502
+ bulkhead where dedup is otherwise useful, replacing the previous
503
+ workaround of encoding exemptions in a bulkhead-wide `keyFn`.
504
+ `dedup: true` cannot enable deduplication when it is disabled at the
505
+ bulkhead level and is treated as omitted.
506
+
507
+ ---
508
+
509
+ ## [3.4.1] - 2026-07-18
510
+
511
+ > **Note:** This release is identical in content to what was intended to be
512
+ > published as `3.4.0`. That version was published to npm and then
513
+ > unpublished, and npm's registry policy prevents re-publishing a version
514
+ > number once it has been unpublished. This release republishes the same
515
+ > changes as `3.4.1`.
516
+
517
+ ### Changed
518
+
519
+
520
+ * **Default deduplication key now covers the entire request.** The old key
521
+ serialized only `{messages, max_tokens, model}`, silently conflating
522
+ requests that differed in any other field — identical messages with
523
+ `temperature: 0` vs `temperature: 1` shared one call, and the second
524
+ caller received a response generated under the first caller's parameters.
525
+ The default key is now a key-order-stable serialization of the whole
526
+ request object, so any own enumerable property difference prevents
527
+ conflation. Tradeoff: volatile per-request fields (request IDs,
528
+ timestamps) now also defeat deduplication — supply a custom `keyFn` that
529
+ omits them if your requests carry such fields. Missing a dedup
530
+ opportunity is cheap; serving a wrong-parameters response is a
531
+ correctness bug, so the default errs entirely toward non-conflation.
532
+ Dedup **hit rates may drop** for callers whose requests carry extra
533
+ fields; admission behavior is otherwise unchanged.
534
+
535
+ * **Dedup keys are SHA-256 hashed before storage.** The in-flight map
536
+ previously held full serialized prompt text as its keys — unbounded
537
+ per-entry key memory, and prompt content resident for the lifetime of
538
+ the entry. Keys are now hashed (scope + `\0` + raw key), bounding key
539
+ size and keeping prompt text out of the map. `keyFn` semantics are
540
+ unchanged: it still returns a plain string, and `""` still opts out.
541
+
542
+ * **Bulkhead-level `timeoutMs` no longer applies to dedup followers.**
543
+ `timeoutMs` is documented as a *queue-wait* timeout, but it was also
544
+ being applied to a follower's wait on an already-running shared call.
545
+ Under the `batch` profile (30s default), any LLM call slower than the
546
+ timeout caused every follower to reject with `"timeout"` while the
547
+ leader succeeded — defeating deduplication exactly when calls are long.
548
+ Followers are now capped only by their own `signal` and an *explicitly
549
+ passed* per-call `timeoutMs`. Callers who relied on the bulkhead
550
+ default bounding follower waits should pass `timeoutMs` per call.
551
+
552
+ * **`reportUsage()` after `release()` now reports `held: 0`.** The token's
553
+ internal hold counter was not zeroed at release, so post-release
554
+ snapshots reported the stale pre-release hold while
555
+ `stats().tokenBudget.inFlightTokens` correctly showed the tokens
556
+ returned. Budget accounting was always correct; only the snapshot lied.
557
+ `reserved` continues to report the historical pre-admission reservation.
558
+
559
+ ### Added
560
+
561
+ * **`dedupScope` option on `run()`.** Requests deduplicate only within the
562
+ same scope; different scopes never share an in-flight call even with
563
+ identical keys. Intended for multi-tenant gateways: the default key has
564
+ no tenant dimension, so without a scope (or a tenant-aware `keyFn`),
565
+ two tenants sending byte-identical requests would share one response.
566
+ Default: `""` (single global scope — prior behavior).
567
+
568
+ * Documented explicitly: deduplication applies to `run()` only;
569
+ `acquire()` never deduplicates. (Existing behavior, previously
570
+ undocumented.)
571
+
572
+ ---
573
+
574
+ ## [3.3.1] - 2026-07-17
575
+
576
+ ### Changed
577
+
578
+
579
+ * **`effectiveBudget("normal")` now clamps to `0` instead of going negative.**
580
+ Construction validates `0 <= highPriorityReserve <= budget` (a startup check
581
+ that catches config typos), but `setBudget()` does not re-run that
582
+ validation — a runtime budget update (e.g. driven by a lease-renewal
583
+ ledger) is trusted as-is, since rejecting the ledger's grant would be
584
+ incorrect. This means `currentBudget` can legitimately drop below
585
+ `highPriorityReserve` after `setBudget()`. Previously, the normal-priority
586
+ ceiling (`currentBudget - highPriorityReserve`) could go negative in that
587
+ state, which was surfaced as a negative `effectiveBudget`/`available` in
588
+ `stats()` and rejection `detail`. It is now `Math.max(0, currentBudget -
589
+ highPriorityReserve)`.
590
+ * **Behavioral consequence (unchanged, now made explicit):** when the
591
+ budget grant drops below the reserve, normal-priority requests are
592
+ fully rejected with `"budget_limit"` while `priority: "high"` requests
593
+ are still checked against the full (shrunk) `currentBudget` and can
594
+ keep admitting whatever capacity remains. This is the intended degraded
595
+ behavior — `highPriorityReserve` exists specifically to protect
596
+ interactive traffic when capacity is scarce, and capacity is never
597
+ scarcer than when the grant itself falls below the reserve.
598
+ * Admission decisions were already correct in this scenario (a negative
599
+ ceiling already rejected every normal-priority request); this change
600
+ only corrects the *reported* numbers (`stats().tokenBudget`, rejection
601
+ `detail.tokenBudget`) from negative to `0`.
602
+ * Construction-time validation (`highPriorityReserve <= budget`) is
603
+ unchanged.
604
+
605
+ ---
606
+
607
+
608
+ ## [3.3.0] - 2026-07-17
609
+
610
+ ### Changed
611
+
612
+ * **`tokenBudget.budget: 0` is now accepted at construction.** Previously,
613
+ `createLLMBulkhead({ tokenBudget: { budget: 0 } })` threw because `budget`
614
+ was validated as a positive integer. A budget of `0` is a legitimate state
615
+ — e.g. a lease ledger reporting pool exhaustion for the current cycle — and
616
+ the bulkhead now represents it as "reject all budget-gated admissions"
617
+ rather than an invalid configuration. `budget` is now validated as a
618
+ non-negative integer, matching the existing validation already used by
619
+ `setBudget()`. Admission behavior is unaffected for any `budget > 0`; a
620
+ `budget: 0` bulkhead rejects every admission that needs `> 0` tokens with
621
+ `"budget_limit"`, and admits requests whose estimator produces a `0`-token
622
+ reservation, consistent with `effectiveBudget()`/`tryReserveTokens()`
623
+ semantics already in place for runtime-lowered budgets.
624
+
625
+ ### Added
626
+
627
+ * **`bulkhead.setBudget(tokens)`** — mutate the token budget ceiling at
628
+ runtime. All admission math (`acquire`/`run`, `wouldAdmit`, rejection
629
+
630
+ `detail`, `stats()`) reads the ceiling dynamically, so a call to
631
+ `setBudget()` propagates immediately with no other behavioral changes.
632
+ * **Raising takes effect immediately** — the very next admission check
633
+ sees the new headroom.
634
+ * **Lowering below `inFlightTokens` is legal — shrink by attrition.**
635
+ No in-flight work is revoked or cancelled. New admissions reject with
636
+ `"budget_limit"` until enough in-flight work releases to bring
637
+ `inFlightTokens` back under the new ceiling. This is consistent with
638
+ the library's existing overrun tolerance (`inFlightTokens` can already
639
+ exceed `budget` via `reportUsage()` overrun) and is pinned with a
640
+ dedicated test.
641
+ * **Throws if `tokenBudget` was never configured** at construction — an
642
+ explicit error beats a silent no-op.
643
+ * **Validates `tokens`** as a non-negative integer (`0` is valid and
644
+ fully closes admission).
645
+
646
+ ### Notes
647
+
648
+ * Purely additive: existing `tokenBudget.budget` behavior is unchanged for
649
+ bulkheads that never call `setBudget()`.
650
+
651
+ ---
652
+
653
+ ## [3.2.0] - 2026-07-14
654
+
655
+
656
+ Gateway-readiness release. All changes are additive (semver-minor).
657
+
658
+ ### Added
659
+
660
+ * **`LLMToken.reportUsage(usage)` / run-context `ctx.reportUsage(usage)`** —
661
+ mid-flight cumulative usage reporting for streaming workloads.
662
+ * Input over-estimates are refunded to the budget immediately (the full
663
+ output reservation is retained until release).
664
+ * Consumption beyond the hold `expands it (overrun), which can push
665
+ `inFlightTokens` above `budget` and correctly blocks new admissions
666
+ until the overrunning request releases.
667
+ * Reports are clamped monotonically non-decreasing per field.
668
+ * `release()` without explicit usage falls back to the last reported
669
+ usage for the final refund.
670
+ * Returns a `UsageReport` snapshot (`reserved`, `held`, `consumed`,
671
+ `outputCap`, `outputRemaining`, `overReservation`).
672
+ * **Priority admission** — `tokenBudget.highPriorityReserve` plus per-call
673
+ `priority: "high" | "normal"` on `acquire()`/`run()`. Normal-priority
674
+ admission is checked against `budget - highPriorityReserve`; high-priority
675
+ against the full budget.
676
+ * **Rejection detail** — failed `acquire()` results, `reject` events, and
677
+ `LLMBulkheadRejectedError` now carry an optional `detail: LLMRejectDetail`
678
+ capacity snapshot (slots, queue, priority-adjusted budget numbers).
679
+ * **`wouldAdmit(request, { priority })`** — advisory, non-reserving dry-run
680
+ for routing decisions. Documented as racy.
681
+ * **Stats** — `tokenBudget.totalOverrun` and `tokenBudget.highPriorityReserve`.
682
+ * New exported types: `UsageReport`, ``LLMRunContext`, `LLMPriority`,
683
+ `LLMRejectDetail`, `LLMAcquireOptions`.
684
+
685
+ ### Changed
686
+
687
+ * `run()` callbacks now receive an optional second argument
688
+ (`LLMRunContext`). Existing single-argument callbacks are unaffected.
689
+ * Release-event semantics when `reportUsage()` was used: `refundedTokens`
690
+ on the `release` event reflects the refund *at release* (against the
691
+ current hold); early refunds from `reportUsage()` are already included
692
+ in `stats().tokenBudget.totalRefunded` as they occur. When
693
+ `reportUsage()` is never called, behavior is byte-identical to 3.1.x.
694
+
695
+ ### Notes
696
+
697
+ * Single-process by design: distributed budget coordination across replicas
698
+ is explicitly out of scope (see README "Scope note").
699
+ * Backward compatible: the full 3.1.x test suite passes unmodified.
700
+
701
+ ---
702
+
703
+ ## [3.1.2] — 2026-05-11
704
+ `
705
+ ### Fixed
706
+
707
+ * **Hardened token accounting input validation.** `tokenBudget.budget`, `tokenBudget.outputCap`, `request.max_tokens`, estimator output, and reported `TokenUsage` are now validated as finite non-negative integer token counts, with `tokenBudget.budget` required to be positive. Invalid usage passed to `release()` still releases capacity before surfacing the validation error.
708
+ * **Avoided duplicate estimator calls during admission.** Token reservation is now estimated once per acquisition attempt, then rechecked against the current budget after the underlying bulkhead slot is acquired.
709
+ * **Deduped caller cancellation.** Callers that join an existing in-flight deduplicated request now honor their own `AbortSignal` and `timeoutMs` while leaving the shared provider call running for other waiters.
710
+ * **CJS source maps after rename.** The CommonJS rename script now rewrites `sourceMappingURL` trailers and source map `file` fields from `.js` to `.cjs`.
711
+ * **Coverage setup.** Added the missing V8 coverage provider and a `test:coverage` script so `vitest run --coverage` works from a clean install.
712
+ * **Release checks.** Added stricter release scripts for lint, deterministic test runs, coverage, package smoke checks, and `npm pack --dry-run`.
713
+ * **Reduced build noise.** The CommonJS rename script no longer writes routine diagnostics during build or pack.
714
+ * **Security policy.** Updated supported versions to the current `3.x` line and removed the placeholder security email.
715
+ * **Deduplication docs.** Fixed the public JSDoc for the default deduplication key to include `model`, matching the implementation and README.
716
+
717
+ ### Tests
718
+
719
+ * Added coverage for invalid token options, invalid request `max_tokens`, invalid estimator output, invalid usage reporting, one-estimation-per-acquire behavior, deduped abort/timeout behavior, and packaged ESM/CJS smoke checks.
720
+
721
+ ### Notes
722
+
723
+ * Patch release: this is a hardening and packaging maintenance release. It rejects invalid numeric inputs that previously produced undefined or unsafe accounting states, but does not intentionally change supported valid API usage.
724
+
725
+ ---
726
+
727
+ ## [3.1.1] — 2026-05-06
728
+
729
+ ### Fixed
730
+
731
+ * **`createModelAwareTokenEstimator({ defaultModel })` typing.** The estimator factory now accepts an options object as the first argument when it includes `defaultModel`, matching external call-site expectations and avoiding the previous TypeScript error where `defaultModel` was interpreted as a numeric ratio override.
732
+
733
+ ### Notes
734
+
735
+ * Backward-compatible patch release. Existing `createModelAwareTokenEstimator(overrides, opts)` calls continue to work.
736
+ * Single-argument ratio overrides remain supported.
737
+ * No runtime changes to token estimation, admission, release, refund, deduplication, event, or shutdown semantics.
738
+
739
+ ---
740
+
741
+ ## [3.1.0] — 2026-04-26
742
+
743
+ ### Added
744
+
745
+ * **`stats().tokenBudget.totalReserved`** — cumulative tokens reserved at admission across all successful admissions. Monotonically increasing. Useful as the numerator companion to `inFlightTokens`/`available` for rate and saturation analysis over time.
746
+ * **`stats().tokenBudget.totalConsumed`** — cumulative actual tokens consumed (`usage.input + usage.output`), summed across releases that reported `TokenUsage` via `token.release(usage)` or `run({ getUsage })`. Releases without usage contribute 0 — `totalConsumed` is meaningful only when `getUsage` is wired up consistently. Not clamped: over-consumption (actual > reserved) is reported as-is.
747
+ When `getUsage` is wired consistently and no over-consumption occurs, the invariant `totalReserved == totalConsumed + totalRefunded` holds after all in-flight requests settle.
748
+
749
+ ### Changed
750
+
751
+ * No changes to admission, release, refund, deduplication, event, or shutdown semantics.
752
+ * **Documentation:** expanded the `release` event JSDoc to document the per-request consumption math (`usage ? usage.input + usage.output : null`) and the `null` vs `0` distinction for unreported usage. Pure docstring change — no API or behavior change.
753
+
754
+ ### Notes
755
+
756
+ * Strict superset of the existing `totalRefunded` field — no breaking changes.
757
+ * Both new fields are present whenever `tokenBudget` is configured (alongside `totalRefunded`); both are absent when `tokenBudget` is omitted.
758
+ * These counters are designed for the library's existing scope: saturation tracking, throughput analysis, and refund-efficiency tuning (e.g., `totalRefunded / totalReserved` to surface overly generous `max_tokens` settings).
759
+ * For accurate cost accounting, the `release` event remains the right primitive — it preserves the input/output split from `TokenUsage`, which `totalConsumed` collapses into a single sum. Token estimation in this library is approximate and intentionally suited to load-shedding, not finance-grade reconciliation.
760
+
761
+ ---
762
+
763
+ ## [3.0.0] — 2026-04-15
764
+
765
+ ### Breaking Changes
766
+
767
+ * **`LLMStats` shape changed.** `bulkhead.stats()` no longer returns base `Stats` fields at the top level.
768
+ Base bulkhead stats now live under `stats().bulkhead`, and LLM-layer counters now live under
769
+ `stats().llm`.
770
+ * Code that previously accessed:
771
+ * `stats().inFlight`
772
+ * `stats().pending`
773
+ * `stats().maxConcurrent`
774
+ * `stats().maxQueue`
775
+ * `stats().closed`
776
+
777
+ must now read:
778
+ * `stats().bulkhead.inFlight`
779
+ * `stats().bulkhead.pending`
780
+ * `stats().bulkhead.maxConcurrent`
781
+ * `stats().bulkhead.maxQueue`
782
+ * `stats().bulkhead.closed`
783
+
784
+ ### Added
785
+
786
+ * `stats().llm` block with LLM-layer request counters:
787
+ * `admitted`
788
+ * `released`
789
+ * `rejected`
790
+ * `rejectedByReason`
791
+
792
+ ### Changed
793
+
794
+ * The `run()` callback signal type now derives from `AcquireOptions["signal"]`
795
+ instead of referring to the global `AbortSignal` type directly.
796
+ * Test utilities now avoid direct dependency on ambient `AbortController` globals.
797
+ * Bumped `async-bulkhead-ts` to `^0.4.1`.
798
+
799
+ ### Migration Guide
800
+
801
+ **From v2 → v3, update stats access only.**
802
+
803
+ Before:
804
+
805
+ ```ts
806
+ const s = bulkhead.stats();
807
+ s.inFlight;
808
+ s.pending;
809
+ ```
810
+
811
+ After:
812
+
813
+ ```ts
814
+ const s = bulkhead.stats();
815
+ s.bulkhead.inFlight;
816
+ s.bulkhead.pending;
817
+ ```
818
+
819
+ LLM-layer counters are now separate:
820
+
821
+ ```ts
822
+ const s = bulkhead.stats();
823
+ s.llm.admitted;
824
+ s.llm.rejected;
825
+ s.llm.rejectedByReason.budget_limit;
826
+ ```
827
+
828
+ ### Notes
829
+
830
+ * No change to admission semantics, token budget semantics, deduplication behavior,
831
+ or graceful shutdown behavior.
832
+ * This release separates underlying bulkhead telemetry from LLM-layer request telemetry.
833
+
834
+ ---
835
+
836
+ ## [2.0.0] — 2026-03-03
837
+
838
+ ### Breaking Changes
839
+
840
+ * **Multimodal content:** `LLMMessage.content` is now `string | ContentBlock[]`. Plain strings remain valid — no changes required for text-only callers. Code that assumed `content` is always a `string` (e.g. `m.content.length`) must be updated to use `extractTextLength()` or handle both shapes.
841
+ * **Deduplication key:** the default key now includes `max_tokens` and `model` in addition to message content. Requests with identical messages but different `max_tokens` are no longer treated as duplicates (they were in v1). This is a behavioral change with no API signature change.
842
+ * **`LLMToken` replaces `Token`:** the token returned by `acquire()` now accepts optional `TokenUsage` at release time: `token.release(usage?)`. Callers that call `release()` with no arguments are unaffected.
843
+ * **`LLMStats.tokenBudget` shape:** added `totalRefunded` field to the token budget stats block.
844
+
845
+ ### Added
846
+
847
+ * **Token refund mechanism.** When `TokenUsage` is passed to `token.release(usage)` or extracted via `getUsage` in `run()`, the bulkhead returns the difference between the pre-admission reservation and actual consumption to the budget immediately. This dramatically improves budget utilization — requests that use fewer output tokens than `max_tokens` no longer hold phantom capacity.
848
+ * **`run()` `getUsage` option.** `run(request, fn, { getUsage })` accepts a function that extracts `TokenUsage` from the result of `fn`. The refund is applied automatically on successful completion.
849
+ * **Per-request model override.** `LLMRequest.model` is now an optional field. When present, the model-aware estimator uses it for ratio lookup instead of the bulkhead-level `defaultModel`. Supports A/B testing, canary deployments, and mixed-model routing.
850
+ * **Multimodal content blocks.** `LLMMessage.content` accepts `ContentBlock[]` with typed `TextContentBlock` and `OpaqueContentBlock` variants. Built-in estimators extract text from text blocks and ignore non-text blocks. `extractTextLength()` is exported as a utility.
851
+ * **Custom deduplication key.** `deduplication` now accepts `DeduplicationOptions` with a `keyFn` property. The default key function includes `messages`, `max_tokens`, and `model`. Return an empty string from `keyFn` to opt a specific request out of deduplication.
852
+ * **Event system.** `bulkhead.on(event, listener)` subscribes to lifecycle events: `'admit'`, `'reject'`, `'release'`, `'dedup'`. Returns an unsubscribe function. Listeners are called synchronously; exceptions are silently caught.
853
+ * **Graceful shutdown.** `bulkhead.close()` stops admission permanently. `bulkhead.drain()` returns a promise that resolves when all in-flight work completes. Compose as `close()` → `drain()` for clean shutdown. Both are forwarded from `async-bulkhead-ts`.
854
+ * **Expanded model ratios.** Built-in ratio table now includes: `claude-haiku-4`, `claude-sonnet-4-5`, `claude-opus-4-5`, `claude-haiku-4-5`, `gpt-4.1`, `o4-mini`, `gemini-2.5`.
855
+ * **`LLMStats.tokenBudget.totalRefunded`** — cumulative tokens returned to the budget via the refund mechanism.
856
+
857
+ ### Changed
858
+
859
+ * `createModelAwareTokenEstimator` now checks `request.model` before `defaultModel` for ratio lookup.
860
+ * Default deduplication key includes `max_tokens` and `model` (see Breaking Changes).
861
+ * Prefix matching in the estimator now uses an iterative longest-match scan instead of `filter + sort`, avoiding an allocation per call.
862
+ * `LLMBulkhead` return type now includes `close`, `drain`, and `on` methods.
863
+
864
+ ### Removed
865
+
866
+ * Nothing removed. All v1 public types remain exported.
867
+
868
+ ### Migration Guide
869
+
870
+ **From v1 → v2, most callers need zero changes.** The common path — `createLLMBulkhead(opts)` → `bulkhead.run(request, fn)` — is fully backward-compatible for text-only requests.
871
+
872
+ Changes required only if you:
873
+
874
+ 1. **Access `content` directly on `LLMMessage`:** replace `m.content.length` with `extractTextLength(m.content)` or guard with `typeof m.content === 'string'`.
875
+ 2. **Rely on dedup treating different `max_tokens` as identical:** pass a custom `keyFn` that omits `max_tokens`: `deduplication: { keyFn: (r) => JSON.stringify(r.messages) }`.
876
+ 3. **Inspect `tokenBudget` stats structurally:** the new `totalRefunded` field is always present when `tokenBudget` is configured.
877
+
878
+ ### Design Notes
879
+
880
+ * Token refund is opt-in and zero-cost when not used. Calling `release()` with no argument behaves identically to v1.
881
+ * `getUsage` is intentionally separated from `fn` to avoid coupling the LLM call signature to the bulkhead. The caller extracts usage from whatever their provider returns.
882
+ * The event system is deliberately minimal — synchronous, fire-and-forget, no async listeners. It's designed for metrics counters and logging, not for control flow.
883
+ * `close()` and `drain()` are thin forwards to `async-bulkhead-ts`. The LLM layer adds no new shutdown semantics — it inherits the base library's guarantees.
884
+ * Multimodal estimation is intentionally conservative. Non-text blocks contribute zero to the estimate. Callers who need accurate multimodal estimation should provide a custom `estimator`.
885
+
886
+ ---
887
+
888
+ ## [1.0.3] — 2026-02-26
889
+
890
+ ### Changed
891
+
892
+ * Aligned package.json license field with the repository license (Apache-2.0)
893
+ * No runtime, API, or type changes
894
+
895
+ ### Notes
896
+
897
+ * Metadata-only correction
898
+ * Fully compatible with 1.0.0–1.0.2
899
+ * Safe upgrade
900
+
901
+ ---
902
+
903
+ ## [1.0.2] — 2026-02-26
904
+
905
+ ### Changed
906
+
907
+ * Corrected GitHub URLs in `package.json` (homepage, repository, bugs) to point to the canonical repository
908
+ * No runtime, API, or type changes
909
+
910
+ ### Notes
911
+
912
+ * Packaging outputs (ESM, CJS, types) unchanged
913
+ * Fully compatible with `1.0.0` and `1.0.1`
914
+ * Safe upgrade — metadata-only correction
915
+
916
+ ---
917
+
918
+ ## [1.0.1] — 2026-02-26
919
+
920
+ ### Changed
921
+
922
+ * Bumped `async-bulkhead-ts` to `^0.3.0`
923
+
924
+ ### Notes
925
+
926
+ * No API changes
927
+ * No functional behavior changes in `async-bulkhead-llm`
928
+
929
+ ---
930
+
931
+ ## [1.0.0] — 2026-02-24
932
+
933
+ ### Added
934
+
935
+ * Initial release of **async-bulkhead-llm**
936
+ * `createLLMBulkhead(options)` — fail-fast admission control for LLM workloads, wrapping `async-bulkhead-ts`
937
+ * `model` required at construction time — one bulkhead per model is the enforced deployment pattern
938
+ * `profile` option — `'interactive'` (fail-fast, default) and `'batch'` (bounded queue, 30s timeout) presets; escape hatch via plain `LLMBulkheadPreset` object; explicit options always override preset defaults
939
+ * Token-aware admission via `tokenBudget` — reserves `input + maxOutput` tokens pre-admission; fail-fast when the budget ceiling is hit, independent of concurrency headroom and profile
940
+ * `naiveTokenEstimator` — flat 4.0 character-per-token ratio; zero configuration; suitable for load-shedding
941
+ * `createModelAwareTokenEstimator` — per-model character ratios for known model families across Anthropic, OpenAI, and Google; longest-prefix match; exact caller overrides checked before prefix scan; `onUnknownModel` hook; falls back to 4.0 ratio for unknown models
942
+ * In-flight request deduplication via `deduplication: true` — identical requests (keyed on `JSON.stringify(messages)`) share one in-flight LLM call; dedup hits tracked in `stats()`
943
+ * `bulkhead.run(request, fn, options?)` — primary API; acquire + release handled automatically; throws `LLMBulkheadRejectedError` on rejection
944
+ * `bulkhead.acquire(request, options?)` — manual acquire / release for advanced control flow; returns typed result object
945
+ * `LLMBulkheadRejectedError` — typed error with `code: 'LLM_BULKHEAD_REJECTED'` and `reason: LLMRejectReason`
946
+ * `LLMRejectReason` — extends base `RejectReason` from `async-bulkhead-ts` with `'budget_limit'`
947
+ * `TokenUsage` type — exported as a forward-looking type for v2 refund support; not acted on in v1
948
+ * `bulkhead.stats()` — returns `LLMStats` extending the base `Stats` type with optional `tokenBudget` and `deduplication` blocks; optional blocks are absent when the feature is disabled
949
+ * `PROFILES` exported — named presets available for direct inspection and composition
950
+ * AbortSignal and `timeoutMs` cancellation — threaded through to `fn` via `run()`; waiting-only timeout semantics inherited from `async-bulkhead-ts`
951
+ * ESM and CommonJS builds
952
+ * Full TypeScript typings
953
+ * Vitest test suite covering estimation, admission, token budget, deduplication, cancellation, profile resolution, and a 4-second soak test validating all invariants under churn
954
+
955
+ ### Design Notes
956
+
957
+ * Fail-fast is the opinionated default — `maxQueue: 0` unless overridden via `profile` or explicit option
958
+ * Token budget admission is always fail-fast, independent of queue configuration — budget is a cost ceiling, not a scheduling constraint
959
+ * One bulkhead per model is enforced by design; `model` is a required constructor argument and does not appear on `LLMRequest`; multi-model routing is documented as a README recipe
960
+ * Token estimation is intentionally approximate — suitable for load-shedding, not cost accounting
961
+ * Refund mechanism (correcting reservations against actual post-call usage) is deferred to v2; `TokenUsage` type is exported now to allow call sites to be written correctly ahead of v2
962
+ * Multimodal content (images, structured blocks) is a known v1 limitation — `content` must be a plain string; estimators ignore non-string content; documented on `LLMRequest`
963
+ * Deduplication key is `JSON.stringify(messages)` in v1 — requests with identical messages but different `max_tokens` are treated as duplicates; key design improvements deferred to v2
964
+ * `tryAcquire()` from the base library is not exposed — synchronous non-blocking admission is not meaningful for LLM workloads where token budget requires the full request object
965
+ * Zero dependencies beyond `async-bulkhead-ts`
966
+
967
+ ---