@usagetap/sdk 1.3.2 → 1.7.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 (60) hide show
  1. package/README.md +372 -39
  2. package/dist/adapters/anthropic.cjs +995 -69
  3. package/dist/adapters/anthropic.cjs.map +1 -1
  4. package/dist/adapters/anthropic.d.cts +45 -3
  5. package/dist/adapters/anthropic.d.ts +45 -3
  6. package/dist/adapters/anthropic.mjs +995 -70
  7. package/dist/adapters/anthropic.mjs.map +1 -1
  8. package/dist/adapters/openai.cjs +1208 -106
  9. package/dist/adapters/openai.cjs.map +1 -1
  10. package/dist/adapters/openai.d.cts +46 -3
  11. package/dist/adapters/openai.d.ts +46 -3
  12. package/dist/adapters/openai.mjs +1208 -107
  13. package/dist/adapters/openai.mjs.map +1 -1
  14. package/dist/adapters/openrouter.cjs +3912 -53
  15. package/dist/adapters/openrouter.cjs.map +1 -1
  16. package/dist/adapters/openrouter.d.cts +6 -3
  17. package/dist/adapters/openrouter.d.ts +6 -3
  18. package/dist/adapters/openrouter.mjs +3910 -54
  19. package/dist/adapters/openrouter.mjs.map +1 -1
  20. package/dist/anthropic/index.cjs +995 -69
  21. package/dist/anthropic/index.cjs.map +1 -1
  22. package/dist/anthropic/index.d.cts +2 -2
  23. package/dist/anthropic/index.d.ts +2 -2
  24. package/dist/anthropic/index.mjs +995 -70
  25. package/dist/anthropic/index.mjs.map +1 -1
  26. package/dist/client-C0UiaqVB.d.cts +1305 -0
  27. package/dist/client-C0UiaqVB.d.ts +1305 -0
  28. package/dist/express/index.cjs +399 -64
  29. package/dist/express/index.cjs.map +1 -1
  30. package/dist/express/index.d.cts +2 -2
  31. package/dist/express/index.d.ts +2 -2
  32. package/dist/express/index.mjs +399 -64
  33. package/dist/express/index.mjs.map +1 -1
  34. package/dist/index.cjs +1044 -163
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +16 -5
  37. package/dist/index.d.ts +16 -5
  38. package/dist/index.mjs +1044 -163
  39. package/dist/index.mjs.map +1 -1
  40. package/dist/openai/index.cjs +1209 -107
  41. package/dist/openai/index.cjs.map +1 -1
  42. package/dist/openai/index.d.cts +2 -2
  43. package/dist/openai/index.d.ts +2 -2
  44. package/dist/openai/index.mjs +1209 -108
  45. package/dist/openai/index.mjs.map +1 -1
  46. package/dist/openrouter/index.cjs +1226 -109
  47. package/dist/openrouter/index.cjs.map +1 -1
  48. package/dist/openrouter/index.d.cts +3 -3
  49. package/dist/openrouter/index.d.ts +3 -3
  50. package/dist/openrouter/index.mjs +1224 -108
  51. package/dist/openrouter/index.mjs.map +1 -1
  52. package/dist/react/index.cjs +19 -1
  53. package/dist/react/index.cjs.map +1 -1
  54. package/dist/react/index.d.cts +17 -4
  55. package/dist/react/index.d.ts +17 -4
  56. package/dist/react/index.mjs +19 -1
  57. package/dist/react/index.mjs.map +1 -1
  58. package/package.json +2 -2
  59. package/dist/client-BD8O2J8Z.d.cts +0 -668
  60. package/dist/client-BD8O2J8Z.d.ts +0 -668
@@ -1,18 +1,2275 @@
1
1
  'use strict';
2
2
 
