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