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
package/README.md CHANGED
@@ -17,15 +17,18 @@ Designed for services that need to enforce **cost ceilings, concurrency limits,
17
17
  - ✅ **Full-request estimation** — `system` prompts counted natively; `extraInputTokens` carries caller-computed costs (tool schemas, provider-priced media)
18
18
  - ✅ **Per-call reservation override** — gateways with their own estimate can bypass the estimator via `reservation` on `acquire()`/`run()`/`wouldAdmit()`
19
19
  - ✅ **Fail-fast by default** — shed load early, never silently queue
20
+ - ✅ **Observe/shadow mode** — measure capacity-policy impact while still executing selected would-be-rejected calls
20
21
  - ✅ **Opinionated profiles** — `'interactive'` and `'batch'` presets with escape hatch
21
22
  - ✅ **In-flight deduplication** — identical requests share one LLM call; hashed keys, whole-request equality
22
23
  - ✅ **Custom dedup key + per-tenant scope** — bring your own equivalence function; `dedupScope` isolates tenants
23
24
  - ✅ **Streaming-safe deduplication** — single-consumer results are never silently shared; `shareResult` fan-out hook + per-call `dedup: false` opt-out
24
- - ✅ **Exact reservation preview** — `estimate()` exposes the reservation admission will use
25
+ - ✅ **Exact reservation preview** — `estimate()` exposes the reservation admission will use, and its result can be passed back verbatim as the per-call `reservation`
26
+ - ✅ **Adaptive estimation** — `createAdaptiveTokenEstimator()` self-calibrates per-model input estimates from observed usage
27
+ - ✅ **Advisory capacity snapshots** — `wouldAdmit(request, { detail: true })` returns the same capacity numbers rejections carry
25
28
  - ✅ **Stable admission IDs** — correlate gateway requests, traces, usage, and release
26
29
  - ✅ **Ordered usage events** — sequence-numbered hold changes for external coordinators
27
- - ✅ **Event hooks** — `on('admit' | 'reject' | 'usage' | 'release' | 'dedup', fn)`
28
- - ✅ **Graceful shutdown** — `close()` + `drain()`
30
+ - ✅ **Event hooks** — admitted and bypassed lifecycles have separate telemetry events
31
+ - ✅ **Graceful shutdown** — `close()` + `drain()`, with an optional bounded wait: `drain({ timeoutMs })`
29
32
  - ✅ Optional **AbortSignal** and **timeout** cancellation
30
33
  - ✅ `bulkhead.run(request, fn)` — acquire + release handled automatically
31
34
  - ✅ Zero dependencies beyond `async-bulkhead-ts`
@@ -53,6 +56,7 @@ Non-goals (by design):
53
56
  | **Concurrency limits** | ✅ Yes | ⚠️ Indirect | ❌ No | ✅ Yes | ⚠️ Indirect |
54
57
  | **Bounded queue (optional)** | ✅ Yes | ⚠️ Internal | ❌ No | ✅ Yes | ⚠️ Indirect |
55
58
  | **Fail-fast overload handling** | ✅ Core feature | ❌ No | ❌ No | ❌ No | ⚠️ Indirect |
59
+ | **Observe/shadow rollout mode** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
56
60
  | **In-flight deduplication** | ✅ Yes | ⚠️ Partial caching | ❌ No | ❌ No | ❌ No |
57
61
  | **Custom dedup key** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
58
62
  | **Model-aware estimation** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
