promptopskit 0.2.6 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,425 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/usagetap/index.ts
21
+ var usagetap_exports = {};
22
+ __export(usagetap_exports, {
23
+ applyUsageTapEntitlements: () => applyUsageTapEntitlements,
24
+ beginUsageTapCall: () => beginUsageTapCall,
25
+ createUsageTapClient: () => createUsageTapClient,
26
+ defaultUsageTapErrorMapper: () => defaultUsageTapErrorMapper,
27
+ endUsageTapCall: () => endUsageTapCall,
28
+ extractAnthropicUsage: () => extractAnthropicUsage,
29
+ extractGeminiUsage: () => extractGeminiUsage,
30
+ extractOpenAIUsage: () => extractOpenAIUsage,
31
+ runAnthropicWithUsageTap: () => runAnthropicWithUsageTap,
32
+ runGeminiWithUsageTap: () => runGeminiWithUsageTap,
33
+ runOpenAIWithUsageTap: () => runOpenAIWithUsageTap,
34
+ runOpenRouterWithUsageTap: () => runOpenRouterWithUsageTap,
35
+ withUsageTapCall: () => withUsageTapCall
36
+ });
37
+ module.exports = __toCommonJS(usagetap_exports);
38
+
39
+ // src/usagetap/client.ts
40
+ var DEFAULT_BASE_URL = "https://api.usagetap.com";
41
+ var ACCEPT_HEADER = "application/vnd.usagetap.v1+json";
42
+ function createUsageTapHttpError(status, body) {
43
+ const error = new Error(`UsageTap request failed with status ${status}`);
44
+ error.statusCode = status;
45
+ error.body = body;
46
+ return error;
47
+ }
48
+ function createUsageTapClient(config) {
49
+ const fetchImpl = config.fetch ?? globalThis.fetch;
50
+ if (!fetchImpl) {
51
+ throw new Error("Fetch API is not available. Provide config.fetch when creating the UsageTap client.");
52
+ }
53
+ const baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
54
+ async function request(path, body, init = {}) {
55
+ const response = await fetchImpl(`${baseUrl}${path}`, {
56
+ method: "POST",
57
+ headers: {
58
+ Authorization: `Bearer ${config.apiKey}`,
59
+ Accept: ACCEPT_HEADER,
60
+ "Content-Type": "application/json"
61
+ },
62
+ body: JSON.stringify(body),
63
+ signal: init.signal
64
+ });
65
+ const text = await response.text();
66
+ const parsed = text ? JSON.parse(text) : {};
67
+ if (!response.ok) {
68
+ throw createUsageTapHttpError(response.status, parsed);
69
+ }
70
+ return parsed;
71
+ }
72
+ return {
73
+ request,
74
+ beginCall(begin, init) {
75
+ return request("/call_begin", begin, init);
76
+ },
77
+ endCall(end, init) {
78
+ return request("/call_end", end, init);
79
+ }
80
+ };
81
+ }
82
+
83
+ // src/usagetap/lifecycle.ts
84
+ function isObject(value) {
85
+ return typeof value === "object" && value !== null;
86
+ }
87
+ function isInvokeResult(value) {
88
+ return isObject(value) && "result" in value && "usage" in value;
89
+ }
90
+ function getErrorStatusCode(error) {
91
+ if (!isObject(error)) {
92
+ return void 0;
93
+ }
94
+ if (typeof error.statusCode === "number") {
95
+ return error.statusCode;
96
+ }
97
+ if (typeof error.status === "number") {
98
+ return error.status;
99
+ }
100
+ if (isObject(error.response) && typeof error.response.status === "number") {
101
+ return error.response.status;
102
+ }
103
+ return void 0;
104
+ }
105
+ function attachEndErrorCause(thrownError, endError) {
106
+ if (thrownError instanceof Error) {
107
+ if (thrownError.cause === void 0) {
108
+ Object.defineProperty(thrownError, "cause", {
109
+ value: endError,
110
+ configurable: true,
111
+ writable: true
112
+ });
113
+ }
114
+ throw thrownError;
115
+ }
116
+ throw new AggregateError([thrownError, endError], "Vendor call failed and UsageTap call_end also failed.");
117
+ }
118
+ function defaultUsageTapErrorMapper(error) {
119
+ return {
120
+ code: "VENDOR_ERROR",
121
+ message: String(error)
122
+ };
123
+ }
124
+ function beginUsageTapCall(client, begin, init) {
125
+ return client.beginCall(begin, init);
126
+ }
127
+ function endUsageTapCall(client, end, init) {
128
+ return client.endCall(end, init);
129
+ }
130
+ async function withUsageTapCall(client, options) {
131
+ const begin = await beginUsageTapCall(client, options.begin, { signal: options.signal });
132
+ const onError = options.onError ?? defaultUsageTapErrorMapper;
133
+ let result;
134
+ let usage;
135
+ let thrownError;
136
+ const setUsage = (nextUsage) => {
137
+ usage = { ...usage, ...nextUsage };
138
+ };
139
+ try {
140
+ const invoked = await options.invoke({
141
+ begin,
142
+ setUsage,
143
+ signal: options.signal
144
+ });
145
+ if (isInvokeResult(invoked)) {
146
+ result = invoked.result;
147
+ setUsage(invoked.usage);
148
+ } else {
149
+ result = invoked;
150
+ }
151
+ } catch (error) {
152
+ thrownError = error;
153
+ }
154
+ const effectiveUsage = {
155
+ ...usage
156
+ };
157
+ if (thrownError) {
158
+ effectiveUsage.error = effectiveUsage.error ?? onError(thrownError);
159
+ effectiveUsage.responseStatusCode = effectiveUsage.responseStatusCode ?? getErrorStatusCode(thrownError);
160
+ } else {
161
+ effectiveUsage.responseStatusCode = effectiveUsage.responseStatusCode ?? 200;
162
+ }
163
+ let end;
164
+ try {
165
+ end = await endUsageTapCall(client, {
166
+ callId: begin.data.callId,
167
+ ...effectiveUsage
168
+ }, { signal: options.signal });
169
+ } catch (endError) {
170
+ if (thrownError) {
171
+ attachEndErrorCause(thrownError, endError);
172
+ }
173
+ throw endError;
174
+ }
175
+ if (thrownError) {
176
+ throw thrownError;
177
+ }
178
+ return {
179
+ result,
180
+ begin,
181
+ end,
182
+ effectiveUsage
183
+ };
184
+ }
185
+
186
+ // src/usagetap/providers.ts
187
+ function cloneRequest(request) {
188
+ return structuredClone(request);
189
+ }
190
+ function isObject2(value) {
191
+ return typeof value === "object" && value !== null;
192
+ }
193
+ function isRecordArray(value) {
194
+ return Array.isArray(value) && value.every((item) => isObject2(item));
195
+ }
196
+ function isInvokeResult2(value) {
197
+ return isObject2(value) && "result" in value && "usage" in value;
198
+ }
199
+ function capabilityAllowed(allowed, capability) {
200
+ return allowed[capability] !== false;
201
+ }
202
+ function reasoningLevelOrder(level) {
203
+ switch (level) {
204
+ case "HIGH":
205
+ return 3;
206
+ case "MEDIUM":
207
+ return 2;
208
+ case "LOW":
209
+ return 1;
210
+ default:
211
+ return 0;
212
+ }
213
+ }
214
+ function capOpenAIReasoning(body, allowed) {
215
+ if (typeof body.reasoning_effort !== "string") {
216
+ return;
217
+ }
218
+ const current = String(body.reasoning_effort).toUpperCase();
219
+ const allowedLevel = allowed.reasoningLevel ?? "HIGH";
220
+ if (allowedLevel === "NONE") {
221
+ delete body.reasoning_effort;
222
+ return;
223
+ }
224
+ if (reasoningLevelOrder(current) > reasoningLevelOrder(allowedLevel)) {
225
+ body.reasoning_effort = allowedLevel.toLowerCase();
226
+ }
227
+ }
228
+ function capGeminiReasoning(body, allowed) {
229
+ if (allowed.reasoningLevel === "NONE") {
230
+ delete body.thinkingConfig;
231
+ return;
232
+ }
233
+ const budgets = {
234
+ LOW: 1024,
235
+ MEDIUM: 4096,
236
+ HIGH: 8192
237
+ };
238
+ const allowedBudget = allowed.reasoningLevel ? budgets[allowed.reasoningLevel] : void 0;
239
+ if (allowedBudget === void 0) {
240
+ return;
241
+ }
242
+ if (!isObject2(body.thinkingConfig)) {
243
+ body.thinkingConfig = { thinkingBudget: allowedBudget };
244
+ return;
245
+ }
246
+ const thinkingConfig = body.thinkingConfig;
247
+ if (typeof thinkingConfig.thinkingBudget === "number") {
248
+ thinkingConfig.thinkingBudget = Math.min(thinkingConfig.thinkingBudget, allowedBudget);
249
+ return;
250
+ }
251
+ thinkingConfig.thinkingBudget = allowedBudget;
252
+ }
253
+ function applyModelTier(request, allowed, options) {
254
+ const nextModel = allowed.premium && options.modelTiers?.premium ? options.modelTiers.premium : allowed.standard && options.modelTiers?.standard ? options.modelTiers.standard : void 0;
255
+ if (!nextModel) {
256
+ return;
257
+ }
258
+ request.model = nextModel;
259
+ if (isObject2(request.body) && "model" in request.body) {
260
+ request.body.model = nextModel;
261
+ }
262
+ }
263
+ function filterOpenAITools(tools, allowed, options) {
264
+ return tools.filter((tool) => {
265
+ if (tool.type === "web_search" && allowed.search === false) {
266
+ return false;
267
+ }
268
+ const functionDef = isObject2(tool.function) ? tool.function : void 0;
269
+ const name = typeof functionDef?.name === "string" ? functionDef.name : typeof tool.name === "string" ? tool.name : typeof tool.type === "string" ? tool.type : void 0;
270
+ if (!name) {
271
+ return true;
272
+ }
273
+ const capability = options.toolEntitlements?.[name];
274
+ return capability ? capabilityAllowed(allowed, capability) : true;
275
+ });
276
+ }
277
+ function filterAnthropicTools(tools, allowed, options) {
278
+ return tools.filter((tool) => {
279
+ const name = typeof tool.name === "string" ? tool.name : void 0;
280
+ if (!name) {
281
+ return true;
282
+ }
283
+ const capability = options.toolEntitlements?.[name];
284
+ return capability ? capabilityAllowed(allowed, capability) : true;
285
+ });
286
+ }
287
+ function filterGeminiTools(tools, allowed, options) {
288
+ return tools.map((tool) => {
289
+ const declarations = Array.isArray(tool.functionDeclarations) ? tool.functionDeclarations.filter((declaration) => {
290
+ if (!isObject2(declaration) || typeof declaration.name !== "string") {
291
+ return true;
292
+ }
293
+ const capability = options.toolEntitlements?.[declaration.name];
294
+ return capability ? capabilityAllowed(allowed, capability) : true;
295
+ }) : tool.functionDeclarations;
296
+ return {
297
+ ...tool,
298
+ functionDeclarations: declarations
299
+ };
300
+ }).filter((tool) => {
301
+ if (!Array.isArray(tool.functionDeclarations)) {
302
+ return true;
303
+ }
304
+ return tool.functionDeclarations.length > 0;
305
+ });
306
+ }
307
+ function applyUsageTapEntitlements(request, begin, options = {}) {
308
+ const nextRequest = cloneRequest(request);
309
+ const allowed = begin.data.allowed ?? {};
310
+ applyModelTier(nextRequest, allowed, options);
311
+ if (!isObject2(nextRequest.body)) {
312
+ return nextRequest;
313
+ }
314
+ if (nextRequest.provider === "openai" || nextRequest.provider === "openrouter") {
315
+ capOpenAIReasoning(nextRequest.body, allowed);
316
+ if (isRecordArray(nextRequest.body.tools)) {
317
+ nextRequest.body.tools = filterOpenAITools(nextRequest.body.tools, allowed, options);
318
+ }
319
+ return nextRequest;
320
+ }
321
+ if (nextRequest.provider === "gemini") {
322
+ capGeminiReasoning(nextRequest.body, allowed);
323
+ if (isRecordArray(nextRequest.body.tools)) {
324
+ nextRequest.body.tools = filterGeminiTools(nextRequest.body.tools, allowed, options);
325
+ }
326
+ return nextRequest;
327
+ }
328
+ if (nextRequest.provider === "anthropic" && isRecordArray(nextRequest.body.tools)) {
329
+ nextRequest.body.tools = filterAnthropicTools(nextRequest.body.tools, allowed, options);
330
+ }
331
+ return nextRequest;
332
+ }
333
+ function extractOpenAIUsage(response, meta = {}) {
334
+ const usage = isObject2(response) && isObject2(response.usage) ? response.usage : {};
335
+ const promptDetails = isObject2(usage.prompt_tokens_details) ? usage.prompt_tokens_details : {};
336
+ const completionDetails = isObject2(usage.completion_tokens_details) ? usage.completion_tokens_details : {};
337
+ return {
338
+ modelUsed: meta.modelUsed,
339
+ inputTokens: typeof usage.prompt_tokens === "number" ? usage.prompt_tokens : 0,
340
+ responseTokens: typeof usage.completion_tokens === "number" ? usage.completion_tokens : 0,
341
+ cachedInputTokens: typeof promptDetails.cached_tokens === "number" ? promptDetails.cached_tokens : void 0,
342
+ reasoningTokens: typeof completionDetails.reasoning_tokens === "number" ? completionDetails.reasoning_tokens : void 0,
343
+ responseStatusCode: meta.responseStatusCode ?? 200
344
+ };
345
+ }
346
+ function extractAnthropicUsage(response, meta = {}) {
347
+ const usage = isObject2(response) && isObject2(response.usage) ? response.usage : {};
348
+ return {
349
+ modelUsed: meta.modelUsed,
350
+ inputTokens: typeof usage.input_tokens === "number" ? usage.input_tokens : 0,
351
+ responseTokens: typeof usage.output_tokens === "number" ? usage.output_tokens : 0,
352
+ cachedInputTokens: typeof usage.cache_read_input_tokens === "number" ? usage.cache_read_input_tokens : void 0,
353
+ responseStatusCode: meta.responseStatusCode ?? 200
354
+ };
355
+ }
356
+ function extractGeminiUsage(response, meta = {}) {
357
+ const usage = isObject2(response) && isObject2(response.usageMetadata) ? response.usageMetadata : {};
358
+ return {
359
+ modelUsed: meta.modelUsed,
360
+ inputTokens: typeof usage.promptTokenCount === "number" ? usage.promptTokenCount : 0,
361
+ responseTokens: typeof usage.candidatesTokenCount === "number" ? usage.candidatesTokenCount : 0,
362
+ cachedInputTokens: typeof usage.cachedContentTokenCount === "number" ? usage.cachedContentTokenCount : void 0,
363
+ reasoningTokens: typeof usage.thoughtsTokenCount === "number" ? usage.thoughtsTokenCount : void 0,
364
+ responseStatusCode: meta.responseStatusCode ?? 200
365
+ };
366
+ }
367
+ async function runProviderWithUsageTap(client, options, defaultExtractor) {
368
+ let requestUsed = cloneRequest(options.request);
369
+ const lifecycle = await withUsageTapCall(client, {
370
+ begin: options.begin,
371
+ signal: options.signal,
372
+ onError: options.onError ?? defaultUsageTapErrorMapper,
373
+ invoke: async ({ begin, setUsage }) => {
374
+ requestUsed = options.entitlementMode === "apply" ? applyUsageTapEntitlements(options.request, begin, options) : cloneRequest(options.request);
375
+ const invoked = await options.invoke(requestUsed);
376
+ if (isInvokeResult2(invoked)) {
377
+ return invoked;
378
+ }
379
+ const response = invoked;
380
+ const usage = (options.extractUsage ?? defaultExtractor)(response, {
381
+ modelUsed: requestUsed.model,
382
+ responseStatusCode: 200
383
+ });
384
+ setUsage(usage);
385
+ return response;
386
+ }
387
+ });
388
+ return {
389
+ response: lifecycle.result,
390
+ begin: lifecycle.begin,
391
+ end: lifecycle.end,
392
+ requestUsed,
393
+ effectiveUsage: lifecycle.effectiveUsage,
394
+ allowed: lifecycle.begin.data.allowed ?? {}
395
+ };
396
+ }
397
+ function runOpenAIWithUsageTap(client, options) {
398
+ return runProviderWithUsageTap(client, options, extractOpenAIUsage);
399
+ }
400
+ function runOpenRouterWithUsageTap(client, options) {
401
+ return runProviderWithUsageTap(client, options, extractOpenAIUsage);
402
+ }
403
+ function runAnthropicWithUsageTap(client, options) {
404
+ return runProviderWithUsageTap(client, options, extractAnthropicUsage);
405
+ }
406
+ function runGeminiWithUsageTap(client, options) {
407
+ return runProviderWithUsageTap(client, options, extractGeminiUsage);
408
+ }
409
+ // Annotate the CommonJS export names for ESM import in node:
410
+ 0 && (module.exports = {
411
+ applyUsageTapEntitlements,
412
+ beginUsageTapCall,
413
+ createUsageTapClient,
414
+ defaultUsageTapErrorMapper,
415
+ endUsageTapCall,
416
+ extractAnthropicUsage,
417
+ extractGeminiUsage,
418
+ extractOpenAIUsage,
419
+ runAnthropicWithUsageTap,
420
+ runGeminiWithUsageTap,
421
+ runOpenAIWithUsageTap,
422
+ runOpenRouterWithUsageTap,
423
+ withUsageTapCall
424
+ });
425
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/usagetap/index.ts","../../src/usagetap/client.ts","../../src/usagetap/lifecycle.ts","../../src/usagetap/providers.ts"],"sourcesContent":["export type {\n UsageTapAllowed,\n UsageTapAllowedCapability,\n UsageTapBeginRequest,\n UsageTapBeginResponse,\n UsageTapCallOptions,\n UsageTapCallResult,\n UsageTapClient,\n UsageTapClientConfig,\n UsageTapEndRequest,\n UsageTapEndResponse,\n UsageTapEndUsage,\n UsageTapEntitlementMode,\n UsageTapEntitlementOptions,\n UsageTapErrorPayload,\n UsageTapInvokeContext,\n UsageTapInvokeResult,\n UsageTapProviderRunOptions,\n UsageTapProviderRunResult,\n UsageTapReasoningLevel,\n} from './types.js';\nexport { createUsageTapClient } from './client.js';\nexport { beginUsageTapCall, defaultUsageTapErrorMapper, endUsageTapCall, withUsageTapCall } from './lifecycle.js';\nexport {\n applyUsageTapEntitlements,\n extractAnthropicUsage,\n extractGeminiUsage,\n extractOpenAIUsage,\n runAnthropicWithUsageTap,\n runGeminiWithUsageTap,\n runOpenAIWithUsageTap,\n runOpenRouterWithUsageTap,\n} from './providers.js';\n","import type {\n UsageTapBeginRequest,\n UsageTapBeginResponse,\n UsageTapClient,\n UsageTapClientConfig,\n UsageTapEndRequest,\n UsageTapEndResponse,\n UsageTapRequestInit,\n} from './types.js';\n\nconst DEFAULT_BASE_URL = 'https://api.usagetap.com';\nconst ACCEPT_HEADER = 'application/vnd.usagetap.v1+json';\n\nfunction createUsageTapHttpError(status: number, body: unknown): Error & { statusCode: number; body: unknown } {\n const error = new Error(`UsageTap request failed with status ${status}`) as Error & {\n statusCode: number;\n body: unknown;\n };\n error.statusCode = status;\n error.body = body;\n return error;\n}\n\nexport function createUsageTapClient(config: UsageTapClientConfig): UsageTapClient {\n const fetchImpl = config.fetch ?? globalThis.fetch;\n\n if (!fetchImpl) {\n throw new Error('Fetch API is not available. Provide config.fetch when creating the UsageTap client.');\n }\n\n const baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '');\n\n async function request<T>(path: string, body: unknown, init: UsageTapRequestInit = {}): Promise<T> {\n const response = await fetchImpl(`${baseUrl}${path}`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${config.apiKey}`,\n Accept: ACCEPT_HEADER,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n signal: init.signal,\n });\n\n const text = await response.text();\n const parsed = text ? JSON.parse(text) as unknown : {};\n\n if (!response.ok) {\n throw createUsageTapHttpError(response.status, parsed);\n }\n\n return parsed as T;\n }\n\n return {\n request,\n beginCall(begin: UsageTapBeginRequest, init?: UsageTapRequestInit): Promise<UsageTapBeginResponse> {\n return request<UsageTapBeginResponse>('/call_begin', begin, init);\n },\n endCall(end: UsageTapEndRequest, init?: UsageTapRequestInit): Promise<UsageTapEndResponse> {\n return request<UsageTapEndResponse>('/call_end', end, init);\n },\n };\n}\n","import type {\n UsageTapCallOptions,\n UsageTapCallResult,\n UsageTapClient,\n UsageTapEndRequest,\n UsageTapEndUsage,\n UsageTapErrorPayload,\n UsageTapInvokeResult,\n UsageTapRequestInit,\n} from './types.js';\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isInvokeResult<TResult>(value: TResult | UsageTapInvokeResult<TResult>): value is UsageTapInvokeResult<TResult> {\n return isObject(value) && 'result' in value && 'usage' in value;\n}\n\nfunction getErrorStatusCode(error: unknown): number | undefined {\n if (!isObject(error)) {\n return undefined;\n }\n\n if (typeof error.statusCode === 'number') {\n return error.statusCode;\n }\n\n if (typeof error.status === 'number') {\n return error.status;\n }\n\n if (isObject(error.response) && typeof error.response.status === 'number') {\n return error.response.status;\n }\n\n return undefined;\n}\n\nfunction attachEndErrorCause(thrownError: unknown, endError: unknown): never {\n if (thrownError instanceof Error) {\n if (thrownError.cause === undefined) {\n Object.defineProperty(thrownError, 'cause', {\n value: endError,\n configurable: true,\n writable: true,\n });\n }\n\n throw thrownError;\n }\n\n throw new AggregateError([thrownError, endError], 'Vendor call failed and UsageTap call_end also failed.');\n}\n\nexport function defaultUsageTapErrorMapper(error: unknown): UsageTapErrorPayload {\n return {\n code: 'VENDOR_ERROR',\n message: String(error),\n };\n}\n\nexport function beginUsageTapCall(client: UsageTapClient, begin: Parameters<UsageTapClient['beginCall']>[0], init?: UsageTapRequestInit) {\n return client.beginCall(begin, init);\n}\n\nexport function endUsageTapCall(client: UsageTapClient, end: UsageTapEndRequest, init?: UsageTapRequestInit) {\n return client.endCall(end, init);\n}\n\nexport async function withUsageTapCall<TResult>(\n client: UsageTapClient,\n options: UsageTapCallOptions<TResult>,\n): Promise<UsageTapCallResult<TResult>> {\n const begin = await beginUsageTapCall(client, options.begin, { signal: options.signal });\n const onError = options.onError ?? defaultUsageTapErrorMapper;\n\n let result: TResult | undefined;\n let usage: UsageTapEndUsage | undefined;\n let thrownError: unknown;\n\n const setUsage = (nextUsage: UsageTapEndUsage): void => {\n usage = { ...usage, ...nextUsage };\n };\n\n try {\n const invoked = await options.invoke({\n begin,\n setUsage,\n signal: options.signal,\n });\n\n if (isInvokeResult(invoked)) {\n result = invoked.result;\n setUsage(invoked.usage);\n } else {\n result = invoked;\n }\n } catch (error) {\n thrownError = error;\n }\n\n const effectiveUsage: UsageTapEndUsage = {\n ...usage,\n };\n\n if (thrownError) {\n effectiveUsage.error = effectiveUsage.error ?? onError(thrownError);\n effectiveUsage.responseStatusCode = effectiveUsage.responseStatusCode ?? getErrorStatusCode(thrownError);\n } else {\n effectiveUsage.responseStatusCode = effectiveUsage.responseStatusCode ?? 200;\n }\n\n let end;\n try {\n end = await endUsageTapCall(client, {\n callId: begin.data.callId,\n ...effectiveUsage,\n }, { signal: options.signal });\n } catch (endError) {\n if (thrownError) {\n attachEndErrorCause(thrownError, endError);\n }\n throw endError;\n }\n\n if (thrownError) {\n throw thrownError;\n }\n\n return {\n result: result as TResult,\n begin,\n end,\n effectiveUsage,\n };\n}\n","import type { ProviderRequest } from '../providers/types.js';\nimport { defaultUsageTapErrorMapper, withUsageTapCall } from './lifecycle.js';\nimport type {\n UsageTapAllowed,\n UsageTapAllowedCapability,\n UsageTapBeginResponse,\n UsageTapClient,\n UsageTapEndUsage,\n UsageTapEntitlementOptions,\n UsageTapProviderRunOptions,\n UsageTapProviderRunResult,\n UsageTapReasoningLevel,\n} from './types.js';\n\nfunction cloneRequest(request: ProviderRequest): ProviderRequest {\n return structuredClone(request);\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isRecordArray(value: unknown): value is Array<Record<string, unknown>> {\n return Array.isArray(value) && value.every((item) => isObject(item));\n}\n\nfunction isInvokeResult<TResult>(value: unknown): value is { result: TResult; usage: UsageTapEndUsage } {\n return isObject(value) && 'result' in value && 'usage' in value;\n}\n\nfunction capabilityAllowed(allowed: UsageTapAllowed, capability: UsageTapAllowedCapability): boolean {\n return allowed[capability] !== false;\n}\n\nfunction reasoningLevelOrder(level: UsageTapReasoningLevel | undefined): number {\n switch (level) {\n case 'HIGH':\n return 3;\n case 'MEDIUM':\n return 2;\n case 'LOW':\n return 1;\n default:\n return 0;\n }\n}\n\nfunction capOpenAIReasoning(body: Record<string, unknown>, allowed: UsageTapAllowed): void {\n if (typeof body.reasoning_effort !== 'string') {\n return;\n }\n\n const current = String(body.reasoning_effort).toUpperCase() as UsageTapReasoningLevel;\n const allowedLevel = allowed.reasoningLevel ?? 'HIGH';\n\n if (allowedLevel === 'NONE') {\n delete body.reasoning_effort;\n return;\n }\n\n if (reasoningLevelOrder(current) > reasoningLevelOrder(allowedLevel)) {\n body.reasoning_effort = allowedLevel.toLowerCase();\n }\n}\n\nfunction capGeminiReasoning(body: Record<string, unknown>, allowed: UsageTapAllowed): void {\n if (allowed.reasoningLevel === 'NONE') {\n delete body.thinkingConfig;\n return;\n }\n\n const budgets: Record<Exclude<UsageTapReasoningLevel, 'NONE'>, number> = {\n LOW: 1024,\n MEDIUM: 4096,\n HIGH: 8192,\n };\n\n const allowedBudget = allowed.reasoningLevel ? budgets[allowed.reasoningLevel as Exclude<UsageTapReasoningLevel, 'NONE'>] : undefined;\n\n if (allowedBudget === undefined) {\n return;\n }\n\n if (!isObject(body.thinkingConfig)) {\n body.thinkingConfig = { thinkingBudget: allowedBudget };\n return;\n }\n\n const thinkingConfig = body.thinkingConfig;\n\n if (typeof thinkingConfig.thinkingBudget === 'number') {\n thinkingConfig.thinkingBudget = Math.min(thinkingConfig.thinkingBudget, allowedBudget);\n return;\n }\n\n thinkingConfig.thinkingBudget = allowedBudget;\n}\n\nfunction applyModelTier(request: ProviderRequest, allowed: UsageTapAllowed, options: UsageTapEntitlementOptions): void {\n const nextModel = allowed.premium && options.modelTiers?.premium\n ? options.modelTiers.premium\n : allowed.standard && options.modelTiers?.standard\n ? options.modelTiers.standard\n : undefined;\n\n if (!nextModel) {\n return;\n }\n\n request.model = nextModel;\n if (isObject(request.body) && 'model' in request.body) {\n request.body.model = nextModel;\n }\n}\n\nfunction filterOpenAITools(tools: Array<Record<string, unknown>>, allowed: UsageTapAllowed, options: UsageTapEntitlementOptions): Array<Record<string, unknown>> {\n return tools.filter((tool) => {\n if (tool.type === 'web_search' && allowed.search === false) {\n return false;\n }\n\n const functionDef = isObject(tool.function) ? tool.function : undefined;\n const name = typeof functionDef?.name === 'string'\n ? functionDef.name\n : typeof tool.name === 'string'\n ? tool.name\n : typeof tool.type === 'string'\n ? tool.type\n : undefined;\n\n if (!name) {\n return true;\n }\n\n const capability = options.toolEntitlements?.[name];\n return capability ? capabilityAllowed(allowed, capability) : true;\n });\n}\n\nfunction filterAnthropicTools(tools: Array<Record<string, unknown>>, allowed: UsageTapAllowed, options: UsageTapEntitlementOptions): Array<Record<string, unknown>> {\n return tools.filter((tool) => {\n const name = typeof tool.name === 'string' ? tool.name : undefined;\n if (!name) {\n return true;\n }\n const capability = options.toolEntitlements?.[name];\n return capability ? capabilityAllowed(allowed, capability) : true;\n });\n}\n\nfunction filterGeminiTools(tools: Array<Record<string, unknown>>, allowed: UsageTapAllowed, options: UsageTapEntitlementOptions): Array<Record<string, unknown>> {\n return tools\n .map((tool) => {\n const declarations = Array.isArray(tool.functionDeclarations)\n ? tool.functionDeclarations.filter((declaration) => {\n if (!isObject(declaration) || typeof declaration.name !== 'string') {\n return true;\n }\n const capability = options.toolEntitlements?.[declaration.name];\n return capability ? capabilityAllowed(allowed, capability) : true;\n })\n : tool.functionDeclarations;\n\n return {\n ...tool,\n functionDeclarations: declarations,\n };\n })\n .filter((tool) => {\n if (!Array.isArray(tool.functionDeclarations)) {\n return true;\n }\n return tool.functionDeclarations.length > 0;\n });\n}\n\nexport function applyUsageTapEntitlements(\n request: ProviderRequest,\n begin: UsageTapBeginResponse,\n options: UsageTapEntitlementOptions = {},\n): ProviderRequest {\n const nextRequest = cloneRequest(request);\n const allowed = begin.data.allowed ?? {};\n\n applyModelTier(nextRequest, allowed, options);\n\n if (!isObject(nextRequest.body)) {\n return nextRequest;\n }\n\n if (nextRequest.provider === 'openai' || nextRequest.provider === 'openrouter') {\n capOpenAIReasoning(nextRequest.body, allowed);\n if (isRecordArray(nextRequest.body.tools)) {\n nextRequest.body.tools = filterOpenAITools(nextRequest.body.tools, allowed, options);\n }\n return nextRequest;\n }\n\n if (nextRequest.provider === 'gemini') {\n capGeminiReasoning(nextRequest.body, allowed);\n if (isRecordArray(nextRequest.body.tools)) {\n nextRequest.body.tools = filterGeminiTools(nextRequest.body.tools, allowed, options);\n }\n return nextRequest;\n }\n\n if (nextRequest.provider === 'anthropic' && isRecordArray(nextRequest.body.tools)) {\n nextRequest.body.tools = filterAnthropicTools(nextRequest.body.tools, allowed, options);\n }\n\n return nextRequest;\n}\n\ninterface UsageMeta {\n modelUsed?: string;\n responseStatusCode?: number;\n}\n\nexport function extractOpenAIUsage(response: unknown, meta: UsageMeta = {}): UsageTapEndUsage {\n const usage = isObject(response) && isObject(response.usage) ? response.usage : {};\n const promptDetails = isObject(usage.prompt_tokens_details) ? usage.prompt_tokens_details : {};\n const completionDetails = isObject(usage.completion_tokens_details) ? usage.completion_tokens_details : {};\n\n return {\n modelUsed: meta.modelUsed,\n inputTokens: typeof usage.prompt_tokens === 'number' ? usage.prompt_tokens : 0,\n responseTokens: typeof usage.completion_tokens === 'number' ? usage.completion_tokens : 0,\n cachedInputTokens: typeof promptDetails.cached_tokens === 'number' ? promptDetails.cached_tokens : undefined,\n reasoningTokens: typeof completionDetails.reasoning_tokens === 'number' ? completionDetails.reasoning_tokens : undefined,\n responseStatusCode: meta.responseStatusCode ?? 200,\n };\n}\n\nexport function extractAnthropicUsage(response: unknown, meta: UsageMeta = {}): UsageTapEndUsage {\n const usage = isObject(response) && isObject(response.usage) ? response.usage : {};\n\n return {\n modelUsed: meta.modelUsed,\n inputTokens: typeof usage.input_tokens === 'number' ? usage.input_tokens : 0,\n responseTokens: typeof usage.output_tokens === 'number' ? usage.output_tokens : 0,\n cachedInputTokens: typeof usage.cache_read_input_tokens === 'number' ? usage.cache_read_input_tokens : undefined,\n responseStatusCode: meta.responseStatusCode ?? 200,\n };\n}\n\nexport function extractGeminiUsage(response: unknown, meta: UsageMeta = {}): UsageTapEndUsage {\n const usage = isObject(response) && isObject(response.usageMetadata) ? response.usageMetadata : {};\n\n return {\n modelUsed: meta.modelUsed,\n inputTokens: typeof usage.promptTokenCount === 'number' ? usage.promptTokenCount : 0,\n responseTokens: typeof usage.candidatesTokenCount === 'number' ? usage.candidatesTokenCount : 0,\n cachedInputTokens: typeof usage.cachedContentTokenCount === 'number' ? usage.cachedContentTokenCount : undefined,\n reasoningTokens: typeof usage.thoughtsTokenCount === 'number' ? usage.thoughtsTokenCount : undefined,\n responseStatusCode: meta.responseStatusCode ?? 200,\n };\n}\n\nasync function runProviderWithUsageTap<TResult>(\n client: UsageTapClient,\n options: UsageTapProviderRunOptions<TResult>,\n defaultExtractor: (response: TResult, meta: UsageMeta) => UsageTapEndUsage,\n): Promise<UsageTapProviderRunResult<TResult>> {\n let requestUsed = cloneRequest(options.request);\n\n const lifecycle = await withUsageTapCall(client, {\n begin: options.begin,\n signal: options.signal,\n onError: options.onError ?? defaultUsageTapErrorMapper,\n invoke: async ({ begin, setUsage }) => {\n requestUsed = options.entitlementMode === 'apply'\n ? applyUsageTapEntitlements(options.request, begin, options)\n : cloneRequest(options.request);\n\n const invoked = await options.invoke(requestUsed);\n\n if (isInvokeResult<TResult>(invoked)) {\n return invoked;\n }\n\n const response = invoked as TResult;\n const usage = (options.extractUsage ?? defaultExtractor)(response, {\n modelUsed: requestUsed.model,\n responseStatusCode: 200,\n });\n setUsage(usage);\n return response;\n },\n });\n\n return {\n response: lifecycle.result,\n begin: lifecycle.begin,\n end: lifecycle.end,\n requestUsed,\n effectiveUsage: lifecycle.effectiveUsage,\n allowed: lifecycle.begin.data.allowed ?? {},\n };\n}\n\nexport function runOpenAIWithUsageTap<TResult>(client: UsageTapClient, options: UsageTapProviderRunOptions<TResult>) {\n return runProviderWithUsageTap(client, options, extractOpenAIUsage);\n}\n\nexport function runOpenRouterWithUsageTap<TResult>(client: UsageTapClient, options: UsageTapProviderRunOptions<TResult>) {\n return runProviderWithUsageTap(client, options, extractOpenAIUsage);\n}\n\nexport function runAnthropicWithUsageTap<TResult>(client: UsageTapClient, options: UsageTapProviderRunOptions<TResult>) {\n return runProviderWithUsageTap(client, options, extractAnthropicUsage);\n}\n\nexport function runGeminiWithUsageTap<TResult>(client: UsageTapClient, options: UsageTapProviderRunOptions<TResult>) {\n return runProviderWithUsageTap(client, options, extractGeminiUsage);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACUA,IAAM,mBAAmB;AACzB,IAAM,gBAAgB;AAEtB,SAAS,wBAAwB,QAAgB,MAA8D;AAC7G,QAAM,QAAQ,IAAI,MAAM,uCAAuC,MAAM,EAAE;AAIvE,QAAM,aAAa;AACnB,QAAM,OAAO;AACb,SAAO;AACT;AAEO,SAAS,qBAAqB,QAA8C;AACjF,QAAM,YAAY,OAAO,SAAS,WAAW;AAE7C,MAAI,CAAC,WAAW;AACd,UAAM,IAAI,MAAM,qFAAqF;AAAA,EACvG;AAEA,QAAM,WAAW,OAAO,WAAW,kBAAkB,QAAQ,OAAO,EAAE;AAEtE,iBAAe,QAAW,MAAc,MAAe,OAA4B,CAAC,GAAe;AACjG,UAAM,WAAW,MAAM,UAAU,GAAG,OAAO,GAAG,IAAI,IAAI;AAAA,MACpD,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,eAAe,UAAU,OAAO,MAAM;AAAA,QACtC,QAAQ;AAAA,QACR,gBAAgB;AAAA,MAClB;AAAA,MACA,MAAM,KAAK,U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E,WAAW,YAAY;AAAA,QACvB,oBAAoB;AAAA,MACtB,CAAC;AACD,eAAS,KAAK;AACd,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AAED,SAAO;AAAA,IACL,UAAU,UAAU;AAAA,IACpB,OAAO,UAAU;AAAA,IACjB,KAAK,UAAU;AAAA,IACf;AAAA,IACA,gBAAgB,UAAU;AAAA,IAC1B,SAAS,UAAU,MAAM,KAAK,WAAW,CAAC;AAAA,EAC5C;AACF;AAEO,SAAS,sBAA+B,QAAwB,SAA8C;AACnH,SAAO,wBAAwB,QAAQ,SAAS,kBAAkB;AACpE;AAEO,SAAS,0BAAmC,QAAwB,SAA8C;AACvH,SAAO,wBAAwB,QAAQ,SAAS,kBAAkB;AACpE;AAEO,SAAS,yBAAkC,QAAwB,SAA8C;AACtH,SAAO,wBAAwB,QAAQ,SAAS,qBAAqB;AACvE;AAEO,SAAS,sBAA+B,QAAwB,SAA8C;AACnH,SAAO,wBAAwB,QAAQ,SAAS,kBAAkB;AACpE;","names":["isObject","isInvokeResult"]}
@@ -0,0 +1,147 @@
1
+ import { a as ProviderRequest } from '../types-1zDDD-Ij.cjs';
2
+ import '../schema-DIOA4OiO.cjs';
3
+ import 'zod';
4
+
5
+ type UsageTapReasoningLevel = 'NONE' | 'LOW' | 'MEDIUM' | 'HIGH';
6
+ type UsageTapEntitlementMode = 'off' | 'apply';
7
+ type UsageTapAllowedCapability = 'standard' | 'premium' | 'audio' | 'image' | 'search';
8
+ interface UsageTapAllowed {
9
+ standard?: boolean;
10
+ premium?: boolean;
11
+ audio?: boolean;
12
+ image?: boolean;
13
+ search?: boolean;
14
+ reasoningLevel?: UsageTapReasoningLevel;
15
+ }
16
+ interface UsageTapBeginRequest {
17
+ customerId: string;
18
+ feature?: string;
19
+ tags?: string[];
20
+ customerName?: string;
21
+ customerEmail?: string;
22
+ stripeCustomerId?: string;
23
+ requested?: Record<string, boolean | string>;
24
+ idempotencyKey?: string;
25
+ batch?: boolean;
26
+ pricingMode?: 'batch' | 'standard';
27
+ }
28
+ interface UsageTapBeginResponse {
29
+ data: {
30
+ callId: string;
31
+ allowed: UsageTapAllowed;
32
+ entitlementHints?: Record<string, unknown>;
33
+ subscription?: Record<string, unknown>;
34
+ plan?: Record<string, unknown>;
35
+ balances?: Record<string, unknown>;
36
+ stripeCustomerId?: string | null;
37
+ [key: string]: unknown;
38
+ };
39
+ [key: string]: unknown;
40
+ }
41
+ interface UsageTapErrorPayload {
42
+ code: string;
43
+ message: string;
44
+ }
45
+ interface UsageTapEndUsage {
46
+ modelUsed?: string;
47
+ inputTokens?: number;
48
+ cachedInputTokens?: number;
49
+ responseTokens?: number;
50
+ reasoningTokens?: number;
51
+ searches?: number;
52
+ audio?: number;
53
+ audioSeconds?: number;
54
+ isPremium?: boolean;
55
+ stripeCustomerId?: string;
56
+ responseStatusCode?: number;
57
+ batch?: boolean;
58
+ pricingMode?: 'batch' | 'standard';
59
+ error?: UsageTapErrorPayload;
60
+ }
61
+ interface UsageTapEndRequest extends UsageTapEndUsage {
62
+ callId: string;
63
+ }
64
+ interface UsageTapEndResponse {
65
+ data?: Record<string, unknown>;
66
+ [key: string]: unknown;
67
+ }
68
+ interface UsageTapClientConfig {
69
+ apiKey: string;
70
+ baseUrl?: string;
71
+ fetch?: typeof globalThis.fetch;
72
+ }
73
+ interface UsageTapRequestInit {
74
+ signal?: AbortSignal;
75
+ }
76
+ interface UsageTapClient {
77
+ request<T>(path: string, body: unknown, init?: UsageTapRequestInit): Promise<T>;
78
+ beginCall(begin: UsageTapBeginRequest, init?: UsageTapRequestInit): Promise<UsageTapBeginResponse>;
79
+ endCall(end: UsageTapEndRequest, init?: UsageTapRequestInit): Promise<UsageTapEndResponse>;
80
+ }
81
+ interface UsageTapInvokeContext {
82
+ begin: UsageTapBeginResponse;
83
+ setUsage: (usage: UsageTapEndUsage) => void;
84
+ signal?: AbortSignal;
85
+ }
86
+ interface UsageTapInvokeResult<TResult> {
87
+ result: TResult;
88
+ usage: UsageTapEndUsage;
89
+ }
90
+ interface UsageTapCallOptions<TResult> {
91
+ begin: UsageTapBeginRequest;
92
+ invoke: (context: UsageTapInvokeContext) => Promise<TResult | UsageTapInvokeResult<TResult>>;
93
+ onError?: (error: unknown) => UsageTapErrorPayload;
94
+ signal?: AbortSignal;
95
+ }
96
+ interface UsageTapCallResult<TResult> {
97
+ result: TResult;
98
+ begin: UsageTapBeginResponse;
99
+ end: UsageTapEndResponse;
100
+ effectiveUsage: UsageTapEndUsage;
101
+ }
102
+ interface UsageTapEntitlementOptions {
103
+ modelTiers?: {
104
+ standard?: string;
105
+ premium?: string;
106
+ };
107
+ toolEntitlements?: Record<string, UsageTapAllowedCapability>;
108
+ }
109
+ interface UsageTapProviderRunOptions<TResult> extends UsageTapEntitlementOptions {
110
+ request: ProviderRequest;
111
+ begin: UsageTapBeginRequest;
112
+ invoke: (request: ProviderRequest) => Promise<TResult | UsageTapInvokeResult<TResult>>;
113
+ extractUsage?: (response: TResult) => UsageTapEndUsage;
114
+ entitlementMode?: UsageTapEntitlementMode;
115
+ signal?: AbortSignal;
116
+ onError?: (error: unknown) => UsageTapErrorPayload;
117
+ }
118
+ interface UsageTapProviderRunResult<TResult> {
119
+ response: TResult;
120
+ begin: UsageTapBeginResponse;
121
+ end: UsageTapEndResponse;
122
+ requestUsed: ProviderRequest;
123
+ effectiveUsage: UsageTapEndUsage;
124
+ allowed: UsageTapAllowed;
125
+ }
126
+
127
+ declare function createUsageTapClient(config: UsageTapClientConfig): UsageTapClient;
128
+
129
+ declare function defaultUsageTapErrorMapper(error: unknown): UsageTapErrorPayload;
130
+ declare function beginUsageTapCall(client: UsageTapClient, begin: Parameters<UsageTapClient['beginCall']>[0], init?: UsageTapRequestInit): Promise<UsageTapBeginResponse>;
131
+ declare function endUsageTapCall(client: UsageTapClient, end: UsageTapEndRequest, init?: UsageTapRequestInit): Promise<UsageTapEndResponse>;
132
+ declare function withUsageTapCall<TResult>(client: UsageTapClient, options: UsageTapCallOptions<TResult>): Promise<UsageTapCallResult<TResult>>;
133
+
134
+ declare function applyUsageTapEntitlements(request: ProviderRequest, begin: UsageTapBeginResponse, options?: UsageTapEntitlementOptions): ProviderRequest;
135
+ interface UsageMeta {
136
+ modelUsed?: string;
137
+ responseStatusCode?: number;
138
+ }
139
+ declare function extractOpenAIUsage(response: unknown, meta?: UsageMeta): UsageTapEndUsage;
140
+ declare function extractAnthropicUsage(response: unknown, meta?: UsageMeta): UsageTapEndUsage;
141
+ declare function extractGeminiUsage(response: unknown, meta?: UsageMeta): UsageTapEndUsage;
142
+ declare function runOpenAIWithUsageTap<TResult>(client: UsageTapClient, options: UsageTapProviderRunOptions<TResult>): Promise<UsageTapProviderRunResult<TResult>>;
143
+ declare function runOpenRouterWithUsageTap<TResult>(client: UsageTapClient, options: UsageTapProviderRunOptions<TResult>): Promise<UsageTapProviderRunResult<TResult>>;
144
+ declare function runAnthropicWithUsageTap<TResult>(client: UsageTapClient, options: UsageTapProviderRunOptions<TResult>): Promise<UsageTapProviderRunResult<TResult>>;
145
+ declare function runGeminiWithUsageTap<TResult>(client: UsageTapClient, options: UsageTapProviderRunOptions<TResult>): Promise<UsageTapProviderRunResult<TResult>>;
146
+
147
+ export { type UsageTapAllowed, type UsageTapAllowedCapability, type UsageTapBeginRequest, type UsageTapBeginResponse, type UsageTapCallOptions, type UsageTapCallResult, type UsageTapClient, type UsageTapClientConfig, type UsageTapEndRequest, type UsageTapEndResponse, type UsageTapEndUsage, type UsageTapEntitlementMode, type UsageTapEntitlementOptions, type UsageTapErrorPayload, type UsageTapInvokeContext, type UsageTapInvokeResult, type UsageTapProviderRunOptions, type UsageTapProviderRunResult, type UsageTapReasoningLevel, applyUsageTapEntitlements, beginUsageTapCall, createUsageTapClient, defaultUsageTapErrorMapper, endUsageTapCall, extractAnthropicUsage, extractGeminiUsage, extractOpenAIUsage, runAnthropicWithUsageTap, runGeminiWithUsageTap, runOpenAIWithUsageTap, runOpenRouterWithUsageTap, withUsageTapCall };