import {z} from 'zod' export type UsageInterval = 'day' | 'week' | 'month'; export type GetApiUsageAgentsArgs = {'Cartesia-Version': '2026-03-01', start_ts?: (string | null) | undefined, end_ts?: (string | null) | undefined, interval?: UsageInterval | undefined}; export type GetApiUsageAgentsOptions = {baseUrl?: string | undefined, AdminAPIKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const usageBucketStartTimestamp = z.string(); export const usageBucketEndTimestamp = z.string(); export const usageAgentsBucket = z.object({start_ts: usageBucketStartTimestamp, end_ts: usageBucketEndTimestamp, cents: z.number().int(), minutes: z.number(), calls: z.number().int()}); export const usageAgentsResponse = z.object({data: z.array(usageAgentsBucket)}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Get Agent Usage * * GET /usage/agents */ export const getApiUsageAgents = async (args: GetApiUsageAgentsArgs, options?: GetApiUsageAgentsOptions) => { const {baseUrl = "https://api.cartesia.ai", fetch: fetchFn = fetch, AdminAPIKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['Cartesia-Version'] != null) headers.set("Cartesia-Version", String(args['Cartesia-Version'])) if (args.start_ts != null) query.append("start_ts", String(args.start_ts)) if (args.end_ts != null) query.append("end_ts", String(args.end_ts)) if (args.interval != null) query.append("interval", String(args.interval)) if (AdminAPIKeyAuth !== undefined) headers.set('authorization', `Bearer ${AdminAPIKeyAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/usage/agents${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(usageAgentsResponse, await res.json()) };