3
+ // src/errors.ts
4
+ var UsageTapError = class extends Error {
5
+ code;
6
+ status;
7
+ retryable;
8
+ correlationId;
9
+ details;
10
+ constructor(code, message, init = {}) {
11
+ super(message, init.cause ? { cause: init.cause } : void 0);
12
+ this.name = "UsageTapError";
13
+ this.code = code;
14
+ this.status = init.status;
15
+ this.retryable = init.retryable ?? false;
16
+ this.correlationId = init.correlationId;
17
+ this.details = init.details;
18
+ }
19
+ toJSON() {
20
+ return {
21
+ name: this.name,
22
+ message: this.message,
23
+ code: this.code,
24
+ status: this.status,
25
+ retryable: this.retryable,
26
+ correlationId: this.correlationId,
27
+ details: this.details
28
+ };
29
+ }
30
+ };
31
+ function isUsageTapError(error) {
32
+ return error instanceof UsageTapError;
33
+ }
34
+
35
+ // src/idempotency.ts
36
+ function createIdempotencyKey() {
37
+ if (typeof globalThis.crypto?.randomUUID === "function") {
38
+ return globalThis.crypto.randomUUID();
39
+ }
40
+ const random = () => Math.random().toString(16).slice(2, 10);
41
+ return `${random()}-${random()}`;
42
+ }
43
+
44
+ // src/retry.ts
45
+ var DEFAULTS = {
46
+ maxAttempts: 3,
47
+ baseDelayMs: 250,
48
+ maxDelayMs: 5e3,
49
+ jitterRatio: 0.2
50
+ };
51
+ function resolveRetryOptions(base, override) {
52
+ const merged = { ...DEFAULTS, ...base, ...override };
53
+ return {
54
+ maxAttempts: Math.max(1, Math.floor(merged.maxAttempts)),
55
+ baseDelayMs: Math.max(0, merged.baseDelayMs),
56
+ maxDelayMs: Math.max(merged.baseDelayMs, merged.maxDelayMs),
57
+ jitterRatio: Math.min(Math.max(merged.jitterRatio, 0), 1)
58
+ };
59
+ }
60
+ async function sleep(delayMs, signal) {
61
+ if (delayMs <= 0) {
62
+ signal?.throwIfAborted?.();
63
+ return;
64
+ }
65
+ await new Promise((resolve, reject) => {
66
+ const timer = setTimeout(() => {
67
+ cleanup();
68
+ resolve();
69
+ }, delayMs);
70
+ const cleanup = () => {
71
+ clearTimeout(timer);
72
+ signal?.removeEventListener("abort", onAbort);
73
+ };
74
+ const onAbort = () => {
75
+ cleanup();
76
+ const abortError = new Error("Aborted");
77
+ abortError.name = "AbortError";
78
+ reject(abortError);
79
+ };
80
+ if (signal) {
81
+ if (signal.aborted) {
82
+ onAbort();
83
+ return;
84
+ }
85
+ signal.addEventListener("abort", onAbort, { once: true });
86
+ }
87
+ });
88
+ }
89
+ function computeDelay(attempt, options) {
90
+ const exp = options.baseDelayMs * Math.pow(2, attempt - 1);
91
+ const capped = Math.min(exp, options.maxDelayMs);
92
+ const jitter = capped * options.jitterRatio;
93
+ const min = capped - jitter;
94
+ const max = capped + jitter;
95
+ return Math.max(0, Math.random() * (max - min) + min);
96
+ }
97
+ async function runWithRetry(operation, options, shouldRetry, onSchedule, signal) {
98
+ let attempt = 0;
99
+ let lastError;
100
+ while (attempt < options.maxAttempts) {
101
+ attempt += 1;
102
+ signal?.throwIfAborted?.();
103
+ try {
104
+ return await operation(attempt);
105
+ } catch (error) {
106
+ lastError = error;
107
+ if (attempt >= options.maxAttempts || !shouldRetry(error)) {
108
+ throw error;
109
+ }
110
+ const delayMs = computeDelay(attempt, options);
111
+ onSchedule?.(attempt, delayMs, error);
112
+ await sleep(delayMs, signal);
113
+ }
114
+ }
115
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
116
+ }
117
+
118
+ // src/prompt-compression.ts
119
+ var DEFAULT_TTC_ENDPOINT = "https://api.thetokencompany.com/v1/compress";
120
+ var DEFAULT_TTC_MODEL = "bear-2";
121
+ var DEFAULT_TTC_AGGRESSIVENESS = 0.2;
122
+ var DEFAULT_USAGETAP_COMPRESSION_ENDPOINT = "https://compress.usagetap.com/v1/compress";
123
+ var DEFAULT_USAGETAP_MESSAGES_COMPRESSION_ENDPOINT = "https://compress.usagetap.com/v1/messages/compress";
124
+ var PROTECTED_TEXT_PATTERN = /<ttc_safe>[\s\S]*?<\/ttc_safe>|<usagetap_safe>[\s\S]*?<\/usagetap_safe>/g;
125
+ async function compressPrompt(options) {
126
+ const input = resolvePromptCompressionInput(options);
127
+ try {
128
+ if (options.provider === "usagetap") {
129
+ return await compressWithUsageTap(options);
130
+ }
131
+ if (options.provider === "thetokencompany" || options.tokenCompanyApiKey) {
132
+ return await compressWithTheTokenCompany(options);
133
+ }
134
+ if (options.provider === "toon") {
135
+ return compressPromptToon(input);
136
+ }
137
+ return compressPromptHeuristic(input);
138
+ } catch (error) {
139
+ if (options.failOpen === false) {
140
+ throw error;
141
+ }
142
+ return createPromptCompressionFallback(
143
+ input,
144
+ options.provider ?? (options.tokenCompanyApiKey ? "thetokencompany" : "heuristic"),
145
+ error
146
+ );
147
+ }
148
+ }
149
+ function compressPromptHeuristic(input) {
150
+ const original = stableStringifyInput(input);
151
+ const techniques = /* @__PURE__ */ new Set();
152
+ const compressedInput = compressValue(input, techniques, { allowToonString: false });
153
+ const compressed = stableStringifyInput(compressedInput);
154
+ const chosenInput = compressed.length <= original.length ? compressedInput : input;
155
+ const chosen = compressed.length <= original.length ? compressed : original;
156
+ if (!techniques.size) {
157
+ techniques.add("no-op");
158
+ }
159
+ return buildResult(
160
+ input,
161
+ chosenInput,
162
+ "heuristic",
163
+ original,
164
+ chosen,
165
+ Array.from(techniques)
166
+ );
167
+ }
168
+ function compressPromptToon(input) {
169
+ const original = stableStringifyInput(input);
170
+ const compressedInput = typeof input === "string" ? compressText(input, /* @__PURE__ */ new Set(), { allowToonString: true }) : encodeToon(input);
171
+ const compressed = stableStringifyInput(compressedInput);
172
+ return buildResult(input, compressedInput, "toon", original, compressed, [
173
+ "toon",
174
+ "json-minify"
175
+ ]);
176
+ }
177
+ async function compressPromptMessages(options) {
178
+ try {
179
+ return await compressMessagesWithUsageTap(options);
180
+ } catch (error) {
181
+ if (options.failOpen === false) {
182
+ throw error;
183
+ }
184
+ return createPromptCompressionFallback(
185
+ options.input,
186
+ options.provider ?? "usagetap",
187
+ error
188
+ );
189
+ }
190
+ }
191
+ async function compressWithTheTokenCompany(options) {
192
+ if (!options.tokenCompanyApiKey) {
193
+ throw new Error(
194
+ "tokenCompanyApiKey is required when provider is thetokencompany"
195
+ );
196
+ }
197
+ const fetchCandidate = options.fetchImpl ?? globalThis.fetch;
198
+ if (typeof fetchCandidate !== "function") {
199
+ throw new Error(
200
+ "A fetch implementation is required for The Token Company compression"
201
+ );
202
+ }
203
+ return compressWithCompatibleRemoteProvider({
204
+ options,
205
+ provider: "thetokencompany",
206
+ endpoint: options.tokenCompanyEndpoint ?? DEFAULT_TTC_ENDPOINT,
207
+ model: options.model ?? options.tokenCompanyModel ?? DEFAULT_TTC_MODEL,
208
+ aggressiveness: options.aggressiveness ?? options.tokenCompanyAggressiveness ?? DEFAULT_TTC_AGGRESSIVENESS,
209
+ apiKey: options.tokenCompanyApiKey,
210
+ appId: options.tokenCompanyAppId,
211
+ providerLabel: "The Token Company"
212
+ });
213
+ }
214
+ async function compressWithUsageTap(options) {
215
+ const fetchCandidate = options.fetchImpl ?? globalThis.fetch;
216
+ if (typeof fetchCandidate !== "function") {
217
+ throw new Error(
218
+ "A fetch implementation is required for UsageTap prompt compression"
219
+ );
220
+ }
221
+ return compressWithCompatibleRemoteProvider({
222
+ options,
223
+ provider: "usagetap",
224
+ endpoint: options.usageTapCompressionEndpoint ?? DEFAULT_USAGETAP_COMPRESSION_ENDPOINT,
225
+ model: options.model ?? options.usageTapCompressionModel ?? options.tokenCompanyModel ?? DEFAULT_TTC_MODEL,
226
+ aggressiveness: options.aggressiveness ?? options.usageTapCompressionAggressiveness ?? options.tokenCompanyAggressiveness ?? DEFAULT_TTC_AGGRESSIVENESS,
227
+ apiKey: options.usageTapCompressionApiKey,
228
+ appId: options.tokenCompanyAppId,
229
+ providerLabel: "UsageTap prompt compression"
230
+ });
231
+ }
232
+ async function compressMessagesWithUsageTap(options) {
233
+ const fetchCandidate = options.fetchImpl ?? globalThis.fetch;
234
+ if (typeof fetchCandidate !== "function") {
235
+ throw new Error(
236
+ "A fetch implementation is required for UsageTap prompt message compression"
237
+ );
238
+ }
239
+ const aggressiveness = options.aggressiveness ?? options.usageTapCompressionAggressiveness ?? DEFAULT_TTC_AGGRESSIVENESS;
240
+ validateAggressiveness(
241
+ aggressiveness,
242
+ "UsageTap prompt message compression"
243
+ );
244
+ if (options.latencyBudgetMs !== void 0 && (!Number.isFinite(options.latencyBudgetMs) || options.latencyBudgetMs < 0)) {
245
+ throw new Error(
246
+ "UsageTap prompt message compression latencyBudgetMs must be a non-negative number"
247
+ );
248
+ }
249
+ const original = stableStringifyInput(options.input);
250
+ const headers = {
251
+ "content-type": "application/json"
252
+ };
253
+ if (options.usageTapCompressionApiKey) {
254
+ headers.authorization = `Bearer ${options.usageTapCompressionApiKey}`;
255
+ }
256
+ const response = await fetchCandidate(
257
+ options.usageTapCompressionMessagesEndpoint ?? DEFAULT_USAGETAP_MESSAGES_COMPRESSION_ENDPOINT,
258
+ {
259
+ method: "POST",
260
+ headers,
261
+ body: JSON.stringify({
262
+ ...cloneInputRecord(options.input),
263
+ compression_settings: {
264
+ aggressiveness,
265
+ ...options.mode === void 0 ? {} : { mode: options.mode },
266
+ ...options.latencyBudgetMs === void 0 ? {} : { latency_budget_ms: options.latencyBudgetMs },
267
+ ...options.compactEmptyUserMessages === void 0 ? {} : { compact_empty_user_messages: options.compactEmptyUserMessages },
268
+ ...options.compactDuplicateUserTextParts === void 0 ? {} : {
269
+ compact_duplicate_user_text_parts: options.compactDuplicateUserTextParts
270
+ }
271
+ }
272
+ }),
273
+ signal: options.signal
274
+ }
275
+ );
276
+ if (!response.ok) {
277
+ throw new Error(
278
+ `UsageTap prompt message compression failed with HTTP ${response.status}`
279
+ );
280
+ }
281
+ const payload = await response.json();
282
+ const compressedInput = payload.compressed_request ?? payload.compressedInput ?? payload.compressed ?? (payload.messages !== void 0 ? { ...cloneInputRecord(options.input), messages: payload.messages } : void 0);
283
+ if (compressedInput === void 0) {
284
+ throw new Error(
285
+ "UsageTap prompt message compression response did not include compressed content"
286
+ );
287
+ }
288
+ const compressed = stableStringifyInput(compressedInput);
289
+ const tokenCounts = normalizeCompatibleTokenCounts(payload);
290
+ return buildResult(
291
+ options.input,
292
+ compressedInput,
293
+ "usagetap",
294
+ original,
295
+ compressed,
296
+ ["usagetap", "messages-endpoint"],
297
+ tokenCounts
298
+ );
299
+ }
300
+ async function compressWithCompatibleRemoteProvider(args) {
301
+ const { options, provider, endpoint, model, aggressiveness, apiKey, appId, providerLabel } = args;
302
+ const fetchCandidate = options.fetchImpl ?? globalThis.fetch;
303
+ const sourceInput = resolvePromptCompressionInput(options);
304
+ const original = stableStringifyInput(sourceInput);
305
+ const heuristic = compressPromptHeuristic(sourceInput);
306
+ const input = typeof heuristic.compressedInput === "string" ? heuristic.compressedInput : stableStringifyInput(heuristic.compressedInput);
307
+ if (!isValidAggressiveness(aggressiveness)) {
308
+ throw new Error(`${providerLabel} aggressiveness must be between 0.0 and 1.0`);
309
+ }
310
+ const headers = {
311
+ "content-type": "application/json"
312
+ };
313
+ if (apiKey) {
314
+ headers.authorization = `Bearer ${apiKey}`;
315
+ }
316
+ const response = await fetchCandidate(
317
+ endpoint,
318
+ {
319
+ method: "POST",
320
+ headers,
321
+ body: JSON.stringify({
322
+ model,
323
+ input,
324
+ ...provider === "usagetap" ? { text: input } : {},
325
+ compression_settings: { aggressiveness },
326
+ ...appId ? { app_id: appId } : {}
327
+ }),
328
+ signal: options.signal
329
+ }
330
+ );
331
+ if (!response.ok) {
332
+ throw new Error(
333
+ `${providerLabel} failed with HTTP ${response.status}`
334
+ );
335
+ }
336
+ const payload = await response.json();
337
+ const tokenCompanyResult = normalizeTheTokenCompanyCompressResponse(payload);
338
+ const compressedInput = payload.compressedInput ?? payload.compressed ?? tokenCompanyResult?.output ?? payload.output ?? payload.text;
339
+ if (compressedInput === void 0) {
340
+ throw new Error(`${providerLabel} response did not include compressed content`);
341
+ }
342
+ const compressed = stableStringifyInput(compressedInput);
343
+ const tokenCounts = tokenCompanyResult ? {
344
+ originalTokens: tokenCompanyResult.input_tokens,
345
+ compressedTokens: tokenCompanyResult.output_tokens,
346
+ savedTokens: tokenCompanyResult.tokens_saved
347
+ } : void 0;
348
+ return buildResult(
349
+ sourceInput,
350
+ compressedInput,
351
+ provider,
352
+ original,
353
+ compressed,
354
+ [...heuristic.techniques, provider],
355
+ tokenCounts
356
+ );
357
+ }
358
+ function resolvePromptCompressionInput(options) {
359
+ if (options.input !== void 0) {
360
+ return options.input;
361
+ }
362
+ if (options.text !== void 0) {
363
+ return options.text;
364
+ }
365
+ throw new Error("Prompt compression requires input or text");
366
+ }
367
+ function validateAggressiveness(value, label) {
368
+ if (typeof value === "number") {
369
+ if (!isValidAggressiveness(value)) {
370
+ throw new Error(`${label} aggressiveness must be between 0.0 and 1.0`);
371
+ }
372
+ return;
373
+ }
374
+ for (const aggressiveness of Object.values(value)) {
375
+ if (aggressiveness !== void 0 && !isValidAggressiveness(aggressiveness)) {
376
+ throw new Error(`${label} aggressiveness must be between 0.0 and 1.0`);
377
+ }
378
+ }
379
+ }
380
+ function isValidAggressiveness(value) {
381
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
382
+ }
383
+ function cloneInputRecord(input) {
384
+ return input && typeof input === "object" && !Array.isArray(input) ? { ...input } : { input };
385
+ }
386
+ function normalizeCompatibleTokenCounts(data) {
387
+ const inputTokens = typeof data.input_tokens === "number" ? data.input_tokens : data.original_input_tokens;
388
+ const outputTokens = data.output_tokens;
389
+ if (typeof inputTokens !== "number" || typeof outputTokens !== "number") {
390
+ return void 0;
391
+ }
392
+ return {
393
+ originalTokens: inputTokens,
394
+ compressedTokens: outputTokens,
395
+ savedTokens: typeof data.tokens_saved === "number" ? data.tokens_saved : inputTokens - outputTokens
396
+ };
397
+ }
398
+ function normalizeTheTokenCompanyCompressResponse(data) {
399
+ if (typeof data.output !== "string" || typeof data.output_tokens !== "number") {
400
+ return void 0;
401
+ }
402
+ const inputTokens = typeof data.input_tokens === "number" ? data.input_tokens : data.original_input_tokens;
403
+ if (typeof inputTokens !== "number") {
404
+ return void 0;
405
+ }
406
+ const tokensSaved = typeof data.tokens_saved === "number" ? data.tokens_saved : inputTokens - data.output_tokens;
407
+ const compressionRatio = typeof data.compression_ratio === "number" ? data.compression_ratio : data.output_tokens === 0 ? 0 : inputTokens / data.output_tokens;
408
+ return {
409
+ output: data.output,
410
+ output_tokens: data.output_tokens,
411
+ input_tokens: inputTokens,
412
+ tokens_saved: tokensSaved,
413
+ compression_ratio: compressionRatio
414
+ };
415
+ }
416
+ function createPromptCompressionFallback(input, provider = "heuristic", error) {
417
+ const original = stableStringifyInput(input);
418
+ const techniques = ["fallback-original"];
419
+ if (error) {
420
+ techniques.push("compression-error");
421
+ }
422
+ return buildResult(input, input, provider, original, original, techniques);
423
+ }
424
+ function buildResult(input, compressedInput, provider, original, compressed, techniques, tokenCounts) {
425
+ const originalCharacters = original.length;
426
+ const compressedCharacters = compressed.length;
427
+ const savedCharacters = Math.max(
428
+ 0,
429
+ originalCharacters - compressedCharacters
430
+ );
431
+ const originalTokens = tokenCounts?.originalTokens ?? estimatePromptTokens(original);
432
+ const compressedTokens = tokenCounts?.compressedTokens ?? estimatePromptTokens(compressed);
433
+ const savedTokens = Math.max(
434
+ 0,
435
+ tokenCounts?.savedTokens ?? originalTokens - compressedTokens
436
+ );
437
+ return {
438
+ input,
439
+ compressedInput,
440
+ provider,
441
+ originalCharacters,
442
+ compressedCharacters,
443
+ savedCharacters,
444
+ originalTokens,
445
+ compressedTokens,
446
+ savedTokens,
447
+ tokenSavingsRatio: originalTokens > 0 ? savedTokens / originalTokens : 0,
448
+ savingsRatio: originalCharacters > 0 ? savedCharacters / originalCharacters : 0,
449
+ techniques
450
+ };
451
+ }
452
+ function estimatePromptTokens(input) {
453
+ const text = typeof input === "string" ? input : stableStringifyInput(input);
454
+ return text.match(/[\p{L}\p{N}]+|[^\s]/gu)?.length ?? 0;
455
+ }
456
+ function compressValue(value, techniques, options) {
457
+ if (typeof value === "string") return compressText(value, techniques, options);
458
+ if (Array.isArray(value)) {
459
+ techniques.add("json-minify");
460
+ return value.map((item) => compressValue(item, techniques, options));
461
+ }
462
+ if (value && typeof value === "object") {
463
+ techniques.add("json-minify");
464
+ return Object.keys(value).reduce((acc, key) => {
465
+ const child = value[key];
466
+ if (child !== void 0) {
467
+ acc[key] = compressValue(child, techniques, options);
468
+ }
469
+ return acc;
470
+ }, {});
471
+ }
472
+ return value;
473
+ }
474
+ function compressText(value, techniques, options) {
475
+ const protectedSpans = [];
476
+ const text = value.replace(PROTECTED_TEXT_PATTERN, (match) => {
477
+ const placeholder = `__USAGETAP_PROTECTED_${protectedSpans.length}__`;
478
+ protectedSpans.push(match);
479
+ techniques.add("protected-text");
480
+ return placeholder;
481
+ });
482
+ const compressed = compressTextWithoutProtection(text, techniques, options);
483
+ return protectedSpans.reduce(
484
+ (output, span, index) => output.replace(`__USAGETAP_PROTECTED_${index}__`, span),
485
+ compressed
486
+ );
487
+ }
488
+ function compressTextWithoutProtection(value, techniques, options) {
489
+ const fencePattern = /```([\w-]+)?\n([\s\S]*?)```/g;
490
+ const parts = [];
491
+ let cursor = 0;
492
+ let match;
493
+ while ((match = fencePattern.exec(value)) !== null) {
494
+ const before = value.slice(cursor, match.index);
495
+ const compressedBefore = compressPlainTextAndEmbeddedJson(
496
+ before,
497
+ techniques,
498
+ options
499
+ );
500
+ if (compressedBefore) parts.push(compressedBefore);
501
+ const lang = match[1]?.toLowerCase();
502
+ const code = cleanCodeBlock(match[2] ?? "");
503
+ const compressedCode = lang === "json" ? compressJsonText(code, techniques, options) : void 0;
504
+ if (compressedCode?.format === "toon") {
505
+ parts.push(`\`\`\`toon
506
+ ${compressedCode.text}
507
+ \`\`\``);
508
+ } else if (compressedCode?.format === "json") {
509
+ parts.push(`\`\`\`json
510
+ ${compressedCode.text}
511
+ \`\`\``);
512
+ } else {
513
+ if (code !== match[2]) {
514
+ techniques.add("code-whitespace");
515
+ }
516
+ parts.push(lang ? `\`\`\`${lang}
517
+ ${code}
518
+ \`\`\`` : `\`\`\`
519
+ ${code}
520
+ \`\`\``);
521
+ }
522
+ cursor = match.index + match[0].length;
523
+ }
524
+ const after = compressPlainTextAndEmbeddedJson(value.slice(cursor), techniques, options);
525
+ if (after) parts.push(after);
526
+ return parts.join("\n").trim();
527
+ }
528
+ function compressPlainText(value, techniques) {
529
+ const compressed = value.split("\n").map((line) => line.trim()).filter((line) => line).join("\n").replace(/[ \t]{2,}/g, " ").trim();
530
+ if (compressed !== value.trim()) {
531
+ techniques.add("text-whitespace");
532
+ }
533
+ return compressed;
534
+ }
535
+ function compressPlainTextAndEmbeddedJson(value, techniques, options) {
536
+ const normalized = compressPlainText(value, techniques);
537
+ return compressEmbeddedJson(normalized, techniques, options);
538
+ }
539
+ function cleanCodeBlock(code) {
540
+ const lines = code.replace(/\r\n/g, "\n").split("\n");
541
+ while (lines.length && lines[0].trim() === "") lines.shift();
542
+ while (lines.length && lines[lines.length - 1].trim() === "") lines.pop();
543
+ const commonIndent = lines.filter((line) => line.trim()).reduce((min, line) => {
544
+ const indent = /^[ \t]*/.exec(line)?.[0].length ?? 0;
545
+ return min === void 0 ? indent : Math.min(min, indent);
546
+ }, void 0);
547
+ return lines.map((line) => commonIndent ? line.slice(commonIndent) : line).join("\n").replace(/[ \t]+$/gm, "");
548
+ }
549
+ function stableStringifyInput(input) {
550
+ if (typeof input === "string") return input;
551
+ return JSON.stringify(input) ?? String(input);
552
+ }
553
+ function compressJsonText(text, techniques, options) {
554
+ const parsed = safeParseJson(text);
555
+ if (parsed === void 0) {
556
+ return void 0;
557
+ }
558
+ const compactJson = JSON.stringify(parsed);
559
+ const candidates = [
560
+ { format: "json", text: compactJson }
561
+ ];
562
+ if (options.allowToonString || shouldUseToonForJson(parsed)) {
563
+ candidates.push({ format: "toon", text: encodeToon(parsed) });
564
+ }
565
+ const originalLength = text.trim().length;
566
+ const best = candidates.reduce(
567
+ (winner, candidate) => candidate.text.length < winner.text.length ? candidate : winner
568
+ );
569
+ if (best.text.length >= originalLength) {
570
+ return void 0;
571
+ }
572
+ techniques.add(best.format === "toon" ? "embedded-json-toon" : "embedded-json-minify");
573
+ return best;
574
+ }
575
+ function compressEmbeddedJson(text, techniques, options) {
576
+ let result = "";
577
+ let cursor = 0;
578
+ while (cursor < text.length) {
579
+ const start = findNextJsonStart(text, cursor);
580
+ if (start < 0) {
581
+ result += text.slice(cursor);
582
+ break;
583
+ }
584
+ result += text.slice(cursor, start);
585
+ const span = findBalancedJsonSpan(text, start);
586
+ if (!span) {
587
+ result += text[start];
588
+ cursor = start + 1;
589
+ continue;
590
+ }
591
+ const candidate = compressJsonText(span.text, techniques, options);
592
+ if (candidate) {
593
+ result += candidate.text;
594
+ } else {
595
+ result += span.text;
596
+ }
597
+ cursor = span.end;
598
+ }
599
+ return result;
600
+ }
601
+ function findNextJsonStart(text, from) {
602
+ const objectStart = text.indexOf("{", from);
603
+ const arrayStart = text.indexOf("[", from);
604
+ if (objectStart < 0) return arrayStart;
605
+ if (arrayStart < 0) return objectStart;
606
+ return Math.min(objectStart, arrayStart);
607
+ }
608
+ function findBalancedJsonSpan(text, start) {
609
+ const opener = text[start];
610
+ const closer = opener === "{" ? "}" : opener === "[" ? "]" : void 0;
611
+ if (!closer) return void 0;
612
+ const stack = [closer];
613
+ let inString = false;
614
+ let escaped = false;
615
+ for (let index = start + 1; index < text.length; index += 1) {
616
+ const char = text[index];
617
+ if (inString) {
618
+ if (escaped) {
619
+ escaped = false;
620
+ } else if (char === "\\") {
621
+ escaped = true;
622
+ } else if (char === '"') {
623
+ inString = false;
624
+ }
625
+ continue;
626
+ }
627
+ if (char === '"') {
628
+ inString = true;
629
+ continue;
630
+ }
631
+ if (char === "{" || char === "[") {
632
+ stack.push(char === "{" ? "}" : "]");
633
+ continue;
634
+ }
635
+ if (char === stack[stack.length - 1]) {
636
+ stack.pop();
637
+ if (!stack.length) {
638
+ const end = index + 1;
639
+ return { text: text.slice(start, end), end };
640
+ }
641
+ }
642
+ }
643
+ return void 0;
644
+ }
645
+ function safeParseJson(text) {
646
+ try {
647
+ return JSON.parse(text);
648
+ } catch {
649
+ return void 0;
650
+ }
651
+ }
652
+ function shouldUseToonForJson(value) {
653
+ if (Array.isArray(value)) {
654
+ return isUniformObjectArray(value) || value.some(shouldUseToonForJson);
655
+ }
656
+ if (isPlainObject(value)) {
657
+ return Object.values(value).some(shouldUseToonForJson);
658
+ }
659
+ return false;
660
+ }
661
+ function encodeToon(value, indent = 0) {
662
+ if (isPrimitive(value)) {
663
+ return scalarToToon(value);
664
+ }
665
+ if (Array.isArray(value)) {
666
+ return encodeArrayToon(value, indent);
667
+ }
668
+ if (isPlainObject(value)) {
669
+ const lines = [];
670
+ for (const [key, child] of Object.entries(value)) {
671
+ lines.push(...encodePropertyToon(key, child, indent));
672
+ }
673
+ return lines.join("\n");
674
+ }
675
+ return scalarToToon(String(value));
676
+ }
677
+ function encodePropertyToon(key, value, indent) {
678
+ const prefix = " ".repeat(indent);
679
+ const toonKey = keyToToon(key);
680
+ if (isPrimitive(value)) {
681
+ return [`${prefix}${toonKey}: ${scalarToToon(value)}`];
682
+ }
683
+ if (Array.isArray(value)) {
684
+ if (value.every(isPrimitive)) {
685
+ return [`${prefix}${toonKey}[${value.length}]: ${value.map(scalarToToon).join(",")}`];
686
+ }
687
+ if (isUniformObjectArray(value)) {
688
+ const fields = Object.keys(value[0]);
689
+ const header = `${prefix}${toonKey}[${value.length}]{${fields.map(keyToToon).join(",")}}:`;
690
+ const rows = value.map(
691
+ (item) => `${" ".repeat(indent + 2)}${fields.map(
692
+ (field) => scalarToToon(item[field])
693
+ ).join(",")}`
694
+ );
695
+ return [header, ...rows];
696
+ }
697
+ return [
698
+ `${prefix}${toonKey}[${value.length}]:`,
699
+ ...value.flatMap((item, index) => {
700
+ if (isPrimitive(item)) {
701
+ return [`${" ".repeat(indent + 2)}- ${scalarToToon(item)}`];
702
+ }
703
+ return [
704
+ `${" ".repeat(indent + 2)}- item${index}:`,
705
+ ...encodeToon(item, indent + 4).split("\n")
706
+ ];
707
+ })
708
+ ];
709
+ }
710
+ return [`${prefix}${toonKey}:`, ...encodeToon(value, indent + 2).split("\n")];
711
+ }
712
+ function encodeArrayToon(value, indent) {
713
+ if (value.every(isPrimitive)) {
714
+ return `[${value.length}]: ${value.map(scalarToToon).join(",")}`;
715
+ }
716
+ if (isUniformObjectArray(value)) {
717
+ const fields = Object.keys(value[0]);
718
+ return [
719
+ `[${value.length}]{${fields.map(keyToToon).join(",")}}:`,
720
+ ...value.map(
721
+ (item) => `${" ".repeat(indent + 2)}${fields.map(
722
+ (field) => scalarToToon(item[field])
723
+ ).join(",")}`
724
+ )
725
+ ].join("\n");
726
+ }
727
+ return value.flatMap((item, index) => [
728
+ `${" ".repeat(indent)}- item${index}:`,
729
+ ...encodeToon(item, indent + 2).split("\n")
730
+ ]).join("\n");
731
+ }
732
+ function isUniformObjectArray(value) {
733
+ if (!value.length || !value.every(isPlainObject)) {
734
+ return false;
735
+ }
736
+ const fields = Object.keys(value[0]);
737
+ if (!fields.length) {
738
+ return false;
739
+ }
740
+ return value.every((item) => {
741
+ const record = item;
742
+ const itemFields = Object.keys(record);
743
+ return itemFields.length === fields.length && fields.every((field) => itemFields.includes(field) && isPrimitive(record[field]));
744
+ });
745
+ }
746
+ function isPlainObject(value) {
747
+ return typeof value === "object" && value !== null && !Array.isArray(value);
748
+ }
749
+ function isPrimitive(value) {
750
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
751
+ }
752
+ function keyToToon(key) {
753
+ return /^[A-Za-z_][A-Za-z0-9_-]*$/.test(key) ? key : JSON.stringify(key);
754
+ }
755
+ function scalarToToon(value) {
756
+ if (value === null) return "null";
757
+ if (typeof value === "number" || typeof value === "boolean") {
758
+ return String(value);
759
+ }
760
+ const text = String(value);
761
+ if (text && !/^(true|false|null|-?\d+(?:\.\d+)?)$/i.test(text) && /^[A-Za-z0-9_./@-]+(?: [A-Za-z0-9_./@-]+)*$/.test(text)) {
762
+ return text;
763
+ }
764
+ return JSON.stringify(text);
765
+ }
766
+
767
+ // src/resources.ts
768
+ var CANONICAL_MEDIA_TYPE = "application/vnd.usagetap.v1+json";
769
+ var DEFAULT_GATEWAY_BASE_URL = "https://gateway.usagetap.com";
770
+ function normalizedBaseUrl(value) {
771
+ return `${value.replace(/\/+$/, "")}/`;
772
+ }
773
+ function errorMessage(payload, status) {
774
+ if (payload && typeof payload === "object") {
775
+ const record = payload;
776
+ const error = record.error;
777
+ if (error && typeof error === "object") {
778
+ const message2 = error.message;
779
+ if (typeof message2 === "string" && message2) return message2;
780
+ }
781
+ const message = record.message;
782
+ if (typeof message === "string" && message) return message;
783
+ }
784
+ return `UsageTap request failed with HTTP ${status}`;
785
+ }
786
+ function errorCode(status) {
787
+ if (status === 401 || status === 403) return "USAGETAP_AUTH_ERROR";
788
+ if (status === 429) return "USAGETAP_RATE_LIMITED";
789
+ if (status >= 500) return "USAGETAP_SERVER_ERROR";
790
+ return "USAGETAP_BAD_REQUEST";
791
+ }
792
+ var ResourceTransport = class {
793
+ baseUrl;
794
+ apiKey;
795
+ fetchImpl;
796
+ defaultHeaders;
797
+ sdkVersion;
798
+ constructor(baseUrl, config) {
799
+ this.baseUrl = normalizedBaseUrl(baseUrl);
800
+ this.apiKey = config.apiKey;
801
+ this.fetchImpl = config.fetchImpl;
802
+ this.defaultHeaders = config.headers ?? {};
803
+ this.sdkVersion = config.sdkVersion;
804
+ }
805
+ async request(request) {
806
+ const body = request.body === void 0 ? void 0 : JSON.stringify(request.body);
807
+ const headers = {
808
+ ...this.defaultHeaders,
809
+ accept: request.response === "data" ? CANONICAL_MEDIA_TYPE : request.response === "ndjson" ? "application/x-ndjson" : "application/json",
810
+ authorization: `Bearer ${this.apiKey}`,
811
+ "x-usage-sdk": `js/${this.sdkVersion}`,
812
+ ...body ? { "content-type": "application/json" } : {},
813
+ ...request.options?.idempotencyKey ? { "idempotency-key": request.options.idempotencyKey } : {},
814
+ ...request.options?.headers
815
+ };
816
+ let response;
817
+ try {
818
+ response = await this.fetchImpl(
819
+ new URL(request.path.replace(/^\/+/, ""), this.baseUrl),
820
+ {
821
+ method: request.method,
822
+ headers,
823
+ body,
824
+ signal: request.options?.signal
825
+ }
826
+ );
827
+ } catch (error) {
828
+ throw new UsageTapError(
829
+ "USAGETAP_NETWORK_ERROR",
830
+ "Failed to reach UsageTap",
831
+ { retryable: true, cause: error }
832
+ );
833
+ }
834
+ const requestId = response.headers.get("x-request-id") ?? response.headers.get("x-usage-correlation-id") ?? void 0;
835
+ const text = await response.text();
836
+ let payload;
837
+ if (text && request.response !== "ndjson") {
838
+ try {
839
+ payload = JSON.parse(text);
840
+ } catch (error) {
841
+ throw new UsageTapError(
842
+ "USAGETAP_INVALID_RESPONSE",
843
+ "UsageTap returned invalid JSON",
844
+ { status: response.status, correlationId: requestId, cause: error }
845
+ );
846
+ }
847
+ }
848
+ if (!response.ok) {
849
+ throw new UsageTapError(
850
+ errorCode(response.status),
851
+ errorMessage(payload, response.status),
852
+ {
853
+ status: response.status,
854
+ retryable: response.status === 429 || response.status >= 500,
855
+ correlationId: requestId,
856
+ details: payload && typeof payload === "object" ? payload : void 0
857
+ }
858
+ );
859
+ }
860
+ if (request.response === "ndjson") {
861
+ if (!text.trim()) return [];
862
+ try {
863
+ return text.trim().split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line));
864
+ } catch (error) {
865
+ throw new UsageTapError(
866
+ "USAGETAP_INVALID_RESPONSE",
867
+ "UsageTap returned invalid NDJSON",
868
+ { status: response.status, correlationId: requestId, cause: error }
869
+ );
870
+ }
871
+ }
872
+ if (request.response === "data") {
873
+ if (!payload || typeof payload !== "object" || !("data" in payload)) {
874
+ throw new UsageTapError(
875
+ "USAGETAP_INVALID_RESPONSE",
876
+ "UsageTap response missing data",
877
+ { status: response.status, correlationId: requestId }
878
+ );
879
+ }
880
+ return payload.data;
881
+ }
882
+ if (payload === void 0) {
883
+ throw new UsageTapError(
884
+ "USAGETAP_INVALID_RESPONSE",
885
+ "UsageTap response was empty",
886
+ { status: response.status, correlationId: requestId }
887
+ );
888
+ }
889
+ return payload;
890
+ }
891
+ };
892
+ function resourceId(value, keys, label) {
893
+ const id = typeof value === "string" ? value : keys.map((key) => value[key]).find((candidate) => Boolean(candidate?.trim()));
894
+ if (!id?.trim()) {
895
+ throw new UsageTapError(
896
+ "USAGETAP_BAD_REQUEST",
897
+ `${label} requires a non-empty ID`
898
+ );
899
+ }
900
+ return id.trim();
901
+ }
902
+ function terminalSummary(status) {
903
+ return status === "COMPLETE" || status === "FAILED";
904
+ }
905
+ function terminalGatewayBatch(status) {
906
+ return ["completed", "failed", "expired", "cancelled"].includes(status);
907
+ }
908
+ function validateWaitOptions(options) {
909
+ const pollIntervalMs = options.pollIntervalMs ?? 1500;
910
+ const timeoutMs = options.timeoutMs ?? 3 * 6e4;
911
+ if (!Number.isFinite(pollIntervalMs) || pollIntervalMs < 0) {
912
+ throw new UsageTapError(
913
+ "USAGETAP_BAD_REQUEST",
914
+ "pollIntervalMs must be a non-negative number"
915
+ );
916
+ }
917
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1) {
918
+ throw new UsageTapError(
919
+ "USAGETAP_BAD_REQUEST",
920
+ "timeoutMs must be a positive number"
921
+ );
922
+ }
923
+ return { pollIntervalMs, timeoutMs };
924
+ }
925
+ var SummarizationResource = class {
926
+ summaries;
927
+ batches;
928
+ profiles;
929
+ measurements;
930
+ transport;
931
+ constructor(config) {
932
+ this.transport = new ResourceTransport(config.apiBaseUrl, config);
933
+ this.summaries = {
934
+ create: (params, options) => this.transport.request({
935
+ method: "POST",
936
+ path: "/v1/compression/summaries",
937
+ body: params,
938
+ options,
939
+ response: "data"
940
+ }),
941
+ retrieve: (jobId, options) => this.transport.request({
942
+ method: "GET",
943
+ path: `/v1/compression/jobs/${encodeURIComponent(
944
+ resourceId(jobId, ["jobId"], "summaries.retrieve")
945
+ )}`,
946
+ options,
947
+ response: "data"
948
+ }),
949
+ wait: (job, options) => this.waitForSummary(job, options)
950
+ };
951
+ this.batches = {
952
+ create: (params, options) => this.transport.request({
953
+ method: "POST",
954
+ path: "/v1/compression/batches",
955
+ body: params,
956
+ options,
957
+ response: "data"
958
+ }),
959
+ retrieve: (batchId, options) => this.transport.request({
960
+ method: "GET",
961
+ path: `/v1/compression/batches/${encodeURIComponent(
962
+ resourceId(batchId, ["batchId"], "summarization.batches.retrieve")
963
+ )}`,
964
+ options,
965
+ response: "data"
966
+ }),
967
+ wait: (batch, options) => this.waitForBatch(batch, options)
968
+ };
969
+ this.profiles = {
970
+ retrieve: (profile, options) => this.transport.request({
971
+ method: "GET",
972
+ path: `/v1/compression/profiles/${encodeURIComponent(
973
+ resourceId(profile, [], "summarization.profiles.retrieve")
974
+ )}`,
975
+ options,
976
+ response: "data"
977
+ })
978
+ };
979
+ this.measurements = {
980
+ create: (params, options) => this.transport.request({
981
+ method: "POST",
982
+ path: "/v1/compression/measurements",
983
+ body: params,
984
+ options,
985
+ response: "data"
986
+ })
987
+ };
988
+ }
989
+ async waitForSummary(value, options = {}) {
990
+ const { pollIntervalMs, timeoutMs } = validateWaitOptions(options);
991
+ const deadline = Date.now() + timeoutMs;
992
+ let job = typeof value === "string" ? await this.summaries.retrieve(value, options) : value;
993
+ while (!terminalSummary(job.status)) {
994
+ if (Date.now() >= deadline) {
995
+ throw new UsageTapError(
996
+ "USAGETAP_RETRY_EXHAUSTED",
997
+ `Summarization job ${job.jobId} did not finish before timeout`,
998
+ { retryable: true }
999
+ );
1000
+ }
1001
+ await sleep(pollIntervalMs, options.signal);
1002
+ job = await this.summaries.retrieve(job.jobId, options);
1003
+ }
1004
+ return job;
1005
+ }
1006
+ async waitForBatch(value, options = {}) {
1007
+ const { pollIntervalMs, timeoutMs } = validateWaitOptions(options);
1008
+ const deadline = Date.now() + timeoutMs;
1009
+ let batch = typeof value === "string" ? await this.batches.retrieve(value, options) : value;
1010
+ while (!terminalSummary(batch.status)) {
1011
+ if (Date.now() >= deadline) {
1012
+ throw new UsageTapError(
1013
+ "USAGETAP_RETRY_EXHAUSTED",
1014
+ `Summarization batch ${batch.batchId} did not finish before timeout`,
1015
+ { retryable: true }
1016
+ );
1017
+ }
1018
+ await sleep(pollIntervalMs, options.signal);
1019
+ batch = await this.batches.retrieve(batch.batchId, options);
1020
+ }
1021
+ return batch;
1022
+ }
1023
+ };
1024
+ var GatewayResource = class {
1025
+ chat;
1026
+ /** Buffered OpenAI Responses-compatible requests. */
1027
+ responses;
1028
+ models;
1029
+ batches;
1030
+ transport;
1031
+ idempotencyGenerator;
1032
+ constructor(config) {
1033
+ this.transport = new ResourceTransport(
1034
+ config.gatewayBaseUrl ?? DEFAULT_GATEWAY_BASE_URL,
1035
+ config
1036
+ );
1037
+ this.idempotencyGenerator = config.idempotencyGenerator ?? createIdempotencyKey;
1038
+ this.chat = {
1039
+ completions: {
1040
+ create: (params, options) => this.transport.request({
1041
+ method: "POST",
1042
+ path: "/v1/chat/completions",
1043
+ body: params,
1044
+ options,
1045
+ response: "json"
1046
+ })
1047
+ }
1048
+ };
1049
+ this.responses = {
1050
+ create: (params, options) => this.transport.request({
1051
+ method: "POST",
1052
+ path: "/v1/responses",
1053
+ body: params,
1054
+ options,
1055
+ response: "json"
1056
+ })
1057
+ };
1058
+ this.models = {
1059
+ list: (options) => this.transport.request({
1060
+ method: "GET",
1061
+ path: "/v1/models",
1062
+ options,
1063
+ response: "json"
1064
+ })
1065
+ };
1066
+ this.batches = {
1067
+ create: (params, options = {}) => this.transport.request({
1068
+ method: "POST",
1069
+ path: "/v1/batches",
1070
+ body: params,
1071
+ options: {
1072
+ ...options,
1073
+ idempotencyKey: options.idempotencyKey ?? this.idempotencyGenerator()
1074
+ },
1075
+ response: "json"
1076
+ }),
1077
+ retrieve: (batchId, options) => this.transport.request({
1078
+ method: "GET",
1079
+ path: `/v1/batches/${encodeURIComponent(
1080
+ resourceId(batchId, ["id"], "gateway.batches.retrieve")
1081
+ )}`,
1082
+ options,
1083
+ response: "json"
1084
+ }),
1085
+ wait: (batch, options) => this.waitForBatch(batch, options),
1086
+ cancel: (batchId, options) => this.transport.request({
1087
+ method: "POST",
1088
+ path: `/v1/batches/${encodeURIComponent(
1089
+ resourceId(batchId, ["id"], "gateway.batches.cancel")
1090
+ )}/cancel`,
1091
+ options,
1092
+ response: "json"
1093
+ }),
1094
+ results: (batchId, options) => this.transport.request({
1095
+ method: "GET",
1096
+ path: `/v1/batches/${encodeURIComponent(
1097
+ resourceId(batchId, ["id"], "gateway.batches.results")
1098
+ )}/results`,
1099
+ options,
1100
+ response: "ndjson"
1101
+ })
1102
+ };
1103
+ }
1104
+ async waitForBatch(value, options = {}) {
1105
+ const { pollIntervalMs, timeoutMs } = validateWaitOptions(options);
1106
+ const deadline = Date.now() + timeoutMs;
1107
+ let batch = typeof value === "string" ? await this.batches.retrieve(value, options) : value;
1108
+ while (!terminalGatewayBatch(batch.status)) {
1109
+ if (Date.now() >= deadline) {
1110
+ throw new UsageTapError(
1111
+ "USAGETAP_RETRY_EXHAUSTED",
1112
+ `Gateway batch ${batch.id} did not finish before timeout`,
1113
+ { retryable: true }
1114
+ );
1115
+ }
1116
+ await sleep(pollIntervalMs, options.signal);
1117
+ batch = await this.batches.retrieve(batch.id, options);
1118
+ }
1119
+ return batch;
1120
+ }
1121
+ };
1122
+
1123
+ // src/client.ts
1124
+ var CALL_BEGIN_PATH = "call_begin";
1125
+ var CALL_END_PATH = "call_end";
1126
+ var COMPRESS_PROMPT_PATH = "compress_prompt";
1127
+ var SAMPLES_PATH = "samples";
1128
+ var SAMPLING_SETTINGS_PATH = "sampling/settings";
1129
+ var SAMPLING_DECIDE_PATH = "sampling/decide";
1130
+ var CHECK_USAGE_PATH = "customers/{customerId}/usage";
1131
+ var CREATE_CUSTOMER_PATH = "customers";
1132
+ var CHANGE_PLAN_PATH = "customers/{customerId}/change_plan";
1133
+ var INCREMENT_CUSTOM_METER_PATH = "custom_meter";
1134
+ var AUTH_HEADER = "authorization";
1135
+ var API_KEY_HEADER = "x-api-key";
1136
+ var CORRELATION_HEADER = "x-usage-correlation-id";
1137
+ var IDEMPOTENCY_HEADER = "idempotency-key";
1138
+ var SDK_HEADER = "x-usage-sdk";
1139
+ var USER_AGENT = "UsageTapClient";
1140
+ var CANONICAL_MEDIA_TYPE2 = "application/vnd.usagetap.v1+json";
1141
+ var DEFAULT_BASE_URL = "https://api.usagetap.com";
1142
+ var DEFAULT_RUN_INACTIVITY_MS = 60 * 60 * 1e3;
1143
+ var SDK_VERSION = "1.7.0" ;
1144
+ var HAS_WINDOW = typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1145
+ var UsageTapClient = class {
1146
+ /** OpenAI-compatible chat, model, and native batch operations. */
1147
+ gateway;
1148
+ /** Published-profile context summarization operations. */
1149
+ summarization;
1150
+ apiKey;
1151
+ baseUrl;
1152
+ fetchImpl;
1153
+ defaultFeature;
1154
+ defaultTags;
1155
+ defaultHeaders;
1156
+ retryDefaults;
1157
+ idempotencyGenerator;
1158
+ logFn;
1159
+ metricFn;
1160
+ authHeader;
1161
+ autoIdempotency;
1162
+ tokenCompanyApiKey;
1163
+ tokenCompanyEndpoint;
1164
+ model;
1165
+ tokenCompanyModel;
1166
+ aggressiveness;
1167
+ tokenCompanyAggressiveness;
1168
+ tokenCompanyAppId;
1169
+ usageTapCompressionApiKey;
1170
+ usageTapCompressionEndpoint;
1171
+ usageTapCompressionMessagesEndpoint;
1172
+ usageTapCompressionModel;
1173
+ usageTapCompressionAggressiveness;
1174
+ sampling;
1175
+ samplingSettingsCacheMs;
1176
+ circuitBreaker;
1177
+ circuitBreakerRuns = /* @__PURE__ */ new Map();
1178
+ samplingSettingsCache;
1179
+ constructor(options = {}) {
1180
+ const apiKey = options.apiKey?.trim() || readEnvironmentVariable("USAGETAP_API_KEY");
1181
+ const baseUrl = options.baseUrl?.trim() || readEnvironmentVariable("USAGETAP_BASE_URL") || DEFAULT_BASE_URL;
1182
+ if (!apiKey) {
1183
+ throw new UsageTapError(
1184
+ "USAGETAP_BAD_REQUEST",
1185
+ "UsageTapClient requires an apiKey or the USAGETAP_API_KEY environment variable"
1186
+ );
1187
+ }
1188
+ if (HAS_WINDOW && !options.allowBrowser) {
1189
+ throw new UsageTapError(
1190
+ "USAGETAP_BROWSER_RUNTIME",
1191
+ "UsageTapClient is designed for server-side environments. Pass allowBrowser=true only for testing."
1192
+ );
1193
+ }
1194
+ const fetchCandidate = options.fetchImpl ?? globalThis.fetch;
1195
+ if (typeof fetchCandidate !== "function") {
1196
+ throw new UsageTapError(
1197
+ "USAGETAP_NETWORK_ERROR",
1198
+ "A global fetch implementation was not found. Pass fetchImpl in UsageTapClientOptions."
1199
+ );
1200
+ }
1201
+ const normalizedBaseUrl2 = normalizeBaseUrl(baseUrl);
1202
+ this.baseUrl = new URL(normalizedBaseUrl2);
1203
+ this.apiKey = apiKey;
1204
+ this.fetchImpl = wrapFetchImplementation(fetchCandidate, !options.fetchImpl);
1205
+ const resourceConfig = {
1206
+ apiKey,
1207
+ apiBaseUrl: normalizedBaseUrl2,
1208
+ gatewayBaseUrl: options.gatewayBaseUrl?.trim() || readEnvironmentVariable("USAGETAP_GATEWAY_URL"),
1209
+ fetchImpl: this.fetchImpl,
1210
+ headers: options.headers,
1211
+ sdkVersion: SDK_VERSION,
1212
+ idempotencyGenerator: options.idempotencyGenerator
1213
+ };
1214
+ this.gateway = new GatewayResource(resourceConfig);
1215
+ this.summarization = new SummarizationResource(resourceConfig);
1216
+ this.defaultFeature = options.defaultFeature;
1217
+ this.defaultTags = options.defaultTags?.length ? dedupeStrings(options.defaultTags) : void 0;
1218
+ this.defaultHeaders = options.headers ? normalizeHeaderDictionary(options.headers) : {};
1219
+ this.retryDefaults = resolveRetryOptions(options.retries);
1220
+ this.idempotencyGenerator = options.idempotencyGenerator ?? createIdempotencyKey;
1221
+ this.logFn = options.onLog;
1222
+ this.metricFn = options.onUsageMetric;
1223
+ this.authHeader = options.useApiKeyHeader ? API_KEY_HEADER : AUTH_HEADER;
1224
+ this.autoIdempotency = options.autoIdempotency ?? true;
1225
+ this.tokenCompanyApiKey = options.tokenCompanyApiKey;
1226
+ this.tokenCompanyEndpoint = options.tokenCompanyEndpoint;
1227
+ this.model = options.model;
1228
+ this.tokenCompanyModel = options.tokenCompanyModel;
1229
+ this.aggressiveness = options.aggressiveness;
1230
+ this.tokenCompanyAggressiveness = options.tokenCompanyAggressiveness;
1231
+ this.tokenCompanyAppId = options.tokenCompanyAppId;
1232
+ this.usageTapCompressionApiKey = options.usageTapCompressionApiKey ?? apiKey;
1233
+ this.usageTapCompressionEndpoint = options.usageTapCompressionEndpoint;
1234
+ this.usageTapCompressionMessagesEndpoint = options.usageTapCompressionMessagesEndpoint;
1235
+ this.usageTapCompressionModel = options.usageTapCompressionModel;
1236
+ this.usageTapCompressionAggressiveness = options.usageTapCompressionAggressiveness;
1237
+ this.sampling = options.sampling;
1238
+ this.samplingSettingsCacheMs = Number.isFinite(options.samplingSettingsCacheMs) ? Math.max(0, Number(options.samplingSettingsCacheMs)) : 5 * 60 * 1e3;
1239
+ if (options.circuitBreaker) {
1240
+ const maxCallsPerRun = options.circuitBreaker.maxCallsPerRun;
1241
+ if (!Number.isInteger(maxCallsPerRun) || maxCallsPerRun < 1) {
1242
+ throw new UsageTapError(
1243
+ "USAGETAP_BAD_REQUEST",
1244
+ "circuitBreaker.maxCallsPerRun must be a positive integer"
1245
+ );
1246
+ }
1247
+ const runInactivityMs = options.circuitBreaker.runInactivityMs ?? DEFAULT_RUN_INACTIVITY_MS;
1248
+ if (!Number.isFinite(runInactivityMs) || runInactivityMs < 1) {
1249
+ throw new UsageTapError(
1250
+ "USAGETAP_BAD_REQUEST",
1251
+ "circuitBreaker.runInactivityMs must be a positive number"
1252
+ );
1253
+ }
1254
+ this.circuitBreaker = {
1255
+ maxCallsPerRun,
1256
+ runInactivityMs
1257
+ };
1258
+ }
1259
+ }
1260
+ shouldSample(request, policy = this.sampling || void 0) {
1261
+ if (!policy) return false;
1262
+ const rate = Math.min(1, Math.max(0, Number(policy.rate) || 0));
1263
+ if (rate <= 0) return false;
1264
+ const customerId = request.customerId?.trim();
1265
+ if (customerId && policy.customers?.exclude?.includes(customerId)) return false;
1266
+ const feature = request.feature?.trim();
1267
+ if (feature && policy.features?.exclude?.includes(feature)) return false;
1268
+ const included = policy.features?.include?.filter(Boolean) ?? [];
1269
+ if (included.length > 0 && (!feature || !included.includes(feature))) return false;
1270
+ const minimum = Math.max(0, Math.round(policy.minInputTokens ?? 0));
1271
+ if (minimum > 0 && estimatePromptTokens(request.input) < minimum) return false;
1272
+ return (policy.random ?? Math.random)() < rate;
1273
+ }
1274
+ async getSamplingSettings(options = {}) {
1275
+ const now = Date.now();
1276
+ if (!options.forceRefresh && this.samplingSettingsCache && this.samplingSettingsCache.expiresAtMs > now) {
1277
+ return {
1278
+ result: { status: "ACCEPTED", code: "SAMPLING_SETTINGS_CACHED" },
1279
+ data: this.samplingSettingsCache.settings,
1280
+ correlationId: options.correlationId ?? "local-cache"
1281
+ };
1282
+ }
1283
+ const response = await this.requestGet(
1284
+ SAMPLING_SETTINGS_PATH,
1285
+ {
1286
+ signal: options.signal,
1287
+ headers: options.headers,
1288
+ retries: options.retries,
1289
+ correlationId: options.correlationId
1290
+ }
1291
+ );
1292
+ const serverCacheMs = Math.max(0, Number(response.data.cacheSeconds) || 0) * 1e3;
1293
+ const cacheMs = Math.min(this.samplingSettingsCacheMs, serverCacheMs);
1294
+ this.samplingSettingsCache = {
1295
+ settings: response.data,
1296
+ expiresAtMs: now + cacheMs
1297
+ };
1298
+ return response;
1299
+ }
1300
+ async shouldSampleAsync(request, policy) {
1301
+ if (policy) return this.shouldSample(request, policy);
1302
+ if (this.sampling === false) return false;
1303
+ if (this.sampling) return this.shouldSample(request, this.sampling);
1304
+ try {
1305
+ const settings = await this.getSamplingSettings();
1306
+ return this.shouldSample(request, settings.data);
1307
+ } catch {
1308
+ return false;
1309
+ }
1310
+ }
1311
+ async decideSample(request, options = {}) {
1312
+ const hasTokens = Number.isFinite(request.inputTokens) && Number(request.inputTokens) >= 0;
1313
+ const hasCharacters = Number.isFinite(request.inputCharacters) && Number(request.inputCharacters) >= 0;
1314
+ if (!hasTokens && !hasCharacters) {
1315
+ throw new UsageTapError(
1316
+ "USAGETAP_BAD_REQUEST",
1317
+ "decideSample requires inputTokens or inputCharacters"
1318
+ );
1319
+ }
1320
+ return this.request(
1321
+ SAMPLING_DECIDE_PATH,
1322
+ request,
1323
+ options
1324
+ );
1325
+ }
1326
+ async captureSample(request, options = {}) {
1327
+ if (!request || request.input === void 0) {
1328
+ throw new UsageTapError(
1329
+ "USAGETAP_BAD_REQUEST",
1330
+ "captureSample requires input"
1331
+ );
1332
+ }
1333
+ if (!request.provider?.trim()) {
1334
+ throw new UsageTapError(
1335
+ "USAGETAP_BAD_REQUEST",
1336
+ "captureSample requires provider"
1337
+ );
1338
+ }
1339
+ const sampleId = request.sampleId?.trim() || this.idempotencyGenerator();
1340
+ return this.request(
1341
+ SAMPLES_PATH,
1342
+ { ...request, sampleId },
1343
+ { ...options, idempotencyKey: sampleId }
1344
+ );
1345
+ }
1346
+ async beginCall(request, options = {}) {
1347
+ const idempotencyKey = request.idempotencyKey ?? request.idempotency ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1348
+ this.reserveRunCall(request, idempotencyKey);
1349
+ const apiRequest = { ...request };
1350
+ delete apiRequest.runId;
1351
+ const payload = {
1352
+ ...apiRequest,
1353
+ feature: request.feature ?? this.defaultFeature,
1354
+ tags: this.mergeTags(request.tags)
1355
+ };
1356
+ if (idempotencyKey) {
1357
+ payload.idempotencyKey = idempotencyKey;
1358
+ payload.idempotency = idempotencyKey;
1359
+ }
1360
+ const response = await this.request(
1361
+ CALL_BEGIN_PATH,
1362
+ payload,
1363
+ {
1364
+ ...options,
1365
+ idempotencyKey
1366
+ }
1367
+ );
1368
+ return response;
1369
+ }
1370
+ /**
1371
+ * Inspect a configured run circuit breaker without consuming another call.
1372
+ */
1373
+ canRunContinue(request) {
1374
+ const identity = this.resolveRunIdentity(request);
1375
+ if (!identity || !this.circuitBreaker) {
1376
+ throw new UsageTapError(
1377
+ "USAGETAP_BAD_REQUEST",
1378
+ "canRunContinue requires circuitBreaker configuration and a non-empty runId"
1379
+ );
1380
+ }
1381
+ this.expireInactiveRuns();
1382
+ const calls = this.circuitBreakerRuns.get(identity.key)?.calls ?? 0;
1383
+ return this.createCircuitBreakerDecision(identity.customerId, identity.runId, calls);
1384
+ }
1385
+ /**
1386
+ * Release local state after a workflow finishes. Returns true when state existed.
1387
+ */
1388
+ resetRun(request) {
1389
+ const identity = this.resolveRunIdentity(request);
1390
+ return identity ? this.circuitBreakerRuns.delete(identity.key) : false;
1391
+ }
1392
+ async promptCompress(request, options = {}) {
1393
+ if (!request?.callId) {
1394
+ throw new UsageTapError(
1395
+ "USAGETAP_BAD_REQUEST",
1396
+ "promptCompress requires callId"
1397
+ );
1398
+ }
1399
+ const requestInput = request.input ?? request.text;
1400
+ if (requestInput === void 0) {
1401
+ throw new UsageTapError(
1402
+ "USAGETAP_BAD_REQUEST",
1403
+ "promptCompress requires input or text"
1404
+ );
1405
+ }
1406
+ const result = await this.compressPromptInput(requestInput, {
1407
+ provider: request.provider,
1408
+ model: request.model,
1409
+ tokenCompanyModel: request.tokenCompanyModel,
1410
+ aggressiveness: request.aggressiveness,
1411
+ tokenCompanyAggressiveness: request.tokenCompanyAggressiveness,
1412
+ tokenCompanyAppId: request.tokenCompanyAppId,
1413
+ usageTapCompressionModel: request.usageTapCompressionModel,
1414
+ usageTapCompressionAggressiveness: request.usageTapCompressionAggressiveness,
1415
+ signal: options.signal
1416
+ });
1417
+ try {
1418
+ await this.recordPromptCompression(
1419
+ {
1420
+ callId: request.callId,
1421
+ promptCompression: this.toPromptCompressionTelemetry(result)
1422
+ },
1423
+ options
1424
+ );
1425
+ return { ...result, callId: request.callId };
1426
+ } catch (error) {
1427
+ return {
1428
+ ...createPromptCompressionFallback(
1429
+ requestInput,
1430
+ request.provider ?? result.provider,
1431
+ error
1432
+ ),
1433
+ callId: request.callId
1434
+ };
1435
+ }
1436
+ }
1437
+ async compressPromptInput(input, options = {}) {
1438
+ return compressPrompt({
1439
+ input,
1440
+ provider: options.provider,
1441
+ tokenCompanyApiKey: this.tokenCompanyApiKey,
1442
+ tokenCompanyEndpoint: this.tokenCompanyEndpoint,
1443
+ model: options.model ?? this.model,
1444
+ tokenCompanyModel: options.tokenCompanyModel ?? this.tokenCompanyModel,
1445
+ aggressiveness: options.aggressiveness ?? this.aggressiveness,
1446
+ tokenCompanyAggressiveness: options.tokenCompanyAggressiveness ?? this.tokenCompanyAggressiveness,
1447
+ tokenCompanyAppId: options.tokenCompanyAppId ?? this.tokenCompanyAppId,
1448
+ usageTapCompressionApiKey: this.usageTapCompressionApiKey,
1449
+ usageTapCompressionEndpoint: this.usageTapCompressionEndpoint,
1450
+ usageTapCompressionModel: options.usageTapCompressionModel ?? this.usageTapCompressionModel,
1451
+ usageTapCompressionAggressiveness: options.usageTapCompressionAggressiveness ?? this.usageTapCompressionAggressiveness,
1452
+ fetchImpl: this.fetchImpl,
1453
+ signal: options.signal,
1454
+ failOpen: options.failOpen
1455
+ });
1456
+ }
1457
+ /**
1458
+ * Compress text with UsageTap's hosted compression service.
1459
+ *
1460
+ * This is the short, standalone path. It does not create a metered call and
1461
+ * fails open to the original text unless failOpen is explicitly disabled.
1462
+ */
1463
+ async compress(text, options = {}) {
1464
+ if (typeof text !== "string") {
1465
+ throw new UsageTapError(
1466
+ "USAGETAP_BAD_REQUEST",
1467
+ "compress requires text"
1468
+ );
1469
+ }
1470
+ const result = await this.compressPromptInput(text, {
1471
+ ...options,
1472
+ provider: "usagetap"
1473
+ });
1474
+ const output = typeof result.compressedInput === "string" ? result.compressedInput : text;
1475
+ return {
1476
+ ...result,
1477
+ compressedInput: output,
1478
+ output
1479
+ };
1480
+ }
1481
+ async compressPromptMessages(input, options = {}) {
1482
+ return compressPromptMessages({
1483
+ input,
1484
+ provider: options.provider ?? "usagetap",
1485
+ usageTapCompressionApiKey: this.usageTapCompressionApiKey,
1486
+ usageTapCompressionMessagesEndpoint: this.usageTapCompressionMessagesEndpoint,
1487
+ aggressiveness: options.aggressiveness ?? this.aggressiveness,
1488
+ usageTapCompressionAggressiveness: options.usageTapCompressionAggressiveness ?? this.usageTapCompressionAggressiveness,
1489
+ mode: options.mode,
1490
+ latencyBudgetMs: options.latencyBudgetMs,
1491
+ compactEmptyUserMessages: options.compactEmptyUserMessages,
1492
+ compactDuplicateUserTextParts: options.compactDuplicateUserTextParts,
1493
+ fetchImpl: this.fetchImpl,
1494
+ signal: options.signal,
1495
+ failOpen: options.failOpen
1496
+ });
1497
+ }
1498
+ async recordPromptCompression(request, options = {}) {
1499
+ if (!request?.callId) {
1500
+ throw new UsageTapError(
1501
+ "USAGETAP_BAD_REQUEST",
1502
+ "recordPromptCompression requires callId"
1503
+ );
1504
+ }
1505
+ return this.request(
1506
+ COMPRESS_PROMPT_PATH,
1507
+ {
1508
+ callId: request.callId,
1509
+ promptCompression: request.promptCompression
1510
+ },
1511
+ options
1512
+ );
1513
+ }
1514
+ async endCall(request, options = {}) {
1515
+ if (!request?.callId) {
1516
+ throw new UsageTapError(
1517
+ "USAGETAP_BAD_REQUEST",
1518
+ "endCall requires callId"
1519
+ );
1520
+ }
1521
+ const { customerId, feature, tags, ...apiPayload } = request;
1522
+ const response = await this.request(
1523
+ CALL_END_PATH,
1524
+ apiPayload,
1525
+ options
1526
+ );
1527
+ this.emitUsageMetric({
1528
+ type: "call_end",
1529
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1530
+ customerId: customerId ?? "unknown",
1531
+ callId: request.callId,
1532
+ feature: feature ?? this.defaultFeature,
1533
+ tags: tags ?? this.defaultTags,
1534
+ providerUsed: request.providerUsed,
1535
+ modelUsed: request.modelUsed,
1536
+ reasoningEffort: request.reasoningEffort,
1537
+ reasoningEffortSource: request.reasoningEffortSource,
1538
+ reasoningMode: request.reasoningMode,
1539
+ reasoningBudgetTokens: request.reasoningBudgetTokens,
1540
+ metrics: {
1541
+ inputTokens: request.inputTokens,
1542
+ responseTokens: request.responseTokens,
1543
+ cachedInputTokens: request.cachedInputTokens,
1544
+ cacheWriteInputTokens: request.cacheWriteInputTokens,
1545
+ cacheWrite5mInputTokens: request.cacheWrite5mInputTokens,
1546
+ cacheWrite1hInputTokens: request.cacheWrite1hInputTokens,
1547
+ reasoningTokens: request.reasoningTokens,
1548
+ searches: request.searches,
1549
+ audioSeconds: request.audioSeconds,
1550
+ imageInputCount: request.imageInputCount,
1551
+ imageInputTokens: request.imageInputTokens,
1552
+ imageOutputCount: request.imageOutputCount,
1553
+ imageOutputTokens: request.imageOutputTokens,
1554
+ audioInputTokens: request.audioInputTokens,
1555
+ cachedAudioInputTokens: request.cachedAudioInputTokens,
1556
+ audioOutputTokens: request.audioOutputTokens,
1557
+ costUsd: response.data.costUSD
1558
+ },
1559
+ correlationId: response.correlationId
1560
+ });
1561
+ return response;
1562
+ }
1563
+ async checkUsage(request, options = {}) {
1564
+ if (!request?.customerId) {
1565
+ throw new UsageTapError(
1566
+ "USAGETAP_BAD_REQUEST",
1567
+ "checkUsage requires customerId"
1568
+ );
1569
+ }
1570
+ const path = CHECK_USAGE_PATH.replace(
1571
+ "{customerId}",
1572
+ encodeURIComponent(request.customerId)
1573
+ );
1574
+ const response = await this.requestGet(
1575
+ path,
1576
+ options
1577
+ );
1578
+ return response;
1579
+ }
1580
+ async createCustomer(request, options = {}) {
1581
+ if (!request?.customerId) {
1582
+ throw new UsageTapError(
1583
+ "USAGETAP_BAD_REQUEST",
1584
+ "createCustomer requires customerId"
1585
+ );
1586
+ }
1587
+ const idempotencyKey = options.idempotencyKey ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1588
+ const response = await this.request(
1589
+ CREATE_CUSTOMER_PATH,
1590
+ { ...request },
1591
+ {
1592
+ ...options,
1593
+ idempotencyKey
1594
+ }
1595
+ );
1596
+ return response;
1597
+ }
1598
+ async changePlan(request, options = {}) {
1599
+ if (!request?.customerId) {
1600
+ throw new UsageTapError(
1601
+ "USAGETAP_BAD_REQUEST",
1602
+ "changePlan requires customerId"
1603
+ );
1604
+ }
1605
+ if (!request?.planId) {
1606
+ throw new UsageTapError(
1607
+ "USAGETAP_BAD_REQUEST",
1608
+ "changePlan requires planId"
1609
+ );
1610
+ }
1611
+ const path = CHANGE_PLAN_PATH.replace(
1612
+ "{customerId}",
1613
+ encodeURIComponent(request.customerId)
1614
+ );
1615
+ const idempotencyKey = options.idempotencyKey ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1616
+ const payload = {
1617
+ planId: request.planId,
1618
+ strategy: request.strategy ?? "IMMEDIATE_RESET"
1619
+ };
1620
+ const response = await this.request(
1621
+ path,
1622
+ payload,
1623
+ {
1624
+ ...options,
1625
+ idempotencyKey
1626
+ }
1627
+ );
1628
+ return response;
1629
+ }
1630
+ async incrementCustomMeter(request, options = {}) {
1631
+ if (!request?.customerId) {
1632
+ throw new UsageTapError(
1633
+ "USAGETAP_BAD_REQUEST",
1634
+ "incrementCustomMeter requires customerId"
1635
+ );
1636
+ }
1637
+ if (!request?.meterSlot) {
1638
+ throw new UsageTapError(
1639
+ "USAGETAP_BAD_REQUEST",
1640
+ "incrementCustomMeter requires meterSlot"
1641
+ );
1642
+ }
1643
+ if (!["CUSTOM1", "CUSTOM2", "AGENTIC_API"].includes(request.meterSlot)) {
1644
+ throw new UsageTapError(
1645
+ "USAGETAP_BAD_REQUEST",
1646
+ "meterSlot must be CUSTOM1, CUSTOM2 or AGENTIC_API"
1647
+ );
1648
+ }
1649
+ if (typeof request.amount !== "number" || !Number.isFinite(request.amount) || request.amount <= 0) {
1650
+ throw new UsageTapError(
1651
+ "USAGETAP_BAD_REQUEST",
1652
+ "incrementCustomMeter requires a positive numeric amount"
1653
+ );
1654
+ }
1655
+ const idempotencyKey = options.idempotencyKey ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1656
+ const payload = {
1657
+ customerId: request.customerId,
1658
+ meterSlot: request.meterSlot,
1659
+ amount: request.amount
1660
+ };
1661
+ if (request.customerUserId) {
1662
+ payload.customerUserId = request.customerUserId;
1663
+ }
1664
+ if (request.customerUserName) {
1665
+ payload.customerUserName = request.customerUserName;
1666
+ }
1667
+ if (request.customerUserEmail) {
1668
+ payload.customerUserEmail = request.customerUserEmail;
1669
+ }
1670
+ if (request.feature) {
1671
+ payload.feature = request.feature;
1672
+ }
1673
+ if (request.tags && request.tags.length > 0) {
1674
+ payload.tags = request.tags;
1675
+ }
1676
+ if (request.metadata) {
1677
+ payload.metadata = request.metadata;
1678
+ }
1679
+ const response = await this.request(
1680
+ INCREMENT_CUSTOM_METER_PATH,
1681
+ payload,
1682
+ {
1683
+ ...options,
1684
+ idempotencyKey
1685
+ }
1686
+ );
1687
+ this.emitUsageMetric({
1688
+ type: "custom_meter",
1689
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1690
+ customerId: request.customerId,
1691
+ feature: request.feature ?? this.defaultFeature,
1692
+ tags: request.tags ?? this.defaultTags,
1693
+ metrics: {
1694
+ customMeterSlot: request.meterSlot,
1695
+ customMeterAmount: request.amount
1696
+ },
1697
+ correlationId: response.correlationId
1698
+ });
1699
+ return response;
1700
+ }
1701
+ async withUsage(beginRequest, handler, options = {}) {
1702
+ const idempotencyKey = beginRequest.idempotencyKey ?? beginRequest.idempotency ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1703
+ const beginPayload = idempotencyKey ? { ...beginRequest, idempotencyKey, idempotency: idempotencyKey } : { ...beginRequest };
1704
+ const beginResponse = await this.beginCall(beginPayload, options);
1705
+ let usage = {};
1706
+ const pricingMode = beginResponse.data.pricingMode ?? beginRequest.pricingMode ?? (beginRequest.batch === true ? "batch" : beginRequest.batch === false ? "standard" : void 0);
1707
+ if (pricingMode) {
1708
+ usage.pricingMode = pricingMode;
1709
+ usage.batch = pricingMode === "batch";
1710
+ }
1711
+ const initialStripeCustomerId = typeof beginResponse.data.stripeCustomerId === "string" ? beginResponse.data.stripeCustomerId : typeof beginRequest.stripeCustomerId === "string" ? beginRequest.stripeCustomerId : void 0;
1712
+ if (initialStripeCustomerId) {
1713
+ usage = { ...usage, stripeCustomerId: initialStripeCustomerId };
1714
+ }
1715
+ let errorPayload;
1716
+ let handlerResult;
1717
+ let handlerError;
1718
+ let endCallError;
1719
+ let finalizationDeferred = false;
1720
+ let finalizationPromise;
1721
+ const finalize = () => {
1722
+ if (!finalizationPromise) {
1723
+ finalizationPromise = this.endCall(
1724
+ {
1725
+ callId: beginResponse.data.callId,
1726
+ // Pass context for metric tracking
1727
+ customerId: beginRequest.customerId,
1728
+ feature: beginRequest.feature ?? this.defaultFeature,
1729
+ tags: beginRequest.tags ?? this.defaultTags,
1730
+ ...usage,
1731
+ error: errorPayload
1732
+ },
1733
+ {
1734
+ ...options,
1735
+ correlationId: beginResponse.correlationId
1736
+ }
1737
+ ).then(() => void 0);
1738
+ }
1739
+ return finalizationPromise;
1740
+ };
1741
+ const context = {
1742
+ begin: beginResponse,
1743
+ setUsage: (u) => {
1744
+ usage = { ...usage, ...u };
1745
+ },
1746
+ setError: (err) => {
1747
+ errorPayload = err;
1748
+ },
1749
+ deferFinalization: () => {
1750
+ finalizationDeferred = true;
1751
+ return finalize;
1752
+ }
1753
+ };
1754
+ try {
1755
+ handlerResult = await handler(context);
1756
+ } catch (error) {
1757
+ handlerError = error;
1758
+ if (!errorPayload) {
1759
+ errorPayload = {
1760
+ code: options.defaultErrorCode ?? "VENDOR_ERROR",
1761
+ message: error instanceof Error ? error.message : String(error)
1762
+ };
1763
+ }
1764
+ } finally {
1765
+ if (handlerError || !finalizationDeferred) {
1766
+ try {
1767
+ await finalize();
1768
+ } catch (error) {
1769
+ endCallError = error;
1770
+ }
1771
+ }
1772
+ }
1773
+ if (handlerError) {
1774
+ throw handlerError;
1775
+ }
1776
+ if (endCallError) {
1777
+ throw wrapEndCallError(endCallError, beginResponse.correlationId);
1778
+ }
1779
+ return handlerResult;
1780
+ }
1781
+ /**
1782
+ * Meter one operation. Pass only a customer ID for the common path, or the
1783
+ * existing begin-call request object when feature, tags, or entitlements are needed.
1784
+ */
1785
+ async meter(request, handler, options = {}) {
1786
+ const beginRequest = typeof request === "string" ? { customerId: request } : request;
1787
+ return this.withUsage(beginRequest, handler, options);
1788
+ }
1789
+ toPromptCompressionTelemetry(result) {
1790
+ return {
1791
+ provider: result.provider,
1792
+ originalTokens: result.originalTokens,
1793
+ compressedTokens: result.compressedTokens,
1794
+ savedTokens: result.savedTokens,
1795
+ tokenSavingsRatio: result.tokenSavingsRatio,
1796
+ techniques: result.techniques
1797
+ };
1798
+ }
1799
+ reserveRunCall(request, idempotencyKey) {
1800
+ const identity = this.resolveRunIdentity(request);
1801
+ if (!identity || !this.circuitBreaker) return;
1802
+ this.expireInactiveRuns();
1803
+ const now = Date.now();
1804
+ const state = this.circuitBreakerRuns.get(identity.key) ?? {
1805
+ calls: 0,
1806
+ reservationKeys: /* @__PURE__ */ new Set(),
1807
+ lastSeenAtMs: now
1808
+ };
1809
+ const reservationKey = idempotencyKey ?? this.idempotencyGenerator();
1810
+ state.lastSeenAtMs = now;
1811
+ if (state.reservationKeys.has(reservationKey)) {
1812
+ this.circuitBreakerRuns.set(identity.key, state);
1813
+ return;
1814
+ }
1815
+ const decision = this.createCircuitBreakerDecision(
1816
+ identity.customerId,
1817
+ identity.runId,
1818
+ state.calls
1819
+ );
1820
+ if (!decision.allowed) {
1821
+ throw new UsageTapError(
1822
+ "USAGETAP_CIRCUIT_OPEN",
1823
+ `Run ${identity.runId} reached its ${decision.limit}-call circuit-breaker limit`,
1824
+ {
1825
+ details: {
1826
+ reason: decision.reason,
1827
+ customerId: identity.customerId,
1828
+ runId: identity.runId,
1829
+ calls: decision.calls,
1830
+ limit: decision.limit,
1831
+ remaining: decision.remaining
1832
+ }
1833
+ }
1834
+ );
1835
+ }
1836
+ state.calls += 1;
1837
+ state.reservationKeys.add(reservationKey);
1838
+ this.circuitBreakerRuns.set(identity.key, state);
1839
+ }
1840
+ resolveRunIdentity(request) {
1841
+ const customerId = request.customerId?.trim();
1842
+ const runId = request.runId?.trim();
1843
+ if (!customerId || !runId) return void 0;
1844
+ return {
1845
+ key: `${customerId}\0${runId}`,
1846
+ customerId,
1847
+ runId
1848
+ };
1849
+ }
1850
+ createCircuitBreakerDecision(customerId, runId, calls) {
1851
+ const limit = this.circuitBreaker?.maxCallsPerRun ?? 0;
1852
+ const allowed = calls < limit;
1853
+ return {
1854
+ allowed,
1855
+ ...allowed ? {} : { reason: "max_calls_per_run" },
1856
+ customerId,
1857
+ runId,
1858
+ calls,
1859
+ limit,
1860
+ remaining: Math.max(0, limit - calls)
1861
+ };
1862
+ }
1863
+ expireInactiveRuns() {
1864
+ if (!this.circuitBreaker || this.circuitBreakerRuns.size === 0) return;
1865
+ const expiredBefore = Date.now() - this.circuitBreaker.runInactivityMs;
1866
+ for (const [key, state] of this.circuitBreakerRuns) {
1867
+ if (state.lastSeenAtMs < expiredBefore) {
1868
+ this.circuitBreakerRuns.delete(key);
1869
+ }
1870
+ }
1871
+ }
1872
+ async request(path, payload, options) {
1873
+ const url = new URL(path, this.baseUrl).toString();
1874
+ const body = payload !== void 0 ? JSON.stringify(payload) : void 0;
1875
+ const headers = this.composeHeaders(body, options);
1876
+ const resolvedRetry = resolveRetryOptions(
1877
+ this.retryDefaults,
1878
+ options.retries
1879
+ );
1880
+ const startTime = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1881
+ return runWithRetry(
1882
+ async (attempt) => {
1883
+ const startedAt = startTime();
1884
+ this.log({
1885
+ event: "request:start",
1886
+ path,
1887
+ attempt,
1888
+ idempotencyKey: options.idempotencyKey,
1889
+ correlationId: options.correlationId
1890
+ });
1891
+ const response = await this.performFetch({
1892
+ url,
1893
+ method: "POST",
1894
+ headers,
1895
+ body,
1896
+ signal: options.signal
1897
+ });
1898
+ this.log({
1899
+ event: "request:success",
1900
+ path,
1901
+ attempt,
1902
+ idempotencyKey: options.idempotencyKey,
1903
+ correlationId: response.correlationId,
1904
+ elapsedMs: startTime() - startedAt
1905
+ });
1906
+ return response;
1907
+ },
1908
+ resolvedRetry,
1909
+ (error) => this.shouldRetry(error),
1910
+ (attempt, delayMs, error) => {
1911
+ this.log({
1912
+ event: "retry:scheduled",
1913
+ path,
1914
+ attempt,
1915
+ idempotencyKey: options.idempotencyKey,
1916
+ correlationId: options.correlationId,
1917
+ error,
1918
+ elapsedMs: delayMs
1919
+ });
1920
+ },
1921
+ options.signal
1922
+ ).catch((error) => {
1923
+ this.log({
1924
+ event: "retry:exhausted",
1925
+ path,
1926
+ attempt: resolvedRetry.maxAttempts,
1927
+ idempotencyKey: options.idempotencyKey,
1928
+ correlationId: options.correlationId,
1929
+ error
1930
+ });
1931
+ throw error;
1932
+ });
1933
+ }
1934
+ async requestGet(path, options) {
1935
+ const url = new URL(path, this.baseUrl).toString();
1936
+ const headers = this.composeHeaders(void 0, options);
1937
+ const resolvedRetry = resolveRetryOptions(
1938
+ this.retryDefaults,
1939
+ options.retries
1940
+ );
1941
+ const startTime = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1942
+ return runWithRetry(
1943
+ async (attempt) => {
1944
+ const startedAt = startTime();
1945
+ this.log({
1946
+ event: "request:start",
1947
+ path,
1948
+ attempt,
1949
+ correlationId: options.correlationId
1950
+ });
1951
+ const response = await this.performFetch({
1952
+ url,
1953
+ method: "GET",
1954
+ headers,
1955
+ signal: options.signal
1956
+ });
1957
+ this.log({
1958
+ event: "request:success",
1959
+ path,
1960
+ attempt,
1961
+ correlationId: response.correlationId,
1962
+ elapsedMs: startTime() - startedAt
1963
+ });
1964
+ return response;
1965
+ },
1966
+ resolvedRetry,
1967
+ (error) => this.shouldRetry(error),
1968
+ (attempt, delayMs, error) => {
1969
+ this.log({
1970
+ event: "retry:scheduled",
1971
+ path,
1972
+ attempt,
1973
+ correlationId: options.correlationId,
1974
+ error,
1975
+ elapsedMs: delayMs
1976
+ });
1977
+ },
1978
+ options.signal
1979
+ ).catch((error) => {
1980
+ this.log({
1981
+ event: "retry:exhausted",
1982
+ path,
1983
+ attempt: resolvedRetry.maxAttempts,
1984
+ correlationId: options.correlationId,
1985
+ error
1986
+ });
1987
+ throw error;
1988
+ });
1989
+ }
1990
+ async performFetch(init) {
1991
+ let response;
1992
+ try {
1993
+ response = await this.fetchImpl(init.url, {
1994
+ method: init.method,
1995
+ headers: init.headers,
1996
+ body: init.body,
1997
+ signal: init.signal
1998
+ });
1999
+ } catch (error) {
2000
+ throw new UsageTapError(
2001
+ "USAGETAP_NETWORK_ERROR",
2002
+ "Failed to reach UsageTap",
2003
+ {
2004
+ retryable: true,
2005
+ cause: error
2006
+ }
2007
+ );
2008
+ }
2009
+ const correlationId = response.headers.get(CORRELATION_HEADER) ?? void 0;
2010
+ const text = await response.text();
2011
+ let payload;
2012
+ if (text) {
2013
+ try {
2014
+ payload = JSON.parse(text);
2015
+ } catch (error) {
2016
+ throw new UsageTapError(
2017
+ "USAGETAP_INVALID_RESPONSE",
2018
+ "UsageTap returned invalid JSON",
2019
+ {
2020
+ retryable: false,
2021
+ correlationId,
2022
+ cause: error
2023
+ }
2024
+ );
2025
+ }
2026
+ }
2027
+ if (!response.ok) {
2028
+ throw this.toHttpError(response.status, payload, correlationId);
2029
+ }
2030
+ if (!payload?.result || payload.result.status !== "ACCEPTED") {
2031
+ throw this.toApiError(payload, correlationId);
2032
+ }
2033
+ const resolvedCorrelation = payload.correlationId ?? correlationId;
2034
+ if (payload.data === void 0 || payload.data === null || !resolvedCorrelation) {
2035
+ throw new UsageTapError(
2036
+ "USAGETAP_INVALID_RESPONSE",
2037
+ "UsageTap response missing data or correlationId",
2038
+ {
2039
+ correlationId: resolvedCorrelation ?? correlationId
2040
+ }
2041
+ );
2042
+ }
2043
+ return {
2044
+ result: {
2045
+ status: payload.result.status,
2046
+ code: payload.result.code,
2047
+ message: payload.result.message,
2048
+ timestamp: payload.result.timestamp
2049
+ },
2050
+ data: payload.data,
2051
+ correlationId: resolvedCorrelation
2052
+ };
2053
+ }
2054
+ composeHeaders(body, options) {
2055
+ const headers = {
2056
+ ...this.defaultHeaders,
2057
+ [SDK_HEADER]: `js/${SDK_VERSION}`,
2058
+ "content-type": "application/json",
2059
+ accept: CANONICAL_MEDIA_TYPE2
2060
+ };
2061
+ if (!HAS_WINDOW) {
2062
+ headers["user-agent"] = `${USER_AGENT}/${SDK_VERSION}`;
2063
+ }
2064
+ if (this.authHeader === API_KEY_HEADER) {
2065
+ headers[API_KEY_HEADER] = this.apiKey;
2066
+ } else {
2067
+ headers[AUTH_HEADER] = `Bearer ${this.apiKey}`;
2068
+ }
2069
+ if (options.idempotencyKey) {
2070
+ headers[IDEMPOTENCY_HEADER] = options.idempotencyKey;
2071
+ }
2072
+ if (options.correlationId) {
2073
+ headers[CORRELATION_HEADER] = options.correlationId;
2074
+ }
2075
+ if (!body) {
2076
+ delete headers["content-type"];
2077
+ }
2078
+ if (options.headers) {
2079
+ Object.assign(headers, normalizeHeaderDictionary(options.headers));
2080
+ }
2081
+ return headers;
2082
+ }
2083
+ log(entry) {
2084
+ this.logFn?.(entry);
2085
+ }
2086
+ emitUsageMetric(event) {
2087
+ try {
2088
+ this.metricFn?.(event);
2089
+ } catch {
2090
+ }
2091
+ }
2092
+ mergeTags(tags) {
2093
+ if (!tags && !this.defaultTags) {
2094
+ return void 0;
2095
+ }
2096
+ const combined = [...this.defaultTags ?? [], ...tags ?? []].filter(
2097
+ Boolean
2098
+ );
2099
+ return combined.length ? dedupeStrings(combined) : void 0;
2100
+ }
2101
+ shouldRetry(error) {
2102
+ if (isUsageTapError(error)) {
2103
+ return Boolean(error.retryable);
2104
+ }
2105
+ if (error instanceof Error && error.name === "AbortError") {
2106
+ return false;
2107
+ }
2108
+ return false;
2109
+ }
2110
+ toHttpError(status, payload, correlationId) {
2111
+ const code = mapStatusToErrorCode(status);
2112
+ const apiCode = payload?.error?.code ?? payload?.result?.code ?? "UNKNOWN";
2113
+ const retryable = isRetryableStatus(status) || isRetryableApiCode(apiCode);
2114
+ const message = payload?.error?.message ?? payload?.result?.message ?? `UsageTap responded with HTTP ${status}`;
2115
+ return new UsageTapError(code, message, {
2116
+ status,
2117
+ retryable,
2118
+ correlationId: payload?.correlationId ?? correlationId,
2119
+ details: sanitizeDetails(payload)
2120
+ });
2121
+ }
2122
+ toApiError(payload, correlationId) {
2123
+ const normalizedCode = payload?.error?.code ?? payload?.result?.code ?? "UNKNOWN";
2124
+ const retryable = isRetryableApiCode(normalizedCode);
2125
+ const message = payload?.error?.message ?? payload?.result?.message ?? "UsageTap reported an error";
2126
+ return new UsageTapError(mapApiCodeToError(normalizedCode), message, {
2127
+ retryable,
2128
+ correlationId: payload?.correlationId ?? correlationId,
2129
+ details: sanitizeDetails(payload)
2130
+ });
2131
+ }
2132
+ };
2133
+ function mapStatusToErrorCode(status) {
2134
+ if (status === 401 || status === 403) return "USAGETAP_AUTH_ERROR";
2135
+ if (status === 400 || status === 404 || status === 409)
2136
+ return "USAGETAP_BAD_REQUEST";
2137
+ if (status === 429) return "USAGETAP_RATE_LIMITED";
2138
+ if (status >= 500) return "USAGETAP_SERVER_ERROR";
2139
+ return "USAGETAP_INVALID_RESPONSE";
2140
+ }
2141
+ function isRetryableStatus(status) {
2142
+ return status === 408 || status === 425 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
2143
+ }
2144
+ function isRetryableApiCode(code) {
2145
+ const normalized = code.toUpperCase();
2146
+ return normalized === "PAYG_CONFLICT" || normalized.includes("TRANSIENT") || normalized.includes("RETRY") || normalized.includes("TIMEOUT") || normalized.includes("THROTTLE") || normalized.includes("RATE_LIMIT");
2147
+ }
2148
+ function mapApiCodeToError(code) {
2149
+ const normalized = code.toUpperCase();
2150
+ if (normalized.includes("AUTH") || normalized.includes("TOKEN")) {
2151
+ return "USAGETAP_AUTH_ERROR";
2152
+ }
2153
+ if (normalized.includes("RATE") || normalized.includes("THROTTLE")) {
2154
+ return "USAGETAP_RATE_LIMITED";
2155
+ }
2156
+ if (normalized.includes("SERVER") || normalized.includes("TRANSIENT")) {
2157
+ return "USAGETAP_SERVER_ERROR";
2158
+ }
2159
+ if (normalized.includes("IDEMPOTENCY") || normalized.includes("VALIDATION") || normalized.includes("REQUEST")) {
2160
+ return "USAGETAP_BAD_REQUEST";
2161
+ }
2162
+ return "USAGETAP_INVALID_RESPONSE";
2163
+ }
2164
+ function sanitizeDetails(payload) {
2165
+ if (!payload) return void 0;
2166
+ const details = {};
2167
+ if (payload.result) details.result = payload.result;
2168
+ if (payload.error) details.error = payload.error;
2169
+ return Object.keys(details).length ? details : void 0;
2170
+ }
2171
+ function readEnvironmentVariable(name) {
2172
+ const runtime = globalThis;
2173
+ const value = runtime.process?.env?.[name]?.trim();
2174
+ return value || void 0;
2175
+ }
2176
+ function normalizeBaseUrl(baseUrl) {
2177
+ const trimmed = baseUrl.trim();
2178
+ if (!trimmed) return trimmed;
2179
+ return trimmed.endsWith("/") ? trimmed : `${trimmed}/`;
2180
+ }
2181
+ function normalizeHeaderDictionary(dict) {
2182
+ return Object.keys(dict).reduce((acc, key) => {
2183
+ acc[key.toLowerCase()] = dict[key];
2184
+ return acc;
2185
+ }, {});
2186
+ }
2187
+ function dedupeStrings(values) {
2188
+ return Array.from(
2189
+ new Set(values.map((value) => value.trim()).filter(Boolean))
2190
+ );
2191
+ }
2192
+ function wrapFetchImplementation(fetchCandidate, preferGlobalContext) {
2193
+ const target = preferGlobalContext ? globalThis : void 0;
2194
+ return ((...args) => target ? Reflect.apply(fetchCandidate, target, args) : fetchCandidate(...args));
2195
+ }
2196
+ function wrapEndCallError(error, correlationId) {
2197
+ if (isUsageTapError(error)) {
2198
+ return new UsageTapError("USAGETAP_END_CALL_ERROR", error.message, {
2199
+ correlationId: error.correlationId ?? correlationId,
2200
+ details: error.details,
2201
+ cause: error
2202
+ });
2203
+ }
2204
+ return new UsageTapError(
2205
+ "USAGETAP_END_CALL_ERROR",
2206
+ "Failed to finalize UsageTap call",
2207
+ {
2208
+ correlationId,
2209
+ cause: error
2210
+ }
2211
+ );
2212
+ }
2213
+
3
2214
  // src/adapters/openai.ts
