async-bulkhead-llm 1.0.3 → 2.0.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
@@ -10,10 +10,16 @@ Designed for services that need to enforce **cost ceilings, concurrency limits,
10
10
 
11
11
  - ✅ Hard **max in-flight** concurrency (`maxConcurrent`)
12
12
  - ✅ **Token-aware admission** — reserves against estimated input + max output tokens
13
+ - ✅ **Token refund** — reclaim unused budget capacity from actual usage post-completion
13
14
  - ✅ **Model-aware estimation** — per-model character ratios for known providers
15
+ - ✅ **Per-request model** — mixed-model routing through a single bulkhead
16
+ - ✅ **Multimodal content** — text blocks counted, non-text blocks ignored
14
17
  - ✅ **Fail-fast by default** — shed load early, never silently queue
15
18
  - ✅ **Opinionated profiles** — `'interactive'` and `'batch'` presets with escape hatch
16
19
  - ✅ **In-flight deduplication** — identical requests share one LLM call
20
+ - ✅ **Custom dedup key** — bring your own equivalence function
21
+ - ✅ **Event hooks** — `on('admit' | 'reject' | 'release' | 'dedup', fn)`
22
+ - ✅ **Graceful shutdown** — `close()` + `drain()`
17
23
  - ✅ Optional **AbortSignal** and **timeout** cancellation
18
24
  - ✅ `bulkhead.run(request, fn)` — acquire + release handled automatically
19
25
  - ✅ Zero dependencies beyond `async-bulkhead-ts`
@@ -51,8 +57,6 @@ const request = {
51
57
  max_tokens: 1024,
52
58
  };
53
59
 
54
- // Acquire + release handled automatically.
55
- // Throws LLMBulkheadRejectedError on rejection.
56
60
  const result = await bulkhead.run(request, async () => {
57
61
  return callYourLLMProvider(request);
58
62
  });
