@usagetap/sdk 1.3.1 → 1.4.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 +1058 -863
  2. package/dist/adapters/anthropic.cjs +990 -24
  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 +990 -25
  7. package/dist/adapters/anthropic.mjs.map +1 -1
  8. package/dist/adapters/openai.cjs +1164 -44
  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 +1164 -45
  13. package/dist/adapters/openai.mjs.map +1 -1
  14. package/dist/adapters/openrouter.cjs +3899 -22
  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 +3897 -23
  19. package/dist/adapters/openrouter.mjs.map +1 -1
  20. package/dist/anthropic/index.cjs +990 -24
  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 +990 -25
  25. package/dist/anthropic/index.mjs.map +1 -1
  26. package/dist/client-CExQ8e1T.d.cts +1225 -0
  27. package/dist/client-CExQ8e1T.d.ts +1225 -0
  28. package/dist/express/index.cjs +421 -29
  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 +421 -29
  33. package/dist/express/index.mjs.map +1 -1
  34. package/dist/index.cjs +680 -15
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +5 -3
  37. package/dist/index.d.ts +5 -3
  38. package/dist/index.mjs +680 -15
  39. package/dist/index.mjs.map +1 -1
  40. package/dist/openai/index.cjs +1165 -45
  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 +1165 -46
  45. package/dist/openai/index.mjs.map +1 -1
  46. package/dist/openrouter/index.cjs +1182 -47
  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 +1180 -46
  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 +84 -84
  59. package/dist/client-BD8O2J8Z.d.cts +0 -668
  60. package/dist/client-BD8O2J8Z.d.ts +0 -668
