async-bulkhead-llm 3.7.0 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +282 -8
  2. package/dist/cjs/adaptive.cjs +128 -0
  3. package/dist/cjs/adaptive.cjs.map +1 -0
  4. package/dist/cjs/bulkhead.cjs +1063 -0
  5. package/dist/cjs/bulkhead.cjs.map +1 -0
  6. package/dist/cjs/dedup.cjs +111 -0
  7. package/dist/cjs/dedup.cjs.map +1 -0
  8. package/dist/cjs/errors.cjs +16 -0
  9. package/dist/cjs/errors.cjs.map +1 -0
  10. package/dist/cjs/estimators.cjs +205 -0
  11. package/dist/cjs/estimators.cjs.map +1 -0
  12. package/dist/cjs/index.cjs +27 -1123
  13. package/dist/cjs/index.cjs.map +1 -1
  14. package/dist/cjs/profiles.cjs +16 -0
  15. package/dist/cjs/profiles.cjs.map +1 -0
  16. package/dist/cjs/types.cjs +3 -0
  17. package/dist/cjs/types.cjs.map +1 -0
  18. package/dist/cjs/validation.cjs +39 -0
  19. package/dist/cjs/validation.cjs.map +1 -0
  20. package/dist/esm/adaptive.js +125 -0
  21. package/dist/esm/adaptive.js.map +1 -0
  22. package/dist/esm/bulkhead.js +1060 -0
  23. package/dist/esm/bulkhead.js.map +1 -0
  24. package/dist/esm/dedup.js +106 -0
  25. package/dist/esm/dedup.js.map +1 -0
  26. package/dist/esm/errors.js +12 -0
  27. package/dist/esm/errors.js.map +1 -0
  28. package/dist/esm/estimators.js +200 -0
  29. package/dist/esm/estimators.js.map +1 -0
  30. package/dist/esm/index.js +19 -1117
  31. package/dist/esm/index.js.map +1 -1
  32. package/dist/esm/profiles.js +13 -0
  33. package/dist/esm/profiles.js.map +1 -0
  34. package/dist/esm/types.js +2 -0
  35. package/dist/esm/types.js.map +1 -0
  36. package/dist/esm/validation.js +32 -0
  37. package/dist/esm/validation.js.map +1 -0
  38. package/dist/types/adaptive.d.ts +109 -0
  39. package/dist/types/adaptive.d.ts.map +1 -0
  40. package/dist/types/bulkhead.d.ts +31 -0
  41. package/dist/types/bulkhead.d.ts.map +1 -0
  42. package/dist/types/dedup.d.ts +32 -0
  43. package/dist/types/dedup.d.ts.map +1 -0
  44. package/dist/types/errors.d.ts +9 -0
  45. package/dist/types/errors.d.ts.map +1 -0
  46. package/dist/types/estimators.d.ts +91 -0
  47. package/dist/types/estimators.d.ts.map +1 -0
  48. package/dist/types/index.d.ts +27 -660
  49. package/dist/types/index.d.ts.map +1 -1
  50. package/dist/types/profiles.d.ts +11 -0
  51. package/dist/types/profiles.d.ts.map +1 -0
  52. package/dist/types/types.d.ts +666 -0
  53. package/dist/types/types.d.ts.map +1 -0
  54. package/dist/types/validation.d.ts +12 -0
  55. package/dist/types/validation.d.ts.map +1 -0
  56. package/package.json +1 -1
