|
| 1 | +import { ABUSE_CLASSIFICATION, GatewayApiKindSchema } from './schema-types'; |
| 2 | +import { z } from 'zod'; |
| 3 | + |
| 4 | +export { ABUSE_CLASSIFICATION, GatewayApiKindSchema } from './schema-types'; |
| 5 | +export type { AbuseClassification, GatewayApiKind } from './schema-types'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Wire contract for `POST /api/internal/usage/record`. |
| 9 | + * |
| 10 | + * The AI gateway runs on `kilocode-global-app`, whose functions execute in both |
| 11 | + * Frankfurt and SFO, while the PostgreSQL primary is Frankfurt-only. The usage |
| 12 | + * write holds row locks on `kilocode_users` / `organizations` / |
| 13 | + * `organization_user_usage` across several sequential statements, so from SFO |
| 14 | + * the lock hold is dominated by transatlantic round trips rather than database |
| 15 | + * work. This contract lets an SFO instance hand the whole write to a |
| 16 | + * Frankfurt-local endpoint so those round trips become local. |
| 17 | + * |
| 18 | + * Invariants this schema deliberately encodes: |
| 19 | + * |
| 20 | + * - Nullable fields use `.nullable()`. Except for additive rollout fields that |
| 21 | + * default to null, missing keys are rejected: `JSON.stringify` drops |
| 22 | + * `undefined`-valued keys, and `null` is load-bearing here. For organization |
| 23 | + * usage `toInsertableDbUsageRecord` explicitly sets `user_prompt_prefix` and |
| 24 | + * `system_prompt_prefix` to `null` so prompt text is never persisted. |
| 25 | + * - `created_at` is validated as strict ISO 8601. Both `core.created_at` and |
| 26 | + * `metadata.created_at` come from `new Date().toISOString()` on the sender, so |
| 27 | + * this holds by construction. It would NOT hold for a value read back out of |
| 28 | + * PostgreSQL, which has shape `2026-04-29 01:16:12.945+00` — see |
| 29 | + * `packages/db/AGENTS.md` "Timestamp boundaries". Keep the strict validator so |
| 30 | + * a DB-shaped timestamp can never enter this path. |
| 31 | + * - `cost` and the token counts are PostgreSQL `bigint` mapped to JS `number`, |
| 32 | + * so they are validated as safe integers. |
| 33 | + * |
| 34 | + * NUL-byte sanitization (`stripNulBytesInPlace`) happens on the sender inside |
| 35 | + * `toInsertableDbUsageRecord`, before serialization. `JSON.stringify` preserves |
| 36 | + * `\u0000` happily, so that sanitization is part of the sending contract: do not |
| 37 | + * move it to the receiver. |
| 38 | + */ |
| 39 | + |
| 40 | +/** PostgreSQL `bigint` columns surfaced to JS as `number`. */ |
| 41 | +const bigintAsNumber = z.number().int().safe(); |
| 42 | + |
| 43 | +const CoreUsageSchema = z.object({ |
| 44 | + id: z.string().uuid(), |
| 45 | + kilo_user_id: z.string(), |
| 46 | + cost: bigintAsNumber, |
| 47 | + input_tokens: bigintAsNumber, |
| 48 | + output_tokens: bigintAsNumber, |
| 49 | + cache_write_tokens: bigintAsNumber, |
| 50 | + cache_hit_tokens: bigintAsNumber, |
| 51 | + created_at: z.string().datetime(), |
| 52 | + provider: z.string().nullable(), |
| 53 | + model: z.string().nullable(), |
| 54 | + requested_model: z.string().nullable(), |
| 55 | + cache_discount: bigintAsNumber.nullable(), |
| 56 | + has_error: z.boolean(), |
| 57 | + abuse_classification: z.nativeEnum(ABUSE_CLASSIFICATION), |
| 58 | + organization_id: z.string().uuid().nullable(), |
| 59 | + inference_provider: z.string().nullable(), |
| 60 | + project_id: z.string().nullable(), |
| 61 | +}); |
| 62 | + |
| 63 | +const UsageMetadataSchema = z.object({ |
| 64 | + id: z.string(), |
| 65 | + message_id: z.string(), |
| 66 | + created_at: z.string().datetime(), |
| 67 | + http_x_forwarded_for: z.string().nullable(), |
| 68 | + http_x_vercel_ip_city: z.string().nullable(), |
| 69 | + http_x_vercel_ip_country: z.string().nullable(), |
| 70 | + http_x_vercel_ip_latitude: z.number().nullable(), |
| 71 | + http_x_vercel_ip_longitude: z.number().nullable(), |
| 72 | + http_x_vercel_ja4_digest: z.string().nullable(), |
| 73 | + user_prompt_prefix: z.string().nullable(), |
| 74 | + system_prompt_prefix: z.string().nullable(), |
| 75 | + system_prompt_length: z.number().int().nullable(), |
| 76 | + http_user_agent: z.string().nullable(), |
| 77 | + max_tokens: z.number().int().nullable(), |
| 78 | + has_middle_out_transform: z.boolean().nullable(), |
| 79 | + status_code: z.number().int().nullable(), |
| 80 | + upstream_id: z.string().nullable(), |
| 81 | + finish_reason: z.string().nullable(), |
| 82 | + latency: z.number().nullable(), |
| 83 | + moderation_latency: z.number().nullable(), |
| 84 | + generation_time: z.number().nullable(), |
| 85 | + is_byok: z.boolean().nullable(), |
| 86 | + is_user_byok: z.boolean(), |
| 87 | + streamed: z.boolean().nullable(), |
| 88 | + cancelled: z.boolean().nullable(), |
| 89 | + editor_name: z.string().nullable(), |
| 90 | + api_kind: GatewayApiKindSchema.nullable(), |
| 91 | + has_tools: z.boolean().nullable(), |
| 92 | + machine_id: z.string().nullable(), |
| 93 | + feature: z.string().nullable(), |
| 94 | + session_id: z.string().nullable(), |
| 95 | + mode: z.string().nullable(), |
| 96 | + auto_model: z.string().nullable(), |
| 97 | + // Like bouncer_usage_event, older gateway senders omit this additive field. |
| 98 | + // Default it to null so parsed metadata still satisfies UsageMetaData. |
| 99 | + reasoning_setting: z.string().nullable().default(null), |
| 100 | + market_cost: z.number().nullable(), |
| 101 | + is_free: z.boolean().nullable(), |
| 102 | + abuse_delay: z.number().nullable(), |
| 103 | + abuse_downgraded_from: z.string().nullable(), |
| 104 | +}); |
| 105 | + |
| 106 | +/** |
| 107 | + * The Bouncer usage event to enqueue in the usage-write transaction, for a request whose decide |
| 108 | + * verdict said `spendWatch`. `payload` is the shaped usage-event wire body; the outbox row's owner |
| 109 | + * is `core.kilo_user_id`. |
| 110 | + */ |
| 111 | +export const BouncerUsageEventEnqueueSchema = z.object({ |
| 112 | + request_id: z.string().min(1), |
| 113 | + payload: z.record(z.string(), z.unknown()), |
| 114 | +}); |
| 115 | + |
| 116 | +export type BouncerUsageEventEnqueue = z.infer<typeof BouncerUsageEventEnqueueSchema>; |
| 117 | + |
| 118 | +export const UsageRecordRequestSchema = z.object({ |
| 119 | + core: CoreUsageSchema, |
| 120 | + metadata: UsageMetadataSchema, |
| 121 | + prior_microdollar_usage: z.number(), |
| 122 | + posthog_distinct_id: z.string().nullable(), |
| 123 | + // Optional, unlike the fields above: a sender from before this field existed omits it, and that |
| 124 | + // must still record the billing row. Null or absent means no outbox row. |
| 125 | + bouncer_usage_event: BouncerUsageEventEnqueueSchema.nullable().optional(), |
| 126 | +}); |
| 127 | + |
| 128 | +export type UsageRecordRequest = z.infer<typeof UsageRecordRequestSchema>; |
| 129 | + |
| 130 | +/** |
| 131 | + * `duplicate` means the usage row already existed, so this delivery was a retry |
| 132 | + * of a call that had already committed. Callers must treat it as success: the |
| 133 | + * row is persisted and its post-commit side effects ran on the first delivery. |
| 134 | + * |
| 135 | + * `not_recorded` mirrors today's local behaviour where `insertUsageRecord` |
| 136 | + * swallows database errors and returns `null`. |
| 137 | + */ |
| 138 | +export const UsageRecordResponseSchema = z.object({ |
| 139 | + status: z.enum(['recorded', 'duplicate', 'not_recorded']), |
| 140 | + result: z |
| 141 | + .object({ |
| 142 | + usageId: z.string(), |
| 143 | + createdAt: z.string(), |
| 144 | + newMicrodollarsUsed: z.number().nullable(), |
| 145 | + }) |
| 146 | + .nullable(), |
| 147 | +}); |
| 148 | + |
| 149 | +export type UsageRecordResponse = z.infer<typeof UsageRecordResponseSchema>; |
0 commit comments