@@ -1,18 +1,2240 @@
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
+ models;
1027
+ batches;
1028
+ transport;
1029
+ idempotencyGenerator;
1030
+ constructor(config) {
1031
+ this.transport = new ResourceTransport(
1032
+ config.gatewayBaseUrl ?? DEFAULT_GATEWAY_BASE_URL,
1033
+ config
1034
+ );
1035
+ this.idempotencyGenerator = config.idempotencyGenerator ?? createIdempotencyKey;
1036
+ this.chat = {
1037
+ completions: {
1038
+ create: (params, options) => this.transport.request({
1039
+ method: "POST",
1040
+ path: "/v1/chat/completions",
1041
+ body: params,
1042
+ options,
1043
+ response: "json"
1044
+ })
1045
+ }
1046
+ };
1047
+ this.models = {
1048
+ list: (options) => this.transport.request({
1049
+ method: "GET",
1050
+ path: "/v1/models",
1051
+ options,
1052
+ response: "json"
1053
+ })
1054
+ };
1055
+ this.batches = {
1056
+ create: (params, options = {}) => this.transport.request({
1057
+ method: "POST",
1058
+ path: "/v1/batches",
1059
+ body: params,
1060
+ options: {
1061
+ ...options,
1062
+ idempotencyKey: options.idempotencyKey ?? this.idempotencyGenerator()
1063
+ },
1064
+ response: "json"
1065
+ }),
1066
+ retrieve: (batchId, options) => this.transport.request({
1067
+ method: "GET",
1068
+ path: `/v1/batches/${encodeURIComponent(
1069
+ resourceId(batchId, ["id"], "gateway.batches.retrieve")
1070
+ )}`,
1071
+ options,
1072
+ response: "json"
1073
+ }),
1074
+ wait: (batch, options) => this.waitForBatch(batch, options),
1075
+ cancel: (batchId, options) => this.transport.request({
1076
+ method: "POST",
1077
+ path: `/v1/batches/${encodeURIComponent(
1078
+ resourceId(batchId, ["id"], "gateway.batches.cancel")
1079
+ )}/cancel`,
1080
+ options,
1081
+ response: "json"
1082
+ }),
1083
+ results: (batchId, options) => this.transport.request({
1084
+ method: "GET",
1085
+ path: `/v1/batches/${encodeURIComponent(
1086
+ resourceId(batchId, ["id"], "gateway.batches.results")
1087
+ )}/results`,
1088
+ options,
1089
+ response: "ndjson"
1090
+ })
1091
+ };
1092
+ }
1093
+ async waitForBatch(value, options = {}) {
1094
+ const { pollIntervalMs, timeoutMs } = validateWaitOptions(options);
1095
+ const deadline = Date.now() + timeoutMs;
1096
+ let batch = typeof value === "string" ? await this.batches.retrieve(value, options) : value;
1097
+ while (!terminalGatewayBatch(batch.status)) {
1098
+ if (Date.now() >= deadline) {
1099
+ throw new UsageTapError(
1100
+ "USAGETAP_RETRY_EXHAUSTED",
1101
+ `Gateway batch ${batch.id} did not finish before timeout`,
1102
+ { retryable: true }
1103
+ );
1104
+ }
1105
+ await sleep(pollIntervalMs, options.signal);
1106
+ batch = await this.batches.retrieve(batch.id, options);
1107
+ }
1108
+ return batch;
1109
+ }
1110
+ };
1111
+
1112
+ // src/client.ts
1113
+ var CALL_BEGIN_PATH = "call_begin";
1114
+ var CALL_END_PATH = "call_end";
1115
+ var COMPRESS_PROMPT_PATH = "compress_prompt";
1116
+ var SAMPLES_PATH = "samples";
1117
+ var SAMPLING_SETTINGS_PATH = "sampling/settings";
1118
+ var SAMPLING_DECIDE_PATH = "sampling/decide";
1119
+ var CHECK_USAGE_PATH = "customers/{customerId}/usage";
1120
+ var CREATE_CUSTOMER_PATH = "customers";
1121
+ var CHANGE_PLAN_PATH = "customers/{customerId}/change_plan";
1122
+ var INCREMENT_CUSTOM_METER_PATH = "custom_meter";
1123
+ var AUTH_HEADER = "authorization";
1124
+ var API_KEY_HEADER = "x-api-key";
1125
+ var CORRELATION_HEADER = "x-usage-correlation-id";
1126
+ var IDEMPOTENCY_HEADER = "idempotency-key";
1127
+ var SDK_HEADER = "x-usage-sdk";
1128
+ var USER_AGENT = "UsageTapClient";
1129
+ var CANONICAL_MEDIA_TYPE2 = "application/vnd.usagetap.v1+json";
1130
+ var DEFAULT_BASE_URL = "https://api.usagetap.com";
1131
+ var DEFAULT_RUN_INACTIVITY_MS = 60 * 60 * 1e3;
1132
+ var SDK_VERSION = "1.4.0" ;
1133
+ var HAS_WINDOW = typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1134
+ var UsageTapClient = class {
1135
+ /** OpenAI-compatible chat, model, and native batch operations. */
1136
+ gateway;
1137
+ /** Published-profile context summarization operations. */
1138
+ summarization;
1139
+ apiKey;
1140
+ baseUrl;
1141
+ fetchImpl;
1142
+ defaultFeature;
1143
+ defaultTags;
1144
+ defaultHeaders;
1145
+ retryDefaults;
1146
+ idempotencyGenerator;
1147
+ logFn;
1148
+ metricFn;
1149
+ authHeader;
1150
+ autoIdempotency;
1151
+ tokenCompanyApiKey;
1152
+ tokenCompanyEndpoint;
1153
+ model;
1154
+ tokenCompanyModel;
1155
+ aggressiveness;
1156
+ tokenCompanyAggressiveness;
1157
+ tokenCompanyAppId;
1158
+ usageTapCompressionApiKey;
1159
+ usageTapCompressionEndpoint;
1160
+ usageTapCompressionMessagesEndpoint;
1161
+ usageTapCompressionModel;
1162
+ usageTapCompressionAggressiveness;
1163
+ sampling;
1164
+ samplingSettingsCacheMs;
1165
+ circuitBreaker;
1166
+ circuitBreakerRuns = /* @__PURE__ */ new Map();
1167
+ samplingSettingsCache;
1168
+ constructor(options = {}) {
1169
+ const apiKey = options.apiKey?.trim() || readEnvironmentVariable("USAGETAP_API_KEY");
1170
+ const baseUrl = options.baseUrl?.trim() || readEnvironmentVariable("USAGETAP_BASE_URL") || DEFAULT_BASE_URL;
1171
+ if (!apiKey) {
1172
+ throw new UsageTapError(
1173
+ "USAGETAP_BAD_REQUEST",
1174
+ "UsageTapClient requires an apiKey or the USAGETAP_API_KEY environment variable"
1175
+ );
1176
+ }
1177
+ if (HAS_WINDOW && !options.allowBrowser) {
1178
+ throw new UsageTapError(
1179
+ "USAGETAP_BROWSER_RUNTIME",
1180
+ "UsageTapClient is designed for server-side environments. Pass allowBrowser=true only for testing."
1181
+ );
1182
+ }
1183
+ const fetchCandidate = options.fetchImpl ?? globalThis.fetch;
1184
+ if (typeof fetchCandidate !== "function") {
1185
+ throw new UsageTapError(
1186
+ "USAGETAP_NETWORK_ERROR",
1187
+ "A global fetch implementation was not found. Pass fetchImpl in UsageTapClientOptions."
1188
+ );
1189
+ }
1190
+ const normalizedBaseUrl2 = normalizeBaseUrl(baseUrl);
1191
+ this.baseUrl = new URL(normalizedBaseUrl2);
1192
+ this.apiKey = apiKey;
1193
+ this.fetchImpl = wrapFetchImplementation(fetchCandidate, !options.fetchImpl);
1194
+ const resourceConfig = {
1195
+ apiKey,
1196
+ apiBaseUrl: normalizedBaseUrl2,
1197
+ gatewayBaseUrl: options.gatewayBaseUrl?.trim() || readEnvironmentVariable("USAGETAP_GATEWAY_URL"),
1198
+ fetchImpl: this.fetchImpl,
1199
+ headers: options.headers,
1200
+ sdkVersion: SDK_VERSION,
1201
+ idempotencyGenerator: options.idempotencyGenerator
1202
+ };
1203
+ this.gateway = new GatewayResource(resourceConfig);
1204
+ this.summarization = new SummarizationResource(resourceConfig);
1205
+ this.defaultFeature = options.defaultFeature;
1206
+ this.defaultTags = options.defaultTags?.length ? dedupeStrings(options.defaultTags) : void 0;
1207
+ this.defaultHeaders = options.headers ? normalizeHeaderDictionary(options.headers) : {};
1208
+ this.retryDefaults = resolveRetryOptions(options.retries);
1209
+ this.idempotencyGenerator = options.idempotencyGenerator ?? createIdempotencyKey;
1210
+ this.logFn = options.onLog;
1211
+ this.metricFn = options.onUsageMetric;
1212
+ this.authHeader = options.useApiKeyHeader ? API_KEY_HEADER : AUTH_HEADER;
1213
+ this.autoIdempotency = options.autoIdempotency ?? true;
1214
+ this.tokenCompanyApiKey = options.tokenCompanyApiKey;
1215
+ this.tokenCompanyEndpoint = options.tokenCompanyEndpoint;
1216
+ this.model = options.model;
1217
+ this.tokenCompanyModel = options.tokenCompanyModel;
1218
+ this.aggressiveness = options.aggressiveness;
1219
+ this.tokenCompanyAggressiveness = options.tokenCompanyAggressiveness;
1220
+ this.tokenCompanyAppId = options.tokenCompanyAppId;
1221
+ this.usageTapCompressionApiKey = options.usageTapCompressionApiKey ?? apiKey;
1222
+ this.usageTapCompressionEndpoint = options.usageTapCompressionEndpoint;
1223
+ this.usageTapCompressionMessagesEndpoint = options.usageTapCompressionMessagesEndpoint;
1224
+ this.usageTapCompressionModel = options.usageTapCompressionModel;
1225
+ this.usageTapCompressionAggressiveness = options.usageTapCompressionAggressiveness;
1226
+ this.sampling = options.sampling;
1227
+ this.samplingSettingsCacheMs = Number.isFinite(options.samplingSettingsCacheMs) ? Math.max(0, Number(options.samplingSettingsCacheMs)) : 5 * 60 * 1e3;
1228
+ if (options.circuitBreaker) {
1229
+ const maxCallsPerRun = options.circuitBreaker.maxCallsPerRun;
1230
+ if (!Number.isInteger(maxCallsPerRun) || maxCallsPerRun < 1) {
1231
+ throw new UsageTapError(
1232
+ "USAGETAP_BAD_REQUEST",
1233
+ "circuitBreaker.maxCallsPerRun must be a positive integer"
1234
+ );
1235
+ }
1236
+ const runInactivityMs = options.circuitBreaker.runInactivityMs ?? DEFAULT_RUN_INACTIVITY_MS;
1237
+ if (!Number.isFinite(runInactivityMs) || runInactivityMs < 1) {
1238
+ throw new UsageTapError(
1239
+ "USAGETAP_BAD_REQUEST",
1240
+ "circuitBreaker.runInactivityMs must be a positive number"
1241
+ );
1242
+ }
1243
+ this.circuitBreaker = {
1244
+ maxCallsPerRun,
1245
+ runInactivityMs
1246
+ };
1247
+ }
1248
+ }
1249
+ shouldSample(request, policy = this.sampling || void 0) {
1250
+ if (!policy) return false;
1251
+ const rate = Math.min(1, Math.max(0, Number(policy.rate) || 0));
1252
+ if (rate <= 0) return false;
1253
+ const customerId = request.customerId?.trim();
1254
+ if (customerId && policy.customers?.exclude?.includes(customerId)) return false;
1255
+ const feature = request.feature?.trim();
1256
+ if (feature && policy.features?.exclude?.includes(feature)) return false;
1257
+ const included = policy.features?.include?.filter(Boolean) ?? [];
1258
+ if (included.length > 0 && (!feature || !included.includes(feature))) return false;
1259
+ const minimum = Math.max(0, Math.round(policy.minInputTokens ?? 0));
1260
+ if (minimum > 0 && estimatePromptTokens(request.input) < minimum) return false;
1261
+ return (policy.random ?? Math.random)() < rate;
1262
+ }
1263
+ async getSamplingSettings(options = {}) {
1264
+ const now = Date.now();
1265
+ if (!options.forceRefresh && this.samplingSettingsCache && this.samplingSettingsCache.expiresAtMs > now) {
1266
+ return {
1267
+ result: { status: "ACCEPTED", code: "SAMPLING_SETTINGS_CACHED" },
1268
+ data: this.samplingSettingsCache.settings,
1269
+ correlationId: options.correlationId ?? "local-cache"
1270
+ };
1271
+ }
1272
+ const response = await this.requestGet(
1273
+ SAMPLING_SETTINGS_PATH,
1274
+ {
1275
+ signal: options.signal,
1276
+ headers: options.headers,
1277
+ retries: options.retries,
1278
+ correlationId: options.correlationId
1279
+ }
1280
+ );
1281
+ const serverCacheMs = Math.max(0, Number(response.data.cacheSeconds) || 0) * 1e3;
1282
+ const cacheMs = Math.min(this.samplingSettingsCacheMs, serverCacheMs);
1283
+ this.samplingSettingsCache = {
1284
+ settings: response.data,
1285
+ expiresAtMs: now + cacheMs
1286
+ };
1287
+ return response;
1288
+ }
1289
+ async shouldSampleAsync(request, policy) {
1290
+ if (policy) return this.shouldSample(request, policy);
1291
+ if (this.sampling === false) return false;
1292
+ if (this.sampling) return this.shouldSample(request, this.sampling);
1293
+ try {
1294
+ const settings = await this.getSamplingSettings();
1295
+ return this.shouldSample(request, settings.data);
1296
+ } catch {
1297
+ return false;
1298
+ }
1299
+ }
1300
+ async decideSample(request, options = {}) {
1301
+ const hasTokens = Number.isFinite(request.inputTokens) && Number(request.inputTokens) >= 0;
1302
+ const hasCharacters = Number.isFinite(request.inputCharacters) && Number(request.inputCharacters) >= 0;
1303
+ if (!hasTokens && !hasCharacters) {
1304
+ throw new UsageTapError(
1305
+ "USAGETAP_BAD_REQUEST",
1306
+ "decideSample requires inputTokens or inputCharacters"
1307
+ );
1308
+ }
1309
+ return this.request(
1310
+ SAMPLING_DECIDE_PATH,
1311
+ request,
1312
+ options
1313
+ );
1314
+ }
1315
+ async captureSample(request, options = {}) {
1316
+ if (!request || request.input === void 0) {
1317
+ throw new UsageTapError(
1318
+ "USAGETAP_BAD_REQUEST",
1319
+ "captureSample requires input"
1320
+ );
1321
+ }
1322
+ if (!request.provider?.trim()) {
1323
+ throw new UsageTapError(
1324
+ "USAGETAP_BAD_REQUEST",
1325
+ "captureSample requires provider"
1326
+ );
1327
+ }
1328
+ const sampleId = request.sampleId?.trim() || this.idempotencyGenerator();
1329
+ return this.request(
1330
+ SAMPLES_PATH,
1331
+ { ...request, sampleId },
1332
+ { ...options, idempotencyKey: sampleId }
1333
+ );
1334
+ }
1335
+ async beginCall(request, options = {}) {
1336
+ const idempotencyKey = request.idempotencyKey ?? request.idempotency ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1337
+ this.reserveRunCall(request, idempotencyKey);
1338
+ const apiRequest = { ...request };
1339
+ delete apiRequest.runId;
1340
+ const payload = {
1341
+ ...apiRequest,
1342
+ feature: request.feature ?? this.defaultFeature,
1343
+ tags: this.mergeTags(request.tags)
1344
+ };
1345
+ if (idempotencyKey) {
1346
+ payload.idempotencyKey = idempotencyKey;
1347
+ payload.idempotency = idempotencyKey;
1348
+ }
1349
+ const response = await this.request(
1350
+ CALL_BEGIN_PATH,
1351
+ payload,
1352
+ {
1353
+ ...options,
1354
+ idempotencyKey
1355
+ }
1356
+ );
1357
+ return response;
1358
+ }
1359
+ /**
1360
+ * Inspect a configured run circuit breaker without consuming another call.
1361
+ */
1362
+ canRunContinue(request) {
1363
+ const identity = this.resolveRunIdentity(request);
1364
+ if (!identity || !this.circuitBreaker) {
1365
+ throw new UsageTapError(
1366
+ "USAGETAP_BAD_REQUEST",
1367
+ "canRunContinue requires circuitBreaker configuration and a non-empty runId"
1368
+ );
1369
+ }
1370
+ this.expireInactiveRuns();
1371
+ const calls = this.circuitBreakerRuns.get(identity.key)?.calls ?? 0;
1372
+ return this.createCircuitBreakerDecision(identity.customerId, identity.runId, calls);
1373
+ }
1374
+ /**
1375
+ * Release local state after a workflow finishes. Returns true when state existed.
1376
+ */
1377
+ resetRun(request) {
1378
+ const identity = this.resolveRunIdentity(request);
1379
+ return identity ? this.circuitBreakerRuns.delete(identity.key) : false;
1380
+ }
1381
+ async promptCompress(request, options = {}) {
1382
+ if (!request?.callId) {
1383
+ throw new UsageTapError(
1384
+ "USAGETAP_BAD_REQUEST",
1385
+ "promptCompress requires callId"
1386
+ );
1387
+ }
1388
+ const requestInput = request.input ?? request.text;
1389
+ if (requestInput === void 0) {
1390
+ throw new UsageTapError(
1391
+ "USAGETAP_BAD_REQUEST",
1392
+ "promptCompress requires input or text"
1393
+ );
1394
+ }
1395
+ const result = await this.compressPromptInput(requestInput, {
1396
+ provider: request.provider,
1397
+ model: request.model,
1398
+ tokenCompanyModel: request.tokenCompanyModel,
1399
+ aggressiveness: request.aggressiveness,
1400
+ tokenCompanyAggressiveness: request.tokenCompanyAggressiveness,
1401
+ tokenCompanyAppId: request.tokenCompanyAppId,
1402
+ usageTapCompressionModel: request.usageTapCompressionModel,
1403
+ usageTapCompressionAggressiveness: request.usageTapCompressionAggressiveness,
1404
+ signal: options.signal
1405
+ });
1406
+ try {
1407
+ await this.recordPromptCompression(
1408
+ {
1409
+ callId: request.callId,
1410
+ promptCompression: this.toPromptCompressionTelemetry(result)
1411
+ },
1412
+ options
1413
+ );
1414
+ return { ...result, callId: request.callId };
1415
+ } catch (error) {
1416
+ return {
1417
+ ...createPromptCompressionFallback(
1418
+ requestInput,
1419
+ request.provider ?? result.provider,
1420
+ error
1421
+ ),
1422
+ callId: request.callId
1423
+ };
1424
+ }
1425
+ }
1426
+ async compressPromptInput(input, options = {}) {
1427
+ return compressPrompt({
1428
+ input,
1429
+ provider: options.provider,
1430
+ tokenCompanyApiKey: this.tokenCompanyApiKey,
1431
+ tokenCompanyEndpoint: this.tokenCompanyEndpoint,
1432
+ model: options.model ?? this.model,
1433
+ tokenCompanyModel: options.tokenCompanyModel ?? this.tokenCompanyModel,
1434
+ aggressiveness: options.aggressiveness ?? this.aggressiveness,
1435
+ tokenCompanyAggressiveness: options.tokenCompanyAggressiveness ?? this.tokenCompanyAggressiveness,
1436
+ tokenCompanyAppId: options.tokenCompanyAppId ?? this.tokenCompanyAppId,
1437
+ usageTapCompressionApiKey: this.usageTapCompressionApiKey,
1438
+ usageTapCompressionEndpoint: this.usageTapCompressionEndpoint,
1439
+ usageTapCompressionModel: options.usageTapCompressionModel ?? this.usageTapCompressionModel,
1440
+ usageTapCompressionAggressiveness: options.usageTapCompressionAggressiveness ?? this.usageTapCompressionAggressiveness,
1441
+ fetchImpl: this.fetchImpl,
1442
+ signal: options.signal,
1443
+ failOpen: options.failOpen
1444
+ });
1445
+ }
1446
+ /**
1447
+ * Compress text with UsageTap's hosted compression service.
1448
+ *
1449
+ * This is the short, standalone path. It does not create a metered call and
1450
+ * fails open to the original text unless failOpen is explicitly disabled.
1451
+ */
1452
+ async compress(text, options = {}) {
1453
+ if (typeof text !== "string") {
1454
+ throw new UsageTapError(
1455
+ "USAGETAP_BAD_REQUEST",
1456
+ "compress requires text"
1457
+ );
1458
+ }
1459
+ const result = await this.compressPromptInput(text, {
1460
+ ...options,
1461
+ provider: "usagetap"
1462
+ });
1463
+ const output = typeof result.compressedInput === "string" ? result.compressedInput : text;
1464
+ return {
1465
+ ...result,
1466
+ compressedInput: output,
1467
+ output
1468
+ };
1469
+ }
1470
+ async compressPromptMessages(input, options = {}) {
1471
+ return compressPromptMessages({
1472
+ input,
1473
+ provider: options.provider ?? "usagetap",
1474
+ usageTapCompressionApiKey: this.usageTapCompressionApiKey,
1475
+ usageTapCompressionMessagesEndpoint: this.usageTapCompressionMessagesEndpoint,
1476
+ aggressiveness: options.aggressiveness ?? this.aggressiveness,
1477
+ usageTapCompressionAggressiveness: options.usageTapCompressionAggressiveness ?? this.usageTapCompressionAggressiveness,
1478
+ mode: options.mode,
1479
+ latencyBudgetMs: options.latencyBudgetMs,
1480
+ compactEmptyUserMessages: options.compactEmptyUserMessages,
1481
+ compactDuplicateUserTextParts: options.compactDuplicateUserTextParts,
1482
+ fetchImpl: this.fetchImpl,
1483
+ signal: options.signal,
1484
+ failOpen: options.failOpen
1485
+ });
1486
+ }
1487
+ async recordPromptCompression(request, options = {}) {
1488
+ if (!request?.callId) {
1489
+ throw new UsageTapError(
1490
+ "USAGETAP_BAD_REQUEST",
1491
+ "recordPromptCompression requires callId"
1492
+ );
1493
+ }
1494
+ return this.request(
1495
+ COMPRESS_PROMPT_PATH,
1496
+ {
1497
+ callId: request.callId,
1498
+ promptCompression: request.promptCompression
1499
+ },
1500
+ options
1501
+ );
1502
+ }
1503
+ async endCall(request, options = {}) {
1504
+ if (!request?.callId) {
1505
+ throw new UsageTapError(
1506
+ "USAGETAP_BAD_REQUEST",
1507
+ "endCall requires callId"
1508
+ );
1509
+ }
1510
+ const { customerId, feature, tags, ...apiPayload } = request;
1511
+ const response = await this.request(
1512
+ CALL_END_PATH,
1513
+ apiPayload,
1514
+ options
1515
+ );
1516
+ this.emitUsageMetric({
1517
+ type: "call_end",
1518
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1519
+ customerId: customerId ?? "unknown",
1520
+ callId: request.callId,
1521
+ feature: feature ?? this.defaultFeature,
1522
+ tags: tags ?? this.defaultTags,
1523
+ providerUsed: request.providerUsed,
1524
+ modelUsed: request.modelUsed,
1525
+ reasoningEffort: request.reasoningEffort,
1526
+ reasoningEffortSource: request.reasoningEffortSource,
1527
+ reasoningMode: request.reasoningMode,
1528
+ reasoningBudgetTokens: request.reasoningBudgetTokens,
1529
+ metrics: {
1530
+ inputTokens: request.inputTokens,
1531
+ responseTokens: request.responseTokens,
1532
+ cachedInputTokens: request.cachedInputTokens,
1533
+ cacheWriteInputTokens: request.cacheWriteInputTokens,
1534
+ reasoningTokens: request.reasoningTokens,
1535
+ searches: request.searches,
1536
+ audioSeconds: request.audioSeconds,
1537
+ costUsd: response.data.costUSD
1538
+ },
1539
+ correlationId: response.correlationId
1540
+ });
1541
+ return response;
1542
+ }
1543
+ async checkUsage(request, options = {}) {
1544
+ if (!request?.customerId) {
1545
+ throw new UsageTapError(
1546
+ "USAGETAP_BAD_REQUEST",
1547
+ "checkUsage requires customerId"
1548
+ );
1549
+ }
1550
+ const path = CHECK_USAGE_PATH.replace(
1551
+ "{customerId}",
1552
+ encodeURIComponent(request.customerId)
1553
+ );
1554
+ const response = await this.requestGet(
1555
+ path,
1556
+ options
1557
+ );
1558
+ return response;
1559
+ }
1560
+ async createCustomer(request, options = {}) {
1561
+ if (!request?.customerId) {
1562
+ throw new UsageTapError(
1563
+ "USAGETAP_BAD_REQUEST",
1564
+ "createCustomer requires customerId"
1565
+ );
1566
+ }
1567
+ const idempotencyKey = options.idempotencyKey ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1568
+ const response = await this.request(
1569
+ CREATE_CUSTOMER_PATH,
1570
+ { ...request },
1571
+ {
1572
+ ...options,
1573
+ idempotencyKey
1574
+ }
1575
+ );
1576
+ return response;
1577
+ }
1578
+ async changePlan(request, options = {}) {
1579
+ if (!request?.customerId) {
1580
+ throw new UsageTapError(
1581
+ "USAGETAP_BAD_REQUEST",
1582
+ "changePlan requires customerId"
1583
+ );
1584
+ }
1585
+ if (!request?.planId) {
1586
+ throw new UsageTapError(
1587
+ "USAGETAP_BAD_REQUEST",
1588
+ "changePlan requires planId"
1589
+ );
1590
+ }
1591
+ const path = CHANGE_PLAN_PATH.replace(
1592
+ "{customerId}",
1593
+ encodeURIComponent(request.customerId)
1594
+ );
1595
+ const idempotencyKey = options.idempotencyKey ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1596
+ const payload = {
1597
+ planId: request.planId,
1598
+ strategy: request.strategy ?? "IMMEDIATE_RESET"
1599
+ };
1600
+ const response = await this.request(
1601
+ path,
1602
+ payload,
1603
+ {
1604
+ ...options,
1605
+ idempotencyKey
1606
+ }
1607
+ );
1608
+ return response;
1609
+ }
1610
+ async incrementCustomMeter(request, options = {}) {
1611
+ if (!request?.customerId) {
1612
+ throw new UsageTapError(
1613
+ "USAGETAP_BAD_REQUEST",
1614
+ "incrementCustomMeter requires customerId"
1615
+ );
1616
+ }
1617
+ if (!request?.meterSlot) {
1618
+ throw new UsageTapError(
1619
+ "USAGETAP_BAD_REQUEST",
1620
+ "incrementCustomMeter requires meterSlot"
1621
+ );
1622
+ }
1623
+ if (!["CUSTOM1", "CUSTOM2"].includes(request.meterSlot)) {
1624
+ throw new UsageTapError(
1625
+ "USAGETAP_BAD_REQUEST",
1626
+ "meterSlot must be CUSTOM1 or CUSTOM2"
1627
+ );
1628
+ }
1629
+ if (typeof request.amount !== "number" || !Number.isFinite(request.amount) || request.amount <= 0) {
1630
+ throw new UsageTapError(
1631
+ "USAGETAP_BAD_REQUEST",
1632
+ "incrementCustomMeter requires a positive numeric amount"
1633
+ );
1634
+ }
1635
+ const idempotencyKey = options.idempotencyKey ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1636
+ const payload = {
1637
+ customerId: request.customerId,
1638
+ meterSlot: request.meterSlot,
1639
+ amount: request.amount
1640
+ };
1641
+ if (request.customerUserId) {
1642
+ payload.customerUserId = request.customerUserId;
1643
+ }
1644
+ if (request.customerUserName) {
1645
+ payload.customerUserName = request.customerUserName;
1646
+ }
1647
+ if (request.customerUserEmail) {
1648
+ payload.customerUserEmail = request.customerUserEmail;
1649
+ }
1650
+ if (request.feature) {
1651
+ payload.feature = request.feature;
1652
+ }
1653
+ if (request.tags && request.tags.length > 0) {
1654
+ payload.tags = request.tags;
1655
+ }
1656
+ if (request.metadata) {
1657
+ payload.metadata = request.metadata;
1658
+ }
1659
+ const response = await this.request(
1660
+ INCREMENT_CUSTOM_METER_PATH,
1661
+ payload,
1662
+ {
1663
+ ...options,
1664
+ idempotencyKey
1665
+ }
1666
+ );
1667
+ this.emitUsageMetric({
1668
+ type: "custom_meter",
1669
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1670
+ customerId: request.customerId,
1671
+ feature: request.feature ?? this.defaultFeature,
1672
+ tags: request.tags ?? this.defaultTags,
1673
+ metrics: {
1674
+ customMeterSlot: request.meterSlot,
1675
+ customMeterAmount: request.amount
1676
+ },
1677
+ correlationId: response.correlationId
1678
+ });
1679
+ return response;
1680
+ }
1681
+ async withUsage(beginRequest, handler, options = {}) {
1682
+ const idempotencyKey = beginRequest.idempotencyKey ?? beginRequest.idempotency ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1683
+ const beginPayload = idempotencyKey ? { ...beginRequest, idempotencyKey, idempotency: idempotencyKey } : { ...beginRequest };
1684
+ const beginResponse = await this.beginCall(beginPayload, options);
1685
+ let usage = {};
1686
+ const pricingMode = beginResponse.data.pricingMode ?? beginRequest.pricingMode ?? (beginRequest.batch === true ? "batch" : beginRequest.batch === false ? "standard" : void 0);
1687
+ if (pricingMode) {
1688
+ usage.pricingMode = pricingMode;
1689
+ usage.batch = pricingMode === "batch";
1690
+ }
1691
+ const initialStripeCustomerId = typeof beginResponse.data.stripeCustomerId === "string" ? beginResponse.data.stripeCustomerId : typeof beginRequest.stripeCustomerId === "string" ? beginRequest.stripeCustomerId : void 0;
1692
+ if (initialStripeCustomerId) {
1693
+ usage = { ...usage, stripeCustomerId: initialStripeCustomerId };
1694
+ }
1695
+ let errorPayload;
1696
+ let handlerResult;
1697
+ let handlerError;
1698
+ let endCallError;
1699
+ const context = {
1700
+ begin: beginResponse,
1701
+ setUsage: (u) => {
1702
+ usage = { ...usage, ...u };
1703
+ },
1704
+ setError: (err) => {
1705
+ errorPayload = err;
1706
+ }
1707
+ };
1708
+ try {
1709
+ handlerResult = await handler(context);
1710
+ } catch (error) {
1711
+ handlerError = error;
1712
+ if (!errorPayload) {
1713
+ errorPayload = {
1714
+ code: options.defaultErrorCode ?? "VENDOR_ERROR",
1715
+ message: error instanceof Error ? error.message : String(error)
1716
+ };
1717
+ }
1718
+ } finally {
1719
+ try {
1720
+ await this.endCall(
1721
+ {
1722
+ callId: beginResponse.data.callId,
1723
+ // Pass context for metric tracking
1724
+ customerId: beginRequest.customerId,
1725
+ feature: beginRequest.feature ?? this.defaultFeature,
1726
+ tags: beginRequest.tags ?? this.defaultTags,
1727
+ ...usage,
1728
+ error: errorPayload
1729
+ },
1730
+ {
1731
+ ...options,
1732
+ correlationId: beginResponse.correlationId
1733
+ }
1734
+ );
1735
+ } catch (error) {
1736
+ endCallError = error;
1737
+ }
1738
+ }
1739
+ if (handlerError) {
1740
+ throw handlerError;
1741
+ }
1742
+ if (endCallError) {
1743
+ throw wrapEndCallError(endCallError, beginResponse.correlationId);
1744
+ }
1745
+ return handlerResult;
1746
+ }
1747
+ /**
1748
+ * Meter one operation. Pass only a customer ID for the common path, or the
1749
+ * existing begin-call request object when feature, tags, or entitlements are needed.
1750
+ */
1751
+ async meter(request, handler, options = {}) {
1752
+ const beginRequest = typeof request === "string" ? { customerId: request } : request;
1753
+ return this.withUsage(beginRequest, handler, options);
1754
+ }
1755
+ toPromptCompressionTelemetry(result) {
1756
+ return {
1757
+ provider: result.provider,
1758
+ originalTokens: result.originalTokens,
1759
+ compressedTokens: result.compressedTokens,
1760
+ savedTokens: result.savedTokens,
1761
+ tokenSavingsRatio: result.tokenSavingsRatio,
1762
+ techniques: result.techniques
1763
+ };
1764
+ }
1765
+ reserveRunCall(request, idempotencyKey) {
1766
+ const identity = this.resolveRunIdentity(request);
1767
+ if (!identity || !this.circuitBreaker) return;
1768
+ this.expireInactiveRuns();
1769
+ const now = Date.now();
1770
+ const state = this.circuitBreakerRuns.get(identity.key) ?? {
1771
+ calls: 0,
1772
+ reservationKeys: /* @__PURE__ */ new Set(),
1773
+ lastSeenAtMs: now
1774
+ };
1775
+ const reservationKey = idempotencyKey ?? this.idempotencyGenerator();
1776
+ state.lastSeenAtMs = now;
1777
+ if (state.reservationKeys.has(reservationKey)) {
1778
+ this.circuitBreakerRuns.set(identity.key, state);
1779
+ return;
1780
+ }
1781
+ const decision = this.createCircuitBreakerDecision(
1782
+ identity.customerId,
1783
+ identity.runId,
1784
+ state.calls
1785
+ );
1786
+ if (!decision.allowed) {
1787
+ throw new UsageTapError(
1788
+ "USAGETAP_CIRCUIT_OPEN",
1789
+ `Run ${identity.runId} reached its ${decision.limit}-call circuit-breaker limit`,
1790
+ {
1791
+ details: {
1792
+ reason: decision.reason,
1793
+ customerId: identity.customerId,
1794
+ runId: identity.runId,
1795
+ calls: decision.calls,
1796
+ limit: decision.limit,
1797
+ remaining: decision.remaining
1798
+ }
1799
+ }
1800
+ );
1801
+ }
1802
+ state.calls += 1;
1803
+ state.reservationKeys.add(reservationKey);
1804
+ this.circuitBreakerRuns.set(identity.key, state);
1805
+ }
1806
+ resolveRunIdentity(request) {
1807
+ const customerId = request.customerId?.trim();
1808
+ const runId = request.runId?.trim();
1809
+ if (!customerId || !runId) return void 0;
1810
+ return {
1811
+ key: `${customerId}\0${runId}`,
1812
+ customerId,
1813
+ runId
1814
+ };
1815
+ }
1816
+ createCircuitBreakerDecision(customerId, runId, calls) {
1817
+ const limit = this.circuitBreaker?.maxCallsPerRun ?? 0;
1818
+ const allowed = calls < limit;
1819
+ return {
1820
+ allowed,
1821
+ ...allowed ? {} : { reason: "max_calls_per_run" },
1822
+ customerId,
1823
+ runId,
1824
+ calls,
1825
+ limit,
1826
+ remaining: Math.max(0, limit - calls)
1827
+ };
1828
+ }
1829
+ expireInactiveRuns() {
1830
+ if (!this.circuitBreaker || this.circuitBreakerRuns.size === 0) return;
1831
+ const expiredBefore = Date.now() - this.circuitBreaker.runInactivityMs;
1832
+ for (const [key, state] of this.circuitBreakerRuns) {
1833
+ if (state.lastSeenAtMs < expiredBefore) {
1834
+ this.circuitBreakerRuns.delete(key);
1835
+ }
1836
+ }
1837
+ }
1838
+ async request(path, payload, options) {
1839
+ const url = new URL(path, this.baseUrl).toString();
1840
+ const body = payload !== void 0 ? JSON.stringify(payload) : void 0;
1841
+ const headers = this.composeHeaders(body, options);
1842
+ const resolvedRetry = resolveRetryOptions(
1843
+ this.retryDefaults,
1844
+ options.retries
1845
+ );
1846
+ const startTime = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1847
+ return runWithRetry(
1848
+ async (attempt) => {
1849
+ const startedAt = startTime();
1850
+ this.log({
1851
+ event: "request:start",
1852
+ path,
1853
+ attempt,
1854
+ idempotencyKey: options.idempotencyKey,
1855
+ correlationId: options.correlationId
1856
+ });
1857
+ const response = await this.performFetch({
1858
+ url,
1859
+ method: "POST",
1860
+ headers,
1861
+ body,
1862
+ signal: options.signal
1863
+ });
1864
+ this.log({
1865
+ event: "request:success",
1866
+ path,
1867
+ attempt,
1868
+ idempotencyKey: options.idempotencyKey,
1869
+ correlationId: response.correlationId,
1870
+ elapsedMs: startTime() - startedAt
1871
+ });
1872
+ return response;
1873
+ },
1874
+ resolvedRetry,
1875
+ (error) => this.shouldRetry(error),
1876
+ (attempt, delayMs, error) => {
1877
+ this.log({
1878
+ event: "retry:scheduled",
1879
+ path,
1880
+ attempt,
1881
+ idempotencyKey: options.idempotencyKey,
1882
+ correlationId: options.correlationId,
1883
+ error,
1884
+ elapsedMs: delayMs
1885
+ });
1886
+ },
1887
+ options.signal
1888
+ ).catch((error) => {
1889
+ this.log({
1890
+ event: "retry:exhausted",
1891
+ path,
1892
+ attempt: resolvedRetry.maxAttempts,
1893
+ idempotencyKey: options.idempotencyKey,
1894
+ correlationId: options.correlationId,
1895
+ error
1896
+ });
1897
+ throw error;
1898
+ });
1899
+ }
1900
+ async requestGet(path, options) {
1901
+ const url = new URL(path, this.baseUrl).toString();
1902
+ const headers = this.composeHeaders(void 0, options);
1903
+ const resolvedRetry = resolveRetryOptions(
1904
+ this.retryDefaults,
1905
+ options.retries
1906
+ );
1907
+ const startTime = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1908
+ return runWithRetry(
1909
+ async (attempt) => {
1910
+ const startedAt = startTime();
1911
+ this.log({
1912
+ event: "request:start",
1913
+ path,
1914
+ attempt,
1915
+ correlationId: options.correlationId
1916
+ });
1917
+ const response = await this.performFetch({
1918
+ url,
1919
+ method: "GET",
1920
+ headers,
1921
+ signal: options.signal
1922
+ });
1923
+ this.log({
1924
+ event: "request:success",
1925
+ path,
1926
+ attempt,
1927
+ correlationId: response.correlationId,
1928
+ elapsedMs: startTime() - startedAt
1929
+ });
1930
+ return response;
1931
+ },
1932
+ resolvedRetry,
1933
+ (error) => this.shouldRetry(error),
1934
+ (attempt, delayMs, error) => {
1935
+ this.log({
1936
+ event: "retry:scheduled",
1937
+ path,
1938
+ attempt,
1939
+ correlationId: options.correlationId,
1940
+ error,
1941
+ elapsedMs: delayMs
1942
+ });
1943
+ },
1944
+ options.signal
1945
+ ).catch((error) => {
1946
+ this.log({
1947
+ event: "retry:exhausted",
1948
+ path,
1949
+ attempt: resolvedRetry.maxAttempts,
1950
+ correlationId: options.correlationId,
1951
+ error
1952
+ });
1953
+ throw error;
1954
+ });
1955
+ }
1956
+ async performFetch(init) {
1957
+ let response;
1958
+ try {
1959
+ response = await this.fetchImpl(init.url, {
1960
+ method: init.method,
1961
+ headers: init.headers,
1962
+ body: init.body,
1963
+ signal: init.signal
1964
+ });
1965
+ } catch (error) {
1966
+ throw new UsageTapError(
1967
+ "USAGETAP_NETWORK_ERROR",
1968
+ "Failed to reach UsageTap",
1969
+ {
1970
+ retryable: true,
1971
+ cause: error
1972
+ }
1973
+ );
1974
+ }
1975
+ const correlationId = response.headers.get(CORRELATION_HEADER) ?? void 0;
1976
+ const text = await response.text();
1977
+ let payload;
1978
+ if (text) {
1979
+ try {
1980
+ payload = JSON.parse(text);
1981
+ } catch (error) {
1982
+ throw new UsageTapError(
1983
+ "USAGETAP_INVALID_RESPONSE",
1984
+ "UsageTap returned invalid JSON",
1985
+ {
1986
+ retryable: false,
1987
+ correlationId,
1988
+ cause: error
1989
+ }
1990
+ );
1991
+ }
1992
+ }
1993
+ if (!response.ok) {
1994
+ throw this.toHttpError(response.status, payload, correlationId);
1995
+ }
1996
+ if (!payload?.result || payload.result.status !== "ACCEPTED") {
1997
+ throw this.toApiError(payload, correlationId);
1998
+ }
1999
+ const resolvedCorrelation = payload.correlationId ?? correlationId;
2000
+ if (payload.data === void 0 || payload.data === null || !resolvedCorrelation) {
2001
+ throw new UsageTapError(
2002
+ "USAGETAP_INVALID_RESPONSE",
2003
+ "UsageTap response missing data or correlationId",
2004
+ {
2005
+ correlationId: resolvedCorrelation ?? correlationId
2006
+ }
2007
+ );
2008
+ }
2009
+ return {
2010
+ result: {
2011
+ status: payload.result.status,
2012
+ code: payload.result.code,
2013
+ message: payload.result.message,
2014
+ timestamp: payload.result.timestamp
2015
+ },
2016
+ data: payload.data,
2017
+ correlationId: resolvedCorrelation
2018
+ };
2019
+ }
2020
+ composeHeaders(body, options) {
2021
+ const headers = {
2022
+ ...this.defaultHeaders,
2023
+ [SDK_HEADER]: `js/${SDK_VERSION}`,
2024
+ "content-type": "application/json",
2025
+ accept: CANONICAL_MEDIA_TYPE2
2026
+ };
2027
+ if (!HAS_WINDOW) {
2028
+ headers["user-agent"] = `${USER_AGENT}/${SDK_VERSION}`;
2029
+ }
2030
+ if (this.authHeader === API_KEY_HEADER) {
2031
+ headers[API_KEY_HEADER] = this.apiKey;
2032
+ } else {
2033
+ headers[AUTH_HEADER] = `Bearer ${this.apiKey}`;
2034
+ }
2035
+ if (options.idempotencyKey) {
2036
+ headers[IDEMPOTENCY_HEADER] = options.idempotencyKey;
2037
+ }
2038
+ if (options.correlationId) {
2039
+ headers[CORRELATION_HEADER] = options.correlationId;
2040
+ }
2041
+ if (!body) {
2042
+ delete headers["content-type"];
2043
+ }
2044
+ if (options.headers) {
2045
+ Object.assign(headers, normalizeHeaderDictionary(options.headers));
2046
+ }
2047
+ return headers;
2048
+ }
2049
+ log(entry) {
2050
+ this.logFn?.(entry);
2051
+ }
2052
+ emitUsageMetric(event) {
2053
+ try {
2054
+ this.metricFn?.(event);
2055
+ } catch {
2056
+ }
2057
+ }
2058
+ mergeTags(tags) {
2059
+ if (!tags && !this.defaultTags) {
2060
+ return void 0;
2061
+ }
2062
+ const combined = [...this.defaultTags ?? [], ...tags ?? []].filter(
2063
+ Boolean
2064
+ );
2065
+ return combined.length ? dedupeStrings(combined) : void 0;
2066
+ }
2067
+ shouldRetry(error) {
2068
+ if (isUsageTapError(error)) {
2069
+ return Boolean(error.retryable);
2070
+ }
2071
+ if (error instanceof Error && error.name === "AbortError") {
2072
+ return false;
2073
+ }
2074
+ return false;
2075
+ }
2076
+ toHttpError(status, payload, correlationId) {
2077
+ const code = mapStatusToErrorCode(status);
2078
+ const retryable = isRetryableStatus(status);
2079
+ const message = payload?.error?.message ?? payload?.result?.message ?? `UsageTap responded with HTTP ${status}`;
2080
+ return new UsageTapError(code, message, {
2081
+ status,
2082
+ retryable,
2083
+ correlationId: payload?.correlationId ?? correlationId,
2084
+ details: sanitizeDetails(payload)
2085
+ });
2086
+ }
2087
+ toApiError(payload, correlationId) {
2088
+ const normalizedCode = payload?.error?.code ?? payload?.result?.code ?? "UNKNOWN";
2089
+ const retryable = isRetryableApiCode(normalizedCode);
2090
+ const message = payload?.error?.message ?? payload?.result?.message ?? "UsageTap reported an error";
2091
+ return new UsageTapError(mapApiCodeToError(normalizedCode), message, {
2092
+ retryable,
2093
+ correlationId: payload?.correlationId ?? correlationId,
2094
+ details: sanitizeDetails(payload)
2095
+ });
2096
+ }
2097
+ };
2098
+ function mapStatusToErrorCode(status) {
2099
+ if (status === 401 || status === 403) return "USAGETAP_AUTH_ERROR";
2100
+ if (status === 400 || status === 404 || status === 409)
2101
+ return "USAGETAP_BAD_REQUEST";
2102
+ if (status === 429) return "USAGETAP_RATE_LIMITED";
2103
+ if (status >= 500) return "USAGETAP_SERVER_ERROR";
2104
+ return "USAGETAP_INVALID_RESPONSE";
2105
+ }
2106
+ function isRetryableStatus(status) {
2107
+ return status === 408 || status === 425 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
2108
+ }
2109
+ function isRetryableApiCode(code) {
2110
+ const normalized = code.toUpperCase();
2111
+ return normalized.includes("TRANSIENT") || normalized.includes("RETRY") || normalized.includes("TIMEOUT") || normalized.includes("THROTTLE") || normalized.includes("RATE_LIMIT");
2112
+ }
2113
+ function mapApiCodeToError(code) {
2114
+ const normalized = code.toUpperCase();
2115
+ if (normalized.includes("AUTH") || normalized.includes("TOKEN")) {
2116
+ return "USAGETAP_AUTH_ERROR";
2117
+ }
2118
+ if (normalized.includes("RATE") || normalized.includes("THROTTLE")) {
2119
+ return "USAGETAP_RATE_LIMITED";
2120
+ }
2121
+ if (normalized.includes("SERVER") || normalized.includes("TRANSIENT")) {
2122
+ return "USAGETAP_SERVER_ERROR";
2123
+ }
2124
+ if (normalized.includes("IDEMPOTENCY") || normalized.includes("VALIDATION") || normalized.includes("REQUEST")) {
2125
+ return "USAGETAP_BAD_REQUEST";
2126
+ }
2127
+ return "USAGETAP_INVALID_RESPONSE";
2128
+ }
2129
+ function sanitizeDetails(payload) {
2130
+ if (!payload) return void 0;
2131
+ const details = {};
2132
+ if (payload.result) details.result = payload.result;
2133
+ if (payload.error) details.error = payload.error;
2134
+ return Object.keys(details).length ? details : void 0;
2135
+ }
2136
+ function readEnvironmentVariable(name) {
2137
+ const runtime = globalThis;
2138
+ const value = runtime.process?.env?.[name]?.trim();
2139
+ return value || void 0;
2140
+ }
2141
+ function normalizeBaseUrl(baseUrl) {
2142
+ const trimmed = baseUrl.trim();
2143
+ if (!trimmed) return trimmed;
2144
+ return trimmed.endsWith("/") ? trimmed : `${trimmed}/`;
2145
+ }
2146
+ function normalizeHeaderDictionary(dict) {
2147
+ return Object.keys(dict).reduce((acc, key) => {
2148
+ acc[key.toLowerCase()] = dict[key];
2149
+ return acc;
2150
+ }, {});
2151
+ }
2152
+ function dedupeStrings(values) {
2153
+ return Array.from(
2154
+ new Set(values.map((value) => value.trim()).filter(Boolean))
2155
+ );
2156
+ }
2157
+ function wrapFetchImplementation(fetchCandidate, preferGlobalContext) {
2158
+ const target = preferGlobalContext ? globalThis : void 0;
2159
+ return ((...args) => target ? Reflect.apply(fetchCandidate, target, args) : fetchCandidate(...args));
2160
+ }
2161
+ function wrapEndCallError(error, correlationId) {
2162
+ if (isUsageTapError(error)) {
2163
+ return new UsageTapError("USAGETAP_END_CALL_ERROR", error.message, {
2164
+ correlationId: error.correlationId ?? correlationId,
2165
+ details: error.details,
2166
+ cause: error
2167
+ });
2168
+ }
2169
+ return new UsageTapError(
2170
+ "USAGETAP_END_CALL_ERROR",
2171
+ "Failed to finalize UsageTap call",
2172
+ {
2173
+ correlationId,
2174
+ cause: error
2175
+ }
2176
+ );
2177
+ }
2178
+
3
2179
  // src/adapters/openai.ts
