@usagetap/sdk 1.2.0 → 1.3.1

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 (50) hide show
  1. package/README.md +200 -225
  2. package/dist/adapters/anthropic.cjs +1609 -5
  3. package/dist/adapters/anthropic.cjs.map +1 -1
  4. package/dist/adapters/anthropic.d.cts +30 -2
  5. package/dist/adapters/anthropic.d.ts +30 -2
  6. package/dist/adapters/anthropic.mjs +1608 -6
  7. package/dist/adapters/anthropic.mjs.map +1 -1
  8. package/dist/adapters/openai.cjs +1659 -5
  9. package/dist/adapters/openai.cjs.map +1 -1
  10. package/dist/adapters/openai.d.cts +37 -2
  11. package/dist/adapters/openai.d.ts +37 -2
  12. package/dist/adapters/openai.mjs +1658 -6
  13. package/dist/adapters/openai.mjs.map +1 -1
  14. package/dist/adapters/openrouter.cjs.map +1 -1
  15. package/dist/adapters/openrouter.d.cts +1 -1
  16. package/dist/adapters/openrouter.d.ts +1 -1
  17. package/dist/adapters/openrouter.mjs.map +1 -1
  18. package/dist/anthropic/index.cjs +1609 -5
  19. package/dist/anthropic/index.cjs.map +1 -1
  20. package/dist/anthropic/index.d.cts +2 -2
  21. package/dist/anthropic/index.d.ts +2 -2
  22. package/dist/anthropic/index.mjs +1608 -6
  23. package/dist/anthropic/index.mjs.map +1 -1
  24. package/dist/{client-EMXt9_fA.d.cts → client-BD8O2J8Z.d.cts} +30 -4
  25. package/dist/{client-EMXt9_fA.d.ts → client-BD8O2J8Z.d.ts} +30 -4
  26. package/dist/express/index.cjs +19 -0
  27. package/dist/express/index.cjs.map +1 -1
  28. package/dist/express/index.d.cts +1 -1
  29. package/dist/express/index.d.ts +1 -1
  30. package/dist/express/index.mjs +19 -0
  31. package/dist/express/index.mjs.map +1 -1
  32. package/dist/index.cjs +48 -19
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +3 -3
  35. package/dist/index.d.ts +3 -3
  36. package/dist/index.mjs +48 -20
  37. package/dist/index.mjs.map +1 -1
  38. package/dist/openai/index.cjs +1659 -5
  39. package/dist/openai/index.cjs.map +1 -1
  40. package/dist/openai/index.d.cts +2 -2
  41. package/dist/openai/index.d.ts +2 -2
  42. package/dist/openai/index.mjs +1658 -6
  43. package/dist/openai/index.mjs.map +1 -1
  44. package/dist/openrouter/index.cjs +3024 -0
  45. package/dist/openrouter/index.cjs.map +1 -0
  46. package/dist/openrouter/index.d.cts +4 -0
  47. package/dist/openrouter/index.d.ts +4 -0
  48. package/dist/openrouter/index.mjs +3019 -0
  49. package/dist/openrouter/index.mjs.map +1 -0
  50. package/package.json +102 -44
@@ -28,16 +28,1546 @@ var UsageTapError = class extends Error {
28
28
  };
29
29
  }
30
30
  };
31
+ function isUsageTapError(error) {
32
+ return error instanceof UsageTapError;
33
+ }
34
+
35
+ // src/idempotency.ts
36
+ function createIdempotencyKey() {
37
+ if (typeof globalThis.crypto?.randomUUID === "function") {
38
+ return globalThis.crypto.randomUUID();
39
+ }
40
+ const random = () => Math.random().toString(16).slice(2, 10);
41
+ return `${random()}-${random()}`;
42
+ }
43
+
44
+ // src/retry.ts
45
+ var DEFAULTS = {
46
+ maxAttempts: 3,
47
+ baseDelayMs: 250,
48
+ maxDelayMs: 5e3,
49
+ jitterRatio: 0.2
50
+ };
51
+ function resolveRetryOptions(base, override) {
52
+ const merged = { ...DEFAULTS, ...base, ...override };
53
+ return {
54
+ maxAttempts: Math.max(1, Math.floor(merged.maxAttempts)),
55
+ baseDelayMs: Math.max(0, merged.baseDelayMs),
56
+ maxDelayMs: Math.max(merged.baseDelayMs, merged.maxDelayMs),
57
+ jitterRatio: Math.min(Math.max(merged.jitterRatio, 0), 1)
58
+ };
59
+ }
60
+ async function sleep(delayMs, signal) {
61
+ if (delayMs <= 0) {
62
+ signal?.throwIfAborted?.();
63
+ return;
64
+ }
65
+ await new Promise((resolve, reject) => {
66
+ const timer = setTimeout(() => {
67
+ cleanup();
68
+ resolve();
69
+ }, delayMs);
70
+ const cleanup = () => {
71
+ clearTimeout(timer);
72
+ signal?.removeEventListener("abort", onAbort);
73
+ };
74
+ const onAbort = () => {
75
+ cleanup();
76
+ const abortError = new Error("Aborted");
77
+ abortError.name = "AbortError";
78
+ reject(abortError);
79
+ };
80
+ if (signal) {
81
+ if (signal.aborted) {
82
+ onAbort();
83
+ return;
84
+ }
85
+ signal.addEventListener("abort", onAbort, { once: true });
86
+ }
87
+ });
88
+ }
89
+ function computeDelay(attempt, options) {
90
+ const exp = options.baseDelayMs * Math.pow(2, attempt - 1);
91
+ const capped = Math.min(exp, options.maxDelayMs);
92
+ const jitter = capped * options.jitterRatio;
93
+ const min = capped - jitter;
94
+ const max = capped + jitter;
95
+ return Math.max(0, Math.random() * (max - min) + min);
96
+ }
97
+ async function runWithRetry(operation, options, shouldRetry, onSchedule, signal) {
98
+ let attempt = 0;
99
+ let lastError;
100
+ while (attempt < options.maxAttempts) {
101
+ attempt += 1;
102
+ signal?.throwIfAborted?.();
103
+ try {
104
+ return await operation(attempt);
105
+ } catch (error) {
106
+ lastError = error;
107
+ if (attempt >= options.maxAttempts || !shouldRetry(error)) {
108
+ throw error;
109
+ }
110
+ const delayMs = computeDelay(attempt, options);
111
+ onSchedule?.(attempt, delayMs, error);
112
+ await sleep(delayMs, signal);
113
+ }
114
+ }
115
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
116
+ }
31
117
 
32
118
  // src/prompt-compression.ts