@@ -60,6 +64,120 @@ const result = await bulkhead.run(request, async () => {
60
64
 
61
65
  ---
62
66
 
67
+ ## What's New in v2
68
+
69
+ ### Token Refund
70
+
71
+ v1 reserved `input + maxOutput` tokens and held that full reservation until release. Most calls use far fewer output tokens than `max_tokens`. v2 reclaims the difference:
72
+
73
+ ```ts
74
+ // Via run() — extract usage from your provider's response
75
+ const result = await bulkhead.run(
76
+ request,
77
+ async () => callLLM(request),
78
+ {
79
+ getUsage: (response) => ({
80
+ input: response.usage.input_tokens,
81
+ output: response.usage.output_tokens,
82
+ }),
83
+ },
84
+ );
85
+
86
+ // Via acquire() — pass usage at release time
87
+ const r = await bulkhead.acquire(request);
88
+ if (r.ok) {
89
+ try {
90
+ const response = await callLLM(request);
91
+ return response;
92
+ } finally {
93
+ r.token.release({
94
+ input: response.usage.input_tokens,
95
+ output: response.usage.output_tokens,
96
+ });
97
+ }
98
+ }
99
+ ```
100
+
101
+ When usage is reported, the refund is `reserved - (actual input + actual output)`. Budget capacity is returned immediately. Without usage, behavior is identical to v1.
102
+
103
+ ### Multimodal Content
104
+
105
+ `content` may now be a plain string or an array of content blocks:
106
+
107
+ ```ts
108
+ const request = {
109
+ messages: [{
110
+ role: 'user',
111
+ content: [
112
+ { type: 'text', text: 'Describe this image...' },
113
+ { type: 'image', source: { type: 'base64', data: '...' } },
114
+ ],
115
+ }],
116
+ max_tokens: 1024,
117
+ };
118
+ ```
119
+
120
+ Built-in estimators extract text from text blocks and ignore non-text blocks. Token estimates for multimodal requests are a lower bound. Provide a custom `estimator` for accurate multimodal estimation.
121
+
122
+ ### Per-Request Model
123
+
124
+ Route multiple models through a single bulkhead with accurate per-model estimation:
125
+
126
+ ```ts
127
+ const bulkhead = createLLMBulkhead({
128
+ model: 'claude-sonnet-4', // default for estimation
129
+ maxConcurrent: 20,
130
+ tokenBudget: { budget: 500_000 },
131
+ });
132
+
133
+ // Estimator uses request.model when present
134
+ await bulkhead.run(
135
+ { model: 'claude-haiku-4-5', messages, max_tokens: 512 },
136
+ async () => callLLM(request),
137
+ );
138
+ ```
139
+
140
+ ### Custom Dedup Key
141
+
142
+ ```ts
143
+ const bulkhead = createLLMBulkhead({
144
+ model: 'claude-sonnet-4',
145
+ maxConcurrent: 10,
146
+ deduplication: {
147
+ keyFn: (request) => {
148
+ // Your own equivalence logic
149
+ return hash(request.messages);
150
+ },
151
+ },
152
+ });
153
+ ```
154
+
155
+ The default key now includes `messages`, `max_tokens`, and `model`. Return an empty string to opt a specific request out.
156
+
157
+ ### Event Hooks
158
+
159
+ ```ts
160
+ const off = bulkhead.on('release', ({ reservedTokens, refundedTokens, usage }) => {
161
+ metrics.histogram('llm.tokens.reserved', reservedTokens);
162
+ metrics.histogram('llm.tokens.refunded', refundedTokens);
163
+ });
164
+
165
+ // Later:
166
+ off(); // unsubscribe
167
+ ```
168
+
169
+ Events: `'admit'`, `'reject'`, `'release'`, `'dedup'`.
170
+
171
+ ### Graceful Shutdown
172
+
173
+ ```ts
174
+ // In your SIGTERM handler:
175
+ bulkhead.close(); // reject all pending; block future admission
176
+ await bulkhead.drain(); // wait for in-flight work to complete
177
+ ```
178
+
179
+ ---
180
+
63
181
  ## Profiles
64
182
 
65
183
  Two built-in presets cover the common cases. Explicit options always override preset defaults.
@@ -69,17 +187,17 @@ Two built-in presets cover the common cases. Explicit options always override pr
69
187
  const bulkhead = createLLMBulkhead({
70
188
  model: 'claude-sonnet-4',
71
189
  maxConcurrent: 10,
72
- profile: 'interactive', // maxQueue: 0
190
+ profile: 'interactive',
73
191
  });
74
192
 
75
193
  // Batch — bounded queue, 30s timeout
76
194
  const bulkhead = createLLMBulkhead({
77
195
  model: 'claude-sonnet-4',
78
196
  maxConcurrent: 4,
79
- profile: 'batch', // maxQueue: 20, timeoutMs: 30_000
197
+ profile: 'batch',
80
198
  });
81
199
 
82
- // Escape hatch — plain object, same shape as the options
200
+ // Escape hatch — plain object
83
201
  const bulkhead = createLLMBulkhead({
84
202
  model: 'claude-sonnet-4',
85
203
  maxConcurrent: 4,
@@ -87,39 +205,31 @@ const bulkhead = createLLMBulkhead({
87
205
  });
88
206
  ```
89
207
 
90
- If no profile is set, the default is fail-fast (`maxQueue: 0`).
91
-
92
208
  ---
93
209
 
94
210
  ## Token Budget
95
211
 
96
- Enforce a ceiling on total tokens in-flight simultaneously. Admission is always **fail-fast** when the ceiling is hit, regardless of profile or concurrency headroom.
97
-
98
212
  ```ts
99
213
  const bulkhead = createLLMBulkhead({
100
214
  model: 'claude-sonnet-4',
101
215
  maxConcurrent: 10,
102
216
  tokenBudget: {
103
- budget: 200_000, // max tokens in-flight at once
217
+ budget: 200_000,
104
218
  },
105
219
  });
106
220
  ```
107
221
 
108
- Token reservations are calculated pre-admission from `input + maxOutput`. Capacity is returned when each request completes.
222
+ Token reservations are calculated pre-admission from `input + maxOutput`. Capacity is returned when each request completes. When `TokenUsage` is provided at release, the refund reclaims unused capacity immediately.
109
223
 
110
- ### How estimation works
224
+ ### How Estimation Works
111
225
 
112
226
  The default estimator is `createModelAwareTokenEstimator` seeded with the bulkhead's `model`. It uses per-model character-to-token ratios for known model families, falling back to a flat `4.0` ratio for unknown models.
113
227
 
114
- Known model families: `claude-3-5-haiku`, `claude-3-5-sonnet`, `claude-3-*`, `claude-sonnet-4`, `claude-opus-4`, `gpt-4o`, `gpt-4-turbo`, `gpt-4`, `gpt-3.5`, `o1`, `o3`, `gemini-1.5`, `gemini-2`.
228
+ v2 checks `request.model` first (when present), then falls back to the bulkhead-level `defaultModel`.
115
229
 
116
- **Accuracy:** ±15% for known models on English prose. Underestimates for code and non-Latin scripts.
117
- **Suitable for:** load-shedding and cost ceilings.
118
- **Not suitable for:** cost accounting or billing.
230
+ Known model families: `claude-3-5-haiku`, `claude-3-5-sonnet`, `claude-3-*`, `claude-sonnet-4`, `claude-opus-4`, `claude-haiku-4`, `claude-*-4-5`, `gpt-4o`, `gpt-4-turbo`, `gpt-4.1`, `gpt-4`, `gpt-3.5`, `o1`, `o3`, `o4-mini`, `gemini-1.5`, `gemini-2`, `gemini-2.5`.
119
231
 
120
- ### Custom estimator
121
-
122
- Bring your own for higher accuracy, or to support Azure deployment names and other non-standard model strings:
232
+ ### Custom Estimator
123
233
 
124
234
  ```ts
125
235
  import { Tiktoken } from 'tiktoken';
@@ -132,42 +242,47 @@ const bulkhead = createLLMBulkhead({
132
242
  tokenBudget: {
133
243
  budget: 200_000,
134
244
  estimator: (request) => ({
135
- input: enc.encode(request.messages.map(m => m.content).join('')).length,
245
+ input: enc.encode(request.messages.map(m =>
246
+ typeof m.content === 'string'
247
+ ? m.content
248
+ : m.content.filter(b => b.type === 'text').map(b => b.text).join('')
249
+ ).join('')).length,
136
250
  maxOutput: request.max_tokens ?? 2_048,
137
251
  }),
138
252
  },
139
253
  });
140
254
  ```
141
255
 
142
- ### Estimator utilities
143
-
144
- Both estimators are exported for use outside the bulkhead — in logging, pre-flight checks, or request routing:
256
+ ### Estimator Utilities
145
257
 
146
258
  ```ts
147
- import { naiveTokenEstimator, createModelAwareTokenEstimator } from 'async-bulkhead-llm';
259
+ import {
260
+ naiveTokenEstimator,
261
+ createModelAwareTokenEstimator,
262
+ extractTextLength,
263
+ } from 'async-bulkhead-llm';
148
264
 
149
- // Flat 4.0 ratio, zero configuration
265
+ // Flat 4.0 ratio, multimodal-safe
150
266
  const est1 = naiveTokenEstimator(request);
151
267
 
152
- // Per-model ratios, optional override map
268
+ // Per-model ratios
153
269
  const estimate = createModelAwareTokenEstimator(
154
- { 'my-azure-deployment': 3.7 }, // exact overrides
270
+ { 'my-azure-deployment': 3.7 },
155
271
  {
156
272
  defaultModel: 'claude-sonnet-4',
157
273
  outputCap: 2_048,
158
274
  onUnknownModel: (model) => console.warn(`Unknown model: ${model}`),
159
275
  },
160
276
  );
161
- ```
162
277
 
163
- `onUnknownModel` fires when neither an override nor a built-in prefix matches. Use it to log, alert, or throw in strict environments.
278
+ // Utility for multimodal content
279
+ const charCount = extractTextLength(message.content);
280
+ ```
164
281
 
165
282
  ---
166
283
 
167
284
  ## Deduplication
168
285
 
169
- When enabled, requests with identical message content that arrive while a matching call is already in-flight share that call — only one LLM request is made.
170
-
171
286
  ```ts
172
287
  const bulkhead = createLLMBulkhead({
173
288
  model: 'claude-sonnet-4',
@@ -175,28 +290,28 @@ const bulkhead = createLLMBulkhead({
175
290
  deduplication: true,
176
291
  });
177
292
 
178
- // Both callers get the same result; only one LLM call is made.
179
293
  const [r1, r2] = await Promise.all([
180
294
  bulkhead.run(request, async () => callLLM(request)),
181
295
  bulkhead.run(request, async () => callLLM(request)), // deduped
182
296
  ]);
183
297
  ```
184
298
 
185
- **v1 key:** `JSON.stringify(request.messages)`. Requests with different `max_tokens` but identical messages are treated as duplicates. Key design is a known limitation in v1.
299
+ v2 default key: `JSON.stringify({ m: request.messages, t: request.max_tokens, o: request.model })`. Requests with different `max_tokens` or `model` are not conflated.
186
300
 
187
- Deduplication stats are tracked:
301
+ Custom key:
188
302
 
189
303
  ```ts
190
- bulkhead.stats().deduplication
191
- // { active: 2, hits: 5 }
304
+ deduplication: {
305
+ keyFn: (request) => myHash(request.messages),
306
+ }
192
307
  ```
193
308
 
309
+ Return `""` from `keyFn` to opt a specific request out.
310
+
194
311
  ---
195
312
 
196
313
  ## Cancellation
197
314
 
198
- Cancel waiting or in-flight requests with an `AbortSignal`:
199
-
200
315
  ```ts
201
316
  const ac = new AbortController();
202
317
 
@@ -206,51 +321,44 @@ await bulkhead.run(
206
321
  { signal: ac.signal },
207
322
  );
208
323
 
209
- // Somewhere else:
210
- ac.abort(); // cancels if still waiting; signals fn if already in-flight
324
+ ac.abort();
211
325
  ```
212
326
 
213
- The signal is passed through to your function. The bulkhead does not forcibly terminate in-flight work — your function is responsible for observing the signal.
214
-
215
- Bound waiting time independently with `timeoutMs`:
327
+ Bound waiting time:
216
328
 
217
329
  ```ts
218
330
  await bulkhead.run(request, async () => callLLM(request), { timeoutMs: 5_000 });
219
331
  ```
220
332
 
221
- `timeoutMs` applies to the waiting period only. It has no effect when `maxQueue` is 0.
222
-
223
333
  ---
224
334
 
225
335
  ## Manual Acquire / Release
226
336
 
227
- For cases where `run()` doesn't fit your control flow:
228
-
229
337
  ```ts
230
338
  const r = await bulkhead.acquire(request);
231
339
 
232
340
  if (!r.ok) {
233
- // r.reason: 'concurrency_limit' | 'queue_limit' | 'budget_limit' | 'timeout' | 'aborted'
341
+ // r.reason: 'concurrency_limit' | 'queue_limit' | 'budget_limit'
342
+ // | 'timeout' | 'aborted' | 'shutdown'
234
343
  return respond503(r.reason);
235
344
  }
236
345
 
237
346
  try {
238
- return await callLLM(request);
347
+ const response = await callLLM(request);
348
+ return response;
239
349
  } finally {
240
- r.token.release();
350
+ // v2: pass usage for refund
351
+ r.token.release({
352
+ input: response.usage.input_tokens,
353
+ output: response.usage.output_tokens,
354
+ });
241
355
  }
242
356
  ```
243
357
 
244
- You must call `token.release()` exactly once if acquisition succeeds.
245
-
246
- > **v1 note:** Token budget reservations are not correctable after admission when using `acquire()` directly — the refund mechanism (adjusting reservations based on actual usage) is deferred to v2. For accurate budget accounting, prefer `run()`.
247
-
248
358
  ---
249
359
 
250
360
  ## Handling Rejections
251
361
 
252
- `run()` throws `LLMBulkheadRejectedError` on rejection:
253
-
254
362
  ```ts
255
363
  import { LLMBulkheadRejectedError } from 'async-bulkhead-llm';
256
364
 
@@ -258,17 +366,14 @@ try {
258
366
  await bulkhead.run(request, async () => callLLM(request));
259
367
  } catch (err) {
260
368
  if (err instanceof LLMBulkheadRejectedError) {
261
- // err.code === 'LLM_BULKHEAD_REJECTED'
262
- // err.reason === 'concurrency_limit' | 'queue_limit' | 'budget_limit'
263
- // | 'timeout' | 'aborted'
369
+ // err.reason: 'concurrency_limit' | 'queue_limit' | 'budget_limit'
370
+ // | 'timeout' | 'aborted' | 'shutdown'
264
371
  return respond503(`Shed: ${err.reason}`);
265
372
  }
266
373
  throw err;
267
374
  }
268
375
  ```
269
376
 
270
- `acquire()` returns a result object instead of throwing — check `r.ok` before using the token.
271
-
272
377
  ---
273
378
 
274
379
  ## Stats
@@ -276,49 +381,55 @@ try {
276
381
  ```ts
277
382
  const s = bulkhead.stats();
278
383
 
279
- s.inFlight // requests currently executing
280
- s.pending // requests waiting in queue
281
- s.maxConcurrent // configured limit
282
- s.maxQueue // configured queue depth
384
+ s.inFlight
385
+ s.pending
386
+ s.maxConcurrent
387
+ s.maxQueue
388
+ s.closed // true after close()
283
389
 
284
- // Present only when tokenBudget is configured:
285
- s.tokenBudget?.budget // total ceiling
286
- s.tokenBudget?.inFlightTokens // currently reserved
287
- s.tokenBudget?.available // remaining headroom
390
+ s.tokenBudget?.budget
391
+ s.tokenBudget?.inFlightTokens
392
+ s.tokenBudget?.available
393
+ s.tokenBudget?.totalRefunded // v2: cumulative refunded tokens
288
394
 
289
- // Present only when deduplication is enabled:
290
- s.deduplication?.active // distinct in-flight keys
291
- s.deduplication?.hits // cumulative dedup hits
395
+ s.deduplication?.active
396
+ s.deduplication?.hits
292
397
  ```
293
398
 
294
399
  ---
295
400
 
296
- ## Multi-Model Routing
401
+ ## Event Hooks
297
402
 
298
- One bulkhead per model is the recommended pattern. Different models have different cost profiles, latency characteristics, and provider rate limits — a unified ceiling can't express those correctly.
403
+ ```ts
404
+ // Subscribe
405
+ const off = bulkhead.on('admit', ({ request, reservedTokens }) => {
406
+ console.log(`Admitted: ${reservedTokens} tokens reserved`);
407
+ });
299
408
 
300
- For fallback routing, A/B testing, or canary deployments, compose multiple bulkheads with a thin routing layer:
409
+ // Unsubscribe
410
+ off();
411
+ ```
301
412
 
302
- ```ts
303
- const bulkheads = {
304
- sonnet: createLLMBulkhead({ model: 'claude-sonnet-4', maxConcurrent: 10 }),
305
- haiku: createLLMBulkhead({ model: 'claude-haiku-3', maxConcurrent: 40 }),
306
- };
413
+ | Event | Payload |
414
+ |-----------|---------|
415
+ | `admit` | `{ request, reservedTokens }` |
416
+ | `reject` | `{ request, reason }` |
417
+ | `release` | `{ request, reservedTokens, refundedTokens, usage? }` |
418
+ | `dedup` | `{ request }` |
307
419
 
308
- async function callWithFallback(request, isPriority: boolean) {
309
- const bulkhead = isPriority ? bulkheads.sonnet : bulkheads.haiku;
310
- try {
311
- return await bulkhead.run(request, () => callLLM(request));
312
- } catch (err) {
313
- if (err instanceof LLMBulkheadRejectedError && !isPriority) {
314
- // Haiku is saturated — shed rather than escalate to Sonnet.
315
- throw err;
316
- }
317
- throw err;
318
- }
319
- }
420
+ Listeners are synchronous and fire-and-forget. Exceptions are silently caught.
421
+
422
+ ---
423
+
424
+ ## Graceful Shutdown
425
+
426
+ ```ts
427
+ bulkhead.close(); // stop admission, reject pending waiters
428
+ await bulkhead.drain(); // wait for in-flight work to finish
320
429
  ```
321
430
 
431
+ `close()` is synchronous, idempotent, and irreversible. `drain()` resolves when `inFlight` and `pending` both reach zero.
432
+
322
433
  ---
323
434
 
324
435
  ## API Reference
@@ -327,84 +438,79 @@ async function callWithFallback(request, isPriority: boolean) {
327
438
 
328
439
  ```ts
329
440
  type LLMBulkheadOptions = {
330
- model: string; // required; one bulkhead per model
331
- maxConcurrent: number; // required
332
- maxQueue?: number; // default: 0 (fail-fast)
333
- timeoutMs?: number; // waiting timeout; no effect if maxQueue is 0
334
- profile?: 'interactive' // maxQueue: 0 (default behaviour)
335
- | 'batch' // maxQueue: 20, timeoutMs: 30_000
336
- | LLMBulkheadPreset; // escape hatch: plain options object
441
+ model: string;
442
+ maxConcurrent: number;
443
+ maxQueue?: number;
444
+ timeoutMs?: number;
445
+ profile?: 'interactive' | 'batch' | LLMBulkheadPreset;
337
446
  tokenBudget?: {
338
447
  budget: number;
339
- estimator?: TokenEstimator; // default: createModelAwareTokenEstimator
340
- outputCap?: number; // default: 2048
448
+ estimator?: TokenEstimator;
449
+ outputCap?: number;
341
450
  };
342
- deduplication?: boolean; // default: false
451
+ deduplication?: boolean | DeduplicationOptions;
343
452
  };
344
- ```
345
453
 
346
- Explicit options always override profile defaults.
454
+ type DeduplicationOptions = {
455
+ keyFn?: (request: LLMRequest) => string;
456
+ };
457
+ ```
347
458
 
348
459
  ### `bulkhead.run(request, fn, options?)`
349
460
 
350
- Primary API. Acquires a slot, calls `fn`, releases on completion or error.
351
-
352
461
  ```ts
353
462
  run<T>(
354
463
  request: LLMRequest,
355
464
  fn: (signal?: AbortSignal) => Promise<T>,
356
- options?: { signal?: AbortSignal; timeoutMs?: number },
465
+ options?: {
466
+ signal?: AbortSignal;
467
+ timeoutMs?: number;
468
+ getUsage?: (result: T) => TokenUsage | undefined;
469
+ },
357
470
  ): Promise<T>
358
471
  ```
359
472
 
360
- Throws `LLMBulkheadRejectedError` on rejection.
361
-
362
473
  ### `bulkhead.acquire(request, options?)`
363
474
 
364
- Advanced. Returns a result object; you manage the token lifecycle.
365
-
366
475
  ```ts
367
476
  acquire(
368
477
  request: LLMRequest,
369
478
  options?: { signal?: AbortSignal; timeoutMs?: number },
370
- ): Promise<
371
- | { ok: true; token: { release(): void } }
372
- | { ok: false; reason: LLMRejectReason }
373
- >
374
- ```
479
+ ): Promise<LLMAcquireResult>
375
480
 
376
- ### `bulkhead.stats()`
481
+ type LLMAcquireResult =
482
+ | { ok: true; token: LLMToken }
483
+ | { ok: false; reason: LLMRejectReason };
377
484
 
378
- Returns current runtime state. See [Stats](#stats) above.
485
+ type LLMToken = { release(usage?: TokenUsage): void };
486
+ ```
379
487
 
380
- ### `naiveTokenEstimator(request)`
488
+ ### `bulkhead.stats()`
381
489
 
382
- Plain function. Flat `4.0` character-per-token ratio. No configuration.
490
+ ### `bulkhead.close()`
383
491
 
384
- ### `createModelAwareTokenEstimator(overrides?, options?)`
492
+ ### `bulkhead.drain()`
385
493
 
386
- Factory. Per-model ratios, longest-prefix match, exact overrides checked first.
494
+ ### `bulkhead.on(event, listener)`
387
495
 
388
496
  ```ts
389
- createModelAwareTokenEstimator(
390
- overrides?: Record<string, number>, // exact-match; caller values win
391
- options?: {
392
- defaultModel?: string;
393
- outputCap?: number;
394
- onUnknownModel?: (model: string) => void;
395
- },
396
- ): TokenEstimator
497
+ on<K extends keyof LLMEventMap>(
498
+ event: K,
499
+ listener: (payload: LLMEventMap[K]) => void,
500
+ ): () => void // returns unsubscribe
397
501
  ```
398
502
 
399
503
  ### Types
400
504
 
401
505
  ```ts
402
- type LLMRequest = { messages: LLMMessage[]; max_tokens?: number };
403
- type LLMMessage = { role: string; content: string };
506
+ type LLMRequest = { model?: string; messages: LLMMessage[]; max_tokens?: number };
507
+ type LLMMessage = { role: string; content: string | ContentBlock[] };
508
+ type ContentBlock = TextContentBlock | OpaqueContentBlock;
509
+ type TextContentBlock = { type: 'text'; text: string };
510
+ type OpaqueContentBlock = { type: string; [key: string]: unknown };
511
+
404
512
  type TokenEstimate = { input: number; maxOutput: number };
405
513
  type TokenEstimator = (request: LLMRequest) => TokenEstimate;
406
-
407
- // Forward-looking: not acted on in v1, useful for annotating provider responses.
408
514
  type TokenUsage = { input: number; output: number };
409
515
 
410
516
  type LLMRejectReason =
@@ -412,11 +518,18 @@ type LLMRejectReason =
412
518
  | 'queue_limit'
413
519
  | 'budget_limit'
414
520
  | 'timeout'
415
- | 'aborted';
521
+ | 'aborted'
522
+ | 'shutdown';
416
523
  ```
417
524
 
418
525
  ---
419
526
 
527
+ ## Migration from v1
528
+
529
+ Most callers need zero changes. See [CHANGELOG](./CHANGELOG.md) for a detailed migration guide.
530
+
531
+ ---
532
+
420
533
  ## Design Notes
421
534
 
422
535
  This library enforces backpressure at the boundary of your LLM calls. It does not replace higher-level concerns:
@@ -426,23 +539,13 @@ This library enforces backpressure at the boundary of your LLM calls. It does no
426
539
  - **Distributed rate limiting** — use a shared token bucket; bulkheads are per-process
427
540
  - **Model selection** — route above the bulkhead layer; each bulkhead instance is model-specific
428
541
 
429
- Token estimation is deliberately approximate. The estimator's job is to prevent gross over-admission — not to predict your invoice. An estimator that's wrong by 20% still prevents the most common cost explosion: a burst of large-context requests all admitted simultaneously.
430
-
431
- The refund mechanism (correcting reservations based on actual usage after a call completes) is on the roadmap for v2. In v1, reservations are based on `input + maxOutput` and held until release.
432
-
433
- ---
434
-
435
- ## Multimodal
436
-
437
- `content` must be a plain string in v1. Multimodal content (images, documents, tool results as structured blocks) is not supported by the built-in estimators — non-string content is ignored, causing underestimation. Treat token budget results as a lower bound for multimodal requests.
438
-
439
- Full multimodal support is planned for v2.
542
+ Token estimation is deliberately approximate. The refund mechanism improves budget utilization but does not make estimation exact — it corrects after the fact based on actual usage.
440
543
 
441
544
  ---
442
545
 
443
546
  ## Compatibility
444
547
 
445
- - Node.js: 20+ (24 LTS recommended)
548
+ - Node.js: 20+
446
549
  - Module formats: ESM and CommonJS
447
550
 
448
551
  ---