@@ -1,662 +1,29 @@
1
- import { type AcquireOptions, type Stats, type RejectReason as BaseRejectReason } from "async-bulkhead-ts";
2
- type BulkheadSignal = NonNullable<AcquireOptions["signal"]>;
3
1
  /**
4
- * A text content block. The only block type that contributes to
5
- * character-based token estimation.
6
- */
7
- export type TextContentBlock = {
8
- type: "text";
9
- text: string;
10
- };
11
- /**
12
- * A non-text content block (image, tool_result, document, etc.).
13
- *
14
- * By default, built-in estimators ignore non-text blocks — token
15
- * estimates for multimodal requests should then be treated as a lower
16
- * bound. To charge a fixed reservation per opaque block instead, use
17
- * `createModelAwareTokenEstimator`'s `opaqueBlockTokens` option, or
18
- * carry a caller-computed total in `LLMRequest.extraInputTokens`, or
19
- * provide a custom estimator.
20
- */
21
- export type OpaqueContentBlock = {
22
- type: string;
23
- [key: string]: unknown;
24
- };
25
- export type ContentBlock = TextContentBlock | OpaqueContentBlock;
26
- /**
27
- * Minimal message shape shared across estimators.
28
- *
29
- * `content` may be a plain string (backward-compatible with v1) or
30
- * an array of content blocks for multimodal requests.
31
- */
32
- export type LLMMessage = {
33
- role: string;
34
- content: string | ContentBlock[];
35
- };
36
- /**
37
- * Minimal request shape.
38
- *
39
- * `model` is optional at the request level. When present, the estimator
40
- * uses it for ratio lookup instead of the bulkhead-level default.
41
- * This supports A/B testing, canary deployments, and mixed-model routing
42
- * through a single bulkhead.
43
- */
44
- export type LLMRequest = {
45
- model?: string;
46
- messages: LLMMessage[];
47
- max_tokens?: number;
48
- /**
49
- * Optional system prompt (v3.7). Counted by the built-in estimators
50
- * exactly like message content: a plain string, or an array of content
51
- * blocks (text blocks counted by characters, non-text blocks subject
52
- * to the model-aware estimator's `opaqueBlockTokens` surcharge).
53
- *
54
- * Before v3.7, callers had to fold the system prompt into a synthetic
55
- * message for it to participate in estimation — which also distorted
56
- * events, logs, and deduplication keys. Carry it here instead.
57
- */
58
- system?: string | ContentBlock[];
59
- /**
60
- * Additional input tokens the character-based estimators cannot see
61
- * (v3.7) — e.g. provider-side cost of tool schemas kept outside
62
- * `messages`, or media priced by out-of-band rules. Built-in
63
- * estimators add this verbatim to their input estimate; custom
64
- * estimators may honor or ignore it.
65
- *
66
- * Must be a non-negative integer when present. Participates in the
67
- * default deduplication key like any other request field, so requests
68
- * differing only here are never conflated.
69
- */
70
- extraInputTokens?: number;
71
- };
72
- export type TokenEstimate = {
73
- input: number;
74
- maxOutput: number;
75
- };
76
- /**
77
- * Exact token reservation the bulkhead will use for admission.
78
- *
79
- * `null` is returned by `bulkhead.estimate()` when `tokenBudget` is not
80
- * configured, because no token reservation participates in admission in
81
- * that mode.
82
- */
83
- export type LLMReservationEstimate = {
84
- readonly input: number;
85
- readonly maxOutput: number;
86
- readonly reserved: number;
87
- };
88
- export type TokenEstimator = (request: LLMRequest) => TokenEstimate;
89
- /**
90
- * Actual token usage returned by the provider after a call completes.
91
- *
92
- * In v2, this drives the refund mechanism: when usage is reported at
93
- * release time, the difference between the pre-admission reservation
94
- * and actual consumption is returned to the budget immediately.
95
- */
96
- export type TokenUsage = {
97
- input: number;
98
- output: number;
99
- };
100
- /**
101
- * Rejection reasons.
102
- *
103
- * `"unshareable_result"` (v3.5) is raised only for deduplication
104
- * *followers*: the shared call resolved to a single-consumer value
105
- * (stream, `Response` with a body, async iterable) that cannot be
106
- * safely handed to more than one caller, and no
107
- * `deduplication.shareResult` hook was configured. The leader always
108
- * receives the original result unaffected.
109
- */
110
- export type LLMRejectReason = BaseRejectReason | "budget_limit" | "unshareable_result";
111
- /**
112
- * Admission priority.
113
- *
114
- * `"high"` requests may use the full token budget. `"normal"` requests
115
- * (the default) are rejected once available budget drops to
116
- * `tokenBudget.highPriorityReserve`, keeping headroom for high-priority
117
- * traffic. Priority has no effect when `tokenBudget` is not configured
118
- * or `highPriorityReserve` is 0/unset.
119
- */
120
- export type LLMPriority = "high" | "normal";
121
- /**
122
- * Capacity snapshot attached to rejections so callers (e.g. gateways)
123
- * can build informative 429/503 responses.
124
- *
125
- * Note: no retry-after estimate is provided — a fail-fast bulkhead has
126
- * no honest ETA for capacity. Expose these numbers instead.
127
- */
128
- export type LLMRejectDetail = {
129
- inFlight: number;
130
- maxConcurrent: number;
131
- pending: number;
132
- maxQueue: number;
133
- tokenBudget?: {
134
- /** Configured budget ceiling. */
135
- budget: number;
136
- /** Tokens currently held by in-flight reservations. */
137
- inFlightTokens: number;
138
- /** Budget this request was admitted against (priority-adjusted). */
139
- effectiveBudget: number;
140
- /** Tokens available at this priority (clamped at 0). */
141
- available: number;
142
- /** Tokens this request needed. */
143
- requested: number;
144
- };
145
- };
146
- /** Options accepted by `acquire()` / `run()` (base options + priority). */
147
- export type LLMAcquireOptions = AcquireOptions & {
148
- priority?: LLMPriority;
149
- /**
150
- * Per-call token reservation override (v3.7).
151
- *
152
- * When provided and `tokenBudget` is configured, admission reserves
153
- * `input + maxOutput` from this value verbatim and the bulkhead's
154
- * estimator is not consulted for this call. Intended for callers —
155
- * typically gateways — that already compute a more accurate estimate
156
- * from the full provider request (tool schemas, response formats,
157
- * provider-priced media) than any character-ratio estimator could.
158
- *
159
- * Both fields must be non-negative integers. Ignored when
160
- * `tokenBudget` is not configured (no reservation participates in
161
- * admission in that mode). Not reflected by `estimate()`, which
162
- * always previews the estimator path.
163
- */
164
- reservation?: TokenEstimate;
165
- };
166
- export declare class LLMBulkheadRejectedError extends Error {
167
- readonly reason: LLMRejectReason;
168
- readonly code: "LLM_BULKHEAD_REJECTED";
169
- readonly detail: LLMRejectDetail | undefined;
170
- constructor(reason: LLMRejectReason, detail?: LLMRejectDetail);
171
- }
172
- export type LLMRequestStats = {
173
- /** Successful LLM admissions (slot + budget acquired). */
174
- admitted: number;
175
- /** Successful LLM releases via the wrapped LLM token. */
176
- released: number;
177
- /** Total LLM-layer rejections. */
178
- rejected: number;
179
- /** LLM-layer rejections by reason. */
180
- rejectedByReason: Partial<Record<LLMRejectReason, number>>;
181
- };
182
- export type LLMStats = {
183
- /** Underlying async-bulkhead-ts stats. */
184
- bulkhead: Stats;
185
- /** LLM-layer request stats. */
186
- llm: LLMRequestStats;
187
- /** Present only when `tokenBudget` is configured. */
188
- tokenBudget?: {
189
- budget: number;
190
- inFlightTokens: number;
191
- available: number;
192
- /**
193
- * Cumulative tokens reserved at admission across all successful
194
- * admissions. Monotonically increasing.
195
- */
196
- totalReserved: number;
197
- /**
198
- * Cumulative actual tokens consumed (`usage.input + usage.output`),
199
- * summed across releases that reported `TokenUsage`. Releases without
200
- * usage contribute 0 — `totalConsumed` is meaningful only when
201
- * `getUsage` is wired up consistently. Not clamped: over-consumption
202
- * (actual > reserved) is reported as-is.
203
- */
204
- totalConsumed: number;
205
- /**
206
- * Cumulative tokens returned to the budget via the refund mechanism —
207
- * both early refunds from `reportUsage()` and refunds at release.
208
- */
209
- totalRefunded: number;
210
- /**
211
- * Cumulative tokens held *beyond* original reservations because
212
- * `reportUsage()` reported consumption exceeding the reserved hold.
213
- * Overrun expands `inFlightTokens` (possibly above `budget`), which
214
- * correctly blocks new admissions until the overrunning work releases.
215
- */
216
- totalOverrun: number;
217
- /** Budget headroom reserved for `priority: "high"` requests. */
218
- highPriorityReserve: number;
219
- };
220
- /** Present only when deduplication is enabled. */
221
- deduplication?: {
222
- /** Number of distinct in-flight deduplication keys. */
223
- active: number;
224
- /** Cumulative requests that shared an existing in-flight call. */
225
- hits: number;
226
- };
227
- };
228
- export type LLMEventMap = {
229
- /** Fired after a request is admitted (slot + budget acquired). */
230
- admit: {
231
- request: LLMRequest;
232
- admissionId: string;
233
- priority: LLMPriority;
234
- reservedTokens: number;
235
- };
236
- /** Fired when a request is rejected at any stage. */
237
- reject: {
238
- request: LLMRequest;
239
- reason: LLMRejectReason;
240
- /** Capacity snapshot; absent for dedup-wait rejections. */
241
- detail?: LLMRejectDetail;
242
- };
243
- /**
244
- * Fired when a slot is released.
245
- *
246
- * `reservedTokens` is the pre-admission reservation (input estimate +
247
- * `max_tokens` reservation). `refundedTokens` is what was returned to
248
- * the budget — non-zero only when `usage` was reported and
249
- * `usage.input + usage.output < reservedTokens`.
250
- *
251
- * Per-request actual consumption: `usage ? usage.input + usage.output : null`.
252
- * The library does not pre-derive this onto the event payload — `null`
253
- * (no usage reported) and `0` (genuinely zero usage) are different
254
- * states that observers should distinguish.
255
- *
256
- * For cumulative consumption across all releases, prefer
257
- * `stats().tokenBudget.totalConsumed` over aggregating these events.
258
- */
259
- release: {
260
- request: LLMRequest;
261
- admissionId: string;
262
- priority: LLMPriority;
263
- reservedTokens: number;
264
- /** Tokens held immediately before release returned them. */
265
- heldTokens: number;
266
- refundedTokens: number;
267
- /** Last emitted usage-event sequence for this admission. */
268
- usageSequence: number;
269
- usage?: TokenUsage;
270
- };
271
- /**
272
- * Fired after an effective cumulative `reportUsage()` update.
273
- *
274
- * Stale or duplicate reports that do not increase either cumulative
275
- * usage field are ignored and do not emit an event. `sequence` starts at
276
- * 1 per admission and increases monotonically, allowing external
277
- * coordinators to reject duplicate or out-of-order updates.
278
- */
279
- usage: {
280
- request: LLMRequest;
281
- admissionId: string;
282
- priority: LLMPriority;
283
- sequence: number;
284
- reservedTokens: number;
285
- previousHeldTokens: number;
286
- heldTokens: number;
287
- deltaTokens: number;
288
- usage: TokenUsage;
289
- outputCap: number | null;
290
- outputRemaining: number | null;
291
- overReservation: boolean;
292
- };
293
- /** Fired when a request joins an existing in-flight call via dedup. */
294
- dedup: {
295
- request: LLMRequest;
296
- };
297
- };
298
- export type LLMEventType = keyof LLMEventMap;
299
- type Listener<K extends LLMEventType> = (payload: LLMEventMap[K]) => void;
300
- export type LLMBulkheadPreset = {
301
- maxQueue?: number;
302
- timeoutMs?: number;
303
- };
304
- /**
305
- * Built-in presets for common deployment patterns.
306
- * Explicit options always override preset defaults.
307
- */
308
- export declare const PROFILES: Record<"interactive" | "batch", LLMBulkheadPreset>;
309
- export type TokenBudgetOptions = {
310
- /**
311
- * Maximum tokens allowed in-flight simultaneously across all active requests.
312
- * Admission is always fail-fast when this ceiling is reached,
313
- * independent of concurrency headroom and independent of `profile`.
314
- *
315
- * Must be a non-negative integer. `0` is valid and intentional — it
316
- * represents a pool with no budget to grant this cycle (e.g. a lease
317
- * ledger reporting exhaustion) and results in every budget-gated
318
- * admission being rejected with `"budget_limit"` until the ceiling is
319
- * raised (via `setBudget()`) or `tokenBudget` admits a zero-token
320
- * request.
321
- */
322
- budget: number;
323
- /**
324
- * Estimator used to calculate token reservation pre-admission.
325
- * Defaults to `createModelAwareTokenEstimator` seeded with the bulkhead's `model`.
326
- */
327
- estimator?: TokenEstimator;
328
- /**
329
- * Fallback output reservation when `request.max_tokens` is absent.
330
- * Default: 2048.
331
- */
332
- outputCap?: number;
333
- /**
334
- * Tokens of budget headroom reserved for `priority: "high"` requests.
335
- *
336
- * Normal-priority admission is checked against
337
- * `budget - highPriorityReserve`; high-priority admission is checked
338
- * against the full `budget`. This lets interactive traffic keep
339
- * admitting while batch traffic has saturated the shared pool.
340
- *
341
- * Must satisfy `0 <= highPriorityReserve <= budget`. Default: 0
342
- * (priority has no effect).
343
- */
344
- highPriorityReserve?: number;
345
- };
346
- export type DeduplicationOptions = {
347
- /**
348
- * Custom function to derive a deduplication key from a request.
349
- * Requests with the same key that arrive while a matching call is
350
- * already in-flight share that call.
351
- *
352
- * Default (v3.4): a key-order-stable serialization of the **entire
353
- * request object**. Any own enumerable property difference —
354
- * `temperature`, `tools`, `system`, etc., not just `messages` /
355
- * `max_tokens` / `model` — prevents conflation. The tradeoff: volatile
356
- * per-request fields (request IDs, timestamps) also defeat
357
- * deduplication. If your requests carry such fields, supply a `keyFn`
358
- * that omits them. Non-serializable values (functions, symbols) are
359
- * dropped by JSON serialization and do not distinguish requests.
360
- *
361
- * Keys are SHA-256 hashed before being stored, so the in-flight map
362
- * never retains prompt text and per-entry key memory is bounded.
363
- *
364
- * Deduplication applies to `run()` only — `acquire()` never
365
- * deduplicates.
366
- *
367
- * **Multi-tenant callers:** the default key has no tenant dimension.
368
- * Two tenants sending byte-identical requests would share one
369
- * response. Pass `dedupScope` (per-call, on `run()` options) or bake
370
- * the tenant into a custom `keyFn` to prevent cross-tenant sharing.
371
- *
372
- * Return an empty string to opt a specific request out of deduplication.
373
- */
374
- keyFn?: (request: LLMRequest) => string;
375
- /**
376
- * Fan-out hook for delivering a shared in-flight result to
377
- * deduplication *followers* (v3.5).
378
- *
379
- * Called once per follower with the leader's resolved result; the
380
- * return value is what that follower receives. The leader always
381
- * receives the original result — `shareResult` is never called for
382
- * the leader.
383
- *
384
- * Why this exists: without it, followers receive the *same object*
385
- * the leader does. For plain JSON results that is fine (and remains
386
- * the default), but single-consumer values — `ReadableStream`,
387
- * Node `Readable`, async iterables, `Response` bodies — can only be
388
- * consumed once. Whichever caller reads first wins; the rest get a
389
- * locked or drained stream. The library cannot tee arbitrary stream
390
- * types on your behalf, so it provides this seam instead:
391
- *
392
- * ```ts
393
- * // fetch Response: hand each follower an independent clone.
394
- * // (clone() must be called before any consumer reads the body —
395
- * // guaranteed here, since fan-out happens at resolution time.)
396
- * deduplication: { shareResult: (r) => (r as Response).clone() }
397
- * ```
398
- *
399
- * When `shareResult` is provided it is called for **every** follower
400
- * delivery, including safe (non-stream) results — it is a general
401
- * fan-out policy, usable e.g. for defensive deep-cloning.
402
- *
403
- * If `shareResult` throws, that follower's `run()` rejects with the
404
- * thrown error as-is; the leader and other followers are unaffected.
405
- *
406
- * When `shareResult` is **not** provided and the shared result is
407
- * detected as single-consumer, followers are rejected with
408
- * `LLMBulkheadRejectedError("unshareable_result")` rather than being
409
- * silently handed a stream they cannot read. Detection is shallow:
410
- * it inspects the result value itself, not nested properties — a
411
- * stream buried inside `{ stream: ... }` is not detected and will be
412
- * shared by reference as before.
413
- */
414
- shareResult?: (result: unknown) => unknown;
415
- };
416
- export type LLMBulkheadOptions = {
417
- /**
418
- * Model identifier. Used by the default estimator for ratio lookup.
419
- *
420
- * One bulkhead per model is the strongly recommended deployment pattern.
421
- * When routing multiple models through one bulkhead, set `model` on
422
- * individual `LLMRequest` objects for accurate estimation.
423
- */
424
- model: string;
425
- /** Maximum number of requests in-flight simultaneously. */
426
- maxConcurrent: number;
427
- /**
428
- * Maximum number of requests waiting for admission.
429
- * Default: 0 (fail-fast). Prefer setting via `profile`.
430
- */
431
- maxQueue?: number;
432
- /**
433
- * Waiting timeout in milliseconds. Applies to queued requests only.
434
- * Has no effect when `maxQueue` is 0.
435
- */
436
- timeoutMs?: number;
437
- /**
438
- * Opinionated defaults for common deployment patterns.
439
- * Explicit options always override profile defaults.
440
- */
441
- profile?: "interactive" | "batch" | LLMBulkheadPreset;
442
- /**
443
- * Token budget enforcement. Admission fails fast when the in-flight token
444
- * ceiling is reached, regardless of concurrency headroom or `profile`.
445
- * Omit to disable token-aware admission.
446
- */
447
- tokenBudget?: TokenBudgetOptions;
448
- /**
449
- * Enable in-flight request deduplication.
450
- *
451
- * - `true` — use the default key function
452
- * - `DeduplicationOptions` — customize the key function
453
- * - `false` / omitted — disabled
454
- */
455
- deduplication?: boolean | DeduplicationOptions;
456
- };
457
- /**
458
- * Snapshot returned by `LLMToken.reportUsage()`.
459
- *
460
- * `outputCap` / `outputRemaining` are `null` when `tokenBudget` is not
461
- * configured (there is no reservation to measure against).
462
- */
463
- export type UsageReport = {
464
- /** Stable identifier of the admission this usage belongs to. */
465
- admissionId: string;
466
- /**
467
- * Last effective usage-update sequence for this admission.
468
- * Starts at 0 before any effective report, increments only when either
469
- * cumulative usage field increases, and remains stable for stale reports.
470
- */
471
- sequence: number;
472
- /** Original pre-admission reservation (0 when budget disabled). */
473
- reserved: number;
474
- /** Tokens currently held against the budget for this request. */
475
- held: number;
476
- /** Cumulative reported consumption (`input + output`). */
477
- consumed: number;
478
- /** Output tokens reserved for this request (`max_tokens`/`outputCap`). */
479
- outputCap: number | null;
480
- /** Output reservation remaining before the stream overruns it. */
481
- outputRemaining: number | null;
482
- /** True once cumulative consumption exceeds the original reservation. */
483
- overReservation: boolean;
484
- };
485
- /** Context passed to `run()` callbacks for mid-flight usage reporting. */
486
- export type LLMRunContext = {
487
- /** Stable identifier for this successful admission. */
488
- readonly admissionId: string;
489
- /** Exact reservation used at admission, or `null` without a token budget. */
490
- readonly reservation: LLMReservationEstimate | null;
491
- reportUsage(usage: TokenUsage): UsageReport;
492
- };
493
- /**
494
- * Admission token returned by `acquire()`.
495
- *
496
- * Call `release()` exactly once when the request completes.
497
- * Pass `TokenUsage` to enable the refund mechanism — the bulkhead
498
- * returns the difference between the pre-admission reservation and
499
- * actual consumption to the budget immediately.
500
- *
501
- * For streaming workloads, call `reportUsage()` with *cumulative* usage
502
- * as stream events arrive:
503
- *
504
- * - If the reported input is lower than the pre-admission estimate, the
505
- * surplus is refunded to the budget immediately (the full output
506
- * reservation is retained).
507
- * - If reported consumption exceeds the hold, the hold expands (overrun),
508
- * which blocks new admissions until this request releases.
509
- * - Reports are clamped to be monotonically non-decreasing per field.
510
- * - If `release()` is later called without usage, the last reported
511
- * usage is used for the final refund.
512
- */
513
- export type LLMToken = {
514
- /** Stable identifier for this successful admission. */
515
- readonly admissionId: string;
516
- /** Exact reservation used at admission, or `null` without a token budget. */
517
- readonly reservation: LLMReservationEstimate | null;
518
- release(usage?: TokenUsage): void;
519
- reportUsage(usage: TokenUsage): UsageReport;
520
- };
521
- export type LLMAcquireResult = {
522
- ok: true;
523
- admissionId: string;
524
- reservation: LLMReservationEstimate | null;
525
- token: LLMToken;
526
- } | {
527
- ok: false;
528
- reason: LLMRejectReason;
529
- detail?: LLMRejectDetail;
530
- };
531
- /**
532
- * Extract total character count from message content.
533
- * Handles both plain strings and multimodal content block arrays.
534
- * Non-text blocks are ignored (contribute 0 characters).
535
- */
536
- export declare function extractTextLength(content: string | ContentBlock[]): number;
537
- /**
538
- * Estimates token usage using a flat 4-characters-per-token ratio.
539
- *
540
- * Handles both plain string and multimodal content.
541
- * Non-text content blocks are ignored (treated as zero tokens).
542
- *
543
- * Accuracy: ±25% for English prose.
544
- * Suitable for load-shedding; not suitable for cost accounting.
545
- *
546
- * v3.7: counts `request.system` alongside message content and adds
547
- * `request.extraInputTokens` verbatim. Non-text blocks still contribute
548
- * zero characters (use the model-aware estimator's `opaqueBlockTokens`
549
- * for per-block surcharges).
550
- */
551
- export declare function naiveTokenEstimator(request: LLMRequest): TokenEstimate;
552
- /**
553
- * Surcharge policy for opaque (non-text) content blocks (v3.7).
554
- *
555
- * - `number` — every opaque block reserves this many input tokens.
556
- * - `{ default?, byType? }` — per-`block.type` surcharges with an
557
- * optional fallback for types not listed; unlisted types with no
558
- * `default` contribute 0.
559
- *
560
- * All values must be non-negative integers. A block is "opaque" unless
561
- * it is a well-formed text block (`type: "text"` with a string `text`)
562
- * — malformed text blocks are treated as opaque, which errs toward
563
- * over-reservation. Applies to blocks in `messages[].content` and
564
- * `system` arrays.
565
- */
566
- export type OpaqueBlockTokens = number | {
567
- /** Fallback surcharge for opaque types without a `byType` entry. */
568
- default?: number;
569
- /** Per-block-type surcharges, keyed by `block.type`. */
570
- byType?: Record<string, number>;
571
- };
572
- export type ModelAwareEstimatorOptions = {
573
- /**
574
- * Model string used for ratio lookup when the request does not
575
- * carry its own `model` field. Should match the `model` field on
576
- * the owning `LLMBulkhead`.
577
- */
578
- defaultModel?: string | undefined;
579
- /**
580
- * Fallback output reservation when `request.max_tokens` is absent.
581
- * Default: 2048.
582
- */
583
- outputCap?: number | undefined;
584
- /**
585
- * Called when the model string matches no built-in prefix and no override.
586
- * The estimator falls back to the naive 4.0 ratio when this fires.
587
- */
588
- onUnknownModel?: ((model: string) => void) | undefined;
589
- /**
590
- * Input-token surcharge for opaque (non-text) content blocks (v3.7).
591
- *
592
- * Without this, opaque blocks contribute 0 input tokens — an
593
- * image-heavy request estimates as nearly free, which is the wrong
594
- * direction for admission control. A flat conservative number (e.g.
595
- * 2048 per block) or a per-type map converts each opaque block into a
596
- * fixed reservation. Validated at estimator creation. Omitted:
597
- * surcharge disabled (previous behavior).
598
- */
599
- opaqueBlockTokens?: OpaqueBlockTokens | undefined;
600
- };
601
- /**
602
- * Estimates token usage using per-model character ratios.
603
- *
604
- * Accuracy: ±15% for known models on English prose.
605
- * Falls back to naiveTokenEstimator (ratio 4.0) for unknown models.
606
- *
607
- * v2: respects `request.model` when present, falling back to `defaultModel`.
608
- * v2: handles multimodal content (text blocks counted, others ignored).
609
- * v3.7: counts `request.system`, adds `request.extraInputTokens`
610
- * verbatim, and applies the `opaqueBlockTokens` surcharge (when
611
- * configured) to every non-text block in messages and system.
612
- */
613
- export declare function createModelAwareTokenEstimator(opts?: ModelAwareEstimatorOptions): TokenEstimator;
614
- export declare function createModelAwareTokenEstimator(overrides?: Record<string, number>, opts?: ModelAwareEstimatorOptions): TokenEstimator;
615
- export declare function createLLMBulkhead(opts: LLMBulkheadOptions): {
616
- estimate: (request: LLMRequest) => LLMReservationEstimate | null;
617
- acquire: (request: LLMRequest, ao?: LLMAcquireOptions) => Promise<LLMAcquireResult>;
618
- run: <T>(request: LLMRequest, fn: (signal?: BulkheadSignal, ctx?: LLMRunContext) => Promise<T>, ao?: LLMAcquireOptions & {
619
- getUsage?: (result: T) => TokenUsage | undefined;
620
- /**
621
- * Deduplication scope. Requests deduplicate only within the same
622
- * scope — calls with different scopes never share an in-flight
623
- * call, even with identical keys. Use this to carry the tenant /
624
- * API-key identity in multi-tenant gateways so responses are never
625
- * shared across tenants. Ignored when deduplication is disabled.
626
- * Default: `""` (single global scope).
627
- */
628
- dedupScope?: string;
629
- /**
630
- * Per-call deduplication opt-out (v3.5). Pass `false` to make
631
- * this call always execute independently — it neither joins an
632
- * existing in-flight call nor registers itself as joinable.
633
- *
634
- * Intended for streaming routes on a bulkhead where dedup is
635
- * otherwise useful: shared stream results are single-consumer
636
- * (see `deduplication.shareResult`), so streaming calls can skip
637
- * dedup here instead of encoding the exemption in a bulkhead-wide
638
- * `keyFn`.
639
- *
640
- * `true` is accepted but cannot enable deduplication when it is
641
- * disabled at the bulkhead level (the key function and shared
642
- * state live there); it is treated the same as omitting the
643
- * option. Ignored by `acquire()`, which never deduplicates.
644
- */
645
- dedup?: boolean;
646
- }) => Promise<T>;
647
- wouldAdmit: (request: LLMRequest, opts?: {
648
- priority?: LLMPriority;
649
- reservation?: TokenEstimate;
650
- }) => {
651
- admit: boolean;
652
- reason?: LLMRejectReason;
653
- };
654
- stats: () => LLMStats;
655
- setBudget: (tokens: number) => void;
656
- close: () => void;
657
- drain: () => Promise<void>;
658
- on: <K extends LLMEventType>(event: K, listener: Listener<K>) => () => void;
659
- };
660
- export type LLMBulkhead = ReturnType<typeof createLLMBulkhead>;
661
- export {};
2
+ * async-bulkhead-llm — public API surface.
3
+ *
4
+ * This entry point re-exports everything the package supports; the
5
+ * implementation lives in focused modules:
6
+ *
7
+ * - `types.ts` — request/result/options/stats/event types
8
+ * - `errors.ts` — `LLMBulkheadRejectedError`
9
+ * - `profiles.ts` — `PROFILES` presets
10
+ * - `estimators.ts` — naive + model-aware estimators, `extractTextLength`
11
+ * - `adaptive.ts` — `createAdaptiveTokenEstimator` (v3.8)
12
+ * - `dedup.ts` — deduplication internals (keying, share safety)
13
+ * - `validation.ts` — internal numeric/estimate/usage guards
14
+ * - `bulkhead.ts` — `createLLMBulkhead` (admission, budget, events)
15
+ *
16
+ * Deep-importing the internal modules is not supported; the package
17
+ * `exports` map exposes only this entry point.
18
+ */
19
+ export type { ContentBlock, DeduplicationOptions, LLMAcquireOptions, LLMAcquireResult, LLMAdmissionMode, LLMBulkheadOptions, LLMDrainResult, LLMEventMap, LLMEventType, LLMMessage, LLMPriority, LLMRejectDetail, LLMRejectReason, LLMRequest, LLMRequestStats, LLMReservationEstimate, LLMRunAdmission, LLMRunOptions, LLMReservationOverride, LLMRunContext, LLMShadowableRejectReason, LLMStats, LLMObserveStats, LLMToken, LLMWouldAdmitResult, OpaqueContentBlock, TextContentBlock, TokenBudgetOptions, TokenEstimate, TokenEstimator, TokenUsage, UsageReport, } from "./types.js";
20
+ export { LLMBulkheadRejectedError } from "./errors.js";
21
+ export { PROFILES } from "./profiles.js";
22
+ export type { LLMBulkheadPreset } from "./profiles.js";
23
+ export { createModelAwareTokenEstimator, extractTextLength, naiveTokenEstimator, } from "./estimators.js";
24
+ export type { ModelAwareEstimatorOptions, OpaqueBlockTokens, } from "./estimators.js";
25
+ export { createAdaptiveTokenEstimator } from "./adaptive.js";
26
+ export type { AdaptiveModelCorrection, AdaptiveTokenEstimator, AdaptiveTokenEstimatorOptions, } from "./adaptive.js";
27
+ export { createLLMBulkhead } from "./bulkhead.js";
28
+ export type { LLMBulkhead } from "./bulkhead.js";
662
29
  //# sourceMappingURL=index.d.ts.map