@opengeni/db 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/{chunk-OGCE6O2X.js → chunk-7LDU7F5P.js} +31 -3
  2. package/dist/chunk-7LDU7F5P.js.map +1 -0
  3. package/dist/chunk-O3D7DABC.js +2314 -0
  4. package/dist/chunk-O3D7DABC.js.map +1 -0
  5. package/dist/{chunk-57MLICFR.js → chunk-YFQ7SGE4.js} +18 -6
  6. package/dist/chunk-YFQ7SGE4.js.map +1 -0
  7. package/dist/index.d.ts +2 -2
  8. package/dist/index.js +13129 -3496
  9. package/dist/index.js.map +1 -1
  10. package/dist/migrate.js +1 -1
  11. package/dist/provision-roles.d.ts +1836 -222
  12. package/dist/provision-roles.js +1 -1
  13. package/dist/{schema-Dsz6UHNv.d.ts → schema-Dp2MbBxx.d.ts} +7480 -3305
  14. package/dist/schema.d.ts +1 -1
  15. package/dist/schema.js +33 -5
  16. package/drizzle/0043_credit_balance_observability.sql +22 -0
  17. package/drizzle/0044_reap_dead_turn_holders.sql +104 -0
  18. package/drizzle/0045_workspace_captures.sql +83 -0
  19. package/drizzle/0045_workspace_memory_v1.sql +71 -0
  20. package/drizzle/0046_variable_sets_rename.sql +56 -0
  21. package/drizzle/0047_rigs.sql +151 -0
  22. package/drizzle/0048_rig_runtime.sql +9 -0
  23. package/drizzle/0049_enrollment_went_offline.sql +28 -0
  24. package/drizzle/0050_enrollment_op_stream.sql +1 -0
  25. package/drizzle/0051_codex_pin_source.sql +48 -0
  26. package/drizzle/0052_file_upload_cleanup.sql +91 -0
  27. package/drizzle/0053_codex_credential_leases.sql +230 -0
  28. package/drizzle/0054_session_pins.sql +85 -0
  29. package/drizzle/0055_session_list_snapshots.sql +73 -0
  30. package/drizzle/0056_workspace_model_policies.sql +48 -0
  31. package/drizzle/0057_durable_queue_control.sql +536 -0
  32. package/drizzle/0058_turn_admission_usage_enrollment.sql +158 -0
  33. package/drizzle/0059_workspace_pause_control_kind.sql +12 -0
  34. package/drizzle/0060_session_system_update_deferral.sql +10 -0
  35. package/drizzle/0061_session_workflow_wake_outbox.sql +157 -0
  36. package/drizzle/0062_session_list_snapshot_reaper.sql +48 -0
  37. package/package.json +17 -13
  38. package/src/codex-token-resolver.ts +58 -23
  39. package/src/connection-token-resolver.ts +146 -57
  40. package/src/environment-crypto.ts +5 -1
  41. package/src/event-payload-sanitizer.ts +29 -1
  42. package/src/index.ts +22460 -6492
  43. package/src/memory-domain.ts +218 -0
  44. package/src/migrate.ts +58 -3
  45. package/src/provision-roles.ts +46 -17
  46. package/src/schema.ts +2557 -1121
  47. package/src/session-control-cutover-audit.ts +1203 -0
  48. package/dist/chunk-57MLICFR.js.map +0 -1
  49. package/dist/chunk-OGCE6O2X.js.map +0 -1
  50. package/dist/chunk-ZIUCA2IO.js +0 -1268
  51. package/dist/chunk-ZIUCA2IO.js.map +0 -1
