Repository navigation
Expand file tree
/
Copy pathschema.ts
More file actions
4862 lines (4588 loc) · 198 KB
/
Copy pathschema.ts
File metadata and controls
4862 lines (4588 loc) · 198 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 { type SQL, sql } from 'drizzle-orm'
import {
type AnyPgColumn,
bigint,
boolean,
check,
customType,
decimal,
doublePrecision,
index,
integer,
json,
jsonb,
pgEnum,
pgTable,
primaryKey,
text,
timestamp,
uniqueIndex,
uuid,
vector,
} from 'drizzle-orm/pg-core'
import { DEFAULT_FREE_CREDITS, TAG_SLOTS } from './constants'
// Custom tsvector type for full-text search
export const tsvector = customType<{
data: string
}>({
dataType() {
return `tsvector`
},
})
/** Raw binary column. Postgres `bytea` ↔ Node `Buffer` (the pg driver handles the encoding). */
export const bytea = customType<{
data: Buffer
driverData: Buffer
}>({
dataType() {
return 'bytea'
},
})
export const user = pgTable('user', {
id: text('id').primaryKey(),
name: text('name').notNull(),
email: text('email').notNull().unique(),
normalizedEmail: text('normalized_email').unique(),
emailVerified: boolean('email_verified').notNull(),
image: text('image'),
createdAt: timestamp('created_at').notNull(),
updatedAt: timestamp('updated_at').notNull(),
stripeCustomerId: text('stripe_customer_id'),
role: text('role').default('user'),
banned: boolean('banned').default(false),
banReason: text('ban_reason'),
banExpires: timestamp('ban_expires'),
})
export const session = pgTable(
'session',
{
id: text('id').primaryKey(),
expiresAt: timestamp('expires_at').notNull(),
token: text('token').notNull().unique(),
createdAt: timestamp('created_at').notNull(),
updatedAt: timestamp('updated_at').notNull(),
ipAddress: text('ip_address'),
userAgent: text('user_agent'),
userId: text('user_id')
.notNull()
.references(() => user.id, { onDelete: 'cascade' }),
activeOrganizationId: text('active_organization_id').references(() => organization.id, {
onDelete: 'set null',
}),
impersonatedBy: text('impersonated_by'),
},
(table) => ({
userIdIdx: index('session_user_id_idx').on(table.userId),
tokenIdx: index('session_token_idx').on(table.token),
})
)
export const account = pgTable(
'account',
{
id: text('id').primaryKey(),
accountId: text('account_id').notNull(),
providerId: text('provider_id').notNull(),
userId: text('user_id')
.notNull()
.references(() => user.id, { onDelete: 'cascade' }),
accessToken: text('access_token'),
refreshToken: text('refresh_token'),
idToken: text('id_token'),
accessTokenExpiresAt: timestamp('access_token_expires_at'),
refreshTokenExpiresAt: timestamp('refresh_token_expires_at'),
scope: text('scope'),
password: text('password'),
createdAt: timestamp('created_at').notNull(),
updatedAt: timestamp('updated_at').notNull(),
},
(table) => ({
userIdIdx: index('account_user_id_idx').on(table.userId),
accountProviderIdx: index('idx_account_on_account_id_provider_id').on(
table.accountId,
table.providerId
),
})
)
export const verification = pgTable(
'verification',
{
id: text('id').primaryKey(),
identifier: text('identifier').notNull(),
value: text('value').notNull(),
expiresAt: timestamp('expires_at').notNull(),
createdAt: timestamp('created_at'),
updatedAt: timestamp('updated_at'),
},
(table) => ({
identifierIdx: index('verification_identifier_idx').on(table.identifier),
expiresAtIdx: index('verification_expires_at_idx').on(table.expiresAt),
})
)
export const folderResourceTypeEnum = pgEnum('folder_resource_type', [
'workflow',
'file',
'knowledge_base',
'table',
])
/**
* Generic folder hierarchy shared by workflows, files, knowledge bases, and tables.
* Supersedes the resource-specific `workflow_folder` and `workspace_file_folders` tables,
* dropped in migration 0276 once the cutover was verified against production.
*
* `resourceType` is a real `pgEnum` here — unlike `pinnedItem.resourceType` — because the
* set of folder-bearing resources is small and fixed. A folder may only parent a folder
* of the same `resourceType` in the same workspace; that invariant is enforced both in
* the application layer and by the `folder_parent_resource_type_match` trigger, since a
* plain FK cannot express it.
*
* `locked` carries over the existing workflow-folder lock feature verbatim. It is NOT
* extended to the other resource types — file/knowledge_base/table folders leave it at
* `false` and no lock cascade reads it for them. Dropping the column would regress
* shipped workflow-folder locking.
*
* `color` and `isExpanded` from the old `workflow_folder` table are intentionally not
* carried over:
* `color` has no UI consumer, and `isExpanded`'s real state lives client-side in the
* folders Zustand store and is never read back from the DB.
*/
export const folder = pgTable(
'folder',
{
id: text('id').primaryKey(),
resourceType: folderResourceTypeEnum('resource_type').notNull(),
name: text('name').notNull(),
userId: text('user_id')
.notNull()
.references(() => user.id, { onDelete: 'cascade' }),
workspaceId: text('workspace_id')
.notNull()
.references(() => workspace.id, { onDelete: 'cascade' }),
parentId: text('parent_id').references((): AnyPgColumn => folder.id, {
onDelete: 'set null',
}),
locked: boolean('locked').notNull().default(false),
sortOrder: integer('sort_order').notNull().default(0),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
deletedAt: timestamp('deleted_at'),
},
(table) => ({
userIdx: index('folder_user_idx').on(table.userId),
workspaceResourceParentIdx: index('folder_workspace_resource_parent_idx').on(
table.workspaceId,
table.resourceType,
table.parentId
),
parentSortIdx: index('folder_parent_sort_idx').on(table.parentId, table.sortOrder),
deletedAtIdx: index('folder_deleted_at_idx').on(table.deletedAt),
workspaceDeletedAtPartialIdx: index('folder_workspace_deleted_partial_idx')
.on(table.workspaceId, table.deletedAt)
.where(sql`${table.deletedAt} IS NOT NULL`),
/**
* Carries over the active-unique key the old `workspace_file_folders` table enforced,
* and extends it to workflow folders, which never had one — 0272's backfill deduplicated
* the 47 pre-existing violations it surfaced.
*/
workspaceResourceParentNameActiveUnique: uniqueIndex(
'folder_workspace_resource_parent_name_active_unique'
)
.on(table.workspaceId, table.resourceType, sql`coalesce(${table.parentId}, '')`, table.name)
.where(sql`${table.deletedAt} IS NULL`),
})
)
/**
* Per-user pinning of workspace resources. Polymorphic on `resourceType`, following
* the same shape as `publicShare.resourceType` below — deliberately plain `text`
* rather than a `pgEnum`, because the set of pinnable kinds is expected to grow
* (folders become pinnable alongside the generic-folder work) and widening a text
* column costs nothing where widening an enum needs a migration.
*
* Pins are per-user, not per-workspace: two members of the same workspace pin
* independently, which is why `userId` leads the unique index and every read path
* filters on the session user.
*/
export const pinnedItem = pgTable(
'pinned_item',
{
id: text('id').primaryKey(),
userId: text('user_id')
.notNull()
.references(() => user.id, { onDelete: 'cascade' }),
workspaceId: text('workspace_id')
.notNull()
.references(() => workspace.id, { onDelete: 'cascade' }),
resourceType: text('resource_type').notNull(), // 'workflow' | 'file' | 'knowledge_base' | 'table' | 'folder' | 'workspace'
resourceId: text('resource_id').notNull(),
pinnedAt: timestamp('pinned_at').notNull().defaultNow(),
},
(table) => ({
userWorkspaceIdx: index('pinned_item_user_workspace_idx').on(table.userId, table.workspaceId),
resourceIdx: index('pinned_item_resource_idx').on(table.resourceType, table.resourceId),
userResourceUnique: uniqueIndex('pinned_item_user_resource_unique').on(
table.userId,
table.resourceType,
table.resourceId
),
})
)
export const workflow = pgTable(
'workflow',
{
id: text('id').primaryKey(),
/**
* Creator and owner. Legitimate as ownership: it anchors personal
* (workspace-less) workflows, cascades the workflow away with the account,
* and names the owner for webhook config and deploy-as-block resolution.
*
* @deprecated As an execution identity. Do not use it to decide who a run
* acts as, what it may read, or what it may authorize. The acting principal
* is `ExecutionMetadata.userId`, which the principal layer
* (`resolvePrincipalAttribution`) resolves to the caller for a session,
* personal API key, or delegated run, and to the workspace billing account
* for a workspace API key, schedule, or webhook.
*
* Exactly one execution use survives, carried as
* `ExecutionMetadata.workflowUserId`: the personal-environment fallback in
* `executeWorkflowCore`, for runs with no identifiable caller — workspace
* API keys, schedules, webhooks, and unauthenticated public-API calls. Those
* have nobody to resolve personal variables as, and a deployed workflow is
* routinely authored against its owner's personal keys, so dropping the
* fallback would break them. Workspace variables never fall back here; they
* always authorize against the actor.
*/
userId: text('user_id')
.notNull()
.references(() => user.id, { onDelete: 'cascade' }),
workspaceId: text('workspace_id').references(() => workspace.id, { onDelete: 'cascade' }),
folderId: text('folder_id').references(() => folder.id, { onDelete: 'set null' }),
sortOrder: integer('sort_order').notNull().default(0),
name: text('name').notNull(),
description: text('description'),
lastSynced: timestamp('last_synced').notNull(),
createdAt: timestamp('created_at').notNull(),
updatedAt: timestamp('updated_at').notNull(),
isDeployed: boolean('is_deployed').notNull().default(false),
deployedAt: timestamp('deployed_at'),
isPublicApi: boolean('is_public_api').notNull().default(false),
locked: boolean('locked').notNull().default(false),
forkSyncExcluded: boolean('fork_sync_excluded').notNull().default(false),
runCount: integer('run_count').notNull().default(0),
lastRunAt: timestamp('last_run_at'),
variables: json('variables').default('{}'),
archivedAt: timestamp('archived_at'),
},
(table) => ({
userIdIdx: index('workflow_user_id_idx').on(table.userId),
workspaceIdIdx: index('workflow_workspace_id_idx').on(table.workspaceId),
userWorkspaceIdx: index('workflow_user_workspace_idx').on(table.userId, table.workspaceId),
workspaceFolderNameUnique: uniqueIndex('workflow_workspace_folder_name_active_unique')
.on(table.workspaceId, sql`coalesce(${table.folderId}, '')`, table.name)
.where(sql`${table.archivedAt} IS NULL`),
folderSortIdx: index('workflow_folder_sort_idx').on(table.folderId, table.sortOrder),
archivedAtIdx: index('workflow_archived_at_idx').on(table.archivedAt),
workspaceArchivedAtPartialIdx: index('workflow_workspace_archived_partial_idx')
.on(table.workspaceId, table.archivedAt)
.where(sql`${table.archivedAt} IS NOT NULL`),
})
)
export const workflowBlocks = pgTable(
'workflow_blocks',
{
id: text('id').primaryKey(),
workflowId: text('workflow_id')
.notNull()
.references(() => workflow.id, { onDelete: 'cascade' }),
type: text('type').notNull(), // 'starter', 'agent', 'api', 'function'
name: text('name').notNull(),
positionX: decimal('position_x').notNull(),
positionY: decimal('position_y').notNull(),
enabled: boolean('enabled').notNull().default(true),
horizontalHandles: boolean('horizontal_handles').notNull().default(true),
isWide: boolean('is_wide').notNull().default(false),
advancedMode: boolean('advanced_mode').notNull().default(false),
triggerMode: boolean('trigger_mode').notNull().default(false),
errorEnabled: boolean('error_enabled').notNull().default(false),
/** Opt-in {@link BlockRetryConfig}; NULL means the block never retries. */
retry: jsonb('retry'),
locked: boolean('locked').notNull().default(false),
height: decimal('height').notNull().default('0'),
subBlocks: jsonb('sub_blocks').notNull().default('{}'),
outputs: jsonb('outputs').notNull().default('{}'),
data: jsonb('data').default('{}'),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
},
(table) => ({
workflowIdIdx: index('workflow_blocks_workflow_id_idx').on(table.workflowId),
typeIdx: index('workflow_blocks_type_idx').on(table.type),
})
)
export const workflowEdges = pgTable(
'workflow_edges',
{
id: text('id').primaryKey(),
workflowId: text('workflow_id')
.notNull()
.references(() => workflow.id, { onDelete: 'cascade' }),
sourceBlockId: text('source_block_id')
.notNull()
.references(() => workflowBlocks.id, { onDelete: 'cascade' }),
targetBlockId: text('target_block_id')
.notNull()
.references(() => workflowBlocks.id, { onDelete: 'cascade' }),
sourceHandle: text('source_handle'),
targetHandle: text('target_handle'),
createdAt: timestamp('created_at').notNull().defaultNow(),
},
(table) => ({
workflowIdIdx: index('workflow_edges_workflow_id_idx').on(table.workflowId),
workflowSourceIdx: index('workflow_edges_workflow_source_idx').on(
table.workflowId,
table.sourceBlockId
),
workflowTargetIdx: index('workflow_edges_workflow_target_idx').on(
table.workflowId,
table.targetBlockId
),
})
)
export const workflowSubflows = pgTable(
'workflow_subflows',
{
id: text('id').primaryKey(),
workflowId: text('workflow_id')
.notNull()
.references(() => workflow.id, { onDelete: 'cascade' }),
type: text('type').notNull(), // 'loop' or 'parallel'
config: jsonb('config').notNull().default('{}'),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
},
(table) => ({
workflowIdIdx: index('workflow_subflows_workflow_id_idx').on(table.workflowId),
workflowTypeIdx: index('workflow_subflows_workflow_type_idx').on(table.workflowId, table.type),
})
)
export const waitlist = pgTable('waitlist', {
id: text('id').primaryKey(),
email: text('email').notNull().unique(),
status: text('status').notNull().default('pending'), // pending, approved, rejected
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
})
export const workflowExecutionSnapshots = pgTable(
'workflow_execution_snapshots',
{
id: text('id').primaryKey(),
workflowId: text('workflow_id').references(() => workflow.id, { onDelete: 'set null' }),
stateHash: text('state_hash').notNull(),
stateData: jsonb('state_data').notNull(),
createdAt: timestamp('created_at').notNull().defaultNow(),
},
(table) => ({
workflowIdIdx: index('workflow_snapshots_workflow_id_idx').on(table.workflowId),
stateHashIdx: index('workflow_snapshots_hash_idx').on(table.stateHash),
workflowHashUnique: uniqueIndex('workflow_snapshots_workflow_hash_idx').on(
table.workflowId,
table.stateHash
),
createdAtIdx: index('workflow_snapshots_created_at_idx').on(table.createdAt),
})
)
export const workflowExecutionLogs = pgTable(
'workflow_execution_logs',
{
id: text('id').primaryKey(),
workflowId: text('workflow_id').references(() => workflow.id, { onDelete: 'set null' }),
workspaceId: text('workspace_id')
.notNull()
.references(() => workspace.id, { onDelete: 'cascade' }),
executionId: text('execution_id').notNull(),
stateSnapshotId: text('state_snapshot_id')
.notNull()
.references(() => workflowExecutionSnapshots.id),
deploymentVersionId: text('deployment_version_id').references(
() => workflowDeploymentVersion.id,
{ onDelete: 'set null' }
),
level: text('level').notNull(), // 'info' | 'error'
/** See `PERSISTED_WORKFLOW_EXECUTION_STATUSES` in `apps/sim/lib/logs/types.ts`. */
status: text('status').notNull().default('running'),
trigger: text('trigger').notNull(), // 'api' | 'webhook' | 'schedule' | 'manual' | 'chat'
startedAt: timestamp('started_at').notNull(),
/** Absolute deadline for the current active attempt; cleared while paused or terminal. */
executionDeadlineAt: timestamp('execution_deadline_at'),
endedAt: timestamp('ended_at'),
/**
* Wall clock from `started_at` for a terminal row; for a `pending` (paused)
* row, the active duration recorded at the checkpoint, which excludes the
* time the run sits waiting. Resuming leaves that checkpoint value in place
* while the row accrues time again, so a `running` row's value is stale
* until the next terminal write recomputes it.
*/
totalDurationMs: integer('total_duration_ms'),
/**
* Heavy trace data (traceSpans, finalOutput, workflowInput, executionState)
* is externalized to object storage; this column then holds a slim payload:
* a `traceStoreRef` (__simLargeValueRef) pointer to the stored object plus
* inline markers (hasTraceSpans, traceSpanCount, environment, trigger,
* truncation flags). It also still holds the FULL payload inline for legacy
* / not-yet-backfilled rows, for the storage-write-failure fallback, and for
* job_execution_logs. Required — not droppable. Read it via
* `materializeExecutionData`, which resolves the pointer.
*/
executionData: jsonb('execution_data').notNull().default('{}'),
/** @deprecated Not written/read; cost lives in usage_log + the `cost_total` projection. Drop in a follow-up PR after the `cost_total` backfill. */
cost: jsonb('cost'),
// Faithful, write-once projection of the run's usage_log ledger sum (dollars).
// Backs list cost display/filter/sort without live aggregation; never an
// independently-computed value (cost_total == SUM(usage_log) for the run).
costTotal: decimal('cost_total'),
// Model names used by the run (incl. zero-cost/BYOK), for the v1 model filter.
modelsUsed: text('models_used').array(),
files: jsonb('files'), // File metadata for execution files
createdAt: timestamp('created_at').notNull().defaultNow(),
},
(table) => ({
workflowIdIdx: index('workflow_execution_logs_workflow_id_idx').on(table.workflowId),
stateSnapshotIdIdx: index('workflow_execution_logs_state_snapshot_id_idx').on(
table.stateSnapshotId
),
deploymentVersionIdIdx: index('workflow_execution_logs_deployment_version_id_idx').on(
table.deploymentVersionId
),
triggerIdx: index('workflow_execution_logs_trigger_idx').on(table.trigger),
levelIdx: index('workflow_execution_logs_level_idx').on(table.level),
startedAtIdx: index('workflow_execution_logs_started_at_idx').on(table.startedAt),
executionIdUnique: uniqueIndex('workflow_execution_logs_execution_id_unique').on(
table.executionId
),
workflowStartedAtIdx: index('workflow_execution_logs_workflow_started_at_idx').on(
table.workflowId,
table.startedAt
),
workspaceStartedAtIdx: index('workflow_execution_logs_workspace_started_at_idx').on(
table.workspaceId,
table.startedAt
),
workspaceStartedAtIdDescIdx: index(
'workflow_execution_logs_workspace_started_at_id_desc_idx'
).on(table.workspaceId, sql`${table.startedAt} DESC NULLS LAST`, sql`${table.id} DESC`),
workspaceCostTotalIdx: index('workflow_execution_logs_workspace_cost_total_idx').on(
table.workspaceId,
table.costTotal
),
modelsUsedIdx: index('workflow_execution_logs_models_used_idx').using('gin', table.modelsUsed),
workspaceEndedAtIdIdx: index('workflow_execution_logs_workspace_ended_at_id_idx').on(
table.workspaceId,
sql`date_trunc('milliseconds', ${table.endedAt})`,
table.id
),
runningStartedAtIdx: index('workflow_execution_logs_running_started_at_idx')
.on(table.startedAt)
.where(sql`status = 'running'`),
runningExecutionDeadlineIdx: index('workflow_execution_logs_running_deadline_idx')
.on(table.executionDeadlineAt)
.where(sql`${table.status} = 'running' AND ${table.executionDeadlineAt} IS NOT NULL`),
completedEndedAtIdx: index('workflow_execution_logs_completed_ended_at_idx')
.on(table.endedAt, table.workspaceId, table.executionId)
.where(
sql`${table.status} = 'completed' AND ${table.level} = 'info' AND ${table.endedAt} IS NOT NULL`
),
})
)
export const executionLargeValueReferenceSourceEnum = pgEnum(
'execution_large_value_reference_source',
['execution_log', 'paused_snapshot']
)
export const executionLargeValues = pgTable(
'execution_large_values',
{
key: text('key').primaryKey(),
workspaceId: text('workspace_id')
.notNull()
.references(() => workspace.id, { onDelete: 'cascade' }),
workflowId: text('workflow_id').references(() => workflow.id, { onDelete: 'set null' }),
ownerExecutionId: text('owner_execution_id').notNull(),
size: integer('size').notNull(),
createdAt: timestamp('created_at').notNull().defaultNow(),
deletedAt: timestamp('deleted_at'),
},
(table) => ({
ownerExecutionIdIdx: index('execution_large_values_owner_execution_id_idx').on(
table.ownerExecutionId
),
cleanupIdx: index('execution_large_values_cleanup_idx')
.on(table.workspaceId, table.createdAt, table.key)
.where(sql`${table.deletedAt} IS NULL`),
tombstoneCleanupIdx: index('execution_large_values_tombstone_cleanup_idx')
.on(table.workspaceId, table.deletedAt, table.key)
.where(sql`${table.deletedAt} IS NOT NULL`),
/**
* Backs the `ON DELETE SET NULL` referential trigger, which runs
* `UPDATE ... WHERE workflow_id = $1` once per deleted workflow row and
* would otherwise sequentially scan this table each time.
*/
workflowIdIdx: index('execution_large_values_workflow_id_idx').on(table.workflowId),
})
)
export const executionLargeValueReferences = pgTable(
'execution_large_value_references',
{
key: text('key').notNull(),
executionId: text('execution_id').notNull(),
source: executionLargeValueReferenceSourceEnum('source').notNull(),
workspaceId: text('workspace_id')
.notNull()
.references(() => workspace.id, { onDelete: 'cascade' }),
workflowId: text('workflow_id').references(() => workflow.id, { onDelete: 'set null' }),
createdAt: timestamp('created_at').notNull().defaultNow(),
},
(table) => ({
pk: primaryKey({ columns: [table.key, table.executionId, table.source] }),
workspaceExecutionSourceIdx: index(
'execution_large_value_references_workspace_execution_source_idx'
).on(table.workspaceId, table.executionId, table.source),
/** Backs the `ON DELETE SET NULL` referential trigger — see `executionLargeValues`. */
workflowIdIdx: index('execution_large_value_references_workflow_id_idx').on(table.workflowId),
})
)
export const executionLargeValueDependencies = pgTable(
'execution_large_value_dependencies',
{
parentKey: text('parent_key').notNull(),
childKey: text('child_key').notNull(),
workspaceId: text('workspace_id')
.notNull()
.references(() => workspace.id, { onDelete: 'cascade' }),
createdAt: timestamp('created_at').notNull().defaultNow(),
},
(table) => ({
pk: primaryKey({ columns: [table.parentKey, table.childKey] }),
workspaceParentKeyIdx: index('execution_large_value_dependencies_workspace_parent_key_idx').on(
table.workspaceId,
table.parentKey
),
workspaceChildKeyIdx: index('execution_large_value_dependencies_workspace_child_key_idx').on(
table.workspaceId,
table.childKey
),
})
)
export const pausedExecutions = pgTable(
'paused_executions',
{
id: text('id').primaryKey(),
workflowId: text('workflow_id')
.notNull()
.references(() => workflow.id, { onDelete: 'cascade' }),
executionId: text('execution_id').notNull(),
executionSnapshot: jsonb('execution_snapshot').notNull(),
pausePoints: jsonb('pause_points').notNull(),
totalPauseCount: integer('total_pause_count').notNull(),
resumedCount: integer('resumed_count').notNull().default(0),
automaticResumeRetryCount: integer('automatic_resume_retry_count').notNull().default(0),
status: text('status').notNull().default('paused'),
metadata: jsonb('metadata').notNull().default(sql`'{}'::jsonb`),
pausedAt: timestamp('paused_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
expiresAt: timestamp('expires_at'),
/** Earliest `resumeAt` across this row's time-based pause points. NULL for human-only pauses. */
nextResumeAt: timestamp('next_resume_at'),
},
(table) => ({
workflowIdx: index('paused_executions_workflow_id_idx').on(table.workflowId),
statusIdx: index('paused_executions_status_idx').on(table.status),
executionUnique: uniqueIndex('paused_executions_execution_id_unique').on(table.executionId),
nextResumeAtIdx: index('paused_executions_next_resume_at_idx')
.on(table.nextResumeAt)
.where(sql`status = 'paused' AND next_resume_at IS NOT NULL`),
})
)
export const resumeQueue = pgTable(
'resume_queue',
{
id: text('id').primaryKey(),
pausedExecutionId: text('paused_execution_id')
.notNull()
.references(() => pausedExecutions.id, { onDelete: 'cascade' }),
parentExecutionId: text('parent_execution_id').notNull(),
newExecutionId: text('new_execution_id').notNull(),
contextId: text('context_id').notNull(),
resumeInput: jsonb('resume_input'),
status: text('status').notNull().default('pending'),
queuedAt: timestamp('queued_at').notNull().defaultNow(),
claimedAt: timestamp('claimed_at'),
completedAt: timestamp('completed_at'),
failureReason: text('failure_reason'),
},
(table) => ({
parentStatusIdx: index('resume_queue_parent_status_idx').on(
table.parentExecutionId,
table.status,
table.queuedAt
),
newExecutionIdx: index('resume_queue_new_execution_idx').on(table.newExecutionId),
})
)
export const environment = pgTable('environment', {
id: text('id').primaryKey(), // Use the user id as the key
userId: text('user_id')
.notNull()
.references(() => user.id, { onDelete: 'cascade' })
.unique(), // One environment per user
variables: json('variables').notNull(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
})
export const workspaceEnvironment = pgTable(
'workspace_environment',
{
id: text('id').primaryKey(),
workspaceId: text('workspace_id')
.notNull()
.references(() => workspace.id, { onDelete: 'cascade' }),
variables: json('variables').notNull().default('{}'),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
},
(table) => ({
workspaceUnique: uniqueIndex('workspace_environment_workspace_unique').on(table.workspaceId),
})
)
export const workspaceBYOKKeys = pgTable(
'workspace_byok_keys',
{
id: text('id').primaryKey(),
workspaceId: text('workspace_id')
.notNull()
.references(() => workspace.id, { onDelete: 'cascade' }),
providerId: text('provider_id').notNull(),
encryptedApiKey: text('encrypted_api_key').notNull(),
name: text('name'),
createdBy: text('created_by').references(() => user.id, { onDelete: 'set null' }),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
},
(table) => ({
workspaceProviderIdx: index('workspace_byok_workspace_provider_idx').on(
table.workspaceId,
table.providerId
),
})
)
export const settings = pgTable('settings', {
id: text('id').primaryKey(), // Use the user id as the key
userId: text('user_id')
.notNull()
.references(() => user.id, { onDelete: 'cascade' })
.unique(), // One settings record per user
// General settings
theme: text('theme').notNull().default('system'),
autoConnect: boolean('auto_connect').notNull().default(true),
// Privacy settings
telemetryEnabled: boolean('telemetry_enabled').notNull().default(true),
// Email preferences
emailPreferences: json('email_preferences').notNull().default('{}'),
// Billing usage notifications preference
billingUsageNotificationsEnabled: boolean('billing_usage_notifications_enabled')
.notNull()
.default(true),
// UI preferences
showTrainingControls: boolean('show_training_controls').notNull().default(false),
superUserModeEnabled: boolean('super_user_mode_enabled').notNull().default(true),
mothershipEnvironment: text('mothership_environment').notNull().default('default'),
// Notification preferences
errorNotificationsEnabled: boolean('error_notifications_enabled').notNull().default(true),
// Canvas preferences
snapToGridSize: integer('snap_to_grid_size').notNull().default(0), // 0 = off, 10-50 = grid size
showActionBar: boolean('show_action_bar').notNull().default(true),
autoFocusOnClick: boolean('auto_focus_on_click').notNull().default(true),
timezone: text('timezone'),
// Copilot preferences - maps model_id to enabled/disabled boolean
copilotEnabledModels: jsonb('copilot_enabled_models').notNull().default('{}'),
// Copilot auto-allowed integration tools - array of tool IDs that can run without confirmation
copilotAutoAllowedTools: jsonb('copilot_auto_allowed_tools').notNull().default('[]'),
// Workspace navigation
lastActiveWorkspaceId: text('last_active_workspace_id'),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
})
export const workflowSchedule = pgTable(
'workflow_schedule',
{
id: text('id').primaryKey(),
workflowId: text('workflow_id').references(() => workflow.id, { onDelete: 'cascade' }),
deploymentVersionId: text('deployment_version_id').references(
() => workflowDeploymentVersion.id,
{ onDelete: 'cascade' }
),
deploymentOperationId: text('deployment_operation_id').references(
(): AnyPgColumn => workflowDeploymentOperation.id,
{ onDelete: 'set null' }
),
blockId: text('block_id'),
cronExpression: text('cron_expression'),
nextRunAt: timestamp('next_run_at'),
lastRanAt: timestamp('last_ran_at'),
lastQueuedAt: timestamp('last_queued_at'),
triggerType: text('trigger_type').notNull(), // "manual", "webhook", "schedule"
timezone: text('timezone').notNull().default('UTC'),
failedCount: integer('failed_count').notNull().default(0),
infraRetryCount: integer('infra_retry_count').notNull().default(0),
status: text('status').notNull().default('active'), // 'active', 'disabled', or 'completed'
lastFailedAt: timestamp('last_failed_at'),
sourceType: text('source_type').notNull().default('workflow'), // 'workflow' or 'job'
jobTitle: text('job_title'),
prompt: text('prompt'),
lifecycle: text('lifecycle').notNull().default('persistent'), // 'persistent' or 'until_complete'
successCondition: text('success_condition'),
maxRuns: integer('max_runs'),
runCount: integer('run_count').notNull().default(0),
sourceChatId: text('source_chat_id'),
sourceTaskName: text('source_task_name'),
sourceUserId: text('source_user_id').references(() => user.id, { onDelete: 'cascade' }),
sourceWorkspaceId: text('source_workspace_id').references(() => workspace.id, {
onDelete: 'cascade',
}),
secretScope: text('secret_scope').notNull().default('all'),
mountedSecrets: jsonb('mounted_secrets').$type<string[]>().notNull().default([]),
jobHistory: jsonb('job_history').$type<Array<{ timestamp: string; summary: string }>>(),
/** `@`-mentioned resources / `/`-invoked skills captured with the prompt, resolved into the agent run at fire time. */
contexts: jsonb('contexts').$type<Array<Record<string, unknown>>>(),
/** ISO timestamps of recurring occurrences the user deleted individually (EXDATE); the executor skips them. */
excludedDates: jsonb('excluded_dates').$type<string[]>(),
/** Recurrence end boundary: the schedule completes once its next run would fall after this instant. */
endsAt: timestamp('ends_at'),
archivedAt: timestamp('archived_at'),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
},
(table) => {
return {
workflowBlockUnique: uniqueIndex('workflow_schedule_workflow_block_deployment_unique')
.on(table.workflowId, table.blockId, table.deploymentVersionId)
.where(sql`${table.archivedAt} IS NULL`),
workflowDeploymentIdx: index('workflow_schedule_workflow_deployment_idx').on(
table.workflowId,
table.deploymentVersionId
),
archivedAtPartialIdx: index('workflow_schedule_archived_at_partial_idx')
.on(table.archivedAt)
.where(sql`${table.archivedAt} IS NOT NULL`),
sourceWorkspaceSourceTypeIdx: index(
'idx_workflow_schedule_on_source_workspace_id_source_t_c07f3bba6'
).on(table.sourceWorkspaceId, table.sourceType, table.archivedAt, table.status),
dueWorkflowIdx: index('workflow_schedule_due_workflow_idx')
.on(table.nextRunAt, table.lastQueuedAt, table.deploymentVersionId, table.workflowId)
.where(
sql`${table.archivedAt} IS NULL AND ${table.status} NOT IN ('disabled', 'completed') AND (${table.sourceType} = 'workflow' OR ${table.sourceType} IS NULL)`
),
dueJobIdx: index('workflow_schedule_due_job_idx')
.on(table.nextRunAt, table.lastQueuedAt)
.where(
sql`${table.archivedAt} IS NULL AND ${table.status} NOT IN ('disabled', 'completed') AND ${table.sourceType} = 'job'`
),
}
}
)
export const jobExecutionLogs = pgTable(
'job_execution_logs',
{
id: text('id').primaryKey(),
scheduleId: text('schedule_id').references(() => workflowSchedule.id, { onDelete: 'set null' }),
workspaceId: text('workspace_id')
.notNull()
.references(() => workspace.id, { onDelete: 'cascade' }),
executionId: text('execution_id').notNull(),
level: text('level').notNull(),
status: text('status').notNull().default('running'),
trigger: text('trigger').notNull(),
startedAt: timestamp('started_at').notNull(),
endedAt: timestamp('ended_at'),
totalDurationMs: integer('total_duration_ms'),
executionData: jsonb('execution_data').notNull().default('{}'),
cost: jsonb('cost'),
createdAt: timestamp('created_at').notNull().defaultNow(),
},
(table) => ({
scheduleIdIdx: index('job_execution_logs_schedule_id_idx').on(table.scheduleId),
workspaceStartedAtIdx: index('job_execution_logs_workspace_started_at_idx').on(
table.workspaceId,
table.startedAt
),
workspaceEndedAtIdIdx: index('job_execution_logs_workspace_ended_at_id_idx').on(
table.workspaceId,
sql`date_trunc('milliseconds', ${table.endedAt})`,
table.id
),
executionIdUnique: uniqueIndex('job_execution_logs_execution_id_unique').on(table.executionId),
triggerIdx: index('job_execution_logs_trigger_idx').on(table.trigger),
})
)
export const webhook = pgTable(
'webhook',
{
id: text('id').primaryKey(),
workflowId: text('workflow_id')
.notNull()
.references(() => workflow.id, { onDelete: 'cascade' }),
deploymentVersionId: text('deployment_version_id').references(
() => workflowDeploymentVersion.id,
{ onDelete: 'cascade' }
),
registrationStatus: text('registration_status'),
registrationGeneration: integer('registration_generation'),
configFingerprint: text('config_fingerprint'),
preparedAt: timestamp('prepared_at'),
blockId: text('block_id'),
/**
* URL-addressable webhook path. NULL for shared-app providers (e.g. the
* native Slack and TikTok triggers) whose events arrive on a single shared
* endpoint and route by `routingKey` instead of a per-workflow path.
*/
path: text('path'),
/**
* Tenant routing key for shared-app providers, such as Slack `team_id` or
* TikTok `open_id`, derived server-side from the connected credential at
* deploy time — never user input. Inbound events match on this after HMAC
* verification.
*/
routingKey: text('routing_key'),
provider: text('provider'), // e.g., "whatsapp", "github", etc.
providerConfig: json('provider_config'), // Store provider-specific configuration
isActive: boolean('is_active').notNull().default(true),
failedCount: integer('failed_count').default(0), // Track consecutive failures
lastFailedAt: timestamp('last_failed_at'), // When the webhook last failed
archivedAt: timestamp('archived_at'),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
},
(table) => {
return {
// Ensure webhook paths are unique per deployment version
pathIdx: uniqueIndex('path_deployment_unique')
.on(table.path, table.deploymentVersionId)
.where(sql`${table.archivedAt} IS NULL`),
workflowDeploymentIdx: index('webhook_workflow_deployment_idx').on(
table.workflowId,
table.deploymentVersionId
),
// Shared-app inbound routing (Slack native OAuth trigger). routingKey leads.
routingKeyActiveIdx: index('webhook_routing_key_active_idx')
.on(table.routingKey, table.provider)
.where(sql`${table.archivedAt} IS NULL AND ${table.routingKey} IS NOT NULL`),
archivedAtPartialIdx: index('webhook_archived_at_partial_idx')
.on(table.archivedAt)
.where(sql`${table.archivedAt} IS NOT NULL`),
providerActiveWorkflowDeploymentIdx: index(
'idx_webhook_on_provider_is_active_workflow_id_deploym_bdeed5468'
).on(table.provider, table.isActive, table.workflowId, table.deploymentVersionId),
workflowBlockUpdatedDescIdx: index('idx_webhook_on_workflow_id_block_id_updated_at_desc').on(
table.workflowId,
table.blockId,
table.updatedAt.desc()
),
activeRegistrationUnique: uniqueIndex('webhook_active_registration_unique')
.on(table.workflowId, table.blockId)
.where(
sql`${table.registrationStatus} = 'active' AND ${table.blockId} IS NOT NULL AND ${table.archivedAt} IS NULL`
),
candidateRegistrationUnique: uniqueIndex('webhook_candidate_registration_unique')
.on(table.workflowId, table.blockId)
.where(sql`${table.registrationStatus} = 'candidate' AND ${table.blockId} IS NOT NULL`),
registrationGenerationIdx: index('webhook_registration_status_generation_idx').on(
table.workflowId,
table.registrationStatus,
table.registrationGeneration
),
registrationStatusCheck: check(
'webhook_registration_status_check',
sql`${table.registrationStatus} IS NULL OR ${table.registrationStatus} IN ('active', 'candidate', 'retired', 'orphaned')`
),
registrationGenerationCheck: check(
'webhook_registration_generation_check',
sql`${table.registrationGeneration} IS NULL OR ${table.registrationGeneration} >= 0`
),
}
}
)
/**
* Owns a normalized path independently from registration generations.
*/
export const webhookPathClaim = pgTable(
'webhook_path_claim',
{
path: text('path').primaryKey(),
workflowId: text('workflow_id')
.notNull()
.references(() => workflow.id, { onDelete: 'cascade' }),
generation: integer('generation').notNull(),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
},
(table) => ({
workflowIdx: index('webhook_path_claim_workflow_idx').on(table.workflowId),
generationCheck: check('webhook_path_claim_generation_check', sql`${table.generation} >= 0`),
})
)
/**
* Cooldown state for Sim workspace-event trigger subscriptions.
*
* Keyed by (workflowId, blockId, scopeKey) rather than the webhook row because
* webhook rows are recreated per deployment version — state stored there would
* reset on every redeploy. `scopeKey` is '' for subscription-level cooldowns
* and the source workflow ID for per-source-workflow rules (no_activity).
*/
export const simTriggerState = pgTable(
'sim_trigger_state',
{
workflowId: text('workflow_id')
.notNull()
.references(() => workflow.id, { onDelete: 'cascade' }),
blockId: text('block_id').notNull(),
scopeKey: text('scope_key').notNull().default(''),
lastFiredAt: timestamp('last_fired_at'),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
},