-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathschema.ts
More file actions
3627 lines (3348 loc) · 135 KB
/
schema.ts
File metadata and controls
3627 lines (3348 loc) · 135 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
pgTable,
pgView,
bigint,
index,
uuid,
date,
boolean,
text,
timestamp,
jsonb,
unique,
real,
integer,
uniqueIndex,
foreignKey,
smallint,
check,
primaryKey,
decimal,
serial,
vector,
type AnyPgColumn,
bigserial,
} from 'drizzle-orm/pg-core';
import { isNotNull, isNull, sql } from 'drizzle-orm';
import * as z from 'zod';
import {
KiloPassTier,
KiloPassCadence,
KiloPassIssuanceSource,
KiloPassIssuanceItemKind,
KiloPassAuditLogAction,
KiloPassAuditLogResult,
KiloPassScheduledChangeStatus,
FeedbackFor,
FeedbackSource,
CliSessionSharedState,
SecurityAuditLogAction,
KiloClawPlan,
KiloClawScheduledPlan,
KiloClawScheduledBy,
KiloClawSubscriptionStatus,
KiloClawPaymentSource,
} from './schema-types';
import type { KiloClawAdminAuditAction } from './schema-types';
import type {
OrganizationModeConfig,
OrganizationPlan,
OrganizationRole,
OrganizationSettings,
AuditLogAction,
EncryptedData,
AuthProviderId,
AbuseClassification,
PlatformRepository,
IntegrationPermissions,
BuildStatus,
Provider,
CodeReviewAgentConfig,
DependabotAlertRaw,
SecurityFindingAnalysis,
NormalizedOpenRouterResponse,
OpenRouterModel,
StripeSubscriptionStatus,
OpenCodeSettings,
StoredModel,
CustomLlmExtraBody,
CustomLlmExtraHeaders,
CustomLlmProvider,
InterleavedFormat,
GatewayApiKind,
} from './schema-types';
import type { AnyPgColumn as DrizzleAnyPgColumn } from 'drizzle-orm/pg-core';
/**
* Generates a complete check constraint for an enum column.
* This ensures the column value is one of the enum values.
*
* IMPORTANT: If you add/remove values from any enum used here, you MUST generate a migration.
* See src/db/schema.test.ts for the test that enforces this.
*
* @param name - The name of the check constraint
* @param column - The column to check
* @param enumObj - The enum object containing the allowed values
* @returns Complete check constraint ready to use in table definition
*/
export function enumCheck<T extends Record<string, string>>(
name: string,
column: DrizzleAnyPgColumn,
enumObj: T
) {
return check(
name,
sql`${column} IN (${sql.join(
Object.values(enumObj).map(v => sql.raw(`'${v}'`)),
sql.raw(', ')
)})`
);
}
export const SCHEMA_CHECK_ENUMS = {
KiloPassTier,
KiloPassCadence,
KiloPassIssuanceSource,
KiloPassIssuanceItemKind,
KiloPassAuditLogAction,
KiloPassAuditLogResult,
KiloPassScheduledChangeStatus,
CliSessionSharedState,
SecurityAuditLogAction,
KiloClawPlan,
KiloClawScheduledPlan,
KiloClawScheduledBy,
KiloClawSubscriptionStatus,
} as const;
export const credit_transactions = pgTable(
'credit_transactions',
{
id: uuid()
.default(sql`pg_catalog.gen_random_uuid()`)
.primaryKey()
.notNull(),
kilo_user_id: text().notNull(),
amount_microdollars: bigint({ mode: 'number' }).notNull(),
expiration_baseline_microdollars_used: bigint({ mode: 'number' }),
original_baseline_microdollars_used: bigint({ mode: 'number' }),
is_free: boolean().notNull(),
description: text(),
original_transaction_id: uuid(), // Links expiration records to their original credit transaction
stripe_payment_id: text(),
coinbase_credit_block_id: text(),
credit_category: text(),
expiry_date: timestamp({ withTimezone: true, mode: 'string' }),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
organization_id: uuid(),
check_category_uniqueness: boolean().notNull().default(false),
},
table => [
index('IDX_credit_transactions_created_at').on(table.created_at),
index('IDX_credit_transactions_is_free').on(table.is_free),
index('IDX_credit_transactions_kilo_user_id').on(table.kilo_user_id),
index('IDX_credit_transactions_credit_category').on(table.credit_category),
uniqueIndex('IDX_credit_transactions_stripe_payment_id').on(table.stripe_payment_id),
uniqueIndex('IDX_credit_transactions_original_transaction_id').on(
table.original_transaction_id
),
uniqueIndex('IDX_credit_transactions_coinbase_credit_block_id').on(
table.coinbase_credit_block_id
),
index('IDX_credit_transactions_organization_id').on(table.organization_id),
uniqueIndex('IDX_credit_transactions_unique_category')
.on(table.kilo_user_id, table.credit_category)
.where(sql`${table.check_category_uniqueness} = TRUE`),
]
);
export type CreditTransaction = typeof credit_transactions.$inferSelect;
/**
* When adding or removing PII/account-linked columns, update
* softDeleteUser() in src/lib/user.ts (and src/lib/user.test.ts) to
* null or reset the field.
*/
export const kilocode_users = pgTable(
'kilocode_users',
{
id: text().primaryKey().notNull(),
google_user_email: text().notNull(),
google_user_name: text().notNull(),
google_user_image_url: text().notNull(),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
updated_at: timestamp({ withTimezone: true, mode: 'string' })
.defaultNow()
.notNull()
.$onUpdateFn(() => sql`now()`),
hosted_domain: text(),
microdollars_used: bigint({ mode: 'number' })
.default(sql`'0'`)
.notNull(),
/**
* If set, bonus credits are issued on usage once `microdollars_used` crosses this threshold.
* For Kilo Pass we currently treat it as "earned" slightly early (threshold - $1) when checking.
*/
kilo_pass_threshold: bigint({ mode: 'number' }),
stripe_customer_id: text().notNull(),
is_admin: boolean().default(false).notNull(),
total_microdollars_acquired: bigint({ mode: 'number' })
.default(sql`'0'`)
.notNull(),
next_credit_expiration_at: timestamp({
withTimezone: true,
mode: 'string',
}),
has_validation_stytch: boolean(),
has_validation_novel_card_with_hold: boolean().default(false).notNull(),
blocked_reason: text(),
api_token_pepper: text(),
auto_top_up_enabled: boolean().default(false).notNull(),
is_bot: boolean().default(false).notNull(),
/** @deprecated */
default_model: text(),
cohorts: jsonb().$type<Record<string, number>>().default({}).notNull(),
completed_welcome_form: boolean().default(false).notNull(),
linkedin_url: text(),
github_url: text(),
discord_server_membership_verified_at: timestamp({ withTimezone: true, mode: 'string' }),
openrouter_upstream_safety_identifier: text(),
customer_source: text(),
},
table => [
unique('UQ_b1afacbcf43f2c7c4cb9f7e7faa').on(table.google_user_email),
// Prevent empty strings
check('blocked_reason_not_empty', sql`length(blocked_reason) > 0`),
uniqueIndex('UQ_kilocode_users_openrouter_upstream_safety_identifier')
.on(table.openrouter_upstream_safety_identifier)
.where(sql`${table.openrouter_upstream_safety_identifier} IS NOT NULL`),
]
);
export type User = typeof kilocode_users.$inferSelect;
export const kilo_pass_subscriptions = pgTable(
'kilo_pass_subscriptions',
{
id: uuid()
.default(sql`pg_catalog.gen_random_uuid()`)
.primaryKey(),
kilo_user_id: text()
.notNull()
.references(() => kilocode_users.id, { onDelete: 'cascade', onUpdate: 'cascade' }),
stripe_subscription_id: text().notNull().unique(),
tier: text().notNull().$type<KiloPassTier>(),
cadence: text().notNull().$type<KiloPassCadence>(),
status: text().notNull().$type<StripeSubscriptionStatus>(),
/**
* Tracks whether the subscription is set to cancel at the end of the current billing period.
* When true with status='active', the subscription is effectively "pending cancellation".
*/
cancel_at_period_end: boolean().notNull().default(false),
started_at: timestamp({ withTimezone: true, mode: 'string' }),
ended_at: timestamp({ withTimezone: true, mode: 'string' }),
current_streak_months: integer().notNull().default(0),
/**
* Used to track the next eligible monthly bonus period for yearly Kilo Pass subscriptions.
*
* Bonus credits are now issued on usage (when a user crosses `kilocode_users.kilo_pass_threshold`),
* but we still need a per-subscription month boundary for yearly cadence.
*/
next_yearly_issue_at: timestamp({ withTimezone: true, mode: 'string' }),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
updated_at: timestamp({ withTimezone: true, mode: 'string' })
.defaultNow()
.notNull()
.$onUpdateFn(() => sql`now()`),
},
table => [
index('IDX_kilo_pass_subscriptions_kilo_user_id').on(table.kilo_user_id),
index('IDX_kilo_pass_subscriptions_status').on(table.status),
index('IDX_kilo_pass_subscriptions_cadence').on(table.cadence),
check(
'kilo_pass_subscriptions_current_streak_months_non_negative_check',
sql`${table.current_streak_months} >= 0`
),
enumCheck('kilo_pass_subscriptions_tier_check', table.tier, KiloPassTier),
enumCheck('kilo_pass_subscriptions_cadence_check', table.cadence, KiloPassCadence),
]
);
export type KiloPassSubscription = typeof kilo_pass_subscriptions.$inferSelect;
export type NewKiloPassSubscription = typeof kilo_pass_subscriptions.$inferInsert;
export const kilo_pass_issuances = pgTable(
'kilo_pass_issuances',
{
id: uuid()
.default(sql`pg_catalog.gen_random_uuid()`)
.primaryKey()
.notNull(),
kilo_pass_subscription_id: uuid()
.notNull()
.references(() => kilo_pass_subscriptions.id, { onDelete: 'cascade', onUpdate: 'cascade' }),
issue_month: date().notNull(),
source: text().notNull().$type<KiloPassIssuanceSource>(),
stripe_invoice_id: text(),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
updated_at: timestamp({ withTimezone: true, mode: 'string' })
.defaultNow()
.notNull()
.$onUpdateFn(() => sql`now()`),
},
table => [
unique('UQ_kilo_pass_issuances_subscription_issue_month').on(
table.kilo_pass_subscription_id,
table.issue_month
),
uniqueIndex('UQ_kilo_pass_issuances_stripe_invoice_id')
.on(table.stripe_invoice_id)
.where(sql`${table.stripe_invoice_id} IS NOT NULL`),
index('IDX_kilo_pass_issuances_subscription_id').on(table.kilo_pass_subscription_id),
index('IDX_kilo_pass_issuances_issue_month').on(table.issue_month),
check(
'kilo_pass_issuances_issue_month_day_one_check',
sql`EXTRACT(DAY FROM ${table.issue_month}) = 1`
),
enumCheck('kilo_pass_issuances_source_check', table.source, KiloPassIssuanceSource),
]
);
export type KiloPassIssuance = typeof kilo_pass_issuances.$inferSelect;
export type NewKiloPassIssuance = typeof kilo_pass_issuances.$inferInsert;
export const kilo_pass_issuance_items = pgTable(
'kilo_pass_issuance_items',
{
id: uuid()
.default(sql`pg_catalog.gen_random_uuid()`)
.primaryKey()
.notNull(),
kilo_pass_issuance_id: uuid()
.notNull()
.references(() => kilo_pass_issuances.id, { onDelete: 'cascade', onUpdate: 'cascade' }),
kind: text().notNull().$type<KiloPassIssuanceItemKind>(),
credit_transaction_id: uuid()
.notNull()
.unique()
.references(() => credit_transactions.id, { onDelete: 'restrict', onUpdate: 'cascade' }),
amount_usd: decimal({ precision: 12, scale: 2, mode: 'number' }).notNull(),
bonus_percent_applied: decimal({ precision: 6, scale: 4, mode: 'number' }),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
updated_at: timestamp({ withTimezone: true, mode: 'string' })
.defaultNow()
.notNull()
.$onUpdateFn(() => sql`now()`),
},
table => [
unique('UQ_kilo_pass_issuance_items_issuance_kind').on(table.kilo_pass_issuance_id, table.kind),
index('IDX_kilo_pass_issuance_items_issuance_id').on(table.kilo_pass_issuance_id),
index('IDX_kilo_pass_issuance_items_credit_transaction_id').on(table.credit_transaction_id),
check(
'kilo_pass_issuance_items_bonus_percent_applied_range_check',
sql`${table.bonus_percent_applied} IS NULL OR (${table.bonus_percent_applied} >= 0 AND ${table.bonus_percent_applied} <= 1)`
),
check('kilo_pass_issuance_items_amount_usd_non_negative_check', sql`${table.amount_usd} >= 0`),
enumCheck('kilo_pass_issuance_items_kind_check', table.kind, KiloPassIssuanceItemKind),
]
);
export type KiloPassIssuanceItem = typeof kilo_pass_issuance_items.$inferSelect;
export type NewKiloPassIssuanceItem = typeof kilo_pass_issuance_items.$inferInsert;
export const kilo_pass_audit_log = pgTable(
'kilo_pass_audit_log',
{
id: uuid()
.default(sql`pg_catalog.gen_random_uuid()`)
.primaryKey()
.notNull(),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
kilo_user_id: text().references(() => kilocode_users.id, {
onDelete: 'set null',
onUpdate: 'cascade',
}),
kilo_pass_subscription_id: uuid().references(() => kilo_pass_subscriptions.id, {
onDelete: 'set null',
onUpdate: 'cascade',
}),
action: text().notNull().$type<KiloPassAuditLogAction>(),
result: text().notNull().$type<KiloPassAuditLogResult>(),
idempotency_key: text(),
stripe_event_id: text(),
stripe_invoice_id: text(),
stripe_subscription_id: text(),
related_credit_transaction_id: uuid().references(() => credit_transactions.id, {
onDelete: 'set null',
onUpdate: 'cascade',
}),
related_monthly_issuance_id: uuid().references(() => kilo_pass_issuances.id, {
onDelete: 'set null',
onUpdate: 'cascade',
}),
payload_json: jsonb().$type<Record<string, unknown>>().notNull().default({}),
},
table => [
index('IDX_kilo_pass_audit_log_created_at').on(table.created_at),
index('IDX_kilo_pass_audit_log_kilo_user_id').on(table.kilo_user_id),
index('IDX_kilo_pass_audit_log_kilo_pass_subscription_id').on(table.kilo_pass_subscription_id),
index('IDX_kilo_pass_audit_log_action').on(table.action),
index('IDX_kilo_pass_audit_log_result').on(table.result),
index('IDX_kilo_pass_audit_log_idempotency_key').on(table.idempotency_key),
index('IDX_kilo_pass_audit_log_stripe_event_id').on(table.stripe_event_id),
index('IDX_kilo_pass_audit_log_stripe_invoice_id').on(table.stripe_invoice_id),
index('IDX_kilo_pass_audit_log_stripe_subscription_id').on(table.stripe_subscription_id),
index('IDX_kilo_pass_audit_log_related_credit_transaction_id').on(
table.related_credit_transaction_id
),
index('IDX_kilo_pass_audit_log_related_monthly_issuance_id').on(
table.related_monthly_issuance_id
),
enumCheck('kilo_pass_audit_log_action_check', table.action, KiloPassAuditLogAction),
enumCheck('kilo_pass_audit_log_result_check', table.result, KiloPassAuditLogResult),
]
);
export type KiloPassAuditLogEntry = typeof kilo_pass_audit_log.$inferSelect;
export type NewKiloPassAuditLogEntry = typeof kilo_pass_audit_log.$inferInsert;
export const kilo_pass_scheduled_changes = pgTable(
'kilo_pass_scheduled_changes',
{
id: uuid()
.default(sql`pg_catalog.gen_random_uuid()`)
.primaryKey(),
kilo_user_id: text()
.notNull()
.references(() => kilocode_users.id, { onDelete: 'cascade', onUpdate: 'cascade' }),
stripe_subscription_id: text()
.notNull()
.references(() => kilo_pass_subscriptions.stripe_subscription_id, {
onDelete: 'cascade',
onUpdate: 'cascade',
}),
from_tier: text().notNull().$type<KiloPassTier>(),
from_cadence: text().notNull().$type<KiloPassCadence>(),
to_tier: text().notNull().$type<KiloPassTier>(),
to_cadence: text().notNull().$type<KiloPassCadence>(),
stripe_schedule_id: text().notNull(),
effective_at: timestamp({ withTimezone: true, mode: 'string' }).notNull(),
status: text().notNull().$type<KiloPassScheduledChangeStatus>(),
deleted_at: timestamp({ withTimezone: true, mode: 'string' }),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
updated_at: timestamp({ withTimezone: true, mode: 'string' })
.defaultNow()
.notNull()
.$onUpdateFn(() => sql`now()`),
},
table => [
index('IDX_kilo_pass_scheduled_changes_kilo_user_id').on(table.kilo_user_id),
index('IDX_kilo_pass_scheduled_changes_status').on(table.status),
index('IDX_kilo_pass_scheduled_changes_stripe_subscription_id').on(
table.stripe_subscription_id
),
// Only one active (non-deleted) scheduled change is allowed per subscription.
// NOTE: This is a partial unique index; we keep historical rows after soft deletion.
uniqueIndex('UQ_kilo_pass_scheduled_changes_active_stripe_subscription_id')
.on(table.stripe_subscription_id)
.where(isNull(table.deleted_at)),
index('IDX_kilo_pass_scheduled_changes_effective_at').on(table.effective_at),
index('IDX_kilo_pass_scheduled_changes_deleted_at').on(table.deleted_at),
enumCheck('kilo_pass_scheduled_changes_from_tier_check', table.from_tier, KiloPassTier),
enumCheck(
'kilo_pass_scheduled_changes_from_cadence_check',
table.from_cadence,
KiloPassCadence
),
enumCheck('kilo_pass_scheduled_changes_to_tier_check', table.to_tier, KiloPassTier),
enumCheck('kilo_pass_scheduled_changes_to_cadence_check', table.to_cadence, KiloPassCadence),
enumCheck(
'kilo_pass_scheduled_changes_status_check',
table.status,
KiloPassScheduledChangeStatus
),
]
);
export type KiloPassScheduledChange = typeof kilo_pass_scheduled_changes.$inferSelect;
export type NewKiloPassScheduledChange = typeof kilo_pass_scheduled_changes.$inferInsert;
export const auto_top_up_configs = pgTable(
'auto_top_up_configs',
{
id: uuid()
.default(sql`pg_catalog.gen_random_uuid()`)
.primaryKey()
.notNull(),
owned_by_user_id: text().references(() => kilocode_users.id, {
onDelete: 'cascade',
onUpdate: 'cascade',
}),
owned_by_organization_id: uuid().references(() => organizations.id, {
onDelete: 'cascade',
onUpdate: 'cascade',
}),
created_by_user_id: text(), // Audit trail: null for user-owned, set for org-owned
stripe_payment_method_id: text().notNull(),
amount_cents: integer().notNull().default(5000), // Default $50, options: 2000, 5000, 10000
last_auto_top_up_at: timestamp({ withTimezone: true, mode: 'string' }),
attempt_started_at: timestamp({ withTimezone: true, mode: 'string' }),
disabled_reason: text(),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
updated_at: timestamp({ withTimezone: true, mode: 'string' })
.defaultNow()
.notNull()
.$onUpdateFn(() => sql`now()`),
},
table => [
uniqueIndex('UQ_auto_top_up_configs_owned_by_user_id')
.on(table.owned_by_user_id)
.where(sql`${table.owned_by_user_id} IS NOT NULL`),
uniqueIndex('UQ_auto_top_up_configs_owned_by_organization_id')
.on(table.owned_by_organization_id)
.where(sql`${table.owned_by_organization_id} IS NOT NULL`),
check(
'auto_top_up_configs_exactly_one_owner',
sql`(${table.owned_by_user_id} IS NOT NULL AND ${table.owned_by_organization_id} IS NULL) OR (${table.owned_by_user_id} IS NULL AND ${table.owned_by_organization_id} IS NOT NULL)`
),
]
);
export type AutoTopUpConfig = typeof auto_top_up_configs.$inferSelect;
export const user_auth_provider = pgTable(
'user_auth_provider',
{
kilo_user_id: text().notNull(),
provider: text().notNull().$type<AuthProviderId>(),
provider_account_id: text().notNull(),
email: text().notNull(),
avatar_url: text().notNull(),
display_name: text(),
hosted_domain: text(),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
},
table => [
primaryKey({ columns: [table.provider, table.provider_account_id] }),
index('IDX_user_auth_provider_kilo_user_id').on(table.kilo_user_id),
index('IDX_user_auth_provider_hosted_domain').on(table.hosted_domain),
]
);
export type PaymentMethod = typeof payment_methods.$inferSelect;
export const payment_methods = pgTable(
'payment_methods',
{
id: uuid()
.default(sql`pg_catalog.gen_random_uuid()`)
.primaryKey()
.notNull(),
stripe_fingerprint: text(),
user_id: text().notNull(),
stripe_id: text().notNull(),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
updated_at: timestamp({ withTimezone: true, mode: 'string' })
.defaultNow()
.notNull()
.$onUpdateFn(() => sql`now()`),
last4: text(),
brand: text(),
address_line1: text(),
address_line2: text(),
address_city: text(),
address_state: text(),
address_zip: text(),
address_country: text(),
name: text(),
three_d_secure_supported: boolean(),
funding: text(),
regulated_status: text(),
address_line1_check_status: text(),
postal_code_check_status: text(),
http_x_forwarded_for: text(),
http_x_vercel_ip_city: text(),
http_x_vercel_ip_country: text(),
http_x_vercel_ip_latitude: real(),
http_x_vercel_ip_longitude: real(),
http_x_vercel_ja4_digest: text(),
eligible_for_free_credits: boolean().default(false).notNull(),
deleted_at: timestamp({ withTimezone: true, mode: 'string' }),
stripe_data: jsonb(),
type: text(),
organization_id: uuid(),
},
table => [
index('IDX_d7d7fb15569674aaadcfbc0428').on(table.user_id),
index('IDX_e1feb919d0ab8a36381d5d5138').on(table.stripe_fingerprint),
unique('UQ_29df1b0403df5792c96bbbfdbe6').on(table.user_id, table.stripe_id),
index('IDX_payment_methods_organization_id').on(table.organization_id),
]
);
export type MicrodollarUsage = typeof microdollar_usage.$inferSelect;
export const microdollar_usage = pgTable(
'microdollar_usage',
{
id: uuid()
.notNull()
.default(sql`pg_catalog.gen_random_uuid()`)
.primaryKey(),
kilo_user_id: text().notNull(),
cost: bigint({ mode: 'number' }).notNull(),
input_tokens: bigint({ mode: 'number' }).notNull(),
output_tokens: bigint({ mode: 'number' }).notNull(),
cache_write_tokens: bigint({ mode: 'number' }).notNull(),
cache_hit_tokens: bigint({ mode: 'number' }).notNull(),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
provider: text(),
model: text(),
requested_model: text(),
cache_discount: bigint({ mode: 'number' }),
has_error: boolean().default(false).notNull(),
// Abuse classification: positive = abuse, negative = not abuse, 0 = not yet classified
abuse_classification: smallint().default(0).notNull().$type<AbuseClassification>(),
organization_id: uuid(),
inference_provider: text(),
project_id: text(),
},
table => [
index('idx_created_at').on(table.created_at),
index('idx_abuse_classification').on(table.abuse_classification),
index('idx_kilo_user_id_created_at2').on(table.kilo_user_id, table.created_at),
index('idx_microdollar_usage_organization_id')
.on(table.organization_id)
.where(isNotNull(table.organization_id)),
]
);
export const microdollar_usage_metadata = pgTable(
'microdollar_usage_metadata',
{
id: uuid().notNull().primaryKey(),
created_at: timestamp({ withTimezone: true, mode: 'string' }),
message_id: text().notNull(),
http_user_agent_id: integer().references(() => http_user_agent.http_user_agent_id),
http_ip_id: integer().references(() => http_ip.http_ip_id),
vercel_ip_city_id: integer().references(() => vercel_ip_city.vercel_ip_city_id),
vercel_ip_country_id: integer().references(() => vercel_ip_country.vercel_ip_country_id),
vercel_ip_latitude: real(),
vercel_ip_longitude: real(),
ja4_digest_id: integer().references(() => ja4_digest.ja4_digest_id),
user_prompt_prefix: text(),
system_prompt_prefix_id: integer().references(
() => system_prompt_prefix.system_prompt_prefix_id
),
system_prompt_length: integer(),
max_tokens: bigint({ mode: 'number' }),
has_middle_out_transform: boolean(),
status_code: smallint(),
upstream_id: text(),
finish_reason_id: integer(),
latency: real(),
moderation_latency: real(),
generation_time: real(),
is_byok: boolean(),
is_user_byok: boolean(),
streamed: boolean(),
cancelled: boolean(),
editor_name_id: integer(),
api_kind_id: integer(),
has_tools: boolean(),
machine_id: text(),
feature_id: integer(),
session_id: text(),
mode_id: integer(),
auto_model_id: integer(),
market_cost: bigint({ mode: 'number' }),
},
table => [index('idx_microdollar_usage_metadata_created_at').on(table.created_at)]
);
export const api_request_log = pgTable(
'api_request_log',
{
id: bigserial({ mode: 'bigint' }).notNull().primaryKey(),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
kilo_user_id: text(),
organization_id: text(),
provider: text(),
model: text(),
status_code: integer(),
request: jsonb(),
response: text(),
},
table => [index('idx_api_request_log_created_at').on(table.created_at)]
);
export const http_user_agent = pgTable(
'http_user_agent',
{
http_user_agent_id: serial().notNull().primaryKey(),
http_user_agent: text().notNull(),
},
table => [
uniqueIndex('UQ_http_user_agent').on(table.http_user_agent), // TODO include columns in migration!
]
);
export const http_ip = pgTable(
'http_ip',
{
http_ip_id: serial().notNull().primaryKey(),
http_ip: text().notNull(),
},
table => [
uniqueIndex('UQ_http_ip').on(table.http_ip), // TODO include columns in migration!
]
);
export const vercel_ip_country = pgTable(
'vercel_ip_country',
{
vercel_ip_country_id: serial().notNull().primaryKey(),
vercel_ip_country: text().notNull(),
},
table => [
uniqueIndex('UQ_vercel_ip_country').on(table.vercel_ip_country), // TODO include columns in migration!
]
);
export const vercel_ip_city = pgTable(
'vercel_ip_city',
{
vercel_ip_city_id: serial().notNull().primaryKey(),
vercel_ip_city: text().notNull(),
},
table => [
uniqueIndex('UQ_vercel_ip_city').on(table.vercel_ip_city), // TODO include columns in migration!
]
);
export const system_prompt_prefix = pgTable(
'system_prompt_prefix',
{
system_prompt_prefix_id: serial().notNull().primaryKey(),
system_prompt_prefix: text().notNull(),
},
table => [
uniqueIndex('UQ_system_prompt_prefix').on(table.system_prompt_prefix), // TODO include columns in migration!
]
);
export const ja4_digest = pgTable(
'ja4_digest',
{
ja4_digest_id: serial().notNull().primaryKey(),
ja4_digest: text().notNull(),
},
table => [
uniqueIndex('UQ_ja4_digest').on(table.ja4_digest), // TODO include columns in migration!
]
);
export const finish_reason = pgTable(
'finish_reason',
{
finish_reason_id: serial().notNull().primaryKey(),
finish_reason: text().notNull(),
},
table => [uniqueIndex('UQ_finish_reason').on(table.finish_reason)]
);
export const editor_name = pgTable(
'editor_name',
{
editor_name_id: serial().notNull().primaryKey(),
editor_name: text().notNull(),
},
table => [uniqueIndex('UQ_editor_name').on(table.editor_name)]
);
export const api_kind = pgTable(
'api_kind',
{
api_kind_id: serial().notNull().primaryKey(),
api_kind: text().notNull().$type<GatewayApiKind>(),
},
table => [uniqueIndex('UQ_api_kind').on(table.api_kind)]
);
export const feature = pgTable(
'feature',
{
feature_id: serial().notNull().primaryKey(),
feature: text().notNull(),
},
table => [uniqueIndex('UQ_feature').on(table.feature)]
);
export const mode = pgTable(
'mode',
{
mode_id: serial().notNull().primaryKey(),
mode: text().notNull(),
},
table => [uniqueIndex('UQ_mode').on(table.mode)]
);
export const auto_model = pgTable(
'auto_model',
{
auto_model_id: serial().notNull().primaryKey(),
auto_model: text().notNull(),
},
table => [uniqueIndex('UQ_auto_model').on(table.auto_model)]
);
export const microdollar_usage_view = pgView('microdollar_usage_view', {
id: uuid().notNull(),
kilo_user_id: text().notNull(),
message_id: text(),
cost: bigint({ mode: 'number' }).notNull(),
input_tokens: bigint({ mode: 'number' }).notNull(),
output_tokens: bigint({ mode: 'number' }).notNull(),
cache_write_tokens: bigint({ mode: 'number' }).notNull(),
cache_hit_tokens: bigint({ mode: 'number' }).notNull(),
created_at: timestamp({ withTimezone: true, mode: 'string' }).notNull(),
http_x_forwarded_for: text(),
http_x_vercel_ip_city: text(),
http_x_vercel_ip_country: text(),
http_x_vercel_ip_latitude: real(),
http_x_vercel_ip_longitude: real(),
http_x_vercel_ja4_digest: text(),
provider: text(),
model: text(),
requested_model: text(),
user_prompt_prefix: text(),
system_prompt_prefix: text(),
system_prompt_length: integer(),
http_user_agent: text(),
cache_discount: bigint({ mode: 'number' }),
max_tokens: bigint({ mode: 'number' }),
has_middle_out_transform: boolean(),
has_error: boolean().notNull(),
abuse_classification: smallint().notNull().$type<AbuseClassification>(),
organization_id: uuid(),
inference_provider: text(),
project_id: text(),
status_code: smallint(),
upstream_id: text(),
finish_reason: text(),
latency: real(),
moderation_latency: real(),
generation_time: real(),
is_byok: boolean(),
is_user_byok: boolean(),
streamed: boolean(),
cancelled: boolean(),
editor_name: text(),
api_kind: text().$type<GatewayApiKind>(),
has_tools: boolean(),
machine_id: text(),
feature: text(),
session_id: text(),
mode: text(),
auto_model: text(),
market_cost: bigint({ mode: 'number' }),
}).as(sql`
SELECT
mu.id,
mu.kilo_user_id,
meta.message_id,
mu.cost,
mu.input_tokens,
mu.output_tokens,
mu.cache_write_tokens,
mu.cache_hit_tokens,
mu.created_at,
ip.http_ip AS http_x_forwarded_for,
city.vercel_ip_city AS http_x_vercel_ip_city,
country.vercel_ip_country AS http_x_vercel_ip_country,
meta.vercel_ip_latitude AS http_x_vercel_ip_latitude,
meta.vercel_ip_longitude AS http_x_vercel_ip_longitude,
ja4.ja4_digest AS http_x_vercel_ja4_digest,
mu.provider,
mu.model,
mu.requested_model,
meta.user_prompt_prefix,
spp.system_prompt_prefix,
meta.system_prompt_length,
ua.http_user_agent,
mu.cache_discount,
meta.max_tokens,
meta.has_middle_out_transform,
mu.has_error,
mu.abuse_classification,
mu.organization_id,
mu.inference_provider,
mu.project_id,
meta.status_code,
meta.upstream_id,
frfr.finish_reason,
meta.latency,
meta.moderation_latency,
meta.generation_time,
meta.is_byok,
meta.is_user_byok,
meta.streamed,
meta.cancelled,
edit.editor_name,
ak.api_kind,
meta.has_tools,
meta.machine_id,
feat.feature,
meta.session_id,
md.mode,
am.auto_model,
meta.market_cost
FROM ${microdollar_usage} mu
LEFT JOIN ${microdollar_usage_metadata} meta ON mu.id = meta.id
LEFT JOIN ${http_ip} ip ON meta.http_ip_id = ip.http_ip_id
LEFT JOIN ${vercel_ip_city} city ON meta.vercel_ip_city_id = city.vercel_ip_city_id
LEFT JOIN ${vercel_ip_country} country ON meta.vercel_ip_country_id = country.vercel_ip_country_id
LEFT JOIN ${ja4_digest} ja4 ON meta.ja4_digest_id = ja4.ja4_digest_id
LEFT JOIN ${system_prompt_prefix} spp ON meta.system_prompt_prefix_id = spp.system_prompt_prefix_id
LEFT JOIN ${http_user_agent} ua ON meta.http_user_agent_id = ua.http_user_agent_id
LEFT JOIN ${finish_reason} frfr ON meta.finish_reason_id = frfr.finish_reason_id
LEFT JOIN ${editor_name} edit ON meta.editor_name_id = edit.editor_name_id
LEFT JOIN ${api_kind} ak ON meta.api_kind_id = ak.api_kind_id
LEFT JOIN ${feature} feat ON meta.feature_id = feat.feature_id
LEFT JOIN ${mode} md ON meta.mode_id = md.mode_id
LEFT JOIN ${auto_model} am ON meta.auto_model_id = am.auto_model_id
`);
export type MicrodollarUsageView = typeof microdollar_usage_view.$inferSelect;
export const custom_llm = pgTable('custom_llm', {
public_id: text().notNull().primaryKey(),
display_name: text().notNull(),
context_length: integer().notNull(),
max_completion_tokens: integer().notNull(),
internal_id: text().notNull(),
provider: text().notNull().$type<CustomLlmProvider>(),
base_url: text().notNull(),
api_key: text().notNull(),
organization_ids: jsonb().notNull().$type<string[]>(),
supports_image_input: boolean(),
force_reasoning: boolean(),
opencode_settings: jsonb().$type<OpenCodeSettings>(),
extra_body: jsonb().$type<CustomLlmExtraBody>(),
extra_headers: jsonb().$type<CustomLlmExtraHeaders>(),
interleaved_format: text().$type<InterleavedFormat>(),
});
export type CustomLlm = typeof custom_llm.$inferSelect;
export const user_admin_notes = pgTable(
'user_admin_notes',
{
id: uuid()
.default(sql`pg_catalog.gen_random_uuid()`)
.primaryKey()
.notNull(),
kilo_user_id: text().notNull(),
note_content: text().notNull(),
admin_kilo_user_id: text(),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
},
table => [
index('IDX_34517df0b385234babc38fe81b').on(table.admin_kilo_user_id),
index('IDX_ccbde98c4c14046daa5682ec4f').on(table.kilo_user_id),
index('IDX_d0270eb24ef6442d65a0b7853c').on(table.created_at),
]
);
export type UserAdminNote = typeof user_admin_notes.$inferSelect;
export const user_feedback = pgTable(
'user_feedback',
{
id: uuid()
.default(sql`pg_catalog.gen_random_uuid()`)
.primaryKey()
.notNull(),
kilo_user_id: text().references(() => kilocode_users.id, {
onDelete: 'set null',
onUpdate: 'cascade',
}),
feedback_text: text().notNull(),
feedback_for: text().notNull().default(FeedbackFor.Unknown),
feedback_batch: text(),
source: text().notNull().default(FeedbackSource.Unknown),
context_json: jsonb().$type<Record<string, unknown>>().notNull().default({}),
created_at: timestamp({ withTimezone: true, mode: 'string' }).defaultNow().notNull(),
},
table => [
index('IDX_user_feedback_created_at').on(table.created_at),
index('IDX_user_feedback_kilo_user_id').on(table.kilo_user_id),
index('IDX_user_feedback_feedback_for').on(table.feedback_for),
index('IDX_user_feedback_feedback_batch').on(table.feedback_batch),
index('IDX_user_feedback_source').on(table.source),
]
);
export type UserFeedback = typeof user_feedback.$inferSelect;
export type NewUserFeedback = typeof user_feedback.$inferInsert;
export const stytch_fingerprints = pgTable(
'stytch_fingerprints',
{
id: uuid()
.default(sql`pg_catalog.gen_random_uuid()`)
.primaryKey()
.notNull(),
kilo_user_id: text().notNull(),
visitor_fingerprint: text().notNull(),
browser_fingerprint: text().notNull(),
browser_id: text(),
hardware_fingerprint: text().notNull(),
network_fingerprint: text().notNull(),