@@ -128,6 +132,201 @@ const result = await bulkhead.run(request, async () => {
128
132
 
129
133
  ---
130
134
 
135
+ ## What's New in v3.9 — First-class observe mode
136
+
137
+ v3.9 adds an explicit rollout mode for measuring admission policy before fully
138
+ enforcing it. `run()` still attempts normal admission first. When a configured
139
+ capacity-related rejection occurs, observe mode executes the callback without
140
+ holding a concurrency slot or token reservation and records the bypass on a
141
+ separate telemetry surface.
142
+
143
+ ```ts
144
+ const result = await bulkhead.run(
145
+ request,
146
+ async (signal, ctx) => {
147
+ logger.info({
148
+ admissionId: ctx?.admissionId,
149
+ admission: ctx?.admission, // "admitted" | "bypassed"
150
+ bypassReason: ctx?.bypassReason, // set only for bypassed work
151
+ bypassDetail: ctx?.bypassDetail, // capacity snapshot, when available
152
+ });
153
+
154
+ return callYourLLMProvider(request, {
155
+ signal,
156
+ onUsage: (usage) => ctx?.reportUsage(usage),
157
+ });
158
+ },
159
+ { mode: "observe" },
160
+ );
161
+ ```
162
+
163
+ By default, observe mode may bypass these capacity outcomes:
164
+
165
+ ```ts
166
+ "budget_limit" | "concurrency_limit" | "queue_limit" | "timeout"
167
+ ```
168
+
169
+ Shutdown, caller cancellation, and unsafe deduplication fan-out remain hard
170
+ failures. Observe mode is therefore not a global "ignore every rejection"
171
+ switch.
172
+
173
+ ### Restrict which outcomes may be bypassed
174
+
175
+ Use `shadowReasons` to roll out one policy at a time:
176
+
177
+ ```ts
178
+ await bulkhead.run(request, fn, {
179
+ mode: "observe",
180
+ shadowReasons: ["budget_limit"],
181
+ });
182
+ ```
183
+
184
+ An empty `shadowReasons` array keeps normal enforcement while still exposing
185
+ `ctx.admission === "admitted"` to callbacks.
186
+
187
+ ### Admitted and bypassed callback context
188
+
189
+ Normally admitted calls receive the same context with:
190
+
191
+ ```ts
192
+ ctx.admission === "admitted"
193
+ ctx.bypassReason === undefined
194
+ ```
195
+
196
+ Bypassed calls receive a `shadow-`-prefixed `admissionId`, the exact evaluated
197
+ reservation, the bypass reason, and the associated capacity detail. Their
198
+ `reportUsage()` snapshots always report `held: 0`, because observed work does
199
+ not consume bulkhead accounting capacity.
200
+
201
+ ### Separate observe telemetry
202
+
203
+ Bypassed work does not increment normal `admit`/`release` counters. It is
204
+ reported through:
205
+
206
+ ```ts
207
+ bulkhead.on("bypass", listener);
208
+ bulkhead.on("bypassUsage", listener);
209
+ bulkhead.on("bypassRelease", listener);
210
+
211
+ const observe = bulkhead.stats().observe;
212
+ // {
213
+ // bypassed,
214
+ // raceBypassed,
215
+ // bypassedByReason,
216
+ // usageReported,
217
+ // totalInputTokens,
218
+ // totalOutputTokens,
219
+ // }
220
+ ```
221
+
222
+ `raceBypassed` counts calls whose advisory check passed but whose authoritative
223
+ acquisition later rejected—for example, a queued request that timed out while
224
+ capacity changed. This makes preview-to-admission races visible instead of
225
+ silently merging them into ordinary bypasses.
226
+
227
+ > Observe mode intentionally allows work to proceed without capacity
228
+ > protection. Use it for policy calibration, migration, and audit periods—not
229
+ > as the steady-state overload posture of a saturated service.
230
+
231
+ ---
232
+
233
+ ## What's New in v3.8 — Feedback and shutdown ergonomics
234
+
235
+ ### Bounded drain
236
+
237
+ `drain()` without arguments is unchanged (`Promise<void>`). With a deadline,
238
+ it always *resolves* — never rejects — with what happened:
239
+
240
+ ```ts
241
+ bulkhead.close();
242
+ const result = await bulkhead.drain({ timeoutMs: 10_000 });
243
+ if (!result.drained) {
244
+ log.warn("abandoning shutdown wait", {
245
+ inFlight: result.inFlight,
246
+ pending: result.pending,
247
+ });
248
+ }
249
+ ```
250
+
251
+ The deadline never cancels or interrupts in-flight work and leaves the
252
+ bulkhead's accounting untouched — work that finishes later still releases
253
+ normally. It exists so a shutdown path can log what it is abandoning and
254
+ proceed, instead of parking forever behind one stuck upstream stream.
255
+ `timeoutMs: 0` is an immediate "is it drained right now?" snapshot.
256
+
257
+ ### Capacity detail from `wouldAdmit()`
258
+
259
+ Routing layers choosing between pools want the numbers, not just the boolean:
260
+
261
+ ```ts
262
+ const { admit, reason, detail } = bulkhead.wouldAdmit(request, {
263
+ detail: true,
264
+ });
265
+ // detail is the same LLMRejectDetail snapshot real rejections carry,
266
+ // present on admit: true as well (detail.tokenBudget.requested is the
267
+ // reservation this request needs).
268
+ ```
269
+
270
+ Omitted by default, so existing callers see the exact v3.7 result shape.
271
+
272
+ ### `estimate()` round-trips as the reservation override
273
+
274
+ The frozen object returned by `estimate()` can now be passed straight back:
275
+
276
+ ```ts
277
+ const preview = bulkhead.estimate(request);
278
+ await bulkhead.run(request, fn, {
279
+ ...(preview !== null ? { reservation: preview } : {}),
280
+ });
281
+ ```
282
+
283
+ When the override carries a `reserved` field it is validated as a
284
+ consistency check (`reserved === input + maxOutput`), catching hand-built
285
+ overrides whose cached total drifted from edited parts. Plain
286
+ `{ input, maxOutput }` overrides are unchanged.
287
+
288
+ ### Adaptive estimation
289
+
290
+ Character-ratio estimation is ±15% at best and drifts with content mix and
291
+ tokenizer changes. `createAdaptiveTokenEstimator()` closes the loop:
292
+
293
+ ```ts
294
+ import {
295
+ createAdaptiveTokenEstimator,
296
+ createLLMBulkhead,
297
+ } from "async-bulkhead-llm";
298
+
299
+ const adaptive = createAdaptiveTokenEstimator({
300
+ defaultModel: "claude-sonnet-4-5",
301
+ opaqueBlockTokens: 2_048,
302
+ // smoothing: 0.2, minSamples: 5,
303
+ // minCorrection: 0.5, maxCorrection: 2, maxModels: 64,
304
+ });
305
+
306
+ const bulkhead = createLLMBulkhead({
307
+ model: "claude-sonnet-4-5",
308
+ maxConcurrent: 8,
309
+ tokenBudget: { budget: 200_000, estimator: adaptive.estimator },
310
+ });
311
+
312
+ // Close the loop from actual usage:
313
+ bulkhead.on("release", (e) => {
314
+ if (e.usage) adaptive.observe(e.request, e.usage);
315
+ });
316
+
317
+ adaptive.corrections(); // per-model { samples, factor, applied } for /stats
318
+ ```
319
+
320
+ It maintains a per-model EWMA of `actual input / estimated input` and
321
+ multiplies future *input* estimates by that factor — clamped, and only
322
+ after `minSamples` observations. Output reservations are never corrected
323
+ (`max_tokens` is a ceiling, not an estimate). Observations always measure
324
+ against the *uncorrected* base estimate, so the loop cannot compound
325
+ through its own corrections. Calibration is in-memory, per-instance, and
326
+ bounded to `maxModels` tracked models.
327
+
328
+ ---
329
+
131
330
  ## What's New in v3.6 — Gateway coordination seams
132
331
 
133
332
  ### Exact reservation preview
@@ -480,6 +679,7 @@ const bulkhead = createLLMBulkhead({
480
679
  import {
481
680
  naiveTokenEstimator,
482
681
  createModelAwareTokenEstimator,
682
+ createAdaptiveTokenEstimator,
483
683
  extractTextLength,
484
684
  } from 'async-bulkhead-llm';
485
685
 
@@ -498,6 +698,13 @@ const estimate = createModelAwareTokenEstimator(
498
698
 
499
699
  // Utility for multimodal content
500
700
  const charCount = extractTextLength(message.content);
701
+
702
+ // Self-calibrating wrapper (v3.8) — see "What's New in v3.8"
703
+ const adaptive = createAdaptiveTokenEstimator({ defaultModel: 'gpt-4o' });
704
+ adaptive.estimator; // pass as tokenBudget.estimator
705
+ adaptive.observe(request, usage); // feed actual usage (release event)
706
+ adaptive.corrections(); // per-model calibration snapshot
707
+ adaptive.reset(); // clear calibration
501
708
  ```
502
709
 
503
710
  ### Runtime Budget Adjustment
@@ -711,7 +918,14 @@ s.bulkhead.closed // true after close()
711
918
  s.llm.admitted
712
919
  s.llm.released
713
920
  s.llm.rejected
714
- s.llm.rejectedByReason?.budget_limit // true after close()
921
+ s.llm.rejectedByReason?.budget_limit
922
+
923
+ s.observe?.bypassed // v3.9: callbacks run without capacity
924
+ s.observe?.raceBypassed // advisory admit raced with rejection
925
+ s.observe?.bypassedByReason
926
+ s.observe?.usageReported
927
+ s.observe?.totalInputTokens
928
+ s.observe?.totalOutputTokens
715
929
 
716
930
  s.tokenBudget?.budget
717
931
  s.tokenBudget?.inFlightTokens
@@ -741,6 +955,17 @@ type LLMStats = {
741
955
  totalConsumed: number;
742
956
  totalRefunded: number;
743
957
  };
958
+ observe?: {
959
+ bypassed: number;
960
+ raceBypassed: number;
961
+ bypassedByReason: Partial<Record<
962
+ 'budget_limit' | 'concurrency_limit' | 'queue_limit' | 'timeout',
963
+ number
964
+ >>;
965
+ usageReported: number;
966
+ totalInputTokens: number;
967
+ totalOutputTokens: number;
968
+ };
744
969
  deduplication?: {
745
970
  active: number;
746
971
  hits: number;
@@ -768,6 +993,9 @@ off();
768
993
  | `reject` | `{ request, reason, detail? }` |
769
994
  | `usage` | `{ request, admissionId, priority, sequence, reservedTokens, previousHeldTokens, heldTokens, deltaTokens, usage, outputCap, outputRemaining, overReservation }` |
770
995
  | `release` | `{ request, admissionId, priority, reservedTokens, heldTokens, refundedTokens, usageSequence, usage? }` |
996
+ | `bypass` | `{ request, admissionId, priority, reason, detail?, reservation, raced }` |
997
+ | `bypassUsage` | `{ request, admissionId, priority, reason, sequence, reservation, usage, outputCap, outputRemaining, overReservation }` |
998
+ | `bypassRelease` | `{ request, admissionId, priority, reason, reservation, usageSequence, usage? }` |
771
999
  | `dedup` | `{ request }` |
772
1000
 
773
1001
  Listeners are synchronous and fire-and-forget. Exceptions are silently caught.
@@ -824,15 +1052,26 @@ run<T>(
824
1052
  timeoutMs?: number; // integer >= 0
825
1053
  priority?: 'normal' | 'high';
826
1054
  getUsage?: (result: T) => TokenUsage | undefined;
1055
+ mode?: 'enforce' | 'observe'; // default: 'enforce' (v3.9)
1056
+ shadowReasons?: readonly (
1057
+ | 'budget_limit'
1058
+ | 'concurrency_limit'
1059
+ | 'queue_limit'
1060
+ | 'timeout'
1061
+ )[];
827
1062
  dedupScope?: string; // dedup isolation scope (e.g. tenant / API key)
828
1063
  dedup?: boolean; // false = opt this call out of dedup (v3.5)
829
1064
  },
830
1065
  ): Promise<T>
831
1066
  ```
832
1067
 
833
- `ctx.admissionId` is the stable admission identifier. `ctx.reservation` is
834
- the exact reservation used at admission (or `null` when token budgeting is
835
- disabled), and `ctx.reportUsage()` reports cumulative streaming usage.
1068
+ `ctx.admissionId` is the stable execution identifier. In observe-mode
1069
+ bypasses it uses a `shadow-` prefix. `ctx.reservation` is the exact evaluated
1070
+ reservation (or `null` when token budgeting is disabled),
1071
+ `ctx.admission` distinguishes `"admitted"` from `"bypassed"`, and
1072
+ `ctx.bypassReason` / `ctx.bypassDetail` describe a bypass.
1073
+ `ctx.reportUsage()` reports cumulative streaming usage; bypassed usage is
1074
+ recorded for telemetry but never changes bulkhead capacity accounting.
836
1075
 
837
1076
  ### `bulkhead.estimate(request)`
838
1077
 
@@ -893,7 +1132,22 @@ See [Runtime Budget Adjustment](#runtime-budget-adjustment) for full semantics.
893
1132
  ### `bulkhead.close()`
894
1133
 
895
1134
 
896
- ### `bulkhead.drain()`
1135
+ ### `bulkhead.drain(opts?)`
1136
+
1137
+ ```ts
1138
+ drain(): Promise<void>;
1139
+ drain(opts: { timeoutMs: number }): Promise<LLMDrainResult>;
1140
+
1141
+ type LLMDrainResult = {
1142
+ drained: boolean; // true: everything completed within the deadline
1143
+ inFlight: number; // outstanding at the deadline (0 when drained)
1144
+ pending: number; // queued waiters at the deadline (0 when drained)
1145
+ };
1146
+ ```
1147
+
1148
+ Resolves when all in-flight work and pending waiters have completed. With
1149
+ `timeoutMs`, always resolves (never rejects) by the deadline with an
1150
+ `LLMDrainResult`; the deadline does not cancel in-flight work.
897
1151
 
898
1152
  ### `bulkhead.on(event, listener)`
899
1153
 
@@ -979,6 +1233,26 @@ See [CHANGELOG](./CHANGELOG.md) for the v2 migration guide.
979
1233
 
980
1234
  ---
981
1235
 
1236
+ ## Source Layout
1237
+
1238
+ The implementation is split into focused modules under `src/`; the package
1239
+ entry point (`src/index.ts`) is a barrel that re-exports the public API.
1240
+ Deep-importing the internal modules is not supported — the package
1241
+ `exports` map exposes only the entry point.
1242
+
1243
+ | Module | Contents |
1244
+ |---|---|
1245
+ | `types.ts` | Public request, result, options, stats, and event types (declarations only) |
1246
+ | `errors.ts` | `LLMBulkheadRejectedError` |
1247
+ | `profiles.ts` | `PROFILES` presets + `LLMBulkheadPreset` |
1248
+ | `estimators.ts` | `naiveTokenEstimator`, `createModelAwareTokenEstimator`, `opaqueBlockTokens` handling, `extractTextLength`, built-in ratio table |
1249
+ | `adaptive.ts` | `createAdaptiveTokenEstimator` (v3.8 self-calibration) |
1250
+ | `dedup.ts` | Deduplication internals: default whole-request key, scope-aware hashing, single-consumer result detection |
1251
+ | `validation.ts` | Internal numeric/estimate/usage guards (not re-exported) |
1252
+ | `bulkhead.ts` | `createLLMBulkhead`: admission, token budget + refund accounting, streaming usage reports, events, stats, shutdown |
1253
+
1254
+ ---
1255
+
982
1256
  ## Design Notes
983
1257
 
984
1258
  This library enforces backpressure at the boundary of your LLM calls. It does not replace higher-level concerns:
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createAdaptiveTokenEstimator = createAdaptiveTokenEstimator;
4
+ const estimators_js_1 = require("./estimators.cjs");
5
+ const validation_js_1 = require("./validation.cjs");
6
+ /**
7
+ * A self-calibrating wrapper around `createModelAwareTokenEstimator`
8
+ * (v3.8).
9
+ *
10
+ * Character-ratio estimation is ±15% at best and drifts with content
11
+ * mix (code vs prose vs CJK) and provider tokenizer changes. This
12
+ * estimator closes the loop: feed it actual usage from completed calls
13
+ * via `observe()`, and it maintains a per-model EWMA of
14
+ * `actual input / estimated input`, multiplying future *input*
15
+ * estimates by that factor (clamped, and only after `minSamples`
16
+ * observations). Output reservations are never corrected —
17
+ * `max_tokens` / `outputCap` is a ceiling, not an estimate.
18
+ *
19
+ * The correction applies to the **whole** input estimate, including
20
+ * any `opaqueBlockTokens` surcharge and `extraInputTokens` — the
21
+ * observed ratio necessarily includes those components too, so scaling
22
+ * the total is the self-consistent choice (the fixed point is
23
+ * "corrected estimate ≈ actual"). If your `extraInputTokens` values
24
+ * are exact, expect the factor to settle slightly differently than a
25
+ * pure-prose deployment; the clamps bound the damage either way.
26
+ *
27
+ * `observe()` always measures against the *uncorrected* base estimate,
28
+ * so feedback does not compound: an already-corrected estimator does
29
+ * not drag its own factor back toward 1.
30
+ *
31
+ * Not distributed and not persisted — calibration lives in this
32
+ * instance. Share one instance per bulkhead (create it, pass
33
+ * `.estimator` into `tokenBudget`, and subscribe `.observe` to the
34
+ * same bulkhead's `release` events).
35
+ */
36
+ function createAdaptiveTokenEstimator(opts = {}) {
37
+ const smoothing = opts.smoothing ?? 0.2;
38
+ if (typeof smoothing !== "number" ||
39
+ !Number.isFinite(smoothing) ||
40
+ smoothing <= 0 ||
41
+ smoothing > 1) {
42
+ throw new Error("smoothing must be a finite number in (0, 1]");
43
+ }
44
+ const minSamples = opts.minSamples ?? 5;
45
+ (0, validation_js_1.assertPositiveInteger)(minSamples, "minSamples");
46
+ const minCorrection = opts.minCorrection ?? 0.5;
47
+ if (typeof minCorrection !== "number" ||
48
+ !Number.isFinite(minCorrection) ||
49
+ minCorrection <= 0) {
50
+ throw new Error("minCorrection must be a finite number > 0");
51
+ }
52
+ const maxCorrection = opts.maxCorrection ?? 2;
53
+ if (typeof maxCorrection !== "number" ||
54
+ !Number.isFinite(maxCorrection) ||
55
+ maxCorrection < minCorrection) {
56
+ throw new Error("maxCorrection must be a finite number >= minCorrection");
57
+ }
58
+ const maxModels = opts.maxModels ?? 64;
59
+ (0, validation_js_1.assertPositiveInteger)(maxModels, "maxModels");
60
+ const base = (0, estimators_js_1.createModelAwareTokenEstimator)(opts.overrides, {
61
+ defaultModel: opts.defaultModel,
62
+ outputCap: opts.outputCap,
63
+ onUnknownModel: opts.onUnknownModel,
64
+ opaqueBlockTokens: opts.opaqueBlockTokens,
65
+ });
66
+ /** Insertion-ordered; oldest-inserted evicted at capacity. */
67
+ const models = new Map();
68
+ const modelKey = (request) => (request.model ?? opts.defaultModel ?? "").toLowerCase();
69
+ const appliedFactor = (state) => {
70
+ if (state === undefined || state.samples < minSamples)
71
+ return 1;
72
+ return Math.min(maxCorrection, Math.max(minCorrection, state.factor));
73
+ };
74
+ const estimator = (request) => {
75
+ const e = base(request);
76
+ const factor = appliedFactor(models.get(modelKey(request)));
77
+ if (factor === 1)
78
+ return e;
79
+ return {
80
+ input: Math.ceil(e.input * factor),
81
+ maxOutput: e.maxOutput,
82
+ };
83
+ };
84
+ function observe(request, usage) {
85
+ const valid = (0, validation_js_1.validateTokenUsage)(usage);
86
+ // Always ratio against the *uncorrected* base estimate so the
87
+ // feedback loop does not compound through its own corrections.
88
+ const baseInput = base(request).input;
89
+ if (baseInput <= 0)
90
+ return;
91
+ const observed = valid.input / baseInput;
92
+ const key = modelKey(request);
93
+ const state = models.get(key);
94
+ if (state === undefined) {
95
+ while (models.size >= maxModels) {
96
+ const oldest = models.keys().next().value;
97
+ if (oldest === undefined)
98
+ break;
99
+ models.delete(oldest);
100
+ }
101
+ models.set(key, { samples: 1, factor: observed });
102
+ return;
103
+ }
104
+ state.factor += smoothing * (observed - state.factor);
105
+ state.samples++;
106
+ }
107
+ function corrections() {
108
+ const out = [];
109
+ for (const [model, state] of models) {
110
+ out.push({
111
+ model,
112
+ samples: state.samples,
113
+ factor: state.factor,
114
+ applied: appliedFactor(state),
115
+ });
116
+ }
117
+ return out;
118
+ }
119
+ function reset(model) {
120
+ if (model === undefined) {
121
+ models.clear();
122
+ return;
123
+ }
124
+ models.delete(model.toLowerCase());
125
+ }
126
+ return { estimator, observe, corrections, reset };
127
+ }
128
+ //# sourceMappingURL=adaptive.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adaptive.cjs","sourceRoot":"","sources":["../../src/adaptive.ts"],"names":[],"mappings":";;AA4HA,oEA4GC;AAlOD,mDAGyB;AACzB,mDAA4E;AAoF5E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,SAAgB,4BAA4B,CAC1C,OAAsC,EAAE;IAExC,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,GAAG,CAAC;IACxC,IACE,OAAO,SAAS,KAAK,QAAQ;QAC7B,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC;QAC3B,SAAS,IAAI,CAAC;QACd,SAAS,GAAG,CAAC,EACb,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;IACjE,CAAC;IACD,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,IAAI,CAAC,CAAC;IACxC,IAAA,qCAAqB,EAAC,UAAU,EAAE,YAAY,CAAC,CAAC;IAChD,MAAM,aAAa,GAAG,IAAI,CA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