async-bulkhead-llm 1.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.
@@ -0,0 +1,343 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PROFILES = exports.LLMBulkheadRejectedError = void 0;
4
+ exports.naiveTokenEstimator = naiveTokenEstimator;
5
+ exports.createModelAwareTokenEstimator = createModelAwareTokenEstimator;
6
+ exports.createLLMBulkhead = createLLMBulkhead;
7
+ const async_bulkhead_ts_1 = require("async-bulkhead-ts");
8
+ class LLMBulkheadRejectedError extends Error {
9
+ reason;
10
+ code = "LLM_BULKHEAD_REJECTED";
11
+ constructor(reason) {
12
+ super(`LLM bulkhead rejected: ${reason}`);
13
+ this.reason = reason;
14
+ this.name = "LLMBulkheadRejectedError";
15
+ }
16
+ }
17
+ exports.LLMBulkheadRejectedError = LLMBulkheadRejectedError;
18
+ /**
19
+ * Built-in presets for common deployment patterns.
20
+ * Explicit options always override preset defaults.
21
+ * Pass a plain `LLMBulkheadPreset` object to escape the named presets entirely.
22
+ */
23
+ exports.PROFILES = {
24
+ interactive: { maxQueue: 0 },
25
+ batch: { maxQueue: 20, timeoutMs: 30_000 },
26
+ };
27
+ // ---- Estimator internals ----
28
+ const DEFAULT_OUTPUT_CAP = 2_048;
29
+ const NAIVE_CHAR_RATIO = 4.0;
30
+ /** Shared helper used by both estimators. */
31
+ function resolveMaxOutput(request, fallback) {
32
+ return request.max_tokens ?? fallback;
33
+ }
34
+ /**
35
+ * Estimates token usage using a flat 4-characters-per-token ratio.
36
+ *
37
+ * Accuracy: ±25% for English prose.
38
+ * Underestimates for code and non-Latin scripts.
39
+ * Suitable for load-shedding; not suitable for cost accounting.
40
+ */
41
+ function naiveTokenEstimator(request) {
42
+ const inputChars = request.messages.reduce((sum, m) => sum + m.content.length, 0);
43
+ return {
44
+ input: Math.ceil(inputChars / NAIVE_CHAR_RATIO),
45
+ maxOutput: resolveMaxOutput(request, DEFAULT_OUTPUT_CAP),
46
+ };
47
+ }
48
+ /**
49
+ * Per-model character-to-token ratios.
50
+ * Flat array of [prefix, ratio] pairs — longest matching prefix wins.
51
+ * Keyed at the model-family level; snapshot suffixes are handled by prefix matching.
52
+ */
53
+ const BUILT_IN_RATIOS = [
54
+ ["claude-3-5-haiku", 3.8],
55
+ ["claude-3-5-sonnet", 3.9],
56
+ ["claude-3-opus", 3.9],
57
+ ["claude-3-sonnet", 3.9],
58
+ ["claude-3-haiku", 3.8],
59
+ ["claude-sonnet-4", 3.9],
60
+ ["claude-opus-4", 3.9],
61
+ ["gpt-4o", 3.7],
62
+ ["gpt-4-turbo", 3.7],
63
+ ["gpt-4", 3.7],
64
+ ["gpt-3.5", 3.8],
65
+ ["o1", 3.7],
66
+ ["o3", 3.7],
67
+ ["gemini-1.5", 3.8],
68
+ ["gemini-2", 3.8],
69
+ ];
70
+ /**
71
+ * Estimates token usage using per-model character ratios.
72
+ *
73
+ * Accuracy: ±15% for known models on English prose.
74
+ * Falls back to naiveTokenEstimator (ratio 4.0) for unknown models.
75
+ * Extend the model map via the `overrides` parameter.
76
+ * Suitable for load-shedding; not suitable for cost accounting.
77
+ *
78
+ * Matching rules:
79
+ * - `overrides` keys are exact-matched first (case-sensitive as provided,
80
+ * also tried lowercased). Exact match always wins over prefix scan.
81
+ * - Built-in ratios are prefix-matched; longest prefix wins.
82
+ * - Model string is lowercased before prefix scan.
83
+ * - Unknown models fire `onUnknownModel` and fall back to ratio 4.0.
84
+ *
85
+ * Azure OpenAI deployment names (e.g. `'my-gpt4-prod'`) will not match any
86
+ * built-in prefix. Pass an override keyed on your deployment name, or
87
+ * provide `onUnknownModel` to surface the miss.
88
+ */
89
+ function createModelAwareTokenEstimator(overrides, opts = {}) {
90
+ const outputCap = opts.outputCap ?? DEFAULT_OUTPUT_CAP;
91
+ function lookupRatio(model) {
92
+ // Option B: exact overrides checked before prefix scan.
93
+ if (overrides) {
94
+ const exact = overrides[model] ?? overrides[model.toLowerCase()];
95
+ if (exact != null)
96
+ return exact;
97
+ }
98
+ // Prefix scan: lowercase, longest match wins.
99
+ const normalized = model.toLowerCase();
100
+ const matched = BUILT_IN_RATIOS.filter(([prefix]) => normalized.startsWith(prefix)).sort((a, b) => b[0].length - a[0].length)[0];
101
+ if (matched)
102
+ return matched[1];
103
+ opts.onUnknownModel?.(model);
104
+ return NAIVE_CHAR_RATIO;
105
+ }
106
+ return (request) => {
107
+ const model = opts.defaultModel ?? "";
108
+ const ratio = lookupRatio(model);
109
+ const inputChars = request.messages.reduce((sum, m) => sum + m.content.length, 0);
110
+ return {
111
+ input: Math.ceil(inputChars / ratio),
112
+ maxOutput: resolveMaxOutput(request, outputCap),
113
+ };
114
+ };
115
+ }
116
+ // ---- Option resolution ----
117
+ function resolvePreset(profile) {
118
+ if (!profile)
119
+ return {};
120
+ if (typeof profile === "string")
121
+ return exports.PROFILES[profile];
122
+ return profile;
123
+ }
124
+ // ---- createLLMBulkhead ----
125
+ function createLLMBulkhead(opts) {
126
+ // Validate
127
+ if (!opts.model || typeof opts.model !== "string") {
128
+ throw new Error("model must be a non-empty string");
129
+ }
130
+ if (!Number.isInteger(opts.maxConcurrent) || opts.maxConcurrent <= 0) {
131
+ throw new Error("maxConcurrent must be a positive integer");
132
+ }
133
+ // Resolve profile defaults; explicit opts always win
134
+ const preset = resolvePreset(opts.profile);
135
+ const maxQueue = opts.maxQueue ?? preset.maxQueue ?? 0;
136
+ const timeoutMs = opts.timeoutMs ?? preset.timeoutMs;
137
+ // Internal bulkhead from async-bulkhead-ts
138
+ const bulkhead = (0, async_bulkhead_ts_1.createBulkhead)({
139
+ maxConcurrent: opts.maxConcurrent,
140
+ maxQueue,
141
+ });
142
+ // ---- Token budget state ----
143
+ const budget = opts.tokenBudget;
144
+ const estimator = budget?.estimator ??
145
+ createModelAwareTokenEstimator(undefined, {
146
+ defaultModel: opts.model,
147
+ outputCap: budget?.outputCap,
148
+ });
149
+ let inFlightTokens = 0;
150
+ // ---- Deduplication state ----
151
+ // v1 key: JSON.stringify(messages). Key design deferred to v2.
152
+ const dedupMap = new Map();
153
+ let dedupHits = 0;
154
+ function createDeferred() {
155
+ let resolve;
156
+ let reject;
157
+ const promise = new Promise((res, rej) => {
158
+ resolve = res;
159
+ reject = rej;
160
+ });
161
+ return { promise, resolve, reject };
162
+ }
163
+ // ---- Internal helpers ----
164
+ /**
165
+ * Attempt token budget admission synchronously before queuing.
166
+ * Returns the reserved token count (0 when budget is disabled),
167
+ * or null if the budget ceiling is exceeded.
168
+ */
169
+ function tryReserveTokens(request) {
170
+ if (!budget)
171
+ return 0;
172
+ const estimate = estimator(request);
173
+ const needed = estimate.input + estimate.maxOutput;
174
+ if (inFlightTokens + needed > budget.budget)
175
+ return null;
176
+ inFlightTokens += needed;
177
+ return needed;
178
+ }
179
+ function releaseTokens(reserved) {
180
+ inFlightTokens = Math.max(0, inFlightTokens - reserved);
181
+ }
182
+ /**
183
+ * Wraps a base Token so that release() also returns the token reservation.
184
+ * The wrapped token is the single place that tracks both concerns atomically.
185
+ */
186
+ function wrapToken(base, reserved) {
187
+ let released = false;
188
+ return {
189
+ release() {
190
+ if (released)
191
+ return;
192
+ released = true;
193
+ try {
194
+ base.release();
195
+ }
196
+ finally {
197
+ releaseTokens(reserved);
198
+ }
199
+ },
200
+ };
201
+ }
202
+ // ---- Internal acquire ----
203
+ // Shared by the public `acquire()` and `run()` paths.
204
+ async function _acquire(request, ao) {
205
+ // Token budget: read-only pre-check before entering the queue.
206
+ // Do NOT reserve here — budget may shift while we wait.
207
+ if (budget) {
208
+ const estimate = estimator(request);
209
+ const needed = estimate.input + estimate.maxOutput;
210
+ if (inFlightTokens + needed > budget.budget)
211
+ return { ok: false, reason: "budget_limit" };
212
+ }
213
+ const mergedOptions = {};
214
+ if (ao.signal !== undefined)
215
+ mergedOptions.signal = ao.signal;
216
+ if (ao.timeoutMs !== undefined)
217
+ mergedOptions.timeoutMs = ao.timeoutMs;
218
+ else if (timeoutMs !== undefined)
219
+ mergedOptions.timeoutMs = timeoutMs;
220
+ const r = await bulkhead.acquire(mergedOptions);
221
+ if (!r.ok) {
222
+ return { ok: false, reason: r.reason };
223
+ }
224
+ // Post-admission: now reserve tokens. Re-check because other
225
+ // requests may have been admitted while this one was queued.
226
+ const reserved = tryReserveTokens(request);
227
+ if (reserved === null) {
228
+ r.token.release(); // return the concurrency slot
229
+ return { ok: false, reason: "budget_limit" };
230
+ }
231
+ return { ok: true, token: wrapToken(r.token, reserved) };
232
+ }
233
+ // ---- Public API ----
234
+ /**
235
+ * Acquire a slot manually.
236
+ *
237
+ * Advanced usage. Token budget reservations are not correctable post-call
238
+ * without `run()` in v1 (refund mechanism deferred to v2). For most
239
+ * use cases, prefer `run()`.
240
+ *
241
+ * Throws a `LLMBulkheadRejectedError` only indirectly via the returned
242
+ * `AcquireResult` — callers must check `r.ok`.
243
+ */
244
+ async function acquire(request, ao = {}) {
245
+ return _acquire(request, ao);
246
+ }
247
+ /**
248
+ * Primary API. Acquire → call `fn` → release, automatically.
249
+ *
250
+ * Throws `LLMBulkheadRejectedError` on rejection.
251
+ * The provided `AbortSignal` (if any) is passed through to `fn`,
252
+ * allowing in-flight work to observe cancellation.
253
+ *
254
+ * Note: cancellation affects admission only; in-flight work is not
255
+ * forcibly terminated by the bulkhead.
256
+ */
257
+ async function run(request, fn, ao = {}) {
258
+ let dedupKey = "";
259
+ if (opts.deduplication) {
260
+ try {
261
+ dedupKey = JSON.stringify(request.messages);
262
+ }
263
+ catch {
264
+ dedupKey = "";
265
+ }
266
+ }
267
+ let deferred;
268
+ // If we create a deferred, this is what BOTH leader and followers should await.
269
+ let resultPromise;
270
+ if (opts.deduplication && dedupKey !== "") {
271
+ const existing = dedupMap.get(dedupKey);
272
+ if (existing) {
273
+ dedupHits++;
274
+ return existing;
275
+ }
276
+ deferred = createDeferred();
277
+ resultPromise = deferred.promise;
278
+ dedupMap.set(dedupKey, deferred.promise);
279
+ const cleanup = () => {
280
+ try {
281
+ const p = dedupMap.get(dedupKey);
282
+ if (p === deferred.promise)
283
+ dedupMap.delete(dedupKey);
284
+ }
285
+ catch {
286
+ // never throw from cleanup
287
+ }
288
+ };
289
+ void deferred.promise.then(cleanup, cleanup);
290
+ }
291
+ try {
292
+ const r = await _acquire(request, ao);
293
+ if (!r.ok) {
294
+ throw new LLMBulkheadRejectedError(r.reason);
295
+ }
296
+ const work = (async () => {
297
+ try {
298
+ return await fn(ao.signal);
299
+ }
300
+ finally {
301
+ r.token.release();
302
+ }
303
+ })();
304
+ if (deferred) {
305
+ void work.then((v) => {
306
+ deferred.resolve(v);
307
+ }, (e) => {
308
+ deferred.reject(e);
309
+ });
310
+ return resultPromise; // leader awaits the same promise as followers
311
+ }
312
+ return work;
313
+ }
314
+ catch (err) {
315
+ if (deferred) {
316
+ deferred.reject(err);
317
+ return resultPromise; // IMPORTANT: avoid throwing here -> no unhandled deferred rejection
318
+ }
319
+ throw err;
320
+ }
321
+ }
322
+ /** Runtime stats. Optional fields are present only when the feature is enabled. */
323
+ function stats() {
324
+ const base = bulkhead.stats();
325
+ const result = { ...base };
326
+ if (budget) {
327
+ result.tokenBudget = {
328
+ budget: budget.budget,
329
+ inFlightTokens,
330
+ available: Math.max(0, budget.budget - inFlightTokens),
331
+ };
332
+ }
333
+ if (opts.deduplication) {
334
+ result.deduplication = {
335
+ active: dedupMap.size,
336
+ hits: dedupHits,
337
+ };
338
+ }
339
+ return result;
340
+ }
341
+ return { acquire, run, stats };
342
+ }
343
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AA6MA,kDASC;AAkED,wEAqCC;AAoBD,8CAoQC;AArlBD,yDAM2B;AAiD3B,MAAa,wBAAyB,SAAQ,KAAK;IAG5B;IAFZ,IAAI,GAAG,uBAAgC,CAAC;IAEjD,YAAqB,MAAuB;QAC1C,KAAK,CAAC,0BAA0B,MAAM,EAAE,CAAC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
+ reason;
4
+ code = "LLM_BULKHEAD_REJECTED";
5
+ constructor(reason) {
6
+ super(`LLM bulkhead rejected: ${reason}`);
7
+ this.reason = reason;
8
+ this.name = "LLMBulkheadRejectedError";
9
+ }
10
+ }
11
+ /**
12
+ * Built-in presets for common deployment patterns.
13
+ * Explicit options always override preset defaults.
14
+ * Pass a plain `LLMBulkheadPreset` object to escape the named presets entirely.
15
+ */
16
+ export const PROFILES = {
17
+ interactive: { maxQueue: 0 },
18
+ batch: { maxQueue: 20, timeoutMs: 30_000 },
19
+ };
20
+ // ---- Estimator internals ----
21
+ const DEFAULT_OUTPUT_CAP = 2_048;
22
+ const NAIVE_CHAR_RATIO = 4.0;
23
+ /** Shared helper used by both estimators. */
24
+ function resolveMaxOutput(request, fallback) {
25
+ return request.max_tokens ?? fallback;
26
+ }
27
+ /**
28
+ * Estimates token usage using a flat 4-characters-per-token ratio.
29
+ *
30
+ * Accuracy: ±25% for English prose.
31
+ * Underestimates for code and non-Latin scripts.
32
+ * Suitable for load-shedding; not suitable for cost accounting.
33
+ */
34
+ export function naiveTokenEstimator(request) {
35
+ const inputChars = request.messages.reduce((sum, m) => sum + m.content.length, 0);
36
+ return {
37
+ input: Math.ceil(inputChars / NAIVE_CHAR_RATIO),
38
+ maxOutput: resolveMaxOutput(request, DEFAULT_OUTPUT_CAP),
39
+ };
40
+ }
41
+ /**
42
+ * Per-model character-to-token ratios.
43
+ * Flat array of [prefix, ratio] pairs — longest matching prefix wins.
44
+ * Keyed at the model-family level; snapshot suffixes are handled by prefix matching.
45
+ */
46
+ const BUILT_IN_RATIOS = [
47
+ ["claude-3-5-haiku", 3.8],
48
+ ["claude-3-5-sonnet", 3.9],
49
+ ["claude-3-opus", 3.9],
50
+ ["claude-3-sonnet", 3.9],
51
+ ["claude-3-haiku", 3.8],
52
+ ["claude-sonnet-4", 3.9],
53
+ ["claude-opus-4", 3.9],
54
+ ["gpt-4o", 3.7],
55
+ ["gpt-4-turbo", 3.7],
56
+ ["gpt-4", 3.7],
57
+ ["gpt-3.5", 3.8],
58
+ ["o1", 3.7],
59
+ ["o3", 3.7],
60
+ ["gemini-1.5", 3.8],
61
+ ["gemini-2", 3.8],
62
+ ];
63
+ /**
64
+ * Estimates token usage using per-model character ratios.
65
+ *
66
+ * Accuracy: ±15% for known models on English prose.
67
+ * Falls back to naiveTokenEstimator (ratio 4.0) for unknown models.
68
+ * Extend the model map via the `overrides` parameter.
69
+ * Suitable for load-shedding; not suitable for cost accounting.
70
+ *
71
+ * Matching rules:
72
+ * - `overrides` keys are exact-matched first (case-sensitive as provided,
73
+ * also tried lowercased). Exact match always wins over prefix scan.
74
+ * - Built-in ratios are prefix-matched; longest prefix wins.
75
+ * - Model string is lowercased before prefix scan.
76
+ * - Unknown models fire `onUnknownModel` and fall back to ratio 4.0.
77
+ *
78
+ * Azure OpenAI deployment names (e.g. `'my-gpt4-prod'`) will not match any
79
+ * built-in prefix. Pass an override keyed on your deployment name, or
80
+ * provide `onUnknownModel` to surface the miss.
81
+ */
82
+ export function createModelAwareTokenEstimator(overrides, opts = {}) {
83
+ const outputCap = opts.outputCap ?? DEFAULT_OUTPUT_CAP;
84
+ function lookupRatio(model) {
85
+ // Option B: exact overrides checked before prefix scan.
86
+ if (overrides) {
87
+ const exact = overrides[model] ?? overrides[model.toLowerCase()];
88
+ if (exact != null)
89
+ return exact;
90
+ }
91
+ // Prefix scan: lowercase, longest match wins.
92
+ const normalized = model.toLowerCase();
93
+ const matched = BUILT_IN_RATIOS.filter(([prefix]) => normalized.startsWith(prefix)).sort((a, b) => b[0].length - a[0].length)[0];
94
+ if (matched)
95
+ return matched[1];
96
+ opts.onUnknownModel?.(model);
97
+ return NAIVE_CHAR_RATIO;
98
+ }
99
+ return (request) => {
100
+ const model = opts.defaultModel ?? "";
101
+ const ratio = lookupRatio(model);
102
+ const inputChars = request.messages.reduce((sum, m) => sum + m.content.length, 0);
103
+ return {
104
+ input: Math.ceil(inputChars / ratio),
105
+ maxOutput: resolveMaxOutput(request, outputCap),
106
+ };
107
+ };
108
+ }
109
+ // ---- Option resolution ----
110
+ function resolvePreset(profile) {
111
+ if (!profile)
112
+ return {};
113
+ if (typeof profile === "string")
114
+ return PROFILES[profile];
115
+ return profile;
116
+ }
117
+ // ---- createLLMBulkhead ----
118
+ export function createLLMBulkhead(opts) {
119
+ // Validate
120
+ if (!opts.model || typeof opts.model !== "string") {
121
+ throw new Error("model must be a non-empty string");
122
+ }
123
+ if (!Number.isInteger(opts.maxConcurrent) || opts.maxConcurrent <= 0) {
124
+ throw new Error("maxConcurrent must be a positive integer");
125
+ }
126
+ // Resolve profile defaults; explicit opts always win
127
+ const preset = resolvePreset(opts.profile);
128
+ const maxQueue = opts.maxQueue ?? preset.maxQueue ?? 0;
129
+ const timeoutMs = opts.timeoutMs ?? preset.timeoutMs;
130
+ // Internal bulkhead from async-bulkhead-ts
131
+ const bulkhead = createBulkhead({
132
+ maxConcurrent: opts.maxConcurrent,
133
+ maxQueue,
134
+ });
135
+ // ---- Token budget state ----
136
+ const budget = opts.tokenBudget;
137
+ const estimator = budget?.estimator ??
138
+ createModelAwareTokenEstimator(undefined, {
139
+ defaultModel: opts.model,
140
+ outputCap: budget?.outputCap,
141
+ });
142
+ let inFlightTokens = 0;
143
+ // ---- Deduplication state ----
144
+ // v1 key: JSON.stringify(messages). Key design deferred to v2.
145
+ const dedupMap = new Map();
146
+ let dedupHits = 0;
147
+ function createDeferred() {
148
+ let resolve;
149
+ let reject;
150
+ const promise = new Promise((res, rej) => {
151
+ resolve = res;
152
+ reject = rej;
153
+ });
154
+ return { promise, resolve, reject };
155
+ }
156
+ // ---- Internal helpers ----
157
+ /**
158
+ * Attempt token budget admission synchronously before queuing.
159
+ * Returns the reserved token count (0 when budget is disabled),
160
+ * or null if the budget ceiling is exceeded.
161
+ */
162
+ function tryReserveTokens(request) {
163
+ if (!budget)
164
+ return 0;
165
+ const estimate = estimator(request);
166
+ const needed = estimate.input + estimate.maxOutput;
167
+ if (inFlightTokens + needed > budget.budget)
168
+ return null;
169
+ inFlightTokens += needed;
170
+ return needed;
171
+ }
172
+ function releaseTokens(reserved) {
173
+ inFlightTokens = Math.max(0, inFlightTokens - reserved);
174
+ }
175
+ /**
176
+ * Wraps a base Token so that release() also returns the token reservation.
177
+ * The wrapped token is the single place that tracks both concerns atomically.
178
+ */
179
+ function wrapToken(base, reserved) {
180
+ let released = false;
181
+ return {
182
+ release() {
183
+ if (released)
184
+ return;
185
+ released = true;
186
+ try {
187
+ base.release();
188
+ }
189
+ finally {
190
+ releaseTokens(reserved);
191
+ }
192
+ },
193
+ };
194
+ }
195
+ // ---- Internal acquire ----
196
+ // Shared by the public `acquire()` and `run()` paths.
197
+ async function _acquire(request, ao) {
198
+ // Token budget: read-only pre-check before entering the queue.
199
+ // Do NOT reserve here — budget may shift while we wait.
200
+ if (budget) {
201
+ const estimate = estimator(request);
202
+ const needed = estimate.input + estimate.maxOutput;
203
+ if (inFlightTokens + needed > budget.budget)
204
+ return { ok: false, reason: "budget_limit" };
205
+ }
206
+ const mergedOptions = {};
207
+ if (ao.signal !== undefined)
208
+ mergedOptions.signal = ao.signal;
209
+ if (ao.timeoutMs !== undefined)
210
+ mergedOptions.timeoutMs = ao.timeoutMs;
211
+ else if (timeoutMs !== undefined)
212
+ mergedOptions.timeoutMs = timeoutMs;
213
+ const r = await bulkhead.acquire(mergedOptions);
214
+ if (!r.ok) {
215
+ return { ok: false, reason: r.reason };
216
+ }
217
+ // Post-admission: now reserve tokens. Re-check because other
218
+ // requests may have been admitted while this one was queued.
219
+ const reserved = tryReserveTokens(request);
220
+ if (reserved === null) {
221
+ r.token.release(); // return the concurrency slot
222
+ return { ok: false, reason: "budget_limit" };
223
+ }
224
+ return { ok: true, token: wrapToken(r.token, reserved) };
225
+ }
226
+ // ---- Public API ----
227
+ /**
228
+ * Acquire a slot manually.
229
+ *
230
+ * Advanced usage. Token budget reservations are not correctable post-call
231
+ * without `run()` in v1 (refund mechanism deferred to v2). For most
232
+ * use cases, prefer `run()`.
233
+ *
234
+ * Throws a `LLMBulkheadRejectedError` only indirectly via the returned
235
+ * `AcquireResult` — callers must check `r.ok`.
236
+ */
237
+ async function acquire(request, ao = {}) {
238
+ return _acquire(request, ao);
239
+ }
240
+ /**
241
+ * Primary API. Acquire → call `fn` → release, automatically.
242
+ *
243
+ * Throws `LLMBulkheadRejectedError` on rejection.
244
+ * The provided `AbortSignal` (if any) is passed through to `fn`,
245
+ * allowing in-flight work to observe cancellation.
246
+ *
247
+ * Note: cancellation affects admission only; in-flight work is not
248
+ * forcibly terminated by the bulkhead.
249
+ */
250
+ async function run(request, fn, ao = {}) {
251
+ let dedupKey = "";
252
+ if (opts.deduplication) {
253
+ try {
254
+ dedupKey = JSON.stringify(request.messages);
255
+ }
256
+ catch {
257
+ dedupKey = "";
258
+ }
259
+ }
260
+ let deferred;
261
+ // If we create a deferred, this is what BOTH leader and followers should await.
262
+ let resultPromise;
263
+ if (opts.deduplication && dedupKey !== "") {
264
+ const existing = dedupMap.get(dedupKey);
265
+ if (existing) {
266
+ dedupHits++;
267
+ return existing;
268
+ }
269
+ deferred = createDeferred();
270
+ resultPromise = deferred.promise;
271
+ dedupMap.set(dedupKey, deferred.promise);
272
+ const cleanup = () => {
273
+ try {
274
+ const p = dedupMap.get(dedupKey);
275
+ if (p === deferred.promise)
276
+ dedupMap.delete(dedupKey);
277
+ }
278
+ catch {
279
+ // never throw from cleanup
280
+ }
281
+ };
282
+ void deferred.promise.then(cleanup, cleanup);
283
+ }
284
+ try {
285
+ const r = await _acquire(request, ao);
286
+ if (!r.ok) {
287
+ throw new LLMBulkheadRejectedError(r.reason);
288
+ }
289
+ const work = (async () => {
290
+ try {
291
+ return await fn(ao.signal);
292
+ }
293
+ finally {
294
+ r.token.release();
295
+ }
296
+ })();
297
+ if (deferred) {
298
+ void work.then((v) => {
299
+ deferred.resolve(v);
300
+ }, (e) => {
301
+ deferred.reject(e);
302
+ });
303
+ return resultPromise; // leader awaits the same promise as followers
304
+ }
305
+ return work;
306
+ }
307
+ catch (err) {
308
+ if (deferred) {
309
+ deferred.reject(err);
310
+ return resultPromise; // IMPORTANT: avoid throwing here -> no unhandled deferred rejection
311
+ }
312
+ throw err;
313
+ }
314
+ }
315
+ /** Runtime stats. Optional fields are present only when the feature is enabled. */
316
+ function stats() {
317
+ const base = bulkhead.stats();
318
+ const result = { ...base };
319
+ if (budget) {
320
+ result.tokenBudget = {
321
+ budget: budget.budget,
322
+ inFlightTokens,
323
+ available: Math.max(0, budget.budget - inFlightTokens),
324
+ };
325
+ }
326
+ if (opts.deduplication) {
327
+ result.deduplication = {
328
+ active: dedupMap.size,
329
+ hits: dedupHits,
330
+ };
331
+ }
332
+ return result;
333
+ }
334
+ return { acquire, run, stats };
335
+ }
336
+ //# sourceMappingURL=index.js.map