119
+ var DEFAULT_PROMPT_COMPRESSION_MIN_CONTEXT_TOKENS = 1e3;
120
+ var DEFAULT_TTC_ENDPOINT = "https://api.thetokencompany.com/v1/compress";
121
+ var DEFAULT_TTC_MODEL = "bear-2";
122
+ var DEFAULT_TTC_AGGRESSIVENESS = 0.2;
123
+ var DEFAULT_USAGETAP_COMPRESSION_ENDPOINT = "https://compress.usagetap.com/v1/compress";
124
+ var DEFAULT_USAGETAP_MESSAGES_COMPRESSION_ENDPOINT = "https://compress.usagetap.com/v1/messages/compress";
125
+ var PROTECTED_TEXT_PATTERN = /<ttc_safe>[\s\S]*?<\/ttc_safe>|<usagetap_safe>[\s\S]*?<\/usagetap_safe>/g;
126
+ async function compressPrompt(options) {
127
+ const input = resolvePromptCompressionInput(options);
128
+ try {
129
+ if (options.provider === "usagetap") {
130
+ return await compressWithUsageTap(options);
131
+ }
132
+ if (options.provider === "thetokencompany" || options.tokenCompanyApiKey) {
133
+ return await compressWithTheTokenCompany(options);
134
+ }
135
+ if (options.provider === "toon") {
136
+ return compressPromptToon(input);
137
+ }
138
+ return compressPromptHeuristic(input);
139
+ } catch (error) {
140
+ if (options.failOpen === false) {
141
+ throw error;
142
+ }
143
+ return createPromptCompressionFallback(
144
+ input,
145
+ options.provider ?? (options.tokenCompanyApiKey ? "thetokencompany" : "heuristic"),
146
+ error
147
+ );
148
+ }
149
+ }
150
+ function compressPromptHeuristic(input) {
151
+ const original = stableStringifyInput(input);
152
+ const techniques = /* @__PURE__ */ new Set();
153
+ const compressedInput = compressValue(input, techniques, { allowToonString: false });
154
+ const compressed = stableStringifyInput(compressedInput);
155
+ const chosenInput = compressed.length <= original.length ? compressedInput : input;
156
+ const chosen = compressed.length <= original.length ? compressed : original;
157
+ if (!techniques.size) {
158
+ techniques.add("no-op");
159
+ }
160
+ return buildResult(
161
+ input,
162
+ chosenInput,
163
+ "heuristic",
164
+ original,
165
+ chosen,
166
+ Array.from(techniques)
167
+ );
168
+ }
169
+ function compressPromptToon(input) {
170
+ const original = stableStringifyInput(input);
171
+ const compressedInput = typeof input === "string" ? compressText(input, /* @__PURE__ */ new Set(), { allowToonString: true }) : encodeToon(input);
172
+ const compressed = stableStringifyInput(compressedInput);
173
+ return buildResult(input, compressedInput, "toon", original, compressed, [
174
+ "toon",
175
+ "json-minify"
176
+ ]);
177
+ }
178
+ async function compressPromptMessages(options) {
179
+ try {
180
+ return await compressMessagesWithUsageTap(options);
181
+ } catch (error) {
182
+ if (options.failOpen === false) {
183
+ throw error;
184
+ }
185
+ return createPromptCompressionFallback(
186
+ options.input,
187
+ options.provider ?? "usagetap",
188
+ error
189
+ );
190
+ }
191
+ }
192
+ async function compressWithTheTokenCompany(options) {
193
+ if (!options.tokenCompanyApiKey) {
194
+ throw new Error(
195
+ "tokenCompanyApiKey is required when provider is thetokencompany"
196
+ );
197
+ }
198
+ const fetchCandidate = options.fetchImpl ?? globalThis.fetch;
199
+ if (typeof fetchCandidate !== "function") {
200
+ throw new Error(
201
+ "A fetch implementation is required for The Token Company compression"
202
+ );
203
+ }
204
+ return compressWithCompatibleRemoteProvider({
205
+ options,
206
+ provider: "thetokencompany",
207
+ endpoint: options.tokenCompanyEndpoint ?? DEFAULT_TTC_ENDPOINT,
208
+ model: options.model ?? options.tokenCompanyModel ?? DEFAULT_TTC_MODEL,
209
+ aggressiveness: options.aggressiveness ?? options.tokenCompanyAggressiveness ?? DEFAULT_TTC_AGGRESSIVENESS,
210
+ apiKey: options.tokenCompanyApiKey,
211
+ appId: options.tokenCompanyAppId,
212
+ providerLabel: "The Token Company"
213
+ });
214
+ }
215
+ async function compressWithUsageTap(options) {
216
+ const fetchCandidate = options.fetchImpl ?? globalThis.fetch;
217
+ if (typeof fetchCandidate !== "function") {
218
+ throw new Error(
219
+ "A fetch implementation is required for UsageTap prompt compression"
220
+ );
221
+ }
222
+ return compressWithCompatibleRemoteProvider({
223
+ options,
224
+ provider: "usagetap",
225
+ endpoint: options.usageTapCompressionEndpoint ?? DEFAULT_USAGETAP_COMPRESSION_ENDPOINT,
226
+ model: options.model ?? options.usageTapCompressionModel ?? options.tokenCompanyModel ?? DEFAULT_TTC_MODEL,
227
+ aggressiveness: options.aggressiveness ?? options.usageTapCompressionAggressiveness ?? options.tokenCompanyAggressiveness ?? DEFAULT_TTC_AGGRESSIVENESS,
228
+ apiKey: options.usageTapCompressionApiKey,
229
+ appId: options.tokenCompanyAppId,
230
+ providerLabel: "UsageTap prompt compression"
231
+ });
232
+ }
233
+ async function compressMessagesWithUsageTap(options) {
234
+ const fetchCandidate = options.fetchImpl ?? globalThis.fetch;
235
+ if (typeof fetchCandidate !== "function") {
236
+ throw new Error(
237
+ "A fetch implementation is required for UsageTap prompt message compression"
238
+ );
239
+ }
240
+ const aggressiveness = options.aggressiveness ?? options.usageTapCompressionAggressiveness ?? DEFAULT_TTC_AGGRESSIVENESS;
241
+ validateAggressiveness(
242
+ aggressiveness,
243
+ "UsageTap prompt message compression"
244
+ );
245
+ const original = stableStringifyInput(options.input);
246
+ const headers = {
247
+ "content-type": "application/json"
248
+ };
249
+ if (options.usageTapCompressionApiKey) {
250
+ headers.authorization = `Bearer ${options.usageTapCompressionApiKey}`;
251
+ }
252
+ const response = await fetchCandidate(
253
+ options.usageTapCompressionMessagesEndpoint ?? DEFAULT_USAGETAP_MESSAGES_COMPRESSION_ENDPOINT,
254
+ {
255
+ method: "POST",
256
+ headers,
257
+ body: JSON.stringify({
258
+ ...cloneInputRecord(options.input),
259
+ compression_settings: { aggressiveness }
260
+ }),
261
+ signal: options.signal
262
+ }
263
+ );
264
+ if (!response.ok) {
265
+ throw new Error(
266
+ `UsageTap prompt message compression failed with HTTP ${response.status}`
267
+ );
268
+ }
269
+ const payload = await response.json();
270
+ const compressedInput = payload.compressed_request ?? payload.compressedInput ?? payload.compressed ?? (payload.messages !== void 0 ? { ...cloneInputRecord(options.input), messages: payload.messages } : void 0);
271
+ if (compressedInput === void 0) {
272
+ throw new Error(
273
+ "UsageTap prompt message compression response did not include compressed content"
274
+ );
275
+ }
276
+ const compressed = stableStringifyInput(compressedInput);
277
+ const tokenCounts = normalizeCompatibleTokenCounts(payload);
278
+ return buildResult(
279
+ options.input,
280
+ compressedInput,
281
+ "usagetap",
282
+ original,
283
+ compressed,
284
+ ["usagetap", "messages-endpoint"],
285
+ tokenCounts
286
+ );
287
+ }
288
+ async function compressWithCompatibleRemoteProvider(args) {
289
+ const { options, provider, endpoint, model, aggressiveness, apiKey, appId, providerLabel } = args;
290
+ const fetchCandidate = options.fetchImpl ?? globalThis.fetch;
291
+ const sourceInput = resolvePromptCompressionInput(options);
292
+ const original = stableStringifyInput(sourceInput);
293
+ const heuristic = compressPromptHeuristic(sourceInput);
294
+ const input = typeof heuristic.compressedInput === "string" ? heuristic.compressedInput : stableStringifyInput(heuristic.compressedInput);
295
+ if (!isValidAggressiveness(aggressiveness)) {
296
+ throw new Error(`${providerLabel} aggressiveness must be between 0.0 and 1.0`);
297
+ }
298
+ const headers = {
299
+ "content-type": "application/json"
300
+ };
301
+ if (apiKey) {
302
+ headers.authorization = `Bearer ${apiKey}`;
303
+ }
304
+ const response = await fetchCandidate(
305
+ endpoint,
306
+ {
307
+ method: "POST",
308
+ headers,
309
+ body: JSON.stringify({
310
+ model,
311
+ input,
312
+ ...provider === "usagetap" ? { text: input } : {},
313
+ compression_settings: { aggressiveness },
314
+ ...appId ? { app_id: appId } : {}
315
+ }),
316
+ signal: options.signal
317
+ }
318
+ );
319
+ if (!response.ok) {
320
+ throw new Error(
321
+ `${providerLabel} failed with HTTP ${response.status}`
322
+ );
323
+ }
324
+ const payload = await response.json();
325
+ const tokenCompanyResult = normalizeTheTokenCompanyCompressResponse(payload);
326
+ const compressedInput = payload.compressedInput ?? payload.compressed ?? tokenCompanyResult?.output ?? payload.output ?? payload.text;
327
+ if (compressedInput === void 0) {
328
+ throw new Error(`${providerLabel} response did not include compressed content`);
329
+ }
330
+ const compressed = stableStringifyInput(compressedInput);
331
+ const tokenCounts = tokenCompanyResult ? {
332
+ originalTokens: tokenCompanyResult.input_tokens,
333
+ compressedTokens: tokenCompanyResult.output_tokens,
334
+ savedTokens: tokenCompanyResult.tokens_saved
335
+ } : void 0;
336
+ return buildResult(
337
+ sourceInput,
338
+ compressedInput,
339
+ provider,
340
+ original,
341
+ compressed,
342
+ [...heuristic.techniques, provider],
343
+ tokenCounts
344
+ );
345
+ }
346
+ function resolvePromptCompressionInput(options) {
347
+ if (options.input !== void 0) {
348
+ return options.input;
349
+ }
350
+ if (options.text !== void 0) {
351
+ return options.text;
352
+ }
353
+ throw new Error("Prompt compression requires input or text");
354
+ }
355
+ function validateAggressiveness(value, label) {
356
+ if (typeof value === "number") {
357
+ if (!isValidAggressiveness(value)) {
358
+ throw new Error(`${label} aggressiveness must be between 0.0 and 1.0`);
359
+ }
360
+ return;
361
+ }
362
+ for (const aggressiveness of Object.values(value)) {
363
+ if (aggressiveness !== void 0 && !isValidAggressiveness(aggressiveness)) {
364
+ throw new Error(`${label} aggressiveness must be between 0.0 and 1.0`);
365
+ }
366
+ }
367
+ }
368
+ function isValidAggressiveness(value) {
369
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
370
+ }
371
+ function cloneInputRecord(input) {
372
+ return input && typeof input === "object" && !Array.isArray(input) ? { ...input } : { input };
373
+ }
374
+ function normalizeCompatibleTokenCounts(data) {
375
+ const inputTokens = typeof data.input_tokens === "number" ? data.input_tokens : data.original_input_tokens;
376
+ const outputTokens = data.output_tokens;
377
+ if (typeof inputTokens !== "number" || typeof outputTokens !== "number") {
378
+ return void 0;
379
+ }
380
+ return {
381
+ originalTokens: inputTokens,
382
+ compressedTokens: outputTokens,
383
+ savedTokens: typeof data.tokens_saved === "number" ? data.tokens_saved : inputTokens - outputTokens
384
+ };
385
+ }
386
+ function normalizeTheTokenCompanyCompressResponse(data) {
387
+ if (typeof data.output !== "string" || typeof data.output_tokens !== "number") {
388
+ return void 0;
389
+ }
390
+ const inputTokens = typeof data.input_tokens === "number" ? data.input_tokens : data.original_input_tokens;
391
+ if (typeof inputTokens !== "number") {
392
+ return void 0;
393
+ }
394
+ const tokensSaved = typeof data.tokens_saved === "number" ? data.tokens_saved : inputTokens - data.output_tokens;
395
+ const compressionRatio = typeof data.compression_ratio === "number" ? data.compression_ratio : data.output_tokens === 0 ? 0 : inputTokens / data.output_tokens;
396
+ return {
397
+ output: data.output,
398
+ output_tokens: data.output_tokens,
399
+ input_tokens: inputTokens,
400
+ tokens_saved: tokensSaved,
401
+ compression_ratio: compressionRatio
402
+ };
403
+ }
404
+ function createPromptCompressionFallback(input, provider = "heuristic", error) {
405
+ const original = stableStringifyInput(input);
406
+ const techniques = ["fallback-original"];
407
+ if (error) {
408
+ techniques.push("compression-error");
409
+ }
410
+ return buildResult(input, input, provider, original, original, techniques);
411
+ }
412
+ function buildResult(input, compressedInput, provider, original, compressed, techniques, tokenCounts) {
413
+ const originalCharacters = original.length;
414
+ const compressedCharacters = compressed.length;
415
+ const savedCharacters = Math.max(
416
+ 0,
417
+ originalCharacters - compressedCharacters
418
+ );
419
+ const originalTokens = tokenCounts?.originalTokens ?? estimatePromptTokens(original);
420
+ const compressedTokens = tokenCounts?.compressedTokens ?? estimatePromptTokens(compressed);
421
+ const savedTokens = Math.max(
422
+ 0,
423
+ tokenCounts?.savedTokens ?? originalTokens - compressedTokens
424
+ );
425
+ return {
426
+ input,
427
+ compressedInput,
428
+ provider,
429
+ originalCharacters,
430
+ compressedCharacters,
431
+ savedCharacters,
432
+ originalTokens,
433
+ compressedTokens,
434
+ savedTokens,
435
+ tokenSavingsRatio: originalTokens > 0 ? savedTokens / originalTokens : 0,
436
+ savingsRatio: originalCharacters > 0 ? savedCharacters / originalCharacters : 0,
437
+ techniques
438
+ };
439
+ }
33
440
  function estimatePromptTokens(input) {
34
441
  const text = typeof input === "string" ? input : stableStringifyInput(input);
35
442
  return text.match(/[\p{L}\p{N}]+|[^\s]/gu)?.length ?? 0;
36
443
  }