2180
+ var OpenAIPromptCompressionStats = class {
2181
+ history = [];
2182
+ failures = [];
2183
+ _record(turn) {
2184
+ this.history.push(turn);
2185
+ }
2186
+ _recordFailure(failure) {
2187
+ this.failures.push(failure);
2188
+ }
2189
+ get totalOriginalTokens() {
2190
+ return this.history.reduce((sum, turn) => sum + (turn.originalTokens ?? 0), 0);
2191
+ }
2192
+ get totalCompressedTokens() {
2193
+ return this.history.reduce((sum, turn) => sum + (turn.compressedTokens ?? 0), 0);
2194
+ }
2195
+ get totalTokensSaved() {
2196
+ return this.history.reduce((sum, turn) => sum + (turn.savedTokens ?? 0), 0);
2197
+ }
2198
+ get totalOriginalCharacters() {
2199
+ return this.history.reduce((sum, turn) => sum + turn.originalCharacters, 0);
2200
+ }
2201
+ get totalCompressedCharacters() {
2202
+ return this.history.reduce((sum, turn) => sum + turn.compressedCharacters, 0);
2203
+ }
2204
+ get totalCharactersSaved() {
2205
+ return this.history.reduce((sum, turn) => sum + turn.savedCharacters, 0);
2206
+ }
2207
+ get calls() {
2208
+ return this.history.length;
2209
+ }
2210
+ get telemetryFailures() {
2211
+ return this.failures.length;
2212
+ }
2213
+ get failOpenEvents() {
2214
+ return this.history.filter(
2215
+ (turn) => turn.techniques.includes("compression-error") || turn.techniques.includes("fallback-original")
2216
+ ).length;
2217
+ }
2218
+ get tokenSavingsRatio() {
2219
+ return this.totalOriginalTokens > 0 ? this.totalTokensSaved / this.totalOriginalTokens : 0;
2220
+ }
2221
+ get savingsRatio() {
2222
+ return this.totalOriginalCharacters > 0 ? this.totalCharactersSaved / this.totalOriginalCharacters : 0;
2223
+ }
2224
+ };
4
2225
  function createOpenAIAdapter(init) {
5
- const { client, usageTap } = init;
2226
+ const { client, usageTap, provider = "openai" } = init;
6
2227
  return {
7
2228
  async invoke(params) {
8
2229
  const result = await usageTap.withUsage(
9
2230
  params.begin,
10
2231
  async (ctx) => {
2232
+ ctx.setUsage({ providerUsed: provider });
11
2233
  const response = await params.call(client, {
12
2234
  hints: ctx.begin.data.vendorHints,
13
2235
  begin: ctx.begin
14
2236
  });
15
- tryInferUsage(response, ctx.begin.data.vendorHints, params.extractUsage, ctx);
2237
+ tryInferUsage(response, ctx.begin.data.vendorHints, params.extractUsage, ctx, provider);
16
2238
  return {
17
2239
  data: response,
18
2240
  begin: ctx.begin
@@ -26,6 +2248,7 @@ function createOpenAIAdapter(init) {
26
2248
  const result = await usageTap.withUsage(
27
2249
  params.begin,
28
2250
  async (ctx) => {
2251
+ ctx.setUsage({ providerUsed: provider });
29
2252
  const { stream, onComplete } = await params.call(client, {
30
2253
  hints: ctx.begin.data.vendorHints,
31
2254
  begin: ctx.begin
@@ -45,32 +2268,1639 @@ function createOpenAIAdapter(init) {
45
2268
  throw error;
46
2269
  }
47
2270
  }, 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;
2271
+ const finalize = async () => {
2272
+ await wrapped.__usageTapFinalize?.();
2273
+ };
2274
+ return {
2275
+ stream: wrapped,
2276
+ begin: ctx.begin,
2277
+ finalize
2278
+ };
2279
+ },
2280
+ params.withUsageOptions
2281
+ );
2282
+ return result;
2283
+ }
2284
+ };
2285
+ }
2286
+ function toNextResponse(stream, options = {}) {
2287
+ const mode = options.mode ?? "text";
2288
+ const headers = new Headers(options.headers ?? {});
2289
+ if (mode === "sse") {
2290
+ headers.set("content-type", "text/event-stream; charset=utf-8");
2291
+ headers.set("cache-control", "no-cache, no-transform");
2292
+ headers.set("connection", "keep-alive");
2293
+ headers.set("x-accel-buffering", "no");
2294
+ } else {
2295
+ headers.set("content-type", options.contentType ?? "text/plain; charset=utf-8");
2296
+ }
2297
+ const encoder = new TextEncoder();
2298
+ let iterator;
2299
+ const body = new ReadableStream({
2300
+ async start(controller) {
2301
+ try {
2302
+ const getIterator = stream[Symbol.asyncIterator];
2303
+ if (typeof getIterator !== "function") {
2304
+ controller.close();
2305
+ return;
2306
+ }
2307
+ iterator = getIterator.call(stream);
2308
+ while (true) {
2309
+ const result = await iterator.next();
2310
+ if (result.done) {
2311
+ break;
2312
+ }
2313
+ const text = chunkToText(result.value);
2314
+ if (!text) {
2315
+ continue;
2316
+ }
2317
+ if (mode === "sse") {
2318
+ controller.enqueue(encoder.encode(formatSsePayload(text, options.sse)));
2319
+ } else {
2320
+ controller.enqueue(encoder.encode(text));
2321
+ }
2322
+ }
2323
+ controller.close();
2324
+ } catch (error) {
2325
+ controller.error(error);
2326
+ } finally {
2327
+ await stream.__usageTapFinalize?.();
2328
+ }
2329
+ },
2330
+ async cancel() {
2331
+ if (!iterator) {
2332
+ const getIterator = stream[Symbol.asyncIterator];
2333
+ if (typeof getIterator === "function") {
2334
+ iterator = getIterator.call(stream);
2335
+ }
2336
+ }
2337
+ if (iterator && typeof iterator.return === "function") {
2338
+ await iterator.return();
2339
+ }
2340
+ await stream.__usageTapFinalize?.();
2341
+ }
2342
+ });
2343
+ return new Response(body, { headers });
2344
+ }
2345
+ async function pipeToResponse(stream, res, options = {}) {
2346
+ const mode = options.mode ?? "text";
2347
+ if (mode === "sse") {
2348
+ setHeaderIfPossible(res, "Content-Type", "text/event-stream; charset=utf-8");
2349
+ setHeaderIfPossible(res, "Cache-Control", "no-cache, no-transform");
2350
+ setHeaderIfPossible(res, "Connection", "keep-alive");
2351
+ setHeaderIfPossible(res, "X-Accel-Buffering", "no");
2352
+ } else {
2353
+ setHeaderIfPossible(res, "Content-Type", options.contentType ?? "text/plain; charset=utf-8");
2354
+ }
2355
+ const encoder = new TextEncoder();
2356
+ const iterator = stream[Symbol.asyncIterator]();
2357
+ try {
2358
+ while (true) {
2359
+ const result = await iterator.next();
2360
+ if (result.done) {
2361
+ break;
2362
+ }
2363
+ const text = chunkToText(result.value);
2364
+ if (!text) {
2365
+ continue;
2366
+ }
2367
+ const payload = mode === "sse" ? formatSsePayload(text, options.sse) : text;
2368
+ res.write(Buffer.from(encoder.encode(payload)));
2369
+ res.flush?.();
2370
+ }
2371
+ } finally {
2372
+ res.end();
2373
+ await stream.__usageTapFinalize?.();
2374
+ }
2375
+ }
2376
+ var USAGETAP_CORRELATION_HEADER = "x-usage-correlation-id";
2377
+ function withSampling(client, options = {}) {
2378
+ if (!client || !options) {
2379
+ throw new UsageTapError(
2380
+ "USAGETAP_BAD_REQUEST",
2381
+ "withSampling requires an OpenAI-compatible client and sampling options"
2382
+ );
2383
+ }
2384
+ const { apiKey, usageTapClient, provider = "openai", ...policy } = options;
2385
+ const localPolicy = typeof policy.rate === "number" ? policy : void 0;
2386
+ const usageTap = usageTapClient ?? new UsageTapClient({ apiKey, sampling: localPolicy });
2387
+ const wrapCreate = (create) => async (params, requestOptions) => {
2388
+ const { usageTap: callContextRaw, ...providerOptions } = requestOptions ?? {};
2389
+ const callContext = isObjectRecord(callContextRaw) ? callContextRaw : {};
2390
+ const streaming = params.stream === true;
2391
+ const decision = streaming ? Promise.resolve(false) : usageTap.shouldSampleAsync({
2392
+ customerId: readString(callContext.customerId),
2393
+ feature: readString(callContext.feature),
2394
+ input: params
2395
+ }, localPolicy);
2396
+ const startedAt = Date.now();
2397
+ try {
2398
+ const response = await create(
2399
+ params,
2400
+ Object.keys(providerOptions).length ? providerOptions : void 0
2401
+ );
2402
+ const selected = await decision;
2403
+ if (selected) {
2404
+ const record = isObjectRecord(response) ? response : {};
2405
+ await usageTap.captureSample({
2406
+ customerId: readString(callContext.customerId),
2407
+ feature: readString(callContext.feature),
2408
+ environment: readString(callContext.environment),
2409
+ tags: readStringArray(callContext.tags),
2410
+ provider,
2411
+ model: readString(record.model) ?? readString(params.model),
2412
+ input: params,
2413
+ output: response,
2414
+ usage: record.usage,
2415
+ latencyMs: Date.now() - startedAt
2416
+ }).catch(() => void 0);
2417
+ }
2418
+ return response;
2419
+ } catch (error) {
2420
+ const selected = await decision;
2421
+ if (selected) {
2422
+ await usageTap.captureSample({
2423
+ customerId: readString(callContext.customerId),
2424
+ feature: readString(callContext.feature),
2425
+ environment: readString(callContext.environment),
2426
+ tags: readStringArray(callContext.tags),
2427
+ provider,
2428
+ model: readString(params.model),
2429
+ input: params,
2430
+ latencyMs: Date.now() - startedAt,
2431
+ error: serializeSamplingError(error)
2432
+ }).catch(() => void 0);
2433
+ }
2434
+ throw error;
2435
+ }
2436
+ };
2437
+ const chat = client.chat?.completions ? new Proxy(client.chat, {
2438
+ get(target, prop, receiver) {
2439
+ if (prop !== "completions") return safeReflectGet(target, prop, receiver);
2440
+ const completions = target.completions;
2441
+ return new Proxy(completions, {
2442
+ get(completionTarget, completionProp, completionReceiver) {
2443
+ if (completionProp === "create") {
2444
+ return wrapCreate(
2445
+ completionTarget.create.bind(completionTarget)
2446
+ );
2447
+ }
2448
+ return safeReflectGet(
2449
+ completionTarget,
2450
+ completionProp,
2451
+ completionReceiver
2452
+ );
2453
+ }
2454
+ });
2455
+ }
2456
+ }) : void 0;
2457
+ const responses = typeof client.responses !== "undefined" && client.responses ? new Proxy(client.responses, {
2458
+ get(target, prop, receiver) {
2459
+ if (prop === "create") {
2460
+ const create = Reflect.get(target, prop, receiver);
2461
+ return wrapCreate(create.bind(target));
2462
+ }
2463
+ return safeReflectGet(target, prop, receiver);
2464
+ }
2465
+ }) : void 0;
2466
+ return new Proxy(client, {
2467
+ get(target, prop, receiver) {
2468
+ if (prop === "chat" && chat) return chat;
2469
+ if (prop === "responses" && responses) return responses;
2470
+ if (prop === "unwrap") return () => target;
2471
+ return safeReflectGet(target, prop, receiver);
2472
+ }
2473
+ });
2474
+ }
2475
+ function safeReflectGet(target, prop, receiver) {
2476
+ return Reflect.get(target, prop, receiver);
2477
+ }
2478
+ function readStringArray(value) {
2479
+ if (!Array.isArray(value)) return void 0;
2480
+ const strings = value.filter((item) => typeof item === "string");
2481
+ return strings.length ? strings : void 0;
2482
+ }
2483
+ function readString(value) {
2484
+ return typeof value === "string" && value.trim() ? value : void 0;
2485
+ }
2486
+ function serializeSamplingError(error) {
2487
+ if (error instanceof Error) {
2488
+ return { name: error.name, message: error.message };
2489
+ }
2490
+ return { message: String(error) };
2491
+ }
2492
+ function normalizeMeteredOpenAISampling(options) {
2493
+ if (!options) return void 0;
2494
+ if (options === true) return { provider: "openai" };
2495
+ const { provider = "openai", ...policyFields } = options;
2496
+ return {
2497
+ provider,
2498
+ policy: typeof policyFields.rate === "number" ? policyFields : void 0
2499
+ };
2500
+ }
2501
+ function startMeteredOpenAISampleDecision({
2502
+ usageTap,
2503
+ sampling,
2504
+ beginRequest,
2505
+ input
2506
+ }) {
2507
+ if (!sampling) return Promise.resolve(false);
2508
+ return usageTap.shouldSampleAsync(
2509
+ {
2510
+ customerId: beginRequest.customerId,
2511
+ feature: beginRequest.feature,
2512
+ input
2513
+ },
2514
+ sampling.policy
2515
+ );
2516
+ }
2517
+ async function captureMeteredOpenAISample({
2518
+ usageTap,
2519
+ sampling,
2520
+ decision,
2521
+ ctx,
2522
+ beginRequest,
2523
+ input,
2524
+ response,
2525
+ error,
2526
+ startedAt
2527
+ }) {
2528
+ if (!sampling) return;
2529
+ let selected = false;
2530
+ try {
2531
+ selected = await decision;
2532
+ } catch {
2533
+ return;
2534
+ }
2535
+ if (!selected) return;
2536
+ const record = isObjectRecord(response) ? response : {};
2537
+ await usageTap.captureSample({
2538
+ sampleId: ctx.begin.data.callId,
2539
+ callId: ctx.begin.data.callId,
2540
+ customerId: beginRequest.customerId,
2541
+ feature: beginRequest.feature,
2542
+ tags: beginRequest.tags,
2543
+ provider: sampling.provider,
2544
+ model: readString(record.model) ?? readString(input.model),
2545
+ input,
2546
+ ...response === void 0 ? {} : { output: response },
2547
+ usage: record.usage,
2548
+ latencyMs: Date.now() - startedAt,
2549
+ ...error === void 0 ? {} : { error: serializeSamplingError(error) }
2550
+ }).catch(() => void 0);
2551
+ }
2552
+ function withMetering(client, customer) {
2553
+ const config = typeof customer === "string" ? { customerId: customer } : customer;
2554
+ if (!config?.customerId) {
2555
+ throw new UsageTapError(
2556
+ "USAGETAP_BAD_REQUEST",
2557
+ "withMetering requires a customerId"
2558
+ );
2559
+ }
2560
+ const {
2561
+ apiKey,
2562
+ usageTapClient,
2563
+ applyVendorHints,
2564
+ promptCompression,
2565
+ sampling,
2566
+ provider,
2567
+ ...defaultContext
2568
+ } = config;
2569
+ const usageTap = usageTapClient ?? new UsageTapClient({ apiKey });
2570
+ const normalizedCompression = promptCompression === true ? { provider: "usagetap" } : promptCompression ? { provider: "usagetap", ...promptCompression } : void 0;
2571
+ return wrapOpenAI(client, usageTap, {
2572
+ defaultContext,
2573
+ applyVendorHints,
2574
+ promptCompression: normalizedCompression,
2575
+ sampling,
2576
+ provider
2577
+ });
2578
+ }
2579
+ function wrapOpenAI(client, usageTap, options = {}) {
2580
+ if (!client) {
2581
+ throw new UsageTapError("USAGETAP_BAD_REQUEST", "wrapOpenAI requires an OpenAI client instance");
2582
+ }
2583
+ const defaultContext = options.defaultContext;
2584
+ const applyVendorHints = options.applyVendorHints !== false;
2585
+ const defaultPromptCompression = normalizePromptCompressionOptions(options.promptCompression);
2586
+ const defaultSampling = normalizeMeteredOpenAISampling(options.sampling);
2587
+ const provider = options.provider ?? "openai";
2588
+ const promptCompressionStats = new OpenAIPromptCompressionStats();
2589
+ const proxiedChat = client.chat ? createChatProxy(
2590
+ client.chat,
2591
+ usageTap,
2592
+ defaultContext,
2593
+ applyVendorHints,
2594
+ defaultPromptCompression,
2595
+ promptCompressionStats,
2596
+ defaultSampling,
2597
+ provider
2598
+ ) : void 0;
2599
+ const proxiedResponses = typeof client.responses !== "undefined" ? createResponsesProxy(
2600
+ client.responses,
2601
+ usageTap,
2602
+ defaultContext,
2603
+ applyVendorHints,
2604
+ defaultPromptCompression,
2605
+ promptCompressionStats,
2606
+ defaultSampling,
2607
+ provider
2608
+ ) : void 0;
2609
+ const handler = {
2610
+ get(target, prop, receiver) {
2611
+ if (prop === "chat" && proxiedChat) {
2612
+ return proxiedChat;
2613
+ }
2614
+ if (prop === "responses" && typeof target.responses !== "undefined") {
2615
+ return proxiedResponses ?? Reflect.get(target, prop, receiver);
2616
+ }
2617
+ if (prop === "toNextResponse") {
2618
+ return toNextResponse;
2619
+ }
2620
+ if (prop === "pipeToResponse") {
2621
+ return pipeToResponse;
2622
+ }
2623
+ if (prop === "promptCompression") {
2624
+ return promptCompressionStats;
2625
+ }
2626
+ if (prop === "unwrap") {
2627
+ return () => target;
2628
+ }
2629
+ return Reflect.get(target, prop, receiver);
2630
+ }
2631
+ };
2632
+ return new Proxy(client, handler);
2633
+ }
2634
+ function createChatProxy(resource, usageTap, defaultContext, applyVendorHints, defaultPromptCompression, promptCompressionStats, defaultSampling, provider) {
2635
+ const completions = createChatCompletionsProxy(
2636
+ resource.completions,
2637
+ usageTap,
2638
+ defaultContext,
2639
+ applyVendorHints,
2640
+ defaultPromptCompression,
2641
+ promptCompressionStats,
2642
+ defaultSampling,
2643
+ provider
2644
+ );
2645
+ const handler = {
2646
+ get(target, prop, receiver) {
2647
+ if (prop === "completions") {
2648
+ return completions;
2649
+ }
2650
+ return Reflect.get(target, prop, receiver);
2651
+ }
2652
+ };
2653
+ return new Proxy(resource, handler);
2654
+ }
2655
+ function createResponsesProxy(resource, usageTap, defaultContext, applyVendorHints, defaultPromptCompression, promptCompressionStats, defaultSampling, provider) {
2656
+ if (!resource || typeof resource !== "object") {
2657
+ return void 0;
2658
+ }
2659
+ if (!("create" in resource) || typeof resource.create !== "function") {
2660
+ return resource;
2661
+ }
2662
+ const originalCreate = resource.create.bind(resource);
2663
+ const wrappedCreate = (params, options) => {
2664
+ const {
2665
+ requestOptions,
2666
+ usageContext,
2667
+ withUsage,
2668
+ promptCompression
2669
+ } = splitUsageOptions(options);
2670
+ const beginRequest = withRuntimeCompressionContext(
2671
+ resolveBeginRequest(defaultContext, usageContext),
2672
+ "openai",
2673
+ String(params.model)
2674
+ );
2675
+ const wantsStream = isStreamingRequest(params);
2676
+ return usageTap.withUsage(beginRequest, async (ctx) => {
2677
+ const sampleStartedAt = Date.now();
2678
+ const sampleDecision = wantsStream ? Promise.resolve(false) : startMeteredOpenAISampleDecision({
2679
+ usageTap,
2680
+ sampling: defaultSampling,
2681
+ beginRequest,
2682
+ input: params
2683
+ });
2684
+ const hintedParams = applyVendorHints ? applyResponsesVendorHints(params, ctx.begin.data.vendorHints) : params;
2685
+ const finalParams = await compressResponsesParamsForCall({
2686
+ params: hintedParams,
2687
+ usageTap,
2688
+ ctx,
2689
+ defaultPromptCompression,
2690
+ callPromptCompression: promptCompression,
2691
+ stats: promptCompressionStats,
2692
+ withUsage,
2693
+ operation: "responses.create"
2694
+ });
2695
+ ctx.setUsage(openAIRequestExecutionMetadata(finalParams, provider));
2696
+ const request = attachCorrelationHeader(requestOptions, ctx.begin.correlationId);
2697
+ if (wantsStream) {
2698
+ const apiPromise2 = originalCreate(finalParams, request);
2699
+ const wrappedPromise2 = transformApiPromise(apiPromise2, (rawStream) => {
2700
+ ensureAsyncIterable(rawStream, "responses.create");
2701
+ const wrappedStream = wrapStreamForUsageTap(rawStream, async () => {
2702
+ const usage = await extractUsageFromStream(rawStream, ctx.begin.data.vendorHints, provider);
2703
+ if (usage) {
2704
+ ctx.setUsage(usage);
2705
+ }
2706
+ }, ctx);
2707
+ return wrappedStream;
2708
+ });
2709
+ return wrappedPromise2;
2710
+ }
2711
+ const apiPromise = originalCreate(finalParams, request);
2712
+ const wrappedPromise = transformApiPromise(apiPromise, async (response) => {
2713
+ tryInferUsage(response, ctx.begin.data.vendorHints, void 0, ctx, provider);
2714
+ await captureMeteredOpenAISample({
2715
+ usageTap,
2716
+ sampling: defaultSampling,
2717
+ decision: sampleDecision,
2718
+ ctx,
2719
+ beginRequest,
2720
+ input: params,
2721
+ response,
2722
+ startedAt: sampleStartedAt
2723
+ });
2724
+ return response;
2725
+ }, async (error) => {
2726
+ await captureMeteredOpenAISample({
2727
+ usageTap,
2728
+ sampling: defaultSampling,
2729
+ decision: sampleDecision,
2730
+ ctx,
2731
+ beginRequest,
2732
+ input: params,
2733
+ error,
2734
+ startedAt: sampleStartedAt
2735
+ });
2736
+ throw error;
2737
+ });
2738
+ return wrappedPromise;
2739
+ }, withUsage);
2740
+ };
2741
+ const handler = {
2742
+ get(target, prop, receiver) {
2743
+ if (prop === "create") {
2744
+ return wrappedCreate;
2745
+ }
2746
+ return Reflect.get(target, prop, receiver);
2747
+ }
2748
+ };
2749
+ return new Proxy(resource, handler);
2750
+ }
2751
+ function createChatCompletionsProxy(resource, usageTap, defaultContext, applyVendorHints, defaultPromptCompression, promptCompressionStats, defaultSampling, provider) {
2752
+ const originalCreate = resource.create.bind(resource);
2753
+ const streamCandidate = resource.stream;
2754
+ const originalStream = typeof streamCandidate === "function" ? streamCandidate.bind(resource) : void 0;
2755
+ const wrappedCreate = (params, options) => {
2756
+ const {
2757
+ requestOptions,
2758
+ usageContext,
2759
+ withUsage,
2760
+ promptCompression
2761
+ } = splitUsageOptions(options);
2762
+ const beginRequest = withRuntimeCompressionContext(
2763
+ resolveBeginRequest(defaultContext, usageContext),
2764
+ "openai",
2765
+ String(params.model)
2766
+ );
2767
+ const wantsStream = isStreamingRequest(params);
2768
+ return usageTap.withUsage(beginRequest, async (ctx) => {
2769
+ const sampleStartedAt = Date.now();
2770
+ const sampleDecision = wantsStream ? Promise.resolve(false) : startMeteredOpenAISampleDecision({
2771
+ usageTap,
2772
+ sampling: defaultSampling,
2773
+ beginRequest,
2774
+ input: params
2775
+ });
2776
+ const hintedParams = applyVendorHints ? applyChatVendorHints(params, ctx.begin.data.vendorHints) : params;
2777
+ const finalParams = await compressChatParamsForCall({
2778
+ params: hintedParams,
2779
+ usageTap,
2780
+ ctx,
2781
+ defaultPromptCompression,
2782
+ callPromptCompression: promptCompression,
2783
+ stats: promptCompressionStats,
2784
+ withUsage,
2785
+ operation: "chat.completions.create"
2786
+ });
2787
+ ctx.setUsage(openAIRequestExecutionMetadata(finalParams, provider));
2788
+ const request = attachCorrelationHeader(requestOptions, ctx.begin.correlationId);
2789
+ if (wantsStream) {
2790
+ const apiPromise2 = originalCreate(finalParams, request);
2791
+ const wrappedPromise2 = transformApiPromise(apiPromise2, (rawStream) => {
2792
+ ensureAsyncIterable(rawStream, "chat.completions.create");
2793
+ const wrappedStream2 = wrapStreamForUsageTap(rawStream, async () => {
2794
+ const usage = await extractUsageFromStream(rawStream, ctx.begin.data.vendorHints, provider);
2795
+ if (usage) {
2796
+ ctx.setUsage(usage);
2797
+ }
2798
+ }, ctx);
2799
+ return wrappedStream2;
2800
+ });
2801
+ return wrappedPromise2;
2802
+ }
2803
+ const apiPromise = originalCreate(finalParams, request);
2804
+ const wrappedPromise = transformApiPromise(apiPromise, async (response) => {
2805
+ tryInferUsage(response, ctx.begin.data.vendorHints, void 0, ctx, provider);
2806
+ await captureMeteredOpenAISample({
2807
+ usageTap,
2808
+ sampling: defaultSampling,
2809
+ decision: sampleDecision,
2810
+ ctx,
2811
+ beginRequest,
2812
+ input: params,
2813
+ response,
2814
+ startedAt: sampleStartedAt
2815
+ });
2816
+ return response;
2817
+ }, async (error) => {
2818
+ await captureMeteredOpenAISample({
2819
+ usageTap,
2820
+ sampling: defaultSampling,
2821
+ decision: sampleDecision,
2822
+ ctx,
2823
+ beginRequest,
2824
+ input: params,
2825
+ error,
2826
+ startedAt: sampleStartedAt
2827
+ });
2828
+ throw error;
2829
+ });
2830
+ return wrappedPromise;
2831
+ }, withUsage);
2832
+ };
2833
+ const wrappedStream = originalStream ? (params, options) => {
2834
+ const {
2835
+ requestOptions,
2836
+ usageContext,
2837
+ withUsage,
2838
+ promptCompression
2839
+ } = splitUsageOptions(options);
2840
+ const beginRequest = withRuntimeCompressionContext(
2841
+ resolveBeginRequest(defaultContext, usageContext),
2842
+ "openai",
2843
+ String(params.model)
2844
+ );
2845
+ return usageTap.withUsage(beginRequest, async (ctx) => {
2846
+ const hintedParams = applyVendorHints ? applyChatVendorHints(params, ctx.begin.data.vendorHints) : params;
2847
+ const finalParams = await compressChatParamsForCall({
2848
+ params: hintedParams,
2849
+ usageTap,
2850
+ ctx,
2851
+ defaultPromptCompression,
2852
+ callPromptCompression: promptCompression,
2853
+ stats: promptCompressionStats,
2854
+ withUsage,
2855
+ operation: "chat.completions.stream"
2856
+ });
2857
+ ctx.setUsage(openAIRequestExecutionMetadata(finalParams, provider));
2858
+ const request = attachCorrelationHeader(requestOptions, ctx.begin.correlationId);
2859
+ const apiPromise = originalStream(finalParams, request);
2860
+ const wrappedPromise = transformApiPromise(apiPromise, (rawStream) => {
2861
+ ensureAsyncIterable(rawStream, "chat.completions.stream");
2862
+ const wrappedStreamInner = wrapStreamForUsageTap(rawStream, async () => {
2863
+ const usage = await extractUsageFromStream(
2864
+ rawStream,
2865
+ ctx.begin.data.vendorHints,
2866
+ provider
2867
+ );
2868
+ if (usage) {
2869
+ ctx.setUsage(usage);
2870
+ }
2871
+ }, ctx);
2872
+ return wrappedStreamInner;
2873
+ });
2874
+ return wrappedPromise;
2875
+ }, withUsage);
2876
+ } : void 0;
2877
+ const handler = {
2878
+ get(target, prop, receiver) {
2879
+ if (prop === "create") {
2880
+ return wrappedCreate;
2881
+ }
2882
+ if (prop === "stream" && wrappedStream) {
2883
+ return wrappedStream;
2884
+ }
2885
+ return Reflect.get(target, prop, receiver);
2886
+ }
2887
+ };
2888
+ return new Proxy(resource, handler);
2889
+ }
2890
+ async function compressChatParamsForCall(args) {
2891
+ let compression = resolveEffectivePromptCompressionOptions(
2892
+ args.defaultPromptCompression,
2893
+ args.callPromptCompression
2894
+ );
2895
+ const runtimePolicy = args.ctx.begin.data.runtimeCompressionPolicy;
2896
+ const policyDriven = !compression && Boolean(runtimePolicy);
2897
+ if (policyDriven && runtimePolicy) {
2898
+ if (!runtimePolicy.selected) {
2899
+ args.ctx.setUsage({
2900
+ runtimeCompression: bypassedRuntimeMeasurement(runtimePolicy)
2901
+ });
2902
+ return args.params;
2903
+ }
2904
+ compression = openAIPolicyCompressionOptions(runtimePolicy);
2905
+ if (runtimePolicy.mode === "SHADOW") {
2906
+ const startedAt2 = Date.now();
2907
+ void compressChatParams(
2908
+ args.params,
2909
+ args.usageTap,
2910
+ compression,
2911
+ args.withUsage?.signal
2912
+ ).then((outcome2) => {
2913
+ args.ctx.setUsage({
2914
+ runtimeCompression: openAIRuntimeMeasurement({
2915
+ policy: runtimePolicy,
2916
+ telemetry: buildPromptCompressionTelemetry(outcome2.segments),
2917
+ latencyMs: Date.now() - startedAt2,
2918
+ shadow: true,
2919
+ originalPayload: args.params,
2920
+ resultPayload: outcome2.params
2921
+ })
2922
+ });
2923
+ }).catch(() => {
2924
+ args.ctx.setUsage({
2925
+ runtimeCompression: failedRuntimeMeasurement(
2926
+ runtimePolicy,
2927
+ Date.now() - startedAt2
2928
+ )
2929
+ });
2930
+ });
2931
+ return args.params;
2932
+ }
2933
+ }
2934
+ if (!compression) {
2935
+ return args.params;
2936
+ }
2937
+ const startedAt = Date.now();
2938
+ const outcome = await compressChatParams(
2939
+ args.params,
2940
+ args.usageTap,
2941
+ compression,
2942
+ args.withUsage?.signal
2943
+ );
2944
+ if (policyDriven && runtimePolicy) {
2945
+ const runtimeMeasurement = openAIRuntimeMeasurement({
2946
+ policy: runtimePolicy,
2947
+ telemetry: buildPromptCompressionTelemetry(outcome.segments),
2948
+ latencyMs: Date.now() - startedAt,
2949
+ originalPayload: args.params,
2950
+ resultPayload: outcome.params
2951
+ });
2952
+ args.ctx.setUsage({ runtimeCompression: runtimeMeasurement });
2953
+ if (runtimeMeasurement.decision !== "compressed") return args.params;
2954
+ }
2955
+ await recordCompressionOutcome({
2956
+ outcome,
2957
+ compression,
2958
+ usageTap: args.usageTap,
2959
+ ctx: args.ctx,
2960
+ stats: args.stats,
2961
+ withUsage: args.withUsage,
2962
+ operation: args.operation
2963
+ });
2964
+ return outcome.params;
2965
+ }
2966
+ async function compressResponsesParamsForCall(args) {
2967
+ let compression = resolveEffectivePromptCompressionOptions(
2968
+ args.defaultPromptCompression,
2969
+ args.callPromptCompression
2970
+ );
2971
+ const runtimePolicy = args.ctx.begin.data.runtimeCompressionPolicy;
2972
+ const policyDriven = !compression && Boolean(runtimePolicy);
2973
+ if (policyDriven && runtimePolicy) {
2974
+ if (!runtimePolicy.selected) {
2975
+ args.ctx.setUsage({
2976
+ runtimeCompression: bypassedRuntimeMeasurement(runtimePolicy)
2977
+ });
2978
+ return args.params;
2979
+ }
2980
+ compression = openAIPolicyCompressionOptions(runtimePolicy);
2981
+ if (runtimePolicy.mode === "SHADOW") {
2982
+ const startedAt2 = Date.now();
2983
+ void compressResponsesParams(
2984
+ args.params,
2985
+ args.usageTap,
2986
+ compression,
2987
+ args.withUsage?.signal
2988
+ ).then((outcome2) => {
2989
+ args.ctx.setUsage({
2990
+ runtimeCompression: openAIRuntimeMeasurement({
2991
+ policy: runtimePolicy,
2992
+ telemetry: buildPromptCompressionTelemetry(outcome2.segments),
2993
+ latencyMs: Date.now() - startedAt2,
2994
+ shadow: true,
2995
+ originalPayload: args.params,
2996
+ resultPayload: outcome2.params
2997
+ })
2998
+ });
2999
+ }).catch(() => {
3000
+ args.ctx.setUsage({
3001
+ runtimeCompression: failedRuntimeMeasurement(
3002
+ runtimePolicy,
3003
+ Date.now() - startedAt2
3004
+ )
3005
+ });
3006
+ });
3007
+ return args.params;
3008
+ }
3009
+ }
3010
+ if (!compression) {
3011
+ return args.params;
3012
+ }
3013
+ const startedAt = Date.now();
3014
+ const outcome = await compressResponsesParams(
3015
+ args.params,
3016
+ args.usageTap,
3017
+ compression,
3018
+ args.withUsage?.signal
3019
+ );
3020
+ if (policyDriven && runtimePolicy) {
3021
+ const runtimeMeasurement = openAIRuntimeMeasurement({
3022
+ policy: runtimePolicy,
3023
+ telemetry: buildPromptCompressionTelemetry(outcome.segments),
3024
+ latencyMs: Date.now() - startedAt,
3025
+ originalPayload: args.params,
3026
+ resultPayload: outcome.params
3027
+ });
3028
+ args.ctx.setUsage({ runtimeCompression: runtimeMeasurement });
3029
+ if (runtimeMeasurement.decision !== "compressed") return args.params;
3030
+ }
3031
+ await recordCompressionOutcome({
3032
+ outcome,
3033
+ compression,
3034
+ usageTap: args.usageTap,
3035
+ ctx: args.ctx,
3036
+ stats: args.stats,
3037
+ withUsage: args.withUsage,
3038
+ operation: args.operation
3039
+ });
3040
+ return outcome.params;
3041
+ }
3042
+ function openAIPolicyCompressionOptions(policy) {
3043
+ const roles = Object.fromEntries(
3044
+ ["system", "user", "tool", "assistant"].filter((role) => policy.snapshot.scope.messageRoles.includes(role)).map((role) => [role, true])
3045
+ );
3046
+ return {
3047
+ provider: "usagetap",
3048
+ roles,
3049
+ minContextTokens: policy.snapshot.scope.minimumTokens,
3050
+ failOpen: true
3051
+ };
3052
+ }
3053
+ function bypassedRuntimeMeasurement(policy) {
3054
+ return {
3055
+ policyId: policy.policyId,
3056
+ policyVersionId: policy.policyVersionId,
3057
+ policyVersion: policy.version,
3058
+ rolloutMode: policy.mode,
3059
+ decision: "bypassed",
3060
+ reasonCode: "not_in_rollout_sample",
3061
+ methodsAttempted: [],
3062
+ methodsApplied: [],
3063
+ originalTokens: 0,
3064
+ resultTokens: 0,
3065
+ savedTokens: 0,
3066
+ reductionPercentage: 0,
3067
+ compressionLatencyMs: 0,
3068
+ compressionComputeCostUsd: 0,
3069
+ financialsEstimated: true
3070
+ };
3071
+ }
3072
+ function failedRuntimeMeasurement(policy, latencyMs) {
3073
+ return {
3074
+ ...bypassedRuntimeMeasurement(policy),
3075
+ decision: "fallback",
3076
+ reasonCode: "transformation_failed",
3077
+ methodsAttempted: ["deterministic"],
3078
+ compressionLatencyMs: latencyMs
3079
+ };
3080
+ }
3081
+ function openAIRuntimeMeasurement(input) {
3082
+ const telemetry = input.telemetry;
3083
+ const originalTokens = telemetry?.originalTokens ?? estimatePromptTokens(JSON.stringify(input.originalPayload));
3084
+ const resultTokens = telemetry?.compressedTokens ?? originalTokens;
3085
+ const savedTokens = Math.max(0, telemetry?.savedTokens ?? 0);
3086
+ const reductionPercentage = originalTokens > 0 ? savedTokens / originalTokens * 100 : 0;
3087
+ const belowMinimumSize = originalTokens < input.policy.snapshot.scope.minimumTokens;
3088
+ const latencyExceeded = input.latencyMs > input.policy.snapshot.gates.maximumLatencyMs;
3089
+ const belowSavings = savedTokens < input.policy.snapshot.gates.minimumTokensRemoved || reductionPercentage < input.policy.snapshot.gates.minimumReductionPercentage;
3090
+ const accepted = !belowMinimumSize && !latencyExceeded && !belowSavings;
3091
+ const deepText = input.policy.snapshot.methods.deepText.enabled && !input.policy.snapshot.rollout.deterministicOnly && (input.policy.mode !== "CANARY" || input.policy.snapshot.rollout.deepTextCanaryAllowed);
3092
+ const reasonCode = belowMinimumSize ? "below_minimum_size" : latencyExceeded ? "latency_budget_exceeded" : belowSavings ? "below_minimum_savings" : void 0;
3093
+ const measurement = {
3094
+ policyId: input.policy.policyId,
3095
+ policyVersionId: input.policy.policyVersionId,
3096
+ policyVersion: input.policy.version,
3097
+ rolloutMode: input.policy.mode,
3098
+ decision: accepted ? input.shadow ? "bypassed" : "compressed" : latencyExceeded ? "fallback" : "skipped",
3099
+ ...reasonCode ? { reasonCode } : {},
3100
+ methodsAttempted: [
3101
+ "deterministic",
3102
+ ...deepText ? ["deep_text"] : []
3103
+ ],
3104
+ methodsApplied: accepted ? ["deterministic"] : [],
3105
+ originalTokens,
3106
+ resultTokens: accepted ? resultTokens : originalTokens,
3107
+ savedTokens: accepted ? savedTokens : 0,
3108
+ reductionPercentage: accepted ? reductionPercentage : 0,
3109
+ compressionLatencyMs: input.latencyMs,
3110
+ compressionComputeCostUsd: 0,
3111
+ financialsEstimated: true
3112
+ };
3113
+ return measurement;
3114
+ }
3115
+ async function recordCompressionOutcome(args) {
3116
+ const telemetry = buildPromptCompressionTelemetry(args.outcome.segments);
3117
+ if (!telemetry) {
3118
+ return;
3119
+ }
3120
+ const turn = {
3121
+ ...telemetry,
3122
+ callId: args.ctx.begin.data.callId,
3123
+ operation: args.operation,
3124
+ messagesCompressed: args.outcome.segments.length,
3125
+ timestamp: Date.now()
3126
+ };
3127
+ args.stats._record(turn);
3128
+ try {
3129
+ await args.usageTap.recordPromptCompression(
3130
+ {
3131
+ callId: args.ctx.begin.data.callId,
3132
+ promptCompression: telemetry
3133
+ },
3134
+ promptCompressionRequestOptions(args.withUsage, args.ctx.begin.correlationId)
3135
+ );
3136
+ } catch (error) {
3137
+ args.stats._recordFailure({
3138
+ callId: args.ctx.begin.data.callId,
3139
+ operation: args.operation,
3140
+ stage: "telemetry",
3141
+ message: error instanceof Error ? error.message : String(error),
3142
+ timestamp: Date.now()
3143
+ });
3144
+ if (args.compression.failOpen === false) {
3145
+ throw error;
3146
+ }
3147
+ }
3148
+ }
3149
+ async function compressChatParams(params, usageTap, compression, signal) {
3150
+ if (!params || typeof params !== "object") {
3151
+ return { params, segments: [] };
3152
+ }
3153
+ const source = cloneRecord(params);
3154
+ const messages = Array.isArray(source.messages) ? source.messages : void 0;
3155
+ if (!messages) {
3156
+ return { params, segments: [] };
3157
+ }
3158
+ if (isBelowMinContextTokens(
3159
+ { messages, tools: source.tools },
3160
+ compression.minContextTokens
3161
+ )) {
3162
+ return { params, segments: [] };
3163
+ }
3164
+ if (shouldUseUsageTapMessageEndpoint(compression)) {
3165
+ const result = await usageTap.compressPromptMessages(source, {
3166
+ provider: "usagetap",
3167
+ failOpen: compression.failOpen,
3168
+ mode: compression.mode,
3169
+ latencyBudgetMs: compression.latencyBudgetMs,
3170
+ compactEmptyUserMessages: compression.compactEmptyUserMessages,
3171
+ compactDuplicateUserTextParts: compression.compactDuplicateUserTextParts,
3172
+ aggressiveness: resolveMessageEndpointAggressiveness(compression),
3173
+ signal
3174
+ });
3175
+ return {
3176
+ params: result.compressedInput,
3177
+ segments: [{ role: "user", result }]
3178
+ };
3179
+ }
3180
+ const messageResults = await Promise.all(
3181
+ messages.map(
3182
+ (message) => compressOpenAIMessage(message, usageTap, compression, signal)
3183
+ )
3184
+ );
3185
+ return {
3186
+ params: {
3187
+ ...source,
3188
+ messages: messageResults.map((result) => result.value)
3189
+ },
3190
+ segments: messageResults.flatMap((result) => result.segments)
3191
+ };
3192
+ }
3193
+ async function compressResponsesParams(params, usageTap, compression, signal) {
3194
+ if (!params || typeof params !== "object") {
3195
+ return { params, segments: [] };
3196
+ }
3197
+ const source = cloneRecord(params);
3198
+ const segments = [];
3199
+ if (isBelowMinContextTokens(
3200
+ {
3201
+ instructions: source.instructions,
3202
+ input: source.input,
3203
+ tools: source.tools
3204
+ },
3205
+ compression.minContextTokens
3206
+ )) {
3207
+ return { params, segments };
3208
+ }
3209
+ if (typeof source.instructions === "string") {
3210
+ const compressed = await compressTextForRole(
3211
+ source.instructions,
3212
+ "system",
3213
+ usageTap,
3214
+ compression,
3215
+ signal
3216
+ );
3217
+ if (compressed) {
3218
+ source.instructions = compressed.text;
3219
+ segments.push(compressed.segment);
3220
+ }
3221
+ }
3222
+ if (typeof source.input === "string") {
3223
+ const compressed = await compressTextForRole(
3224
+ source.input,
3225
+ "user",
3226
+ usageTap,
3227
+ compression,
3228
+ signal
3229
+ );
3230
+ if (compressed) {
3231
+ source.input = compressed.text;
3232
+ segments.push(compressed.segment);
3233
+ }
3234
+ } else if (Array.isArray(source.input)) {
3235
+ const inputResults = await Promise.all(
3236
+ source.input.map(
3237
+ (item) => compressResponsesInputItem(item, usageTap, compression, signal)
3238
+ )
3239
+ );
3240
+ source.input = inputResults.map((result) => result.value);
3241
+ segments.push(...inputResults.flatMap((result) => result.segments));
3242
+ }
3243
+ return {
3244
+ params: source,
3245
+ segments
3246
+ };
3247
+ }
3248
+ async function compressOpenAIMessage(message, usageTap, compression, signal) {
3249
+ if (!isObjectRecord(message)) {
3250
+ return { value: message, segments: [] };
3251
+ }
3252
+ const role = mapOpenAIRole(message.role);
3253
+ if (!role) {
3254
+ return { value: message, segments: [] };
3255
+ }
3256
+ const content = message.content;
3257
+ if (typeof content === "string") {
3258
+ const compressed = await compressTextForRole(
3259
+ content,
3260
+ role,
3261
+ usageTap,
3262
+ compression,
3263
+ signal
3264
+ );
3265
+ if (!compressed) {
3266
+ return { value: message, segments: [] };
3267
+ }
3268
+ return {
3269
+ value: { ...message, content: compressed.text },
3270
+ segments: [compressed.segment]
3271
+ };
3272
+ }
3273
+ if (Array.isArray(content)) {
3274
+ const blockResults = await Promise.all(
3275
+ content.map(
3276
+ (block) => compressOpenAITextBlock(block, role, usageTap, compression, signal)
3277
+ )
3278
+ );
3279
+ const segments = blockResults.flatMap(
3280
+ (result) => result.segment ? [result.segment] : []
3281
+ );
3282
+ return {
3283
+ value: segments.length ? { ...message, content: blockResults.map((result) => result.value) } : message,
3284
+ segments
3285
+ };
3286
+ }
3287
+ return { value: message, segments: [] };
3288
+ }
3289
+ async function compressOpenAITextBlock(block, role, usageTap, compression, signal) {
3290
+ if (!isObjectRecord(block) || block.type !== "text" || typeof block.text !== "string") {
3291
+ return { value: block };
3292
+ }
3293
+ const compressed = await compressTextForRole(
3294
+ block.text,
3295
+ role,
3296
+ usageTap,
3297
+ compression,
3298
+ signal
3299
+ );
3300
+ if (!compressed) {
3301
+ return { value: block };
3302
+ }
3303
+ return {
3304
+ value: { ...block, text: compressed.text },
3305
+ segment: compressed.segment
3306
+ };
3307
+ }
3308
+ async function compressResponsesInputItem(item, usageTap, compression, signal) {
3309
+ if (!isObjectRecord(item)) {
3310
+ return { value: item, segments: [] };
3311
+ }
3312
+ const specialToolRole = mapResponsesItemTypeToRole(item.type);
3313
+ const role = specialToolRole ?? mapOpenAIRole(item.role);
3314
+ const segments = [];
3315
+ let next = item;
3316
+ if (role && typeof item.content === "string") {
3317
+ const compressed = await compressTextForRole(
3318
+ item.content,
3319
+ role,
3320
+ usageTap,
3321
+ compression,
3322
+ signal
3323
+ );
3324
+ if (compressed) {
3325
+ next = { ...next, content: compressed.text };
3326
+ segments.push(compressed.segment);
3327
+ }
3328
+ } else if (role && Array.isArray(item.content)) {
3329
+ const contentResults = await Promise.all(
3330
+ item.content.map(
3331
+ (block) => compressResponsesContentBlock(block, role, usageTap, compression, signal)
3332
+ )
3333
+ );
3334
+ segments.push(
3335
+ ...contentResults.flatMap(
3336
+ (result) => result.segment ? [result.segment] : []
3337
+ )
3338
+ );
3339
+ if (segments.length) {
3340
+ next = {
3341
+ ...next,
3342
+ content: contentResults.map((result) => result.value)
3343
+ };
3344
+ }
3345
+ }
3346
+ if (specialToolRole && typeof item.output === "string") {
3347
+ const compressed = await compressTextForRole(
3348
+ item.output,
3349
+ specialToolRole,
3350
+ usageTap,
3351
+ compression,
3352
+ signal
3353
+ );
3354
+ if (compressed) {
3355
+ next = { ...next, output: compressed.text };
3356
+ segments.push(compressed.segment);
3357
+ }
3358
+ }
3359
+ return { value: next, segments };
3360
+ }
3361
+ async function compressResponsesContentBlock(block, role, usageTap, compression, signal) {
3362
+ if (!isObjectRecord(block)) {
3363
+ return { value: block };
3364
+ }
3365
+ if ((block.type === "input_text" || block.type === "text") && typeof block.text === "string") {
3366
+ const compressed = await compressTextForRole(
3367
+ block.text,
3368
+ role,
3369
+ usageTap,
3370
+ compression,
3371
+ signal
3372
+ );
3373
+ if (compressed) {
3374
+ return {
3375
+ value: { ...block, text: compressed.text },
3376
+ segment: compressed.segment
3377
+ };
3378
+ }
3379
+ }
3380
+ if (role === "tool" && typeof block.output === "string") {
3381
+ const compressed = await compressTextForRole(
3382
+ block.output,
3383
+ role,
3384
+ usageTap,
3385
+ compression,
3386
+ signal
3387
+ );
3388
+ if (compressed) {
3389
+ return {
3390
+ value: { ...block, output: compressed.text },
3391
+ segment: compressed.segment
3392
+ };
3393
+ }
3394
+ }
3395
+ return { value: block };
3396
+ }
3397
+ async function compressTextForRole(text, role, usageTap, compression, signal) {
3398
+ if (!text.trim()) {
3399
+ return void 0;
3400
+ }
3401
+ const roleOptions = resolveRoleCompressionOptions(compression, role);
3402
+ if (!roleOptions) {
3403
+ return void 0;
3404
+ }
3405
+ const estimatedTokens = estimatePromptTokens(text);
3406
+ if (typeof roleOptions.minTokens === "number" && estimatedTokens < roleOptions.minTokens) {
3407
+ return void 0;
3408
+ }
3409
+ const result = await usageTap.compressPromptInput(text, {
3410
+ provider: roleOptions.provider,
3411
+ failOpen: roleOptions.failOpen,
3412
+ tokenCompanyModel: roleOptions.tokenCompanyModel,
3413
+ aggressiveness: roleOptions.aggressiveness,
3414
+ tokenCompanyAggressiveness: roleOptions.tokenCompanyAggressiveness,
3415
+ tokenCompanyAppId: roleOptions.tokenCompanyAppId,
3416
+ usageTapCompressionModel: roleOptions.usageTapCompressionModel,
3417
+ usageTapCompressionAggressiveness: roleOptions.usageTapCompressionAggressiveness,
3418
+ signal
3419
+ });
3420
+ const compressedText = typeof result.compressedInput === "string" ? result.compressedInput : String(result.compressedInput);
3421
+ return {
3422
+ text: compressedText,
3423
+ segment: { role, result: { ...result, compressedInput: compressedText } }
3424
+ };
3425
+ }
3426
+ function normalizePromptCompressionOptions(options) {
3427
+ if (!options) {
3428
+ return void 0;
3429
+ }
3430
+ if (options === true) {
3431
+ return {};
3432
+ }
3433
+ if (options.enabled === false) {
3434
+ return void 0;
3435
+ }
3436
+ return options;
3437
+ }
3438
+ function isBelowMinContextTokens(context, minContextTokens) {
3439
+ return typeof minContextTokens === "number" && estimatePromptTokens(context) < Math.max(0, minContextTokens);
3440
+ }
3441
+ function resolveEffectivePromptCompressionOptions(defaults, override) {
3442
+ if (override === false) {
3443
+ return void 0;
3444
+ }
3445
+ if (override === void 0) {
3446
+ return defaults;
3447
+ }
3448
+ if (override === true) {
3449
+ return defaults ?? {};
3450
+ }
3451
+ const merged = {
3452
+ ...defaults ?? {},
3453
+ ...override,
3454
+ roles: override.roles ?? defaults?.roles
3455
+ };
3456
+ return normalizePromptCompressionOptions(merged);
3457
+ }
3458
+ function resolveRoleCompressionOptions(compression, role) {
3459
+ const hasExplicitRoles = compression.roles !== void 0;
3460
+ const setting = compression.roles?.[role];
3461
+ if (hasExplicitRoles && setting === void 0) {
3462
+ return void 0;
3463
+ }
3464
+ if (!hasExplicitRoles && role === "assistant") {
3465
+ return void 0;
3466
+ }
3467
+ if (setting === false) {
3468
+ return void 0;
3469
+ }
3470
+ const roleOptions = typeof setting === "object" ? setting : void 0;
3471
+ if (roleOptions?.enabled === false) {
3472
+ return void 0;
3473
+ }
3474
+ return {
3475
+ provider: roleOptions?.provider ?? compression.provider,
3476
+ minTokens: roleOptions?.minTokens ?? compression.minTokens,
3477
+ failOpen: compression.failOpen,
3478
+ tokenCompanyModel: compression.tokenCompanyModel,
3479
+ aggressiveness: roleOptions?.aggressiveness ?? resolveAggressiveness(compression, role),
3480
+ tokenCompanyAggressiveness: roleOptions?.tokenCompanyAggressiveness ?? resolveTokenCompanyAggressiveness(compression, role),
3481
+ tokenCompanyAppId: compression.tokenCompanyAppId,
3482
+ usageTapCompressionModel: compression.usageTapCompressionModel,
3483
+ usageTapCompressionAggressiveness: roleOptions?.usageTapCompressionAggressiveness ?? resolveUsageTapCompressionAggressiveness(compression, role)
3484
+ };
3485
+ }
3486
+ function resolveAggressiveness(compression, role) {
3487
+ if (typeof compression.aggressiveness === "number") {
3488
+ return compression.aggressiveness;
3489
+ }
3490
+ return compression.aggressiveness?.[role];
3491
+ }
3492
+ function resolveTokenCompanyAggressiveness(compression, role) {
3493
+ if (typeof compression.tokenCompanyAggressiveness === "number") {
3494
+ return compression.tokenCompanyAggressiveness;
3495
+ }
3496
+ return compression.tokenCompanyAggressiveness?.[role];
3497
+ }
3498
+ function resolveUsageTapCompressionAggressiveness(compression, role) {
3499
+ if (typeof compression.usageTapCompressionAggressiveness === "number") {
3500
+ return compression.usageTapCompressionAggressiveness;
3501
+ }
3502
+ return compression.usageTapCompressionAggressiveness?.[role];
3503
+ }
3504
+ function shouldUseUsageTapMessageEndpoint(compression) {
3505
+ if (compression.provider !== "usagetap") {
3506
+ return false;
3507
+ }
3508
+ return Object.values(compression.roles ?? {}).every((setting) => {
3509
+ if (typeof setting !== "object" || setting === null) {
3510
+ return true;
3511
+ }
3512
+ return setting.provider === void 0 || setting.provider === "usagetap";
3513
+ });
3514
+ }
3515
+ function resolveMessageEndpointAggressiveness(compression) {
3516
+ const base = compression.aggressiveness ?? compression.usageTapCompressionAggressiveness ?? compression.tokenCompanyAggressiveness;
3517
+ if (typeof base === "number" || base === void 0) {
3518
+ return hasExplicitEnabledRoles(compression) ? buildRoleAggressiveness(compression, base) : base;
3519
+ }
3520
+ return buildRoleAggressiveness(compression, void 0, base);
3521
+ }
3522
+ function hasExplicitEnabledRoles(compression) {
3523
+ return Object.values(compression.roles ?? {}).some((setting) => setting !== false);
3524
+ }
3525
+ function buildRoleAggressiveness(compression, fallback, base = {}) {
3526
+ const roles = ["system", "user", "tool", "assistant"];
3527
+ const result = {};
3528
+ for (const role of roles) {
3529
+ const roleOptions = resolveRoleCompressionOptions(compression, role);
3530
+ if (!roleOptions) {
3531
+ continue;
3532
+ }
3533
+ const roleAggressiveness = roleOptions.aggressiveness ?? roleOptions.usageTapCompressionAggressiveness ?? roleOptions.tokenCompanyAggressiveness ?? base[role] ?? fallback;
3534
+ if (roleAggressiveness !== void 0) {
3535
+ result[role] = roleAggressiveness;
3536
+ }
3537
+ }
3538
+ return result;
3539
+ }
3540
+ function buildPromptCompressionTelemetry(segments) {
3541
+ if (!segments.length) {
3542
+ return void 0;
3543
+ }
3544
+ const originalCharacters = segments.reduce(
3545
+ (sum, segment) => sum + segment.result.originalCharacters,
3546
+ 0
3547
+ );
3548
+ const compressedCharacters = segments.reduce(
3549
+ (sum, segment) => sum + segment.result.compressedCharacters,
3550
+ 0
3551
+ );
3552
+ const originalTokens = segments.reduce(
3553
+ (sum, segment) => sum + segment.result.originalTokens,
3554
+ 0
3555
+ );
3556
+ const compressedTokens = segments.reduce(
3557
+ (sum, segment) => sum + segment.result.compressedTokens,
3558
+ 0
3559
+ );
3560
+ const savedCharacters = Math.max(0, originalCharacters - compressedCharacters);
3561
+ const savedTokens = Math.max(0, originalTokens - compressedTokens);
3562
+ const providers = dedupeStrings2(segments.map((segment) => segment.result.provider));
3563
+ const roles = dedupeStrings2(segments.map((segment) => `role:${segment.role}`));
3564
+ const techniques = dedupeStrings2([
3565
+ "openai-wrapper",
3566
+ ...roles,
3567
+ ...segments.flatMap((segment) => segment.result.techniques),
3568
+ ...providers.length > 1 ? ["mixed-providers"] : []
3569
+ ]);
3570
+ return {
3571
+ provider: segments[0]?.result.provider ?? "heuristic",
3572
+ originalCharacters,
3573
+ compressedCharacters,
3574
+ savedCharacters,
3575
+ originalTokens,
3576
+ compressedTokens,
3577
+ savedTokens,
3578
+ tokenSavingsRatio: originalTokens > 0 ? savedTokens / originalTokens : 0,
3579
+ savingsRatio: originalCharacters > 0 ? savedCharacters / originalCharacters : 0,
3580
+ techniques
3581
+ };
3582
+ }
3583
+ function promptCompressionRequestOptions(withUsage, correlationId) {
3584
+ return {
3585
+ signal: withUsage?.signal,
3586
+ headers: withUsage?.headers,
3587
+ retries: withUsage?.retries,
3588
+ correlationId
3589
+ };
3590
+ }
3591
+ function mapOpenAIRole(role) {
3592
+ if (role === "system" || role === "developer") {
3593
+ return "system";
3594
+ }
3595
+ if (role === "user") {
3596
+ return "user";
3597
+ }
3598
+ if (role === "tool" || role === "function") {
3599
+ return "tool";
3600
+ }
3601
+ if (role === "assistant") {
3602
+ return "assistant";
3603
+ }
3604
+ return void 0;
3605
+ }
3606
+ function mapResponsesItemTypeToRole(type) {
3607
+ if (type === "function_call_output" || type === "tool_result" || type === "computer_call_output") {
3608
+ return "tool";
3609
+ }
3610
+ return void 0;
3611
+ }
3612
+ function splitUsageOptions(options) {
3613
+ if (!options || typeof options !== "object") {
3614
+ return {};
3615
+ }
3616
+ const { usageTap, withUsage, promptCompression, ...rest } = options;
3617
+ const requestOptions = Object.keys(rest).length ? cloneRequestOptions(rest) : void 0;
3618
+ return {
3619
+ requestOptions,
3620
+ usageContext: usageTap,
3621
+ withUsage,
3622
+ promptCompression
3623
+ };
3624
+ }
3625
+ function resolveBeginRequest(defaults, override) {
3626
+ const base = defaults ?? {};
3627
+ const current = override ?? {};
3628
+ const customerId = current.customerId ?? base.customerId;
3629
+ if (!customerId) {
3630
+ throw new UsageTapError(
3631
+ "USAGETAP_BAD_REQUEST",
3632
+ "wrapOpenAI requires usageTap.customerId (provide defaultContext or options.usageTap)"
3633
+ );
3634
+ }
3635
+ const tags = mergeTags(base.tags, current.tags);
3636
+ const begin = { customerId };
3637
+ const runtimeCompressionContext = current.runtimeCompressionContext ?? base.runtimeCompressionContext;
3638
+ if (runtimeCompressionContext) {
3639
+ begin.runtimeCompressionContext = runtimeCompressionContext;
3640
+ }
3641
+ const requested = current.requested ?? base.requested;
3642
+ if (requested) begin.requested = requested;
3643
+ const feature = current.feature ?? base.feature;
3644
+ if (feature) begin.feature = feature;
3645
+ const runId = current.runId ?? base.runId;
3646
+ if (runId) begin.runId = runId;
3647
+ const idempotency = current.idempotency ?? base.idempotency;
3648
+ if (idempotency) begin.idempotency = idempotency;
3649
+ const customerName = current.customerName ?? base.customerName;
3650
+ if (customerName) begin.customerName = customerName;
3651
+ const customerEmail = current.customerEmail ?? base.customerEmail;
3652
+ if (customerEmail) begin.customerEmail = customerEmail;
3653
+ const customerUserId = current.customerUserId ?? base.customerUserId;
3654
+ if (customerUserId) begin.customerUserId = customerUserId;
3655
+ const customerUserName = current.customerUserName ?? base.customerUserName;
3656
+ if (customerUserName) begin.customerUserName = customerUserName;
3657
+ const customerUserEmail = current.customerUserEmail ?? base.customerUserEmail;
3658
+ if (customerUserEmail) begin.customerUserEmail = customerUserEmail;
3659
+ const stripeCustomerId = current.stripeCustomerId ?? base.stripeCustomerId;
3660
+ if (stripeCustomerId) begin.stripeCustomerId = stripeCustomerId;
3661
+ const holdUsd = current.holdUsd ?? base.holdUsd;
3662
+ if (typeof holdUsd === "number") begin.holdUsd = holdUsd;
3663
+ const batch = current.batch ?? base.batch;
3664
+ if (typeof batch === "boolean") begin.batch = batch;
3665
+ const pricingMode = current.pricingMode ?? base.pricingMode;
3666
+ if (pricingMode) begin.pricingMode = pricingMode;
3667
+ if (tags?.length) {
3668
+ begin.tags = tags;
3669
+ }
3670
+ return begin;
3671
+ }
3672
+ function withRuntimeCompressionContext(begin, provider, model) {
3673
+ return {
3674
+ ...begin,
3675
+ runtimeCompressionContext: {
3676
+ ...begin.runtimeCompressionContext ?? {},
3677
+ provider,
3678
+ model
60
3679
  }
61
3680
  };
62
3681
  }
3682
+ function transformApiPromise(apiPromise, onResolve, onReject) {
3683
+ const resolvedPromise = Promise.resolve(apiPromise).then(onResolve, onReject);
3684
+ if (isObjectRecord(apiPromise)) {
3685
+ const proto = Object.getPrototypeOf(apiPromise);
3686
+ if (proto) {
3687
+ Object.setPrototypeOf(resolvedPromise, proto);
3688
+ }
3689
+ for (const key of Reflect.ownKeys(apiPromise)) {
3690
+ if (key === "then" || key === "catch" || key === "finally") {
3691
+ continue;
3692
+ }
3693
+ try {
3694
+ const descriptor = Object.getOwnPropertyDescriptor(apiPromise, key);
3695
+ if (descriptor) {
3696
+ Reflect.defineProperty(resolvedPromise, key, descriptor);
3697
+ }
3698
+ } catch {
3699
+ }
3700
+ }
3701
+ }
3702
+ return resolvedPromise;
3703
+ }
63
3704
  function isObjectRecord(value) {
64
3705
  return typeof value === "object" && value !== null;
65
3706
  }
66
- function tryInferUsage(response, hints, extractor, ctx) {
3707
+ function cloneRecord(value) {
3708
+ return isObjectRecord(value) ? { ...value } : {};
3709
+ }
3710
+ function isStringTuple(value) {
3711
+ return Array.isArray(value) && value.length >= 2 && typeof value[0] === "string" && typeof value[1] === "string";
3712
+ }
3713
+ function cloneRequestOptions(source) {
3714
+ const clone = { ...source };
3715
+ if ("headers" in clone) {
3716
+ clone.headers = normalizeHeaders(clone.headers);
3717
+ }
3718
+ return clone;
3719
+ }
3720
+ function attachCorrelationHeader(options, correlationId) {
3721
+ const normalized = normalizeHeaders(options?.headers);
3722
+ if (correlationId && !normalized[USAGETAP_CORRELATION_HEADER]) {
3723
+ normalized[USAGETAP_CORRELATION_HEADER] = correlationId;
3724
+ }
3725
+ if (!options) {
3726
+ return Object.keys(normalized).length ? { headers: normalized } : void 0;
3727
+ }
3728
+ const next = { ...options };
3729
+ if (Object.keys(normalized).length) {
3730
+ next.headers = normalized;
3731
+ }
3732
+ return next;
3733
+ }
3734
+ function normalizeHeaders(headers) {
3735
+ if (!headers) {
3736
+ return {};
3737
+ }
3738
+ if (headers instanceof Headers) {
3739
+ const result = {};
3740
+ headers.forEach((value, key) => {
3741
+ result[key.toLowerCase()] = value;
3742
+ });
3743
+ return result;
3744
+ }
3745
+ if (Array.isArray(headers)) {
3746
+ const result = {};
3747
+ for (const entry of headers) {
3748
+ if (!isStringTuple(entry)) {
3749
+ continue;
3750
+ }
3751
+ const [key, value] = entry;
3752
+ result[key.toLowerCase()] = value;
3753
+ }
3754
+ return result;
3755
+ }
3756
+ if (isObjectRecord(headers)) {
3757
+ const result = {};
3758
+ const record = headers;
3759
+ for (const key of Object.keys(record)) {
3760
+ const value = record[key];
3761
+ if (value !== void 0 && value !== null) {
3762
+ result[key.toLowerCase()] = String(value);
3763
+ }
3764
+ }
3765
+ return result;
3766
+ }
3767
+ return {};
3768
+ }
3769
+ function mergeTags(a, b) {
3770
+ const values = [...a ?? [], ...b ?? []].map((value) => typeof value === "string" ? value.trim() : "").filter(Boolean);
3771
+ if (!values.length) {
3772
+ return void 0;
3773
+ }
3774
+ return dedupeStrings2(values);
3775
+ }
3776
+ function dedupeStrings2(values) {
3777
+ return Array.from(new Set(values));
3778
+ }
3779
+ function isStreamingRequest(params) {
3780
+ if (!params || typeof params !== "object") {
3781
+ return false;
3782
+ }
3783
+ const stream = params.stream;
3784
+ if (typeof stream === "boolean") {
3785
+ return stream;
3786
+ }
3787
+ return stream != null;
3788
+ }
3789
+ function applyChatVendorHints(params, hints) {
3790
+ if (!hints) {
3791
+ return params;
3792
+ }
3793
+ const next = cloneRecord(params);
3794
+ if (hints.preferredModel && (next.model === void 0 || next.model === null)) {
3795
+ next.model = hints.preferredModel;
3796
+ }
3797
+ if (typeof hints.maxResponseTokens === "number" && next.max_tokens == null) {
3798
+ next.max_tokens = hints.maxResponseTokens;
3799
+ }
3800
+ if (typeof hints.maxInputTokens === "number" && next.max_input_tokens == null) {
3801
+ next.max_input_tokens = hints.maxInputTokens;
3802
+ }
3803
+ return next;
3804
+ }
3805
+ function applyResponsesVendorHints(params, hints) {
3806
+ if (!hints) {
3807
+ return params;
3808
+ }
3809
+ const next = cloneRecord(params);
3810
+ if (hints.preferredModel && (next.model === void 0 || next.model === null)) {
3811
+ next.model = hints.preferredModel;
3812
+ }
3813
+ if (typeof hints.maxResponseTokens === "number" && next.max_output_tokens == null) {
3814
+ next.max_output_tokens = hints.maxResponseTokens;
3815
+ }
3816
+ return next;
3817
+ }
3818
+ async function extractUsageFromStream(stream, hints, provider = "openai") {
3819
+ const finalPayload = await resolveStreamFinalPayload(stream);
3820
+ if (!finalPayload) {
3821
+ return void 0;
3822
+ }
3823
+ return inferUsageFromResponse(finalPayload, hints, provider);
3824
+ }
3825
+ async function resolveStreamFinalPayload(stream) {
3826
+ if (!stream || typeof stream !== "object") {
3827
+ return void 0;
3828
+ }
3829
+ const candidate = stream;
3830
+ if (typeof candidate.finalChatCompletion === "function") {
3831
+ return candidate.finalChatCompletion();
3832
+ }
3833
+ if (typeof candidate.finalResponse === "function") {
3834
+ return candidate.finalResponse();
3835
+ }
3836
+ if (typeof candidate.finalCompletion === "function") {
3837
+ return candidate.finalCompletion();
3838
+ }
3839
+ if (typeof candidate.finalContent === "function") {
3840
+ return candidate.finalContent();
3841
+ }
3842
+ return void 0;
3843
+ }
3844
+ function ensureAsyncIterable(value, label) {
3845
+ if (!value || typeof value !== "object" || typeof value[Symbol.asyncIterator] !== "function") {
3846
+ throw new UsageTapError(
3847
+ "USAGETAP_BAD_REQUEST",
3848
+ `${label} expected an async iterable stream but received ${typeof value}`
3849
+ );
3850
+ }
3851
+ }
3852
+ function chunkToText(chunk) {
3853
+ if (chunk === void 0 || chunk === null) {
3854
+ return "";
3855
+ }
3856
+ if (typeof chunk === "string") {
3857
+ return chunk;
3858
+ }
3859
+ if (typeof chunk === "object") {
3860
+ const candidate = chunk;
3861
+ const delta = candidate.choices?.[0]?.delta;
3862
+ const content = delta?.content ?? candidate.content;
3863
+ if (typeof content === "string") {
3864
+ return content;
3865
+ }
3866
+ if (Array.isArray(content)) {
3867
+ return content.map((entry) => {
3868
+ if (!entry) return "";
3869
+ if (typeof entry === "string") return entry;
3870
+ if (typeof entry.text === "string") return entry.text;
3871
+ return "";
3872
+ }).join("");
3873
+ }
3874
+ }
3875
+ return String(chunk);
3876
+ }
3877
+ function formatSsePayload(text, options) {
3878
+ if (!text) {
3879
+ return "";
3880
+ }
3881
+ const lines = text.split(/\r?\n/);
3882
+ const eventLine = options?.event ? `event: ${options.event}
3883
+ ` : "";
3884
+ const retryLine = options?.retry ? `retry: ${options.retry}
3885
+ ` : "";
3886
+ const dataLines = lines.map((line) => `data: ${line}`).join("\n");
3887
+ return `${eventLine}${retryLine}${dataLines}
3888
+
3889
+ `;
3890
+ }
3891
+ function setHeaderIfPossible(res, key, value) {
3892
+ if (typeof res.setHeader === "function" && res.headersSent !== true) {
3893
+ res.setHeader(key, value);
3894
+ }
3895
+ }
3896
+ function tryInferUsage(response, hints, extractor, ctx, provider = "openai") {
67
3897
  const explicit = extractor?.(response);
68
- const inferred = explicit ?? inferUsageFromResponse(response, hints);
3898
+ const inferred = explicit ?? inferUsageFromResponse(response, hints, provider);
69
3899
  if (inferred) {
70
3900
  ctx.setUsage(inferred);
71
3901
  }
72
3902
  }
73
- function inferUsageFromResponse(response, hints) {
3903
+ function inferUsageFromResponse(response, hints, provider = "openai") {
74
3904
  if (!response || typeof response !== "object") {
75
3905
  return void 0;
76
3906
  }
@@ -78,12 +3908,41 @@ function inferUsageFromResponse(response, hints) {
78
3908
  if (!candidate.usage) {
79
3909
  return void 0;
80
3910
  }
81
- const cachedInputTokens = candidate.usage.prompt_tokens_details?.cached_tokens ?? candidate.usage.cached_tokens;
3911
+ const cachedInputTokens = candidate.usage.prompt_tokens_details?.cached_tokens ?? candidate.usage.input_tokens_details?.cached_tokens ?? candidate.usage.cached_tokens;
3912
+ const responseEffort = normalizeExecutionReasoningEffort(
3913
+ candidate.reasoning?.effort
3914
+ );
82
3915
  return {
3916
+ providerUsed: provider,
83
3917
  modelUsed: candidate.model ?? hints?.preferredModel,
84
- inputTokens: candidate.usage.prompt_tokens,
85
- responseTokens: candidate.usage.completion_tokens,
86
- cachedInputTokens
3918
+ inputTokens: candidate.usage.prompt_tokens ?? candidate.usage.input_tokens,
3919
+ responseTokens: candidate.usage.completion_tokens ?? candidate.usage.output_tokens,
3920
+ cachedInputTokens,
3921
+ reasoningTokens: candidate.usage.completion_tokens_details?.reasoning_tokens ?? candidate.usage.output_tokens_details?.reasoning_tokens,
3922
+ ...responseEffort ? {
3923
+ reasoningEffort: responseEffort,
3924
+ reasoningEffortSource: "provider_response"
3925
+ } : {},
3926
+ ...typeof candidate.reasoning?.type === "string" ? { reasoningMode: candidate.reasoning.type } : typeof candidate.reasoning?.mode === "string" ? { reasoningMode: candidate.reasoning.mode } : {}
3927
+ };
3928
+ }
3929
+ function normalizeExecutionReasoningEffort(value) {
3930
+ return value === "none" || value === "minimal" || value === "low" || value === "medium" || value === "high" || value === "xhigh" || value === "max" ? value : void 0;
3931
+ }
3932
+ function openAIRequestExecutionMetadata(params, provider) {
3933
+ const record = params && typeof params === "object" ? params : {};
3934
+ const reasoning = record.reasoning && typeof record.reasoning === "object" ? record.reasoning : void 0;
3935
+ const effort = normalizeExecutionReasoningEffort(
3936
+ record.reasoning_effort ?? reasoning?.effort ?? record.thinking_level
3937
+ );
3938
+ const mode = typeof reasoning?.type === "string" ? reasoning.type : typeof reasoning?.mode === "string" ? reasoning.mode : void 0;
3939
+ const rawBudget = reasoning?.budget_tokens ?? record.thinking_budget ?? record.thinking_budget_tokens;
3940
+ const budget = typeof rawBudget === "number" && Number.isInteger(rawBudget) && rawBudget >= 0 ? rawBudget : void 0;
3941
+ return {
3942
+ providerUsed: provider,
3943
+ ...effort ? { reasoningEffort: effort, reasoningEffortSource: "provider_request" } : {},
3944
+ ...mode ? { reasoningMode: mode } : {},
3945
+ ...budget !== void 0 ? { reasoningBudgetTokens: budget } : {}
87
3946
  };
88
3947
  }
89
3948
  function wrapStreamForUsageTap(source, finalize, ctx) {
@@ -185,9 +4044,27 @@ function isIteratorResult(value) {
185
4044
 
186
4045
  // src/adapters/openrouter.ts
187
4046
  function createOpenRouterAdapter(init) {
188
- return createOpenAIAdapter(init);
4047
+ return createOpenAIAdapter({ ...init, provider: "openrouter" });
4048
+ }
4049
+ function withMetering2(client, customer) {
4050
+ return withMetering(
4051
+ client,
4052
+ typeof customer === "string" ? { customerId: customer, provider: "openrouter" } : { ...customer, provider: "openrouter" }
4053
+ );
4054
+ }
4055
+ function wrapOpenAI2(client, usageTap, options = {}) {
4056
+ return wrapOpenAI(client, usageTap, {
4057
+ ...options,
4058
+ provider: "openrouter"
4059
+ });
4060
+ }
4061
+ function withSampling2(client, options = {}) {
4062
+ return withSampling(client, { ...options, provider: "openrouter" });
189
4063
  }
190
4064
 
191
4065
  exports.createOpenRouterAdapter = createOpenRouterAdapter;
4066
+ exports.withMetering = withMetering2;
4067
+ exports.withSampling = withSampling2;
4068
+ exports.wrapOpenAI = wrapOpenAI2;
192
4069
  //# sourceMappingURL=openrouter.cjs.map
193
4070
  //# sourceMappingURL=openrouter.cjs.map