@opengeni/db 0.12.6 → 0.13.1

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.
@@ -1,3822 +0,0 @@
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
- codexResetRedemptionAttempts: () => codexResetRedemptionAttempts,
17
- codexRotationSettings: () => codexRotationSettings,
18
- codexSubscriptionCredentials: () => codexSubscriptionCredentials,
19
- composerDrafts: () => composerDrafts,
20
- connections: () => connections,
21
- creditLedgerEntries: () => creditLedgerEntries,
22
- deviceEnrollmentRequests: () => deviceEnrollmentRequests,
23
- deviceEnrollmentStatusValues: () => deviceEnrollmentStatusValues,
24
- documentBases: () => documentBases,
25
- documentChunks: () => documentChunks,
26
- documents: () => documents,
27
- enrollmentExposureValues: () => enrollmentExposureValues,
28
- enrollmentOsValues: () => enrollmentOsValues,
29
- enrollmentStatusValues: () => enrollmentStatusValues,
30
- enrollments: () => enrollments,
31
- fileUploads: () => fileUploads,
32
- files: () => files,
33
- githubInstallationRepositories: () => githubInstallationRepositories,
34
- githubInstallations: () => githubInstallations,
35
- hostExportConfig: () => hostExportConfig,
36
- hostExportConsumers: () => hostExportConsumers,
37
- hostExportCursorState: () => hostExportCursorState,
38
- hostExportDeadLetters: () => hostExportDeadLetters,
39
- hostExportOutbox: () => hostExportOutbox,
40
- importBatches: () => importBatches,
41
- integrationOauthClients: () => integrationOauthClients,
42
- integrationOauthStateNonces: () => integrationOauthStateNonces,
43
- knowledgeMemories: () => knowledgeMemories,
44
- machineMetricsLatest: () => machineMetricsLatest,
45
- machineMetricsSeries: () => machineMetricsSeries,
46
- managedAccounts: () => managedAccounts,
47
- nestedAgentDepthConfiguration: () => nestedAgentDepthConfiguration,
48
- newSessionDrafts: () => newSessionDrafts,
49
- packInstallations: () => packInstallations,
50
- rigChanges: () => rigChanges,
51
- rigVersions: () => rigVersions,
52
- rigs: () => rigs,
53
- sandboxKindValues: () => sandboxKindValues,
54
- sandboxLeaseHolders: () => sandboxLeaseHolders,
55
- sandboxLeaseLivenessValues: () => sandboxLeaseLivenessValues,
56
- sandboxLeases: () => sandboxLeases,
57
- sandboxPtySessions: () => sandboxPtySessions,
58
- sandboxRetainedProcessStateValues: () => sandboxRetainedProcessStateValues,
59
- sandboxRetainedProcesses: () => sandboxRetainedProcesses,
60
- sandboxSessionEnvelopes: () => sandboxSessionEnvelopes,
61
- sandboxWorkspaceMutationActorKindValues: () => sandboxWorkspaceMutationActorKindValues,
62
- sandboxWorkspaceMutationAdmissions: () => sandboxWorkspaceMutationAdmissions,
63
- sandboxWorkspaceMutationHolderKindValues: () => sandboxWorkspaceMutationHolderKindValues,
64
- sandboxes: () => sandboxes,
65
- scheduledTaskRuns: () => scheduledTaskRuns,
66
- scheduledTasks: () => scheduledTasks,
67
- sessionAttemptInterruptions: () => sessionAttemptInterruptions,
68
- sessionCommandReceipts: () => sessionCommandReceipts,
69
- sessionEvents: () => sessionEvents,
70
- sessionGoals: () => sessionGoals,
71
- sessionHistoryItems: () => sessionHistoryItems,
72
- sessionHumanInputRequests: () => sessionHumanInputRequests,
73
- sessionListSnapshots: () => sessionListSnapshots,
74
- sessionMcpServers: () => sessionMcpServers,
75
- sessionPendingToolCalls: () => sessionPendingToolCalls,
76
- sessionPins: () => sessionPins,
77
- sessionRecordingCodecValues: () => sessionRecordingCodecValues,
78
- sessionRecordingModeValues: () => sessionRecordingModeValues,
79
- sessionRecordingStateValues: () => sessionRecordingStateValues,
80
- sessionRecordings: () => sessionRecordings,
81
- sessionSpawnDenials: () => sessionSpawnDenials,
82
- sessionSystemUpdateOutbox: () => sessionSystemUpdateOutbox,
83
- sessionSystemUpdates: () => sessionSystemUpdates,
84
- sessionTurnAttempts: () => sessionTurnAttempts,
85
- sessionTurns: () => sessionTurns,
86
- sessionWorkflowWakeOutbox: () => sessionWorkflowWakeOutbox,
87
- sessions: () => sessions,
88
- socialConnections: () => socialConnections,
89
- socialPosts: () => socialPosts,
90
- stripeWebhookEvents: () => stripeWebhookEvents,
91
- usageEvents: () => usageEvents,
92
- workspaceCaptures: () => workspaceCaptures,
93
- workspaceControlEvents: () => workspaceControlEvents,
94
- workspaceInferenceControls: () => workspaceInferenceControls,
95
- workspaceMemberships: () => workspaceMemberships,
96
- workspaceModelPolicies: () => workspaceModelPolicies,
97
- workspacePacks: () => workspacePacks,
98
- workspaceSessionActivityRevisions: () => workspaceSessionActivityRevisions,
99
- workspaceVariableSetVariables: () => workspaceVariableSetVariables,
100
- workspaceVariableSets: () => workspaceVariableSets,
101
- workspaces: () => workspaces
102
- });
103
- import { sql } from "drizzle-orm";
104
- import {
105
- bigint,
106
- boolean,
107
- check,
108
- foreignKey,
109
- index,
110
- integer,
111
- jsonb,
112
- numeric,
113
- pgTable,
114
- text,
115
- timestamp,
116
- uniqueIndex,
117
- uuid,
118
- customType
119
- } from "drizzle-orm/pg-core";
120
- var vector = customType({
121
- dataType() {
122
- return "vector(3072)";
123
- },
124
- toDriver(value) {
125
- return `[${value.join(",")}]`;
126
- }
127
- });
128
- var managedAccounts = pgTable(
129
- "managed_accounts",
130
- {
131
- id: uuid("id").primaryKey().defaultRandom(),
132
- name: text("name").notNull(),
133
- externalSource: text("external_source"),
134
- externalId: text("external_id"),
135
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
136
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
137
- },
138
- (table) => ({
139
- external: uniqueIndex("managed_accounts_external_idx").on(
140
- table.externalSource,
141
- table.externalId
142
- )
143
- })
144
- );
145
- var workspaces = pgTable(
146
- "workspaces",
147
- {
148
- id: uuid("id").primaryKey().defaultRandom(),
149
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
150
- name: text("name").notNull(),
151
- slug: text("slug"),
152
- externalSource: text("external_source"),
153
- externalId: text("external_id"),
154
- // White-label agent persona template override. NULL means the deployment
155
- // default (OPENGENI_AGENT_INSTRUCTIONS_TEMPLATE / DEFAULT_AGENT_INSTRUCTIONS).
156
- agentInstructions: text("agent_instructions"),
157
- // Growth-ready per-workspace settings bag (migration 0045). Holds memoryEnabled
158
- // and future workspace-level toggles; validated/merged via WorkspaceSettingsSchema.
159
- settings: jsonb("settings").$type().notNull().default({}),
160
- // The workspace's default rig (migration 0047). NULL ⇒ no default; sessions
161
- // created without an explicit rig ride no rig (today's behavior exactly). FK
162
- // (-> rigs(id) ON DELETE SET NULL) lives in migration 0047, not a Drizzle
163
- // .references(), because `rigs` is declared later in this file (same
164
- // forward-reference pattern as sessions.activeSandboxId). Consumed in M3.
165
- defaultRigId: uuid("default_rig_id"),
166
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
167
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
168
- },
169
- (table) => ({
170
- account: index("workspaces_account_idx").on(table.accountId),
171
- accountSlug: uniqueIndex("workspaces_account_slug_idx").on(table.accountId, table.slug).where(sql`${table.slug} is not null`),
172
- external: uniqueIndex("workspaces_external_idx").on(table.externalSource, table.externalId)
173
- })
174
- );
175
- var nestedAgentDepthConfiguration = pgTable(
176
- "nested_agent_depth_configuration",
177
- {
178
- singleton: boolean("singleton").primaryKey().notNull().default(true),
179
- maxNestedAgentDepth: integer("max_nested_agent_depth").notNull(),
180
- policySource: text("policy_source").$type().notNull(),
181
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
182
- },
183
- (table) => ({
184
- singletonOnly: check(
185
- "nested_agent_depth_configuration_singleton_check",
186
- sql`${table.singleton}`
187
- ),
188
- maxValid: check(
189
- "nested_agent_depth_configuration_max_check",
190
- sql`${table.maxNestedAgentDepth} >= 0`
191
- ),
192
- sourceValid: check(
193
- "nested_agent_depth_configuration_source_check",
194
- sql`${table.policySource} in ('deployment', 'default')`
195
- )
196
- })
197
- );
198
- var workspaceInferenceControls = pgTable(
199
- "workspace_inference_controls",
200
- {
201
- workspaceId: uuid("workspace_id").primaryKey(),
202
- accountId: uuid("account_id").notNull(),
203
- revision: bigint("revision", { mode: "number" }).notNull().default(0),
204
- workspaceState: text("workspace_state").notNull().default("active"),
205
- workspacePauseRevision: bigint("workspace_pause_revision", {
206
- mode: "number"
207
- }),
208
- reason: text("reason"),
209
- changedBy: text("changed_by"),
210
- changedAt: timestamp("changed_at", { withTimezone: true }),
211
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
212
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
213
- },
214
- (table) => ({
215
- workspaceAccount: foreignKey({
216
- name: "workspace_inference_controls_workspace_account_fk",
217
- columns: [table.workspaceId, table.accountId],
218
- foreignColumns: [workspaces.id, workspaces.accountId]
219
- }).onDelete("cascade"),
220
- workspaceAccountIdentity: uniqueIndex("workspace_inference_controls_workspace_account_uq").on(
221
- table.workspaceId,
222
- table.accountId
223
- ),
224
- stateValid: check(
225
- "workspace_inference_controls_state_check",
226
- sql`${table.workspaceState} in ('active', 'paused')`
227
- ),
228
- pauseRevisionConsistent: check(
229
- "workspace_inference_controls_pause_revision_check",
230
- sql`(${table.workspaceState} = 'active' and ${table.workspacePauseRevision} is null)
231
- or (${table.workspaceState} = 'paused' and ${table.workspacePauseRevision} is not null)`
232
- ),
233
- revisionValid: check(
234
- "workspace_inference_controls_revision_check",
235
- sql`${table.revision} >= 0 and (${table.workspacePauseRevision} is null or ${table.workspacePauseRevision} <= ${table.revision})`
236
- )
237
- })
238
- );
239
- var workspaceSessionActivityRevisions = pgTable(
240
- "workspace_session_activity_revisions",
241
- {
242
- workspaceId: uuid("workspace_id").primaryKey(),
243
- accountId: uuid("account_id").notNull(),
244
- revision: bigint("revision", { mode: "number" }).notNull().default(0)
245
- },
246
- (table) => ({
247
- workspaceAccount: foreignKey({
248
- name: "workspace_session_activity_revisions_workspace_account_fk",
249
- columns: [table.workspaceId, table.accountId],
250
- foreignColumns: [workspaces.id, workspaces.accountId]
251
- }).onDelete("cascade"),
252
- revisionValid: check(
253
- "workspace_session_activity_revisions_revision_check",
254
- sql`${table.revision} >= 0`
255
- )
256
- })
257
- );
258
- var workspaceMemberships = pgTable(
259
- "workspace_memberships",
260
- {
261
- id: uuid("id").primaryKey().defaultRandom(),
262
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
263
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
264
- subjectId: text("subject_id").notNull(),
265
- subjectLabel: text("subject_label"),
266
- role: text("role").notNull().default("member"),
267
- permissions: jsonb("permissions").$type().notNull().default([]),
268
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
269
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
270
- },
271
- (table) => ({
272
- subjectWorkspace: uniqueIndex("workspace_memberships_subject_workspace_idx").on(
273
- table.subjectId,
274
- table.workspaceId
275
- ),
276
- subject: index("workspace_memberships_subject_idx").on(table.subjectId),
277
- account: index("workspace_memberships_account_idx").on(table.accountId)
278
- })
279
- );
280
- var apiKeys = pgTable(
281
- "api_keys",
282
- {
283
- id: uuid("id").primaryKey().defaultRandom(),
284
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
285
- workspaceId: uuid("workspace_id").references(() => workspaces.id, {
286
- onDelete: "cascade"
287
- }),
288
- name: text("name").notNull(),
289
- prefix: text("prefix").notNull(),
290
- keyHash: text("key_hash").notNull(),
291
- permissions: jsonb("permissions").$type().notNull().default([]),
292
- expiresAt: timestamp("expires_at", { withTimezone: true }),
293
- revokedAt: timestamp("revoked_at", { withTimezone: true }),
294
- lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
295
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
296
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
297
- },
298
- (table) => ({
299
- prefix: index("api_keys_prefix_idx").on(table.prefix),
300
- hash: uniqueIndex("api_keys_key_hash_idx").on(table.keyHash),
301
- account: index("api_keys_account_idx").on(table.accountId),
302
- workspace: index("api_keys_workspace_idx").on(table.workspaceId)
303
- })
304
- );
305
- var workspaceVariableSets = pgTable(
306
- "workspace_variable_sets",
307
- {
308
- id: uuid("id").primaryKey().defaultRandom(),
309
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
310
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
311
- name: text("name").notNull(),
312
- description: text("description"),
313
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
314
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
315
- },
316
- (table) => ({
317
- workspaceName: uniqueIndex("workspace_variable_sets_workspace_name_idx").on(
318
- table.workspaceId,
319
- table.name
320
- ),
321
- workspaceCreated: index("workspace_variable_sets_workspace_created_idx").on(
322
- table.workspaceId,
323
- table.createdAt
324
- )
325
- })
326
- );
327
- var workspaceVariableSetVariables = pgTable(
328
- "workspace_variable_set_variables",
329
- {
330
- id: uuid("id").primaryKey().defaultRandom(),
331
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
332
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
333
- variableSetId: uuid("variable_set_id").notNull().references(() => workspaceVariableSets.id, { onDelete: "cascade" }),
334
- name: text("name").notNull(),
335
- // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. Never returned by any API.
336
- valueEncrypted: text("value_encrypted").notNull(),
337
- version: integer("version").notNull().default(1),
338
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
339
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
340
- },
341
- (table) => ({
342
- variableSetName: uniqueIndex("workspace_variable_set_variables_env_name_idx").on(
343
- table.workspaceId,
344
- table.variableSetId,
345
- table.name
346
- ),
347
- variableSet: index("workspace_variable_set_variables_workspace_env_idx").on(
348
- table.workspaceId,
349
- table.variableSetId
350
- )
351
- })
352
- );
353
- var codexSubscriptionCredentials = pgTable(
354
- "codex_subscription_credentials",
355
- {
356
- id: uuid("id").primaryKey().defaultRandom(),
357
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
358
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
359
- // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. JSON {access_token, refresh_token, id_token}. Never returned by any API.
360
- credentialEncrypted: text("credential_encrypted").notNull(),
361
- chatgptAccountId: text("chatgpt_account_id"),
362
- // plaintext ChatGPT-Account-ID header value (non-secret)
363
- scopes: text("scopes"),
364
- // space-delimited, as granted
365
- planType: text("plan_type"),
366
- isFedramp: boolean("is_fedramp").notNull().default(false),
367
- expiresAt: timestamp("expires_at", { withTimezone: true }),
368
- // derived from access-token JWT exp
369
- lastRefreshAt: timestamp("last_refresh_at", { withTimezone: true }),
370
- status: text("status").notNull().default("active"),
371
- // active | needs_relogin | error
372
- lastError: text("last_error"),
373
- version: integer("version").notNull().default(1),
374
- label: text("label"),
375
- // user-chosen nickname; null ⇒ derive from email/plan/account
376
- accountEmail: text("account_email"),
377
- // email from the id_token (user's own email; non-secret)
378
- // P2 usage cache (plaintext metadata; NEVER a token). Snapshotted from
379
- // GET /wham/usage; drives the quota bars + the cache TTL. primary = 5h window
380
- // (limit_window_seconds 18000), secondary = weekly (604800).
381
- primaryUsedPercent: integer("primary_used_percent"),
382
- primaryResetAt: timestamp("primary_reset_at", { withTimezone: true }),
383
- secondaryUsedPercent: integer("secondary_used_percent"),
384
- secondaryResetAt: timestamp("secondary_reset_at", { withTimezone: true }),
385
- usageCheckedAt: timestamp("usage_checked_at", { withTimezone: true }),
386
- // snapshot freshness → cache TTL clock
387
- // P3 rotation cooldown (plaintext metadata; NEVER a token). Set when this account hit its
388
- // usage cap on a rotation turn; the rotation engine treats `exhausted_until > now()` as
389
- // capped/skip so it isn't immediately re-picked. Self-clears via the now() comparison.
390
- exhaustedUntil: timestamp("exhausted_until", { withTimezone: true }),
391
- // P4 connector-aware rotation cache (plaintext metadata; NEVER a token). The set
392
- // of ORIGINAL-dotted connector namespaces (github/gmail/linear/…) this account
393
- // exposes via codex_apps, captured from the per-turn tools/list. null ⇒ never
394
- // probed (the ranker treats it as unknown: never credited as covering, never
395
- // excluded). The writer only ever sets a NON-empty set, so a flaky empty turn
396
- // can't false-drop coverage. connectorsCheckedAt is the freshness clock.
397
- connectorNamespaces: text("connector_namespaces").array(),
398
- connectorsCheckedAt: timestamp("connectors_checked_at", {
399
- withTimezone: true
400
- }),
401
- // Workspace-local, server-held fairness cursor. Provider usage headers are
402
- // capacity hints, never the sole allocator: live lease count is ranked first
403
- // and this cursor deterministically breaks equal-load/equal-capacity ties.
404
- // This flag controls NEW automatic allocations only. Credential health,
405
- // refresh, encrypted material, and already-frozen/in-flight turns are
406
- // intentionally independent. account eligibility policy owns toggle OCC/audit and product UI.
407
- allocatorEnabled: boolean("allocator_enabled").notNull().default(true),
408
- // Independent OCC/audit sequence for the allocator toggle. Token refresh
409
- // continues to own `version`; quota/cache writes own neither counter.
410
- allocatorVersion: integer("allocator_version").notNull().default(1),
411
- allocatorUpdatedBySubjectId: text("allocator_updated_by_subject_id"),
412
- allocatorUpdatedAt: timestamp("allocator_updated_at", { withTimezone: true }),
413
- // Authoritative count-only summary cached from /wham/usage. Detailed rows
414
- // are never persisted as redemption authority; every first POST preflights
415
- // the provider's fresh detail endpoint.
416
- resetCreditAvailableCount: integer("reset_credit_available_count"),
417
- resetCreditsCheckedAt: timestamp("reset_credits_checked_at", { withTimezone: true }),
418
- // Set only by a direct Better Auth cookie connection/reconnection. Legacy,
419
- // configured, delegated, API-key, and agent-created rows remain view-only.
420
- connectedBySubjectId: text("connected_by_subject_id"),
421
- selectionCount: integer("selection_count").notNull().default(0),
422
- lastSelectedAt: timestamp("last_selected_at", { withTimezone: true }),
423
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
424
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
425
- },
426
- (table) => ({
427
- // REPLACES codex_subscription_credentials_workspace_idx (the one-per-workspace cap).
428
- // One row per (workspace, ChatGPT account). Partial WHERE chatgpt_account_id IS NOT NULL
429
- // so degenerate null-account rows can't collide; the device-grant connect path always
430
- // populates chatgpt_account_id.
431
- wsAccount: uniqueIndex("codex_subscription_credentials_ws_account_idx").on(table.workspaceId, table.chatgptAccountId).where(sql`${table.chatgptAccountId} is not null`),
432
- workspace: index("codex_subscription_credentials_workspace_lookup_idx").on(table.workspaceId),
433
- // Composite identity is the defense-in-depth FK target for workspace-local
434
- // lease references in migration 0053.
435
- workspaceIdentity: uniqueIndex("codex_subscription_credentials_workspace_id_idx").on(
436
- table.workspaceId,
437
- table.id
438
- )
439
- })
440
- );
441
- var codexResetRedemptionAttempts = pgTable(
442
- "codex_reset_redemption_attempts",
443
- {
444
- id: uuid("id").primaryKey(),
445
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
446
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
447
- credentialId: uuid("credential_id").notNull(),
448
- subjectId: text("subject_id").notNull(),
449
- browserSessionHash: text("browser_session_hash").notNull(),
450
- creditId: text("credit_id").notNull(),
451
- upstreamIdempotencyKey: uuid("upstream_idempotency_key").notNull().defaultRandom(),
452
- status: text("status").notNull().default("processing"),
453
- outcome: text("outcome"),
454
- claimHolderId: uuid("claim_holder_id"),
455
- claimExpiresAt: timestamp("claim_expires_at", { withTimezone: true }),
456
- confirmationExpiresAt: timestamp("confirmation_expires_at", { withTimezone: true }).notNull(),
457
- providerStartedAt: timestamp("provider_started_at", { withTimezone: true }),
458
- completedAt: timestamp("completed_at", { withTimezone: true }),
459
- lastFailureKind: text("last_failure_kind"),
460
- retryCount: integer("retry_count").notNull().default(0),
461
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
462
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
463
- },
464
- (table) => ({
465
- workspaceAccount: foreignKey({
466
- name: "codex_reset_redemption_workspace_account_fk",
467
- columns: [table.workspaceId, table.accountId],
468
- foreignColumns: [workspaces.id, workspaces.accountId]
469
- }).onDelete("cascade"),
470
- upstreamKey: uniqueIndex("codex_reset_redemption_upstream_key_idx").on(
471
- table.upstreamIdempotencyKey
472
- ),
473
- credentialCredit: uniqueIndex("codex_reset_redemption_credential_credit_idx").on(table.workspaceId, table.credentialId, table.creditId).where(
474
- sql`${table.status} <> 'completed' or ${table.outcome} in ('reset', 'alreadyRedeemed')`
475
- ),
476
- workspaceCredential: index("codex_reset_redemption_workspace_credential_idx").on(
477
- table.workspaceId,
478
- table.credentialId,
479
- table.createdAt
480
- ),
481
- claimExpiry: index("codex_reset_redemption_claim_expiry_idx").on(table.claimExpiresAt).where(sql`${table.status} <> 'completed'`),
482
- statusValid: check(
483
- "codex_reset_redemption_status_check",
484
- sql`${table.status} in ('processing', 'provider_started', 'completed')`
485
- ),
486
- outcomeValid: check(
487
- "codex_reset_redemption_outcome_check",
488
- sql`${table.outcome} is null or ${table.outcome} in ('reset', 'nothingToReset', 'noCredit', 'alreadyRedeemed')`
489
- ),
490
- completionConsistent: check(
491
- "codex_reset_redemption_completed_check",
492
- sql`(${table.status} = 'completed') = (${table.outcome} is not null and ${table.completedAt} is not null)`
493
- ),
494
- retryCountValid: check(
495
- "codex_reset_redemption_retry_count_check",
496
- sql`${table.retryCount} >= 0`
497
- ),
498
- humanSubjectValid: check(
499
- "codex_reset_redemption_human_subject_check",
500
- sql`${table.subjectId} like 'user:_%'`
501
- )
502
- })
503
- );
504
- var connections = pgTable(
505
- "connections",
506
- {
507
- id: uuid("id").primaryKey().defaultRandom(),
508
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
509
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
510
- subjectId: text("subject_id"),
511
- providerDomain: text("provider_domain").notNull(),
512
- kind: text("kind").notNull(),
513
- status: text("status").notNull().default("active"),
514
- credentialEncrypted: text("credential_encrypted").notNull(),
515
- grantedScopes: jsonb("granted_scopes").$type().notNull().default([]),
516
- expiresAt: timestamp("expires_at", { withTimezone: true }),
517
- lastRefreshAt: timestamp("last_refresh_at", { withTimezone: true }),
518
- lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
519
- lastError: text("last_error"),
520
- version: integer("version").notNull().default(1),
521
- metadata: jsonb("metadata").$type().notNull().default({}),
522
- createdBySubjectId: text("created_by_subject_id"),
523
- updatedBySubjectId: text("updated_by_subject_id"),
524
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
525
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
526
- },
527
- (table) => ({
528
- workspaceProviderStatus: index("connections_workspace_provider_status_idx").on(
529
- table.workspaceId,
530
- table.providerDomain,
531
- table.status
532
- ),
533
- workspaceSubjectProvider: index("connections_workspace_subject_provider_idx").on(
534
- table.workspaceId,
535
- table.subjectId,
536
- table.providerDomain
537
- ),
538
- workspaceKind: index("connections_workspace_kind_idx").on(table.workspaceId, table.kind),
539
- workspaceExpires: index("connections_workspace_expires_idx").on(
540
- table.workspaceId,
541
- table.expiresAt
542
- )
543
- })
544
- );
545
- var integrationOauthClients = pgTable(
546
- "integration_oauth_clients",
547
- {
548
- id: uuid("id").primaryKey().defaultRandom(),
549
- issuer: text("issuer").notNull(),
550
- authorizationServer: text("authorization_server").notNull(),
551
- clientId: text("client_id").notNull(),
552
- clientSecretEncrypted: text("client_secret_encrypted"),
553
- tokenEndpointAuthMethod: text("token_endpoint_auth_method").notNull().default("none"),
554
- metadata: jsonb("metadata").$type().notNull().default({}),
555
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
556
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
557
- },
558
- (table) => ({
559
- issuer: uniqueIndex("integration_oauth_clients_issuer_idx").on(table.issuer),
560
- authorizationServer: index("integration_oauth_clients_as_idx").on(table.authorizationServer)
561
- })
562
- );
563
- var integrationOauthStateNonces = pgTable(
564
- "integration_oauth_state_nonces",
565
- {
566
- nonce: text("nonce").primaryKey(),
567
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
568
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
569
- subjectId: text("subject_id").notNull(),
570
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
571
- usedAt: timestamp("used_at", { withTimezone: true }).notNull().defaultNow(),
572
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
573
- },
574
- (table) => ({
575
- workspace: index("integration_oauth_state_nonces_workspace_idx").on(table.workspaceId),
576
- expires: index("integration_oauth_state_nonces_expires_idx").on(table.expiresAt)
577
- })
578
- );
579
- var codexRotationSettings = pgTable(
580
- "codex_rotation_settings",
581
- {
582
- id: uuid("id").primaryKey().defaultRandom(),
583
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
584
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
585
- activeCredentialId: uuid("active_credential_id"),
586
- // Legacy selector bit. Keep false as the DB default forever: an old worker
587
- // only understands this column, so a schema-first rollout or binary
588
- // rollback must never make it enter the non-atomic rotation path.
589
- rotationEnabled: boolean("rotation_enabled").notNull().default(false),
590
- // Revision-aware allocator cutover. Only migration-compatible API/worker
591
- // code reads this bit; old binaries safely ignore it and keep the legacy
592
- // pin/rotation policy.
593
- leaseRotationEnabled: boolean("lease_rotation_enabled").notNull().default(false),
594
- rotationStrategy: text("rotation_strategy").notNull().default("sharded"),
595
- // sharded-rotation policy: legacy residue; behavior is always sharded
596
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
597
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
598
- },
599
- (table) => ({
600
- workspace: uniqueIndex("codex_rotation_settings_workspace_idx").on(table.workspaceId)
601
- })
602
- );
603
- var workspaceModelPolicies = pgTable(
604
- "workspace_model_policies",
605
- {
606
- id: uuid("id").primaryKey().defaultRandom(),
607
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
608
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
609
- allowedProviders: text("allowed_providers").array(),
610
- allowedModels: text("allowed_models").array(),
611
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
612
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
613
- },
614
- (table) => ({
615
- workspace: uniqueIndex("workspace_model_policies_workspace_idx").on(table.workspaceId)
616
- })
617
- );
618
- var codexCredentialLeases = pgTable(
619
- "codex_credential_leases",
620
- {
621
- id: uuid("id").primaryKey().defaultRandom(),
622
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
623
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
624
- credentialId: uuid("credential_id").notNull(),
625
- turnId: uuid("turn_id").notNull(),
626
- // Temporal activity execution fence. A successor dispatch for the same
627
- // durable turn replaces holderId and increments generation atomically;
628
- // stale/zombie heartbeats and releases must match both values.
629
- holderId: text("holder_id").notNull(),
630
- generation: integer("generation").notNull().default(1),
631
- leasedUntil: timestamp("leased_until", { withTimezone: true }).notNull(),
632
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
633
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
634
- },
635
- (table) => ({
636
- turn: uniqueIndex("codex_credential_leases_workspace_turn_idx").on(
637
- table.workspaceId,
638
- table.turnId
639
- ),
640
- activeCredential: index("codex_credential_leases_active_credential_idx").on(
641
- table.workspaceId,
642
- table.credentialId,
643
- table.leasedUntil
644
- ),
645
- expiry: index("codex_credential_leases_expiry_idx").on(table.leasedUntil)
646
- })
647
- );
648
- var sessions = pgTable(
649
- "sessions",
650
- {
651
- id: uuid("id").primaryKey().defaultRandom(),
652
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
653
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
654
- status: text("status").notNull().default("queued"),
655
- initialMessage: text("initial_message").notNull(),
656
- // Invisible host context frozen with the winning session create. The
657
- // initial turn copies this value so an idempotent repair can never adopt a
658
- // retrying caller's different instructions.
659
- initialTurnInstructions: text("initial_turn_instructions"),
660
- title: text("title"),
661
- titleSource: text("title_source"),
662
- // Per-session agent persona/system instructions supplied at create (the
663
- // per-agent-type prompt lever for embedding hosts). NULL ⇒ the session
664
- // carried none, so the composed agent instructions are byte-identical to a
665
- // workspace-only persona (no backfill, no behavior change for existing rows).
666
- // Composed system-level AFTER the workspace agentInstructions; never emitted
667
- // as a timeline event.
668
- instructions: text("instructions"),
669
- resources: jsonb("resources").$type().notNull().default([]),
670
- tools: jsonb("tools").$type().notNull().default([]),
671
- metadata: jsonb("metadata").$type().notNull().default({}),
672
- // Frozen creator fact. This is used for creation attribution and for the
673
- // idempotent first-turn repair only; later turns capture their own actor.
674
- createdByKind: text("created_by_kind").notNull().default("service"),
675
- createdBySubjectId: text("created_by_subject_id").notNull().default("unattributed-legacy"),
676
- createdByContext: jsonb("created_by_context").$type().notNull().default({ backfill: true }),
677
- model: text("model").notNull(),
678
- sandboxBackend: text("sandbox_backend").notNull(),
679
- // The OS this session's box runs. Defaults to 'linux' (today's only OS, so
680
- // every existing + new row is a behavior-preserving no-op). CHECK-constrained
681
- // to the SandboxOs enum (linux|macos|windows) in migration 0018.
682
- sandboxOs: text("sandbox_os").notNull().default("linux"),
683
- // The shared-sandbox group this session's box belongs to. Defaults to the
684
- // session's OWN id (a singleton group: group === session — today's 1:1
685
- // behavior). When spawned shared via session_create, set to the PARENT's
686
- // sandboxGroupId so both run in ONE box. Immutable once set. NOT an FK (the
687
- // value is this row's id or an ancestor session's id in the same workspace;
688
- // the live lease row, not a sandbox_groups table, materializes the group).
689
- // The app generates the uuid and uses it for both id and sandbox_group_id in
690
- // one insert — it cannot SQL-default to id (id is defaultRandom()).
691
- sandboxGroupId: uuid("sandbox_group_id").notNull(),
692
- // The first-class swappable-sandbox POINTER (bring-your-own-compute M2).
693
- // NULL == "use the session's own group sandbox" (the
694
- // backward-compat default — every existing/new row is a behavior-preserving
695
- // no-op). The routing proxy re-reads (active_sandbox_id, active_epoch) PER
696
- // TOOL CALL to make a Modal<->selfhosted hot-swap seamless. The FK
697
- // (-> sandboxes(id) ON DELETE SET NULL — a deleted sandbox degrades the
698
- // pointer to the group default, never dangles) lives in migration 0024, NOT a
699
- // Drizzle .references() — exactly like parentSessionId below, so the const
700
- // ordering imposes no forward-reference.
701
- activeSandboxId: uuid("active_sandbox_id"),
702
- // The SECOND epoch ABOVE sandbox_leases.lease_epoch, bumped on every swap; an
703
- // in-flight op fenced by a stale active_epoch retries against the new active
704
- // sandbox. integer (NOT bigint) — the lease-epoch spike: int8 reads back as a
705
- // JS string and breaks the strict fence; int4 returns a number.
706
- activeEpoch: integer("active_epoch").notNull().default(0),
707
- // The session's WORKING DIRECTORY — the path/cwd base the (selfhosted) box's
708
- // agent/terminal/file-dock operate under. A launch-workspace_root-relative
709
- // subdir or an absolute machine path; surfaced alongside the active-sandbox
710
- // pointer (readActiveSandbox) and written through the epoch-fenced
711
- // setActiveSandbox CAS, NOT the row INSERT. NULL (the default) ⇒ today's
712
- // behavior exactly — the agent substitutes its workspace_root for an empty cwd,
713
- // so an unset working_dir is a byte-identical no-op. Create-time only (Stage A).
714
- workingDir: text("working_dir"),
715
- variableSetId: uuid("variable_set_id").references(() => workspaceVariableSets.id, {
716
- onDelete: "set null"
717
- }),
718
- // The rig this session rides + the exact rig version frozen at create time
719
- // (migration 0047). NULL ⇒ the session rides no rig (today's behavior). FKs
720
- // (-> rigs(id)/rig_versions(id) ON DELETE SET NULL) live in migration 0047,
721
- // not Drizzle .references(), because those tables are declared later in this
722
- // file (forward-reference pattern, same as activeSandboxId). Consumed in M3.
723
- rigId: uuid("rig_id"),
724
- rigVersionId: uuid("rig_version_id"),
725
- // Non-default first-party MCP token permissions (manager-style sessions);
726
- // null means the fixed worker default set in @opengeni/runtime.
727
- firstPartyMcpPermissions: jsonb("first_party_mcp_permissions").$type(),
728
- // Durable tool-policy origin. NULL is retained for pre-migration rows;
729
- // mapSession exposes those rows as `legacy` instead of guessing omitted vs
730
- // explicit [].
731
- toolPolicy: jsonb("tool_policy").$type(),
732
- // Optimistic-concurrency fence for durable session tool-policy writes.
733
- toolPolicyVersion: integer("tool_policy_version").notNull().default(1),
734
- // The manager session that spawned this one via session_create. Set only
735
- // when the creating grant carried a worker-signed sessionId claim (a session
736
- // spawning a worker); null for direct API creates and scheduled-task runs.
737
- // When set, this worker's terminal-for-now transitions wake the parent so a
738
- // manager can orchestrate workers without busy-polling. Self-referencing FK,
739
- // ON DELETE SET NULL so deleting a manager never cascades into its workers.
740
- parentSessionId: uuid("parent_session_id"),
741
- // Workspace-scoped CREATE idempotency key. NULL means the create carried no
742
- // key (each such create is independent). When set, the partial unique index
743
- // below collapses concurrent/retried creates with the same key in the same
744
- // workspace to a single session row — the dedup that closes the
745
- // double-submit/double-dispatch stuck-queued bug.
746
- createIdempotencyKey: text("create_idempotency_key"),
747
- // Immutable creation-time hierarchy and policy snapshot. These values are
748
- // populated by the database admission boundary and never re-derived from
749
- // a live workspace setting for an existing session.
750
- rootSessionId: uuid("root_session_id").notNull(),
751
- nestedAgentDepth: integer("nested_agent_depth").notNull(),
752
- maxNestedAgentDepthOverride: integer("max_nested_agent_depth_override"),
753
- effectiveMaxNestedAgentDepth: integer("effective_max_nested_agent_depth").notNull(),
754
- nestedAgentDepthPolicySource: text("nested_agent_depth_policy_source").notNull(),
755
- nestedAgentDepthPolicySessionId: uuid("nested_agent_depth_policy_session_id"),
756
- temporalWorkflowId: text("temporal_workflow_id"),
757
- activeTurnId: uuid("active_turn_id"),
758
- // Actual input tokens reported for the last model call of the most recent
759
- // turn. The pre-turn portable compaction trigger reads this as its budget
760
- // signal (char/4 estimate is the same-turn fallback). Null until a turn with
761
- // usage has completed.
762
- lastInputTokens: integer("last_input_tokens"),
763
- // Operator /compact request flag. The API sets
764
- // it true; the worker honors it BEFORE the next turn's model call by forcing
765
- // a compaction, then clears it. A durable flag (not a transient signal) so
766
- // the trigger survives a worker restart and converges before the next turn.
767
- compactRequested: boolean("compact_requested").notNull().default(false),
768
- queueVersion: integer("queue_version").notNull().default(0),
769
- queueHeadPosition: bigint("queue_head_position", { mode: "number" }).notNull().default(0),
770
- queueTailPosition: bigint("queue_tail_position", { mode: "number" }).notNull().default(0),
771
- directControlState: text("direct_control_state").notNull().default("active"),
772
- directPauseRevision: bigint("direct_pause_revision", { mode: "number" }),
773
- subtreeRunOverrideRevision: bigint("subtree_run_override_revision", {
774
- mode: "number"
775
- }),
776
- controlVersion: bigint("control_version", { mode: "number" }).notNull().default(0),
777
- directControlReason: text("direct_control_reason"),
778
- directControlChangedBy: text("direct_control_changed_by"),
779
- directControlChangedAt: timestamp("direct_control_changed_at", {
780
- withTimezone: true
781
- }),
782
- lastSequence: integer("last_sequence").notNull().default(0),
783
- // The session's PINNED Codex account (manual override from the in-session
784
- // switcher). NULL ⇒ follow the workspace active pointer. FK declared in the
785
- // migration with ON DELETE SET NULL (a disconnected pin degrades to "follow
786
- // active", never dangles), same pattern as activeSandboxId.
787
- codexPinnedCredentialId: uuid("codex_pinned_credential_id"),
788
- // The Codex account the session's most recent turn ACTUALLY ran on — drives
789
- // the "Running on:" indicator. Written by the worker at the turn boundary. FK
790
- // ON DELETE SET NULL (migration).
791
- codexLastCredentialId: uuid("codex_last_credential_id"),
792
- // The SOURCE of codex_pinned_credential_id (AM-2): 'manual' — the user's
793
- // in-session account switcher, which is SACRED and never moved by any policy —
794
- // or 'policy' — the sharded rotation strategy's deterministic per-session home
795
- // assignment, which MAY be re-sharded to another account when its own account
796
- // caps. NULL when there is no pin (and for every pre-existing row). CHECK
797
- // (manual|policy) lives in the migration; no FK (it describes the pin, not an
798
- // account).
799
- codexPinSource: text("codex_pin_source"),
800
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
801
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
802
- // Assigned by the database trigger whenever canonical updated_at activity
803
- // advances. Legacy rows remain zero until touched; raw delta-only writers
804
- // intentionally omit updated_at and therefore do not allocate revisions.
805
- activityRevision: bigint("activity_revision", { mode: "number" }).notNull().default(0)
806
- },
807
- (table) => ({
808
- workspaceIdentity: uniqueIndex("sessions_workspace_id_idx").on(table.workspaceId, table.id),
809
- workspaceCreated: index("sessions_workspace_created_idx").on(
810
- table.workspaceId,
811
- table.createdAt
812
- ),
813
- // Model-facing monitoring pages use exact (timestamp,id) keysets. Keep the
814
- // older prefix index during rolling deploys; these composites serve both
815
- // deterministic traversal and updatedAfter change scans.
816
- workspaceCreatedId: index("sessions_workspace_created_id_idx").on(
817
- table.workspaceId,
818
- table.createdAt.desc(),
819
- table.id.desc()
820
- ),
821
- workspaceUpdatedId: index("sessions_workspace_updated_id_idx").on(
822
- table.workspaceId,
823
- table.updatedAt.desc(),
824
- table.id.desc()
825
- ),
826
- workspaceActivityRevision: index("sessions_workspace_activity_revision_idx").on(
827
- table.workspaceId,
828
- table.activityRevision.desc(),
829
- table.updatedAt.desc(),
830
- table.id.desc()
831
- ),
832
- variableSet: index("sessions_variable_set_idx").on(table.workspaceId, table.variableSetId),
833
- parent: index("sessions_parent_idx").on(table.workspaceId, table.parentSessionId),
834
- // Routing index: resolve session_id -> sandbox_group_id at every lease entry
835
- // point and enumerate all sessions in a group for attribution/disclosure.
836
- sandboxGroup: index("sessions_sandbox_group_idx").on(table.workspaceId, table.sandboxGroupId),
837
- // Partial unique index: one session per (workspace, create_idempotency_key)
838
- // when a key is present. The boundary trigger reserves the cross-outcome
839
- // winner before this source row commits; a losing source insert is
840
- // suppressed and the domain layer replays the durable winner.
841
- createIdempotency: uniqueIndex("sessions_workspace_create_idempotency_idx").on(table.workspaceId, table.createIdempotencyKey).where(sql`${table.createIdempotencyKey} is not null`),
842
- rootDepth: index("sessions_workspace_root_depth_idx").on(
843
- table.workspaceId,
844
- table.rootSessionId,
845
- table.nestedAgentDepth
846
- )
847
- })
848
- );
849
- var sessionSpawnDenials = pgTable(
850
- "session_spawn_denials",
851
- {
852
- id: uuid("id").primaryKey().defaultRandom(),
853
- accountId: uuid("account_id").notNull(),
854
- workspaceId: uuid("workspace_id").notNull(),
855
- parentSessionId: uuid("parent_session_id"),
856
- rootSessionId: uuid("root_session_id"),
857
- currentDepth: integer("current_depth").notNull(),
858
- attemptedDepth: bigint("attempted_depth", { mode: "number" }).notNull(),
859
- effectiveMaxNestedAgentDepth: integer("effective_max_nested_agent_depth").notNull(),
860
- requestedMaxNestedAgentDepthOverride: integer("requested_max_nested_agent_depth_override"),
861
- policySource: text("policy_source").notNull(),
862
- policySessionId: uuid("policy_session_id"),
863
- subjectId: text("subject_id"),
864
- code: text("code").notNull(),
865
- idempotencyKey: text("idempotency_key"),
866
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
867
- },
868
- (table) => ({
869
- workspaceIdentity: uniqueIndex("session_spawn_denials_workspace_id_uq").on(
870
- table.workspaceId,
871
- table.id
872
- ),
873
- workspaceCreated: index("session_spawn_denials_workspace_created_idx").on(
874
- table.workspaceId,
875
- table.createdAt
876
- ),
877
- parent: index("session_spawn_denials_parent_idx").on(
878
- table.workspaceId,
879
- table.parentSessionId,
880
- table.createdAt
881
- ),
882
- idempotency: uniqueIndex("session_spawn_denials_workspace_idempotency_idx").on(table.workspaceId, table.idempotencyKey).where(sql`${table.idempotencyKey} is not null`),
883
- workspaceAccount: foreignKey({
884
- name: "session_spawn_denials_workspace_account_fk",
885
- columns: [table.workspaceId, table.accountId],
886
- foreignColumns: [workspaces.id, workspaces.accountId]
887
- }).onDelete("cascade")
888
- })
889
- );
890
- var sessionPins = pgTable(
891
- "session_pins",
892
- {
893
- id: uuid("id").primaryKey().defaultRandom(),
894
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
895
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
896
- subjectId: text("subject_id").notNull(),
897
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
898
- // Keep an unpinned tombstone (pinned=false, pinned_at=null) rather than
899
- // deleting it. That preserves a monotonic version and prevents an ABA race:
900
- // a stale client that saw pin version 1 cannot silently overwrite a later
901
- // unpin+re-pin that would otherwise recreate version 1.
902
- pinned: boolean("pinned").notNull().default(true),
903
- pinnedAt: timestamp("pinned_at", { withTimezone: true }).defaultNow(),
904
- version: integer("version").notNull().default(1)
905
- },
906
- (table) => ({
907
- subjectNonempty: check(
908
- "session_pins_subject_nonempty",
909
- sql`length(btrim(${table.subjectId})) > 0`
910
- ),
911
- versionPositive: check("session_pins_version_positive", sql`${table.version} >= 1`),
912
- stateConsistent: check(
913
- "session_pins_state_consistent",
914
- sql`((${table.pinned}) and (${table.pinnedAt}) is not null) or ((not ${table.pinned}) and (${table.pinnedAt}) is null)`
915
- ),
916
- workspaceAccount: foreignKey({
917
- name: "session_pins_workspace_account_fk",
918
- columns: [table.workspaceId, table.accountId],
919
- foreignColumns: [workspaces.id, workspaces.accountId]
920
- }).onDelete("cascade"),
921
- workspaceSession: foreignKey({
922
- name: "session_pins_workspace_session_fk",
923
- columns: [table.workspaceId, table.sessionId],
924
- foreignColumns: [sessions.workspaceId, sessions.id]
925
- }).onDelete("cascade"),
926
- subjectSession: uniqueIndex("session_pins_subject_workspace_session_idx").on(
927
- table.subjectId,
928
- table.workspaceId,
929
- table.sessionId
930
- ),
931
- subjectPinned: index("session_pins_workspace_subject_pinned_idx").on(
932
- table.workspaceId,
933
- table.subjectId,
934
- table.pinned,
935
- table.pinnedAt.desc(),
936
- table.sessionId.desc()
937
- )
938
- })
939
- );
940
- var sessionListSnapshots = pgTable(
941
- "session_list_snapshots",
942
- {
943
- id: uuid("id").primaryKey().defaultRandom(),
944
- accountId: uuid("account_id").notNull(),
945
- workspaceId: uuid("workspace_id").notNull(),
946
- subjectId: text("subject_id").notNull(),
947
- parentSessionFilter: text("parent_session_filter").notNull().default("all"),
948
- search: text("search"),
949
- ordinarySessionIds: uuid("ordinary_session_ids").array().notNull().default(sql`'{}'::uuid[]`),
950
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
951
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
952
- },
953
- (table) => ({
954
- workspaceAccount: foreignKey({
955
- name: "session_list_snapshots_workspace_account_fk",
956
- columns: [table.workspaceId, table.accountId],
957
- foreignColumns: [workspaces.id, workspaces.accountId]
958
- }).onDelete("cascade"),
959
- subjectNonempty: check(
960
- "session_list_snapshots_subject_nonempty",
961
- sql`length(btrim(${table.subjectId})) > 0`
962
- ),
963
- parentFilterValid: check(
964
- "session_list_snapshots_parent_filter_valid",
965
- sql`${table.parentSessionFilter} = 'all' or ${table.parentSessionFilter} = 'null' or ${table.parentSessionFilter} ~ '^[0-9a-fA-F-]{36}$'`
966
- ),
967
- searchLength: check(
968
- "session_list_snapshots_search_length",
969
- sql`${table.search} is null or length(${table.search}) <= 200`
970
- ),
971
- workspaceExpiry: index("session_list_snapshots_workspace_expiry_idx").on(
972
- table.workspaceId,
973
- table.subjectId,
974
- table.expiresAt
975
- ),
976
- expiryReaper: index("session_list_snapshots_expiry_reaper_idx").on(table.expiresAt, table.id)
977
- })
978
- );
979
- var sessionMcpServers = pgTable(
980
- "session_mcp_servers",
981
- {
982
- id: uuid("id").primaryKey().defaultRandom(),
983
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
984
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
985
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
986
- serverId: text("server_id").notNull(),
987
- name: text("name"),
988
- url: text("url").notNull(),
989
- allowedTools: jsonb("allowed_tools").$type(),
990
- timeoutMs: integer("timeout_ms"),
991
- cacheToolsList: boolean("cache_tools_list").notNull().default(false),
992
- // Human-approval policy: `true` = every tool requires approval, a string[] of
993
- // UNPREFIXED tool names = only those require it, null/absent = auto-run.
994
- requireApproval: jsonb("require_approval").$type(),
995
- // Non-secret pointer resolved at request time by the standalone broker or
996
- // an embedding host. Unlike headersEncrypted, this is safe to project.
997
- connectionRef: jsonb("connection_ref").$type(),
998
- // Map of header name -> AES-GCM ciphertext. Values are decrypted only by the
999
- // worker's run-preparation path and never returned by API helpers.
1000
- headersEncrypted: jsonb("headers_encrypted").$type().notNull().default({}),
1001
- credentialVersion: integer("credential_version").notNull().default(1),
1002
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1003
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1004
- },
1005
- (table) => ({
1006
- sessionServer: uniqueIndex("session_mcp_servers_session_server_idx").on(
1007
- table.workspaceId,
1008
- table.sessionId,
1009
- table.serverId
1010
- ),
1011
- session: index("session_mcp_servers_session_idx").on(table.workspaceId, table.sessionId)
1012
- })
1013
- );
1014
- var files = pgTable(
1015
- "files",
1016
- {
1017
- id: uuid("id").primaryKey().defaultRandom(),
1018
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1019
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1020
- status: text("status").notNull().default("pending_upload"),
1021
- filename: text("filename").notNull(),
1022
- safeFilename: text("safe_filename").notNull(),
1023
- contentType: text("content_type").notNull(),
1024
- sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(),
1025
- sha256: text("sha256"),
1026
- bucket: text("bucket").notNull(),
1027
- objectKey: text("object_key").notNull(),
1028
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1029
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1030
- },
1031
- (table) => ({
1032
- workspaceCreated: index("files_workspace_created_idx").on(table.workspaceId, table.createdAt),
1033
- objectKey: uniqueIndex("files_object_key_idx").on(table.objectKey),
1034
- status: index("files_status_idx").on(table.status)
1035
- })
1036
- );
1037
- var fileUploads = pgTable(
1038
- "file_uploads",
1039
- {
1040
- id: uuid("id").primaryKey().defaultRandom(),
1041
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1042
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1043
- fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "cascade" }),
1044
- status: text("status").notNull().default("pending"),
1045
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
1046
- completedAt: timestamp("completed_at", { withTimezone: true }),
1047
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1048
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1049
- },
1050
- (table) => ({
1051
- workspace: index("file_uploads_workspace_idx").on(table.workspaceId),
1052
- fileId: index("file_uploads_file_id_idx").on(table.fileId),
1053
- status: index("file_uploads_status_idx").on(table.status)
1054
- })
1055
- );
1056
- var documentBases = pgTable(
1057
- "document_bases",
1058
- {
1059
- id: uuid("id").primaryKey().defaultRandom(),
1060
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1061
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1062
- name: text("name").notNull(),
1063
- description: text("description"),
1064
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1065
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1066
- },
1067
- (table) => ({
1068
- workspaceCreated: index("document_bases_workspace_created_idx").on(
1069
- table.workspaceId,
1070
- table.createdAt
1071
- ),
1072
- defaultName: uniqueIndex("document_bases_workspace_default_name_uq").on(table.workspaceId).where(sql`lower(btrim(${table.name})) = 'default'`)
1073
- })
1074
- );
1075
- var documents = pgTable(
1076
- "documents",
1077
- {
1078
- id: uuid("id").primaryKey().defaultRandom(),
1079
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1080
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1081
- baseId: uuid("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
1082
- fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
1083
- status: text("status").notNull().default("queued"),
1084
- title: text("title").notNull(),
1085
- parser: text("parser").notNull().default("liteparse"),
1086
- chunkCount: integer("chunk_count").notNull().default(0),
1087
- error: text("error"),
1088
- sourceKind: text("source_kind").notNull().default("manual_upload"),
1089
- sourceUri: text("source_uri"),
1090
- sourceExternalId: text("source_external_id"),
1091
- sourceTitle: text("source_title"),
1092
- sourceAuthor: text("source_author"),
1093
- sourceCreatedAt: timestamp("source_created_at", { withTimezone: true }),
1094
- sourceUpdatedAt: timestamp("source_updated_at", { withTimezone: true }),
1095
- sourceVersion: text("source_version"),
1096
- aclTags: jsonb("acl_tags").$type().notNull().default([]),
1097
- // Per-document access controls. visibility 'private' restricts human reads to
1098
- // created_by (a grant subject id, not a uuid); agent_access=false hides the
1099
- // document from agent retrieval surfaces (docs MCP) while humans keep REST.
1100
- visibility: text("visibility").notNull().default("workspace"),
1101
- createdBy: text("created_by"),
1102
- agentAccess: boolean("agent_access").notNull().default(true),
1103
- // Auto-curation output (knowledge drops).
1104
- summary: text("summary"),
1105
- topics: jsonb("topics").$type().notNull().default([]),
1106
- curationStatus: text("curation_status").notNull().default("none"),
1107
- curation: jsonb("curation").$type(),
1108
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1109
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1110
- },
1111
- (table) => ({
1112
- baseFile: uniqueIndex("documents_workspace_base_file_idx").on(
1113
- table.workspaceId,
1114
- table.baseId,
1115
- table.fileId
1116
- ),
1117
- baseStatus: index("documents_workspace_base_status_idx").on(
1118
- table.workspaceId,
1119
- table.baseId,
1120
- table.status
1121
- ),
1122
- sourceKind: index("documents_workspace_source_kind_idx").on(
1123
- table.workspaceId,
1124
- table.sourceKind
1125
- ),
1126
- sourceExternalId: index("documents_workspace_source_external_id_idx").on(
1127
- table.workspaceId,
1128
- table.sourceExternalId
1129
- ),
1130
- curationStatus: index("documents_workspace_curation_status_idx").on(
1131
- table.workspaceId,
1132
- table.curationStatus
1133
- ),
1134
- visibilityState: check(
1135
- "documents_visibility_chk",
1136
- sql`${table.visibility} in ('workspace', 'private')`
1137
- ),
1138
- curationState: check(
1139
- "documents_curation_status_chk",
1140
- sql`${table.curationStatus} in ('none', 'pending', 'suggested', 'auto_filed', 'failed')`
1141
- ),
1142
- privateCreator: check(
1143
- "documents_private_creator_chk",
1144
- sql`${table.visibility} <> 'private' or nullif(btrim(${table.createdBy}), '') is not null`
1145
- ),
1146
- topicsArray: check("documents_topics_array_chk", sql`jsonb_typeof(${table.topics}) = 'array'`),
1147
- curationObject: check(
1148
- "documents_curation_object_chk",
1149
- sql`${table.curation} is null or jsonb_typeof(${table.curation}) = 'object'`
1150
- )
1151
- })
1152
- );
1153
- var documentChunks = pgTable(
1154
- "document_chunks",
1155
- {
1156
- id: uuid("id").primaryKey().defaultRandom(),
1157
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1158
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1159
- documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
1160
- baseId: uuid("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
1161
- fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
1162
- chunkIndex: integer("chunk_index").notNull(),
1163
- text: text("text").notNull(),
1164
- metadata: jsonb("metadata").$type().notNull().default({}),
1165
- embedding: vector("embedding").notNull(),
1166
- embeddingModel: text("embedding_model").notNull(),
1167
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1168
- },
1169
- (table) => ({
1170
- documentIndex: uniqueIndex("document_chunks_workspace_document_index_idx").on(
1171
- table.workspaceId,
1172
- table.documentId,
1173
- table.chunkIndex
1174
- ),
1175
- base: index("document_chunks_workspace_base_idx").on(table.workspaceId, table.baseId)
1176
- })
1177
- );
1178
- var knowledgeMemories = pgTable(
1179
- "knowledge_memories",
1180
- {
1181
- id: uuid("id").primaryKey().defaultRandom(),
1182
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1183
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1184
- status: text("status").notNull().default("proposed"),
1185
- kind: text("kind").notNull().default("semantic"),
1186
- scope: text("scope").notNull().default("workspace"),
1187
- text: text("text").notNull(),
1188
- sourceRefs: jsonb("source_refs").$type().notNull().default([]),
1189
- confidence: integer("confidence").notNull().default(50),
1190
- metadata: jsonb("metadata").$type().notNull().default({}),
1191
- createdBySessionId: uuid("created_by_session_id").references(() => sessions.id, {
1192
- onDelete: "set null"
1193
- }),
1194
- reviewedBy: text("reviewed_by"),
1195
- reviewedAt: timestamp("reviewed_at", { withTimezone: true }),
1196
- // Workspace Memory V1 (migration 0045). Embedding is nullable: fail-soft writes
1197
- // (embedder unavailable) persist keyword-searchable rows without a vector.
1198
- embedding: vector("embedding"),
1199
- embeddingModel: text("embedding_model"),
1200
- pinned: boolean("pinned").notNull().default(false),
1201
- usageCount: integer("usage_count").notNull().default(0),
1202
- lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
1203
- // Self-referential supersession chain. FKs live in migration 0045 (ON DELETE SET
1204
- // NULL); declared here as plain columns like the migration-only composite FK.
1205
- supersedesId: uuid("supersedes_id"),
1206
- supersededById: uuid("superseded_by_id"),
1207
- validFrom: timestamp("valid_from", { withTimezone: true }).notNull().defaultNow(),
1208
- validUntil: timestamp("valid_until", { withTimezone: true }),
1209
- // sha256(normalizeMemoryText(text)) — exact-dedup key; see memory-domain.
1210
- textHash: text("text_hash"),
1211
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1212
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1213
- },
1214
- (table) => ({
1215
- workspaceStatus: index("knowledge_memories_workspace_status_idx").on(
1216
- table.workspaceId,
1217
- table.status,
1218
- table.updatedAt
1219
- ),
1220
- workspaceKind: index("knowledge_memories_workspace_kind_idx").on(table.workspaceId, table.kind),
1221
- workspaceScope: index("knowledge_memories_workspace_scope_idx").on(
1222
- table.workspaceId,
1223
- table.scope
1224
- ),
1225
- createdBySession: index("knowledge_memories_workspace_created_by_session_idx").on(
1226
- table.workspaceId,
1227
- table.createdBySessionId
1228
- ),
1229
- // Working-set selection (partial index mirrors migration 0045).
1230
- workspaceVisible: index("knowledge_memories_workspace_visible_idx").on(table.workspaceId, table.pinned, table.updatedAt).where(sql`${table.status} in ('active', 'approved')`),
1231
- workspaceTextHash: index("knowledge_memories_workspace_text_hash_idx").on(
1232
- table.workspaceId,
1233
- table.textHash
1234
- ),
1235
- 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`)
1236
- })
1237
- );
1238
- var sessionTurns = pgTable(
1239
- "session_turns",
1240
- {
1241
- id: uuid("id").primaryKey().defaultRandom(),
1242
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1243
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1244
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1245
- triggerEventId: uuid("trigger_event_id").notNull(),
1246
- temporalWorkflowId: text("temporal_workflow_id").notNull(),
1247
- status: text("status").notNull(),
1248
- source: text("source").notNull().default("user"),
1249
- position: bigint("position", { mode: "number" }).notNull(),
1250
- prompt: text("prompt").notNull(),
1251
- // Host context for this exact turn. System-level at runtime and deliberately
1252
- // separate from the visible prompt/event payload.
1253
- turnInstructions: text("turn_instructions"),
1254
- resources: jsonb("resources").$type().notNull().default([]),
1255
- tools: jsonb("tools").$type().notNull().default([]),
1256
- // false = inherit the durable session policy; true = this turn explicitly
1257
- // replaces it with `tools` after the core subset fence.
1258
- toolsProvided: boolean("tools_provided").notNull().default(false),
1259
- model: text("model").notNull(),
1260
- reasoningEffort: text("reasoning_effort").notNull(),
1261
- sandboxBackend: text("sandbox_backend").notNull(),
1262
- // Per-turn OS override. NULL = inherit the session's sandbox_os. CHECK-
1263
- // constrained to the SandboxOs enum (or NULL) in migration 0018.
1264
- sandboxOs: text("sandbox_os"),
1265
- metadata: jsonb("metadata").$type().notNull().default({}),
1266
- version: integer("version").notNull().default(1),
1267
- executionGeneration: integer("execution_generation").notNull().default(0),
1268
- // Composite FK to session_turn_attempts is installed by migration 0063.
1269
- // It lives in SQL because attempts carry the reciprocal turn FK and because
1270
- // the claim transaction preallocates this ID before inserting the attempt;
1271
- // the SQL constraint is therefore DEFERRABLE INITIALLY DEFERRED.
1272
- activeAttemptId: uuid("active_attempt_id"),
1273
- lineage: jsonb("lineage").$type().notNull().default({}),
1274
- // Required immutable authority captured when the turn is accepted. These
1275
- // columns are deliberately outside mutable metadata/lineage.
1276
- initiatorKind: text("initiator_kind").notNull().default("service"),
1277
- initiatorSubjectId: text("initiator_subject_id").notNull().default("unattributed-legacy"),
1278
- initiatorContext: jsonb("initiator_context").$type().notNull().default({ backfill: true }),
1279
- cancelledBy: text("cancelled_by"),
1280
- cancelReason: text("cancel_reason"),
1281
- // Atomic per-turn toolspace call budget counter (migration 0043). Incremented
1282
- // by a single conditional UPDATE at tools/call time; the row lock serializes
1283
- // concurrent reservations so exactly `toolspaceMaxCallsPerTurn` succeed.
1284
- toolspaceCallCount: integer("toolspace_call_count").notNull().default(0),
1285
- startedAt: timestamp("started_at", { withTimezone: true }),
1286
- finishedAt: timestamp("finished_at", { withTimezone: true }),
1287
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1288
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1289
- },
1290
- (table) => ({
1291
- workspaceIdentity: uniqueIndex("session_turns_workspace_id_idx").on(
1292
- table.workspaceId,
1293
- table.id
1294
- ),
1295
- queue: index("session_turns_workspace_queue_idx").on(
1296
- table.workspaceId,
1297
- table.sessionId,
1298
- table.status,
1299
- table.position
1300
- ),
1301
- oneCurrentInference: uniqueIndex("session_turns_one_current_inference_uq").on(table.workspaceId, table.sessionId).where(sql`${table.status} in ('running','requires_action','recovering','waiting_capacity')`)
1302
- })
1303
- );
1304
- var sessionTurnAttempts = pgTable(
1305
- "session_turn_attempts",
1306
- {
1307
- id: uuid("id").primaryKey(),
1308
- accountId: uuid("account_id").notNull(),
1309
- workspaceId: uuid("workspace_id").notNull(),
1310
- sessionId: uuid("session_id").notNull(),
1311
- turnId: uuid("turn_id").notNull(),
1312
- executionGeneration: integer("execution_generation").notNull(),
1313
- state: text("state").notNull().default("claimed"),
1314
- outcome: text("outcome"),
1315
- temporalWorkflowId: text("temporal_workflow_id").notNull(),
1316
- temporalWorkflowRunId: text("temporal_workflow_run_id").notNull(),
1317
- temporalActivityId: text("temporal_activity_id").notNull(),
1318
- workerId: text("worker_id"),
1319
- leaseId: text("lease_id"),
1320
- leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }),
1321
- verifiedControlRevision: bigint("verified_control_revision", {
1322
- mode: "number"
1323
- }).notNull(),
1324
- // Immutable policy snapshot captured under the session lock at claim.
1325
- mcpApprovalPolicies: jsonb("mcp_approval_policies").$type().notNull(),
1326
- startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(),
1327
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1328
- closedAt: timestamp("closed_at", { withTimezone: true }),
1329
- // The cancelled activity writes this after losing inference, user-visible
1330
- // output, and workspace-persistence authority. Fenced/idempotent cleanup
1331
- // and telemetry may still finish. Temporal activity cancellation or
1332
- // terminalization is transport state only; queue admission and clients use
1333
- // this durable receipt as the physical-quiescence authority.
1334
- quiescedAt: timestamp("quiesced_at", { withTimezone: true })
1335
- },
1336
- (table) => ({
1337
- workspaceAccount: foreignKey({
1338
- name: "session_turn_attempts_workspace_account_fk",
1339
- columns: [table.workspaceId, table.accountId],
1340
- foreignColumns: [workspaces.id, workspaces.accountId]
1341
- }).onDelete("cascade"),
1342
- workspaceSession: foreignKey({
1343
- name: "session_turn_attempts_workspace_session_fk",
1344
- columns: [table.workspaceId, table.sessionId],
1345
- foreignColumns: [sessions.workspaceId, sessions.id]
1346
- }).onDelete("restrict"),
1347
- workspaceTurn: foreignKey({
1348
- name: "session_turn_attempts_workspace_turn_fk",
1349
- columns: [table.workspaceId, table.turnId],
1350
- foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
1351
- }).onDelete("restrict"),
1352
- workspaceIdentity: uniqueIndex("session_turn_attempts_workspace_id_uq").on(
1353
- table.workspaceId,
1354
- table.id
1355
- ),
1356
- ownershipIdentity: uniqueIndex("session_turn_attempts_human_input_owner_uq").on(
1357
- table.accountId,
1358
- table.workspaceId,
1359
- table.sessionId,
1360
- table.turnId,
1361
- table.id
1362
- ),
1363
- liveTurn: uniqueIndex("session_turn_attempts_live_turn_uq").on(table.workspaceId, table.turnId).where(sql`${table.state} in ('claimed', 'running')`),
1364
- liveSession: uniqueIndex("session_turn_attempts_live_session_uq").on(table.workspaceId, table.sessionId).where(sql`${table.state} in ('claimed', 'running')`),
1365
- latestSessionAttempt: index("session_turn_attempts_latest_session_idx").on(
1366
- table.workspaceId,
1367
- table.sessionId,
1368
- table.startedAt.desc(),
1369
- table.id.desc()
1370
- ),
1371
- dispatch: uniqueIndex("session_turn_attempts_dispatch_uq").on(
1372
- table.workspaceId,
1373
- table.temporalWorkflowRunId,
1374
- table.temporalActivityId
1375
- ),
1376
- leaseExpiry: index("session_turn_attempts_lease_expiry_idx").on(table.leaseExpiresAt, table.workspaceId, table.sessionId).where(sql`${table.state} in ('claimed', 'running')`),
1377
- stateValid: check(
1378
- "session_turn_attempts_state_check",
1379
- sql`${table.state} in ('claimed', 'running', 'closed')`
1380
- ),
1381
- outcomeValid: check(
1382
- "session_turn_attempts_outcome_check",
1383
- sql`${table.outcome} is null or ${table.outcome} in (
1384
- 'completed', 'failed', 'cancelled', 'superseded', 'requires_action',
1385
- 'waiting_capacity', 'interrupted_recoverable', 'lease_lost_recoverable',
1386
- 'pre_cutover_closed'
1387
- )`
1388
- ),
1389
- closedConsistent: check(
1390
- "session_turn_attempts_closed_check",
1391
- sql`(${table.state} = 'closed' and ${table.outcome} is not null and ${table.closedAt} is not null)
1392
- or (${table.state} <> 'closed' and ${table.outcome} is null and ${table.closedAt} is null)`
1393
- )
1394
- })
1395
- );
1396
- var sessionCommandReceipts = pgTable(
1397
- "session_command_receipts",
1398
- {
1399
- id: uuid("id").primaryKey().defaultRandom(),
1400
- accountId: uuid("account_id").notNull(),
1401
- workspaceId: uuid("workspace_id").notNull(),
1402
- actorType: text("actor_type").notNull(),
1403
- actorSubjectId: text("actor_subject_id"),
1404
- actorAttemptId: uuid("actor_attempt_id"),
1405
- action: text("action").notNull(),
1406
- targetSessionId: uuid("target_session_id"),
1407
- targetTurnId: uuid("target_turn_id"),
1408
- operationKey: text("operation_key").notNull(),
1409
- canonicalRequestHash: text("canonical_request_hash").notNull(),
1410
- appliedControlRevision: bigint("applied_control_revision", {
1411
- mode: "number"
1412
- }),
1413
- appliedQueueVersion: integer("applied_queue_version"),
1414
- appliedTurnVersion: integer("applied_turn_version"),
1415
- appliedDraftRevision: bigint("applied_draft_revision", { mode: "number" }),
1416
- result: jsonb("result").$type().notNull().default({}),
1417
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1418
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1419
- },
1420
- (table) => ({
1421
- workspaceAccount: foreignKey({
1422
- name: "session_command_receipts_workspace_account_fk",
1423
- columns: [table.workspaceId, table.accountId],
1424
- foreignColumns: [workspaces.id, workspaces.accountId]
1425
- }).onDelete("cascade"),
1426
- actorAttempt: foreignKey({
1427
- name: "session_command_receipts_actor_attempt_fk",
1428
- columns: [table.workspaceId, table.actorAttemptId],
1429
- foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
1430
- }).onDelete("restrict"),
1431
- targetSession: foreignKey({
1432
- name: "session_command_receipts_target_session_fk",
1433
- columns: [table.workspaceId, table.targetSessionId],
1434
- foreignColumns: [sessions.workspaceId, sessions.id]
1435
- }).onDelete("restrict"),
1436
- targetTurn: foreignKey({
1437
- name: "session_command_receipts_target_turn_fk",
1438
- columns: [table.workspaceId, table.targetTurnId],
1439
- foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
1440
- }).onDelete("restrict"),
1441
- workspaceIdentity: uniqueIndex("session_command_receipts_workspace_id_uq").on(
1442
- table.workspaceId,
1443
- table.id
1444
- ),
1445
- targetCreated: index("session_command_receipts_target_created_idx").on(
1446
- table.workspaceId,
1447
- table.targetSessionId,
1448
- table.createdAt
1449
- ),
1450
- goalUpdateOperation: uniqueIndex("session_command_receipts_goal_update_operation_uq").on(table.workspaceId, table.action, table.targetSessionId, table.operationKey).where(sql`${table.action} = 'goal.update'`),
1451
- actorValid: check(
1452
- "session_command_receipts_actor_check",
1453
- sql`(
1454
- ${table.actorType} = 'agent_attempt'
1455
- and ${table.actorAttemptId} is not null
1456
- and ${table.actorSubjectId} is null
1457
- ) or (
1458
- ${table.actorType} in ('human', 'operator', 'service')
1459
- and ${table.actorSubjectId} is not null
1460
- and ${table.actorAttemptId} is null
1461
- )`
1462
- )
1463
- })
1464
- );
1465
- var workspaceControlEvents = pgTable(
1466
- "workspace_control_events",
1467
- {
1468
- id: uuid("id").primaryKey().defaultRandom(),
1469
- accountId: uuid("account_id").notNull(),
1470
- workspaceId: uuid("workspace_id").notNull(),
1471
- revision: bigint("revision", { mode: "number" }).notNull(),
1472
- scope: text("scope").notNull(),
1473
- rootSessionId: uuid("root_session_id"),
1474
- action: text("action").notNull(),
1475
- automatic: boolean("automatic").notNull().default(false),
1476
- reason: text("reason"),
1477
- reasonOriginalBytes: integer("reason_original_bytes"),
1478
- actor: text("actor").notNull(),
1479
- // Null is the rolling-upgrade shape for untouched, already-bounded legacy
1480
- // rows. New writes and rewritten poison rows carry exact source byte facts.
1481
- actorOriginalBytes: integer("actor_original_bytes"),
1482
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow()
1483
- },
1484
- (table) => ({
1485
- workspaceAccount: foreignKey({
1486
- name: "workspace_control_events_workspace_account_fk",
1487
- columns: [table.workspaceId, table.accountId],
1488
- foreignColumns: [workspaces.id, workspaces.accountId]
1489
- }).onDelete("cascade"),
1490
- rootSession: foreignKey({
1491
- name: "workspace_control_events_root_session_fk",
1492
- columns: [table.workspaceId, table.rootSessionId],
1493
- foreignColumns: [sessions.workspaceId, sessions.id]
1494
- }).onDelete("restrict"),
1495
- workspaceRevision: uniqueIndex("workspace_control_events_workspace_revision_uq").on(
1496
- table.workspaceId,
1497
- table.revision
1498
- ),
1499
- revisionValid: check("workspace_control_events_revision_check", sql`${table.revision} > 0`),
1500
- shapeValid: check(
1501
- "workspace_control_events_shape_check",
1502
- sql`(${table.scope} = 'workspace' and ${table.rootSessionId} is null)
1503
- or (${table.scope} = 'session' and ${table.rootSessionId} is not null)`
1504
- ),
1505
- actionValid: check(
1506
- "workspace_control_events_action_check",
1507
- sql`${table.action} in ('pause', 'resume')`
1508
- )
1509
- })
1510
- );
1511
- var sessionAttemptInterruptions = pgTable(
1512
- "session_attempt_interruptions",
1513
- {
1514
- id: uuid("id").primaryKey().defaultRandom(),
1515
- accountId: uuid("account_id").notNull(),
1516
- workspaceId: uuid("workspace_id").notNull(),
1517
- sessionId: uuid("session_id").notNull(),
1518
- operationId: uuid("operation_id").notNull(),
1519
- attemptId: uuid("attempt_id").notNull(),
1520
- kind: text("kind").notNull(),
1521
- controlRevision: bigint("control_revision", { mode: "number" }).notNull(),
1522
- state: text("state").notNull().default("pending"),
1523
- requestedAt: timestamp("requested_at", { withTimezone: true }).notNull().defaultNow(),
1524
- deliveredAt: timestamp("delivered_at", { withTimezone: true }),
1525
- acknowledgedAt: timestamp("acknowledged_at", { withTimezone: true }),
1526
- settledAt: timestamp("settled_at", { withTimezone: true })
1527
- },
1528
- (table) => ({
1529
- workspaceAccount: foreignKey({
1530
- name: "session_attempt_interruptions_workspace_account_fk",
1531
- columns: [table.workspaceId, table.accountId],
1532
- foreignColumns: [workspaces.id, workspaces.accountId]
1533
- }).onDelete("cascade"),
1534
- workspaceSession: foreignKey({
1535
- name: "session_attempt_interruptions_workspace_session_fk",
1536
- columns: [table.workspaceId, table.sessionId],
1537
- foreignColumns: [sessions.workspaceId, sessions.id]
1538
- }).onDelete("restrict"),
1539
- operation: foreignKey({
1540
- name: "session_attempt_interruptions_operation_fk",
1541
- columns: [table.workspaceId, table.operationId],
1542
- foreignColumns: [sessionCommandReceipts.workspaceId, sessionCommandReceipts.id]
1543
- }).onDelete("restrict"),
1544
- attempt: foreignKey({
1545
- name: "session_attempt_interruptions_attempt_fk",
1546
- columns: [table.workspaceId, table.attemptId],
1547
- foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
1548
- }).onDelete("restrict"),
1549
- operationAttempt: uniqueIndex("session_attempt_interruptions_operation_attempt_uq").on(
1550
- table.operationId,
1551
- table.attemptId
1552
- ),
1553
- unsettled: index("session_attempt_interruptions_unsettled_idx").on(table.workspaceId, table.sessionId, table.requestedAt).where(sql`${table.state} in ('pending', 'delivered', 'acknowledged')`),
1554
- kindValid: check(
1555
- "session_attempt_interruptions_kind_check",
1556
- sql`${table.kind} in ('session_pause', 'workspace_pause', 'steer', 'maintenance')`
1557
- ),
1558
- stateValid: check(
1559
- "session_attempt_interruptions_state_check",
1560
- sql`${table.state} in ('pending', 'delivered', 'acknowledged', 'settled', 'rejected_stale')`
1561
- )
1562
- })
1563
- );
1564
- var composerDrafts = pgTable(
1565
- "composer_drafts",
1566
- {
1567
- id: uuid("id").primaryKey().defaultRandom(),
1568
- accountId: uuid("account_id").notNull(),
1569
- workspaceId: uuid("workspace_id").notNull(),
1570
- sessionId: uuid("session_id").notNull(),
1571
- subjectId: text("subject_id").notNull(),
1572
- revision: bigint("revision", { mode: "number" }).notNull().default(1),
1573
- text: text("text").notNull().default(""),
1574
- resources: jsonb("resources").$type().notNull().default([]),
1575
- tools: jsonb("tools").$type().notNull().default([]),
1576
- toolsProvided: boolean("tools_provided").notNull().default(false),
1577
- model: text("model").notNull(),
1578
- reasoningEffort: text("reasoning_effort").notNull(),
1579
- sourceTurnId: uuid("source_turn_id"),
1580
- sourceTurnVersion: integer("source_turn_version"),
1581
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1582
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1583
- },
1584
- (table) => ({
1585
- workspaceAccount: foreignKey({
1586
- name: "composer_drafts_workspace_account_fk",
1587
- columns: [table.workspaceId, table.accountId],
1588
- foreignColumns: [workspaces.id, workspaces.accountId]
1589
- }).onDelete("cascade"),
1590
- workspaceSession: foreignKey({
1591
- name: "composer_drafts_workspace_session_fk",
1592
- columns: [table.workspaceId, table.sessionId],
1593
- foreignColumns: [sessions.workspaceId, sessions.id]
1594
- }).onDelete("cascade"),
1595
- sourceTurn: foreignKey({
1596
- name: "composer_drafts_source_turn_fk",
1597
- columns: [table.workspaceId, table.sourceTurnId],
1598
- foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
1599
- }).onDelete("restrict"),
1600
- subjectSession: uniqueIndex("composer_drafts_subject_session_uq").on(
1601
- table.workspaceId,
1602
- table.sessionId,
1603
- table.subjectId
1604
- ),
1605
- subjectValid: check(
1606
- "composer_drafts_subject_check",
1607
- sql`length(btrim(${table.subjectId})) > 0`
1608
- ),
1609
- revisionValid: check("composer_drafts_revision_check", sql`${table.revision} >= 1`)
1610
- })
1611
- );
1612
- var newSessionDrafts = pgTable(
1613
- "new_session_drafts",
1614
- {
1615
- id: uuid("id").primaryKey().defaultRandom(),
1616
- accountId: uuid("account_id").notNull(),
1617
- workspaceId: uuid("workspace_id").notNull(),
1618
- subjectId: text("subject_id").notNull(),
1619
- revision: bigint("revision", { mode: "number" }).notNull().default(1),
1620
- text: text("text").notNull().default(""),
1621
- resources: jsonb("resources").$type().notNull().default([]),
1622
- tools: jsonb("tools").$type().notNull().default([]),
1623
- model: text("model").notNull(),
1624
- reasoningEffort: text("reasoning_effort").notNull(),
1625
- sessionOptions: jsonb("session_options").$type().notNull().default({}),
1626
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1627
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1628
- },
1629
- (table) => ({
1630
- workspaceAccount: foreignKey({
1631
- name: "new_session_drafts_workspace_account_fk",
1632
- columns: [table.workspaceId, table.accountId],
1633
- foreignColumns: [workspaces.id, workspaces.accountId]
1634
- }).onDelete("cascade"),
1635
- subjectWorkspace: uniqueIndex("new_session_drafts_subject_workspace_uq").on(
1636
- table.workspaceId,
1637
- table.subjectId
1638
- ),
1639
- subjectValid: check(
1640
- "new_session_drafts_subject_check",
1641
- sql`length(btrim(${table.subjectId})) > 0`
1642
- ),
1643
- revisionValid: check("new_session_drafts_revision_check", sql`${table.revision} >= 1`)
1644
- })
1645
- );
1646
- var sessionSystemUpdates = pgTable(
1647
- "session_system_updates",
1648
- {
1649
- id: uuid("id").primaryKey().defaultRandom(),
1650
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1651
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1652
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1653
- kind: text("kind").notNull(),
1654
- classification: text("classification").notNull().default("info"),
1655
- sourceId: text("source_id").notNull(),
1656
- dedupeKey: text("dedupe_key").notNull(),
1657
- summary: text("summary").notNull(),
1658
- payload: jsonb("payload").$type().notNull().default({}),
1659
- lineage: jsonb("lineage").$type().notNull().default({}),
1660
- // pending: eligible to start/attach to an inference; deferred: preserved
1661
- // after a failed internal-only inference but dormant until a real prompt or
1662
- // a genuinely new pending update arrives; delivered/cancelled/failed are
1663
- // terminal for that delivery attempt.
1664
- state: text("state").notNull().default("pending"),
1665
- deliveredTurnId: uuid("delivered_turn_id").references(() => sessionTurns.id, {
1666
- onDelete: "set null"
1667
- }),
1668
- deliveredAt: timestamp("delivered_at", { withTimezone: true }),
1669
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1670
- },
1671
- (table) => ({
1672
- kindValid: check(
1673
- "system_updates_kind_check",
1674
- sql`${table.kind} in ('scheduled_occurrence', 'goal_continuation', 'agent_message', 'agent_steer_instruction', 'child_terminal_result')`
1675
- ),
1676
- payloadKindValid: check(
1677
- "system_updates_payload_kind_check",
1678
- sql`${table.payload} ->> 'type' = ${table.kind}`
1679
- ),
1680
- stateValid: check(
1681
- "system_updates_state_check",
1682
- sql`${table.state} in ('pending', 'deferred', 'delivered', 'cancelled', 'superseded', 'failed')`
1683
- ),
1684
- dedupe: uniqueIndex("session_system_updates_dedupe_uq").on(
1685
- table.workspaceId,
1686
- table.sessionId,
1687
- table.dedupeKey
1688
- ),
1689
- pending: index("session_system_updates_pending_idx").on(
1690
- table.workspaceId,
1691
- table.sessionId,
1692
- table.state,
1693
- table.createdAt
1694
- )
1695
- })
1696
- );
1697
- var sessionSystemUpdateOutbox = pgTable(
1698
- "session_system_update_outbox",
1699
- {
1700
- id: uuid("id").primaryKey().defaultRandom(),
1701
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1702
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1703
- sourceSessionId: uuid("source_session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1704
- targetSessionId: uuid("target_session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1705
- dedupeKey: text("dedupe_key").notNull(),
1706
- kind: text("kind").notNull(),
1707
- classification: text("classification").notNull(),
1708
- sourceId: text("source_id").notNull(),
1709
- summary: text("summary").notNull(),
1710
- payload: jsonb("payload").$type().notNull().default({}),
1711
- lineage: jsonb("lineage").$type().notNull().default({}),
1712
- status: text("status").notNull().default("pending"),
1713
- attempts: integer("attempts").notNull().default(0),
1714
- updateId: uuid("update_id"),
1715
- lastError: text("last_error"),
1716
- deliveredAt: timestamp("delivered_at", { withTimezone: true }),
1717
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1718
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1719
- },
1720
- (table) => ({
1721
- kindValid: check(
1722
- "system_update_outbox_kind_check",
1723
- sql`${table.kind} = 'child_terminal_result'`
1724
- ),
1725
- payloadKindValid: check(
1726
- "system_update_outbox_payload_kind_check",
1727
- sql`${table.payload} ->> 'type' = 'child_terminal_result'`
1728
- ),
1729
- dedupe: uniqueIndex("session_system_update_outbox_dedupe_uq").on(
1730
- table.workspaceId,
1731
- table.dedupeKey
1732
- ),
1733
- pending: index("session_system_update_outbox_pending_idx").on(table.status, table.createdAt)
1734
- })
1735
- );
1736
- var sessionWorkflowWakeOutbox = pgTable(
1737
- "session_workflow_wake_outbox",
1738
- {
1739
- sessionId: uuid("session_id").primaryKey(),
1740
- accountId: uuid("account_id").notNull(),
1741
- workspaceId: uuid("workspace_id").notNull(),
1742
- temporalWorkflowId: text("temporal_workflow_id").notNull(),
1743
- wakeRevision: bigint("wake_revision", { mode: "number" }).notNull().default(1),
1744
- deliveredRevision: bigint("delivered_revision", { mode: "number" }).notNull().default(0),
1745
- reason: text("reason").notNull(),
1746
- attempts: integer("attempts").notNull().default(0),
1747
- nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
1748
- lastError: text("last_error"),
1749
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1750
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1751
- },
1752
- (table) => ({
1753
- revisionValid: check(
1754
- "session_workflow_wake_outbox_revision_check",
1755
- sql`${table.wakeRevision} > 0 and ${table.deliveredRevision} >= 0 and ${table.deliveredRevision} <= ${table.wakeRevision}`
1756
- ),
1757
- revisionSafe: check(
1758
- "session_workflow_wake_outbox_revision_safe_check",
1759
- sql`${table.wakeRevision} <= 9007199254740991 and ${table.deliveredRevision} <= 9007199254740991`
1760
- ),
1761
- workspaceAccount: foreignKey({
1762
- name: "session_workflow_wake_outbox_workspace_account_fk",
1763
- columns: [table.workspaceId, table.accountId],
1764
- foreignColumns: [workspaces.id, workspaces.accountId]
1765
- }).onDelete("cascade"),
1766
- workspaceSessionFk: foreignKey({
1767
- name: "session_workflow_wake_outbox_workspace_session_fk",
1768
- columns: [table.workspaceId, table.sessionId],
1769
- foreignColumns: [sessions.workspaceId, sessions.id]
1770
- }).onDelete("cascade"),
1771
- workspaceSession: uniqueIndex("session_workflow_wake_outbox_workspace_session_uq").on(
1772
- table.workspaceId,
1773
- table.sessionId
1774
- ),
1775
- pending: index("session_workflow_wake_outbox_pending_idx").on(table.nextAttemptAt, table.updatedAt, table.sessionId).where(sql`${table.wakeRevision} > ${table.deliveredRevision}`)
1776
- })
1777
- );
1778
- var sessionGoals = pgTable(
1779
- "session_goals",
1780
- {
1781
- id: uuid("id").primaryKey().defaultRandom(),
1782
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1783
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1784
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1785
- status: text("status").notNull().default("active"),
1786
- // active | paused | completed
1787
- text: text("text").notNull(),
1788
- successCriteria: text("success_criteria"),
1789
- evidence: text("evidence"),
1790
- // set by goal_complete
1791
- rationale: text("rationale"),
1792
- // set by goal_pause
1793
- pausedReason: text("paused_reason"),
1794
- // agent | user_pause | api | no_progress | max_auto_continuations | limits
1795
- createdBy: text("created_by").notNull().default("api"),
1796
- // api | agent | scheduled_task
1797
- version: integer("version").notNull().default(1),
1798
- // bumped on every set/update; progress signal
1799
- autoContinuations: integer("auto_continuations").notNull().default(0),
1800
- noProgressStreak: integer("no_progress_streak").notNull().default(0),
1801
- maxAutoContinuations: integer("max_auto_continuations"),
1802
- // per-goal override; a configured settings cap (if any) remains the hard ceiling
1803
- lastContinuationTurnId: uuid("last_continuation_turn_id"),
1804
- versionAtLastContinuation: integer("version_at_last_continuation"),
1805
- // Postgres owns the continuation obligation. Terminal settlement advances
1806
- // wakeRevision in the same transaction that makes the session idle;
1807
- // materialization advances observedRevision only alongside the one typed
1808
- // update, timeline events, usage row, and workflow-wake outbox row.
1809
- // Temporal signals and workflow history are replaceable nudges over these
1810
- // monotonic revisions.
1811
- continuationWakeRevision: bigint("continuation_wake_revision", { mode: "number" }).notNull().default(0),
1812
- continuationObservedRevision: bigint("continuation_observed_revision", { mode: "number" }).notNull().default(0),
1813
- metadata: jsonb("metadata").$type().notNull().default({}),
1814
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1815
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1816
- },
1817
- (table) => ({
1818
- workspaceIdentity: uniqueIndex("session_goals_workspace_id_idx").on(
1819
- table.workspaceId,
1820
- table.id
1821
- ),
1822
- workspaceSession: uniqueIndex("session_goals_workspace_session_idx").on(
1823
- table.workspaceId,
1824
- table.sessionId
1825
- ),
1826
- status: index("session_goals_workspace_status_idx").on(table.workspaceId, table.status),
1827
- continuationRevisionValid: check(
1828
- "session_goals_continuation_revision_check",
1829
- sql`${table.continuationWakeRevision} >= 0 and ${table.continuationObservedRevision} >= 0 and ${table.continuationObservedRevision} <= ${table.continuationWakeRevision} and ${table.continuationWakeRevision} <= 9007199254740991 and ${table.continuationObservedRevision} <= 9007199254740991`
1830
- )
1831
- })
1832
- );
1833
- var codexCapacityWaiters = pgTable(
1834
- "codex_capacity_waiters",
1835
- {
1836
- id: uuid("id").primaryKey().defaultRandom(),
1837
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1838
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1839
- sessionId: uuid("session_id").notNull(),
1840
- goalId: uuid("goal_id"),
1841
- blockedTurnId: uuid("blocked_turn_id").notNull(),
1842
- blockedTurnGeneration: integer("blocked_turn_generation").notNull(),
1843
- workflowId: text("workflow_id").notNull(),
1844
- generation: integer("generation").notNull().default(1),
1845
- status: text("status").notNull().default("waiting"),
1846
- // waiting | resumed | superseded
1847
- goalVersion: integer("goal_version"),
1848
- policyHash: text("policy_hash"),
1849
- earliestResetAt: timestamp("earliest_reset_at", { withTimezone: true }),
1850
- nextCheckAt: timestamp("next_check_at", { withTimezone: true }).notNull(),
1851
- resetKind: text("reset_kind").notNull(),
1852
- // authoritative | bounded_refresh
1853
- refreshAttempt: integer("refresh_attempt").notNull().default(0),
1854
- // Coalescing outbox generation. Every eligibility-affecting mutation bumps
1855
- // wakeRevision. Duplicate/lost Temporal signals are harmless because only
1856
- // the row-locked evaluator moves observedWakeRevision and may enqueue work.
1857
- wakeRevision: integer("wake_revision").notNull().default(1),
1858
- observedWakeRevision: integer("observed_wake_revision").notNull().default(0),
1859
- lastWakeReason: text("last_wake_reason").notNull().default("capacity_wait_armed"),
1860
- resumedUpdateId: uuid("resumed_update_id"),
1861
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1862
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1863
- },
1864
- (table) => ({
1865
- workspaceSession: uniqueIndex("codex_capacity_waiters_workspace_session_idx").on(
1866
- table.workspaceId,
1867
- table.sessionId
1868
- ),
1869
- workspaceId: uniqueIndex("codex_capacity_waiters_workspace_id_idx").on(
1870
- table.workspaceId,
1871
- table.id
1872
- ),
1873
- pending: index("codex_capacity_waiters_pending_idx").on(
1874
- table.workspaceId,
1875
- table.status,
1876
- table.nextCheckAt
1877
- ),
1878
- wakeRepair: index("codex_capacity_waiters_wake_repair_idx").on(
1879
- table.status,
1880
- table.wakeRevision,
1881
- table.observedWakeRevision
1882
- )
1883
- })
1884
- );
1885
- var sessionEvents = pgTable(
1886
- "session_events",
1887
- {
1888
- id: uuid("id").primaryKey().defaultRandom(),
1889
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1890
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1891
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1892
- turnId: uuid("turn_id"),
1893
- turnGeneration: integer("turn_generation"),
1894
- turnAttemptId: uuid("turn_attempt_id"),
1895
- turnAssociation: text("turn_association"),
1896
- duplicateOfEventId: uuid("duplicate_of_event_id"),
1897
- duplicateReason: text("duplicate_reason"),
1898
- sequence: integer("sequence").notNull(),
1899
- type: text("type").notNull(),
1900
- payload: jsonb("payload").$type().notNull().default({}),
1901
- clientEventId: text("client_event_id"),
1902
- producerId: text("producer_id"),
1903
- producerSeq: integer("producer_seq"),
1904
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
1905
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1906
- },
1907
- (table) => ({
1908
- workspaceAttempt: foreignKey({
1909
- name: "session_events_workspace_attempt_fk",
1910
- columns: [table.workspaceId, table.turnAttemptId],
1911
- foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
1912
- }).onDelete("restrict"),
1913
- sessionSequence: uniqueIndex("session_events_workspace_session_sequence_idx").on(
1914
- table.workspaceId,
1915
- table.sessionId,
1916
- table.sequence
1917
- ),
1918
- clientEvent: uniqueIndex("session_events_workspace_client_event_idx").on(table.workspaceId, table.sessionId, table.clientEventId).where(sql`${table.clientEventId} is not null`),
1919
- 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`),
1920
- sessionCreated: index("session_events_workspace_session_created_idx").on(
1921
- table.workspaceId,
1922
- table.sessionId,
1923
- table.createdAt
1924
- ),
1925
- sessionTypeSequence: index("session_events_workspace_session_type_sequence_idx").on(
1926
- table.workspaceId,
1927
- table.sessionId,
1928
- table.type,
1929
- table.sequence
1930
- ),
1931
- monitoringTail: index("session_events_workspace_session_monitoring_tail_idx").on(table.workspaceId, table.sessionId, table.sequence).where(
1932
- sql`${table.type} not in ('agent.message.delta', 'agent.reasoning.delta', 'sandbox.command.output.delta', 'terminal.pty.output.delta')`
1933
- ),
1934
- duplicateOfEvent: index("session_events_duplicate_of_event_idx").on(table.duplicateOfEventId),
1935
- payloadBytes: check(
1936
- "session_events_payload_bytes_check",
1937
- sql`octet_length(${table.payload}::text) <= 65536`
1938
- ),
1939
- typeBytes: check(
1940
- "session_events_type_bytes_check",
1941
- sql`octet_length(${table.type}) <= 256 and position(E'\n' in ${table.type}) = 0 and position(E'\r' in ${table.type}) = 0`
1942
- ),
1943
- clientEventIdBytes: check(
1944
- "session_events_client_event_id_bytes_check",
1945
- sql`${table.clientEventId} is null or octet_length(${table.clientEventId}) <= 1024`
1946
- ),
1947
- producerIdBytes: check(
1948
- "session_events_producer_id_bytes_check",
1949
- sql`${table.producerId} is null or octet_length(${table.producerId}) <= 1024`
1950
- ),
1951
- turnAssociationBytes: check(
1952
- "session_events_turn_association_bytes_check",
1953
- sql`${table.turnAssociation} is null or octet_length(${table.turnAssociation}) <= 64`
1954
- ),
1955
- duplicateReasonBytes: check(
1956
- "session_events_duplicate_reason_bytes_check",
1957
- sql`${table.duplicateReason} is null or octet_length(${table.duplicateReason}) <= 4096`
1958
- )
1959
- })
1960
- );
1961
- var agentRunStates = pgTable("agent_run_states", {
1962
- id: uuid("id").primaryKey().defaultRandom(),
1963
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1964
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1965
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1966
- turnId: uuid("turn_id").references(() => sessionTurns.id, {
1967
- onDelete: "set null"
1968
- }),
1969
- stateVersion: integer("state_version").notNull(),
1970
- serializedRunState: text("serialized_run_state").notNull(),
1971
- pendingApprovals: jsonb("pending_approvals").$type().notNull().default([]),
1972
- // The Codex account that FROZE this run state: the turn's resolved codex
1973
- // credential id (pin > workspace-active), or NULL when frozen on the
1974
- // non-codex / Azure path (or before this column existed). The serialized
1975
- // RunState blob round-trips `reasoning.encrypted_content` minted by the
1976
- // ChatGPT/Codex backend — account/org-bound, so a foreign blob 400s — and the
1977
- // foreign reasoning ids the Responses backend validates; but the blob carries
1978
- // NO per-item producer tag (those live only on session_history_items). So we
1979
- // stamp the freezing account here: on an approval resume whose codex account
1980
- // DIFFERS from this value,
1981
- // the replay path neutralizes every reasoning item's account-bound identity
1982
- // (encrypted_content + provider id) in the blob before it reaches the model.
1983
- // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect (a
1984
- // stale-but-null tag still mismatches a live codex id, so the strip stays
1985
- // correct either way). NULL on both sides (non-codex freeze + non-codex
1986
- // resume) is a no-op, so single-account and non-codex sessions are unchanged.
1987
- frozenCodexCredentialId: uuid("frozen_codex_credential_id"),
1988
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1989
- });
1990
- var sessionHumanInputRequests = pgTable(
1991
- "session_human_input_requests",
1992
- {
1993
- id: uuid("id").primaryKey().defaultRandom(),
1994
- accountId: uuid("account_id").notNull(),
1995
- workspaceId: uuid("workspace_id").notNull(),
1996
- sessionId: uuid("session_id").notNull(),
1997
- turnId: uuid("turn_id").notNull(),
1998
- turnGeneration: integer("turn_generation").notNull(),
1999
- creationAttemptId: uuid("creation_attempt_id").notNull(),
2000
- toolCallId: text("tool_call_id").notNull(),
2001
- status: text("status").notNull().default("pending"),
2002
- questions: jsonb("questions").$type().notNull(),
2003
- allowSkip: boolean("allow_skip").notNull().default(false),
2004
- response: jsonb("response").$type(),
2005
- respondedBy: text("responded_by"),
2006
- respondedAt: timestamp("responded_at", { withTimezone: true }),
2007
- expiresAt: timestamp("expires_at", { withTimezone: true }),
2008
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2009
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2010
- },
2011
- (table) => ({
2012
- creationAttemptOwner: foreignKey({
2013
- name: "session_human_input_requests_creation_attempt_fk",
2014
- columns: [
2015
- table.accountId,
2016
- table.workspaceId,
2017
- table.sessionId,
2018
- table.turnId,
2019
- table.creationAttemptId
2020
- ],
2021
- foreignColumns: [
2022
- sessionTurnAttempts.accountId,
2023
- sessionTurnAttempts.workspaceId,
2024
- sessionTurnAttempts.sessionId,
2025
- sessionTurnAttempts.turnId,
2026
- sessionTurnAttempts.id
2027
- ]
2028
- }).onDelete("cascade"),
2029
- toolCall: uniqueIndex("session_human_input_requests_tool_call_uq").on(
2030
- table.workspaceId,
2031
- table.sessionId,
2032
- table.turnId,
2033
- table.toolCallId
2034
- ),
2035
- pendingSession: index("session_human_input_requests_pending_session_idx").on(table.workspaceId, table.sessionId, table.createdAt, table.id).where(sql`${table.status} = 'pending'`),
2036
- pendingExpiry: index("session_human_input_requests_pending_expiry_idx").on(table.expiresAt, table.id).where(sql`${table.status} = 'pending' and ${table.expiresAt} is not null`),
2037
- status: check(
2038
- "session_human_input_requests_status_check",
2039
- sql`${table.status} in ('pending','answered','skipped','expired','cancelled')`
2040
- ),
2041
- generation: check(
2042
- "session_human_input_requests_generation_check",
2043
- sql`${table.turnGeneration} > 0`
2044
- ),
2045
- toolCallBytes: check(
2046
- "session_human_input_requests_tool_call_bytes_check",
2047
- sql`octet_length(${table.toolCallId}) between 1 and 1024`
2048
- ),
2049
- questionsBytes: check(
2050
- "session_human_input_requests_questions_bytes_check",
2051
- sql`octet_length(${table.questions}::text) <= 49152`
2052
- ),
2053
- responseBytes: check(
2054
- "session_human_input_requests_response_bytes_check",
2055
- sql`${table.response} is null or octet_length(${table.response}::text) <= 49152`
2056
- ),
2057
- actorBytes: check(
2058
- "session_human_input_requests_actor_bytes_check",
2059
- sql`${table.respondedBy} is null or octet_length(${table.respondedBy}) <= 1024`
2060
- )
2061
- })
2062
- );
2063
- var sessionHistoryItems = pgTable(
2064
- "session_history_items",
2065
- {
2066
- id: uuid("id").primaryKey().defaultRandom(),
2067
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2068
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2069
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2070
- turnId: uuid("turn_id").references(() => sessionTurns.id, {
2071
- onDelete: "set null"
2072
- }),
2073
- // Numeric (not integer) so the synthetic compaction-summary row can be
2074
- // inserted at a FRACTIONAL position (boundaryPosition - 0.5) that sorts ahead
2075
- // of the kept tail without colliding with — and thus overwriting — the real
2076
- // prefix row at boundaryPosition - 1. Normally-appended rows keep whole-number
2077
- // positions; only the summary uses the half-step. `mode: "number"` maps the
2078
- // postgres.js string back to a JS number so every reader stays numeric.
2079
- position: numeric("position", { mode: "number" }).notNull(),
2080
- item: jsonb("item").$type().notNull(),
2081
- // Live-row flag for client-side context compaction. The read path selects
2082
- // only active rows; a compaction supersedes the summarized prefix (sets this
2083
- // false — never deletes, so the full transcript stays as an audit trail) and
2084
- // inserts ONE synthetic active summary row at the boundary. Defaults true so
2085
- // every existing and normally-appended row is live.
2086
- active: boolean("active").notNull().default(true),
2087
- // The Codex account that PRODUCED these items: the per-turn resolved codex
2088
- // credential id (pin > workspace-active), or NULL when produced on the
2089
- // non-codex / Azure path (or before this column existed). Used to strip
2090
- // cross-account `reasoning.encrypted_content` blobs — those are account/org-
2091
- // bound, minted by the ChatGPT/Codex backend, so replaying account A's blob
2092
- // into a turn running on account B 400s. The read path drops the encrypted
2093
- // reasoning of any item whose producer != the turn's current codex account.
2094
- // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect
2095
- // (an ON DELETE SET NULL would erase the tag, and a stale-but-null tag still
2096
- // mismatches a live codex id so the strip stays correct either way).
2097
- producerCodexCredentialId: uuid("producer_codex_credential_id"),
2098
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
2099
- },
2100
- (table) => ({
2101
- positionIdx: uniqueIndex("session_history_items_position_idx").on(
2102
- table.workspaceId,
2103
- table.sessionId,
2104
- table.position
2105
- )
2106
- })
2107
- );
2108
- var sessionPendingToolCalls = pgTable(
2109
- "session_pending_tool_calls",
2110
- {
2111
- id: uuid("id").primaryKey().defaultRandom(),
2112
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2113
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2114
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2115
- turnId: uuid("turn_id").notNull().references(() => sessionTurns.id, { onDelete: "cascade" }),
2116
- executionGeneration: integer("execution_generation").notNull(),
2117
- attemptId: uuid("attempt_id").notNull(),
2118
- callId: text("call_id").notNull(),
2119
- callType: text("call_type").notNull(),
2120
- callItem: jsonb("call_item").$type().notNull(),
2121
- modelToolOutputTruncationTokens: integer("model_tool_output_truncation_tokens"),
2122
- resultItem: jsonb("result_item").$type(),
2123
- resultRecordedAt: timestamp("result_recorded_at", { withTimezone: true }),
2124
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
2125
- },
2126
- (table) => ({
2127
- workspaceAttempt: foreignKey({
2128
- name: "pending_tool_calls_workspace_attempt_fk",
2129
- columns: [table.workspaceId, table.attemptId],
2130
- foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
2131
- }).onDelete("restrict"),
2132
- turnCall: uniqueIndex("session_pending_tool_calls_turn_call_idx").on(
2133
- table.workspaceId,
2134
- table.turnId,
2135
- table.callId
2136
- ),
2137
- sessionTurn: index("session_pending_tool_calls_session_turn_idx").on(
2138
- table.workspaceId,
2139
- table.sessionId,
2140
- table.turnId
2141
- )
2142
- })
2143
- );
2144
- var sandboxSessionEnvelopes = pgTable(
2145
- "sandbox_session_envelopes",
2146
- {
2147
- id: uuid("id").primaryKey().defaultRandom(),
2148
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2149
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2150
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2151
- envelope: jsonb("envelope").$type().notNull(),
2152
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2153
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2154
- },
2155
- (table) => ({
2156
- sessionIdx: uniqueIndex("sandbox_session_envelopes_session_idx").on(
2157
- table.workspaceId,
2158
- table.sessionId
2159
- )
2160
- })
2161
- );
2162
- var sandboxLeaseLivenessValues = ["cold", "warming", "warm", "draining"];
2163
- var sandboxLeases = pgTable(
2164
- "sandbox_leases",
2165
- {
2166
- id: uuid("id").primaryKey().defaultRandom(),
2167
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2168
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2169
- sandboxGroupId: uuid("sandbox_group_id").notNull(),
2170
- liveness: text("liveness", { enum: sandboxLeaseLivenessValues }).notNull().default("cold"),
2171
- refcount: integer("refcount").notNull().default(0),
2172
- turnHolders: integer("turn_holders").notNull().default(0),
2173
- viewerHolders: integer("viewer_holders").notNull().default(0),
2174
- instanceId: text("instance_id"),
2175
- backend: text("backend").notNull(),
2176
- os: text("os").notNull().default("linux"),
2177
- // The container IMAGE the group box runs (Modal image ref / docker image). A shared
2178
- // box is SHARED STATE: all its sessions run the SAME filesystem, so they must run the
2179
- // same image. This column stamps the image the live box was created with; a resume
2180
- // whose resolved image DIFFERS is a conflict (B3): a solo holder recreates the box on
2181
- // the new image, N-holders are rejected (SandboxImageConflictError). Nullable — a
2182
- // legacy/cold row reads NULL = "image unknown", which never conflicts.
2183
- image: text("image"),
2184
- // The frozen rig version the live box was created under (M3). Like `image`,
2185
- // this is SHARED STATE: all the box's sessions run the same rig-baked setup,
2186
- // so a resume resolving a DIFFERENT rig_version_id conflicts (solo holder
2187
- // recreates cold on the new rig; N-holders throw SandboxRigConflictError).
2188
- // Nullable — a legacy/cold row or a rig-less session reads NULL = "rig
2189
- // unknown", which never conflicts. No FK (symmetric with sandbox_group_id's
2190
- // bare-uuid rationale: this lease outlives no single rig_versions row's RLS).
2191
- rigVersionId: uuid("rig_version_id"),
2192
- dataPlaneUrl: text("data_plane_url"),
2193
- // The REAL PTY terminal (ttyd pty-ws) rides a SEPARATE provider tunnel (7681)
2194
- // from the desktop noVNC (6080), so its resolved URL is cached independently.
2195
- // Recorded under the epoch fence by recordLeaseTerminalDataPlaneUrl; reset to
2196
- // null on every box re-key (warm-commit / fail / drain), symmetric with
2197
- // data_plane_url.
2198
- terminalDataPlaneUrl: text("terminal_data_plane_url"),
2199
- // integer (NOT bigint): the lease-epoch spike proved a raw int8 read returns a
2200
- // JS STRING from postgres-js, breaking the strict epoch-fence comparison (it
2201
- // was always-true → every turn fenced); int4 returns a JS number, the fix.
2202
- // Epochs never approach 2^31, so the narrower type loses nothing.
2203
- leaseEpoch: integer("lease_epoch").notNull().default(0),
2204
- // Monotonic mutation intent for the live workspace. Every acknowledged
2205
- // filesystem-writing operation advances this under the exact lease epoch +
2206
- // provider-instance fence BEFORE it reaches the provider. A verified
2207
- // archive fold copies the exact captured value into archive_generation in
2208
- // the same row update; equality is the only durable completeness proof.
2209
- workspaceGeneration: integer("workspace_generation").notNull().default(0),
2210
- archiveGeneration: integer("archive_generation"),
2211
- // The group box-envelope (the "envelope split" Critical): the small recovery
2212
- // descriptor to resume()-by-id the group's box without a per-session join.
2213
- resumeBackendId: text("resume_backend_id"),
2214
- resumeState: jsonb("resume_state").$type(),
2215
- // Warm-time billing cursor: last_meter_at = accrual cursor; last_meter_tick =
2216
- // idempotency tick (warm_seconds accrued idempotent on
2217
- // (sandbox_group_id, lease_epoch, last_meter_tick) in P2.1).
2218
- lastMeterAt: timestamp("last_meter_at", { withTimezone: true }),
2219
- lastMeterTick: integer("last_meter_tick").notNull().default(0),
2220
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
2221
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2222
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2223
- },
2224
- (table) => ({
2225
- groupIdx: uniqueIndex("sandbox_leases_group_idx").on(table.workspaceId, table.sandboxGroupId),
2226
- scopedId: uniqueIndex("sandbox_leases_scoped_id_uq").on(
2227
- table.accountId,
2228
- table.workspaceId,
2229
- table.sandboxGroupId,
2230
- table.id
2231
- ),
2232
- accountWorkspaceId: uniqueIndex("sandbox_leases_account_workspace_id_uq").on(
2233
- table.accountId,
2234
- table.workspaceId,
2235
- table.id
2236
- ),
2237
- reaperIdx: index("sandbox_leases_reaper_idx").on(table.expiresAt).where(sql`${table.liveness} in ('warming','warm','draining')`),
2238
- expiredDrainingInventory: index("sandbox_leases_expired_draining_inventory_idx").on(table.expiresAt, table.backend).where(sql`${table.liveness} = 'draining'`),
2239
- workspaceGenerationValid: check(
2240
- "sandbox_leases_workspace_generation_check",
2241
- sql`${table.workspaceGeneration} >= 0`
2242
- ),
2243
- archiveGenerationValid: check(
2244
- "sandbox_leases_archive_generation_check",
2245
- sql`${table.archiveGeneration} is null
2246
- or (${table.archiveGeneration} >= 0
2247
- and ${table.archiveGeneration} <= ${table.workspaceGeneration})`
2248
- )
2249
- })
2250
- );
2251
- var sandboxLeaseHolders = pgTable(
2252
- "sandbox_lease_holders",
2253
- {
2254
- id: uuid("id").primaryKey().defaultRandom(),
2255
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2256
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2257
- leaseId: uuid("lease_id").notNull().references(() => sandboxLeases.id, { onDelete: "cascade" }),
2258
- kind: text("kind", { enum: ["turn", "viewer", "direct", "process"] }).notNull(),
2259
- holderId: text("holder_id").notNull(),
2260
- // The attributing session within the (possibly shared) group.
2261
- subjectId: uuid("subject_id"),
2262
- lastHeartbeatAt: timestamp("last_heartbeat_at", { withTimezone: true }).notNull().defaultNow(),
2263
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
2264
- },
2265
- (table) => ({
2266
- leaseScope: foreignKey({
2267
- name: "sandbox_lease_holders_lease_scope_fk",
2268
- columns: [table.accountId, table.workspaceId, table.leaseId],
2269
- foreignColumns: [sandboxLeases.accountId, sandboxLeases.workspaceId, sandboxLeases.id]
2270
- }).onDelete("cascade"),
2271
- holderIdx: uniqueIndex("sandbox_lease_holders_holder_idx").on(
2272
- table.leaseId,
2273
- table.kind,
2274
- table.holderId
2275
- ),
2276
- staleIdx: index("sandbox_lease_holders_stale_idx").on(table.kind, table.lastHeartbeatAt),
2277
- leaseIdx: index("sandbox_lease_holders_lease_idx").on(table.leaseId)
2278
- })
2279
- );
2280
- var sandboxWorkspaceMutationActorKindValues = ["turn", "direct", "process"];
2281
- var sandboxWorkspaceMutationHolderKindValues = ["turn", "direct", "process"];
2282
- var sandboxWorkspaceMutationAdmissions = pgTable(
2283
- "sandbox_workspace_mutation_admissions",
2284
- {
2285
- id: uuid("id").primaryKey().defaultRandom(),
2286
- accountId: uuid("account_id").notNull(),
2287
- workspaceId: uuid("workspace_id").notNull(),
2288
- leaseId: uuid("lease_id").notNull().references(() => sandboxLeases.id, { onDelete: "cascade" }),
2289
- sandboxGroupId: uuid("sandbox_group_id").notNull(),
2290
- sessionId: uuid("session_id").notNull(),
2291
- actorKind: text("actor_kind", { enum: sandboxWorkspaceMutationActorKindValues }).notNull(),
2292
- actorId: uuid("actor_id").notNull(),
2293
- // Exact turn authority is present only for actor_kind='turn'. Direct HTTP
2294
- // requests and retained processes never invent a turn or quiescence owner.
2295
- turnId: uuid("turn_id"),
2296
- attemptId: uuid("attempt_id"),
2297
- executionGeneration: integer("execution_generation"),
2298
- holderKind: text("holder_kind", {
2299
- enum: sandboxWorkspaceMutationHolderKindValues
2300
- }).notNull(),
2301
- holderId: text("holder_id").notNull(),
2302
- leaseEpoch: integer("lease_epoch").notNull(),
2303
- providerBackend: text("provider_backend").notNull(),
2304
- providerInstanceId: text("provider_instance_id").notNull(),
2305
- routeKind: text("route_kind", { enum: ["home", "active"] }).notNull(),
2306
- // null route target means the persistable home/group provider. A non-null
2307
- // target is pinned together with the active pointer epoch observed when the
2308
- // operation was admitted.
2309
- routeTargetId: uuid("route_target_id"),
2310
- routeEpoch: integer("route_epoch").notNull(),
2311
- workspaceGeneration: integer("workspace_generation").notNull(),
2312
- operation: text("operation").notNull(),
2313
- providerOutcome: text("provider_outcome", {
2314
- enum: ["resolved", "rejected", "retained"]
2315
- }),
2316
- admittedAt: timestamp("admitted_at", { withTimezone: true }).notNull().defaultNow(),
2317
- settledAt: timestamp("settled_at", { withTimezone: true })
2318
- },
2319
- (table) => ({
2320
- workspaceAccount: foreignKey({
2321
- name: "sandbox_workspace_mutation_admissions_workspace_account_fk",
2322
- columns: [table.workspaceId, table.accountId],
2323
- foreignColumns: [workspaces.id, workspaces.accountId]
2324
- }).onDelete("cascade"),
2325
- workspaceSession: foreignKey({
2326
- name: "sandbox_workspace_mutation_admissions_workspace_session_fk",
2327
- columns: [table.workspaceId, table.sessionId],
2328
- foreignColumns: [sessions.workspaceId, sessions.id]
2329
- }).onDelete("restrict"),
2330
- workspaceTurn: foreignKey({
2331
- name: "sandbox_workspace_mutation_admissions_workspace_turn_fk",
2332
- columns: [table.workspaceId, table.turnId],
2333
- foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
2334
- }).onDelete("restrict"),
2335
- workspaceAttempt: foreignKey({
2336
- name: "sandbox_workspace_mutation_admissions_workspace_attempt_fk",
2337
- columns: [table.workspaceId, table.attemptId],
2338
- foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
2339
- }).onDelete("restrict"),
2340
- leaseGeneration: uniqueIndex("sandbox_workspace_mutation_admissions_lease_generation_uq").on(
2341
- table.leaseId,
2342
- table.workspaceGeneration
2343
- ),
2344
- scopedId: uniqueIndex("sandbox_workspace_mutation_admissions_scoped_id_uq").on(
2345
- table.accountId,
2346
- table.workspaceId,
2347
- table.sessionId,
2348
- table.leaseId,
2349
- table.id
2350
- ),
2351
- blocking: index("sandbox_workspace_mutation_admissions_blocking_idx").on(table.leaseId, table.workspaceGeneration).where(sql`${table.settledAt} is null`),
2352
- attempt: index("sandbox_workspace_mutation_admissions_attempt_idx").on(
2353
- table.workspaceId,
2354
- table.attemptId
2355
- ),
2356
- actor: index("sandbox_workspace_mutation_admissions_actor_idx").on(
2357
- table.workspaceId,
2358
- table.actorKind,
2359
- table.actorId
2360
- ),
2361
- generationValid: check(
2362
- "sandbox_workspace_mutation_admissions_generation_check",
2363
- sql`${table.workspaceGeneration} > 0
2364
- and ${table.leaseEpoch} >= 0
2365
- and ${table.routeEpoch} >= 0
2366
- and (${table.executionGeneration} is null or ${table.executionGeneration} > 0)`
2367
- ),
2368
- actorValid: check(
2369
- "sandbox_workspace_mutation_admissions_actor_check",
2370
- sql`(
2371
- ${table.actorKind} = 'turn'
2372
- and ${table.actorId} = ${table.attemptId}
2373
- and ${table.turnId} is not null
2374
- and ${table.attemptId} is not null
2375
- and ${table.executionGeneration} is not null
2376
- and ${table.holderKind} = 'turn'
2377
- ) or (
2378
- ${table.actorKind} = 'direct'
2379
- and ${table.turnId} is null
2380
- and ${table.attemptId} is null
2381
- and ${table.executionGeneration} is null
2382
- and ${table.holderKind} = 'direct'
2383
- ) or (
2384
- ${table.actorKind} = 'process'
2385
- and ${table.turnId} is null
2386
- and ${table.attemptId} is null
2387
- and ${table.executionGeneration} is null
2388
- and ${table.holderKind} = 'process'
2389
- )`
2390
- ),
2391
- routeValid: check(
2392
- "sandbox_workspace_mutation_admissions_route_check",
2393
- sql`${table.actorKind} in ('turn', 'direct', 'process')
2394
- and ${table.holderKind} in ('turn', 'direct', 'process')
2395
- and octet_length(${table.holderId}) between 1 and 256
2396
- and octet_length(${table.providerBackend}) between 1 and 64
2397
- and octet_length(${table.providerInstanceId}) between 1 and 512
2398
- and ${table.routeKind} in ('home', 'active')
2399
- and (${table.routeKind} = 'active' or ${table.routeTargetId} is null)`
2400
- ),
2401
- operationValid: check(
2402
- "sandbox_workspace_mutation_admissions_operation_check",
2403
- sql`octet_length(${table.operation}) between 1 and 128`
2404
- ),
2405
- outcomeValid: check(
2406
- "sandbox_workspace_mutation_admissions_outcome_check",
2407
- sql`${table.providerOutcome} is null or ${table.providerOutcome} in ('resolved', 'rejected', 'retained')`
2408
- ),
2409
- settlementConsistent: check(
2410
- "sandbox_workspace_mutation_admissions_settlement_check",
2411
- sql`(${table.providerOutcome} is null and ${table.settledAt} is null)
2412
- or (${table.providerOutcome} = 'retained' and ${table.settledAt} is null)
2413
- or (${table.providerOutcome} in ('resolved', 'rejected') and ${table.settledAt} is not null)`
2414
- )
2415
- })
2416
- );
2417
- var sandboxRetainedProcessStateValues = ["active", "exited", "lost"];
2418
- var sandboxRetainedProcesses = pgTable(
2419
- "sandbox_retained_processes",
2420
- {
2421
- id: uuid("id").primaryKey().defaultRandom(),
2422
- accountId: uuid("account_id").notNull(),
2423
- workspaceId: uuid("workspace_id").notNull(),
2424
- sessionId: uuid("session_id").notNull(),
2425
- leaseId: uuid("lease_id").notNull(),
2426
- sandboxGroupId: uuid("sandbox_group_id").notNull(),
2427
- parentAdmissionId: uuid("parent_admission_id").notNull(),
2428
- holderId: text("holder_id").notNull(),
2429
- ownerActorKind: text("owner_actor_kind", { enum: ["turn", "direct"] }).notNull(),
2430
- ownerActorId: uuid("owner_actor_id").notNull(),
2431
- ownerTurnId: uuid("owner_turn_id"),
2432
- ownerAttemptId: uuid("owner_attempt_id"),
2433
- ownerExecutionGeneration: integer("owner_execution_generation"),
2434
- leaseEpoch: integer("lease_epoch").notNull(),
2435
- providerBackend: text("provider_backend").notNull(),
2436
- providerInstanceId: text("provider_instance_id").notNull(),
2437
- routeKind: text("route_kind", { enum: ["home", "active"] }).notNull(),
2438
- routeTargetId: uuid("route_target_id"),
2439
- routeEpoch: integer("route_epoch").notNull(),
2440
- providerSessionId: integer("provider_session_id").notNull(),
2441
- state: text("state", { enum: sandboxRetainedProcessStateValues }).notNull().default("active"),
2442
- exitCode: integer("exit_code"),
2443
- settlementReason: text("settlement_reason"),
2444
- startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(),
2445
- settledAt: timestamp("settled_at", { withTimezone: true }),
2446
- // Coordination state for bounded terminal-owner reconciliation. While a
2447
- // claim is live, reconcileAfter is its expiry; otherwise it is the next
2448
- // retry time. Becoming due only licenses an exact provider probe and is
2449
- // never exit/loss proof.
2450
- reconcileAfter: timestamp("reconcile_after", { withTimezone: true }).notNull().defaultNow(),
2451
- reconcileClaimId: uuid("reconcile_claim_id"),
2452
- reconcileClaimedAt: timestamp("reconcile_claimed_at", { withTimezone: true }),
2453
- reconcileAttempts: integer("reconcile_attempts").notNull().default(0),
2454
- lastReconcileOutcome: text("last_reconcile_outcome"),
2455
- reconcileProofOutcome: text("reconcile_proof_outcome", { enum: ["exited", "lost"] }),
2456
- reconcileProofExitCode: integer("reconcile_proof_exit_code"),
2457
- reconcileProofReason: text("reconcile_proof_reason"),
2458
- reconcileProofObservedAt: timestamp("reconcile_proof_observed_at", { withTimezone: true })
2459
- },
2460
- (table) => ({
2461
- workspaceAccount: foreignKey({
2462
- name: "sandbox_retained_processes_workspace_account_fk",
2463
- columns: [table.workspaceId, table.accountId],
2464
- foreignColumns: [workspaces.id, workspaces.accountId]
2465
- }).onDelete("cascade"),
2466
- workspaceSession: foreignKey({
2467
- name: "sandbox_retained_processes_workspace_session_fk",
2468
- columns: [table.workspaceId, table.sessionId],
2469
- foreignColumns: [sessions.workspaceId, sessions.id]
2470
- }).onDelete("restrict"),
2471
- parentAdmissionScope: foreignKey({
2472
- name: "sandbox_retained_processes_parent_admission_scope_fk",
2473
- columns: [
2474
- table.accountId,
2475
- table.workspaceId,
2476
- table.sessionId,
2477
- table.leaseId,
2478
- table.parentAdmissionId
2479
- ],
2480
- foreignColumns: [
2481
- sandboxWorkspaceMutationAdmissions.accountId,
2482
- sandboxWorkspaceMutationAdmissions.workspaceId,
2483
- sandboxWorkspaceMutationAdmissions.sessionId,
2484
- sandboxWorkspaceMutationAdmissions.leaseId,
2485
- sandboxWorkspaceMutationAdmissions.id
2486
- ]
2487
- }).onDelete("restrict"),
2488
- scopedId: uniqueIndex("sandbox_retained_processes_scoped_id_uq").on(
2489
- table.accountId,
2490
- table.workspaceId,
2491
- table.sessionId,
2492
- table.leaseId,
2493
- table.id
2494
- ),
2495
- parentAdmission: uniqueIndex("sandbox_retained_processes_parent_admission_uq").on(
2496
- table.parentAdmissionId
2497
- ),
2498
- liveProviderSession: uniqueIndex("sandbox_retained_processes_live_provider_session_uq").on(
2499
- table.leaseId,
2500
- table.leaseEpoch,
2501
- table.providerInstanceId,
2502
- table.routeEpoch,
2503
- table.providerSessionId
2504
- ).where(sql`${table.state} = 'active'`),
2505
- holder: uniqueIndex("sandbox_retained_processes_holder_uq").on(table.leaseId, table.holderId),
2506
- active: index("sandbox_retained_processes_active_idx").on(table.workspaceId, table.sessionId, table.startedAt).where(sql`${table.state} = 'active'`),
2507
- reconcileDue: index("sandbox_retained_processes_reconcile_due_idx").on(table.reconcileAfter, table.startedAt, table.id).where(sql`${table.state} = 'active'`),
2508
- activeInventory: index("sandbox_retained_processes_active_inventory_idx").on(table.ownerActorKind, table.workspaceId, table.ownerTurnId, table.ownerAttemptId).where(sql`${table.state} = 'active'`),
2509
- identityValid: check(
2510
- "sandbox_retained_processes_identity_check",
2511
- sql`${table.leaseEpoch} >= 0
2512
- and ${table.routeEpoch} >= 0
2513
- and ${table.providerSessionId} > 0
2514
- and octet_length(${table.holderId}) between 1 and 256
2515
- and octet_length(${table.providerBackend}) between 1 and 64
2516
- and octet_length(${table.providerInstanceId}) between 1 and 512
2517
- and (${table.routeKind} = 'active' or ${table.routeTargetId} is null)`
2518
- ),
2519
- ownerValid: check(
2520
- "sandbox_retained_processes_owner_check",
2521
- sql`(
2522
- ${table.ownerActorKind} = 'turn'
2523
- and ${table.ownerActorId} = ${table.ownerAttemptId}
2524
- and ${table.ownerTurnId} is not null
2525
- and ${table.ownerAttemptId} is not null
2526
- and ${table.ownerExecutionGeneration} > 0
2527
- ) or (
2528
- ${table.ownerActorKind} = 'direct'
2529
- and ${table.ownerTurnId} is null
2530
- and ${table.ownerAttemptId} is null
2531
- and ${table.ownerExecutionGeneration} is null
2532
- )`
2533
- ),
2534
- settlementValid: check(
2535
- "sandbox_retained_processes_settlement_check",
2536
- sql`(${table.state} = 'active' and ${table.settledAt} is null and ${table.exitCode} is null)
2537
- or (${table.state} = 'exited' and ${table.settledAt} is not null)
2538
- or (${table.state} = 'lost' and ${table.settledAt} is not null and ${table.exitCode} is null)`
2539
- ),
2540
- reasonValid: check(
2541
- "sandbox_retained_processes_reason_check",
2542
- sql`${table.settlementReason} is null
2543
- or octet_length(${table.settlementReason}) between 1 and 512`
2544
- ),
2545
- reconcileClaimValid: check(
2546
- "sandbox_retained_processes_reconcile_claim_check",
2547
- sql`(${table.reconcileClaimId} is null and ${table.reconcileClaimedAt} is null)
2548
- or (${table.reconcileClaimId} is not null and ${table.reconcileClaimedAt} is not null)`
2549
- ),
2550
- reconcileAttemptsValid: check(
2551
- "sandbox_retained_processes_reconcile_attempts_check",
2552
- sql`${table.reconcileAttempts} >= 0`
2553
- ),
2554
- reconcileOutcomeValid: check(
2555
- "sandbox_retained_processes_reconcile_outcome_check",
2556
- sql`${table.lastReconcileOutcome} is null
2557
- or octet_length(${table.lastReconcileOutcome}) between 1 and 64`
2558
- ),
2559
- reconcileProofValid: check(
2560
- "sandbox_retained_processes_reconcile_proof_check",
2561
- sql`(
2562
- ${table.reconcileProofOutcome} is null
2563
- and ${table.reconcileProofExitCode} is null
2564
- and ${table.reconcileProofReason} is null
2565
- and ${table.reconcileProofObservedAt} is null
2566
- ) or (
2567
- ${table.reconcileProofOutcome} = 'exited'
2568
- and ${table.reconcileProofExitCode} is not null
2569
- and ${table.reconcileProofReason} = 'provider_exit_banner'
2570
- and ${table.reconcileProofObservedAt} is not null
2571
- ) or (
2572
- ${table.reconcileProofOutcome} = 'lost'
2573
- and ${table.reconcileProofExitCode} is null
2574
- and ${table.reconcileProofReason} in (
2575
- 'provider_session_lost_banner', 'provider_instance_not_found'
2576
- )
2577
- and ${table.reconcileProofObservedAt} is not null
2578
- )`
2579
- )
2580
- })
2581
- );
2582
- var sessionRecordingStateValues = [
2583
- "recording",
2584
- "finalizing",
2585
- "available",
2586
- "failed"
2587
- ];
2588
- var sessionRecordingModeValues = ["manual", "on-turn", "on-verify"];
2589
- var sessionRecordingCodecValues = ["h264-mp4", "vp9-webm"];
2590
- var sessionRecordings = pgTable(
2591
- "session_recordings",
2592
- {
2593
- id: uuid("id").primaryKey().defaultRandom(),
2594
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2595
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2596
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2597
- turnId: uuid("turn_id").references(() => sessionTurns.id, {
2598
- onDelete: "set null"
2599
- }),
2600
- state: text("state", { enum: sessionRecordingStateValues }).notNull(),
2601
- mode: text("mode", { enum: sessionRecordingModeValues }).notNull(),
2602
- codec: text("codec", { enum: sessionRecordingCodecValues }).notNull(),
2603
- storageKey: text("storage_key"),
2604
- sizeBytes: bigint("size_bytes", { mode: "number" }),
2605
- durationSeconds: numeric("duration_seconds").$type(),
2606
- width: integer("width").notNull(),
2607
- height: integer("height").notNull(),
2608
- reason: text("reason"),
2609
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2610
- finalizedAt: timestamp("finalized_at", { withTimezone: true })
2611
- },
2612
- (table) => ({
2613
- sessionIdx: index("session_recordings_session_idx").on(
2614
- table.workspaceId,
2615
- table.sessionId,
2616
- table.createdAt
2617
- )
2618
- })
2619
- );
2620
- var workspaceCaptures = pgTable(
2621
- "workspace_captures",
2622
- {
2623
- id: uuid("id").primaryKey().defaultRandom(),
2624
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2625
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2626
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2627
- turnId: uuid("turn_id").references(() => sessionTurns.id, {
2628
- onDelete: "set null"
2629
- }),
2630
- revision: bigint("revision", { mode: "number" }).notNull(),
2631
- leaseEpoch: integer("lease_epoch").notNull(),
2632
- // 'available' on a committed capture. 'failed' reserved for a future two-phase
2633
- // write; the current synchronous capture only ever inserts 'available'.
2634
- state: text("state", { enum: ["available", "failed"] }).notNull().default("available"),
2635
- // Single JSON manifest blob (tree index + repos + file refs) — the cold-paint payload.
2636
- manifestKey: text("manifest_key"),
2637
- // The fs tree index blob, kept separate from the manifest so the API can inline
2638
- // or sign it independently of the (usually small) manifest metadata.
2639
- treeIndexKey: text("tree_index_key"),
2640
- // Content-addressed after-image blob keys this revision references (GC input).
2641
- blobKeys: jsonb("blob_keys").$type().notNull().default([]),
2642
- sizeBytes: bigint("size_bytes", { mode: "number" }),
2643
- stats: jsonb("stats").$type().notNull().default({}),
2644
- capturedAt: timestamp("captured_at", { withTimezone: true }).notNull().defaultNow()
2645
- },
2646
- (table) => ({
2647
- sessionRevision: uniqueIndex("workspace_captures_session_revision_idx").on(
2648
- table.sessionId,
2649
- table.revision
2650
- ),
2651
- latest: index("workspace_captures_latest_idx").on(
2652
- table.workspaceId,
2653
- table.sessionId,
2654
- table.revision
2655
- )
2656
- })
2657
- );
2658
- var sandboxPtySessions = pgTable(
2659
- "sandbox_pty_sessions",
2660
- {
2661
- id: uuid("id").primaryKey().defaultRandom(),
2662
- // == ptyId on the wire
2663
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2664
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2665
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2666
- leaseId: uuid("lease_id"),
2667
- sandboxGroupId: uuid("sandbox_group_id"),
2668
- retainedProcessId: uuid("retained_process_id"),
2669
- openAdmissionId: uuid("open_admission_id"),
2670
- // Copied provider locator for the adopted retained process.
2671
- execSessionId: integer("exec_session_id"),
2672
- leaseEpoch: integer("lease_epoch").notNull(),
2673
- providerBackend: text("provider_backend"),
2674
- providerInstanceId: text("provider_instance_id"),
2675
- routeKind: text("route_kind", { enum: ["home", "active"] }),
2676
- routeTargetId: uuid("route_target_id"),
2677
- routeEpoch: integer("route_epoch"),
2678
- cols: integer("cols").notNull(),
2679
- rows: integer("rows").notNull(),
2680
- shell: text("shell").notNull(),
2681
- cwd: text("cwd").notNull(),
2682
- status: text("status").notNull().default("open"),
2683
- // 'open' | 'closed'
2684
- // The viewer grant/subject that opened it (free-text — access subjects are not
2685
- // always UUIDs, M5; so a text column, never a uuid NOT NULL).
2686
- openedBy: text("opened_by").notNull(),
2687
- lastInputAt: timestamp("last_input_at", { withTimezone: true }).notNull().defaultNow(),
2688
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2689
- closedAt: timestamp("closed_at", { withTimezone: true })
2690
- },
2691
- (table) => ({
2692
- retainedProcessScope: foreignKey({
2693
- name: "sandbox_pty_sessions_retained_process_scope_fk",
2694
- columns: [
2695
- table.accountId,
2696
- table.workspaceId,
2697
- table.sessionId,
2698
- table.leaseId,
2699
- table.retainedProcessId
2700
- ],
2701
- foreignColumns: [
2702
- sandboxRetainedProcesses.accountId,
2703
- sandboxRetainedProcesses.workspaceId,
2704
- sandboxRetainedProcesses.sessionId,
2705
- sandboxRetainedProcesses.leaseId,
2706
- sandboxRetainedProcesses.id
2707
- ]
2708
- }).onDelete("restrict"),
2709
- openIdx: index("sandbox_pty_sessions_session_idx").on(table.workspaceId, table.sessionId).where(sql`${table.status} = 'open'`),
2710
- processIdx: uniqueIndex("sandbox_pty_sessions_open_process_uq").on(table.retainedProcessId).where(sql`${table.status} = 'open'`),
2711
- openIdentityValid: check(
2712
- "sandbox_pty_sessions_open_identity_check",
2713
- sql`${table.status} <> 'open' or (
2714
- ${table.leaseId} is not null
2715
- and ${table.sandboxGroupId} is not null
2716
- and ${table.retainedProcessId} is not null
2717
- and ${table.openAdmissionId} is not null
2718
- and ${table.execSessionId} > 0
2719
- and octet_length(${table.providerBackend}) between 1 and 64
2720
- and octet_length(${table.providerInstanceId}) between 1 and 512
2721
- and ${table.routeKind} in ('home', 'active')
2722
- and (${table.routeKind} = 'active' or ${table.routeTargetId} is null)
2723
- and ${table.routeEpoch} is not null
2724
- and ${table.leaseEpoch} >= 0
2725
- and ${table.routeEpoch} >= 0
2726
- )`
2727
- )
2728
- })
2729
- );
2730
- var enrollmentExposureValues = ["whole-machine"];
2731
- var enrollmentStatusValues = ["active", "revoked"];
2732
- var enrollmentOsValues = ["linux", "macos", "windows"];
2733
- var sandboxKindValues = ["modal", "selfhosted"];
2734
- var enrollments = pgTable(
2735
- "enrollments",
2736
- {
2737
- id: uuid("id").primaryKey().defaultRandom(),
2738
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2739
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2740
- // The agent's ed25519 public key (the machine identity).
2741
- pubkey: text("pubkey").notNull(),
2742
- exposure: text("exposure", { enum: enrollmentExposureValues }).notNull().default("whole-machine"),
2743
- hasDisplay: boolean("has_display").notNull().default(false),
2744
- // Refreshed from every connect Hello (Capabilities.op_stream); false for
2745
- // agents predating the op-stream engine.
2746
- opStream: boolean("op_stream").notNull().default(false),
2747
- // When the machine has a display it CANNOT capture (macOS Screen Recording / TCC
2748
- // not granted), the agent reports has_display=false AND a human, actionable reason
2749
- // here (e.g. "grant Screen Recording in System Settings"). NULL means capture is
2750
- // permitted (has_display=true) or the machine is genuinely headless — the reason
2751
- // distinguishes "display present but capture not granted" from plain "no display"
2752
- // so the Machines dashboard / VM picker can surface the specific hint. Refreshed
2753
- // from every connect Hello alongside has_display.
2754
- desktopUnavailableReason: text("desktop_unavailable_reason"),
2755
- allowScreenControl: boolean("allow_screen_control").notNull().default(false),
2756
- status: text("status", { enum: enrollmentStatusValues }).notNull().default("active"),
2757
- os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"),
2758
- arch: text("arch").notNull().default("x86_64"),
2759
- // Heartbeat liveness cursor. Null until the first connect.
2760
- lastSeenAt: timestamp("last_seen_at", { withTimezone: true }),
2761
- // Clean going-offline marker (migration 0049). Set when the machine announces a
2762
- // typed GoingOffline (user-stop / self-update / host-shutdown); the liveness
2763
- // derivation reads an un-cleared marker as OFFLINE immediately, regardless of a
2764
- // still-fresh last_seen. Any newer liveness signal (a reconnect Hello or a
2765
- // fresher heartbeat via touchEnrollmentLastSeen) clears BOTH back to NULL. NULL
2766
- // (the default) ⇒ no goodbye pending — today's last_seen-aging behavior.
2767
- wentOfflineAt: timestamp("went_offline_at", { withTimezone: true }),
2768
- wentOfflineReason: text("went_offline_reason"),
2769
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2770
- revokedAt: timestamp("revoked_at", { withTimezone: true }),
2771
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2772
- },
2773
- (table) => ({
2774
- // One enrollment per (workspace, pubkey): a re-enroll is an idempotent upsert.
2775
- workspacePubkey: uniqueIndex("enrollments_workspace_pubkey_idx").on(
2776
- table.workspaceId,
2777
- table.pubkey
2778
- ),
2779
- // List a workspace's ACTIVE machines without scanning revoked rows.
2780
- workspaceStatus: index("enrollments_workspace_status_idx").on(table.workspaceId, table.status)
2781
- })
2782
- );
2783
- var deviceEnrollmentStatusValues = ["pending", "approved", "denied", "consumed"];
2784
- var deviceEnrollmentRequests = pgTable(
2785
- "device_enrollment_requests",
2786
- {
2787
- id: uuid("id").primaryKey().defaultRandom(),
2788
- // The opaque code the agent polls with (unguessable, single-use). Unique.
2789
- deviceCode: text("device_code").notNull(),
2790
- // The short human-typed code (e.g. "WDJB-MJHT"). Unique among LIVE (pending)
2791
- // rows via a partial unique index so a recycled code never collides with a
2792
- // terminal row.
2793
- userCode: text("user_code").notNull(),
2794
- // The workspace this request was started for (resolved from the deployment-edge
2795
- // request context — the agent presents the access key, the flow binds to the
2796
- // single managed workspace OR a workspace hint). account_id rides along for RLS.
2797
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2798
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2799
- // The agent's ed25519 public key (the machine identity the enrollment binds to).
2800
- pubkey: text("pubkey").notNull(),
2801
- os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"),
2802
- arch: text("arch").notNull().default("x86_64"),
2803
- machineName: text("machine_name"),
2804
- // The exposure the agent REQUESTED (whole-machine in v1; loudly consented at
2805
- // approve). Mirrors the enrollment column domain.
2806
- requestedExposure: text("requested_exposure", {
2807
- enum: enrollmentExposureValues
2808
- }).notNull().default("whole-machine"),
2809
- // The agent CAN offer a display (a real screen / Xvfb is available) — gates
2810
- // whether screen-control consent is even meaningful. has_display on the
2811
- // resulting enrollment is derived from this.
2812
- canOfferDisplay: boolean("can_offer_display").notNull().default(false),
2813
- // The agent REQUESTS screen control (computer-use). The user's allow_screen_control
2814
- // at approve is the AUTHORITATIVE consent; this is only the agent's request.
2815
- requestsScreenControl: boolean("requests_screen_control").notNull().default(false),
2816
- status: text("status", { enum: deviceEnrollmentStatusValues }).notNull().default("pending"),
2817
- // ── LOUD CONSENT capture (who/when/what), stamped at approve ──────────────
2818
- approvedBySubjectId: text("approved_by_subject_id"),
2819
- approvedBySubjectLabel: text("approved_by_subject_label"),
2820
- // The user's screen-control consent decision (whole-machine is mandatory at
2821
- // approve; screen-control is opt-in per this flag).
2822
- allowScreenControl: boolean("allow_screen_control").notNull().default(false),
2823
- approvedAt: timestamp("approved_at", { withTimezone: true }),
2824
- // The enrollment + sandbox the approve produced (acceptance #2: an enrollment
2825
- // row AND a sandbox row appear). Null until approved.
2826
- enrollmentId: uuid("enrollment_id").references(() => enrollments.id, {
2827
- onDelete: "set null"
2828
- }),
2829
- sandboxId: uuid("sandbox_id").references(() => sandboxes.id, {
2830
- onDelete: "set null"
2831
- }),
2832
- // The short-TTL expiry; a pending row past this is EXPIRED on poll.
2833
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
2834
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2835
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2836
- },
2837
- (table) => ({
2838
- // The device_code is the agent's poll key — globally unique + indexed.
2839
- deviceCode: uniqueIndex("device_enrollment_requests_device_code_idx").on(table.deviceCode),
2840
- // The user_code must be unique among LIVE (pending) rows so the approve lookup
2841
- // is unambiguous; a terminal row's code may be recycled.
2842
- userCodePending: uniqueIndex("device_enrollment_requests_user_code_pending_idx").on(table.userCode).where(sql`${table.status} = 'pending'`),
2843
- workspaceCreated: index("device_enrollment_requests_workspace_created_idx").on(
2844
- table.workspaceId,
2845
- table.createdAt
2846
- ),
2847
- expires: index("device_enrollment_requests_expires_idx").on(table.expiresAt)
2848
- })
2849
- );
2850
- var sandboxes = pgTable(
2851
- "sandboxes",
2852
- {
2853
- id: uuid("id").primaryKey().defaultRandom(),
2854
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2855
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2856
- kind: text("kind", { enum: sandboxKindValues }).notNull(),
2857
- name: text("name").notNull(),
2858
- enrollmentId: uuid("enrollment_id").references(() => enrollments.id, {
2859
- onDelete: "set null"
2860
- }),
2861
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2862
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2863
- },
2864
- (table) => ({
2865
- workspaceCreated: index("sandboxes_workspace_created_idx").on(
2866
- table.workspaceId,
2867
- table.createdAt
2868
- ),
2869
- enrollment: index("sandboxes_enrollment_idx").on(table.enrollmentId).where(sql`${table.enrollmentId} is not null`)
2870
- })
2871
- );
2872
- var machineMetricsLatest = pgTable(
2873
- "machine_metrics_latest",
2874
- {
2875
- enrollmentId: uuid("enrollment_id").primaryKey().references(() => enrollments.id, { onDelete: "cascade" }),
2876
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2877
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2878
- cpuPercent: numeric("cpu_percent").$type(),
2879
- load1: numeric("load1").$type(),
2880
- load5: numeric("load5").$type(),
2881
- load15: numeric("load15").$type(),
2882
- memUsedBytes: bigint("mem_used_bytes", { mode: "number" }),
2883
- memTotalBytes: bigint("mem_total_bytes", { mode: "number" }),
2884
- diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }),
2885
- diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }),
2886
- gpuUtilPercent: numeric("gpu_util_percent").$type(),
2887
- gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }),
2888
- gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }),
2889
- contention: numeric("contention").$type(),
2890
- sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(),
2891
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2892
- },
2893
- (table) => ({
2894
- workspace: index("machine_metrics_latest_workspace_idx").on(table.workspaceId)
2895
- })
2896
- );
2897
- var machineMetricsSeries = pgTable(
2898
- "machine_metrics_series",
2899
- {
2900
- id: uuid("id").primaryKey().defaultRandom(),
2901
- enrollmentId: uuid("enrollment_id").notNull().references(() => enrollments.id, { onDelete: "cascade" }),
2902
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2903
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2904
- cpuPercent: numeric("cpu_percent").$type(),
2905
- load1: numeric("load1").$type(),
2906
- load5: numeric("load5").$type(),
2907
- load15: numeric("load15").$type(),
2908
- memUsedBytes: bigint("mem_used_bytes", { mode: "number" }),
2909
- memTotalBytes: bigint("mem_total_bytes", { mode: "number" }),
2910
- diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }),
2911
- diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }),
2912
- gpuUtilPercent: numeric("gpu_util_percent").$type(),
2913
- gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }),
2914
- gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }),
2915
- contention: numeric("contention").$type(),
2916
- sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(),
2917
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
2918
- },
2919
- (table) => ({
2920
- enrollmentSampled: index("machine_metrics_series_enrollment_sampled_idx").on(
2921
- table.enrollmentId,
2922
- table.sampledAt
2923
- ),
2924
- sampled: index("machine_metrics_series_sampled_idx").on(table.sampledAt)
2925
- })
2926
- );
2927
- var scheduledTasks = pgTable(
2928
- "scheduled_tasks",
2929
- {
2930
- id: uuid("id").primaryKey().defaultRandom(),
2931
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2932
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2933
- name: text("name").notNull(),
2934
- status: text("status").notNull().default("active"),
2935
- schedule: jsonb("schedule").$type().notNull(),
2936
- temporalScheduleId: text("temporal_schedule_id").notNull(),
2937
- runMode: text("run_mode").notNull().default("new_session_per_run"),
2938
- overlapPolicy: text("overlap_policy").notNull().default("allow_concurrent"),
2939
- agentConfig: jsonb("agent_config").$type().notNull(),
2940
- reusableSessionId: uuid("reusable_session_id").references(() => sessions.id, {
2941
- onDelete: "set null"
2942
- }),
2943
- variableSetId: uuid("variable_set_id").references(() => workspaceVariableSets.id, {
2944
- onDelete: "restrict"
2945
- }),
2946
- // The rig this task's runs ride; the active version is resolved per fire
2947
- // (migration 0047). NULL ⇒ no rig. FK (-> rigs(id) ON DELETE SET NULL) lives
2948
- // in migration 0047 (forward-reference pattern). Consumed in M3.
2949
- rigId: uuid("rig_id"),
2950
- metadata: jsonb("metadata").$type().notNull().default({}),
2951
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2952
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2953
- },
2954
- (table) => ({
2955
- temporalScheduleId: uniqueIndex("scheduled_tasks_workspace_temporal_schedule_id_idx").on(
2956
- table.workspaceId,
2957
- table.temporalScheduleId
2958
- ),
2959
- status: index("scheduled_tasks_workspace_status_idx").on(table.workspaceId, table.status),
2960
- variableSet: index("scheduled_tasks_variable_set_idx").on(
2961
- table.workspaceId,
2962
- table.variableSetId
2963
- )
2964
- })
2965
- );
2966
- var scheduledTaskRuns = pgTable(
2967
- "scheduled_task_runs",
2968
- {
2969
- id: uuid("id").primaryKey().defaultRandom(),
2970
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2971
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2972
- taskId: uuid("task_id").notNull().references(() => scheduledTasks.id, { onDelete: "cascade" }),
2973
- status: text("status").notNull().default("queued"),
2974
- triggerType: text("trigger_type").notNull(),
2975
- scheduledAt: timestamp("scheduled_at", { withTimezone: true }),
2976
- firedAt: timestamp("fired_at", { withTimezone: true }).notNull().defaultNow(),
2977
- sessionId: uuid("session_id").references(() => sessions.id, {
2978
- onDelete: "set null"
2979
- }),
2980
- triggerEventId: uuid("trigger_event_id"),
2981
- // Stable Temporal producer identity. Activity replay/re-dispatch returns
2982
- // the exact run instead of allocating a second schedule source row.
2983
- producerKey: text("producer_key"),
2984
- error: text("error"),
2985
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2986
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2987
- },
2988
- (table) => ({
2989
- taskCreated: index("scheduled_task_runs_workspace_task_created_idx").on(
2990
- table.workspaceId,
2991
- table.taskId,
2992
- table.createdAt
2993
- ),
2994
- session: index("scheduled_task_runs_workspace_session_idx").on(
2995
- table.workspaceId,
2996
- table.sessionId
2997
- ),
2998
- producer: uniqueIndex("scheduled_task_runs_producer_key_uq").on(table.workspaceId, table.producerKey).where(sql`${table.producerKey} is not null`)
2999
- })
3000
- );
3001
- var githubInstallations = pgTable(
3002
- "github_installations",
3003
- {
3004
- id: uuid("id").primaryKey().defaultRandom(),
3005
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3006
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3007
- installationId: integer("installation_id").notNull(),
3008
- githubAccountId: bigint("github_account_id", { mode: "number" }),
3009
- accountLogin: text("account_login"),
3010
- accountType: text("account_type"),
3011
- repositoryScope: text("repository_scope").notNull().default("all"),
3012
- linkedBySubjectId: text("linked_by_subject_id"),
3013
- githubActorId: bigint("github_actor_id", { mode: "number" }),
3014
- githubActorLogin: text("github_actor_login"),
3015
- authorityKind: text("authority_kind"),
3016
- authorityCheckedAt: timestamp("authority_checked_at", { withTimezone: true }),
3017
- authorityExpiresAt: timestamp("authority_expires_at", { withTimezone: true }),
3018
- authorityNonce: text("authority_nonce"),
3019
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3020
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3021
- },
3022
- (table) => ({
3023
- workspaceInstallation: uniqueIndex("github_installations_workspace_installation_idx").on(
3024
- table.workspaceId,
3025
- table.installationId
3026
- ),
3027
- installation: index("github_installations_installation_idx").on(table.installationId),
3028
- workspace: index("github_installations_workspace_idx").on(table.workspaceId),
3029
- repositoryScopeCheck: check(
3030
- "github_installations_repository_scope_check",
3031
- sql`${table.repositoryScope} in ('all', 'selected')`
3032
- ),
3033
- authorityKindCheck: check(
3034
- "github_installations_authority_kind_check",
3035
- sql`
3036
- (
3037
- ${table.githubAccountId} is null
3038
- and ${table.githubActorId} is null
3039
- and ${table.githubActorLogin} is null
3040
- and ${table.authorityKind} is null
3041
- and ${table.authorityCheckedAt} is null
3042
- and ${table.authorityExpiresAt} is null
3043
- and ${table.authorityNonce} is null
3044
- )
3045
- or (
3046
- ${table.githubAccountId} is not null
3047
- and ${table.githubAccountId} > 0
3048
- and ${table.githubActorId} is not null
3049
- and ${table.githubActorId} > 0
3050
- and ${table.githubActorLogin} is not null
3051
- and length(${table.githubActorLogin}) > 0
3052
- and ${table.accountLogin} is not null
3053
- and length(${table.accountLogin}) > 0
3054
- and ${table.accountType} is not null
3055
- and ${table.linkedBySubjectId} is not null
3056
- and length(${table.linkedBySubjectId}) > 0
3057
- and ${table.authorityKind} is not null
3058
- and ${table.authorityCheckedAt} is not null
3059
- and ${table.authorityExpiresAt} is not null
3060
- and ${table.authorityCheckedAt} < ${table.authorityExpiresAt}
3061
- and ${table.authorityExpiresAt} <= ${table.authorityCheckedAt} + interval '10 minutes'
3062
- and ${table.authorityNonce} is not null
3063
- and length(${table.authorityNonce}) > 0
3064
- and ${table.repositoryScope} = 'selected'
3065
- and (
3066
- (
3067
- ${table.authorityKind} = 'personal_owner'
3068
- and ${table.accountType} = 'User'
3069
- and ${table.githubActorId} = ${table.githubAccountId}
3070
- )
3071
- or (
3072
- ${table.authorityKind} = 'organization_owner'
3073
- and ${table.accountType} = 'Organization'
3074
- )
3075
- )
3076
- )
3077
- `
3078
- ),
3079
- authorityNonce: uniqueIndex("github_installations_authority_nonce_uq").on(table.authorityNonce).where(sql`${table.authorityNonce} is not null`)
3080
- })
3081
- );
3082
- var githubInstallationRepositories = pgTable(
3083
- "github_installation_repositories",
3084
- {
3085
- id: uuid("id").primaryKey().defaultRandom(),
3086
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3087
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3088
- installationId: integer("installation_id").notNull(),
3089
- repositoryId: bigint("repository_id", { mode: "number" }).notNull(),
3090
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
3091
- },
3092
- (table) => ({
3093
- installationRepository: uniqueIndex("github_install_repo_workspace_installation_repo_idx").on(
3094
- table.workspaceId,
3095
- table.installationId,
3096
- table.repositoryId
3097
- ),
3098
- workspaceInstallation: index("github_install_repo_workspace_installation_idx").on(
3099
- table.workspaceId,
3100
- table.installationId
3101
- ),
3102
- workspaceAccount: foreignKey({
3103
- columns: [table.workspaceId, table.accountId],
3104
- foreignColumns: [workspaces.id, workspaces.accountId],
3105
- name: "github_installation_repositories_workspace_account_fk"
3106
- }).onDelete("cascade"),
3107
- installationBinding: foreignKey({
3108
- columns: [table.workspaceId, table.installationId],
3109
- foreignColumns: [githubInstallations.workspaceId, githubInstallations.installationId],
3110
- name: "github_installation_repositories_installation_fk"
3111
- }).onDelete("cascade")
3112
- })
3113
- );
3114
- var usageEvents = pgTable(
3115
- "usage_events",
3116
- {
3117
- id: uuid("id").primaryKey().defaultRandom(),
3118
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3119
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3120
- subjectId: text("subject_id"),
3121
- eventType: text("event_type").notNull(),
3122
- quantity: bigint("quantity", { mode: "number" }).notNull(),
3123
- unit: text("unit").notNull(),
3124
- sourceResourceType: text("source_resource_type"),
3125
- sourceResourceId: text("source_resource_id"),
3126
- // Exact execution source for host usage export. These are deliberately
3127
- // validated soft references rather than cascading foreign keys: usage is
3128
- // an immutable billing/audit fact and must retain its source identity after
3129
- // a session or turn is deleted.
3130
- sessionId: uuid("session_id"),
3131
- turnId: uuid("turn_id"),
3132
- turnAttemptId: uuid("turn_attempt_id"),
3133
- initiatorKind: text("initiator_kind"),
3134
- initiatorSubjectId: text("initiator_subject_id"),
3135
- initiatorContext: jsonb("initiator_context").$type().notNull().default({}),
3136
- origin: text("origin"),
3137
- idempotencyKey: text("idempotency_key").notNull(),
3138
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),
3139
- recordedAt: timestamp("recorded_at", { withTimezone: true }).notNull().defaultNow(),
3140
- exportedToBillingAt: timestamp("exported_to_billing_at", {
3141
- withTimezone: true
3142
- }),
3143
- billingProviderEventId: text("billing_provider_event_id")
3144
- },
3145
- (table) => ({
3146
- idempotency: uniqueIndex("usage_events_idempotency_idx").on(table.idempotencyKey),
3147
- workspaceMetric: index("usage_events_workspace_metric_idx").on(
3148
- table.workspaceId,
3149
- table.eventType,
3150
- table.occurredAt
3151
- ),
3152
- accountMetric: index("usage_events_account_metric_idx").on(
3153
- table.accountId,
3154
- table.eventType,
3155
- table.occurredAt
3156
- ),
3157
- workspaceSession: index("usage_events_workspace_session_idx").on(
3158
- table.workspaceId,
3159
- table.sessionId,
3160
- table.occurredAt
3161
- ),
3162
- contextHierarchy: check(
3163
- "usage_events_context_hierarchy_check",
3164
- sql`(${table.turnId} is null or ${table.sessionId} is not null)
3165
- and (${table.turnAttemptId} is null or ${table.turnId} is not null)`
3166
- ),
3167
- initiatorConsistent: check(
3168
- "usage_events_initiator_check",
3169
- sql`(${table.initiatorKind} is null and ${table.initiatorSubjectId} is null)
3170
- or (${table.initiatorKind} in ('subject', 'service')
3171
- and ${table.initiatorSubjectId} is not null
3172
- and octet_length(${table.initiatorSubjectId}) between 1 and 1024)`
3173
- ),
3174
- attributionContextBytes: check(
3175
- "usage_events_initiator_context_bytes_check",
3176
- sql`octet_length(${table.initiatorContext}::text) <= 4096`
3177
- ),
3178
- originValid: check(
3179
- "usage_events_origin_check",
3180
- sql`${table.origin} is null or ${table.origin} in (
3181
- 'user', 'scheduled_task', 'api', 'goal', 'system', 'compaction'
3182
- )`
3183
- )
3184
- })
3185
- );
3186
- var hostExportConfig = pgTable(
3187
- "host_export_config",
3188
- {
3189
- id: integer("id").primaryKey().default(1),
3190
- sessionEventsEnabled: boolean("session_events_enabled").notNull().default(false),
3191
- usageEventsEnabled: boolean("usage_events_enabled").notNull().default(false),
3192
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3193
- },
3194
- (table) => ({
3195
- singleton: check("host_export_config_singleton_check", sql`${table.id} = 1`)
3196
- })
3197
- );
3198
- var hostExportOutbox = pgTable(
3199
- "host_export_outbox",
3200
- {
3201
- id: uuid("id").primaryKey().defaultRandom(),
3202
- exportKind: text("export_kind").notNull(),
3203
- exportCursor: bigint("export_cursor", { mode: "bigint" }),
3204
- sourceId: uuid("source_id").notNull(),
3205
- accountId: uuid("account_id").notNull(),
3206
- workspaceId: uuid("workspace_id").notNull(),
3207
- sessionId: uuid("session_id"),
3208
- rootSessionId: uuid("root_session_id"),
3209
- turnId: uuid("turn_id"),
3210
- turnGeneration: integer("turn_generation"),
3211
- turnAttemptId: uuid("turn_attempt_id"),
3212
- sessionSequence: integer("session_sequence"),
3213
- clientEventId: text("client_event_id"),
3214
- turnAssociation: text("turn_association"),
3215
- duplicateOfEventId: uuid("duplicate_of_event_id"),
3216
- duplicateReason: text("duplicate_reason"),
3217
- eventType: text("event_type").notNull(),
3218
- idempotencyKey: text("idempotency_key").notNull(),
3219
- initiator: jsonb("initiator").$type(),
3220
- initiatorContext: jsonb("initiator_context").$type().notNull().default({}),
3221
- origin: text("origin"),
3222
- payload: jsonb("payload").$type().notNull(),
3223
- envelopeBytes: integer("envelope_bytes").notNull(),
3224
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),
3225
- sourceRecordedAt: timestamp("source_recorded_at", { withTimezone: true }).notNull(),
3226
- enqueuedAt: timestamp("enqueued_at", { withTimezone: true }).notNull()
3227
- },
3228
- (table) => ({
3229
- kindValid: check(
3230
- "host_export_outbox_kind_check",
3231
- sql`${table.exportKind} in ('session_event', 'usage_event')`
3232
- ),
3233
- rootSessionCaptured: check(
3234
- "host_export_outbox_root_session_check",
3235
- sql`${table.sessionId} is null or ${table.rootSessionId} is not null`
3236
- ),
3237
- sourceUnique: uniqueIndex("host_export_outbox_source_uq").on(table.exportKind, table.sourceId),
3238
- cursorUnique: uniqueIndex("host_export_outbox_cursor_uq").on(table.exportKind, table.exportCursor).where(sql`${table.exportCursor} is not null`),
3239
- unassigned: index("host_export_outbox_unassigned_idx").on(table.exportKind, table.enqueuedAt, table.id).where(sql`${table.exportCursor} is null`),
3240
- unassignedSession: index("host_export_outbox_unassigned_session_idx").on(table.exportKind, table.sessionId, table.sessionSequence).where(sql`${table.exportCursor} is null and ${table.sessionId} is not null`),
3241
- contextBytes: check(
3242
- "host_export_outbox_context_bytes_check",
3243
- sql`octet_length(${table.initiatorContext}::text) <= 4096`
3244
- ),
3245
- originValid: check(
3246
- "host_export_outbox_origin_check",
3247
- sql`${table.origin} is null or ${table.origin} in (
3248
- 'user', 'scheduled_task', 'api', 'goal', 'system', 'compaction'
3249
- )`
3250
- )
3251
- })
3252
- );
3253
- var hostExportCursorState = pgTable(
3254
- "host_export_cursor_state",
3255
- {
3256
- exportKind: text("export_kind").primaryKey(),
3257
- nextCursor: bigint("next_cursor", { mode: "bigint" }).notNull().default(1n),
3258
- prunedThrough: bigint("pruned_through", { mode: "bigint" }).notNull().default(0n),
3259
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3260
- },
3261
- (table) => ({
3262
- kindValid: check(
3263
- "host_export_cursor_state_kind_check",
3264
- sql`${table.exportKind} in ('session_event', 'usage_event')`
3265
- ),
3266
- cursorValid: check(
3267
- "host_export_cursor_state_next_check",
3268
- sql`${table.nextCursor} > 0 and ${table.prunedThrough} >= 0
3269
- and ${table.prunedThrough} < ${table.nextCursor}`
3270
- )
3271
- })
3272
- );
3273
- var hostExportConsumers = pgTable(
3274
- "host_export_consumers",
3275
- {
3276
- id: uuid("id").primaryKey().defaultRandom(),
3277
- consumerId: text("consumer_id").notNull(),
3278
- exportKind: text("export_kind").notNull(),
3279
- checkpoint: bigint("checkpoint", { mode: "bigint" }).notNull().default(0n),
3280
- enabled: boolean("enabled").notNull().default(true),
3281
- leaseToken: uuid("lease_token"),
3282
- leaseHolderId: text("lease_holder_id"),
3283
- leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }),
3284
- leaseFrom: bigint("lease_from", { mode: "bigint" }),
3285
- leaseThrough: bigint("lease_through", { mode: "bigint" }),
3286
- consecutiveFailures: integer("consecutive_failures").notNull().default(0),
3287
- nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
3288
- lastError: text("last_error"),
3289
- lastErrorAt: timestamp("last_error_at", { withTimezone: true }),
3290
- blockedAt: timestamp("blocked_at", { withTimezone: true }),
3291
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3292
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3293
- },
3294
- (table) => ({
3295
- consumerKind: uniqueIndex("host_export_consumers_kind_id_uq").on(
3296
- table.exportKind,
3297
- table.consumerId
3298
- ),
3299
- kindValid: check(
3300
- "host_export_consumers_kind_check",
3301
- sql`${table.exportKind} in ('session_event', 'usage_event')`
3302
- ),
3303
- checkpointValid: check("host_export_consumers_checkpoint_check", sql`${table.checkpoint} >= 0`),
3304
- due: index("host_export_consumers_due_idx").on(
3305
- table.enabled,
3306
- table.blockedAt,
3307
- table.nextAttemptAt
3308
- )
3309
- })
3310
- );
3311
- var hostExportDeadLetters = pgTable(
3312
- "host_export_dead_letters",
3313
- {
3314
- id: uuid("id").primaryKey().defaultRandom(),
3315
- consumerId: text("consumer_id").notNull(),
3316
- exportKind: text("export_kind").notNull(),
3317
- exportCursor: bigint("export_cursor", { mode: "bigint" }).notNull(),
3318
- sourceId: uuid("source_id").notNull(),
3319
- reason: text("reason").notNull(),
3320
- envelope: jsonb("envelope").$type().notNull(),
3321
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
3322
- },
3323
- (table) => ({
3324
- consumerCursor: uniqueIndex("host_export_dead_letters_consumer_cursor_uq").on(
3325
- table.exportKind,
3326
- table.consumerId,
3327
- table.exportCursor
3328
- ),
3329
- kindValid: check(
3330
- "host_export_dead_letters_kind_check",
3331
- sql`${table.exportKind} in ('session_event', 'usage_event')`
3332
- ),
3333
- reasonValid: check(
3334
- "host_export_dead_letters_reason_check",
3335
- sql`length(${table.reason}) between 1 and 500`
3336
- ),
3337
- envelopeBytes: check(
3338
- "host_export_dead_letters_envelope_bytes_check",
3339
- sql`pg_column_size(${table.envelope}) <= 114688`
3340
- )
3341
- })
3342
- );
3343
- var creditLedgerEntries = pgTable(
3344
- "credit_ledger_entries",
3345
- {
3346
- id: uuid("id").primaryKey().defaultRandom(),
3347
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3348
- workspaceId: uuid("workspace_id").references(() => workspaces.id, {
3349
- onDelete: "set null"
3350
- }),
3351
- type: text("type").notNull(),
3352
- amountMicros: bigint("amount_micros", { mode: "number" }).notNull(),
3353
- currency: text("currency").notNull().default("usd"),
3354
- sourceType: text("source_type"),
3355
- sourceId: text("source_id"),
3356
- idempotencyKey: text("idempotency_key").notNull(),
3357
- metadata: jsonb("metadata").$type().notNull().default({}),
3358
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
3359
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
3360
- },
3361
- (table) => ({
3362
- idempotency: uniqueIndex("credit_ledger_entries_idempotency_idx").on(table.idempotencyKey),
3363
- accountCreated: index("credit_ledger_entries_account_created_idx").on(
3364
- table.accountId,
3365
- table.createdAt
3366
- )
3367
- })
3368
- );
3369
- var billingCustomers = pgTable(
3370
- "billing_customers",
3371
- {
3372
- id: uuid("id").primaryKey().defaultRandom(),
3373
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3374
- provider: text("provider").notNull().default("stripe"),
3375
- providerCustomerId: text("provider_customer_id").notNull(),
3376
- email: text("email"),
3377
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3378
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3379
- },
3380
- (table) => ({
3381
- accountProvider: uniqueIndex("billing_customers_account_provider_idx").on(
3382
- table.accountId,
3383
- table.provider
3384
- ),
3385
- providerCustomer: uniqueIndex("billing_customers_provider_customer_idx").on(
3386
- table.provider,
3387
- table.providerCustomerId
3388
- )
3389
- })
3390
- );
3391
- var stripeWebhookEvents = pgTable("stripe_webhook_events", {
3392
- id: text("id").primaryKey(),
3393
- type: text("type").notNull(),
3394
- livemode: text("livemode").notNull().default("false"),
3395
- payload: jsonb("payload").$type().notNull(),
3396
- processedAt: timestamp("processed_at", { withTimezone: true }),
3397
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
3398
- });
3399
- var auditEvents = pgTable(
3400
- "audit_events",
3401
- {
3402
- id: uuid("id").primaryKey().defaultRandom(),
3403
- accountId: uuid("account_id").references(() => managedAccounts.id, {
3404
- onDelete: "set null"
3405
- }),
3406
- workspaceId: uuid("workspace_id").references(() => workspaces.id, {
3407
- onDelete: "set null"
3408
- }),
3409
- subjectId: text("subject_id"),
3410
- action: text("action").notNull(),
3411
- targetType: text("target_type"),
3412
- targetId: text("target_id"),
3413
- metadata: jsonb("metadata").$type().notNull().default({}),
3414
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow()
3415
- },
3416
- (table) => ({
3417
- accountCreated: index("audit_events_account_created_idx").on(table.accountId, table.occurredAt),
3418
- workspaceCreated: index("audit_events_workspace_created_idx").on(
3419
- table.workspaceId,
3420
- table.occurredAt
3421
- )
3422
- })
3423
- );
3424
- var packInstallations = pgTable(
3425
- "pack_installations",
3426
- {
3427
- id: uuid("id").primaryKey().defaultRandom(),
3428
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3429
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3430
- packId: text("pack_id").notNull(),
3431
- status: text("status").notNull().default("active"),
3432
- metadata: jsonb("metadata").$type().notNull().default({}),
3433
- enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(),
3434
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3435
- },
3436
- (table) => ({
3437
- workspacePack: uniqueIndex("pack_installations_workspace_pack_idx").on(
3438
- table.workspaceId,
3439
- table.packId
3440
- ),
3441
- status: index("pack_installations_workspace_status_idx").on(table.workspaceId, table.status)
3442
- })
3443
- );
3444
- var workspacePacks = pgTable(
3445
- "workspace_packs",
3446
- {
3447
- id: uuid("id").primaryKey().defaultRandom(),
3448
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3449
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3450
- packId: text("pack_id").notNull(),
3451
- manifest: jsonb("manifest").$type().notNull(),
3452
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3453
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3454
- },
3455
- (table) => ({
3456
- workspacePack: uniqueIndex("workspace_packs_workspace_pack_idx").on(
3457
- table.workspaceId,
3458
- table.packId
3459
- )
3460
- })
3461
- );
3462
- var importBatches = pgTable(
3463
- "import_batches",
3464
- {
3465
- id: uuid("id").primaryKey().defaultRandom(),
3466
- source: text("source").notNull(),
3467
- snapshotDate: timestamp("snapshot_date", { withTimezone: true }).notNull(),
3468
- snapshotRef: text("snapshot_ref"),
3469
- attributionNote: text("attribution_note").notNull(),
3470
- importedCount: integer("imported_count").notNull().default(0),
3471
- skippedCount: integer("skipped_count").notNull().default(0),
3472
- quarantinedCount: integer("quarantined_count").notNull().default(0),
3473
- logoFailureCount: integer("logo_failure_count").notNull().default(0),
3474
- staleCount: integer("stale_count").notNull().default(0),
3475
- details: jsonb("details").$type().notNull().default({}),
3476
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3477
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3478
- },
3479
- (table) => ({
3480
- sourceSnapshot: index("import_batches_source_snapshot_idx").on(
3481
- table.source,
3482
- table.snapshotDate
3483
- ),
3484
- createdAt: index("import_batches_created_at_idx").on(table.createdAt)
3485
- })
3486
- );
3487
- var capabilityCatalogItems = pgTable(
3488
- "capability_catalog_items",
3489
- {
3490
- id: text("id").notNull(),
3491
- accountId: uuid("account_id").references(() => managedAccounts.id, {
3492
- onDelete: "cascade"
3493
- }),
3494
- workspaceId: uuid("workspace_id").references(() => workspaces.id, {
3495
- onDelete: "cascade"
3496
- }),
3497
- kind: text("kind").notNull(),
3498
- source: text("source").notNull().default("manual"),
3499
- name: text("name").notNull(),
3500
- description: text("description"),
3501
- category: text("category").notNull().default("custom"),
3502
- tags: jsonb("tags").$type().notNull().default([]),
3503
- homepageUrl: text("homepage_url"),
3504
- endpointUrl: text("endpoint_url"),
3505
- installUrl: text("install_url"),
3506
- authModel: text("auth_model"),
3507
- providerDomain: text("provider_domain"),
3508
- surfaceType: text("surface_type"),
3509
- transport: text("transport"),
3510
- mcpUrl: text("mcp_url"),
3511
- authKind: text("auth_kind"),
3512
- credentialFacts: jsonb("credential_facts").$type().notNull().default([]),
3513
- tier: text("tier"),
3514
- provenance: text("provenance"),
3515
- logoAssetPath: text("logo_asset_path"),
3516
- importBatchId: uuid("import_batch_id").references(() => importBatches.id, {
3517
- onDelete: "set null"
3518
- }),
3519
- stale: boolean("stale").notNull().default(false),
3520
- staleAt: timestamp("stale_at", { withTimezone: true }),
3521
- metadata: jsonb("metadata").$type().notNull().default({}),
3522
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3523
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3524
- },
3525
- (table) => ({
3526
- workspaceCapability: uniqueIndex("capability_catalog_items_workspace_capability_idx").on(
3527
- table.workspaceId,
3528
- table.id
3529
- ),
3530
- registrySurface: uniqueIndex("capability_catalog_items_registry_surface_idx").on(
3531
- table.source,
3532
- table.providerDomain,
3533
- table.mcpUrl
3534
- ),
3535
- globalCapability: uniqueIndex("capability_catalog_items_global_capability_idx").on(table.id).where(sql`${table.workspaceId} is null`),
3536
- kind: index("capability_catalog_items_workspace_kind_idx").on(table.workspaceId, table.kind),
3537
- category: index("capability_catalog_items_workspace_category_idx").on(
3538
- table.workspaceId,
3539
- table.category
3540
- ),
3541
- source: index("capability_catalog_items_workspace_source_idx").on(
3542
- table.workspaceId,
3543
- table.source
3544
- ),
3545
- providerDomain: index("capability_catalog_items_provider_domain_idx").on(table.providerDomain),
3546
- importBatch: index("capability_catalog_items_import_batch_idx").on(table.importBatchId),
3547
- stale: index("capability_catalog_items_source_stale_idx").on(table.source, table.stale)
3548
- })
3549
- );
3550
- var capabilityInstallations = pgTable(
3551
- "capability_installations",
3552
- {
3553
- id: uuid("id").primaryKey().defaultRandom(),
3554
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3555
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3556
- capabilityId: text("capability_id").notNull(),
3557
- kind: text("kind").notNull(),
3558
- status: text("status").notNull().default("active"),
3559
- config: jsonb("config").$type().notNull().default({}),
3560
- metadata: jsonb("metadata").$type().notNull().default({}),
3561
- enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(),
3562
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3563
- },
3564
- (table) => ({
3565
- workspaceCapability: uniqueIndex("capability_installations_workspace_capability_idx").on(
3566
- table.workspaceId,
3567
- table.capabilityId
3568
- ),
3569
- kind: index("capability_installations_workspace_kind_idx").on(table.workspaceId, table.kind),
3570
- status: index("capability_installations_workspace_status_idx").on(
3571
- table.workspaceId,
3572
- table.status
3573
- )
3574
- })
3575
- );
3576
- var socialConnections = pgTable(
3577
- "social_connections",
3578
- {
3579
- id: uuid("id").primaryKey().defaultRandom(),
3580
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3581
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3582
- provider: text("provider").notNull(),
3583
- accountHandle: text("account_handle").notNull(),
3584
- accountName: text("account_name"),
3585
- externalAccountId: text("external_account_id"),
3586
- status: text("status").notNull().default("connected"),
3587
- scopes: jsonb("scopes").$type().notNull().default([]),
3588
- credentialRef: text("credential_ref"),
3589
- tokenMetadata: jsonb("token_metadata").$type().notNull().default({}),
3590
- metadata: jsonb("metadata").$type().notNull().default({}),
3591
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3592
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3593
- },
3594
- (table) => ({
3595
- workspaceProviderHandle: uniqueIndex("social_connections_workspace_provider_handle_idx").on(
3596
- table.workspaceId,
3597
- table.provider,
3598
- table.accountHandle
3599
- ),
3600
- providerStatus: index("social_connections_workspace_provider_status_idx").on(
3601
- table.workspaceId,
3602
- table.provider,
3603
- table.status
3604
- )
3605
- })
3606
- );
3607
- var socialPosts = pgTable(
3608
- "social_posts",
3609
- {
3610
- id: uuid("id").primaryKey().defaultRandom(),
3611
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3612
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3613
- connectionId: uuid("connection_id").notNull().references(() => socialConnections.id, { onDelete: "cascade" }),
3614
- provider: text("provider").notNull(),
3615
- externalPostId: text("external_post_id"),
3616
- url: text("url"),
3617
- authorHandle: text("author_handle"),
3618
- text: text("text").notNull(),
3619
- publishedAt: timestamp("published_at", { withTimezone: true }).notNull(),
3620
- metrics: jsonb("metrics").$type().notNull().default({}),
3621
- raw: jsonb("raw").$type().notNull().default({}),
3622
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
3623
- },
3624
- (table) => ({
3625
- connectionExternalPost: uniqueIndex("social_posts_workspace_connection_external_post_idx").on(
3626
- table.workspaceId,
3627
- table.connectionId,
3628
- table.externalPostId
3629
- ),
3630
- connectionPublished: index("social_posts_workspace_connection_published_idx").on(
3631
- table.workspaceId,
3632
- table.connectionId,
3633
- table.publishedAt
3634
- ),
3635
- providerPublished: index("social_posts_workspace_provider_published_idx").on(
3636
- table.workspaceId,
3637
- table.provider,
3638
- table.publishedAt
3639
- )
3640
- })
3641
- );
3642
- var rigs = pgTable(
3643
- "rigs",
3644
- {
3645
- id: uuid("id").primaryKey().defaultRandom(),
3646
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3647
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3648
- name: text("name").notNull(),
3649
- description: text("description"),
3650
- // Attribution string: 'user:<subject>' | 'session:<id>' | 'system'.
3651
- createdBy: text("created_by"),
3652
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3653
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3654
- },
3655
- (table) => ({
3656
- workspaceName: uniqueIndex("rigs_workspace_name_idx").on(table.workspaceId, table.name),
3657
- workspaceCreated: index("rigs_workspace_created_idx").on(table.workspaceId, table.createdAt)
3658
- })
3659
- );
3660
- var rigVersions = pgTable(
3661
- "rig_versions",
3662
- {
3663
- id: uuid("id").primaryKey().defaultRandom(),
3664
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3665
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3666
- rigId: uuid("rig_id").notNull().references(() => rigs.id, { onDelete: "cascade" }),
3667
- version: integer("version").notNull(),
3668
- image: text("image"),
3669
- setupScript: text("setup_script"),
3670
- // Self-declared health checks: [{ name, command }].
3671
- checks: jsonb("checks").$type().notNull().default([]),
3672
- // Registered credential-hook names (resolved to hook implementations in M3).
3673
- credentialHooks: jsonb("credential_hooks").$type().notNull().default([]),
3674
- // Variable-set ids layered below the session's variable set at run time (M3).
3675
- defaultVariableSetIds: jsonb("default_variable_set_ids").$type().notNull().default([]),
3676
- changelog: text("changelog"),
3677
- createdBy: text("created_by"),
3678
- active: boolean("active").notNull().default(false),
3679
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
3680
- },
3681
- (table) => ({
3682
- rigVersion: uniqueIndex("rig_versions_rig_version_idx").on(table.rigId, table.version),
3683
- // At most one active version per rig — the single-active invariant, in the DB.
3684
- rigActive: uniqueIndex("rig_versions_rig_active_idx").on(table.rigId).where(sql`${table.active}`),
3685
- workspaceRig: index("rig_versions_workspace_rig_idx").on(
3686
- table.workspaceId,
3687
- table.rigId,
3688
- table.version
3689
- )
3690
- })
3691
- );
3692
- var rigChanges = pgTable(
3693
- "rig_changes",
3694
- {
3695
- id: uuid("id").primaryKey().defaultRandom(),
3696
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3697
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3698
- rigId: uuid("rig_id").notNull().references(() => rigs.id, { onDelete: "cascade" }),
3699
- baseVersionId: uuid("base_version_id").references(() => rigVersions.id, {
3700
- onDelete: "set null"
3701
- }),
3702
- // 'setup_append' | 'definition_edit' (CHECK in migration 0047).
3703
- kind: text("kind").notNull(),
3704
- payload: jsonb("payload").$type().notNull(),
3705
- // 'proposed' | 'verifying' | 'merged' | 'rejected' | 'failed' (CHECK in 0047).
3706
- status: text("status").notNull().default("proposed"),
3707
- proposedBy: text("proposed_by"),
3708
- verification: jsonb("verification").$type(),
3709
- resultVersionId: uuid("result_version_id").references(() => rigVersions.id, {
3710
- onDelete: "set null"
3711
- }),
3712
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3713
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3714
- },
3715
- (table) => ({
3716
- workspaceRig: index("rig_changes_workspace_rig_idx").on(
3717
- table.workspaceId,
3718
- table.rigId,
3719
- table.createdAt
3720
- ),
3721
- workspaceStatus: index("rig_changes_workspace_status_idx").on(table.workspaceId, table.status)
3722
- })
3723
- );
3724
-
3725
- export {
3726
- managedAccounts,
3727
- workspaces,
3728
- nestedAgentDepthConfiguration,
3729
- workspaceInferenceControls,
3730
- workspaceSessionActivityRevisions,
3731
- workspaceMemberships,
3732
- apiKeys,
3733
- workspaceVariableSets,
3734
- workspaceVariableSetVariables,
3735
- codexSubscriptionCredentials,
3736
- codexResetRedemptionAttempts,
3737
- connections,
3738
- integrationOauthClients,
3739
- integrationOauthStateNonces,
3740
- codexRotationSettings,
3741
- workspaceModelPolicies,
3742
- codexCredentialLeases,
3743
- sessions,
3744
- sessionSpawnDenials,
3745
- sessionPins,
3746
- sessionListSnapshots,
3747
- sessionMcpServers,
3748
- files,
3749
- fileUploads,
3750
- documentBases,
3751
- documents,
3752
- documentChunks,
3753
- knowledgeMemories,
3754
- sessionTurns,
3755
- sessionTurnAttempts,
3756
- sessionCommandReceipts,
3757
- workspaceControlEvents,
3758
- sessionAttemptInterruptions,
3759
- composerDrafts,
3760
- newSessionDrafts,
3761
- sessionSystemUpdates,
3762
- sessionSystemUpdateOutbox,
3763
- sessionWorkflowWakeOutbox,
3764
- sessionGoals,
3765
- codexCapacityWaiters,
3766
- sessionEvents,
3767
- agentRunStates,
3768
- sessionHumanInputRequests,
3769
- sessionHistoryItems,
3770
- sessionPendingToolCalls,
3771
- sandboxSessionEnvelopes,
3772
- sandboxLeaseLivenessValues,
3773
- sandboxLeases,
3774
- sandboxLeaseHolders,
3775
- sandboxWorkspaceMutationActorKindValues,
3776
- sandboxWorkspaceMutationHolderKindValues,
3777
- sandboxWorkspaceMutationAdmissions,
3778
- sandboxRetainedProcessStateValues,
3779
- sandboxRetainedProcesses,
3780
- sessionRecordingStateValues,
3781
- sessionRecordingModeValues,
3782
- sessionRecordingCodecValues,
3783
- sessionRecordings,
3784
- workspaceCaptures,
3785
- sandboxPtySessions,
3786
- enrollmentExposureValues,
3787
- enrollmentStatusValues,
3788
- enrollmentOsValues,
3789
- sandboxKindValues,
3790
- enrollments,
3791
- deviceEnrollmentStatusValues,
3792
- deviceEnrollmentRequests,
3793
- sandboxes,
3794
- machineMetricsLatest,
3795
- machineMetricsSeries,
3796
- scheduledTasks,
3797
- scheduledTaskRuns,
3798
- githubInstallations,
3799
- githubInstallationRepositories,
3800
- usageEvents,
3801
- hostExportConfig,
3802
- hostExportOutbox,
3803
- hostExportCursorState,
3804
- hostExportConsumers,
3805
- hostExportDeadLetters,
3806
- creditLedgerEntries,
3807
- billingCustomers,
3808
- stripeWebhookEvents,
3809
- auditEvents,
3810
- packInstallations,
3811
- workspacePacks,
3812
- importBatches,
3813
- capabilityCatalogItems,
3814
- capabilityInstallations,
3815
- socialConnections,
3816
- socialPosts,
3817
- rigs,
3818
- rigVersions,
3819
- rigChanges,
3820
- schema_exports
3821
- };
3822
- //# sourceMappingURL=chunk-CYA6BHV6.js.map