444
+ function compressValue(value, techniques, options) {
445
+ if (typeof value === "string") return compressText(value, techniques, options);
446
+ if (Array.isArray(value)) {
447
+ techniques.add("json-minify");
448
+ return value.map((item) => compressValue(item, techniques, options));
449
+ }
450
+ if (value && typeof value === "object") {
451
+ techniques.add("json-minify");
452
+ return Object.keys(value).reduce((acc, key) => {
453
+ const child = value[key];
454
+ if (child !== void 0) {
455
+ acc[key] = compressValue(child, techniques, options);
456
+ }
457
+ return acc;
458
+ }, {});
459
+ }
460
+ return value;
461
+ }
462
+ function compressText(value, techniques, options) {
463
+ const protectedSpans = [];
464
+ const text = value.replace(PROTECTED_TEXT_PATTERN, (match) => {
465
+ const placeholder = `__USAGETAP_PROTECTED_${protectedSpans.length}__`;
466
+ protectedSpans.push(match);
467
+ techniques.add("protected-text");
468
+ return placeholder;
469
+ });
470
+ const compressed = compressTextWithoutProtection(text, techniques, options);
471
+ return protectedSpans.reduce(
472
+ (output, span, index) => output.replace(`__USAGETAP_PROTECTED_${index}__`, span),
473
+ compressed
474
+ );
475
+ }
476
+ function compressTextWithoutProtection(value, techniques, options) {
477
+ const fencePattern = /```([\w-]+)?\n([\s\S]*?)```/g;
478
+ const parts = [];
479
+ let cursor = 0;
480
+ let match;
481
+ while ((match = fencePattern.exec(value)) !== null) {
482
+ const before = value.slice(cursor, match.index);
483
+ const compressedBefore = compressPlainTextAndEmbeddedJson(
484
+ before,
485
+ techniques,
486
+ options
487
+ );
488
+ if (compressedBefore) parts.push(compressedBefore);
489
+ const lang = match[1]?.toLowerCase();
490
+ const code = cleanCodeBlock(match[2] ?? "");
491
+ const compressedCode = lang === "json" ? compressJsonText(code, techniques, options) : void 0;
492
+ if (compressedCode?.format === "toon") {
493
+ parts.push(`\`\`\`toon
494
+ ${compressedCode.text}
495
+ \`\`\``);
496
+ } else if (compressedCode?.format === "json") {
497
+ parts.push(`\`\`\`json
498
+ ${compressedCode.text}
499
+ \`\`\``);
500
+ } else {
501
+ if (code !== match[2]) {
502
+ techniques.add("code-whitespace");
503
+ }
504
+ parts.push(lang ? `\`\`\`${lang}
505
+ ${code}
506
+ \`\`\`` : `\`\`\`
507
+ ${code}
508
+ \`\`\``);
509
+ }
510
+ cursor = match.index + match[0].length;
511
+ }
512
+ const after = compressPlainTextAndEmbeddedJson(value.slice(cursor), techniques, options);
513
+ if (after) parts.push(after);
514
+ return parts.join("\n").trim();
515
+ }
516
+ function compressPlainText(value, techniques) {
517
+ const compressed = value.split("\n").map((line) => line.trim()).filter((line) => line).join("\n").replace(/[ \t]{2,}/g, " ").trim();
518
+ if (compressed !== value.trim()) {
519
+ techniques.add("text-whitespace");
520
+ }
521
+ return compressed;
522
+ }
523
+ function compressPlainTextAndEmbeddedJson(value, techniques, options) {
524
+ const normalized = compressPlainText(value, techniques);
525
+ return compressEmbeddedJson(normalized, techniques, options);
526
+ }
527
+ function cleanCodeBlock(code) {
528
+ const lines = code.replace(/\r\n/g, "\n").split("\n");
529
+ while (lines.length && lines[0].trim() === "") lines.shift();
530
+ while (lines.length && lines[lines.length - 1].trim() === "") lines.pop();
531
+ const commonIndent = lines.filter((line) => line.trim()).reduce((min, line) => {
532
+ const indent = /^[ \t]*/.exec(line)?.[0].length ?? 0;
533
+ return min === void 0 ? indent : Math.min(min, indent);
534
+ }, void 0);
535
+ return lines.map((line) => commonIndent ? line.slice(commonIndent) : line).join("\n").replace(/[ \t]+$/gm, "");
536
+ }
37
537
  function stableStringifyInput(input) {
38
538
  if (typeof input === "string") return input;
39
539
  return JSON.stringify(input) ?? String(input);
40
540
  }