@@ -0,0 +1,2314 @@
1
+ import {
2
+ __export
3
+ } from "./chunk-PZ5AY32C.js";
4
+
5
+ // src/schema.ts
6
+ var schema_exports = {};
7
+ __export(schema_exports, {
8
+ agentRunStates: () => agentRunStates,
9
+ apiKeys: () => apiKeys,
10
+ auditEvents: () => auditEvents,
11
+ billingCustomers: () => billingCustomers,
12
+ capabilityCatalogItems: () => capabilityCatalogItems,
13
+ capabilityInstallations: () => capabilityInstallations,
14
+ codexCapacityWaiters: () => codexCapacityWaiters,
15
+ codexCredentialLeases: () => codexCredentialLeases,
16
+ codexRotationSettings: () => codexRotationSettings,
17
+ codexSubscriptionCredentials: () => codexSubscriptionCredentials,
18
+ connections: () => connections,
19
+ creditLedgerEntries: () => creditLedgerEntries,
20
+ deviceEnrollmentRequests: () => deviceEnrollmentRequests,
21
+ deviceEnrollmentStatusValues: () => deviceEnrollmentStatusValues,
22
+ documentBases: () => documentBases,
23
+ documentChunks: () => documentChunks,
24
+ documents: () => documents,
25
+ enrollmentExposureValues: () => enrollmentExposureValues,
26
+ enrollmentOsValues: () => enrollmentOsValues,
27
+ enrollmentStatusValues: () => enrollmentStatusValues,
28
+ enrollments: () => enrollments,
29
+ fileUploads: () => fileUploads,
30
+ files: () => files,
31
+ githubInstallations: () => githubInstallations,
32
+ importBatches: () => importBatches,
33
+ integrationOauthClients: () => integrationOauthClients,
34
+ integrationOauthStateNonces: () => integrationOauthStateNonces,
35
+ knowledgeMemories: () => knowledgeMemories,
36
+ machineMetricsLatest: () => machineMetricsLatest,
37
+ machineMetricsSeries: () => machineMetricsSeries,
38
+ managedAccounts: () => managedAccounts,
39
+ packInstallations: () => packInstallations,
40
+ rigChanges: () => rigChanges,
41
+ rigVersions: () => rigVersions,
42
+ rigs: () => rigs,
43
+ runtimeControlOperations: () => runtimeControlOperations,
44
+ sandboxKindValues: () => sandboxKindValues,
45
+ sandboxLeaseHolders: () => sandboxLeaseHolders,
46
+ sandboxLeaseLivenessValues: () => sandboxLeaseLivenessValues,
47
+ sandboxLeases: () => sandboxLeases,
48
+ sandboxPtySessions: () => sandboxPtySessions,
49
+ sandboxSessionEnvelopes: () => sandboxSessionEnvelopes,
50
+ sandboxes: () => sandboxes,
51
+ scheduledTaskRuns: () => scheduledTaskRuns,
52
+ scheduledTasks: () => scheduledTasks,
53
+ sessionEvents: () => sessionEvents,
54
+ sessionGoals: () => sessionGoals,
55
+ sessionHistoryItems: () => sessionHistoryItems,
56
+ sessionListSnapshots: () => sessionListSnapshots,
57
+ sessionMcpServers: () => sessionMcpServers,
58
+ sessionPendingToolCalls: () => sessionPendingToolCalls,
59
+ sessionPins: () => sessionPins,
60
+ sessionRecordingCodecValues: () => sessionRecordingCodecValues,
61
+ sessionRecordingModeValues: () => sessionRecordingModeValues,
62
+ sessionRecordingStateValues: () => sessionRecordingStateValues,
63
+ sessionRecordings: () => sessionRecordings,
64
+ sessionSystemUpdateOutbox: () => sessionSystemUpdateOutbox,
65
+ sessionSystemUpdates: () => sessionSystemUpdates,
66
+ sessionTurns: () => sessionTurns,
67
+ sessionWorkflowWakeOutbox: () => sessionWorkflowWakeOutbox,
68
+ sessions: () => sessions,
69
+ socialConnections: () => socialConnections,
70
+ socialPosts: () => socialPosts,
71
+ stripeWebhookEvents: () => stripeWebhookEvents,
72
+ usageEvents: () => usageEvents,
73
+ workspaceCaptures: () => workspaceCaptures,
74
+ workspaceMemberships: () => workspaceMemberships,
75
+ workspaceModelPolicies: () => workspaceModelPolicies,
76
+ workspacePacks: () => workspacePacks,
77
+ workspaceVariableSetVariables: () => workspaceVariableSetVariables,
78
+ workspaceVariableSets: () => workspaceVariableSets,
79
+ workspaces: () => workspaces
80
+ });
81
+ import { sql } from "drizzle-orm";
82
+ import {
83
+ bigint,
84
+ boolean,
85
+ check,
86
+ foreignKey,
87
+ index,
88
+ integer,
89
+ jsonb,
90
+ numeric,
91
+ pgTable,
92
+ text,
93
+ timestamp,
94
+ uniqueIndex,
95
+ uuid,
96
+ customType
97
+ } from "drizzle-orm/pg-core";
98
+ var vector = customType({
99
+ dataType() {
100
+ return "vector(3072)";
101
+ },
102
+ toDriver(value) {
103
+ return `[${value.join(",")}]`;
104
+ }
105
+ });
106
+ var managedAccounts = pgTable(
107
+ "managed_accounts",
108
+ {
109
+ id: uuid("id").primaryKey().defaultRandom(),
110
+ name: text("name").notNull(),
111
+ externalSource: text("external_source"),
112
+ externalId: text("external_id"),
113
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
114
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
115
+ },
116
+ (table) => ({
117
+ external: uniqueIndex("managed_accounts_external_idx").on(
118
+ table.externalSource,
119
+ table.externalId
120
+ )
121
+ })
122
+ );
123
+ var workspaces = pgTable(
124
+ "workspaces",
125
+ {
126
+ id: uuid("id").primaryKey().defaultRandom(),
127
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
128
+ name: text("name").notNull(),
129
+ slug: text("slug"),
130
+ externalSource: text("external_source"),
131
+ externalId: text("external_id"),
132
+ // White-label agent persona template override. NULL means the deployment
133
+ // default (OPENGENI_AGENT_INSTRUCTIONS_TEMPLATE / DEFAULT_AGENT_INSTRUCTIONS).
134
+ agentInstructions: text("agent_instructions"),
135
+ // Growth-ready per-workspace settings bag (migration 0045). Holds memoryEnabled
136
+ // and future workspace-level toggles; validated/merged via WorkspaceSettingsSchema.
137
+ settings: jsonb("settings").$type().notNull().default({}),
138
+ inferenceState: text("inference_state").notNull().default("active"),
139
+ inferenceGeneration: integer("inference_generation").notNull().default(0),
140
+ inferenceReason: text("inference_reason"),
141
+ inferenceChangedBy: text("inference_changed_by"),
142
+ inferenceChangedAt: timestamp("inference_changed_at", { withTimezone: true }),
143
+ // The workspace's default rig (migration 0047). NULL ⇒ no default; sessions
144
+ // created without an explicit rig ride no rig (today's behavior exactly). FK
145
+ // (-> rigs(id) ON DELETE SET NULL) lives in migration 0047, not a Drizzle
146
+ // .references(), because `rigs` is declared later in this file (same
147
+ // forward-reference pattern as sessions.activeSandboxId). Consumed in M3.
148
+ defaultRigId: uuid("default_rig_id"),
149
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
150
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
151
+ },
152
+ (table) => ({
153
+ account: index("workspaces_account_idx").on(table.accountId),
154
+ accountSlug: uniqueIndex("workspaces_account_slug_idx").on(table.accountId, table.slug).where(sql`${table.slug} is not null`),
155
+ external: uniqueIndex("workspaces_external_idx").on(table.externalSource, table.externalId)
156
+ })
157
+ );
158
+ var workspaceMemberships = pgTable(
159
+ "workspace_memberships",
160
+ {
161
+ id: uuid("id").primaryKey().defaultRandom(),
162
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
163
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
164
+ subjectId: text("subject_id").notNull(),
165
+ subjectLabel: text("subject_label"),
166
+ role: text("role").notNull().default("member"),
167
+ permissions: jsonb("permissions").$type().notNull().default([]),
168
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
169
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
170
+ },
171
+ (table) => ({
172
+ subjectWorkspace: uniqueIndex("workspace_memberships_subject_workspace_idx").on(
173
+ table.subjectId,
174
+ table.workspaceId
175
+ ),
176
+ subject: index("workspace_memberships_subject_idx").on(table.subjectId),
177
+ account: index("workspace_memberships_account_idx").on(table.accountId)
178
+ })
179
+ );
180
+ var apiKeys = pgTable(
181
+ "api_keys",
182
+ {
183
+ id: uuid("id").primaryKey().defaultRandom(),
184
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
185
+ workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade" }),
186
+ name: text("name").notNull(),
187
+ prefix: text("prefix").notNull(),
188
+ keyHash: text("key_hash").notNull(),
189
+ permissions: jsonb("permissions").$type().notNull().default([]),
190
+ expiresAt: timestamp("expires_at", { withTimezone: true }),
191
+ revokedAt: timestamp("revoked_at", { withTimezone: true }),
192
+ lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
193
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
194
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
195
+ },
196
+ (table) => ({
197
+ prefix: index("api_keys_prefix_idx").on(table.prefix),
198
+ hash: uniqueIndex("api_keys_key_hash_idx").on(table.keyHash),
199
+ account: index("api_keys_account_idx").on(table.accountId),
200
+ workspace: index("api_keys_workspace_idx").on(table.workspaceId)
201
+ })
202
+ );
203
+ var workspaceVariableSets = pgTable(
204
+ "workspace_variable_sets",
205
+ {
206
+ id: uuid("id").primaryKey().defaultRandom(),
207
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
208
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
209
+ name: text("name").notNull(),
210
+ description: text("description"),
211
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
212
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
213
+ },
214
+ (table) => ({
215
+ workspaceName: uniqueIndex("workspace_variable_sets_workspace_name_idx").on(
216
+ table.workspaceId,
217
+ table.name
218
+ ),
219
+ workspaceCreated: index("workspace_variable_sets_workspace_created_idx").on(
220
+ table.workspaceId,
221
+ table.createdAt
222
+ )
223
+ })
224
+ );
225
+ var workspaceVariableSetVariables = pgTable(
226
+ "workspace_variable_set_variables",
227
+ {
228
+ id: uuid("id").primaryKey().defaultRandom(),
229
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
230
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
231
+ variableSetId: uuid("variable_set_id").notNull().references(() => workspaceVariableSets.id, { onDelete: "cascade" }),
232
+ name: text("name").notNull(),
233
+ // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. Never returned by any API.
234
+ valueEncrypted: text("value_encrypted").notNull(),
235
+ version: integer("version").notNull().default(1),
236
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
237
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
238
+ },
239
+ (table) => ({
240
+ variableSetName: uniqueIndex("workspace_variable_set_variables_env_name_idx").on(
241
+ table.workspaceId,
242
+ table.variableSetId,
243
+ table.name
244
+ ),
245
+ variableSet: index("workspace_variable_set_variables_workspace_env_idx").on(
246
+ table.workspaceId,
247
+ table.variableSetId
248
+ )
249
+ })
250
+ );
251
+ var codexSubscriptionCredentials = pgTable(
252
+ "codex_subscription_credentials",
253
+ {
254
+ id: uuid("id").primaryKey().defaultRandom(),
255
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
256
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
257
+ // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. JSON {access_token, refresh_token, id_token}. Never returned by any API.
258
+ credentialEncrypted: text("credential_encrypted").notNull(),
259
+ chatgptAccountId: text("chatgpt_account_id"),
260
+ // plaintext ChatGPT-Account-ID header value (non-secret)
261
+ scopes: text("scopes"),
262
+ // space-delimited, as granted
263
+ planType: text("plan_type"),
264
+ isFedramp: boolean("is_fedramp").notNull().default(false),
265
+ expiresAt: timestamp("expires_at", { withTimezone: true }),
266
+ // derived from access-token JWT exp
267
+ lastRefreshAt: timestamp("last_refresh_at", { withTimezone: true }),
268
+ status: text("status").notNull().default("active"),
269
+ // active | needs_relogin | error
270
+ lastError: text("last_error"),
271
+ version: integer("version").notNull().default(1),
272
+ label: text("label"),
273
+ // user-chosen nickname; null ⇒ derive from email/plan/account
274
+ accountEmail: text("account_email"),
275
+ // email from the id_token (user's own email; non-secret)
276
+ // P2 usage cache (plaintext metadata; NEVER a token). Snapshotted from
277
+ // GET /wham/usage; drives the quota bars + the cache TTL. primary = 5h window
278
+ // (limit_window_seconds 18000), secondary = weekly (604800).
279
+ primaryUsedPercent: integer("primary_used_percent"),
280
+ primaryResetAt: timestamp("primary_reset_at", { withTimezone: true }),
281
+ secondaryUsedPercent: integer("secondary_used_percent"),
282
+ secondaryResetAt: timestamp("secondary_reset_at", { withTimezone: true }),
283
+ usageCheckedAt: timestamp("usage_checked_at", { withTimezone: true }),
284
+ // snapshot freshness → cache TTL clock
285
+ // P3 rotation cooldown (plaintext metadata; NEVER a token). Set when this account hit its
286
+ // usage cap on a rotation turn; the rotation engine treats `exhausted_until > now()` as
287
+ // capped/skip so it isn't immediately re-picked. Self-clears via the now() comparison.
288
+ exhaustedUntil: timestamp("exhausted_until", { withTimezone: true }),
289
+ // P4 connector-aware rotation cache (plaintext metadata; NEVER a token). The set
290
+ // of ORIGINAL-dotted connector namespaces (github/gmail/linear/…) this account
291
+ // exposes via codex_apps, captured from the per-turn tools/list. null ⇒ never
292
+ // probed (the ranker treats it as unknown: never credited as covering, never
293
+ // excluded). The writer only ever sets a NON-empty set, so a flaky empty turn
294
+ // can't false-drop coverage. connectorsCheckedAt is the freshness clock.
295
+ connectorNamespaces: text("connector_namespaces").array(),
296
+ connectorsCheckedAt: timestamp("connectors_checked_at", { withTimezone: true }),
297
+ // Workspace-local, server-held fairness cursor. Provider usage headers are
298
+ // capacity hints, never the sole allocator: live lease count is ranked first
299
+ // and this cursor deterministically breaks equal-load/equal-capacity ties.
300
+ // This flag controls NEW automatic allocations only. Credential health,
301
+ // refresh, encrypted material, and already-frozen/in-flight turns are
302
+ // intentionally independent. OPE-24 owns toggle OCC/audit and product UI.
303
+ allocatorEnabled: boolean("allocator_enabled").notNull().default(true),
304
+ selectionCount: integer("selection_count").notNull().default(0),
305
+ lastSelectedAt: timestamp("last_selected_at", { withTimezone: true }),
306
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
307
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
308
+ },
309
+ (table) => ({
310
+ // REPLACES codex_subscription_credentials_workspace_idx (the one-per-workspace cap).
311
+ // One row per (workspace, ChatGPT account). Partial WHERE chatgpt_account_id IS NOT NULL
312
+ // so degenerate null-account rows can't collide; the device-grant connect path always
313
+ // populates chatgpt_account_id.
314
+ wsAccount: uniqueIndex("codex_subscription_credentials_ws_account_idx").on(table.workspaceId, table.chatgptAccountId).where(sql`${table.chatgptAccountId} is not null`),
315
+ workspace: index("codex_subscription_credentials_workspace_lookup_idx").on(table.workspaceId),
316
+ // Composite identity is the defense-in-depth FK target for workspace-local
317
+ // lease references in migration 0053.
318
+ workspaceIdentity: uniqueIndex("codex_subscription_credentials_workspace_id_idx").on(
319
+ table.workspaceId,
320
+ table.id
321
+ )
322
+ })
323
+ );
324
+ var connections = pgTable(
325
+ "connections",
326
+ {
327
+ id: uuid("id").primaryKey().defaultRandom(),
328
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
329
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
330
+ subjectId: text("subject_id"),
331
+ providerDomain: text("provider_domain").notNull(),
332
+ kind: text("kind").notNull(),
333
+ status: text("status").notNull().default("active"),
334
+ credentialEncrypted: text("credential_encrypted").notNull(),
335
+ grantedScopes: jsonb("granted_scopes").$type().notNull().default([]),
336
+ expiresAt: timestamp("expires_at", { withTimezone: true }),
337
+ lastRefreshAt: timestamp("last_refresh_at", { withTimezone: true }),
338
+ lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
339
+ lastError: text("last_error"),
340
+ version: integer("version").notNull().default(1),
341
+ metadata: jsonb("metadata").$type().notNull().default({}),
342
+ createdBySubjectId: text("created_by_subject_id"),
343
+ updatedBySubjectId: text("updated_by_subject_id"),
344
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
345
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
346
+ },
347
+ (table) => ({
348
+ workspaceProviderStatus: index("connections_workspace_provider_status_idx").on(
349
+ table.workspaceId,
350
+ table.providerDomain,
351
+ table.status
352
+ ),
353
+ workspaceSubjectProvider: index("connections_workspace_subject_provider_idx").on(
354
+ table.workspaceId,
355
+ table.subjectId,
356
+ table.providerDomain
357
+ ),
358
+ workspaceKind: index("connections_workspace_kind_idx").on(table.workspaceId, table.kind),
359
+ workspaceExpires: index("connections_workspace_expires_idx").on(
360
+ table.workspaceId,
361
+ table.expiresAt
362
+ )
363
+ })
364
+ );
365
+ var integrationOauthClients = pgTable(
366
+ "integration_oauth_clients",
367
+ {
368
+ id: uuid("id").primaryKey().defaultRandom(),
369
+ issuer: text("issuer").notNull(),
370
+ authorizationServer: text("authorization_server").notNull(),
371
+ clientId: text("client_id").notNull(),
372
+ clientSecretEncrypted: text("client_secret_encrypted"),
373
+ tokenEndpointAuthMethod: text("token_endpoint_auth_method").notNull().default("none"),
374
+ metadata: jsonb("metadata").$type().notNull().default({}),
375
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
376
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
377
+ },
378
+ (table) => ({
379
+ issuer: uniqueIndex("integration_oauth_clients_issuer_idx").on(table.issuer),
380
+ authorizationServer: index("integration_oauth_clients_as_idx").on(table.authorizationServer)
381
+ })
382
+ );
383
+ var integrationOauthStateNonces = pgTable(
384
+ "integration_oauth_state_nonces",
385
+ {
386
+ nonce: text("nonce").primaryKey(),
387
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
388
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
389
+ subjectId: text("subject_id").notNull(),
390
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
391
+ usedAt: timestamp("used_at", { withTimezone: true }).notNull().defaultNow(),
392
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
393
+ },
394
+ (table) => ({
395
+ workspace: index("integration_oauth_state_nonces_workspace_idx").on(table.workspaceId),
396
+ expires: index("integration_oauth_state_nonces_expires_idx").on(table.expiresAt)
397
+ })
398
+ );
399
+ var codexRotationSettings = pgTable(
400
+ "codex_rotation_settings",
401
+ {
402
+ id: uuid("id").primaryKey().defaultRandom(),
403
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
404
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
405
+ activeCredentialId: uuid("active_credential_id"),
406
+ // Legacy selector bit. Keep false as the DB default forever: an old worker
407
+ // only understands this column, so a schema-first rollout or binary
408
+ // rollback must never make it enter the non-atomic rotation path.
409
+ rotationEnabled: boolean("rotation_enabled").notNull().default(false),
410
+ // Revision-aware allocator cutover. Only migration-compatible API/worker
411
+ // code reads this bit; old binaries safely ignore it and keep the legacy
412
+ // pin/rotation policy.
413
+ leaseRotationEnabled: boolean("lease_rotation_enabled").notNull().default(false),
414
+ rotationStrategy: text("rotation_strategy").notNull().default("most_remaining"),
415
+ // P3, inert
416
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
417
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
418
+ },
419
+ (table) => ({
420
+ workspace: uniqueIndex("codex_rotation_settings_workspace_idx").on(table.workspaceId)
421
+ })
422
+ );
423
+ var workspaceModelPolicies = pgTable(
424
+ "workspace_model_policies",
425
+ {
426
+ id: uuid("id").primaryKey().defaultRandom(),
427
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
428
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
429
+ allowedProviders: text("allowed_providers").array(),
430
+ allowedModels: text("allowed_models").array(),
431
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
432
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
433
+ },
434
+ (table) => ({
435
+ workspace: uniqueIndex("workspace_model_policies_workspace_idx").on(table.workspaceId)
436
+ })
437
+ );
438
+ var codexCredentialLeases = pgTable(
439
+ "codex_credential_leases",
440
+ {
441
+ id: uuid("id").primaryKey().defaultRandom(),
442
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
443
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
444
+ credentialId: uuid("credential_id").notNull(),
445
+ turnId: uuid("turn_id").notNull(),
446
+ // Temporal activity execution fence. A successor dispatch for the same
447
+ // durable turn replaces holderId and increments generation atomically;
448
+ // stale/zombie heartbeats and releases must match both values.
449
+ holderId: text("holder_id").notNull(),
450
+ generation: integer("generation").notNull().default(1),
451
+ leasedUntil: timestamp("leased_until", { withTimezone: true }).notNull(),
452
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
453
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
454
+ },
455
+ (table) => ({
456
+ turn: uniqueIndex("codex_credential_leases_workspace_turn_idx").on(
457
+ table.workspaceId,
458
+ table.turnId
459
+ ),
460
+ activeCredential: index("codex_credential_leases_active_credential_idx").on(
461
+ table.workspaceId,
462
+ table.credentialId,
463
+ table.leasedUntil
464
+ ),
465
+ expiry: index("codex_credential_leases_expiry_idx").on(table.leasedUntil)
466
+ })
467
+ );
468
+ var sessions = pgTable(
469
+ "sessions",
470
+ {
471
+ id: uuid("id").primaryKey().defaultRandom(),
472
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
473
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
474
+ status: text("status").notNull().default("queued"),
475
+ initialMessage: text("initial_message").notNull(),
476
+ title: text("title"),
477
+ titleSource: text("title_source"),
478
+ // Per-session agent persona/system instructions supplied at create (the
479
+ // per-agent-type prompt lever for embedding hosts). NULL ⇒ the session
480
+ // carried none, so the composed agent instructions are byte-identical to a
481
+ // workspace-only persona (no backfill, no behavior change for existing rows).
482
+ // Composed system-level AFTER the workspace agentInstructions; never emitted
483
+ // as a timeline event.
484
+ instructions: text("instructions"),
485
+ resources: jsonb("resources").$type().notNull().default([]),
486
+ tools: jsonb("tools").$type().notNull().default([]),
487
+ metadata: jsonb("metadata").$type().notNull().default({}),
488
+ model: text("model").notNull(),
489
+ sandboxBackend: text("sandbox_backend").notNull(),
490
+ // The OS this session's box runs. Defaults to 'linux' (today's only OS, so
491
+ // every existing + new row is a behavior-preserving no-op). CHECK-constrained
492
+ // to the SandboxOs enum (linux|macos|windows) in migration 0018.
493
+ sandboxOs: text("sandbox_os").notNull().default("linux"),
494
+ // The shared-sandbox group this session's box belongs to. Defaults to the
495
+ // session's OWN id (a singleton group: group === session — today's 1:1
496
+ // behavior). When spawned shared via session_create, set to the PARENT's
497
+ // sandboxGroupId so both run in ONE box. Immutable once set. NOT an FK (the
498
+ // value is this row's id or an ancestor session's id in the same workspace;
499
+ // the live lease row, not a sandbox_groups table, materializes the group).
500
+ // The app generates the uuid and uses it for both id and sandbox_group_id in
501
+ // one insert — it cannot SQL-default to id (id is defaultRandom()).
502
+ sandboxGroupId: uuid("sandbox_group_id").notNull(),
503
+ // The first-class swappable-sandbox POINTER (bring-your-own-compute M2,
504
+ // dossier §10.3). NULL == "use the session's own group sandbox" (the
505
+ // backward-compat default — every existing/new row is a behavior-preserving
506
+ // no-op). The routing proxy re-reads (active_sandbox_id, active_epoch) PER
507
+ // TOOL CALL to make a Modal<->selfhosted hot-swap seamless. The FK
508
+ // (-> sandboxes(id) ON DELETE SET NULL — a deleted sandbox degrades the
509
+ // pointer to the group default, never dangles) lives in migration 0024, NOT a
510
+ // Drizzle .references() — exactly like parentSessionId below, so the const
511
+ // ordering imposes no forward-reference.
512
+ activeSandboxId: uuid("active_sandbox_id"),
513
+ // The SECOND epoch ABOVE sandbox_leases.lease_epoch, bumped on every swap; an
514
+ // in-flight op fenced by a stale active_epoch retries against the new active
515
+ // sandbox. integer (NOT bigint) — the lease-epoch spike: int8 reads back as a
516
+ // JS string and breaks the strict fence; int4 returns a number.
517
+ activeEpoch: integer("active_epoch").notNull().default(0),
518
+ // The session's WORKING DIRECTORY — the path/cwd base the (selfhosted) box's
519
+ // agent/terminal/file-dock operate under. A launch-workspace_root-relative
520
+ // subdir or an absolute machine path; surfaced alongside the active-sandbox
521
+ // pointer (readActiveSandbox) and written through the epoch-fenced
522
+ // setActiveSandbox CAS, NOT the row INSERT. NULL (the default) ⇒ today's
523
+ // behavior exactly — the agent substitutes its workspace_root for an empty cwd,
524
+ // so an unset working_dir is a byte-identical no-op. Create-time only (Stage A).
525
+ workingDir: text("working_dir"),
526
+ variableSetId: uuid("variable_set_id").references(() => workspaceVariableSets.id, {
527
+ onDelete: "set null"
528
+ }),
529
+ // The rig this session rides + the exact rig version frozen at create time
530
+ // (migration 0047). NULL ⇒ the session rides no rig (today's behavior). FKs
531
+ // (-> rigs(id)/rig_versions(id) ON DELETE SET NULL) live in migration 0047,
532
+ // not Drizzle .references(), because those tables are declared later in this
533
+ // file (forward-reference pattern, same as activeSandboxId). Consumed in M3.
534
+ rigId: uuid("rig_id"),
535
+ rigVersionId: uuid("rig_version_id"),
536
+ // Non-default first-party MCP token permissions (manager-style sessions);
537
+ // null means the fixed worker default set in @opengeni/runtime.
538
+ firstPartyMcpPermissions: jsonb("first_party_mcp_permissions").$type(),
539
+ // The manager session that spawned this one via session_create. Set only
540
+ // when the creating grant carried a worker-signed sessionId claim (a session
541
+ // spawning a worker); null for direct API creates and scheduled-task runs.
542
+ // When set, this worker's terminal-for-now transitions wake the parent so a
543
+ // manager can orchestrate workers without busy-polling. Self-referencing FK,
544
+ // ON DELETE SET NULL so deleting a manager never cascades into its workers.
545
+ parentSessionId: uuid("parent_session_id"),
546
+ // Workspace-scoped CREATE idempotency key. NULL means the create carried no
547
+ // key (each such create is independent). When set, the partial unique index
548
+ // below collapses concurrent/retried creates with the same key in the same
549
+ // workspace to a single session row — the dedup that closes the
550
+ // double-submit/double-dispatch stuck-queued bug.
551
+ createIdempotencyKey: text("create_idempotency_key"),
552
+ temporalWorkflowId: text("temporal_workflow_id"),
553
+ activeTurnId: uuid("active_turn_id"),
554
+ // Actual input tokens reported for the last model call of the most recent
555
+ // turn. The pre-turn portable compaction trigger reads this as its budget
556
+ // signal (char/4 estimate is the same-turn fallback). Null until a turn with
557
+ // usage has completed.
558
+ lastInputTokens: integer("last_input_tokens"),
559
+ // Operator /compact request flag. The API sets
560
+ // it true; the worker honors it BEFORE the next turn's model call by forcing
561
+ // a compaction, then clears it. A durable flag (not a transient signal) so
562
+ // the trigger survives a worker restart and converges before the next turn.
563
+ compactRequested: boolean("compact_requested").notNull().default(false),
564
+ queueVersion: integer("queue_version").notNull().default(0),
565
+ queueHeadPosition: bigint("queue_head_position", { mode: "number" }).notNull().default(0),
566
+ queueTailPosition: bigint("queue_tail_position", { mode: "number" }).notNull().default(0),
567
+ controlState: text("control_state").notNull().default("active"),
568
+ controlGeneration: integer("control_generation").notNull().default(0),
569
+ controlReason: text("control_reason"),
570
+ controlChangedBy: text("control_changed_by"),
571
+ controlChangedAt: timestamp("control_changed_at", { withTimezone: true }),
572
+ pendingControlEventId: uuid("pending_control_event_id"),
573
+ pendingControlKind: text("pending_control_kind"),
574
+ pendingControlExpectedTurnId: uuid("pending_control_expected_turn_id"),
575
+ pendingControlExpectedGeneration: integer("pending_control_expected_generation"),
576
+ pendingControlExpectedAttemptId: uuid("pending_control_expected_attempt_id"),
577
+ workspaceRunExceptionGeneration: integer("workspace_run_exception_generation"),
578
+ lastSequence: integer("last_sequence").notNull().default(0),
579
+ // The session's PINNED Codex account (manual override from the in-session
580
+ // switcher). NULL ⇒ follow the workspace active pointer. FK declared in the
581
+ // migration with ON DELETE SET NULL (a disconnected pin degrades to "follow
582
+ // active", never dangles), same pattern as activeSandboxId.
583
+ codexPinnedCredentialId: uuid("codex_pinned_credential_id"),
584
+ // The Codex account the session's most recent turn ACTUALLY ran on — drives
585
+ // the "Running on:" indicator. Written by the worker at the turn boundary. FK
586
+ // ON DELETE SET NULL (migration).
587
+ codexLastCredentialId: uuid("codex_last_credential_id"),
588
+ // The SOURCE of codex_pinned_credential_id (AM-2): 'manual' — the user's
589
+ // in-session account switcher, which is SACRED and never moved by any policy —
590
+ // or 'policy' — the sharded rotation strategy's deterministic per-session home
591
+ // assignment, which MAY be re-sharded to another account when its own account
592
+ // caps. NULL when there is no pin (and for every pre-existing row). CHECK
593
+ // (manual|policy) lives in the migration; no FK (it describes the pin, not an
594
+ // account).
595
+ codexPinSource: text("codex_pin_source"),
596
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
597
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
598
+ },
599
+ (table) => ({
600
+ workspaceIdentity: uniqueIndex("sessions_workspace_id_idx").on(table.workspaceId, table.id),
601
+ workspaceCreated: index("sessions_workspace_created_idx").on(
602
+ table.workspaceId,
603
+ table.createdAt
604
+ ),
605
+ variableSet: index("sessions_variable_set_idx").on(table.workspaceId, table.variableSetId),
606
+ parent: index("sessions_parent_idx").on(table.workspaceId, table.parentSessionId),
607
+ // Routing index: resolve session_id -> sandbox_group_id at every lease entry
608
+ // point and enumerate all sessions in a group for attribution/disclosure.
609
+ sandboxGroup: index("sessions_sandbox_group_idx").on(table.workspaceId, table.sandboxGroupId),
610
+ // Partial unique index: one session per (workspace, create_idempotency_key)
611
+ // when a key is present. Concurrent creates racing on the same key see a
612
+ // unique violation on all but one; the domain layer catches it and returns
613
+ // the winning row instead of erroring.
614
+ createIdempotency: uniqueIndex("sessions_workspace_create_idempotency_idx").on(table.workspaceId, table.createIdempotencyKey).where(sql`${table.createIdempotencyKey} is not null`)
615
+ })
616
+ );
617
+ var sessionPins = pgTable(
618
+ "session_pins",
619
+ {
620
+ id: uuid("id").primaryKey().defaultRandom(),
621
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
622
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
623
+ subjectId: text("subject_id").notNull(),
624
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
625
+ // Keep an unpinned tombstone (pinned=false, pinned_at=null) rather than
626
+ // deleting it. That preserves a monotonic version and prevents an ABA race:
627
+ // a stale client that saw pin version 1 cannot silently overwrite a later
628
+ // unpin+re-pin that would otherwise recreate version 1.
629
+ pinned: boolean("pinned").notNull().default(true),
630
+ pinnedAt: timestamp("pinned_at", { withTimezone: true }).defaultNow(),
631
+ version: integer("version").notNull().default(1)
632
+ },
633
+ (table) => ({
634
+ subjectNonempty: check(
635
+ "session_pins_subject_nonempty",
636
+ sql`length(btrim(${table.subjectId})) > 0`
637
+ ),
638
+ versionPositive: check("session_pins_version_positive", sql`${table.version} >= 1`),
639
+ stateConsistent: check(
640
+ "session_pins_state_consistent",
641
+ sql`((${table.pinned}) and (${table.pinnedAt}) is not null) or ((not ${table.pinned}) and (${table.pinnedAt}) is null)`
642
+ ),
643
+ workspaceAccount: foreignKey({
644
+ name: "session_pins_workspace_account_fk",
645
+ columns: [table.workspaceId, table.accountId],
646
+ foreignColumns: [workspaces.id, workspaces.accountId]
647
+ }).onDelete("cascade"),
648
+ workspaceSession: foreignKey({
649
+ name: "session_pins_workspace_session_fk",
650
+ columns: [table.workspaceId, table.sessionId],
651
+ foreignColumns: [sessions.workspaceId, sessions.id]
652
+ }).onDelete("cascade"),
653
+ subjectSession: uniqueIndex("session_pins_subject_workspace_session_idx").on(
654
+ table.subjectId,
655
+ table.workspaceId,
656
+ table.sessionId
657
+ ),
658
+ subjectPinned: index("session_pins_workspace_subject_pinned_idx").on(
659
+ table.workspaceId,
660
+ table.subjectId,
661
+ table.pinned,
662
+ table.pinnedAt.desc(),
663
+ table.sessionId.desc()
664
+ )
665
+ })
666
+ );
667
+ var sessionListSnapshots = pgTable(
668
+ "session_list_snapshots",
669
+ {
670
+ id: uuid("id").primaryKey().defaultRandom(),
671
+ accountId: uuid("account_id").notNull(),
672
+ workspaceId: uuid("workspace_id").notNull(),
673
+ subjectId: text("subject_id").notNull(),
674
+ parentSessionFilter: text("parent_session_filter").notNull().default("all"),
675
+ search: text("search"),
676
+ ordinarySessionIds: uuid("ordinary_session_ids").array().notNull().default(sql`'{}'::uuid[]`),
677
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
678
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
679
+ },
680
+ (table) => ({
681
+ workspaceAccount: foreignKey({
682
+ name: "session_list_snapshots_workspace_account_fk",
683
+ columns: [table.workspaceId, table.accountId],
684
+ foreignColumns: [workspaces.id, workspaces.accountId]
685
+ }).onDelete("cascade"),
686
+ subjectNonempty: check(
687
+ "session_list_snapshots_subject_nonempty",
688
+ sql`length(btrim(${table.subjectId})) > 0`
689
+ ),
690
+ parentFilterValid: check(
691
+ "session_list_snapshots_parent_filter_valid",
692
+ sql`${table.parentSessionFilter} = 'all' or ${table.parentSessionFilter} = 'null' or ${table.parentSessionFilter} ~ '^[0-9a-fA-F-]{36}$'`
693
+ ),
694
+ searchLength: check(
695
+ "session_list_snapshots_search_length",
696
+ sql`${table.search} is null or length(${table.search}) <= 200`
697
+ ),
698
+ workspaceExpiry: index("session_list_snapshots_workspace_expiry_idx").on(
699
+ table.workspaceId,
700
+ table.subjectId,
701
+ table.expiresAt
702
+ ),
703
+ expiryReaper: index("session_list_snapshots_expiry_reaper_idx").on(table.expiresAt, table.id)
704
+ })
705
+ );
706
+ var sessionMcpServers = pgTable(
707
+ "session_mcp_servers",
708
+ {
709
+ id: uuid("id").primaryKey().defaultRandom(),
710
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
711
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
712
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
713
+ serverId: text("server_id").notNull(),
714
+ name: text("name"),
715
+ url: text("url").notNull(),
716
+ allowedTools: jsonb("allowed_tools").$type(),
717
+ timeoutMs: integer("timeout_ms"),
718
+ cacheToolsList: boolean("cache_tools_list").notNull().default(false),
719
+ // Human-approval policy: `true` = every tool requires approval, a string[] of
720
+ // UNPREFIXED tool names = only those require it, null/absent = auto-run.
721
+ requireApproval: jsonb("require_approval").$type(),
722
+ // Map of header name -> AES-GCM ciphertext. Values are decrypted only by the
723
+ // worker's run-preparation path and never returned by API helpers.
724
+ headersEncrypted: jsonb("headers_encrypted").$type().notNull().default({}),
725
+ credentialVersion: integer("credential_version").notNull().default(1),
726
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
727
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
728
+ },
729
+ (table) => ({
730
+ sessionServer: uniqueIndex("session_mcp_servers_session_server_idx").on(
731
+ table.workspaceId,
732
+ table.sessionId,
733
+ table.serverId
734
+ ),
735
+ session: index("session_mcp_servers_session_idx").on(table.workspaceId, table.sessionId)
736
+ })
737
+ );
738
+ var files = pgTable(
739
+ "files",
740
+ {
741
+ id: uuid("id").primaryKey().defaultRandom(),
742
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
743
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
744
+ status: text("status").notNull().default("pending_upload"),
745
+ filename: text("filename").notNull(),
746
+ safeFilename: text("safe_filename").notNull(),
747
+ contentType: text("content_type").notNull(),
748
+ sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(),
749
+ sha256: text("sha256"),
750
+ bucket: text("bucket").notNull(),
751
+ objectKey: text("object_key").notNull(),
752
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
753
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
754
+ },
755
+ (table) => ({
756
+ workspaceCreated: index("files_workspace_created_idx").on(table.workspaceId, table.createdAt),
757
+ objectKey: uniqueIndex("files_object_key_idx").on(table.objectKey),
758
+ status: index("files_status_idx").on(table.status)
759
+ })
760
+ );
761
+ var fileUploads = pgTable(
762
+ "file_uploads",
763
+ {
764
+ id: uuid("id").primaryKey().defaultRandom(),
765
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
766
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
767
+ fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "cascade" }),
768
+ status: text("status").notNull().default("pending"),
769
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
770
+ completedAt: timestamp("completed_at", { withTimezone: true }),
771
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
772
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
773
+ },
774
+ (table) => ({
775
+ workspace: index("file_uploads_workspace_idx").on(table.workspaceId),
776
+ fileId: index("file_uploads_file_id_idx").on(table.fileId),
777
+ status: index("file_uploads_status_idx").on(table.status)
778
+ })
779
+ );
780
+ var documentBases = pgTable(
781
+ "document_bases",
782
+ {
783
+ id: uuid("id").primaryKey().defaultRandom(),
784
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
785
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
786
+ name: text("name").notNull(),
787
+ description: text("description"),
788
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
789
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
790
+ },
791
+ (table) => ({
792
+ workspaceCreated: index("document_bases_workspace_created_idx").on(
793
+ table.workspaceId,
794
+ table.createdAt
795
+ )
796
+ })
797
+ );
798
+ var documents = pgTable(
799
+ "documents",
800
+ {
801
+ id: uuid("id").primaryKey().defaultRandom(),
802
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
803
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
804
+ baseId: uuid("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
805
+ fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
806
+ status: text("status").notNull().default("queued"),
807
+ title: text("title").notNull(),
808
+ parser: text("parser").notNull().default("liteparse"),
809
+ chunkCount: integer("chunk_count").notNull().default(0),
810
+ error: text("error"),
811
+ sourceKind: text("source_kind").notNull().default("manual_upload"),
812
+ sourceUri: text("source_uri"),
813
+ sourceExternalId: text("source_external_id"),
814
+ sourceTitle: text("source_title"),
815
+ sourceAuthor: text("source_author"),
816
+ sourceCreatedAt: timestamp("source_created_at", { withTimezone: true }),
817
+ sourceUpdatedAt: timestamp("source_updated_at", { withTimezone: true }),
818
+ sourceVersion: text("source_version"),
819
+ aclTags: jsonb("acl_tags").$type().notNull().default([]),
820
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
821
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
822
+ },
823
+ (table) => ({
824
+ baseFile: uniqueIndex("documents_workspace_base_file_idx").on(
825
+ table.workspaceId,
826
+ table.baseId,
827
+ table.fileId
828
+ ),
829
+ baseStatus: index("documents_workspace_base_status_idx").on(
830
+ table.workspaceId,
831
+ table.baseId,
832
+ table.status
833
+ ),
834
+ sourceKind: index("documents_workspace_source_kind_idx").on(
835
+ table.workspaceId,
836
+ table.sourceKind
837
+ ),
838
+ sourceExternalId: index("documents_workspace_source_external_id_idx").on(
839
+ table.workspaceId,
840
+ table.sourceExternalId
841
+ )
842
+ })
843
+ );
844
+ var documentChunks = pgTable(
845
+ "document_chunks",
846
+ {
847
+ id: uuid("id").primaryKey().defaultRandom(),
848
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
849
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
850
+ documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
851
+ baseId: uuid("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
852
+ fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
853
+ chunkIndex: integer("chunk_index").notNull(),
854
+ text: text("text").notNull(),
855
+ metadata: jsonb("metadata").$type().notNull().default({}),
856
+ embedding: vector("embedding").notNull(),
857
+ embeddingModel: text("embedding_model").notNull(),
858
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
859
+ },
860
+ (table) => ({
861
+ documentIndex: uniqueIndex("document_chunks_workspace_document_index_idx").on(
862
+ table.workspaceId,
863
+ table.documentId,
864
+ table.chunkIndex
865
+ ),
866
+ base: index("document_chunks_workspace_base_idx").on(table.workspaceId, table.baseId)
867
+ })
868
+ );
869
+ var knowledgeMemories = pgTable(
870
+ "knowledge_memories",
871
+ {
872
+ id: uuid("id").primaryKey().defaultRandom(),
873
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
874
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
875
+ status: text("status").notNull().default("proposed"),
876
+ kind: text("kind").notNull().default("semantic"),
877
+ scope: text("scope").notNull().default("workspace"),
878
+ text: text("text").notNull(),
879
+ sourceRefs: jsonb("source_refs").$type().notNull().default([]),
880
+ confidence: integer("confidence").notNull().default(50),
881
+ metadata: jsonb("metadata").$type().notNull().default({}),
882
+ createdBySessionId: uuid("created_by_session_id").references(() => sessions.id, {
883
+ onDelete: "set null"
884
+ }),
885
+ reviewedBy: text("reviewed_by"),
886
+ reviewedAt: timestamp("reviewed_at", { withTimezone: true }),
887
+ // Workspace Memory V1 (migration 0045). Embedding is nullable: fail-soft writes
888
+ // (embedder unavailable) persist keyword-searchable rows without a vector.
889
+ embedding: vector("embedding"),
890
+ embeddingModel: text("embedding_model"),
891
+ pinned: boolean("pinned").notNull().default(false),
892
+ usageCount: integer("usage_count").notNull().default(0),
893
+ lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
894
+ // Self-referential supersession chain. FKs live in migration 0045 (ON DELETE SET
895
+ // NULL); declared here as plain columns like the migration-only composite FK.
896
+ supersedesId: uuid("supersedes_id"),
897
+ supersededById: uuid("superseded_by_id"),
898
+ validFrom: timestamp("valid_from", { withTimezone: true }).notNull().defaultNow(),
899
+ validUntil: timestamp("valid_until", { withTimezone: true }),
900
+ // sha256(normalizeMemoryText(text)) — exact-dedup key; see memory-domain.
901
+ textHash: text("text_hash"),
902
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
903
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
904
+ },
905
+ (table) => ({
906
+ workspaceStatus: index("knowledge_memories_workspace_status_idx").on(
907
+ table.workspaceId,
908
+ table.status,
909
+ table.updatedAt
910
+ ),
911
+ workspaceKind: index("knowledge_memories_workspace_kind_idx").on(table.workspaceId, table.kind),
912
+ workspaceScope: index("knowledge_memories_workspace_scope_idx").on(
913
+ table.workspaceId,
914
+ table.scope
915
+ ),
916
+ createdBySession: index("knowledge_memories_workspace_created_by_session_idx").on(
917
+ table.workspaceId,
918
+ table.createdBySessionId
919
+ ),
920
+ // Working-set selection (partial index mirrors migration 0045).
921
+ workspaceVisible: index("knowledge_memories_workspace_visible_idx").on(table.workspaceId, table.pinned, table.updatedAt).where(sql`${table.status} in ('active', 'approved')`),
922
+ workspaceTextHash: index("knowledge_memories_workspace_text_hash_idx").on(
923
+ table.workspaceId,
924
+ table.textHash
925
+ ),
926
+ workspaceVisibleTextHashUnique: uniqueIndex("knowledge_memories_workspace_visible_text_hash_uq").on(table.workspaceId, table.textHash).where(sql`${table.status} in ('active', 'approved') and ${table.textHash} is not null`)
927
+ })
928
+ );
929
+ var sessionTurns = pgTable(
930
+ "session_turns",
931
+ {
932
+ id: uuid("id").primaryKey().defaultRandom(),
933
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
934
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
935
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
936
+ triggerEventId: uuid("trigger_event_id").notNull(),
937
+ temporalWorkflowId: text("temporal_workflow_id").notNull(),
938
+ status: text("status").notNull(),
939
+ source: text("source").notNull().default("user"),
940
+ position: bigint("position", { mode: "number" }).notNull(),
941
+ prompt: text("prompt").notNull(),
942
+ resources: jsonb("resources").$type().notNull().default([]),
943
+ tools: jsonb("tools").$type().notNull().default([]),
944
+ model: text("model").notNull(),
945
+ reasoningEffort: text("reasoning_effort").notNull(),
946
+ sandboxBackend: text("sandbox_backend").notNull(),
947
+ // Per-turn OS override. NULL = inherit the session's sandbox_os. CHECK-
948
+ // constrained to the SandboxOs enum (or NULL) in migration 0018.
949
+ sandboxOs: text("sandbox_os"),
950
+ metadata: jsonb("metadata").$type().notNull().default({}),
951
+ version: integer("version").notNull().default(1),
952
+ executionGeneration: integer("execution_generation").notNull().default(0),
953
+ activeAttemptId: uuid("active_attempt_id"),
954
+ lineage: jsonb("lineage").$type().notNull().default({}),
955
+ cancelledBy: text("cancelled_by"),
956
+ cancelReason: text("cancel_reason"),
957
+ // Atomic per-turn toolspace call budget counter (migration 0043). Incremented
958
+ // by a single conditional UPDATE at tools/call time; the row lock serializes
959
+ // concurrent reservations so exactly `toolspaceMaxCallsPerTurn` succeed.
960
+ toolspaceCallCount: integer("toolspace_call_count").notNull().default(0),
961
+ startedAt: timestamp("started_at", { withTimezone: true }),
962
+ finishedAt: timestamp("finished_at", { withTimezone: true }),
963
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
964
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
965
+ },
966
+ (table) => ({
967
+ workspaceIdentity: uniqueIndex("session_turns_workspace_id_idx").on(
968
+ table.workspaceId,
969
+ table.id
970
+ ),
971
+ queue: index("session_turns_workspace_queue_idx").on(
972
+ table.workspaceId,
973
+ table.sessionId,
974
+ table.status,
975
+ table.position
976
+ ),
977
+ oneCurrentInference: uniqueIndex("session_turns_one_current_inference_uq").on(table.workspaceId, table.sessionId).where(sql`${table.status} in ('running','requires_action','recovering','waiting_capacity')`)
978
+ })
979
+ );
980
+ var sessionSystemUpdates = pgTable(
981
+ "session_system_updates",
982
+ {
983
+ id: uuid("id").primaryKey().defaultRandom(),
984
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
985
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
986
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
987
+ kind: text("kind").notNull(),
988
+ classification: text("classification").notNull().default("info"),
989
+ sourceId: text("source_id").notNull(),
990
+ dedupeKey: text("dedupe_key").notNull(),
991
+ summary: text("summary").notNull(),
992
+ payload: jsonb("payload").$type().notNull().default({}),
993
+ lineage: jsonb("lineage").$type().notNull().default({}),
994
+ // pending: eligible to start/attach to an inference; deferred: preserved
995
+ // after a failed internal-only inference but dormant until a real prompt or
996
+ // a genuinely new pending update arrives; delivered/cancelled/failed are
997
+ // terminal for that delivery attempt.
998
+ state: text("state").notNull().default("pending"),
999
+ deliveredTurnId: uuid("delivered_turn_id").references(() => sessionTurns.id, {
1000
+ onDelete: "set null"
1001
+ }),
1002
+ deliveredAt: timestamp("delivered_at", { withTimezone: true }),
1003
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1004
+ },
1005
+ (table) => ({
1006
+ dedupe: uniqueIndex("session_system_updates_dedupe_uq").on(
1007
+ table.workspaceId,
1008
+ table.sessionId,
1009
+ table.dedupeKey
1010
+ ),
1011
+ pending: index("session_system_updates_pending_idx").on(
1012
+ table.workspaceId,
1013
+ table.sessionId,
1014
+ table.state,
1015
+ table.createdAt
1016
+ )
1017
+ })
1018
+ );
1019
+ var runtimeControlOperations = pgTable(
1020
+ "runtime_control_operations",
1021
+ {
1022
+ id: uuid("id").primaryKey().defaultRandom(),
1023
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1024
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1025
+ scope: text("scope").notNull(),
1026
+ targetId: uuid("target_id").notNull(),
1027
+ clientEventId: text("client_event_id").notNull(),
1028
+ requestedState: text("requested_state").notNull(),
1029
+ expectedState: text("expected_state"),
1030
+ expectedGeneration: integer("expected_generation"),
1031
+ result: jsonb("result").$type().notNull().default({}),
1032
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1033
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1034
+ },
1035
+ (table) => ({
1036
+ idempotency: uniqueIndex("runtime_control_operations_client_uq").on(
1037
+ table.workspaceId,
1038
+ table.clientEventId
1039
+ ),
1040
+ target: index("runtime_control_operations_target_idx").on(
1041
+ table.workspaceId,
1042
+ table.scope,
1043
+ table.targetId,
1044
+ table.createdAt
1045
+ )
1046
+ })
1047
+ );
1048
+ var sessionSystemUpdateOutbox = pgTable(
1049
+ "session_system_update_outbox",
1050
+ {
1051
+ id: uuid("id").primaryKey().defaultRandom(),
1052
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1053
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1054
+ sourceSessionId: uuid("source_session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1055
+ targetSessionId: uuid("target_session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1056
+ dedupeKey: text("dedupe_key").notNull(),
1057
+ kind: text("kind").notNull(),
1058
+ classification: text("classification").notNull(),
1059
+ sourceId: text("source_id").notNull(),
1060
+ summary: text("summary").notNull(),
1061
+ payload: jsonb("payload").$type().notNull().default({}),
1062
+ lineage: jsonb("lineage").$type().notNull().default({}),
1063
+ status: text("status").notNull().default("pending"),
1064
+ attempts: integer("attempts").notNull().default(0),
1065
+ updateId: uuid("update_id"),
1066
+ lastError: text("last_error"),
1067
+ deliveredAt: timestamp("delivered_at", { withTimezone: true }),
1068
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1069
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1070
+ },
1071
+ (table) => ({
1072
+ dedupe: uniqueIndex("session_system_update_outbox_dedupe_uq").on(
1073
+ table.workspaceId,
1074
+ table.dedupeKey
1075
+ ),
1076
+ pending: index("session_system_update_outbox_pending_idx").on(table.status, table.createdAt)
1077
+ })
1078
+ );
1079
+ var sessionWorkflowWakeOutbox = pgTable(
1080
+ "session_workflow_wake_outbox",
1081
+ {
1082
+ sessionId: uuid("session_id").primaryKey(),
1083
+ accountId: uuid("account_id").notNull(),
1084
+ workspaceId: uuid("workspace_id").notNull(),
1085
+ temporalWorkflowId: text("temporal_workflow_id").notNull(),
1086
+ wakeRevision: bigint("wake_revision", { mode: "number" }).notNull().default(1),
1087
+ deliveredRevision: bigint("delivered_revision", { mode: "number" }).notNull().default(0),
1088
+ reason: text("reason").notNull(),
1089
+ attempts: integer("attempts").notNull().default(0),
1090
+ nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
1091
+ lastError: text("last_error"),
1092
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1093
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1094
+ },
1095
+ (table) => ({
1096
+ revisionValid: check(
1097
+ "session_workflow_wake_outbox_revision_check",
1098
+ sql`${table.wakeRevision} > 0 and ${table.deliveredRevision} >= 0 and ${table.deliveredRevision} <= ${table.wakeRevision}`
1099
+ ),
1100
+ workspaceAccount: foreignKey({
1101
+ name: "session_workflow_wake_outbox_workspace_account_fk",
1102
+ columns: [table.workspaceId, table.accountId],
1103
+ foreignColumns: [workspaces.id, workspaces.accountId]
1104
+ }).onDelete("cascade"),
1105
+ workspaceSessionFk: foreignKey({
1106
+ name: "session_workflow_wake_outbox_workspace_session_fk",
1107
+ columns: [table.workspaceId, table.sessionId],
1108
+ foreignColumns: [sessions.workspaceId, sessions.id]
1109
+ }).onDelete("cascade"),
1110
+ workspaceSession: uniqueIndex("session_workflow_wake_outbox_workspace_session_uq").on(
1111
+ table.workspaceId,
1112
+ table.sessionId
1113
+ ),
1114
+ pending: index("session_workflow_wake_outbox_pending_idx").on(table.nextAttemptAt, table.updatedAt, table.sessionId).where(sql`${table.wakeRevision} > ${table.deliveredRevision}`)
1115
+ })
1116
+ );
1117
+ var sessionGoals = pgTable(
1118
+ "session_goals",
1119
+ {
1120
+ id: uuid("id").primaryKey().defaultRandom(),
1121
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1122
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1123
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1124
+ status: text("status").notNull().default("active"),
1125
+ // active | paused | completed
1126
+ text: text("text").notNull(),
1127
+ successCriteria: text("success_criteria"),
1128
+ evidence: text("evidence"),
1129
+ // set by goal_complete
1130
+ rationale: text("rationale"),
1131
+ // set by goal_pause
1132
+ pausedReason: text("paused_reason"),
1133
+ // agent | user_pause | api | no_progress | max_auto_continuations | limits
1134
+ createdBy: text("created_by").notNull().default("api"),
1135
+ // api | agent | scheduled_task
1136
+ version: integer("version").notNull().default(1),
1137
+ // bumped on every set/update; progress signal
1138
+ autoContinuations: integer("auto_continuations").notNull().default(0),
1139
+ noProgressStreak: integer("no_progress_streak").notNull().default(0),
1140
+ maxAutoContinuations: integer("max_auto_continuations"),
1141
+ // per-goal override; a configured settings cap (if any) remains the hard ceiling
1142
+ lastContinuationTurnId: uuid("last_continuation_turn_id"),
1143
+ versionAtLastContinuation: integer("version_at_last_continuation"),
1144
+ metadata: jsonb("metadata").$type().notNull().default({}),
1145
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1146
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1147
+ },
1148
+ (table) => ({
1149
+ workspaceIdentity: uniqueIndex("session_goals_workspace_id_idx").on(
1150
+ table.workspaceId,
1151
+ table.id
1152
+ ),
1153
+ workspaceSession: uniqueIndex("session_goals_workspace_session_idx").on(
1154
+ table.workspaceId,
1155
+ table.sessionId
1156
+ ),
1157
+ status: index("session_goals_workspace_status_idx").on(table.workspaceId, table.status)
1158
+ })
1159
+ );
1160
+ var codexCapacityWaiters = pgTable(
1161
+ "codex_capacity_waiters",
1162
+ {
1163
+ id: uuid("id").primaryKey().defaultRandom(),
1164
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1165
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1166
+ sessionId: uuid("session_id").notNull(),
1167
+ goalId: uuid("goal_id").notNull(),
1168
+ blockedTurnId: uuid("blocked_turn_id").notNull(),
1169
+ workflowId: text("workflow_id").notNull(),
1170
+ generation: integer("generation").notNull().default(1),
1171
+ status: text("status").notNull().default("waiting"),
1172
+ // waiting | resumed | superseded
1173
+ goalVersion: integer("goal_version").notNull(),
1174
+ controlGeneration: integer("control_generation").notNull().default(0),
1175
+ policyHash: text("policy_hash"),
1176
+ earliestResetAt: timestamp("earliest_reset_at", { withTimezone: true }),
1177
+ nextCheckAt: timestamp("next_check_at", { withTimezone: true }).notNull(),
1178
+ resetKind: text("reset_kind").notNull(),
1179
+ // authoritative | bounded_refresh
1180
+ refreshAttempt: integer("refresh_attempt").notNull().default(0),
1181
+ // Coalescing outbox generation. Every eligibility-affecting mutation bumps
1182
+ // wakeRevision. Duplicate/lost Temporal signals are harmless because only
1183
+ // the row-locked evaluator moves observedWakeRevision and may enqueue work.
1184
+ wakeRevision: integer("wake_revision").notNull().default(1),
1185
+ observedWakeRevision: integer("observed_wake_revision").notNull().default(0),
1186
+ lastWakeReason: text("last_wake_reason").notNull().default("capacity_wait_armed"),
1187
+ resumedUpdateId: uuid("resumed_update_id"),
1188
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1189
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1190
+ },
1191
+ (table) => ({
1192
+ workspaceSession: uniqueIndex("codex_capacity_waiters_workspace_session_idx").on(
1193
+ table.workspaceId,
1194
+ table.sessionId
1195
+ ),
1196
+ workspaceId: uniqueIndex("codex_capacity_waiters_workspace_id_idx").on(
1197
+ table.workspaceId,
1198
+ table.id
1199
+ ),
1200
+ pending: index("codex_capacity_waiters_pending_idx").on(
1201
+ table.workspaceId,
1202
+ table.status,
1203
+ table.nextCheckAt
1204
+ ),
1205
+ wakeRepair: index("codex_capacity_waiters_wake_repair_idx").on(
1206
+ table.status,
1207
+ table.wakeRevision,
1208
+ table.observedWakeRevision
1209
+ )
1210
+ })
1211
+ );
1212
+ var sessionEvents = pgTable(
1213
+ "session_events",
1214
+ {
1215
+ id: uuid("id").primaryKey().defaultRandom(),
1216
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1217
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1218
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1219
+ turnId: uuid("turn_id"),
1220
+ turnGeneration: integer("turn_generation"),
1221
+ turnAttemptId: uuid("turn_attempt_id"),
1222
+ turnAssociation: text("turn_association"),
1223
+ duplicateOfEventId: uuid("duplicate_of_event_id"),
1224
+ duplicateReason: text("duplicate_reason"),
1225
+ sequence: integer("sequence").notNull(),
1226
+ type: text("type").notNull(),
1227
+ payload: jsonb("payload").$type().notNull().default({}),
1228
+ clientEventId: text("client_event_id"),
1229
+ producerId: text("producer_id"),
1230
+ producerSeq: integer("producer_seq"),
1231
+ occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
1232
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1233
+ },
1234
+ (table) => ({
1235
+ sessionSequence: uniqueIndex("session_events_workspace_session_sequence_idx").on(
1236
+ table.workspaceId,
1237
+ table.sessionId,
1238
+ table.sequence
1239
+ ),
1240
+ clientEvent: uniqueIndex("session_events_workspace_client_event_idx").on(table.workspaceId, table.sessionId, table.clientEventId).where(sql`${table.clientEventId} is not null`),
1241
+ producer: uniqueIndex("session_events_workspace_producer_idx").on(table.workspaceId, table.sessionId, table.producerId, table.producerSeq).where(sql`${table.producerId} is not null and ${table.producerSeq} is not null`),
1242
+ sessionCreated: index("session_events_workspace_session_created_idx").on(
1243
+ table.workspaceId,
1244
+ table.sessionId,
1245
+ table.createdAt
1246
+ )
1247
+ })
1248
+ );
1249
+ var agentRunStates = pgTable("agent_run_states", {
1250
+ id: uuid("id").primaryKey().defaultRandom(),
1251
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1252
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1253
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1254
+ turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
1255
+ stateVersion: integer("state_version").notNull(),
1256
+ serializedRunState: text("serialized_run_state").notNull(),
1257
+ pendingApprovals: jsonb("pending_approvals").$type().notNull().default([]),
1258
+ // The Codex account that FROZE this run state: the turn's resolved codex
1259
+ // credential id (pin > workspace-active), or NULL when frozen on the
1260
+ // non-codex / Azure path (or before this column existed). The serialized
1261
+ // RunState blob round-trips `reasoning.encrypted_content` minted by the
1262
+ // ChatGPT/Codex backend — account/org-bound, so a foreign blob 400s — and the
1263
+ // foreign reasoning ids the Responses backend validates; but the blob carries
1264
+ // NO per-item producer tag (those live only on session_history_items). So we
1265
+ // stamp the freezing account here: on an approval resume whose codex account
1266
+ // DIFFERS from this value,
1267
+ // the replay path neutralizes every reasoning item's account-bound identity
1268
+ // (encrypted_content + provider id) in the blob before it reaches the model.
1269
+ // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect (a
1270
+ // stale-but-null tag still mismatches a live codex id, so the strip stays
1271
+ // correct either way). NULL on both sides (non-codex freeze + non-codex
1272
+ // resume) is a no-op, so single-account and non-codex sessions are unchanged.
1273
+ frozenCodexCredentialId: uuid("frozen_codex_credential_id"),
1274
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1275
+ });
1276
+ var sessionHistoryItems = pgTable(
1277
+ "session_history_items",
1278
+ {
1279
+ id: uuid("id").primaryKey().defaultRandom(),
1280
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1281
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1282
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1283
+ turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
1284
+ // Numeric (not integer) so the synthetic compaction-summary row can be
1285
+ // inserted at a FRACTIONAL position (boundaryPosition - 0.5) that sorts ahead
1286
+ // of the kept tail without colliding with — and thus overwriting — the real
1287
+ // prefix row at boundaryPosition - 1. Normally-appended rows keep whole-number
1288
+ // positions; only the summary uses the half-step. `mode: "number"` maps the
1289
+ // postgres.js string back to a JS number so every reader stays numeric.
1290
+ position: numeric("position", { mode: "number" }).notNull(),
1291
+ item: jsonb("item").$type().notNull(),
1292
+ // Live-row flag for client-side context compaction. The read path selects
1293
+ // only active rows; a compaction supersedes the summarized prefix (sets this
1294
+ // false — never deletes, so the full transcript stays as an audit trail) and
1295
+ // inserts ONE synthetic active summary row at the boundary. Defaults true so
1296
+ // every existing and normally-appended row is live.
1297
+ active: boolean("active").notNull().default(true),
1298
+ // The Codex account that PRODUCED these items: the per-turn resolved codex
1299
+ // credential id (pin > workspace-active), or NULL when produced on the
1300
+ // non-codex / Azure path (or before this column existed). Used to strip
1301
+ // cross-account `reasoning.encrypted_content` blobs — those are account/org-
1302
+ // bound, minted by the ChatGPT/Codex backend, so replaying account A's blob
1303
+ // into a turn running on account B 400s. The read path drops the encrypted
1304
+ // reasoning of any item whose producer != the turn's current codex account.
1305
+ // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect
1306
+ // (an ON DELETE SET NULL would erase the tag, and a stale-but-null tag still
1307
+ // mismatches a live codex id so the strip stays correct either way).
1308
+ producerCodexCredentialId: uuid("producer_codex_credential_id"),
1309
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1310
+ },
1311
+ (table) => ({
1312
+ positionIdx: uniqueIndex("session_history_items_position_idx").on(
1313
+ table.workspaceId,
1314
+ table.sessionId,
1315
+ table.position
1316
+ )
1317
+ })
1318
+ );
1319
+ var sessionPendingToolCalls = pgTable(
1320
+ "session_pending_tool_calls",
1321
+ {
1322
+ id: uuid("id").primaryKey().defaultRandom(),
1323
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1324
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1325
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1326
+ turnId: uuid("turn_id").notNull().references(() => sessionTurns.id, { onDelete: "cascade" }),
1327
+ executionGeneration: integer("execution_generation").notNull(),
1328
+ attemptId: uuid("attempt_id").notNull(),
1329
+ callId: text("call_id").notNull(),
1330
+ callType: text("call_type").notNull(),
1331
+ callItem: jsonb("call_item").$type().notNull(),
1332
+ resultItem: jsonb("result_item").$type(),
1333
+ resultRecordedAt: timestamp("result_recorded_at", { withTimezone: true }),
1334
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1335
+ },
1336
+ (table) => ({
1337
+ turnCall: uniqueIndex("session_pending_tool_calls_turn_call_idx").on(
1338
+ table.workspaceId,
1339
+ table.turnId,
1340
+ table.callId
1341
+ ),
1342
+ sessionTurn: index("session_pending_tool_calls_session_turn_idx").on(
1343
+ table.workspaceId,
1344
+ table.sessionId,
1345
+ table.turnId
1346
+ )
1347
+ })
1348
+ );
1349
+ var sandboxSessionEnvelopes = pgTable(
1350
+ "sandbox_session_envelopes",
1351
+ {
1352
+ id: uuid("id").primaryKey().defaultRandom(),
1353
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1354
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1355
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1356
+ envelope: jsonb("envelope").$type().notNull(),
1357
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1358
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1359
+ },
1360
+ (table) => ({
1361
+ sessionIdx: uniqueIndex("sandbox_session_envelopes_session_idx").on(
1362
+ table.workspaceId,
1363
+ table.sessionId
1364
+ )
1365
+ })
1366
+ );
1367
+ var sandboxLeaseLivenessValues = ["cold", "warming", "warm", "draining"];
1368
+ var sandboxLeases = pgTable(
1369
+ "sandbox_leases",
1370
+ {
1371
+ id: uuid("id").primaryKey().defaultRandom(),
1372
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1373
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1374
+ sandboxGroupId: uuid("sandbox_group_id").notNull(),
1375
+ liveness: text("liveness", { enum: sandboxLeaseLivenessValues }).notNull().default("cold"),
1376
+ refcount: integer("refcount").notNull().default(0),
1377
+ turnHolders: integer("turn_holders").notNull().default(0),
1378
+ viewerHolders: integer("viewer_holders").notNull().default(0),
1379
+ instanceId: text("instance_id"),
1380
+ backend: text("backend").notNull(),
1381
+ os: text("os").notNull().default("linux"),
1382
+ // The container IMAGE the group box runs (Modal image ref / docker image). A shared
1383
+ // box is SHARED STATE: all its sessions run the SAME filesystem, so they must run the
1384
+ // same image. This column stamps the image the live box was created with; a resume
1385
+ // whose resolved image DIFFERS is a conflict (B3): a solo holder recreates the box on
1386
+ // the new image, N-holders are rejected (SandboxImageConflictError). Nullable — a
1387
+ // legacy/cold row reads NULL = "image unknown", which never conflicts.
1388
+ image: text("image"),
1389
+ // The frozen rig version the live box was created under (M3). Like `image`,
1390
+ // this is SHARED STATE: all the box's sessions run the same rig-baked setup,
1391
+ // so a resume resolving a DIFFERENT rig_version_id conflicts (solo holder
1392
+ // recreates cold on the new rig; N-holders throw SandboxRigConflictError).
1393
+ // Nullable — a legacy/cold row or a rig-less session reads NULL = "rig
1394
+ // unknown", which never conflicts. No FK (symmetric with sandbox_group_id's
1395
+ // bare-uuid rationale: this lease outlives no single rig_versions row's RLS).
1396
+ rigVersionId: uuid("rig_version_id"),
1397
+ dataPlaneUrl: text("data_plane_url"),
1398
+ // The REAL PTY terminal (ttyd pty-ws) rides a SEPARATE provider tunnel (7681)
1399
+ // from the desktop noVNC (6080), so its resolved URL is cached independently.
1400
+ // Recorded under the epoch fence by recordLeaseTerminalDataPlaneUrl; reset to
1401
+ // null on every box re-key (warm-commit / fail / drain), symmetric with
1402
+ // data_plane_url.
1403
+ terminalDataPlaneUrl: text("terminal_data_plane_url"),
1404
+ // integer (NOT bigint): the lease-epoch spike proved a raw int8 read returns a
1405
+ // JS STRING from postgres-js, breaking the strict epoch-fence comparison (it
1406
+ // was always-true → every turn fenced); int4 returns a JS number, the fix.
1407
+ // Epochs never approach 2^31, so the narrower type loses nothing.
1408
+ leaseEpoch: integer("lease_epoch").notNull().default(0),
1409
+ // The group box-envelope (the "envelope split" Critical): the small recovery
1410
+ // descriptor to resume()-by-id the group's box without a per-session join.
1411
+ resumeBackendId: text("resume_backend_id"),
1412
+ resumeState: jsonb("resume_state").$type(),
1413
+ // Warm-time billing cursor: last_meter_at = accrual cursor; last_meter_tick =
1414
+ // idempotency tick (warm_seconds accrued idempotent on
1415
+ // (sandbox_group_id, lease_epoch, last_meter_tick) in P2.1).
1416
+ lastMeterAt: timestamp("last_meter_at", { withTimezone: true }),
1417
+ lastMeterTick: integer("last_meter_tick").notNull().default(0),
1418
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
1419
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1420
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1421
+ },
1422
+ (table) => ({
1423
+ groupIdx: uniqueIndex("sandbox_leases_group_idx").on(table.workspaceId, table.sandboxGroupId),
1424
+ reaperIdx: index("sandbox_leases_reaper_idx").on(table.expiresAt).where(sql`${table.liveness} in ('warming','warm','draining')`)
1425
+ })
1426
+ );
1427
+ var sandboxLeaseHolders = pgTable(
1428
+ "sandbox_lease_holders",
1429
+ {
1430
+ id: uuid("id").primaryKey().defaultRandom(),
1431
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1432
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1433
+ leaseId: uuid("lease_id").notNull().references(() => sandboxLeases.id, { onDelete: "cascade" }),
1434
+ kind: text("kind", { enum: ["turn", "viewer"] }).notNull(),
1435
+ holderId: text("holder_id").notNull(),
1436
+ // The attributing session within the (possibly shared) group.
1437
+ subjectId: uuid("subject_id"),
1438
+ lastHeartbeatAt: timestamp("last_heartbeat_at", { withTimezone: true }).notNull().defaultNow(),
1439
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1440
+ },
1441
+ (table) => ({
1442
+ holderIdx: uniqueIndex("sandbox_lease_holders_holder_idx").on(
1443
+ table.leaseId,
1444
+ table.kind,
1445
+ table.holderId
1446
+ ),
1447
+ staleIdx: index("sandbox_lease_holders_stale_idx").on(table.kind, table.lastHeartbeatAt),
1448
+ leaseIdx: index("sandbox_lease_holders_lease_idx").on(table.leaseId)
1449
+ })
1450
+ );
1451
+ var sessionRecordingStateValues = [
1452
+ "recording",
1453
+ "finalizing",
1454
+ "available",
1455
+ "failed"
1456
+ ];
1457
+ var sessionRecordingModeValues = ["manual", "on-turn", "on-verify"];
1458
+ var sessionRecordingCodecValues = ["h264-mp4", "vp9-webm"];
1459
+ var sessionRecordings = pgTable(
1460
+ "session_recordings",
1461
+ {
1462
+ id: uuid("id").primaryKey().defaultRandom(),
1463
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1464
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1465
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1466
+ turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
1467
+ state: text("state", { enum: sessionRecordingStateValues }).notNull(),
1468
+ mode: text("mode", { enum: sessionRecordingModeValues }).notNull(),
1469
+ codec: text("codec", { enum: sessionRecordingCodecValues }).notNull(),
1470
+ storageKey: text("storage_key"),
1471
+ sizeBytes: bigint("size_bytes", { mode: "number" }),
1472
+ durationSeconds: numeric("duration_seconds").$type(),
1473
+ width: integer("width").notNull(),
1474
+ height: integer("height").notNull(),
1475
+ reason: text("reason"),
1476
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1477
+ finalizedAt: timestamp("finalized_at", { withTimezone: true })
1478
+ },
1479
+ (table) => ({
1480
+ sessionIdx: index("session_recordings_session_idx").on(
1481
+ table.workspaceId,
1482
+ table.sessionId,
1483
+ table.createdAt
1484
+ )
1485
+ })
1486
+ );
1487
+ var workspaceCaptures = pgTable(
1488
+ "workspace_captures",
1489
+ {
1490
+ id: uuid("id").primaryKey().defaultRandom(),
1491
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1492
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1493
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1494
+ turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
1495
+ revision: bigint("revision", { mode: "number" }).notNull(),
1496
+ leaseEpoch: integer("lease_epoch").notNull(),
1497
+ // 'available' on a committed capture. 'failed' reserved for a future two-phase
1498
+ // write; the current synchronous capture only ever inserts 'available'.
1499
+ state: text("state", { enum: ["available", "failed"] }).notNull().default("available"),
1500
+ // Single JSON manifest blob (tree index + repos + file refs) — the cold-paint payload.
1501
+ manifestKey: text("manifest_key"),
1502
+ // The fs tree index blob, kept separate from the manifest so the API can inline
1503
+ // or sign it independently of the (usually small) manifest metadata.
1504
+ treeIndexKey: text("tree_index_key"),
1505
+ // Content-addressed after-image blob keys this revision references (GC input).
1506
+ blobKeys: jsonb("blob_keys").$type().notNull().default([]),
1507
+ sizeBytes: bigint("size_bytes", { mode: "number" }),
1508
+ stats: jsonb("stats").$type().notNull().default({}),
1509
+ capturedAt: timestamp("captured_at", { withTimezone: true }).notNull().defaultNow()
1510
+ },
1511
+ (table) => ({
1512
+ sessionRevision: uniqueIndex("workspace_captures_session_revision_idx").on(
1513
+ table.sessionId,
1514
+ table.revision
1515
+ ),
1516
+ latest: index("workspace_captures_latest_idx").on(
1517
+ table.workspaceId,
1518
+ table.sessionId,
1519
+ table.revision
1520
+ )
1521
+ })
1522
+ );
1523
+ var sandboxPtySessions = pgTable(
1524
+ "sandbox_pty_sessions",
1525
+ {
1526
+ id: uuid("id").primaryKey().defaultRandom(),
1527
+ // == ptyId on the wire
1528
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1529
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1530
+ sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1531
+ // The SDK numeric exec-session id used by writeStdin({ sessionId }). Null until
1532
+ // the open exec yields a still-running process (a fast-exiting shell has none).
1533
+ execSessionId: integer("exec_session_id"),
1534
+ leaseEpoch: integer("lease_epoch").notNull(),
1535
+ // fenced to the box that opened it
1536
+ cols: integer("cols").notNull(),
1537
+ rows: integer("rows").notNull(),
1538
+ shell: text("shell").notNull(),
1539
+ cwd: text("cwd").notNull(),
1540
+ status: text("status").notNull().default("open"),
1541
+ // 'open' | 'closed'
1542
+ // The viewer grant/subject that opened it (free-text — access subjects are not
1543
+ // always UUIDs, M5; so a text column, never a uuid NOT NULL).
1544
+ openedBy: text("opened_by").notNull(),
1545
+ lastInputAt: timestamp("last_input_at", { withTimezone: true }).notNull().defaultNow(),
1546
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1547
+ closedAt: timestamp("closed_at", { withTimezone: true })
1548
+ },
1549
+ (table) => ({
1550
+ openIdx: index("sandbox_pty_sessions_session_idx").on(table.workspaceId, table.sessionId).where(sql`${table.status} = 'open'`)
1551
+ })
1552
+ );
1553
+ var enrollmentExposureValues = ["whole-machine"];
1554
+ var enrollmentStatusValues = ["active", "revoked"];
1555
+ var enrollmentOsValues = ["linux", "macos", "windows"];
1556
+ var sandboxKindValues = ["modal", "selfhosted"];
1557
+ var enrollments = pgTable(
1558
+ "enrollments",
1559
+ {
1560
+ id: uuid("id").primaryKey().defaultRandom(),
1561
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1562
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1563
+ // The agent's ed25519 public key (the machine identity).
1564
+ pubkey: text("pubkey").notNull(),
1565
+ exposure: text("exposure", { enum: enrollmentExposureValues }).notNull().default("whole-machine"),
1566
+ hasDisplay: boolean("has_display").notNull().default(false),
1567
+ // Refreshed from every connect Hello (Capabilities.op_stream); false for
1568
+ // agents predating the op-stream engine.
1569
+ opStream: boolean("op_stream").notNull().default(false),
1570
+ // When the machine has a display it CANNOT capture (macOS Screen Recording / TCC
1571
+ // not granted), the agent reports has_display=false AND a human, actionable reason
1572
+ // here (e.g. "grant Screen Recording in System Settings"). NULL means capture is
1573
+ // permitted (has_display=true) or the machine is genuinely headless — the reason
1574
+ // distinguishes "display present but capture not granted" from plain "no display"
1575
+ // so the Machines dashboard / VM picker can surface the specific hint. Refreshed
1576
+ // from every connect Hello alongside has_display.
1577
+ desktopUnavailableReason: text("desktop_unavailable_reason"),
1578
+ allowScreenControl: boolean("allow_screen_control").notNull().default(false),
1579
+ status: text("status", { enum: enrollmentStatusValues }).notNull().default("active"),
1580
+ os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"),
1581
+ arch: text("arch").notNull().default("x86_64"),
1582
+ // Heartbeat liveness cursor. Null until the first connect.
1583
+ lastSeenAt: timestamp("last_seen_at", { withTimezone: true }),
1584
+ // Clean going-offline marker (migration 0049). Set when the machine announces a
1585
+ // typed GoingOffline (user-stop / self-update / host-shutdown); the liveness
1586
+ // derivation reads an un-cleared marker as OFFLINE immediately, regardless of a
1587
+ // still-fresh last_seen. Any newer liveness signal (a reconnect Hello or a
1588
+ // fresher heartbeat via touchEnrollmentLastSeen) clears BOTH back to NULL. NULL
1589
+ // (the default) ⇒ no goodbye pending — today's last_seen-aging behavior.
1590
+ wentOfflineAt: timestamp("went_offline_at", { withTimezone: true }),
1591
+ wentOfflineReason: text("went_offline_reason"),
1592
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1593
+ revokedAt: timestamp("revoked_at", { withTimezone: true }),
1594
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1595
+ },
1596
+ (table) => ({
1597
+ // One enrollment per (workspace, pubkey): a re-enroll is an idempotent upsert.
1598
+ workspacePubkey: uniqueIndex("enrollments_workspace_pubkey_idx").on(
1599
+ table.workspaceId,
1600
+ table.pubkey
1601
+ ),
1602
+ // List a workspace's ACTIVE machines without scanning revoked rows.
1603
+ workspaceStatus: index("enrollments_workspace_status_idx").on(table.workspaceId, table.status)
1604
+ })
1605
+ );
1606
+ var deviceEnrollmentStatusValues = ["pending", "approved", "denied", "consumed"];
1607
+ var deviceEnrollmentRequests = pgTable(
1608
+ "device_enrollment_requests",
1609
+ {
1610
+ id: uuid("id").primaryKey().defaultRandom(),
1611
+ // The opaque code the agent polls with (unguessable, single-use). Unique.
1612
+ deviceCode: text("device_code").notNull(),
1613
+ // The short human-typed code (e.g. "WDJB-MJHT"). Unique among LIVE (pending)
1614
+ // rows via a partial unique index so a recycled code never collides with a
1615
+ // terminal row.
1616
+ userCode: text("user_code").notNull(),
1617
+ // The workspace this request was started for (resolved from the deployment-edge
1618
+ // request context — the agent presents the access key, the flow binds to the
1619
+ // single managed workspace OR a workspace hint). account_id rides along for RLS.
1620
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1621
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1622
+ // The agent's ed25519 public key (the machine identity the enrollment binds to).
1623
+ pubkey: text("pubkey").notNull(),
1624
+ os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"),
1625
+ arch: text("arch").notNull().default("x86_64"),
1626
+ machineName: text("machine_name"),
1627
+ // The exposure the agent REQUESTED (whole-machine in v1; loudly consented at
1628
+ // approve). Mirrors the enrollment column domain.
1629
+ requestedExposure: text("requested_exposure", { enum: enrollmentExposureValues }).notNull().default("whole-machine"),
1630
+ // The agent CAN offer a display (a real screen / Xvfb is available) — gates
1631
+ // whether screen-control consent is even meaningful. has_display on the
1632
+ // resulting enrollment is derived from this.
1633
+ canOfferDisplay: boolean("can_offer_display").notNull().default(false),
1634
+ // The agent REQUESTS screen control (computer-use). The user's allow_screen_control
1635
+ // at approve is the AUTHORITATIVE consent; this is only the agent's request.
1636
+ requestsScreenControl: boolean("requests_screen_control").notNull().default(false),
1637
+ status: text("status", { enum: deviceEnrollmentStatusValues }).notNull().default("pending"),
1638
+ // ── LOUD CONSENT capture (who/when/what), stamped at approve ──────────────
1639
+ approvedBySubjectId: text("approved_by_subject_id"),
1640
+ approvedBySubjectLabel: text("approved_by_subject_label"),
1641
+ // The user's screen-control consent decision (whole-machine is mandatory at
1642
+ // approve; screen-control is opt-in per this flag).
1643
+ allowScreenControl: boolean("allow_screen_control").notNull().default(false),
1644
+ approvedAt: timestamp("approved_at", { withTimezone: true }),
1645
+ // The enrollment + sandbox the approve produced (acceptance #2: an enrollment
1646
+ // row AND a sandbox row appear). Null until approved.
1647
+ enrollmentId: uuid("enrollment_id").references(() => enrollments.id, { onDelete: "set null" }),
1648
+ sandboxId: uuid("sandbox_id").references(() => sandboxes.id, { onDelete: "set null" }),
1649
+ // The short-TTL expiry; a pending row past this is EXPIRED on poll.
1650
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
1651
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1652
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1653
+ },
1654
+ (table) => ({
1655
+ // The device_code is the agent's poll key — globally unique + indexed.
1656
+ deviceCode: uniqueIndex("device_enrollment_requests_device_code_idx").on(table.deviceCode),
1657
+ // The user_code must be unique among LIVE (pending) rows so the approve lookup
1658
+ // is unambiguous; a terminal row's code may be recycled.
1659
+ userCodePending: uniqueIndex("device_enrollment_requests_user_code_pending_idx").on(table.userCode).where(sql`${table.status} = 'pending'`),
1660
+ workspaceCreated: index("device_enrollment_requests_workspace_created_idx").on(
1661
+ table.workspaceId,
1662
+ table.createdAt
1663
+ ),
1664
+ expires: index("device_enrollment_requests_expires_idx").on(table.expiresAt)
1665
+ })
1666
+ );
1667
+ var sandboxes = pgTable(
1668
+ "sandboxes",
1669
+ {
1670
+ id: uuid("id").primaryKey().defaultRandom(),
1671
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1672
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1673
+ kind: text("kind", { enum: sandboxKindValues }).notNull(),
1674
+ name: text("name").notNull(),
1675
+ enrollmentId: uuid("enrollment_id").references(() => enrollments.id, { onDelete: "set null" }),
1676
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1677
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1678
+ },
1679
+ (table) => ({
1680
+ workspaceCreated: index("sandboxes_workspace_created_idx").on(
1681
+ table.workspaceId,
1682
+ table.createdAt
1683
+ ),
1684
+ enrollment: index("sandboxes_enrollment_idx").on(table.enrollmentId).where(sql`${table.enrollmentId} is not null`)
1685
+ })
1686
+ );
1687
+ var machineMetricsLatest = pgTable(
1688
+ "machine_metrics_latest",
1689
+ {
1690
+ enrollmentId: uuid("enrollment_id").primaryKey().references(() => enrollments.id, { onDelete: "cascade" }),
1691
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1692
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1693
+ cpuPercent: numeric("cpu_percent").$type(),
1694
+ load1: numeric("load1").$type(),
1695
+ load5: numeric("load5").$type(),
1696
+ load15: numeric("load15").$type(),
1697
+ memUsedBytes: bigint("mem_used_bytes", { mode: "number" }),
1698
+ memTotalBytes: bigint("mem_total_bytes", { mode: "number" }),
1699
+ diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }),
1700
+ diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }),
1701
+ gpuUtilPercent: numeric("gpu_util_percent").$type(),
1702
+ gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }),
1703
+ gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }),
1704
+ contention: numeric("contention").$type(),
1705
+ sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(),
1706
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1707
+ },
1708
+ (table) => ({
1709
+ workspace: index("machine_metrics_latest_workspace_idx").on(table.workspaceId)
1710
+ })
1711
+ );
1712
+ var machineMetricsSeries = pgTable(
1713
+ "machine_metrics_series",
1714
+ {
1715
+ id: uuid("id").primaryKey().defaultRandom(),
1716
+ enrollmentId: uuid("enrollment_id").notNull().references(() => enrollments.id, { onDelete: "cascade" }),
1717
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1718
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1719
+ cpuPercent: numeric("cpu_percent").$type(),
1720
+ load1: numeric("load1").$type(),
1721
+ load5: numeric("load5").$type(),
1722
+ load15: numeric("load15").$type(),
1723
+ memUsedBytes: bigint("mem_used_bytes", { mode: "number" }),
1724
+ memTotalBytes: bigint("mem_total_bytes", { mode: "number" }),
1725
+ diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }),
1726
+ diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }),
1727
+ gpuUtilPercent: numeric("gpu_util_percent").$type(),
1728
+ gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }),
1729
+ gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }),
1730
+ contention: numeric("contention").$type(),
1731
+ sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(),
1732
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1733
+ },
1734
+ (table) => ({
1735
+ enrollmentSampled: index("machine_metrics_series_enrollment_sampled_idx").on(
1736
+ table.enrollmentId,
1737
+ table.sampledAt
1738
+ ),
1739
+ sampled: index("machine_metrics_series_sampled_idx").on(table.sampledAt)
1740
+ })
1741
+ );
1742
+ var scheduledTasks = pgTable(
1743
+ "scheduled_tasks",
1744
+ {
1745
+ id: uuid("id").primaryKey().defaultRandom(),
1746
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1747
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1748
+ name: text("name").notNull(),
1749
+ status: text("status").notNull().default("active"),
1750
+ schedule: jsonb("schedule").$type().notNull(),
1751
+ temporalScheduleId: text("temporal_schedule_id").notNull(),
1752
+ runMode: text("run_mode").notNull().default("new_session_per_run"),
1753
+ overlapPolicy: text("overlap_policy").notNull().default("allow_concurrent"),
1754
+ agentConfig: jsonb("agent_config").$type().notNull(),
1755
+ reusableSessionId: uuid("reusable_session_id").references(() => sessions.id, {
1756
+ onDelete: "set null"
1757
+ }),
1758
+ variableSetId: uuid("variable_set_id").references(() => workspaceVariableSets.id, {
1759
+ onDelete: "restrict"
1760
+ }),
1761
+ // The rig this task's runs ride; the active version is resolved per fire
1762
+ // (migration 0047). NULL ⇒ no rig. FK (-> rigs(id) ON DELETE SET NULL) lives
1763
+ // in migration 0047 (forward-reference pattern). Consumed in M3.
1764
+ rigId: uuid("rig_id"),
1765
+ metadata: jsonb("metadata").$type().notNull().default({}),
1766
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1767
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1768
+ },
1769
+ (table) => ({
1770
+ temporalScheduleId: uniqueIndex("scheduled_tasks_workspace_temporal_schedule_id_idx").on(
1771
+ table.workspaceId,
1772
+ table.temporalScheduleId
1773
+ ),
1774
+ status: index("scheduled_tasks_workspace_status_idx").on(table.workspaceId, table.status),
1775
+ variableSet: index("scheduled_tasks_variable_set_idx").on(
1776
+ table.workspaceId,
1777
+ table.variableSetId
1778
+ )
1779
+ })
1780
+ );
1781
+ var scheduledTaskRuns = pgTable(
1782
+ "scheduled_task_runs",
1783
+ {
1784
+ id: uuid("id").primaryKey().defaultRandom(),
1785
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1786
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1787
+ taskId: uuid("task_id").notNull().references(() => scheduledTasks.id, { onDelete: "cascade" }),
1788
+ status: text("status").notNull().default("queued"),
1789
+ triggerType: text("trigger_type").notNull(),
1790
+ scheduledAt: timestamp("scheduled_at", { withTimezone: true }),
1791
+ firedAt: timestamp("fired_at", { withTimezone: true }).notNull().defaultNow(),
1792
+ sessionId: uuid("session_id").references(() => sessions.id, { onDelete: "set null" }),
1793
+ triggerEventId: uuid("trigger_event_id"),
1794
+ // Stable Temporal producer identity. Activity replay/re-dispatch returns
1795
+ // the exact run instead of allocating a second schedule source row.
1796
+ producerKey: text("producer_key"),
1797
+ error: text("error"),
1798
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1799
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1800
+ },
1801
+ (table) => ({
1802
+ taskCreated: index("scheduled_task_runs_workspace_task_created_idx").on(
1803
+ table.workspaceId,
1804
+ table.taskId,
1805
+ table.createdAt
1806
+ ),
1807
+ session: index("scheduled_task_runs_workspace_session_idx").on(
1808
+ table.workspaceId,
1809
+ table.sessionId
1810
+ ),
1811
+ producer: uniqueIndex("scheduled_task_runs_producer_key_uq").on(table.workspaceId, table.producerKey).where(sql`${table.producerKey} is not null`)
1812
+ })
1813
+ );
1814
+ var githubInstallations = pgTable(
1815
+ "github_installations",
1816
+ {
1817
+ id: uuid("id").primaryKey().defaultRandom(),
1818
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1819
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1820
+ installationId: integer("installation_id").notNull(),
1821
+ accountLogin: text("account_login"),
1822
+ accountType: text("account_type"),
1823
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1824
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1825
+ },
1826
+ (table) => ({
1827
+ workspaceInstallation: uniqueIndex("github_installations_workspace_installation_idx").on(
1828
+ table.workspaceId,
1829
+ table.installationId
1830
+ ),
1831
+ installation: index("github_installations_installation_idx").on(table.installationId),
1832
+ workspace: index("github_installations_workspace_idx").on(table.workspaceId)
1833
+ })
1834
+ );
1835
+ var usageEvents = pgTable(
1836
+ "usage_events",
1837
+ {
1838
+ id: uuid("id").primaryKey().defaultRandom(),
1839
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1840
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1841
+ subjectId: text("subject_id"),
1842
+ eventType: text("event_type").notNull(),
1843
+ quantity: bigint("quantity", { mode: "number" }).notNull(),
1844
+ unit: text("unit").notNull(),
1845
+ sourceResourceType: text("source_resource_type"),
1846
+ sourceResourceId: text("source_resource_id"),
1847
+ idempotencyKey: text("idempotency_key").notNull(),
1848
+ occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),
1849
+ recordedAt: timestamp("recorded_at", { withTimezone: true }).notNull().defaultNow(),
1850
+ exportedToBillingAt: timestamp("exported_to_billing_at", { withTimezone: true }),
1851
+ billingProviderEventId: text("billing_provider_event_id")
1852
+ },
1853
+ (table) => ({
1854
+ idempotency: uniqueIndex("usage_events_idempotency_idx").on(table.idempotencyKey),
1855
+ workspaceMetric: index("usage_events_workspace_metric_idx").on(
1856
+ table.workspaceId,
1857
+ table.eventType,
1858
+ table.occurredAt
1859
+ ),
1860
+ accountMetric: index("usage_events_account_metric_idx").on(
1861
+ table.accountId,
1862
+ table.eventType,
1863
+ table.occurredAt
1864
+ )
1865
+ })
1866
+ );
1867
+ var creditLedgerEntries = pgTable(
1868
+ "credit_ledger_entries",
1869
+ {
1870
+ id: uuid("id").primaryKey().defaultRandom(),
1871
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1872
+ workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "set null" }),
1873
+ type: text("type").notNull(),
1874
+ amountMicros: bigint("amount_micros", { mode: "number" }).notNull(),
1875
+ currency: text("currency").notNull().default("usd"),
1876
+ sourceType: text("source_type"),
1877
+ sourceId: text("source_id"),
1878
+ idempotencyKey: text("idempotency_key").notNull(),
1879
+ metadata: jsonb("metadata").$type().notNull().default({}),
1880
+ occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
1881
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1882
+ },
1883
+ (table) => ({
1884
+ idempotency: uniqueIndex("credit_ledger_entries_idempotency_idx").on(table.idempotencyKey),
1885
+ accountCreated: index("credit_ledger_entries_account_created_idx").on(
1886
+ table.accountId,
1887
+ table.createdAt
1888
+ )
1889
+ })
1890
+ );
1891
+ var billingCustomers = pgTable(
1892
+ "billing_customers",
1893
+ {
1894
+ id: uuid("id").primaryKey().defaultRandom(),
1895
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1896
+ provider: text("provider").notNull().default("stripe"),
1897
+ providerCustomerId: text("provider_customer_id").notNull(),
1898
+ email: text("email"),
1899
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1900
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1901
+ },
1902
+ (table) => ({
1903
+ accountProvider: uniqueIndex("billing_customers_account_provider_idx").on(
1904
+ table.accountId,
1905
+ table.provider
1906
+ ),
1907
+ providerCustomer: uniqueIndex("billing_customers_provider_customer_idx").on(
1908
+ table.provider,
1909
+ table.providerCustomerId
1910
+ )
1911
+ })
1912
+ );
1913
+ var stripeWebhookEvents = pgTable("stripe_webhook_events", {
1914
+ id: text("id").primaryKey(),
1915
+ type: text("type").notNull(),
1916
+ livemode: text("livemode").notNull().default("false"),
1917
+ payload: jsonb("payload").$type().notNull(),
1918
+ processedAt: timestamp("processed_at", { withTimezone: true }),
1919
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1920
+ });
1921
+ var auditEvents = pgTable(
1922
+ "audit_events",
1923
+ {
1924
+ id: uuid("id").primaryKey().defaultRandom(),
1925
+ accountId: uuid("account_id").references(() => managedAccounts.id, { onDelete: "set null" }),
1926
+ workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "set null" }),
1927
+ subjectId: text("subject_id"),
1928
+ action: text("action").notNull(),
1929
+ targetType: text("target_type"),
1930
+ targetId: text("target_id"),
1931
+ metadata: jsonb("metadata").$type().notNull().default({}),
1932
+ occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow()
1933
+ },
1934
+ (table) => ({
1935
+ accountCreated: index("audit_events_account_created_idx").on(table.accountId, table.occurredAt),
1936
+ workspaceCreated: index("audit_events_workspace_created_idx").on(
1937
+ table.workspaceId,
1938
+ table.occurredAt
1939
+ )
1940
+ })
1941
+ );
1942
+ var packInstallations = pgTable(
1943
+ "pack_installations",
1944
+ {
1945
+ id: uuid("id").primaryKey().defaultRandom(),
1946
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1947
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1948
+ packId: text("pack_id").notNull(),
1949
+ status: text("status").notNull().default("active"),
1950
+ metadata: jsonb("metadata").$type().notNull().default({}),
1951
+ enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(),
1952
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1953
+ },
1954
+ (table) => ({
1955
+ workspacePack: uniqueIndex("pack_installations_workspace_pack_idx").on(
1956
+ table.workspaceId,
1957
+ table.packId
1958
+ ),
1959
+ status: index("pack_installations_workspace_status_idx").on(table.workspaceId, table.status)
1960
+ })
1961
+ );
1962
+ var workspacePacks = pgTable(
1963
+ "workspace_packs",
1964
+ {
1965
+ id: uuid("id").primaryKey().defaultRandom(),
1966
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1967
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1968
+ packId: text("pack_id").notNull(),
1969
+ manifest: jsonb("manifest").$type().notNull(),
1970
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1971
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1972
+ },
1973
+ (table) => ({
1974
+ workspacePack: uniqueIndex("workspace_packs_workspace_pack_idx").on(
1975
+ table.workspaceId,
1976
+ table.packId
1977
+ )
1978
+ })
1979
+ );
1980
+ var importBatches = pgTable(
1981
+ "import_batches",
1982
+ {
1983
+ id: uuid("id").primaryKey().defaultRandom(),
1984
+ source: text("source").notNull(),
1985
+ snapshotDate: timestamp("snapshot_date", { withTimezone: true }).notNull(),
1986
+ snapshotRef: text("snapshot_ref"),
1987
+ attributionNote: text("attribution_note").notNull(),
1988
+ importedCount: integer("imported_count").notNull().default(0),
1989
+ skippedCount: integer("skipped_count").notNull().default(0),
1990
+ quarantinedCount: integer("quarantined_count").notNull().default(0),
1991
+ logoFailureCount: integer("logo_failure_count").notNull().default(0),
1992
+ staleCount: integer("stale_count").notNull().default(0),
1993
+ details: jsonb("details").$type().notNull().default({}),
1994
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1995
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1996
+ },
1997
+ (table) => ({
1998
+ sourceSnapshot: index("import_batches_source_snapshot_idx").on(
1999
+ table.source,
2000
+ table.snapshotDate
2001
+ ),
2002
+ createdAt: index("import_batches_created_at_idx").on(table.createdAt)
2003
+ })
2004
+ );
2005
+ var capabilityCatalogItems = pgTable(
2006
+ "capability_catalog_items",
2007
+ {
2008
+ id: text("id").notNull(),
2009
+ accountId: uuid("account_id").references(() => managedAccounts.id, { onDelete: "cascade" }),
2010
+ workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade" }),
2011
+ kind: text("kind").notNull(),
2012
+ source: text("source").notNull().default("manual"),
2013
+ name: text("name").notNull(),
2014
+ description: text("description"),
2015
+ category: text("category").notNull().default("custom"),
2016
+ tags: jsonb("tags").$type().notNull().default([]),
2017
+ homepageUrl: text("homepage_url"),
2018
+ endpointUrl: text("endpoint_url"),
2019
+ installUrl: text("install_url"),
2020
+ authModel: text("auth_model"),
2021
+ providerDomain: text("provider_domain"),
2022
+ surfaceType: text("surface_type"),
2023
+ transport: text("transport"),
2024
+ mcpUrl: text("mcp_url"),
2025
+ authKind: text("auth_kind"),
2026
+ credentialFacts: jsonb("credential_facts").$type().notNull().default([]),
2027
+ tier: text("tier"),
2028
+ provenance: text("provenance"),
2029
+ logoAssetPath: text("logo_asset_path"),
2030
+ importBatchId: uuid("import_batch_id").references(() => importBatches.id, {
2031
+ onDelete: "set null"
2032
+ }),
2033
+ stale: boolean("stale").notNull().default(false),
2034
+ staleAt: timestamp("stale_at", { withTimezone: true }),
2035
+ metadata: jsonb("metadata").$type().notNull().default({}),
2036
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2037
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2038
+ },
2039
+ (table) => ({
2040
+ workspaceCapability: uniqueIndex("capability_catalog_items_workspace_capability_idx").on(
2041
+ table.workspaceId,
2042
+ table.id
2043
+ ),
2044
+ registrySurface: uniqueIndex("capability_catalog_items_registry_surface_idx").on(
2045
+ table.source,
2046
+ table.providerDomain,
2047
+ table.mcpUrl
2048
+ ),
2049
+ globalCapability: uniqueIndex("capability_catalog_items_global_capability_idx").on(table.id).where(sql`${table.workspaceId} is null`),
2050
+ kind: index("capability_catalog_items_workspace_kind_idx").on(table.workspaceId, table.kind),
2051
+ category: index("capability_catalog_items_workspace_category_idx").on(
2052
+ table.workspaceId,
2053
+ table.category
2054
+ ),
2055
+ source: index("capability_catalog_items_workspace_source_idx").on(
2056
+ table.workspaceId,
2057
+ table.source
2058
+ ),
2059
+ providerDomain: index("capability_catalog_items_provider_domain_idx").on(table.providerDomain),
2060
+ importBatch: index("capability_catalog_items_import_batch_idx").on(table.importBatchId),
2061
+ stale: index("capability_catalog_items_source_stale_idx").on(table.source, table.stale)
2062
+ })
2063
+ );
2064
+ var capabilityInstallations = pgTable(
2065
+ "capability_installations",
2066
+ {
2067
+ id: uuid("id").primaryKey().defaultRandom(),
2068
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2069
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2070
+ capabilityId: text("capability_id").notNull(),
2071
+ kind: text("kind").notNull(),
2072
+ status: text("status").notNull().default("active"),
2073
+ config: jsonb("config").$type().notNull().default({}),
2074
+ metadata: jsonb("metadata").$type().notNull().default({}),
2075
+ enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(),
2076
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2077
+ },
2078
+ (table) => ({
2079
+ workspaceCapability: uniqueIndex("capability_installations_workspace_capability_idx").on(
2080
+ table.workspaceId,
2081
+ table.capabilityId
2082
+ ),
2083
+ kind: index("capability_installations_workspace_kind_idx").on(table.workspaceId, table.kind),
2084
+ status: index("capability_installations_workspace_status_idx").on(
2085
+ table.workspaceId,
2086
+ table.status
2087
+ )
2088
+ })
2089
+ );
2090
+ var socialConnections = pgTable(
2091
+ "social_connections",
2092
+ {
2093
+ id: uuid("id").primaryKey().defaultRandom(),
2094
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2095
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2096
+ provider: text("provider").notNull(),
2097
+ accountHandle: text("account_handle").notNull(),
2098
+ accountName: text("account_name"),
2099
+ externalAccountId: text("external_account_id"),
2100
+ status: text("status").notNull().default("connected"),
2101
+ scopes: jsonb("scopes").$type().notNull().default([]),
2102
+ credentialRef: text("credential_ref"),
2103
+ tokenMetadata: jsonb("token_metadata").$type().notNull().default({}),
2104
+ metadata: jsonb("metadata").$type().notNull().default({}),
2105
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2106
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2107
+ },
2108
+ (table) => ({
2109
+ workspaceProviderHandle: uniqueIndex("social_connections_workspace_provider_handle_idx").on(
2110
+ table.workspaceId,
2111
+ table.provider,
2112
+ table.accountHandle
2113
+ ),
2114
+ providerStatus: index("social_connections_workspace_provider_status_idx").on(
2115
+ table.workspaceId,
2116
+ table.provider,
2117
+ table.status
2118
+ )
2119
+ })
2120
+ );
2121
+ var socialPosts = pgTable(
2122
+ "social_posts",
2123
+ {
2124
+ id: uuid("id").primaryKey().defaultRandom(),
2125
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2126
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2127
+ connectionId: uuid("connection_id").notNull().references(() => socialConnections.id, { onDelete: "cascade" }),
2128
+ provider: text("provider").notNull(),
2129
+ externalPostId: text("external_post_id"),
2130
+ url: text("url"),
2131
+ authorHandle: text("author_handle"),
2132
+ text: text("text").notNull(),
2133
+ publishedAt: timestamp("published_at", { withTimezone: true }).notNull(),
2134
+ metrics: jsonb("metrics").$type().notNull().default({}),
2135
+ raw: jsonb("raw").$type().notNull().default({}),
2136
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
2137
+ },
2138
+ (table) => ({
2139
+ connectionExternalPost: uniqueIndex("social_posts_workspace_connection_external_post_idx").on(
2140
+ table.workspaceId,
2141
+ table.connectionId,
2142
+ table.externalPostId
2143
+ ),
2144
+ connectionPublished: index("social_posts_workspace_connection_published_idx").on(
2145
+ table.workspaceId,
2146
+ table.connectionId,
2147
+ table.publishedAt
2148
+ ),
2149
+ providerPublished: index("social_posts_workspace_provider_published_idx").on(
2150
+ table.workspaceId,
2151
+ table.provider,
2152
+ table.publishedAt
2153
+ )
2154
+ })
2155
+ );
2156
+ var rigs = pgTable(
2157
+ "rigs",
2158
+ {
2159
+ id: uuid("id").primaryKey().defaultRandom(),
2160
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2161
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2162
+ name: text("name").notNull(),
2163
+ description: text("description"),
2164
+ // Attribution string: 'user:<subject>' | 'session:<id>' | 'system'.
2165
+ createdBy: text("created_by"),
2166
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2167
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2168
+ },
2169
+ (table) => ({
2170
+ workspaceName: uniqueIndex("rigs_workspace_name_idx").on(table.workspaceId, table.name),
2171
+ workspaceCreated: index("rigs_workspace_created_idx").on(table.workspaceId, table.createdAt)
2172
+ })
2173
+ );
2174
+ var rigVersions = pgTable(
2175
+ "rig_versions",
2176
+ {
2177
+ id: uuid("id").primaryKey().defaultRandom(),
2178
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2179
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2180
+ rigId: uuid("rig_id").notNull().references(() => rigs.id, { onDelete: "cascade" }),
2181
+ version: integer("version").notNull(),
2182
+ image: text("image"),
2183
+ setupScript: text("setup_script"),
2184
+ // Self-declared health checks: [{ name, command }].
2185
+ checks: jsonb("checks").$type().notNull().default([]),
2186
+ // Registered credential-hook names (resolved to hook implementations in M3).
2187
+ credentialHooks: jsonb("credential_hooks").$type().notNull().default([]),
2188
+ // Variable-set ids layered below the session's variable set at run time (M3).
2189
+ defaultVariableSetIds: jsonb("default_variable_set_ids").$type().notNull().default([]),
2190
+ changelog: text("changelog"),
2191
+ createdBy: text("created_by"),
2192
+ active: boolean("active").notNull().default(false),
2193
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
2194
+ },
2195
+ (table) => ({
2196
+ rigVersion: uniqueIndex("rig_versions_rig_version_idx").on(table.rigId, table.version),
2197
+ // At most one active version per rig — the single-active invariant, in the DB.
2198
+ rigActive: uniqueIndex("rig_versions_rig_active_idx").on(table.rigId).where(sql`${table.active}`),
2199
+ workspaceRig: index("rig_versions_workspace_rig_idx").on(
2200
+ table.workspaceId,
2201
+ table.rigId,
2202
+ table.version
2203
+ )
2204
+ })
2205
+ );
2206
+ var rigChanges = pgTable(
2207
+ "rig_changes",
2208
+ {
2209
+ id: uuid("id").primaryKey().defaultRandom(),
2210
+ accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2211
+ workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2212
+ rigId: uuid("rig_id").notNull().references(() => rigs.id, { onDelete: "cascade" }),
2213
+ baseVersionId: uuid("base_version_id").references(() => rigVersions.id, {
2214
+ onDelete: "set null"
2215
+ }),
2216
+ // 'setup_append' | 'definition_edit' (CHECK in migration 0047).
2217
+ kind: text("kind").notNull(),
2218
+ payload: jsonb("payload").$type().notNull(),
2219
+ // 'proposed' | 'verifying' | 'merged' | 'rejected' | 'failed' (CHECK in 0047).
2220
+ status: text("status").notNull().default("proposed"),
2221
+ proposedBy: text("proposed_by"),
2222
+ verification: jsonb("verification").$type(),
2223
+ resultVersionId: uuid("result_version_id").references(() => rigVersions.id, {
2224
+ onDelete: "set null"
2225
+ }),
2226
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2227
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2228
+ },
2229
+ (table) => ({
2230
+ workspaceRig: index("rig_changes_workspace_rig_idx").on(
2231
+ table.workspaceId,
2232
+ table.rigId,
2233
+ table.createdAt
2234
+ ),
2235
+ workspaceStatus: index("rig_changes_workspace_status_idx").on(table.workspaceId, table.status)
2236
+ })
2237
+ );
2238
+
2239
+ export {
2240
+ managedAccounts,
2241
+ workspaces,
2242
+ workspaceMemberships,
2243
+ apiKeys,
2244
+ workspaceVariableSets,
2245
+ workspaceVariableSetVariables,
2246
+ codexSubscriptionCredentials,
2247
+ connections,
2248
+ integrationOauthClients,
2249
+ integrationOauthStateNonces,
2250
+ codexRotationSettings,
2251
+ workspaceModelPolicies,
2252
+ codexCredentialLeases,
2253
+ sessions,
2254
+ sessionPins,
2255
+ sessionListSnapshots,
2256
+ sessionMcpServers,
2257
+ files,
2258
+ fileUploads,
2259
+ documentBases,
2260
+ documents,
2261
+ documentChunks,
2262
+ knowledgeMemories,
2263
+ sessionTurns,
2264
+ sessionSystemUpdates,
2265
+ runtimeControlOperations,
2266
+ sessionSystemUpdateOutbox,
2267
+ sessionWorkflowWakeOutbox,
2268
+ sessionGoals,
2269
+ codexCapacityWaiters,
2270
+ sessionEvents,
2271
+ agentRunStates,
2272
+ sessionHistoryItems,
2273
+ sessionPendingToolCalls,
2274
+ sandboxSessionEnvelopes,
2275
+ sandboxLeaseLivenessValues,
2276
+ sandboxLeases,
2277
+ sandboxLeaseHolders,
2278
+ sessionRecordingStateValues,
2279
+ sessionRecordingModeValues,
2280
+ sessionRecordingCodecValues,
2281
+ sessionRecordings,
2282
+ workspaceCaptures,
2283
+ sandboxPtySessions,
2284
+ enrollmentExposureValues,
2285
+ enrollmentStatusValues,
2286
+ enrollmentOsValues,
2287
+ sandboxKindValues,
2288
+ enrollments,
2289
+ deviceEnrollmentStatusValues,
2290
+ deviceEnrollmentRequests,
2291
+ sandboxes,
2292
+ machineMetricsLatest,
2293
+ machineMetricsSeries,
2294
+ scheduledTasks,
2295
+ scheduledTaskRuns,
2296
+ githubInstallations,
2297
+ usageEvents,
2298
+ creditLedgerEntries,
2299
+ billingCustomers,
2300
+ stripeWebhookEvents,
2301
+ auditEvents,
2302
+ packInstallations,
2303
+ workspacePacks,
2304
+ importBatches,
2305
+ capabilityCatalogItems,
2306
+ capabilityInstallations,
2307
+ socialConnections,
2308
+ socialPosts,
2309
+ rigs,
2310
+ rigVersions,
2311
+ rigChanges,
2312
+ schema_exports
2313
+ };
2314
+ //# sourceMappingURL=chunk-O3D7DABC.js.map