import {z} from 'zod' export type MetricEvent = {id: string, occurred_at: string, session_id?: string | undefined, install_id?: string | undefined, harness?: string | undefined, provider?: string | undefined, model?: string | undefined, action_kind: 'unknown' | 'log' | 'test_build_lint' | 'search' | 'file_list' | 'document_read' | 'agent_handoff' | 'query' | 'verbatim', decision: string, reason?: string | undefined, original_bytes?: number | undefined, replacement_bytes?: number | undefined, provider_input_tokens?: number | undefined, provider_output_tokens?: number | undefined, provider_cache_read_tokens?: number | undefined, provider_cache_write_tokens?: number | undefined, estimated_cost_microusd?: number | undefined, reducer_cost_microusd?: number | undefined, elapsed_ms?: number | undefined, turn_count?: number | undefined, retry_count?: number | undefined, reread_count?: number | undefined, retrieval_count?: number | undefined, client_version?: string | undefined}; export type MetricsBatch = {events: Array}; export type CreateApiV1MetricsBatchArgs = {body: MetricsBatch}; export type CreateApiV1MetricsBatchOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const createApiV1MetricsBatchResponse = z.record(z.string(), z.number().int()); 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 }; /** * Record Metrics * * POST /v1/metrics/batch */ export const createApiV1MetricsBatch = async (args: CreateApiV1MetricsBatchArgs, options: CreateApiV1MetricsBatchOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/v1/metrics/batch${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiV1MetricsBatchResponse, await res.json()) };