541
+ function compressJsonText(text, techniques, options) {
542
+ const parsed = safeParseJson(text);
543
+ if (parsed === void 0) {
544
+ return void 0;
545
+ }
546
+ const compactJson = JSON.stringify(parsed);
547
+ const candidates = [
548
+ { format: "json", text: compactJson }
549
+ ];
550
+ if (options.allowToonString || shouldUseToonForJson(parsed)) {
551
+ candidates.push({ format: "toon", text: encodeToon(parsed) });
552
+ }
553
+ const originalLength = text.trim().length;
554
+ const best = candidates.reduce(
555
+ (winner, candidate) => candidate.text.length < winner.text.length ? candidate : winner
556
+ );
557
+ if (best.text.length >= originalLength) {
558
+ return void 0;
559
+ }
560
+ techniques.add(best.format === "toon" ? "embedded-json-toon" : "embedded-json-minify");
561
+ return best;
562
+ }
563
+ function compressEmbeddedJson(text, techniques, options) {
564
+ let result = "";
565
+ let cursor = 0;
566
+ while (cursor < text.length) {
567
+ const start = findNextJsonStart(text, cursor);
568
+ if (start < 0) {
569
+ result += text.slice(cursor);
570
+ break;
571
+ }
572
+ result += text.slice(cursor, start);
573
+ const span = findBalancedJsonSpan(text, start);
574
+ if (!span) {
575
+ result += text[start];
576
+ cursor = start + 1;
577
+ continue;
578
+ }
579
+ const candidate = compressJsonText(span.text, techniques, options);
580
+ if (candidate) {
581
+ result += candidate.text;
582
+ } else {
583
+ result += span.text;
584
+ }
585
+ cursor = span.end;
586
+ }
587
+ return result;
588
+ }
589
+ function findNextJsonStart(text, from) {
590
+ const objectStart = text.indexOf("{", from);
591
+ const arrayStart = text.indexOf("[", from);
592
+ if (objectStart < 0) return arrayStart;
593
+ if (arrayStart < 0) return objectStart;
594
+ return Math.min(objectStart, arrayStart);
595
+ }
596
+ function findBalancedJsonSpan(text, start) {
597
+ const opener = text[start];
598
+ const closer = opener === "{" ? "}" : opener === "[" ? "]" : void 0;
599
+ if (!closer) return void 0;
600
+ const stack = [closer];
601
+ let inString = false;
602
+ let escaped = false;
603
+ for (let index = start + 1; index < text.length; index += 1) {
604
+ const char = text[index];
605
+ if (inString) {
606
+ if (escaped) {
607
+ escaped = false;
608
+ } else if (char === "\\") {
609
+ escaped = true;
610
+ } else if (char === '"') {
611
+ inString = false;
612
+ }
613
+ continue;
614
+ }
615
+ if (char === '"') {
616
+ inString = true;
617
+ continue;
618
+ }
619
+ if (char === "{" || char === "[") {
620
+ stack.push(char === "{" ? "}" : "]");
621
+ continue;
622
+ }
623
+ if (char === stack[stack.length - 1]) {
624
+ stack.pop();
625
+ if (!stack.length) {
626
+ const end = index + 1;
627
+ return { text: text.slice(start, end), end };
628
+ }
629
+ }
630
+ }
631
+ return void 0;
632
+ }
633
+ function safeParseJson(text) {
634
+ try {
635
+ return JSON.parse(text);
636
+ } catch {
637
+ return void 0;
638
+ }
639
+ }
640
+ function shouldUseToonForJson(value) {
641
+ if (Array.isArray(value)) {
642
+ return isUniformObjectArray(value) || value.some(shouldUseToonForJson);
643
+ }
644
+ if (isPlainObject(value)) {
645
+ return Object.values(value).some(shouldUseToonForJson);
646
+ }
647
+ return false;
648
+ }
649
+ function encodeToon(value, indent = 0) {
650
+ if (isPrimitive(value)) {
651
+ return scalarToToon(value);
652
+ }
653
+ if (Array.isArray(value)) {
654
+ return encodeArrayToon(value, indent);
655
+ }
656
+ if (isPlainObject(value)) {
657
+ const lines = [];
658
+ for (const [key, child] of Object.entries(value)) {
659
+ lines.push(...encodePropertyToon(key, child, indent));
660
+ }
661
+ return lines.join("\n");
662
+ }
663
+ return scalarToToon(String(value));
664
+ }
665
+ function encodePropertyToon(key, value, indent) {
666
+ const prefix = " ".repeat(indent);
667
+ const toonKey = keyToToon(key);
668
+ if (isPrimitive(value)) {
669
+ return [`${prefix}${toonKey}: ${scalarToToon(value)}`];
670
+ }
671
+ if (Array.isArray(value)) {
672
+ if (value.every(isPrimitive)) {
673
+ return [`${prefix}${toonKey}[${value.length}]: ${value.map(scalarToToon).join(",")}`];
674
+ }
675
+ if (isUniformObjectArray(value)) {
676
+ const fields = Object.keys(value[0]);
677
+ const header = `${prefix}${toonKey}[${value.length}]{${fields.map(keyToToon).join(",")}}:`;
678
+ const rows = value.map(
679
+ (item) => `${" ".repeat(indent + 2)}${fields.map(
680
+ (field) => scalarToToon(item[field])
681
+ ).join(",")}`
682
+ );
683
+ return [header, ...rows];
684
+ }
685
+ return [
686
+ `${prefix}${toonKey}[${value.length}]:`,
687
+ ...value.flatMap((item, index) => {
688
+ if (isPrimitive(item)) {
689
+ return [`${" ".repeat(indent + 2)}- ${scalarToToon(item)}`];
690
+ }
691
+ return [
692
+ `${" ".repeat(indent + 2)}- item${index}:`,
693
+ ...encodeToon(item, indent + 4).split("\n")
694
+ ];
695
+ })
696
+ ];
697
+ }
698
+ return [`${prefix}${toonKey}:`, ...encodeToon(value, indent + 2).split("\n")];
699
+ }
700
+ function encodeArrayToon(value, indent) {
701
+ if (value.every(isPrimitive)) {
702
+ return `[${value.length}]: ${value.map(scalarToToon).join(",")}`;
703
+ }
704
+ if (isUniformObjectArray(value)) {
705
+ const fields = Object.keys(value[0]);
706
+ return [
707
+ `[${value.length}]{${fields.map(keyToToon).join(",")}}:`,
708
+ ...value.map(
709
+ (item) => `${" ".repeat(indent + 2)}${fields.map(
710
+ (field) => scalarToToon(item[field])
711
+ ).join(",")}`
712
+ )
713
+ ].join("\n");
714
+ }
715
+ return value.flatMap((item, index) => [
716
+ `${" ".repeat(indent)}- item${index}:`,
717
+ ...encodeToon(item, indent + 2).split("\n")
718
+ ]).join("\n");
719
+ }
720
+ function isUniformObjectArray(value) {
721
+ if (!value.length || !value.every(isPlainObject)) {
722
+ return false;
723
+ }
724
+ const fields = Object.keys(value[0]);
725
+ if (!fields.length) {
726
+ return false;
727
+ }
728
+ return value.every((item) => {
729
+ const record = item;
730
+ const itemFields = Object.keys(record);
731
+ return itemFields.length === fields.length && fields.every((field) => itemFields.includes(field) && isPrimitive(record[field]));
732
+ });
733
+ }
734
+ function isPlainObject(value) {
735
+ return typeof value === "object" && value !== null && !Array.isArray(value);
736
+ }
737
+ function isPrimitive(value) {
738
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
739
+ }
740
+ function keyToToon(key) {
741
+ return /^[A-Za-z_][A-Za-z0-9_-]*$/.test(key) ? key : JSON.stringify(key);
742
+ }
743
+ function scalarToToon(value) {
744
+ if (value === null) return "null";
745
+ if (typeof value === "number" || typeof value === "boolean") {
746
+ return String(value);
747
+ }
748
+ const text = String(value);
749
+ if (text && !/^(true|false|null|-?\d+(?:\.\d+)?)$/i.test(text) && /^[A-Za-z0-9_./@-]+(?: [A-Za-z0-9_./@-]+)*$/.test(text)) {
750
+ return text;
751
+ }
752
+ return JSON.stringify(text);
753
+ }
754
+
755
+ // src/client.ts
756
+ var CALL_BEGIN_PATH = "call_begin";
757
+ var CALL_END_PATH = "call_end";
758
+ var COMPRESS_PROMPT_PATH = "compress_prompt";
759
+ var CHECK_USAGE_PATH = "customers/{customerId}/usage";
760
+ var CREATE_CUSTOMER_PATH = "customers";
761
+ var CHANGE_PLAN_PATH = "customers/{customerId}/change_plan";
762
+ var INCREMENT_CUSTOM_METER_PATH = "custom_meter";
763
+ var AUTH_HEADER = "authorization";
764
+ var API_KEY_HEADER = "x-api-key";
765
+ var CORRELATION_HEADER = "x-usage-correlation-id";
766
+ var IDEMPOTENCY_HEADER = "idempotency-key";
767
+ var SDK_HEADER = "x-usage-sdk";
768
+ var USER_AGENT = "UsageTapClient";
769
+ var CANONICAL_MEDIA_TYPE = "application/vnd.usagetap.v1+json";
770
+ var DEFAULT_BASE_URL = "https://api.usagetap.com";
771
+ var SDK_VERSION = "1.3.1" ;
772
+ var HAS_WINDOW = typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
773
+ var UsageTapClient = class {
774
+ apiKey;
775
+ baseUrl;
776
+ fetchImpl;
777
+ defaultFeature;
778
+ defaultTags;
779
+ defaultHeaders;
780
+ retryDefaults;
781
+ idempotencyGenerator;
782
+ logFn;
783
+ metricFn;
784
+ authHeader;
785
+ autoIdempotency;
786
+ tokenCompanyApiKey;
787
+ tokenCompanyEndpoint;
788
+ model;
789
+ tokenCompanyModel;
790
+ aggressiveness;
791
+ tokenCompanyAggressiveness;
792
+ tokenCompanyAppId;
793
+ usageTapCompressionApiKey;
794
+ usageTapCompressionEndpoint;
795
+ usageTapCompressionMessagesEndpoint;
796
+ usageTapCompressionModel;
797
+ usageTapCompressionAggressiveness;
798
+ constructor(options = {}) {
799
+ const apiKey = options.apiKey?.trim() || readEnvironmentVariable("USAGETAP_API_KEY");
800
+ const baseUrl = options.baseUrl?.trim() || readEnvironmentVariable("USAGETAP_BASE_URL") || DEFAULT_BASE_URL;
801
+ if (!apiKey) {
802
+ throw new UsageTapError(
803
+ "USAGETAP_BAD_REQUEST",
804
+ "UsageTapClient requires an apiKey or the USAGETAP_API_KEY environment variable"
805
+ );
806
+ }
807
+ if (HAS_WINDOW && !options.allowBrowser) {
808
+ throw new UsageTapError(
809
+ "USAGETAP_BROWSER_RUNTIME",
810
+ "UsageTapClient is designed for server-side environments. Pass allowBrowser=true only for testing."
811
+ );
812
+ }
813
+ const fetchCandidate = options.fetchImpl ?? globalThis.fetch;
814
+ if (typeof fetchCandidate !== "function") {
815
+ throw new UsageTapError(
816
+ "USAGETAP_NETWORK_ERROR",
817
+ "A global fetch implementation was not found. Pass fetchImpl in UsageTapClientOptions."
818
+ );
819
+ }
820
+ const normalizedBaseUrl = normalizeBaseUrl(baseUrl);
821
+ this.baseUrl = new URL(normalizedBaseUrl);
822
+ this.apiKey = apiKey;
823
+ this.fetchImpl = wrapFetchImplementation(fetchCandidate, !options.fetchImpl);
824
+ this.defaultFeature = options.defaultFeature;
825
+ this.defaultTags = options.defaultTags?.length ? dedupeStrings(options.defaultTags) : void 0;
826
+ this.defaultHeaders = options.headers ? normalizeHeaderDictionary(options.headers) : {};
827
+ this.retryDefaults = resolveRetryOptions(options.retries);
828
+ this.idempotencyGenerator = options.idempotencyGenerator ?? createIdempotencyKey;
829
+ this.logFn = options.onLog;
830
+ this.metricFn = options.onUsageMetric;
831
+ this.authHeader = options.useApiKeyHeader ? API_KEY_HEADER : AUTH_HEADER;
832
+ this.autoIdempotency = options.autoIdempotency ?? true;
833
+ this.tokenCompanyApiKey = options.tokenCompanyApiKey;
834
+ this.tokenCompanyEndpoint = options.tokenCompanyEndpoint;
835
+ this.model = options.model;
836
+ this.tokenCompanyModel = options.tokenCompanyModel;
837
+ this.aggressiveness = options.aggressiveness;
838
+ this.tokenCompanyAggressiveness = options.tokenCompanyAggressiveness;
839
+ this.tokenCompanyAppId = options.tokenCompanyAppId;
840
+ this.usageTapCompressionApiKey = options.usageTapCompressionApiKey ?? apiKey;
841
+ this.usageTapCompressionEndpoint = options.usageTapCompressionEndpoint;
842
+ this.usageTapCompressionMessagesEndpoint = options.usageTapCompressionMessagesEndpoint;
843
+ this.usageTapCompressionModel = options.usageTapCompressionModel;
844
+ this.usageTapCompressionAggressiveness = options.usageTapCompressionAggressiveness;
845
+ }
846
+ async beginCall(request, options = {}) {
847
+ const idempotencyKey = request.idempotencyKey ?? request.idempotency ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
848
+ const payload = {
849
+ ...request,
850
+ feature: request.feature ?? this.defaultFeature,
851
+ tags: this.mergeTags(request.tags)
852
+ };
853
+ if (idempotencyKey) {
854
+ payload.idempotencyKey = idempotencyKey;
855
+ payload.idempotency = idempotencyKey;
856
+ }
857
+ const response = await this.request(
858
+ CALL_BEGIN_PATH,
859
+ payload,
860
+ {
861
+ ...options,
862
+ idempotencyKey
863
+ }
864
+ );
865
+ return response;
866
+ }
867
+ async promptCompress(request, options = {}) {
868
+ if (!request?.callId) {
869
+ throw new UsageTapError(
870
+ "USAGETAP_BAD_REQUEST",
871
+ "promptCompress requires callId"
872
+ );
873
+ }
874
+ const requestInput = request.input ?? request.text;
875
+ if (requestInput === void 0) {
876
+ throw new UsageTapError(
877
+ "USAGETAP_BAD_REQUEST",
878
+ "promptCompress requires input or text"
879
+ );
880
+ }
881
+ const result = await this.compressPromptInput(requestInput, {
882
+ provider: request.provider,
883
+ model: request.model,
884
+ tokenCompanyModel: request.tokenCompanyModel,
885
+ aggressiveness: request.aggressiveness,
886
+ tokenCompanyAggressiveness: request.tokenCompanyAggressiveness,
887
+ tokenCompanyAppId: request.tokenCompanyAppId,
888
+ usageTapCompressionModel: request.usageTapCompressionModel,
889
+ usageTapCompressionAggressiveness: request.usageTapCompressionAggressiveness,
890
+ signal: options.signal
891
+ });
892
+ try {
893
+ await this.recordPromptCompression(
894
+ {
895
+ callId: request.callId,
896
+ promptCompression: this.toPromptCompressionTelemetry(result)
897
+ },
898
+ options
899
+ );
900
+ return { ...result, callId: request.callId };
901
+ } catch (error) {
902
+ return {
903
+ ...createPromptCompressionFallback(
904
+ requestInput,
905
+ request.provider ?? result.provider,
906
+ error
907
+ ),
908
+ callId: request.callId
909
+ };
910
+ }
911
+ }
912
+ async compressPromptInput(input, options = {}) {
913
+ return compressPrompt({
914
+ input,
915
+ provider: options.provider,
916
+ tokenCompanyApiKey: this.tokenCompanyApiKey,
917
+ tokenCompanyEndpoint: this.tokenCompanyEndpoint,
918
+ model: options.model ?? this.model,
919
+ tokenCompanyModel: options.tokenCompanyModel ?? this.tokenCompanyModel,
920
+ aggressiveness: options.aggressiveness ?? this.aggressiveness,
921
+ tokenCompanyAggressiveness: options.tokenCompanyAggressiveness ?? this.tokenCompanyAggressiveness,
922
+ tokenCompanyAppId: options.tokenCompanyAppId ?? this.tokenCompanyAppId,
923
+ usageTapCompressionApiKey: this.usageTapCompressionApiKey,
924
+ usageTapCompressionEndpoint: this.usageTapCompressionEndpoint,
925
+ usageTapCompressionModel: options.usageTapCompressionModel ?? this.usageTapCompressionModel,
926
+ usageTapCompressionAggressiveness: options.usageTapCompressionAggressiveness ?? this.usageTapCompressionAggressiveness,
927
+ fetchImpl: this.fetchImpl,
928
+ signal: options.signal,
929
+ failOpen: options.failOpen
930
+ });
931
+ }
932
+ /**
933
+ * Compress text with UsageTap's hosted compression service.
934
+ *
935
+ * This is the short, standalone path. It does not create a metered call and
936
+ * fails open to the original text unless failOpen is explicitly disabled.
937
+ */
938
+ async compress(text, options = {}) {
939
+ if (typeof text !== "string") {
940
+ throw new UsageTapError(
941
+ "USAGETAP_BAD_REQUEST",
942
+ "compress requires text"
943
+ );
944
+ }
945
+ const result = await this.compressPromptInput(text, {
946
+ ...options,
947
+ provider: "usagetap"
948
+ });
949
+ const output = typeof result.compressedInput === "string" ? result.compressedInput : text;
950
+ return {
951
+ ...result,
952
+ compressedInput: output,
953
+ output
954
+ };
955
+ }
956
+ async compressPromptMessages(input, options = {}) {
957
+ return compressPromptMessages({
958
+ input,
959
+ provider: options.provider ?? "usagetap",
960
+ usageTapCompressionApiKey: this.usageTapCompressionApiKey,
961
+ usageTapCompressionMessagesEndpoint: this.usageTapCompressionMessagesEndpoint,
962
+ aggressiveness: options.aggressiveness ?? this.aggressiveness,
963
+ usageTapCompressionAggressiveness: options.usageTapCompressionAggressiveness ?? this.usageTapCompressionAggressiveness,
964
+ fetchImpl: this.fetchImpl,
965
+ signal: options.signal,
966
+ failOpen: options.failOpen
967
+ });
968
+ }
969
+ async recordPromptCompression(request, options = {}) {
970
+ if (!request?.callId) {
971
+ throw new UsageTapError(
972
+ "USAGETAP_BAD_REQUEST",
973
+ "recordPromptCompression requires callId"
974
+ );
975
+ }
976
+ return this.request(
977
+ COMPRESS_PROMPT_PATH,
978
+ {
979
+ callId: request.callId,
980
+ promptCompression: request.promptCompression
981
+ },
982
+ options
983
+ );
984
+ }
985
+ async endCall(request, options = {}) {
986
+ if (!request?.callId) {
987
+ throw new UsageTapError(
988
+ "USAGETAP_BAD_REQUEST",
989
+ "endCall requires callId"
990
+ );
991
+ }
992
+ const { customerId, feature, tags, ...apiPayload } = request;
993
+ const response = await this.request(
994
+ CALL_END_PATH,
995
+ apiPayload,
996
+ options
997
+ );
998
+ this.emitUsageMetric({
999
+ type: "call_end",
1000
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1001
+ customerId: customerId ?? "unknown",
1002
+ callId: request.callId,
1003
+ feature: feature ?? this.defaultFeature,
1004
+ tags: tags ?? this.defaultTags,
1005
+ modelUsed: request.modelUsed,
1006
+ metrics: {
1007
+ inputTokens: request.inputTokens,
1008
+ responseTokens: request.responseTokens,
1009
+ cachedInputTokens: request.cachedInputTokens,
1010
+ reasoningTokens: request.reasoningTokens,
1011
+ searches: request.searches,
1012
+ audioSeconds: request.audioSeconds,
1013
+ costUsd: response.data.costUSD
1014
+ },
1015
+ correlationId: response.correlationId
1016
+ });
1017
+ return response;
1018
+ }
1019
+ async checkUsage(request, options = {}) {
1020
+ if (!request?.customerId) {
1021
+ throw new UsageTapError(
1022
+ "USAGETAP_BAD_REQUEST",
1023
+ "checkUsage requires customerId"
1024
+ );
1025
+ }
1026
+ const path = CHECK_USAGE_PATH.replace(
1027
+ "{customerId}",
1028
+ encodeURIComponent(request.customerId)
1029
+ );
1030
+ const response = await this.requestGet(
1031
+ path,
1032
+ options
1033
+ );
1034
+ return response;
1035
+ }
1036
+ async createCustomer(request, options = {}) {
1037
+ if (!request?.customerId) {
1038
+ throw new UsageTapError(
1039
+ "USAGETAP_BAD_REQUEST",
1040
+ "createCustomer requires customerId"
1041
+ );
1042
+ }
1043
+ const idempotencyKey = options.idempotencyKey ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1044
+ const response = await this.request(
1045
+ CREATE_CUSTOMER_PATH,
1046
+ { ...request },
1047
+ {
1048
+ ...options,
1049
+ idempotencyKey
1050
+ }
1051
+ );
1052
+ return response;
1053
+ }
1054
+ async changePlan(request, options = {}) {
1055
+ if (!request?.customerId) {
1056
+ throw new UsageTapError(
1057
+ "USAGETAP_BAD_REQUEST",
1058
+ "changePlan requires customerId"
1059
+ );
1060
+ }
1061
+ if (!request?.planId) {
1062
+ throw new UsageTapError(
1063
+ "USAGETAP_BAD_REQUEST",
1064
+ "changePlan requires planId"
1065
+ );
1066
+ }
1067
+ const path = CHANGE_PLAN_PATH.replace(
1068
+ "{customerId}",
1069
+ encodeURIComponent(request.customerId)
1070
+ );
1071
+ const idempotencyKey = options.idempotencyKey ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1072
+ const payload = {
1073
+ planId: request.planId,
1074
+ strategy: request.strategy ?? "IMMEDIATE_RESET"
1075
+ };
1076
+ const response = await this.request(
1077
+ path,
1078
+ payload,
1079
+ {
1080
+ ...options,
1081
+ idempotencyKey
1082
+ }
1083
+ );
1084
+ return response;
1085
+ }
1086
+ async incrementCustomMeter(request, options = {}) {
1087
+ if (!request?.customerId) {
1088
+ throw new UsageTapError(
1089
+ "USAGETAP_BAD_REQUEST",
1090
+ "incrementCustomMeter requires customerId"
1091
+ );
1092
+ }
1093
+ if (!request?.meterSlot) {
1094
+ throw new UsageTapError(
1095
+ "USAGETAP_BAD_REQUEST",
1096
+ "incrementCustomMeter requires meterSlot"
1097
+ );
1098
+ }
1099
+ if (!["CUSTOM1", "CUSTOM2"].includes(request.meterSlot)) {
1100
+ throw new UsageTapError(
1101
+ "USAGETAP_BAD_REQUEST",
1102
+ "meterSlot must be CUSTOM1 or CUSTOM2"
1103
+ );
1104
+ }
1105
+ if (typeof request.amount !== "number" || !Number.isFinite(request.amount) || request.amount <= 0) {
1106
+ throw new UsageTapError(
1107
+ "USAGETAP_BAD_REQUEST",
1108
+ "incrementCustomMeter requires a positive numeric amount"
1109
+ );
1110
+ }
1111
+ const idempotencyKey = options.idempotencyKey ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1112
+ const payload = {
1113
+ customerId: request.customerId,
1114
+ meterSlot: request.meterSlot,
1115
+ amount: request.amount
1116
+ };
1117
+ if (request.feature) {
1118
+ payload.feature = request.feature;
1119
+ }
1120
+ if (request.tags && request.tags.length > 0) {
1121
+ payload.tags = request.tags;
1122
+ }
1123
+ if (request.metadata) {
1124
+ payload.metadata = request.metadata;
1125
+ }
1126
+ const response = await this.request(
1127
+ INCREMENT_CUSTOM_METER_PATH,
1128
+ payload,
1129
+ {
1130
+ ...options,
1131
+ idempotencyKey
1132
+ }
1133
+ );
1134
+ this.emitUsageMetric({
1135
+ type: "custom_meter",
1136
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1137
+ customerId: request.customerId,
1138
+ feature: request.feature ?? this.defaultFeature,
1139
+ tags: request.tags ?? this.defaultTags,
1140
+ metrics: {
1141
+ customMeterSlot: request.meterSlot,
1142
+ customMeterAmount: request.amount
1143
+ },
1144
+ correlationId: response.correlationId
1145
+ });
1146
+ return response;
1147
+ }
1148
+ async withUsage(beginRequest, handler, options = {}) {
1149
+ const idempotencyKey = beginRequest.idempotencyKey ?? beginRequest.idempotency ?? (this.autoIdempotency ? this.idempotencyGenerator() : void 0);
1150
+ const beginPayload = idempotencyKey ? { ...beginRequest, idempotencyKey, idempotency: idempotencyKey } : { ...beginRequest };
1151
+ const beginResponse = await this.beginCall(beginPayload, options);
1152
+ let usage = {};
1153
+ const initialStripeCustomerId = typeof beginResponse.data.stripeCustomerId === "string" ? beginResponse.data.stripeCustomerId : typeof beginRequest.stripeCustomerId === "string" ? beginRequest.stripeCustomerId : void 0;
1154
+ if (initialStripeCustomerId) {
1155
+ usage = { ...usage, stripeCustomerId: initialStripeCustomerId };
1156
+ }
1157
+ let errorPayload;
1158
+ let handlerResult;
1159
+ let handlerError;
1160
+ let endCallError;
1161
+ const context = {
1162
+ begin: beginResponse,
1163
+ setUsage: (u) => {
1164
+ usage = { ...usage, ...u };
1165
+ },
1166
+ setError: (err) => {
1167
+ errorPayload = err;
1168
+ }
1169
+ };
1170
+ try {
1171
+ handlerResult = await handler(context);
1172
+ } catch (error) {
1173
+ handlerError = error;
1174
+ if (!errorPayload) {
1175
+ errorPayload = {
1176
+ code: options.defaultErrorCode ?? "VENDOR_ERROR",
1177
+ message: error instanceof Error ? error.message : String(error)
1178
+ };
1179
+ }
1180
+ } finally {
1181
+ try {
1182
+ await this.endCall(
1183
+ {
1184
+ callId: beginResponse.data.callId,
1185
+ // Pass context for metric tracking
1186
+ customerId: beginRequest.customerId,
1187
+ feature: beginRequest.feature ?? this.defaultFeature,
1188
+ tags: beginRequest.tags ?? this.defaultTags,
1189
+ ...usage,
1190
+ error: errorPayload
1191
+ },
1192
+ {
1193
+ ...options,
1194
+ correlationId: beginResponse.correlationId
1195
+ }
1196
+ );
1197
+ } catch (error) {
1198
+ endCallError = error;
1199
+ }
1200
+ }
1201
+ if (handlerError) {
1202
+ throw handlerError;
1203
+ }
1204
+ if (endCallError) {
1205
+ throw wrapEndCallError(endCallError, beginResponse.correlationId);
1206
+ }
1207
+ return handlerResult;
1208
+ }
1209
+ /**
1210
+ * Meter one operation. Pass only a customer ID for the common path, or the
1211
+ * existing begin-call request object when feature, tags, or entitlements are needed.
1212
+ */
1213
+ async meter(request, handler, options = {}) {
1214
+ const beginRequest = typeof request === "string" ? { customerId: request } : request;
1215
+ return this.withUsage(beginRequest, handler, options);
1216
+ }
1217
+ toPromptCompressionTelemetry(result) {
1218
+ return {
1219
+ provider: result.provider,
1220
+ originalCharacters: result.originalCharacters,
1221
+ compressedCharacters: result.compressedCharacters,
1222
+ savedCharacters: result.savedCharacters,
1223
+ originalTokens: result.originalTokens,
1224
+ compressedTokens: result.compressedTokens,
1225
+ savedTokens: result.savedTokens,
1226
+ tokenSavingsRatio: result.tokenSavingsRatio,
1227
+ savingsRatio: result.savingsRatio,
1228
+ techniques: result.techniques
1229
+ };
1230
+ }
1231
+ async request(path, payload, options) {
1232
+ const url = new URL(path, this.baseUrl).toString();
1233
+ const body = payload !== void 0 ? JSON.stringify(payload) : void 0;
1234
+ const headers = this.composeHeaders(body, options);
1235
+ const resolvedRetry = resolveRetryOptions(
1236
+ this.retryDefaults,
1237
+ options.retries
1238
+ );
1239
+ const startTime = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1240
+ return runWithRetry(
1241
+ async (attempt) => {
1242
+ const startedAt = startTime();
1243
+ this.log({
1244
+ event: "request:start",
1245
+ path,
1246
+ attempt,
1247
+ idempotencyKey: options.idempotencyKey,
1248
+ correlationId: options.correlationId
1249
+ });
1250
+ const response = await this.performFetch({
1251
+ url,
1252
+ method: "POST",
1253
+ headers,
1254
+ body,
1255
+ signal: options.signal
1256
+ });
1257
+ this.log({
1258
+ event: "request:success",
1259
+ path,
1260
+ attempt,
1261
+ idempotencyKey: options.idempotencyKey,
1262
+ correlationId: response.correlationId,
1263
+ elapsedMs: startTime() - startedAt
1264
+ });
1265
+ return response;
1266
+ },
1267
+ resolvedRetry,
1268
+ (error) => this.shouldRetry(error),
1269
+ (attempt, delayMs, error) => {
1270
+ this.log({
1271
+ event: "retry:scheduled",
1272
+ path,
1273
+ attempt,
1274
+ idempotencyKey: options.idempotencyKey,
1275
+ correlationId: options.correlationId,
1276
+ error,
1277
+ elapsedMs: delayMs
1278
+ });
1279
+ },
1280
+ options.signal
1281
+ ).catch((error) => {
1282
+ this.log({
1283
+ event: "retry:exhausted",
1284
+ path,
1285
+ attempt: resolvedRetry.maxAttempts,
1286
+ idempotencyKey: options.idempotencyKey,
1287
+ correlationId: options.correlationId,
1288
+ error
1289
+ });
1290
+ throw error;
1291
+ });
1292
+ }
1293
+ async requestGet(path, options) {
1294
+ const url = new URL(path, this.baseUrl).toString();
1295
+ const headers = this.composeHeaders(void 0, options);
1296
+ const resolvedRetry = resolveRetryOptions(
1297
+ this.retryDefaults,
1298
+ options.retries
1299
+ );
1300
+ const startTime = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1301
+ return runWithRetry(
1302
+ async (attempt) => {
1303
+ const startedAt = startTime();
1304
+ this.log({
1305
+ event: "request:start",
1306
+ path,
1307
+ attempt,
1308
+ correlationId: options.correlationId
1309
+ });
1310
+ const response = await this.performFetch({
1311
+ url,
1312
+ method: "GET",
1313
+ headers,
1314
+ signal: options.signal
1315
+ });
1316
+ this.log({
1317
+ event: "request:success",
1318
+ path,
1319
+ attempt,
1320
+ correlationId: response.correlationId,
1321
+ elapsedMs: startTime() - startedAt
1322
+ });
1323
+ return response;
1324
+ },
1325
+ resolvedRetry,
1326
+ (error) => this.shouldRetry(error),
1327
+ (attempt, delayMs, error) => {
1328
+ this.log({
1329
+ event: "retry:scheduled",
1330
+ path,
1331
+ attempt,
1332
+ correlationId: options.correlationId,
1333
+ error,
1334
+ elapsedMs: delayMs
1335
+ });
1336
+ },
1337
+ options.signal
1338
+ ).catch((error) => {
1339
+ this.log({
1340
+ event: "retry:exhausted",
1341
+ path,
1342
+ attempt: resolvedRetry.maxAttempts,
1343
+ correlationId: options.correlationId,
1344
+ error
1345
+ });
1346
+ throw error;
1347
+ });
1348
+ }
1349
+ async performFetch(init) {
1350
+ let response;
1351
+ try {
1352
+ response = await this.fetchImpl(init.url, {
1353
+ method: init.method,
1354
+ headers: init.headers,
1355
+ body: init.body,
1356
+ signal: init.signal
1357
+ });
1358
+ } catch (error) {
1359
+ throw new UsageTapError(
1360
+ "USAGETAP_NETWORK_ERROR",
1361
+ "Failed to reach UsageTap",
1362
+ {
1363
+ retryable: true,
1364
+ cause: error
1365
+ }
1366
+ );
1367
+ }
1368
+ const correlationId = response.headers.get(CORRELATION_HEADER) ?? void 0;
1369
+ const text = await response.text();
1370
+ let payload;
1371
+ if (text) {
1372
+ try {
1373
+ payload = JSON.parse(text);
1374
+ } catch (error) {
1375
+ throw new UsageTapError(
1376
+ "USAGETAP_INVALID_RESPONSE",
1377
+ "UsageTap returned invalid JSON",
1378
+ {
1379
+ retryable: false,
1380
+ correlationId,
1381
+ cause: error
1382
+ }
1383
+ );
1384
+ }
1385
+ }
1386
+ if (!response.ok) {
1387
+ throw this.toHttpError(response.status, payload, correlationId);
1388
+ }
1389
+ if (!payload?.result || payload.result.status !== "ACCEPTED") {
1390
+ throw this.toApiError(payload, correlationId);
1391
+ }
1392
+ const resolvedCorrelation = payload.correlationId ?? correlationId;
1393
+ if (payload.data === void 0 || payload.data === null || !resolvedCorrelation) {
1394
+ throw new UsageTapError(
1395
+ "USAGETAP_INVALID_RESPONSE",
1396
+ "UsageTap response missing data or correlationId",
1397
+ {
1398
+ correlationId: resolvedCorrelation ?? correlationId
1399
+ }
1400
+ );
1401
+ }
1402
+ return {
1403
+ result: {
1404
+ status: payload.result.status,
1405
+ code: payload.result.code,
1406
+ message: payload.result.message,
1407
+ timestamp: payload.result.timestamp
1408
+ },
1409
+ data: payload.data,
1410
+ correlationId: resolvedCorrelation
1411
+ };
1412
+ }
1413
+ composeHeaders(body, options) {
1414
+ const headers = {
1415
+ ...this.defaultHeaders,
1416
+ [SDK_HEADER]: `js/${SDK_VERSION}`,
1417
+ "content-type": "application/json",
1418
+ accept: CANONICAL_MEDIA_TYPE
1419
+ };
1420
+ if (!HAS_WINDOW) {
1421
+ headers["user-agent"] = `${USER_AGENT}/${SDK_VERSION}`;
1422
+ }
1423
+ if (this.authHeader === API_KEY_HEADER) {
1424
+ headers[API_KEY_HEADER] = this.apiKey;
1425
+ } else {
1426
+ headers[AUTH_HEADER] = `Bearer ${this.apiKey}`;
1427
+ }
1428
+ if (options.idempotencyKey) {
1429
+ headers[IDEMPOTENCY_HEADER] = options.idempotencyKey;
1430
+ }
1431
+ if (options.correlationId) {
1432
+ headers[CORRELATION_HEADER] = options.correlationId;
1433
+ }
1434
+ if (!body) {
1435
+ delete headers["content-type"];
1436
+ }
1437
+ if (options.headers) {
1438
+ Object.assign(headers, normalizeHeaderDictionary(options.headers));
1439
+ }
1440
+ return headers;
1441
+ }
1442
+ log(entry) {
1443
+ this.logFn?.(entry);
1444
+ }
1445
+ emitUsageMetric(event) {
1446
+ try {
1447
+ this.metricFn?.(event);
1448
+ } catch {
1449
+ }
1450
+ }
1451
+ mergeTags(tags) {
1452
+ if (!tags && !this.defaultTags) {
1453
+ return void 0;
1454
+ }
1455
+ const combined = [...this.defaultTags ?? [], ...tags ?? []].filter(
1456
+ Boolean
1457
+ );
1458
+ return combined.length ? dedupeStrings(combined) : void 0;
1459
+ }
1460
+ shouldRetry(error) {
1461
+ if (isUsageTapError(error)) {
1462
+ return Boolean(error.retryable);
1463
+ }
1464
+ if (error instanceof Error && error.name === "AbortError") {
1465
+ return false;
1466
+ }
1467
+ return false;
1468
+ }
1469
+ toHttpError(status, payload, correlationId) {
1470
+ const code = mapStatusToErrorCode(status);
1471
+ const retryable = isRetryableStatus(status);
1472
+ const message = payload?.error?.message ?? payload?.result?.message ?? `UsageTap responded with HTTP ${status}`;
1473
+ return new UsageTapError(code, message, {
1474
+ status,
1475
+ retryable,
1476
+ correlationId: payload?.correlationId ?? correlationId,
1477
+ details: sanitizeDetails(payload)
1478
+ });
1479
+ }
1480
+ toApiError(payload, correlationId) {
1481
+ const normalizedCode = payload?.error?.code ?? payload?.result?.code ?? "UNKNOWN";
1482
+ const retryable = isRetryableApiCode(normalizedCode);
1483
+ const message = payload?.error?.message ?? payload?.result?.message ?? "UsageTap reported an error";
1484
+ return new UsageTapError(mapApiCodeToError(normalizedCode), message, {
1485
+ retryable,
1486
+ correlationId: payload?.correlationId ?? correlationId,
1487
+ details: sanitizeDetails(payload)
1488
+ });
1489
+ }
1490
+ };
1491
+ function mapStatusToErrorCode(status) {
1492
+ if (status === 401 || status === 403) return "USAGETAP_AUTH_ERROR";
1493
+ if (status === 400 || status === 404 || status === 409)
1494
+ return "USAGETAP_BAD_REQUEST";
1495
+ if (status === 429) return "USAGETAP_RATE_LIMITED";
1496
+ if (status >= 500) return "USAGETAP_SERVER_ERROR";
1497
+ return "USAGETAP_INVALID_RESPONSE";
1498
+ }
1499
+ function isRetryableStatus(status) {
1500
+ return status === 408 || status === 425 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
1501
+ }
1502
+ function isRetryableApiCode(code) {
1503
+ const normalized = code.toUpperCase();
1504
+ return normalized.includes("TRANSIENT") || normalized.includes("RETRY") || normalized.includes("TIMEOUT") || normalized.includes("THROTTLE") || normalized.includes("RATE_LIMIT");
1505
+ }
1506
+ function mapApiCodeToError(code) {
1507
+ const normalized = code.toUpperCase();
1508
+ if (normalized.includes("AUTH") || normalized.includes("TOKEN")) {
1509
+ return "USAGETAP_AUTH_ERROR";
1510
+ }
1511
+ if (normalized.includes("RATE") || normalized.includes("THROTTLE")) {
1512
+ return "USAGETAP_RATE_LIMITED";
1513
+ }
1514
+ if (normalized.includes("SERVER") || normalized.includes("TRANSIENT")) {
1515
+ return "USAGETAP_SERVER_ERROR";
1516
+ }
1517
+ if (normalized.includes("IDEMPOTENCY") || normalized.includes("VALIDATION") || normalized.includes("REQUEST")) {
1518
+ return "USAGETAP_BAD_REQUEST";
1519
+ }
1520
+ return "USAGETAP_INVALID_RESPONSE";
1521
+ }
1522
+ function sanitizeDetails(payload) {
1523
+ if (!payload) return void 0;
1524
+ const details = {};
1525
+ if (payload.result) details.result = payload.result;
1526
+ if (payload.error) details.error = payload.error;
1527
+ return Object.keys(details).length ? details : void 0;
1528
+ }
1529
+ function readEnvironmentVariable(name) {
1530
+ const runtime = globalThis;
1531
+ const value = runtime.process?.env?.[name]?.trim();
1532
+ return value || void 0;
1533
+ }
1534
+ function normalizeBaseUrl(baseUrl) {
1535
+ const trimmed = baseUrl.trim();
1536
+ if (!trimmed) return trimmed;
1537
+ return trimmed.endsWith("/") ? trimmed : `${trimmed}/`;
1538
+ }
1539
+ function normalizeHeaderDictionary(dict) {
1540
+ return Object.keys(dict).reduce((acc, key) => {
1541
+ acc[key.toLowerCase()] = dict[key];
1542
+ return acc;
1543
+ }, {});
1544
+ }
1545
+ function dedupeStrings(values) {
1546
+ return Array.from(
1547
+ new Set(values.map((value) => value.trim()).filter(Boolean))
1548
+ );
1549
+ }
1550
+ function wrapFetchImplementation(fetchCandidate, preferGlobalContext) {
1551
+ const target = preferGlobalContext ? globalThis : void 0;
1552
+ return ((...args) => target ? Reflect.apply(fetchCandidate, target, args) : fetchCandidate(...args));
1553
+ }
1554
+ function wrapEndCallError(error, correlationId) {
1555
+ if (isUsageTapError(error)) {
1556
+ return new UsageTapError("USAGETAP_END_CALL_ERROR", error.message, {
1557
+ correlationId: error.correlationId ?? correlationId,
1558
+ details: error.details,
1559
+ cause: error
1560
+ });
1561
+ }
1562
+ return new UsageTapError(
1563
+ "USAGETAP_END_CALL_ERROR",
1564
+ "Failed to finalize UsageTap call",
1565
+ {
1566
+ correlationId,
1567
+ cause: error
1568
+ }
1569
+ );
1570
+ }
41
1571
 
