import {z} from 'zod' export type GetApiApiTokensArgs = {action?: ('list' | 'stats' | 'agent-costs' | 'export' | 'trends') | undefined, timeframe?: ('hour' | 'day' | 'week' | 'month' | 'all') | undefined, format?: ('json' | 'csv') | undefined}; export type GetApiApiTokensOptions = {baseUrl: string, sessionCookie?: string | undefined, fetch?: typeof fetch | undefined}; export const tokenUsageRecord = z.object({id: z.string().optional(), model: z.string().optional(), sessionId: z.string().optional(), timestamp: z.number().int().optional(), inputTokens: z.number().int().optional(), outputTokens: z.number().int().optional(), totalTokens: z.number().int().optional(), cost: z.number().optional(), operation: z.string().optional(), duration: z.number().optional()}); export const tokenStats = z.object({totalTokens: z.number().int().optional(), totalCost: z.number().optional(), requestCount: z.number().int().optional(), avgTokensPerRequest: z.number().int().optional(), avgCostPerRequest: z.number().optional()}); export const getApiApiTokensResponse = z.union([z.object({usage: z.array(tokenUsageRecord).optional(), total: z.number().int().optional(), timeframe: z.string().optional()}), z.object({summary: tokenStats.optional(), models: z.record(z.string(), tokenStats).optional(), sessions: z.record(z.string(), tokenStats).optional(), agents: z.record(z.string(), tokenStats).optional(), timeframe: z.string().optional(), recordCount: z.number().int().optional()}), z.object({trends: z.array(z.object({timestamp: z.string().optional(), tokens: z.number().int().optional(), cost: z.number().optional(), requests: z.number().int().optional()})).optional(), timeframe: z.string().optional()})]); 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 }; /** * Query token usage * * GET /api/tokens * * Also accepts auth: apiKey */ export const getApiApiTokens = async (args: GetApiApiTokensArgs, options: GetApiApiTokensOptions) => { const {baseUrl, fetch: fetchFn = fetch, sessionCookie} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.action != null) query.append("action", String(args.action)) if (args.timeframe != null) query.append("timeframe", String(args.timeframe)) if (args.format != null) query.append("format", String(args.format)) if (sessionCookie !== undefined) cookies.push("__Host-mc-session=" + encodeURIComponent(sessionCookie)) const url = `${baseUrl.replace(/\/+$/, '')}/api/tokens${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(getApiApiTokensResponse, await res.json()) };