2215
+ var OpenAIPromptCompressionStats = class {
2216
+ history = [];
2217
+ failures = [];
2218
+ _record(turn) {
2219
+ this.history.push(turn);
2220
+ }
2221
+ _recordFailure(failure) {
2222
+ this.failures.push(failure);
2223
+ }
2224
+ get totalOriginalTokens() {
2225
+ return this.history.reduce((sum, turn) => sum + (turn.originalTokens ?? 0), 0);
2226
+ }
2227
+ get totalCompressedTokens() {
2228
+ return this.history.reduce((sum, turn) => sum + (turn.compressedTokens ?? 0), 0);
2229
+ }
2230
+ get totalTokensSaved() {
2231
+ return this.history.reduce((sum, turn) => sum + (turn.savedTokens ?? 0), 0);
2232
+ }
2233
+ get totalOriginalCharacters() {
2234
+ return this.history.reduce((sum, turn) => sum + turn.originalCharacters, 0);
2235
+ }
2236
+ get totalCompressedCharacters() {
2237
+ return this.history.reduce((sum, turn) => sum + turn.compressedCharacters, 0);
2238
+ }
2239
+ get totalCharactersSaved() {
2240
+ return this.history.reduce((sum, turn) => sum + turn.savedCharacters, 0);
2241
+ }
2242
+ get calls() {
2243
+ return this.history.length;
2244
+ }
2245
+ get telemetryFailures() {
2246
+ return this.failures.length;
2247
+ }
2248
+ get failOpenEvents() {
2249
+ return this.history.filter(
2250
+ (turn) => turn.techniques.includes("compression-error") || turn.techniques.includes("fallback-original")
2251
+ ).length;
2252
+ }
2253
+ get tokenSavingsRatio() {
2254
+ return this.totalOriginalTokens > 0 ? this.totalTokensSaved / this.totalOriginalTokens : 0;
2255
+ }
2256
+ get savingsRatio() {
2257
+ return this.totalOriginalCharacters > 0 ? this.totalCharactersSaved / this.totalOriginalCharacters : 0;
2258
+ }
2259
+ };
4
2260
  function createOpenAIAdapter(init) {
5
- const { client, usageTap } = init;
2261
+ const { client, usageTap, provider = "openai" } = init;
6
2262
  return {
7
2263
  async invoke(params) {
8
2264
  const result = await usageTap.withUsage(
9
2265
  params.begin,
10
2266
  async (ctx) => {
2267
+ ctx.setUsage({ providerUsed: provider });
11
2268
  const response = await params.call(client, {
12
2269
  hints: ctx.begin.data.vendorHints,
13
2270
  begin: ctx.begin
14
2271
  });
15
- tryInferUsage(response, ctx.begin.data.vendorHints, params.extractUsage, ctx);
2272
+ tryInferUsage(response, ctx.begin.data.vendorHints, params.extractUsage, ctx, provider);
16
2273
  return {
17
2274
  data: response,
18
2275
  begin: ctx.begin
@@ -26,16 +2283,576 @@ function createOpenAIAdapter(init) {
26
2283
  const result = await usageTap.withUsage(
27
2284
  params.begin,
28
2285
  async (ctx) => {
2286
+ const settle = deferUsageFinalization(ctx);
2287
+ ctx.setUsage({ providerUsed: provider });
29
2288
  const { stream, onComplete } = await params.call(client, {
30
2289
  hints: ctx.begin.data.vendorHints,
31
2290
  begin: ctx.begin
32
2291
  });
33
- const wrapped = wrapStreamForUsageTap(stream, async () => {
34
- if (!onComplete) return;
2292
+ const wrapped = wrapStreamForUsageTap(stream, async (termination) => {
2293
+ try {
2294
+ if (termination === "complete" && onComplete) {
2295
+ const maybeUsage = await onComplete();
2296
+ if (maybeUsage) {
2297
+ ctx.setUsage(maybeUsage);
2298
+ }
2299
+ }
2300
+ } catch (error) {
2301
+ ctx.setError({
2302
+ code: "USAGE_FINALIZE_ERROR",
2303
+ message: error instanceof Error ? error.message : String(error)
2304
+ });
2305
+ await settle();
2306
+ throw error;
2307
+ }
2308
+ await settle();
2309
+ }, ctx);
2310
+ const finalize = async () => {
2311
+ await wrapped.__usageTapFinalize?.();
2312
+ };
2313
+ return {
2314
+ stream: wrapped,
2315
+ begin: ctx.begin,
2316
+ finalize
2317
+ };
2318
+ },
2319
+ params.withUsageOptions
2320
+ );
2321
+ return result;
2322
+ }
2323
+ };
2324
+ }
2325
+ function toNextResponse(stream, options = {}) {
2326
+ const mode = options.mode ?? "text";
2327
+ const headers = new Headers(options.headers ?? {});
2328
+ if (mode === "sse") {
2329
+ headers.set("content-type", "text/event-stream; charset=utf-8");
2330
+ headers.set("cache-control", "no-cache, no-transform");
2331
+ headers.set("connection", "keep-alive");
2332
+ headers.set("x-accel-buffering", "no");
2333
+ } else {
2334
+ headers.set("content-type", options.contentType ?? "text/plain; charset=utf-8");
2335
+ }
2336
+ const encoder = new TextEncoder();
2337
+ let iterator;
2338
+ const body = new ReadableStream({
2339
+ async start(controller) {
2340
+ try {
2341
+ const getIterator = stream[Symbol.asyncIterator];
2342
+ if (typeof getIterator !== "function") {
2343
+ controller.close();
2344
+ return;
2345
+ }
2346
+ iterator = getIterator.call(stream);
2347
+ while (true) {
2348
+ const result = await iterator.next();
2349
+ if (result.done) {
2350
+ break;
2351
+ }
2352
+ const text = chunkToText(result.value);
2353
+ if (!text) {
2354
+ continue;
2355
+ }
2356
+ if (mode === "sse") {
2357
+ controller.enqueue(encoder.encode(formatSsePayload(text, options.sse)));
2358
+ } else {
2359
+ controller.enqueue(encoder.encode(text));
2360
+ }
2361
+ }
2362
+ controller.close();
2363
+ } catch (error) {
2364
+ controller.error(error);
2365
+ } finally {
2366
+ await stream.__usageTapFinalize?.();
2367
+ }
2368
+ },
2369
+ async cancel() {
2370
+ if (!iterator) {
2371
+ const getIterator = stream[Symbol.asyncIterator];
2372
+ if (typeof getIterator === "function") {
2373
+ iterator = getIterator.call(stream);
2374
+ }
2375
+ }
2376
+ if (iterator && typeof iterator.return === "function") {
2377
+ await iterator.return();
2378
+ }
2379
+ await stream.__usageTapFinalize?.();
2380
+ }
2381
+ });
2382
+ return new Response(body, { headers });
2383
+ }
2384
+ async function pipeToResponse(stream, res, options = {}) {
2385
+ const mode = options.mode ?? "text";
2386
+ if (mode === "sse") {
2387
+ setHeaderIfPossible(res, "Content-Type", "text/event-stream; charset=utf-8");
2388
+ setHeaderIfPossible(res, "Cache-Control", "no-cache, no-transform");
2389
+ setHeaderIfPossible(res, "Connection", "keep-alive");
2390
+ setHeaderIfPossible(res, "X-Accel-Buffering", "no");
2391
+ } else {
2392
+ setHeaderIfPossible(res, "Content-Type", options.contentType ?? "text/plain; charset=utf-8");
2393
+ }
2394
+ const encoder = new TextEncoder();
2395
+ const iterator = stream[Symbol.asyncIterator]();
2396
+ try {
2397
+ while (true) {
2398
+ const result = await iterator.next();
2399
+ if (result.done) {
2400
+ break;
2401
+ }
2402
+ const text = chunkToText(result.value);
2403
+ if (!text) {
2404
+ continue;
2405
+ }
2406
+ const payload = mode === "sse" ? formatSsePayload(text, options.sse) : text;
2407
+ res.write(Buffer.from(encoder.encode(payload)));
2408
+ res.flush?.();
2409
+ }
2410
+ } finally {
2411
+ res.end();
2412
+ await stream.__usageTapFinalize?.();
2413
+ }
2414
+ }
2415
+ var USAGETAP_CORRELATION_HEADER = "x-usage-correlation-id";
2416
+ function withSampling(client, options = {}) {
2417
+ if (!client || !options) {
2418
+ throw new UsageTapError(
2419
+ "USAGETAP_BAD_REQUEST",
2420
+ "withSampling requires an OpenAI-compatible client and sampling options"
2421
+ );
2422
+ }
2423
+ const { apiKey, usageTapClient, provider = "openai", ...policy } = options;
2424
+ const localPolicy = typeof policy.rate === "number" ? policy : void 0;
2425
+ const usageTap = usageTapClient ?? new UsageTapClient({ apiKey, sampling: localPolicy });
2426
+ const wrapCreate = (create) => async (params, requestOptions) => {
2427
+ const { usageTap: callContextRaw, ...providerOptions } = requestOptions ?? {};
2428
+ const callContext = isObjectRecord(callContextRaw) ? callContextRaw : {};
2429
+ const streaming = params.stream === true;
2430
+ const decision = streaming ? Promise.resolve(false) : usageTap.shouldSampleAsync({
2431
+ customerId: readString(callContext.customerId),
2432
+ feature: readString(callContext.feature),
2433
+ input: params
2434
+ }, localPolicy);
2435
+ const startedAt = Date.now();
2436
+ try {
2437
+ const response = await create(
2438
+ params,
2439
+ Object.keys(providerOptions).length ? providerOptions : void 0
2440
+ );
2441
+ const selected = await decision;
2442
+ if (selected) {
2443
+ const record = isObjectRecord(response) ? response : {};
2444
+ await usageTap.captureSample({
2445
+ customerId: readString(callContext.customerId),
2446
+ feature: readString(callContext.feature),
2447
+ environment: readString(callContext.environment),
2448
+ tags: readStringArray(callContext.tags),
2449
+ provider,
2450
+ model: readString(record.model) ?? readString(params.model),
2451
+ input: params,
2452
+ output: response,
2453
+ usage: record.usage,
2454
+ latencyMs: Date.now() - startedAt
2455
+ }).catch(() => void 0);
2456
+ }
2457
+ return response;
2458
+ } catch (error) {
2459
+ const selected = await decision;
2460
+ if (selected) {
2461
+ await usageTap.captureSample({
2462
+ customerId: readString(callContext.customerId),
2463
+ feature: readString(callContext.feature),
2464
+ environment: readString(callContext.environment),
2465
+ tags: readStringArray(callContext.tags),
2466
+ provider,
2467
+ model: readString(params.model),
2468
+ input: params,
2469
+ latencyMs: Date.now() - startedAt,
2470
+ error: serializeSamplingError(error)
2471
+ }).catch(() => void 0);
2472
+ }
2473
+ throw error;
2474
+ }
2475
+ };
2476
+ const chat = client.chat?.completions ? new Proxy(client.chat, {
2477
+ get(target, prop, receiver) {
2478
+ if (prop !== "completions") return safeReflectGet(target, prop, receiver);
2479
+ const completions = target.completions;
2480
+ return new Proxy(completions, {
2481
+ get(completionTarget, completionProp, completionReceiver) {
2482
+ if (completionProp === "create") {
2483
+ return wrapCreate(
2484
+ completionTarget.create.bind(completionTarget)
2485
+ );
2486
+ }
2487
+ return safeReflectGet(
2488
+ completionTarget,
2489
+ completionProp,
2490
+ completionReceiver
2491
+ );
2492
+ }
2493
+ });
2494
+ }
2495
+ }) : void 0;
2496
+ const responses = typeof client.responses !== "undefined" && client.responses ? new Proxy(client.responses, {
2497
+ get(target, prop, receiver) {
2498
+ if (prop === "create") {
2499
+ const create = Reflect.get(target, prop, receiver);
2500
+ return wrapCreate(create.bind(target));
2501
+ }
2502
+ return safeReflectGet(target, prop, receiver);
2503
+ }
2504
+ }) : void 0;
2505
+ return new Proxy(client, {
2506
+ get(target, prop, receiver) {
2507
+ if (prop === "chat" && chat) return chat;
2508
+ if (prop === "responses" && responses) return responses;
2509
+ if (prop === "unwrap") return () => target;
2510
+ return safeReflectGet(target, prop, receiver);
2511
+ }
2512
+ });
2513
+ }
2514
+ function safeReflectGet(target, prop, receiver) {
2515
+ return Reflect.get(target, prop, receiver);
2516
+ }
2517
+ function readStringArray(value) {
2518
+ if (!Array.isArray(value)) return void 0;
2519
+ const strings = value.filter((item) => typeof item === "string");
2520
+ return strings.length ? strings : void 0;
2521
+ }
2522
+ function readString(value) {
2523
+ return typeof value === "string" && value.trim() ? value : void 0;
2524
+ }
2525
+ function serializeSamplingError(error) {
2526
+ if (error instanceof Error) {
2527
+ return { name: error.name, message: error.message };
2528
+ }
2529
+ return { message: String(error) };
2530
+ }
2531
+ function normalizeMeteredOpenAISampling(options) {
2532
+ if (!options) return void 0;
2533
+ if (options === true) return { provider: "openai" };
2534
+ const { provider = "openai", ...policyFields } = options;
2535
+ return {
2536
+ provider,
2537
+ policy: typeof policyFields.rate === "number" ? policyFields : void 0
2538
+ };
2539
+ }
2540
+ function startMeteredOpenAISampleDecision({
2541
+ usageTap,
2542
+ sampling,
2543
+ beginRequest,
2544
+ input
2545
+ }) {
2546
+ if (!sampling) return Promise.resolve(false);
2547
+ return usageTap.shouldSampleAsync(
2548
+ {
2549
+ customerId: beginRequest.customerId,
2550
+ feature: beginRequest.feature,
2551
+ input
2552
+ },
2553
+ sampling.policy
2554
+ );
2555
+ }
2556
+ async function captureMeteredOpenAISample({
2557
+ usageTap,
2558
+ sampling,
2559
+ decision,
2560
+ ctx,
2561
+ beginRequest,
2562
+ input,
2563
+ response,
2564
+ error,
2565
+ startedAt
2566
+ }) {
2567
+ if (!sampling) return;
2568
+ let selected = false;
2569
+ try {
2570
+ selected = await decision;
2571
+ } catch {
2572
+ return;
2573
+ }
2574
+ if (!selected) return;
2575
+ const record = isObjectRecord(response) ? response : {};
2576
+ await usageTap.captureSample({
2577
+ sampleId: ctx.begin.data.callId,
2578
+ callId: ctx.begin.data.callId,
2579
+ customerId: beginRequest.customerId,
2580
+ feature: beginRequest.feature,
2581
+ tags: beginRequest.tags,
2582
+ provider: sampling.provider,
2583
+ model: readString(record.model) ?? readString(input.model),
2584
+ input,
2585
+ ...response === void 0 ? {} : { output: response },
2586
+ usage: record.usage,
2587
+ latencyMs: Date.now() - startedAt,
2588
+ ...error === void 0 ? {} : { error: serializeSamplingError(error) }
2589
+ }).catch(() => void 0);
2590
+ }
2591
+ function withMetering(client, customer) {
2592
+ const config = typeof customer === "string" ? { customerId: customer } : customer;
2593
+ if (!config?.customerId) {
2594
+ throw new UsageTapError(
2595
+ "USAGETAP_BAD_REQUEST",
2596
+ "withMetering requires a customerId"
2597
+ );
2598
+ }
2599
+ const {
2600
+ apiKey,
2601
+ usageTapClient,
2602
+ applyVendorHints,
2603
+ promptCompression,
2604
+ sampling,
2605
+ provider,
2606
+ ...defaultContext
2607
+ } = config;
2608
+ const usageTap = usageTapClient ?? new UsageTapClient({ apiKey });
2609
+ const normalizedCompression = promptCompression === true ? { provider: "usagetap" } : promptCompression ? { provider: "usagetap", ...promptCompression } : void 0;
2610
+ return wrapOpenAI(client, usageTap, {
2611
+ defaultContext,
2612
+ applyVendorHints,
2613
+ promptCompression: normalizedCompression,
2614
+ sampling,
2615
+ provider
2616
+ });
2617
+ }
2618
+ function wrapOpenAI(client, usageTap, options = {}) {
2619
+ if (!client) {
2620
+ throw new UsageTapError("USAGETAP_BAD_REQUEST", "wrapOpenAI requires an OpenAI client instance");
2621
+ }
2622
+ const defaultContext = options.defaultContext;
2623
+ const applyVendorHints = options.applyVendorHints !== false;
2624
+ const defaultPromptCompression = normalizePromptCompressionOptions(options.promptCompression);
2625
+ const defaultSampling = normalizeMeteredOpenAISampling(options.sampling);
2626
+ const provider = options.provider ?? "openai";
2627
+ const promptCompressionStats = new OpenAIPromptCompressionStats();
2628
+ const proxiedChat = client.chat ? createChatProxy(
2629
+ client.chat,
2630
+ usageTap,
2631
+ defaultContext,
2632
+ applyVendorHints,
2633
+ defaultPromptCompression,
2634
+ promptCompressionStats,
2635
+ defaultSampling,
2636
+ provider
2637
+ ) : void 0;
2638
+ const proxiedResponses = typeof client.responses !== "undefined" ? createResponsesProxy(
2639
+ client.responses,
2640
+ usageTap,
2641
+ defaultContext,
2642
+ applyVendorHints,
2643
+ defaultPromptCompression,
2644
+ promptCompressionStats,
2645
+ defaultSampling,
2646
+ provider
2647
+ ) : void 0;
2648
+ const handler = {
2649
+ get(target, prop, receiver) {
2650
+ if (prop === "chat" && proxiedChat) {
2651
+ return proxiedChat;
2652
+ }
2653
+ if (prop === "responses" && typeof target.responses !== "undefined") {
2654
+ return proxiedResponses ?? Reflect.get(target, prop, receiver);
2655
+ }
2656
+ if (prop === "toNextResponse") {
2657
+ return toNextResponse;
2658
+ }
2659
+ if (prop === "pipeToResponse") {
2660
+ return pipeToResponse;
2661
+ }
2662
+ if (prop === "promptCompression") {
2663
+ return promptCompressionStats;
2664
+ }
2665
+ if (prop === "unwrap") {
2666
+ return () => target;
2667
+ }
2668
+ return Reflect.get(target, prop, receiver);
2669
+ }
2670
+ };
2671
+ return new Proxy(client, handler);
2672
+ }
2673
+ function createChatProxy(resource, usageTap, defaultContext, applyVendorHints, defaultPromptCompression, promptCompressionStats, defaultSampling, provider) {
2674
+ const completions = createChatCompletionsProxy(
2675
+ resource.completions,
2676
+ usageTap,
2677
+ defaultContext,
2678
+ applyVendorHints,
2679
+ defaultPromptCompression,
2680
+ promptCompressionStats,
2681
+ defaultSampling,
2682
+ provider
2683
+ );
2684
+ const handler = {
2685
+ get(target, prop, receiver) {
2686
+ if (prop === "completions") {
2687
+ return completions;
2688
+ }
2689
+ return Reflect.get(target, prop, receiver);
2690
+ }
2691
+ };
2692
+ return new Proxy(resource, handler);
2693
+ }
2694
+ function createResponsesProxy(resource, usageTap, defaultContext, applyVendorHints, defaultPromptCompression, promptCompressionStats, defaultSampling, provider) {
2695
+ if (!resource || typeof resource !== "object") {
2696
+ return void 0;
2697
+ }
2698
+ if (!("create" in resource) || typeof resource.create !== "function") {
2699
+ return resource;
2700
+ }
2701
+ const originalCreate = resource.create.bind(resource);
2702
+ const wrappedCreate = (params, options) => {
2703
+ const {
2704
+ requestOptions,
2705
+ usageContext,
2706
+ withUsage,
2707
+ promptCompression
2708
+ } = splitUsageOptions(options);
2709
+ const beginRequest = responsesBeginRequest(
2710
+ resolveBeginRequest(defaultContext, usageContext),
2711
+ params
2712
+ );
2713
+ const wantsStream = isStreamingRequest(params);
2714
+ return usageTap.withUsage(beginRequest, async (ctx) => {
2715
+ const settle = wantsStream ? deferUsageFinalization(ctx) : void 0;
2716
+ const sampleStartedAt = Date.now();
2717
+ const sampleDecision = wantsStream ? Promise.resolve(false) : startMeteredOpenAISampleDecision({
2718
+ usageTap,
2719
+ sampling: defaultSampling,
2720
+ beginRequest,
2721
+ input: params
2722
+ });
2723
+ const hintedParams = applyVendorHints ? applyResponsesVendorHints(params, ctx.begin.data.vendorHints) : params;
2724
+ const finalParams = await compressResponsesParamsForCall({
2725
+ params: hintedParams,
2726
+ usageTap,
2727
+ ctx,
2728
+ defaultPromptCompression,
2729
+ callPromptCompression: promptCompression,
2730
+ stats: promptCompressionStats,
2731
+ withUsage,
2732
+ operation: "responses.create"
2733
+ });
2734
+ ctx.setUsage(openAIRequestExecutionMetadata(finalParams, provider));
2735
+ const request = attachCorrelationHeader(requestOptions, ctx.begin.correlationId);
2736
+ if (wantsStream) {
2737
+ const apiPromise2 = originalCreate(finalParams, request);
2738
+ const wrappedPromise2 = transformApiPromise(apiPromise2, (rawStream) => {
2739
+ ensureAsyncIterable(rawStream, "responses.create");
2740
+ const wrappedStream = wrapStreamForUsageTap(rawStream, async (termination) => {
2741
+ try {
2742
+ if (termination === "complete") {
2743
+ const usage = await extractUsageFromStream(rawStream, ctx.begin.data.vendorHints, provider);
2744
+ if (usage) {
2745
+ ctx.setUsage(usage);
2746
+ }
2747
+ }
2748
+ } catch (error) {
2749
+ ctx.setError({
2750
+ code: "USAGE_FINALIZE_ERROR",
2751
+ message: error instanceof Error ? error.message : String(error)
2752
+ });
2753
+ throw error;
2754
+ } finally {
2755
+ await settle?.();
2756
+ }
2757
+ }, ctx, (chunk) => {
2758
+ tryInferUsageFromStreamChunk(
2759
+ chunk,
2760
+ ctx.begin.data.vendorHints,
2761
+ ctx,
2762
+ provider
2763
+ );
2764
+ });
2765
+ return wrappedStream;
2766
+ });
2767
+ return wrappedPromise2;
2768
+ }
2769
+ const apiPromise = originalCreate(finalParams, request);
2770
+ const wrappedPromise = transformApiPromise(apiPromise, async (response) => {
2771
+ tryInferUsage(response, ctx.begin.data.vendorHints, void 0, ctx, provider);
2772
+ await captureMeteredOpenAISample({
2773
+ usageTap,
2774
+ sampling: defaultSampling,
2775
+ decision: sampleDecision,
2776
+ ctx,
2777
+ beginRequest,
2778
+ input: params,
2779
+ response,
2780
+ startedAt: sampleStartedAt
2781
+ });
2782
+ return response;
2783
+ }, async (error) => {
2784
+ await captureMeteredOpenAISample({
2785
+ usageTap,
2786
+ sampling: defaultSampling,
2787
+ decision: sampleDecision,
2788
+ ctx,
2789
+ beginRequest,
2790
+ input: params,
2791
+ error,
2792
+ startedAt: sampleStartedAt
2793
+ });
2794
+ throw error;
2795
+ });
2796
+ return wrappedPromise;
2797
+ }, withUsage);
2798
+ };
2799
+ const handler = {
2800
+ get(target, prop, receiver) {
2801
+ if (prop === "create") {
2802
+ return wrappedCreate;
2803
+ }
2804
+ return Reflect.get(target, prop, receiver);
2805
+ }
2806
+ };
2807
+ return new Proxy(resource, handler);
2808
+ }
2809
+ function createChatCompletionsProxy(resource, usageTap, defaultContext, applyVendorHints, defaultPromptCompression, promptCompressionStats, defaultSampling, provider) {
2810
+ const originalCreate = resource.create.bind(resource);
2811
+ const streamCandidate = resource.stream;
2812
+ const originalStream = typeof streamCandidate === "function" ? streamCandidate.bind(resource) : void 0;
2813
+ const wrappedCreate = (params, options) => {
2814
+ const {
2815
+ requestOptions,
2816
+ usageContext,
2817
+ withUsage,
2818
+ promptCompression
2819
+ } = splitUsageOptions(options);
2820
+ const beginRequest = resolveBeginRequest(defaultContext, usageContext);
2821
+ const wantsStream = isStreamingRequest(params);
2822
+ return usageTap.withUsage(beginRequest, async (ctx) => {
2823
+ const settle = wantsStream ? deferUsageFinalization(ctx) : void 0;
2824
+ const sampleStartedAt = Date.now();
2825
+ const sampleDecision = wantsStream ? Promise.resolve(false) : startMeteredOpenAISampleDecision({
2826
+ usageTap,
2827
+ sampling: defaultSampling,
2828
+ beginRequest,
2829
+ input: params
2830
+ });
2831
+ const hintedParams = applyVendorHints ? applyChatVendorHints(params, ctx.begin.data.vendorHints) : params;
2832
+ const compressedParams = await compressChatParamsForCall({
2833
+ params: hintedParams,
2834
+ usageTap,
2835
+ ctx,
2836
+ defaultPromptCompression,
2837
+ callPromptCompression: promptCompression,
2838
+ stats: promptCompressionStats,
2839
+ withUsage,
2840
+ operation: "chat.completions.create"
2841
+ });
2842
+ const finalParams = wantsStream ? ensureOpenAIStreamUsage(compressedParams) : compressedParams;
2843
+ ctx.setUsage(openAIRequestExecutionMetadata(finalParams, provider));
2844
+ const request = attachCorrelationHeader(requestOptions, ctx.begin.correlationId);
2845
+ if (wantsStream) {
2846
+ const apiPromise2 = originalCreate(finalParams, request);
2847
+ const wrappedPromise2 = transformApiPromise(apiPromise2, (rawStream) => {
2848
+ ensureAsyncIterable(rawStream, "chat.completions.create");
2849
+ const wrappedStream2 = wrapStreamForUsageTap(rawStream, async (termination) => {
35
2850
  try {
36
- const maybeUsage = await onComplete();
37
- if (maybeUsage) {
38
- ctx.setUsage(maybeUsage);
2851
+ if (termination === "complete") {
2852
+ const usage = await extractUsageFromStream(rawStream, ctx.begin.data.vendorHints, provider);
2853
+ if (usage) {
2854
+ ctx.setUsage(usage);
2855
+ }
39
2856
  }
40
2857
  } catch (error) {
41
2858
  ctx.setError({
@@ -43,34 +2860,967 @@ function createOpenAIAdapter(init) {
43
2860
  message: error instanceof Error ? error.message : String(error)
44
2861
  });
45
2862
  throw error;
2863
+ } finally {
2864
+ await settle?.();
46
2865
  }
47
- }, ctx);
48
- const finalize = async () => {
49
- await wrapped.__usageTapFinalize?.();
50
- };
51
- return {
52
- stream: wrapped,
53
- begin: ctx.begin,
54
- finalize
55
- };
56
- },
57
- params.withUsageOptions
58
- );
59
- return result;
2866
+ }, ctx, (chunk) => {
2867
+ tryInferUsageFromStreamChunk(
2868
+ chunk,
2869
+ ctx.begin.data.vendorHints,
2870
+ ctx,
2871
+ provider
2872
+ );
2873
+ });
2874
+ return wrappedStream2;
2875
+ });
2876
+ return wrappedPromise2;
2877
+ }
2878
+ const apiPromise = originalCreate(finalParams, request);
2879
+ const wrappedPromise = transformApiPromise(apiPromise, async (response) => {
2880
+ tryInferUsage(response, ctx.begin.data.vendorHints, void 0, ctx, provider);
2881
+ await captureMeteredOpenAISample({
2882
+ usageTap,
2883
+ sampling: defaultSampling,
2884
+ decision: sampleDecision,
2885
+ ctx,
2886
+ beginRequest,
2887
+ input: params,
2888
+ response,
2889
+ startedAt: sampleStartedAt
2890
+ });
2891
+ return response;
2892
+ }, async (error) => {
2893
+ await captureMeteredOpenAISample({
2894
+ usageTap,
2895
+ sampling: defaultSampling,
2896
+ decision: sampleDecision,
2897
+ ctx,
2898
+ beginRequest,
2899
+ input: params,
2900
+ error,
2901
+ startedAt: sampleStartedAt
2902
+ });
2903
+ throw error;
2904
+ });
2905
+ return wrappedPromise;
2906
+ }, withUsage);
2907
+ };
2908
+ const wrappedStream = originalStream ? (params, options) => {
2909
+ const {
2910
+ requestOptions,
2911
+ usageContext,
2912
+ withUsage,
2913
+ promptCompression
2914
+ } = splitUsageOptions(options);
2915
+ const beginRequest = resolveBeginRequest(defaultContext, usageContext);
2916
+ return usageTap.withUsage(beginRequest, async (ctx) => {
2917
+ const settle = deferUsageFinalization(ctx);
2918
+ const hintedParams = applyVendorHints ? applyChatVendorHints(params, ctx.begin.data.vendorHints) : params;
2919
+ const compressedParams = await compressChatParamsForCall({
2920
+ params: hintedParams,
2921
+ usageTap,
2922
+ ctx,
2923
+ defaultPromptCompression,
2924
+ callPromptCompression: promptCompression,
2925
+ stats: promptCompressionStats,
2926
+ withUsage,
2927
+ operation: "chat.completions.stream"
2928
+ });
2929
+ const finalParams = ensureOpenAIStreamUsage(compressedParams);
2930
+ ctx.setUsage(openAIRequestExecutionMetadata(finalParams, provider));
2931
+ const request = attachCorrelationHeader(requestOptions, ctx.begin.correlationId);
2932
+ const apiPromise = originalStream(finalParams, request);
2933
+ const wrappedPromise = transformApiPromise(apiPromise, (rawStream) => {
2934
+ ensureAsyncIterable(rawStream, "chat.completions.stream");
2935
+ const wrappedStreamInner = wrapStreamForUsageTap(rawStream, async (termination) => {
2936
+ try {
2937
+ if (termination === "complete") {
2938
+ const usage = await extractUsageFromStream(
2939
+ rawStream,
2940
+ ctx.begin.data.vendorHints,
2941
+ provider
2942
+ );
2943
+ if (usage) {
2944
+ ctx.setUsage(usage);
2945
+ }
2946
+ }
2947
+ } catch (error) {
2948
+ ctx.setError({
2949
+ code: "USAGE_FINALIZE_ERROR",
2950
+ message: error instanceof Error ? error.message : String(error)
2951
+ });
2952
+ throw error;
2953
+ } finally {
2954
+ await settle();
2955
+ }
2956
+ }, ctx, (chunk) => {
2957
+ tryInferUsageFromStreamChunk(
2958
+ chunk,
2959
+ ctx.begin.data.vendorHints,
2960
+ ctx,
2961
+ provider
2962
+ );
2963
+ });
2964
+ return wrappedStreamInner;
2965
+ });
2966
+ return wrappedPromise;
2967
+ }, withUsage);
2968
+ } : void 0;
2969
+ const handler = {
2970
+ get(target, prop, receiver) {
2971
+ if (prop === "create") {
2972
+ return wrappedCreate;
2973
+ }
2974
+ if (prop === "stream" && wrappedStream) {
2975
+ return wrappedStream;
2976
+ }
2977
+ return Reflect.get(target, prop, receiver);
2978
+ }
2979
+ };
2980
+ return new Proxy(resource, handler);
2981
+ }
2982
+ async function compressChatParamsForCall(args) {
2983
+ const compression = resolveEffectivePromptCompressionOptions(
2984
+ args.defaultPromptCompression,
2985
+ args.callPromptCompression
2986
+ );
2987
+ if (!compression) {
2988
+ return args.params;
2989
+ }
2990
+ const outcome = await compressChatParams(
2991
+ args.params,
2992
+ args.usageTap,
2993
+ compression,
2994
+ args.withUsage?.signal
2995
+ );
2996
+ await recordCompressionOutcome({
2997
+ outcome,
2998
+ compression,
2999
+ usageTap: args.usageTap,
3000
+ ctx: args.ctx,
3001
+ stats: args.stats,
3002
+ withUsage: args.withUsage,
3003
+ operation: args.operation
3004
+ });
3005
+ return outcome.params;
3006
+ }
3007
+ async function compressResponsesParamsForCall(args) {
3008
+ const compression = resolveEffectivePromptCompressionOptions(
3009
+ args.defaultPromptCompression,
3010
+ args.callPromptCompression
3011
+ );
3012
+ if (!compression) {
3013
+ return args.params;
3014
+ }
3015
+ const outcome = await compressResponsesParams(
3016
+ args.params,
3017
+ args.usageTap,
3018
+ compression,
3019
+ args.withUsage?.signal
3020
+ );
3021
+ await recordCompressionOutcome({
3022
+ outcome,
3023
+ compression,
3024
+ usageTap: args.usageTap,
3025
+ ctx: args.ctx,
3026
+ stats: args.stats,
3027
+ withUsage: args.withUsage,
3028
+ operation: args.operation
3029
+ });
3030
+ return outcome.params;
3031
+ }
3032
+ async function recordCompressionOutcome(args) {
3033
+ const telemetry = buildPromptCompressionTelemetry(args.outcome.segments);
3034
+ if (!telemetry) {
3035
+ return;
3036
+ }
3037
+ const turn = {
3038
+ ...telemetry,
3039
+ callId: args.ctx.begin.data.callId,
3040
+ operation: args.operation,
3041
+ messagesCompressed: args.outcome.segments.length,
3042
+ timestamp: Date.now()
3043
+ };
3044
+ args.stats._record(turn);
3045
+ try {
3046
+ await args.usageTap.recordPromptCompression(
3047
+ {
3048
+ callId: args.ctx.begin.data.callId,
3049
+ promptCompression: telemetry
3050
+ },
3051
+ promptCompressionRequestOptions(args.withUsage, args.ctx.begin.correlationId)
3052
+ );
3053
+ } catch (error) {
3054
+ args.stats._recordFailure({
3055
+ callId: args.ctx.begin.data.callId,
3056
+ operation: args.operation,
3057
+ stage: "telemetry",
3058
+ message: error instanceof Error ? error.message : String(error),
3059
+ timestamp: Date.now()
3060
+ });
3061
+ if (args.compression.failOpen === false) {
3062
+ throw error;
3063
+ }
3064
+ }
3065
+ }
3066
+ async function compressChatParams(params, usageTap, compression, signal) {
3067
+ if (!params || typeof params !== "object") {
3068
+ return { params, segments: [] };
3069
+ }
3070
+ const source = cloneRecord(params);
3071
+ const messages = Array.isArray(source.messages) ? source.messages : void 0;
3072
+ if (!messages) {
3073
+ return { params, segments: [] };
3074
+ }
3075
+ if (isBelowMinContextTokens(
3076
+ { messages, tools: source.tools },
3077
+ compression.minContextTokens
3078
+ )) {
3079
+ return { params, segments: [] };
3080
+ }
3081
+ if (shouldUseUsageTapMessageEndpoint(compression)) {
3082
+ const result = await usageTap.compressPromptMessages(source, {
3083
+ provider: "usagetap",
3084
+ failOpen: compression.failOpen,
3085
+ mode: compression.mode,
3086
+ latencyBudgetMs: compression.latencyBudgetMs,
3087
+ compactEmptyUserMessages: compression.compactEmptyUserMessages,
3088
+ compactDuplicateUserTextParts: compression.compactDuplicateUserTextParts,
3089
+ aggressiveness: resolveMessageEndpointAggressiveness(compression),
3090
+ signal
3091
+ });
3092
+ return {
3093
+ params: result.compressedInput,
3094
+ segments: [{ role: "user", result }]
3095
+ };
3096
+ }
3097
+ const messageResults = await Promise.all(
3098
+ messages.map(
3099
+ (message) => compressOpenAIMessage(message, usageTap, compression, signal)
3100
+ )
3101
+ );
3102
+ return {
3103
+ params: {
3104
+ ...source,
3105
+ messages: messageResults.map((result) => result.value)
3106
+ },
3107
+ segments: messageResults.flatMap((result) => result.segments)
3108
+ };
3109
+ }
3110
+ async function compressResponsesParams(params, usageTap, compression, signal) {
3111
+ if (!params || typeof params !== "object") {
3112
+ return { params, segments: [] };
3113
+ }
3114
+ const source = cloneRecord(params);
3115
+ const segments = [];
3116
+ if (isBelowMinContextTokens(
3117
+ {
3118
+ instructions: source.instructions,
3119
+ input: source.input,
3120
+ tools: source.tools
3121
+ },
3122
+ compression.minContextTokens
3123
+ )) {
3124
+ return { params, segments };
3125
+ }
3126
+ if (typeof source.instructions === "string") {
3127
+ const compressed = await compressTextForRole(
3128
+ source.instructions,
3129
+ "system",
3130
+ usageTap,
3131
+ compression,
3132
+ signal
3133
+ );
3134
+ if (compressed) {
3135
+ source.instructions = compressed.text;
3136
+ segments.push(compressed.segment);
3137
+ }
3138
+ }
3139
+ if (typeof source.input === "string") {
3140
+ const compressed = await compressTextForRole(
3141
+ source.input,
3142
+ "user",
3143
+ usageTap,
3144
+ compression,
3145
+ signal
3146
+ );
3147
+ if (compressed) {
3148
+ source.input = compressed.text;
3149
+ segments.push(compressed.segment);
3150
+ }
3151
+ } else if (Array.isArray(source.input)) {
3152
+ const inputResults = await Promise.all(
3153
+ source.input.map(
3154
+ (item) => compressResponsesInputItem(item, usageTap, compression, signal)
3155
+ )
3156
+ );
3157
+ source.input = inputResults.map((result) => result.value);
3158
+ segments.push(...inputResults.flatMap((result) => result.segments));
3159
+ }
3160
+ return {
3161
+ params: source,
3162
+ segments
3163
+ };
3164
+ }
3165
+ async function compressOpenAIMessage(message, usageTap, compression, signal) {
3166
+ if (!isObjectRecord(message)) {
3167
+ return { value: message, segments: [] };
3168
+ }
3169
+ const role = mapOpenAIRole(message.role);
3170
+ if (!role) {
3171
+ return { value: message, segments: [] };
3172
+ }
3173
+ const content = message.content;
3174
+ if (typeof content === "string") {
3175
+ const compressed = await compressTextForRole(
3176
+ content,
3177
+ role,
3178
+ usageTap,
3179
+ compression,
3180
+ signal
3181
+ );
3182
+ if (!compressed) {
3183
+ return { value: message, segments: [] };
3184
+ }
3185
+ return {
3186
+ value: { ...message, content: compressed.text },
3187
+ segments: [compressed.segment]
3188
+ };
3189
+ }
3190
+ if (Array.isArray(content)) {
3191
+ const blockResults = await Promise.all(
3192
+ content.map(
3193
+ (block) => compressOpenAITextBlock(block, role, usageTap, compression, signal)
3194
+ )
3195
+ );
3196
+ const segments = blockResults.flatMap(
3197
+ (result) => result.segment ? [result.segment] : []
3198
+ );
3199
+ return {
3200
+ value: segments.length ? { ...message, content: blockResults.map((result) => result.value) } : message,
3201
+ segments
3202
+ };
3203
+ }
3204
+ return { value: message, segments: [] };
3205
+ }
3206
+ async function compressOpenAITextBlock(block, role, usageTap, compression, signal) {
3207
+ if (!isObjectRecord(block) || block.type !== "text" || typeof block.text !== "string") {
3208
+ return { value: block };
3209
+ }
3210
+ const compressed = await compressTextForRole(
3211
+ block.text,
3212
+ role,
3213
+ usageTap,
3214
+ compression,
3215
+ signal
3216
+ );
3217
+ if (!compressed) {
3218
+ return { value: block };
3219
+ }
3220
+ return {
3221
+ value: { ...block, text: compressed.text },
3222
+ segment: compressed.segment
3223
+ };
3224
+ }
3225
+ async function compressResponsesInputItem(item, usageTap, compression, signal) {
3226
+ if (!isObjectRecord(item)) {
3227
+ return { value: item, segments: [] };
3228
+ }
3229
+ const specialToolRole = mapResponsesItemTypeToRole(item.type);
3230
+ const role = specialToolRole ?? mapOpenAIRole(item.role);
3231
+ const segments = [];
3232
+ let next = item;
3233
+ if (role && typeof item.content === "string") {
3234
+ const compressed = await compressTextForRole(
3235
+ item.content,
3236
+ role,
3237
+ usageTap,
3238
+ compression,
3239
+ signal
3240
+ );
3241
+ if (compressed) {
3242
+ next = { ...next, content: compressed.text };
3243
+ segments.push(compressed.segment);
3244
+ }
3245
+ } else if (role && Array.isArray(item.content)) {
3246
+ const contentResults = await Promise.all(
3247
+ item.content.map(
3248
+ (block) => compressResponsesContentBlock(block, role, usageTap, compression, signal)
3249
+ )
3250
+ );
3251
+ segments.push(
3252
+ ...contentResults.flatMap(
3253
+ (result) => result.segment ? [result.segment] : []
3254
+ )
3255
+ );
3256
+ if (segments.length) {
3257
+ next = {
3258
+ ...next,
3259
+ content: contentResults.map((result) => result.value)
3260
+ };
3261
+ }
3262
+ }
3263
+ if (specialToolRole && typeof item.output === "string") {
3264
+ const compressed = await compressTextForRole(
3265
+ item.output,
3266
+ specialToolRole,
3267
+ usageTap,
3268
+ compression,
3269
+ signal
3270
+ );
3271
+ if (compressed) {
3272
+ next = { ...next, output: compressed.text };
3273
+ segments.push(compressed.segment);
3274
+ }
3275
+ }
3276
+ return { value: next, segments };
3277
+ }
3278
+ async function compressResponsesContentBlock(block, role, usageTap, compression, signal) {
3279
+ if (!isObjectRecord(block)) {
3280
+ return { value: block };
3281
+ }
3282
+ if ((block.type === "input_text" || block.type === "text") && typeof block.text === "string") {
3283
+ const compressed = await compressTextForRole(
3284
+ block.text,
3285
+ role,
3286
+ usageTap,
3287
+ compression,
3288
+ signal
3289
+ );
3290
+ if (compressed) {
3291
+ return {
3292
+ value: { ...block, text: compressed.text },
3293
+ segment: compressed.segment
3294
+ };
3295
+ }
3296
+ }
3297
+ if (role === "tool" && typeof block.output === "string") {
3298
+ const compressed = await compressTextForRole(
3299
+ block.output,
3300
+ role,
3301
+ usageTap,
3302
+ compression,
3303
+ signal
3304
+ );
3305
+ if (compressed) {
3306
+ return {
3307
+ value: { ...block, output: compressed.text },
3308
+ segment: compressed.segment
3309
+ };
3310
+ }
3311
+ }
3312
+ return { value: block };
3313
+ }
3314
+ async function compressTextForRole(text, role, usageTap, compression, signal) {
3315
+ if (!text.trim()) {
3316
+ return void 0;
3317
+ }
3318
+ const roleOptions = resolveRoleCompressionOptions(compression, role);
3319
+ if (!roleOptions) {
3320
+ return void 0;
3321
+ }
3322
+ const estimatedTokens = estimatePromptTokens(text);
3323
+ if (typeof roleOptions.minTokens === "number" && estimatedTokens < roleOptions.minTokens) {
3324
+ return void 0;
3325
+ }
3326
+ const result = await usageTap.compressPromptInput(text, {
3327
+ provider: roleOptions.provider,
3328
+ failOpen: roleOptions.failOpen,
3329
+ tokenCompanyModel: roleOptions.tokenCompanyModel,
3330
+ aggressiveness: roleOptions.aggressiveness,
3331
+ tokenCompanyAggressiveness: roleOptions.tokenCompanyAggressiveness,
3332
+ tokenCompanyAppId: roleOptions.tokenCompanyAppId,
3333
+ usageTapCompressionModel: roleOptions.usageTapCompressionModel,
3334
+ usageTapCompressionAggressiveness: roleOptions.usageTapCompressionAggressiveness,
3335
+ signal
3336
+ });
3337
+ const compressedText = typeof result.compressedInput === "string" ? result.compressedInput : String(result.compressedInput);
3338
+ return {
3339
+ text: compressedText,
3340
+ segment: { role, result: { ...result, compressedInput: compressedText } }
3341
+ };
3342
+ }
3343
+ function normalizePromptCompressionOptions(options) {
3344
+ if (!options) {
3345
+ return void 0;
3346
+ }
3347
+ if (options === true) {
3348
+ return {};
3349
+ }
3350
+ if (options.enabled === false) {
3351
+ return void 0;
3352
+ }
3353
+ return options;
3354
+ }
3355
+ function isBelowMinContextTokens(context, minContextTokens) {
3356
+ return typeof minContextTokens === "number" && estimatePromptTokens(context) < Math.max(0, minContextTokens);
3357
+ }
3358
+ function resolveEffectivePromptCompressionOptions(defaults, override) {
3359
+ if (override === false) {
3360
+ return void 0;
3361
+ }
3362
+ if (override === void 0) {
3363
+ return defaults;
3364
+ }
3365
+ if (override === true) {
3366
+ return defaults ?? {};
3367
+ }
3368
+ const merged = {
3369
+ ...defaults ?? {},
3370
+ ...override,
3371
+ roles: override.roles ?? defaults?.roles
3372
+ };
3373
+ return normalizePromptCompressionOptions(merged);
3374
+ }
3375
+ function resolveRoleCompressionOptions(compression, role) {
3376
+ const hasExplicitRoles = compression.roles !== void 0;
3377
+ const setting = compression.roles?.[role];
3378
+ if (hasExplicitRoles && setting === void 0) {
3379
+ return void 0;
3380
+ }
3381
+ if (!hasExplicitRoles && role === "assistant") {
3382
+ return void 0;
3383
+ }
3384
+ if (setting === false) {
3385
+ return void 0;
3386
+ }
3387
+ const roleOptions = typeof setting === "object" ? setting : void 0;
3388
+ if (roleOptions?.enabled === false) {
3389
+ return void 0;
3390
+ }
3391
+ return {
3392
+ provider: roleOptions?.provider ?? compression.provider,
3393
+ minTokens: roleOptions?.minTokens ?? compression.minTokens,
3394
+ failOpen: compression.failOpen,
3395
+ tokenCompanyModel: compression.tokenCompanyModel,
3396
+ aggressiveness: roleOptions?.aggressiveness ?? resolveAggressiveness(compression, role),
3397
+ tokenCompanyAggressiveness: roleOptions?.tokenCompanyAggressiveness ?? resolveTokenCompanyAggressiveness(compression, role),
3398
+ tokenCompanyAppId: compression.tokenCompanyAppId,
3399
+ usageTapCompressionModel: compression.usageTapCompressionModel,
3400
+ usageTapCompressionAggressiveness: roleOptions?.usageTapCompressionAggressiveness ?? resolveUsageTapCompressionAggressiveness(compression, role)
3401
+ };
3402
+ }
3403
+ function resolveAggressiveness(compression, role) {
3404
+ if (typeof compression.aggressiveness === "number") {
3405
+ return compression.aggressiveness;
3406
+ }
3407
+ return compression.aggressiveness?.[role];
3408
+ }
3409
+ function resolveTokenCompanyAggressiveness(compression, role) {
3410
+ if (typeof compression.tokenCompanyAggressiveness === "number") {
3411
+ return compression.tokenCompanyAggressiveness;
3412
+ }
3413
+ return compression.tokenCompanyAggressiveness?.[role];
3414
+ }
3415
+ function resolveUsageTapCompressionAggressiveness(compression, role) {
3416
+ if (typeof compression.usageTapCompressionAggressiveness === "number") {
3417
+ return compression.usageTapCompressionAggressiveness;
3418
+ }
3419
+ return compression.usageTapCompressionAggressiveness?.[role];
3420
+ }
3421
+ function shouldUseUsageTapMessageEndpoint(compression) {
3422
+ if (compression.provider !== "usagetap") {
3423
+ return false;
3424
+ }
3425
+ return Object.values(compression.roles ?? {}).every((setting) => {
3426
+ if (typeof setting !== "object" || setting === null) {
3427
+ return true;
3428
+ }
3429
+ return setting.provider === void 0 || setting.provider === "usagetap";
3430
+ });
3431
+ }
3432
+ function resolveMessageEndpointAggressiveness(compression) {
3433
+ const base = compression.aggressiveness ?? compression.usageTapCompressionAggressiveness ?? compression.tokenCompanyAggressiveness;
3434
+ if (typeof base === "number" || base === void 0) {
3435
+ return hasExplicitEnabledRoles(compression) ? buildRoleAggressiveness(compression, base) : base;
3436
+ }
3437
+ return buildRoleAggressiveness(compression, void 0, base);
3438
+ }
3439
+ function hasExplicitEnabledRoles(compression) {
3440
+ return Object.values(compression.roles ?? {}).some((setting) => setting !== false);
3441
+ }
3442
+ function buildRoleAggressiveness(compression, fallback, base = {}) {
3443
+ const roles = ["system", "user", "tool", "assistant"];
3444
+ const result = {};
3445
+ for (const role of roles) {
3446
+ const roleOptions = resolveRoleCompressionOptions(compression, role);
3447
+ if (!roleOptions) {
3448
+ continue;
3449
+ }
3450
+ const roleAggressiveness = roleOptions.aggressiveness ?? roleOptions.usageTapCompressionAggressiveness ?? roleOptions.tokenCompanyAggressiveness ?? base[role] ?? fallback;
3451
+ if (roleAggressiveness !== void 0) {
3452
+ result[role] = roleAggressiveness;
3453
+ }
3454
+ }
3455
+ return result;
3456
+ }
3457
+ function buildPromptCompressionTelemetry(segments) {
3458
+ if (!segments.length) {
3459
+ return void 0;
3460
+ }
3461
+ const originalCharacters = segments.reduce(
3462
+ (sum, segment) => sum + segment.result.originalCharacters,
3463
+ 0
3464
+ );
3465
+ const compressedCharacters = segments.reduce(
3466
+ (sum, segment) => sum + segment.result.compressedCharacters,
3467
+ 0
3468
+ );
3469
+ const originalTokens = segments.reduce(
3470
+ (sum, segment) => sum + segment.result.originalTokens,
3471
+ 0
3472
+ );
3473
+ const compressedTokens = segments.reduce(
3474
+ (sum, segment) => sum + segment.result.compressedTokens,
3475
+ 0
3476
+ );
3477
+ const savedCharacters = Math.max(0, originalCharacters - compressedCharacters);
3478
+ const savedTokens = Math.max(0, originalTokens - compressedTokens);
3479
+ const providers = dedupeStrings2(segments.map((segment) => segment.result.provider));
3480
+ const roles = dedupeStrings2(segments.map((segment) => `role:${segment.role}`));
3481
+ const techniques = dedupeStrings2([
3482
+ "openai-wrapper",
3483
+ ...roles,
3484
+ ...segments.flatMap((segment) => segment.result.techniques),
3485
+ ...providers.length > 1 ? ["mixed-providers"] : []
3486
+ ]);
3487
+ return {
3488
+ provider: segments[0]?.result.provider ?? "heuristic",
3489
+ originalCharacters,
3490
+ compressedCharacters,
3491
+ savedCharacters,
3492
+ originalTokens,
3493
+ compressedTokens,
3494
+ savedTokens,
3495
+ tokenSavingsRatio: originalTokens > 0 ? savedTokens / originalTokens : 0,
3496
+ savingsRatio: originalCharacters > 0 ? savedCharacters / originalCharacters : 0,
3497
+ techniques
3498
+ };
3499
+ }
3500
+ function promptCompressionRequestOptions(withUsage, correlationId) {
3501
+ return {
3502
+ signal: withUsage?.signal,
3503
+ headers: withUsage?.headers,
3504
+ retries: withUsage?.retries,
3505
+ correlationId
3506
+ };
3507
+ }
3508
+ function mapOpenAIRole(role) {
3509
+ if (role === "system" || role === "developer") {
3510
+ return "system";
3511
+ }
3512
+ if (role === "user") {
3513
+ return "user";
3514
+ }
3515
+ if (role === "tool" || role === "function") {
3516
+ return "tool";
3517
+ }
3518
+ if (role === "assistant") {
3519
+ return "assistant";
3520
+ }
3521
+ return void 0;
3522
+ }
3523
+ function mapResponsesItemTypeToRole(type) {
3524
+ if (type === "function_call_output" || type === "tool_result" || type === "computer_call_output") {
3525
+ return "tool";
3526
+ }
3527
+ return void 0;
3528
+ }
3529
+ function splitUsageOptions(options) {
3530
+ if (!options || typeof options !== "object") {
3531
+ return {};
3532
+ }
3533
+ const { usageTap, withUsage, promptCompression, ...rest } = options;
3534
+ const requestOptions = Object.keys(rest).length ? cloneRequestOptions(rest) : void 0;
3535
+ return {
3536
+ requestOptions,
3537
+ usageContext: usageTap,
3538
+ withUsage,
3539
+ promptCompression
3540
+ };
3541
+ }
3542
+ function resolveBeginRequest(defaults, override) {
3543
+ const base = defaults ?? {};
3544
+ const current = override ?? {};
3545
+ const customerId = current.customerId ?? base.customerId;
3546
+ if (!customerId) {
3547
+ throw new UsageTapError(
3548
+ "USAGETAP_BAD_REQUEST",
3549
+ "wrapOpenAI requires usageTap.customerId (provide defaultContext or options.usageTap)"
3550
+ );
3551
+ }
3552
+ const tags = mergeTags(base.tags, current.tags);
3553
+ const begin = { customerId };
3554
+ const requested = current.requested ?? base.requested;
3555
+ if (requested) begin.requested = requested;
3556
+ const feature = current.feature ?? base.feature;
3557
+ if (feature) begin.feature = feature;
3558
+ const runId = current.runId ?? base.runId;
3559
+ if (runId) begin.runId = runId;
3560
+ const idempotency = current.idempotency ?? base.idempotency;
3561
+ if (idempotency) begin.idempotency = idempotency;
3562
+ const customerName = current.customerName ?? base.customerName;
3563
+ if (customerName) begin.customerName = customerName;
3564
+ const customerEmail = current.customerEmail ?? base.customerEmail;
3565
+ if (customerEmail) begin.customerEmail = customerEmail;
3566
+ const customerUserId = current.customerUserId ?? base.customerUserId;
3567
+ if (customerUserId) begin.customerUserId = customerUserId;
3568
+ const customerUserName = current.customerUserName ?? base.customerUserName;
3569
+ if (customerUserName) begin.customerUserName = customerUserName;
3570
+ const customerUserEmail = current.customerUserEmail ?? base.customerUserEmail;
3571
+ if (customerUserEmail) begin.customerUserEmail = customerUserEmail;
3572
+ const stripeCustomerId = current.stripeCustomerId ?? base.stripeCustomerId;
3573
+ if (stripeCustomerId) begin.stripeCustomerId = stripeCustomerId;
3574
+ const batch = current.batch ?? base.batch;
3575
+ if (typeof batch === "boolean") begin.batch = batch;
3576
+ const pricingMode = current.pricingMode ?? base.pricingMode;
3577
+ if (pricingMode) begin.pricingMode = pricingMode;
3578
+ if (tags?.length) {
3579
+ begin.tags = tags;
3580
+ }
3581
+ return begin;
3582
+ }
3583
+ function responsesBeginRequest(begin, params) {
3584
+ if (!responsesRequestUsesWebSearch(params)) return begin;
3585
+ return {
3586
+ ...begin,
3587
+ requested: {
3588
+ ...begin.requested ?? {},
3589
+ search: true
60
3590
  }
61
3591
  };
62
3592
  }
3593
+ function responsesRequestUsesWebSearch(params) {
3594
+ if (!params || typeof params !== "object") return false;
3595
+ const tools = params.tools;
3596
+ return Array.isArray(tools) && tools.some((tool) => {
3597
+ if (!tool || typeof tool !== "object") return false;
3598
+ const type = tool.type;
3599
+ return type === "web_search" || type === "web_search_preview";
3600
+ });
3601
+ }
3602
+ function transformApiPromise(apiPromise, onResolve, onReject) {
3603
+ const resolvedPromise = Promise.resolve(apiPromise).then(onResolve, onReject);
3604
+ if (isObjectRecord(apiPromise)) {
3605
+ const proto = Object.getPrototypeOf(apiPromise);
3606
+ if (proto) {
3607
+ Object.setPrototypeOf(resolvedPromise, proto);
3608
+ }
3609
+ for (const key of Reflect.ownKeys(apiPromise)) {
3610
+ if (key === "then" || key === "catch" || key === "finally") {
3611
+ continue;
3612
+ }
3613
+ try {
3614
+ const descriptor = Object.getOwnPropertyDescriptor(apiPromise, key);
3615
+ if (descriptor) {
3616
+ Reflect.defineProperty(resolvedPromise, key, descriptor);
3617
+ }
3618
+ } catch {
3619
+ }
3620
+ }
3621
+ }
3622
+ return resolvedPromise;
3623
+ }
63
3624
  function isObjectRecord(value) {
64
3625
  return typeof value === "object" && value !== null;
65
3626
  }
66
- function tryInferUsage(response, hints, extractor, ctx) {
3627
+ function cloneRecord(value) {
3628
+ return isObjectRecord(value) ? { ...value } : {};
3629
+ }
3630
+ function isStringTuple(value) {
3631
+ return Array.isArray(value) && value.length >= 2 && typeof value[0] === "string" && typeof value[1] === "string";
3632
+ }
3633
+ function cloneRequestOptions(source) {
3634
+ const clone = { ...source };
3635
+ if ("headers" in clone) {
3636
+ clone.headers = normalizeHeaders(clone.headers);
3637
+ }
3638
+ return clone;
3639
+ }
3640
+ function attachCorrelationHeader(options, correlationId) {
3641
+ const normalized = normalizeHeaders(options?.headers);
3642
+ if (correlationId && !normalized[USAGETAP_CORRELATION_HEADER]) {
3643
+ normalized[USAGETAP_CORRELATION_HEADER] = correlationId;
3644
+ }
3645
+ if (!options) {
3646
+ return Object.keys(normalized).length ? { headers: normalized } : void 0;
3647
+ }
3648
+ const next = { ...options };
3649
+ if (Object.keys(normalized).length) {
3650
+ next.headers = normalized;
3651
+ }
3652
+ return next;
3653
+ }
3654
+ function normalizeHeaders(headers) {
3655
+ if (!headers) {
3656
+ return {};
3657
+ }
3658
+ if (headers instanceof Headers) {
3659
+ const result = {};
3660
+ headers.forEach((value, key) => {
3661
+ result[key.toLowerCase()] = value;
3662
+ });
3663
+ return result;
3664
+ }
3665
+ if (Array.isArray(headers)) {
3666
+ const result = {};
3667
+ for (const entry of headers) {
3668
+ if (!isStringTuple(entry)) {
3669
+ continue;
3670
+ }
3671
+ const [key, value] = entry;
3672
+ result[key.toLowerCase()] = value;
3673
+ }
3674
+ return result;
3675
+ }
3676
+ if (isObjectRecord(headers)) {
3677
+ const result = {};
3678
+ const record = headers;
3679
+ for (const key of Object.keys(record)) {
3680
+ const value = record[key];
3681
+ if (value !== void 0 && value !== null) {
3682
+ result[key.toLowerCase()] = String(value);
3683
+ }
3684
+ }
3685
+ return result;
3686
+ }
3687
+ return {};
3688
+ }
3689
+ function mergeTags(a, b) {
3690
+ const values = [...a ?? [], ...b ?? []].map((value) => typeof value === "string" ? value.trim() : "").filter(Boolean);
3691
+ if (!values.length) {
3692
+ return void 0;
3693
+ }
3694
+ return dedupeStrings2(values);
3695
+ }
3696
+ function dedupeStrings2(values) {
3697
+ return Array.from(new Set(values));
3698
+ }
3699
+ function isStreamingRequest(params) {
3700
+ if (!params || typeof params !== "object") {
3701
+ return false;
3702
+ }
3703
+ const stream = params.stream;
3704
+ if (typeof stream === "boolean") {
3705
+ return stream;
3706
+ }
3707
+ return stream != null;
3708
+ }
3709
+ function applyChatVendorHints(params, hints) {
3710
+ if (!hints) {
3711
+ return params;
3712
+ }
3713
+ const next = cloneRecord(params);
3714
+ if (hints.preferredModel && (next.model === void 0 || next.model === null)) {
3715
+ next.model = hints.preferredModel;
3716
+ }
3717
+ if (typeof hints.maxResponseTokens === "number" && next.max_tokens == null) {
3718
+ next.max_tokens = hints.maxResponseTokens;
3719
+ }
3720
+ if (typeof hints.maxInputTokens === "number" && next.max_input_tokens == null) {
3721
+ next.max_input_tokens = hints.maxInputTokens;
3722
+ }
3723
+ return next;
3724
+ }
3725
+ function applyResponsesVendorHints(params, hints) {
3726
+ if (!hints) {
3727
+ return params;
3728
+ }
3729
+ const next = cloneRecord(params);
3730
+ if (hints.preferredModel && (next.model === void 0 || next.model === null)) {
3731
+ next.model = hints.preferredModel;
3732
+ }
3733
+ if (typeof hints.maxResponseTokens === "number" && next.max_output_tokens == null) {
3734
+ next.max_output_tokens = hints.maxResponseTokens;
3735
+ }
3736
+ return next;
3737
+ }
3738
+ async function extractUsageFromStream(stream, hints, provider = "openai") {
3739
+ const finalPayload = await resolveStreamFinalPayload(stream);
3740
+ if (!finalPayload) {
3741
+ return void 0;
3742
+ }
3743
+ return inferUsageFromResponse(finalPayload, hints, provider);
3744
+ }
3745
+ async function resolveStreamFinalPayload(stream) {
3746
+ if (!stream || typeof stream !== "object") {
3747
+ return void 0;
3748
+ }
3749
+ const candidate = stream;
3750
+ if (typeof candidate.finalChatCompletion === "function") {
3751
+ return candidate.finalChatCompletion();
3752
+ }
3753
+ if (typeof candidate.finalResponse === "function") {
3754
+ return candidate.finalResponse();
3755
+ }
3756
+ if (typeof candidate.finalCompletion === "function") {
3757
+ return candidate.finalCompletion();
3758
+ }
3759
+ if (typeof candidate.finalContent === "function") {
3760
+ return candidate.finalContent();
3761
+ }
3762
+ return void 0;
3763
+ }
3764
+ function ensureAsyncIterable(value, label) {
3765
+ if (!value || typeof value !== "object" || typeof value[Symbol.asyncIterator] !== "function") {
3766
+ throw new UsageTapError(
3767
+ "USAGETAP_BAD_REQUEST",
3768
+ `${label} expected an async iterable stream but received ${typeof value}`
3769
+ );
3770
+ }
3771
+ }
3772
+ function chunkToText(chunk) {
3773
+ if (chunk === void 0 || chunk === null) {
3774
+ return "";
3775
+ }
3776
+ if (typeof chunk === "string") {
3777
+ return chunk;
3778
+ }
3779
+ if (typeof chunk === "object") {
3780
+ const candidate = chunk;
3781
+ const delta = candidate.choices?.[0]?.delta;
3782
+ const content = delta?.content ?? candidate.content;
3783
+ if (typeof content === "string") {
3784
+ return content;
3785
+ }
3786
+ if (Array.isArray(content)) {
3787
+ return content.map((entry) => {
3788
+ if (!entry) return "";
3789
+ if (typeof entry === "string") return entry;
3790
+ if (typeof entry.text === "string") return entry.text;
3791
+ return "";
3792
+ }).join("");
3793
+ }
3794
+ }
3795
+ return String(chunk);
3796
+ }
3797
+ function formatSsePayload(text, options) {
3798
+ if (!text) {
3799
+ return "";
3800
+ }
3801
+ const lines = text.split(/\r?\n/);
3802
+ const eventLine = options?.event ? `event: ${options.event}
3803
+ ` : "";
3804
+ const retryLine = options?.retry ? `retry: ${options.retry}
3805
+ ` : "";
3806
+ const dataLines = lines.map((line) => `data: ${line}`).join("\n");
3807
+ return `${eventLine}${retryLine}${dataLines}
3808
+
3809
+ `;
3810
+ }
3811
+ function setHeaderIfPossible(res, key, value) {
3812
+ if (typeof res.setHeader === "function" && res.headersSent !== true) {
3813
+ res.setHeader(key, value);
3814
+ }
3815
+ }
3816
+ function tryInferUsage(response, hints, extractor, ctx, provider = "openai") {
67
3817
  const explicit = extractor?.(response);
68
- const inferred = explicit ?? inferUsageFromResponse(response, hints);
3818
+ const inferred = explicit ?? inferUsageFromResponse(response, hints, provider);
69
3819
  if (inferred) {
70
3820
  ctx.setUsage(inferred);
71
3821
  }
72
3822
  }
73
- function inferUsageFromResponse(response, hints) {
3823
+ function inferUsageFromResponse(response, hints, provider = "openai") {
74
3824
  if (!response || typeof response !== "object") {
75
3825
  return void 0;
76
3826
  }
@@ -78,32 +3828,110 @@ function inferUsageFromResponse(response, hints) {
78
3828
  if (!candidate.usage) {
79
3829
  return void 0;
80
3830
  }
81
- const cachedInputTokens = candidate.usage.prompt_tokens_details?.cached_tokens ?? candidate.usage.cached_tokens;
3831
+ const cachedInputTokens = candidate.usage.prompt_tokens_details?.cached_tokens ?? candidate.usage.input_tokens_details?.cached_tokens ?? candidate.usage.cached_tokens;
3832
+ const cacheWriteInputTokens = candidate.usage.prompt_tokens_details?.cache_write_tokens ?? candidate.usage.prompt_tokens_details?.cache_creation_tokens ?? candidate.usage.input_tokens_details?.cache_write_tokens ?? candidate.usage.input_tokens_details?.cache_creation_tokens ?? candidate.usage.cache_creation_input_tokens ?? candidate.usage.cache_write_input_tokens ?? candidate.usage.cache_write_tokens;
3833
+ const cacheWrite5mInputTokens = candidate.usage.cache_write_5m_input_tokens ?? candidate.usage.cache_creation?.ephemeral_5m_input_tokens;
3834
+ const cacheWrite1hInputTokens = candidate.usage.cache_write_1h_input_tokens ?? candidate.usage.cache_creation?.ephemeral_1h_input_tokens;
3835
+ const outputSearches = Array.isArray(candidate.output) ? candidate.output.filter((item) => item?.type === "web_search_call").length : 0;
3836
+ const searches = candidate.usage.searches ?? candidate.usage.web_search_queries ?? candidate.usage.server_tool_use?.web_search_requests ?? outputSearches;
3837
+ const responseEffort = normalizeExecutionReasoningEffort(
3838
+ candidate.reasoning?.effort
3839
+ );
82
3840
  return {
3841
+ providerUsed: provider,
83
3842
  modelUsed: candidate.model ?? hints?.preferredModel,
84
- inputTokens: candidate.usage.prompt_tokens,
85
- responseTokens: candidate.usage.completion_tokens,
86
- cachedInputTokens
3843
+ inputTokens: candidate.usage.prompt_tokens ?? candidate.usage.input_tokens,
3844
+ responseTokens: candidate.usage.completion_tokens ?? candidate.usage.output_tokens,
3845
+ cachedInputTokens,
3846
+ cacheWriteInputTokens,
3847
+ cacheWrite5mInputTokens,
3848
+ cacheWrite1hInputTokens,
3849
+ audioInputTokens: candidate.usage.prompt_tokens_details?.audio_tokens ?? candidate.usage.input_tokens_details?.audio_tokens,
3850
+ cachedAudioInputTokens: candidate.usage.prompt_tokens_details?.cached_audio_tokens ?? candidate.usage.input_tokens_details?.cached_audio_tokens ?? candidate.usage.prompt_tokens_details?.cached_tokens_details?.audio_tokens ?? candidate.usage.input_tokens_details?.cached_tokens_details?.audio_tokens,
3851
+ imageInputTokens: candidate.usage.prompt_tokens_details?.image_tokens ?? candidate.usage.input_tokens_details?.image_tokens,
3852
+ imageOutputTokens: candidate.usage.completion_tokens_details?.image_tokens ?? candidate.usage.output_tokens_details?.image_tokens,
3853
+ audioOutputTokens: candidate.usage.completion_tokens_details?.audio_tokens ?? candidate.usage.output_tokens_details?.audio_tokens,
3854
+ reasoningTokens: candidate.usage.completion_tokens_details?.reasoning_tokens ?? candidate.usage.output_tokens_details?.reasoning_tokens,
3855
+ ...responseEffort ? {
3856
+ reasoningEffort: responseEffort,
3857
+ reasoningEffortSource: "provider_response"
3858
+ } : {},
3859
+ ...typeof candidate.reasoning?.type === "string" ? { reasoningMode: candidate.reasoning.type } : typeof candidate.reasoning?.mode === "string" ? { reasoningMode: candidate.reasoning.mode } : {},
3860
+ ...typeof searches === "number" && searches > 0 ? { searches } : {}
3861
+ };
3862
+ }
3863
+ function normalizeExecutionReasoningEffort(value) {
3864
+ return value === "none" || value === "minimal" || value === "low" || value === "medium" || value === "high" || value === "xhigh" || value === "max" ? value : void 0;
3865
+ }
3866
+ function openAIRequestExecutionMetadata(params, provider) {
3867
+ const record = params && typeof params === "object" ? params : {};
3868
+ const reasoning = record.reasoning && typeof record.reasoning === "object" ? record.reasoning : void 0;
3869
+ const effort = normalizeExecutionReasoningEffort(
3870
+ record.reasoning_effort ?? reasoning?.effort ?? record.thinking_level
3871
+ );
3872
+ const mode = typeof reasoning?.type === "string" ? reasoning.type : typeof reasoning?.mode === "string" ? reasoning.mode : void 0;
3873
+ const rawBudget = reasoning?.budget_tokens ?? record.thinking_budget ?? record.thinking_budget_tokens;
3874
+ const budget = typeof rawBudget === "number" && Number.isInteger(rawBudget) && rawBudget >= 0 ? rawBudget : void 0;
3875
+ return {
3876
+ providerUsed: provider,
3877
+ ...typeof record.model === "string" ? { modelUsed: record.model } : {},
3878
+ ...effort ? { reasoningEffort: effort, reasoningEffortSource: "provider_request" } : {},
3879
+ ...mode ? { reasoningMode: mode } : {},
3880
+ ...budget !== void 0 ? { reasoningBudgetTokens: budget } : {}
3881
+ };
3882
+ }
3883
+ function tryInferUsageFromStreamChunk(chunk, hints, ctx, provider) {
3884
+ const payload = isObjectRecord(chunk) && isObjectRecord(chunk.response) ? chunk.response : chunk;
3885
+ const inferred = inferUsageFromResponse(payload, hints, provider);
3886
+ if (inferred) {
3887
+ ctx.setUsage(inferred);
3888
+ }
3889
+ }
3890
+ function ensureOpenAIStreamUsage(params) {
3891
+ if (!isObjectRecord(params)) {
3892
+ return params;
3893
+ }
3894
+ const streamOptions = isObjectRecord(params.stream_options) ? params.stream_options : {};
3895
+ return {
3896
+ ...params,
3897
+ stream_options: {
3898
+ ...streamOptions,
3899
+ include_usage: true
3900
+ }
87
3901
  };
88
3902
  }
89
- function wrapStreamForUsageTap(source, finalize, ctx) {
3903
+ function deferUsageFinalization(ctx) {
3904
+ return ctx.deferFinalization?.() ?? (() => Promise.resolve());
3905
+ }
3906
+ function wrapStreamForUsageTap(source, finalize, ctx, onChunk) {
90
3907
  const getIterator = source[Symbol.asyncIterator];
91
3908
  if (typeof getIterator !== "function") {
92
3909
  throw new TypeError("Stream is not async iterable");
93
3910
  }
94
3911
  const iterator = getIterator.call(source);
95
3912
  let completed = false;
96
- const invokeFinalize = async () => {
3913
+ const invokeFinalize = async (termination, error) => {
97
3914
  if (completed) return;
98
3915
  completed = true;
3916
+ if (termination === "cancel" || termination === "manual") {
3917
+ ctx.setError({
3918
+ code: "STREAM_ABORTED",
3919
+ message: termination === "cancel" ? "Provider stream consumption was cancelled before completion" : "Provider stream was finalized before completion"
3920
+ });
3921
+ } else if (termination === "error") {
3922
+ ctx.setError({
3923
+ code: "VENDOR_ERROR",
3924
+ message: error instanceof Error ? error.message : String(error)
3925
+ });
3926
+ }
99
3927
  try {
100
- await finalize();
101
- } catch (error) {
3928
+ await finalize(termination);
3929
+ } catch (error2) {
102
3930
  ctx.setError({
103
3931
  code: "USAGE_FINALIZE_ERROR",
104
- message: error instanceof Error ? error.message : String(error)
3932
+ message: error2 instanceof Error ? error2.message : String(error2)
105
3933
  });
106
- throw error;
3934
+ throw error2;
107
3935
  }
108
3936
  };
109
3937
  const prototype = Object.getPrototypeOf(source) ?? Object.prototype;
@@ -127,12 +3955,15 @@ function wrapStreamForUsageTap(source, finalize, ctx) {
127
3955
  value: async (...args) => {
128
3956
  try {
129
3957
  const result = await iterator.next(...args);
3958
+ if (!result.done) {
3959
+ onChunk?.(result.value);
3960
+ }
130
3961
  if (result.done) {
131
- await invokeFinalize();
3962
+ await invokeFinalize("complete");
132
3963
  }
133
3964
  return result;
134
3965
  } catch (error) {
135
- await invokeFinalize().catch(() => void 0);
3966
+ await invokeFinalize("error", error).catch(() => void 0);
136
3967
  throw error;
137
3968
  }
138
3969
  },
@@ -141,39 +3972,49 @@ function wrapStreamForUsageTap(source, finalize, ctx) {
141
3972
  });
142
3973
  Object.defineProperty(wrapped, "return", {
143
3974
  value: async (value) => {
144
- if (typeof iterator.return === "function") {
145
- const rawResult = await iterator.return(value);
146
- if (!isIteratorResult(rawResult)) {
147
- throw new TypeError("Iterator.return() returned an invalid result");
3975
+ try {
3976
+ if (typeof iterator.return === "function") {
3977
+ const rawResult = await iterator.return(value);
3978
+ if (!isIteratorResult(rawResult)) {
3979
+ throw new TypeError("Iterator.return() returned an invalid result");
3980
+ }
3981
+ await invokeFinalize("cancel");
3982
+ return rawResult;
148
3983
  }
149
- await invokeFinalize();
150
- return rawResult;
3984
+ await invokeFinalize("cancel");
3985
+ return { done: true, value };
3986
+ } catch (error) {
3987
+ await invokeFinalize("error", error).catch(() => void 0);
3988
+ throw error;
151
3989
  }
152
- await invokeFinalize();
153
- return { done: true, value };
154
3990
  },
155
3991
  configurable: true,
156
3992
  writable: true
157
3993
  });
158
3994
  Object.defineProperty(wrapped, "throw", {
159
3995
  value: async (error) => {
160
- if (typeof iterator.throw === "function") {
161
- const rawResult = await iterator.throw(error);
162
- if (!isIteratorResult(rawResult)) {
163
- throw new TypeError("Iterator.throw() returned an invalid result");
3996
+ try {
3997
+ if (typeof iterator.throw === "function") {
3998
+ const rawResult = await iterator.throw(error);
3999
+ if (!isIteratorResult(rawResult)) {
4000
+ throw new TypeError("Iterator.throw() returned an invalid result");
4001
+ }
4002
+ await invokeFinalize("error", error);
4003
+ return rawResult;
164
4004
  }
165
- await invokeFinalize();
166
- return rawResult;
4005
+ await invokeFinalize("error", error);
4006
+ throw error;
4007
+ } catch (thrownError) {
4008
+ await invokeFinalize("error", thrownError).catch(() => void 0);
4009
+ throw thrownError;
167
4010
  }
168
- await invokeFinalize();
169
- throw error;
170
4011
  },
171
4012
  configurable: true,
172
4013
  writable: true
173
4014
  });
174
4015
  Object.defineProperty(wrapped, "__usageTapFinalize", {
175
4016
  value: async () => {
176
- await invokeFinalize();
4017
+ await invokeFinalize("manual");
177
4018
  },
178
4019
  configurable: true
179
4020
  });
@@ -185,9 +4026,27 @@ function isIteratorResult(value) {
185
4026
 
186
4027
  // src/adapters/openrouter.ts
187
4028
  function createOpenRouterAdapter(init) {
188
- return createOpenAIAdapter(init);
4029
+ return createOpenAIAdapter({ ...init, provider: "openrouter" });
4030
+ }
4031
+ function withMetering2(client, customer) {
4032
+ return withMetering(
4033
+ client,
4034
+ typeof customer === "string" ? { customerId: customer, provider: "openrouter" } : { ...customer, provider: "openrouter" }
4035
+ );
4036
+ }
4037
+ function wrapOpenAI2(client, usageTap, options = {}) {
4038
+ return wrapOpenAI(client, usageTap, {
4039
+ ...options,
4040
+ provider: "openrouter"
4041
+ });
4042
+ }
4043
+ function withSampling2(client, options = {}) {
4044
+ return withSampling(client, { ...options, provider: "openrouter" });
189
4045
  }
190
4046
 
191
4047
  exports.createOpenRouterAdapter = createOpenRouterAdapter;
4048
+ exports.withMetering = withMetering2;
4049
+ exports.withSampling = withSampling2;
4050
+ exports.wrapOpenAI = wrapOpenAI2;
192
4051
  //# sourceMappingURL=openrouter.cjs.map
193
4052
  //# sourceMappingURL=openrouter.cjs.map