42
1572
  // src/adapters/anthropic.ts
43
1573
  var AnthropicPromptCompressionStats = class {
@@ -86,6 +1616,65 @@ var AnthropicPromptCompressionStats = class {
86
1616
  }
87
1617
  };
88
1618
  var USAGETAP_CORRELATION_HEADER = "x-usage-correlation-id";
1619
+ function withCompression(client, options = {}) {
1620
+ if (!client?.messages || typeof client.messages.create !== "function") {
1621
+ throw new UsageTapError(
1622
+ "USAGETAP_BAD_REQUEST",
1623
+ "withCompression requires an Anthropic client instance"
1624
+ );
1625
+ }
1626
+ const {
1627
+ apiKey,
1628
+ usageTapClient,
1629
+ ...compressionOverrides
1630
+ } = options;
1631
+ const usageTap = usageTapClient ?? new UsageTapClient({ apiKey });
1632
+ const compression = {
1633
+ provider: "usagetap",
1634
+ minContextTokens: DEFAULT_PROMPT_COMPRESSION_MIN_CONTEXT_TOKENS,
1635
+ ...compressionOverrides
1636
+ };
1637
+ const originalCreate = client.messages.create.bind(client.messages);
1638
+ const wrappedCreate = (params, requestOptions) => {
1639
+ return compressAnthropicParams(params, usageTap, compression).then((outcome) => originalCreate(outcome.params, requestOptions));
1640
+ };
1641
+ const proxiedMessages = new Proxy(client.messages, {
1642
+ get(target, prop, receiver) {
1643
+ if (prop === "create") return wrappedCreate;
1644
+ return Reflect.get(target, prop, receiver);
1645
+ }
1646
+ });
1647
+ return new Proxy(client, {
1648
+ get(target, prop, receiver) {
1649
+ if (prop === "messages") return proxiedMessages;
1650
+ if (prop === "unwrap") return () => target;
1651
+ return Reflect.get(target, prop, receiver);
1652
+ }
1653
+ });
1654
+ }
1655
+ function withMetering(client, customer) {
1656
+ const config = typeof customer === "string" ? { customerId: customer } : customer;
1657
+ if (!config?.customerId) {
1658
+ throw new UsageTapError(
1659
+ "USAGETAP_BAD_REQUEST",
1660
+ "withMetering requires a customerId"
1661
+ );
1662
+ }
1663
+ const {
1664
+ apiKey,
1665
+ usageTapClient,
1666
+ applyVendorHints,
1667
+ promptCompression,
1668
+ ...defaultContext
1669
+ } = config;
1670
+ const usageTap = usageTapClient ?? new UsageTapClient({ apiKey });
1671
+ const normalizedCompression = promptCompression === true ? { provider: "usagetap" } : promptCompression ? { provider: "usagetap", ...promptCompression } : void 0;
1672
+ return wrapAnthropic(client, usageTap, {
1673
+ defaultContext,
1674
+ applyVendorHints,
1675
+ promptCompression: normalizedCompression
1676
+ });
1677
+ }
89
1678
  function wrapAnthropic(client, usageTap, options = {}) {
90
1679
  if (!client) {
91
1680
  throw new UsageTapError("USAGETAP_BAD_REQUEST", "wrapAnthropic requires an Anthropic client instance");
@@ -268,6 +1857,16 @@ async function compressAnthropicParams(params, usageTap, compression, signal) {
268
1857
  }
269
1858
  const source = cloneRecord(params);
270
1859
  const segments = [];
1860
+ if (isBelowMinContextTokens(
1861
+ {
1862
+ system: source.system,
1863
+ messages: source.messages,
1864
+ tools: source.tools
1865
+ },
1866
+ compression.minContextTokens
1867
+ )) {
1868
+ return { params, segments };
1869
+ }
271
1870
  if (shouldUseUsageTapMessageEndpoint(compression)) {
272
1871
  const result = await usageTap.compressPromptMessages(source, {
273
1872
  provider: "usagetap",
@@ -478,6 +2077,9 @@ function normalizePromptCompressionOptions(options) {
478
2077
  }
479
2078
  return options;
480
2079
  }
2080
+ function isBelowMinContextTokens(context, minContextTokens) {
2081
+ return typeof minContextTokens === "number" && estimatePromptTokens(context) < Math.max(0, minContextTokens);
2082
+ }
481
2083
  function resolveEffectivePromptCompressionOptions(defaults, override) {
482
2084
  if (override === false) {
483
2085
  return void 0;
@@ -599,9 +2201,9 @@ function buildPromptCompressionTelemetry(segments) {
599
2201
  );
600
2202
  const savedCharacters = Math.max(0, originalCharacters - compressedCharacters);
601
2203
  const savedTokens = Math.max(0, originalTokens - compressedTokens);
602
- const providers = dedupeStrings(segments.map((segment) => segment.result.provider));
603
- const roles = dedupeStrings(segments.map((segment) => `role:${segment.role}`));
604
- const techniques = dedupeStrings([
2204
+ const providers = dedupeStrings2(segments.map((segment) => segment.result.provider));
2205
+ const roles = dedupeStrings2(segments.map((segment) => `role:${segment.role}`));
2206
+ const techniques = dedupeStrings2([
605
2207
  "anthropic-wrapper",
606
2208
  ...roles,
607
2209
  ...segments.flatMap((segment) => segment.result.techniques),
@@ -976,9 +2578,9 @@ function mergeTags(a, b) {
976
2578
  if (!values.length) {
977
2579
  return void 0;
978
2580
  }
979
- return dedupeStrings(values);
2581
+ return dedupeStrings2(values);
980
2582
  }
981
- function dedupeStrings(values) {
2583
+ function dedupeStrings2(values) {
982
2584
  return Array.from(new Set(values));
983
2585
  }
984
2586
  function isStreamingRequest(params) {
@@ -1004,6 +2606,8 @@ function isIteratorResult(value) {
1004
2606
  }
1005
2607
 
1006
2608
  exports.AnthropicPromptCompressionStats = AnthropicPromptCompressionStats;
2609
+ exports.withCompression = withCompression;
2610
+ exports.withMetering = withMetering;
1007
2611
  exports.wrapAnthropic = wrapAnthropic;
1008
2612
  //# sourceMappingURL=index.cjs.map
1009
2613
  //# sourceMappingURL=index.cjs.map